signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def parse ( cls , rule_string ) :
"""returns a list of rules
a single line may yield multiple rules""" | result = parser . parseString ( rule_string )
rules = [ ]
# breakout port ranges into multple rules
kwargs = { }
kwargs [ 'address' ] = result . ip_and_mask or None
kwargs [ 'group' ] = result . security_group or None
kwargs [ 'group_name' ] = result . group_name or None
for x , y in result . ports :
r = Rule ( res... |
def clear ( self , pat = None ) :
"""Minor diversion with built - in dict here ; clear can take a glob
style expression and remove keys based on that expression .""" | if pat is None :
return self . __dict__ . clear ( )
expr = re . compile ( fnmatch . translate ( pat ) )
for key in tuple ( self . keys ( ) ) : # make sure the key is a str first
if isinstance ( key , string_types ) :
if expr . match ( key ) :
del self . __dict__ [ key ] |
def from_message ( bot , message ) :
"""Create a ` ` Chat ` ` object from a message .
: param Bot bot : ` ` Bot ` ` object the message and chat belong to
: param dict message : Message to base the object on
: return : A chat object based on the message""" | chat = message [ "chat" ]
return Chat ( bot , chat [ "id" ] , chat [ "type" ] , message ) |
def is_days_ago ( adatetime , days ) :
""": param days : a positive integer .
Return true if the adatetime is on the specified days ago""" | if days == 1 :
end_time = last_midnight ( )
start_time = end_time - timedelta ( days = 1 )
else :
start_time = last_midnight ( ) - timedelta ( days = days )
end_time = start_time + timedelta ( days = 1 )
return start_time <= adatetime <= end_time |
def get_Z ( x_segment , y_segment , x_int , y_int , slope ) :
"""input : x _ segment , y _ segment , x _ int , y _ int , slope
output : Z ( Arai plot zigzag parameter )""" | Z = 0
first_time = True
for num , x in enumerate ( x_segment ) :
b_wiggle = get_b_wiggle ( x , y_segment [ num ] , y_int )
z = old_div ( ( x * abs ( b_wiggle - abs ( slope ) ) ) , abs ( x_int ) )
Z += z
first_time = False
return Z |
def commit ( self , commands = "" , confirmed = None , comment = None , at_time = None , synchronize = False , req_format = 'text' ) :
"""Perform a commit operation .
Purpose : Executes a commit operation . All parameters are optional .
| commit confirm and commit at are mutually exclusive . All
| the others ... | # ncclient doesn ' t support a truly blank commit , so if nothing is
# passed , use ' annotate system ' to make a blank commit
if not commands :
commands = 'annotate system ""'
clean_cmds = [ ]
for cmd in clean_lines ( commands ) :
clean_cmds . append ( cmd )
# try to lock the candidate config so we can make ch... |
def region_calcs ( self , arr , func ) :
"""Perform a calculation for all regions .""" | # Get pressure values for data output on hybrid vertical coordinates .
bool_pfull = ( self . def_vert and self . dtype_in_vert == internal_names . ETA_STR and self . dtype_out_vert is False )
if bool_pfull :
pfull_data = self . _get_input_data ( _P_VARS [ self . dtype_in_vert ] , self . start_date , self . end_date... |
def _stride ( stride_spec ) :
"""Expands the stride spec into a length 4 list .
Args :
stride _ spec : If length 0 , 1 or 2 then assign the inner dimensions , otherwise
return stride _ spec if it is length 4.
Returns :
A length 4 list .""" | if stride_spec is None :
return [ 1 , 1 , 1 , 1 ]
elif isinstance ( stride_spec , tf . compat . integral_types ) :
return [ 1 , stride_spec , stride_spec , 1 ]
elif len ( stride_spec ) == 1 :
return [ 1 , stride_spec [ 0 ] , stride_spec [ 0 ] , 1 ]
elif len ( stride_spec ) == 2 :
return [ 1 , stride_spe... |
def order_assets ( self , asset_ids , composition_id ) :
"""Reorders a set of assets in a composition .
arg : asset _ ids ( osid . id . Id [ ] ) : ` ` Ids ` ` for a set of
` ` Assets ` `
arg : composition _ id ( osid . id . Id ) : ` ` Id ` ` of the
` ` Composition ` `
raise : NotFound - ` ` composition _ ... | if ( not isinstance ( composition_id , ABCId ) and composition_id . get_identifier_namespace ( ) != 'repository.Composition' ) :
raise errors . InvalidArgument ( 'the argument is not a valid OSID Id' )
composition_map , collection = self . _get_composition_collection ( composition_id )
composition_map [ 'assetIds' ... |
def _evolve_reader ( in_file ) :
"""Generate a list of region IDs and trees from a top _ k _ trees evolve . py file .""" | cur_id_list = None
cur_tree = None
with open ( in_file ) as in_handle :
for line in in_handle :
if line . startswith ( "id," ) :
if cur_id_list :
yield cur_id_list , cur_tree
cur_id_list = [ ]
cur_tree = None
elif cur_tree is not None :
... |
def Ctrl_Fn ( self , n , dl = 0 ) :
"""Ctrl + Fn1 ~ 12 组合键""" | self . Delay ( dl )
self . keyboard . press_key ( self . keyboard . control_key )
self . keyboard . tap_key ( self . keyboard . function_keys [ n ] )
self . keyboard . release_key ( self . keyboard . control_key ) |
def _writeCloseFrame ( self , reason = DISCONNECT . GO_AWAY ) :
'''Write a close frame with the given reason and schedule this
connection close .''' | self . transport . writeClose ( reason )
self . transport . loseConnection ( )
self . transport = None |
def factory ( cls , target_type , alias = None ) :
"""Creates an addressable factory for the given target type and alias .
: returns : A factory that can capture : class : ` TargetAddressable ` instances .
: rtype : : class : ` Addressable . Factory `""" | class Factory ( Addressable . Factory ) :
@ property
def target_types ( self ) :
return ( target_type , )
def capture ( self , * args , ** kwargs ) :
return TargetAddressable ( alias , target_type , * args , ** kwargs )
return Factory ( ) |
def requiv_to_pot_contact ( requiv , q , sma , compno = 1 ) :
""": param requiv : user - provided equivalent radius
: param q : mass ratio
: param sma : semi - major axis ( d = sma because we explicitly assume circular orbits for contacts )
: param compno : 1 for primary , 2 for secondary
: return : potenti... | logger . debug ( "requiv_to_pot_contact(requiv={}, q={}, sma={}, compno={})" . format ( requiv , q , sma , compno ) )
# since the functions called here work with normalized r , we need to set d = D = sma = 1.
# or provide sma as a function parameter and normalize r here as requiv = requiv / sma
requiv = requiv / sma
ve... |
def _data_ports_changed ( self , model ) :
"""Reload list store and reminds selection when the model was changed""" | if not isinstance ( model , AbstractStateModel ) :
return
# store port selection
path_list = None
if self . view is not None :
model , path_list = self . tree_view . get_selection ( ) . get_selected_rows ( )
selected_data_port_ids = [ self . list_store [ path [ 0 ] ] [ self . ID_STORAGE_ID ] for path in path_li... |
def _execute_cell ( args , cell_body ) :
"""Implements the BigQuery cell magic used to execute BQ queries .
The supported syntax is :
% % bigquery execute [ - q | - - sql < query identifier > ] < other args >
[ < YAML or JSON cell _ body or inline SQL > ]
Args :
args : the arguments following ' % bigquery... | query = _get_query_argument ( args , cell_body , datalab . utils . commands . notebook_environment ( ) )
if args [ 'verbose' ] :
print ( query . sql )
return query . execute ( args [ 'target' ] , table_mode = args [ 'mode' ] , use_cache = not args [ 'nocache' ] , allow_large_results = args [ 'large' ] , dialect = a... |
def _get_firmware_embedded_health ( self , data ) :
"""Parse the get _ host _ health _ data ( ) for server capabilities
: param data : the output returned by get _ host _ health _ data ( )
: returns : a dictionary of firmware name and firmware version .""" | firmware = self . get_value_as_list ( data [ 'GET_EMBEDDED_HEALTH_DATA' ] , 'FIRMWARE_INFORMATION' )
if firmware is None :
return None
return dict ( ( y [ 'FIRMWARE_NAME' ] [ 'VALUE' ] , y [ 'FIRMWARE_VERSION' ] [ 'VALUE' ] ) for x in firmware for y in x . values ( ) ) |
def anime ( self , item_id ) :
"""The function to retrieve an anime ' s details .
: param int item _ id : the anime ' s ID
: return : dict or None
: rtype : dict or NoneType""" | query_string = """\
query ($id: Int) {
Media(id: $id, type: ANIME) {
title {
romaji
english
}
startDate {
year
month
... |
def get ( self , queue = '' , no_ack = False , to_dict = False , auto_decode = True ) :
"""Fetch a single message .
: param str queue : Queue name
: param bool no _ ack : No acknowledgement needed
: param bool to _ dict : Should incoming messages be converted to a
dictionary before delivery .
: param bool... | if not compatibility . is_string ( queue ) :
raise AMQPInvalidArgument ( 'queue should be a string' )
elif not isinstance ( no_ack , bool ) :
raise AMQPInvalidArgument ( 'no_ack should be a boolean' )
elif self . _channel . consumer_tags :
raise AMQPChannelError ( "Cannot call 'get' when channel is " "set t... |
def sql ( self ) :
"""Convert primary key attribute tuple into its SQL CREATE TABLE clause .
Default values are not reflected .
This is used for declaring foreign keys in referencing tables
: return : SQL code""" | assert self . in_key and not self . nullable
# primary key attributes are never nullable
return '`{name}` {type} NOT NULL COMMENT "{comment}"' . format ( name = self . name , type = self . type , comment = self . comment ) |
def _load_item ( self , key ) :
'''Load the specified item from the [ flask ] section . Type is
determined by the type of the equivalent value in app . default _ config
or string if unknown .''' | key_u = key . upper ( )
default = current_app . default_config . get ( key_u )
# One of the default config vars is a timedelta - interpret it
# as an int and construct using it
if isinstance ( default , datetime . timedelta ) :
current_app . config [ key_u ] = datetime . timedelta ( self . getint ( 'flask' , key ) ... |
def encipher ( self , string ) :
"""Encipher string using Polybius square cipher according to initialised key .
Example : :
ciphertext = Polybius ( ' APCZWRLFBDKOTYUQGENHXMIVS ' , 5 , ' MKSBU ' ) . encipher ( plaintext )
: param string : The string to encipher .
: returns : The enciphered string . The ciphe... | string = self . remove_punctuation ( string )
# , filter = ' [ ^ ' + self . key + ' ] ' )
ret = ''
for c in range ( 0 , len ( string ) ) :
ret += self . encipher_char ( string [ c ] )
return ret |
def get_koji_module_build ( session , module_spec ) :
"""Get build information from Koji for a module . The module specification must
include at least name , stream and version . For legacy support , you can omit
context if there is only one build of the specified NAME : STREAM : VERSION .
: param session : K... | if module_spec . context is not None : # The easy case - we can build the koji " name - version - release " out of the
# module spec .
koji_nvr = "{}-{}-{}.{}" . format ( module_spec . name , module_spec . stream . replace ( "-" , "_" ) , module_spec . version , module_spec . context )
logger . info ( "Looking ... |
def execute_sql ( self , statement ) :
"""Executes a single SQL statement .
: param statement : SQL string
: return : String response
: rtype : str""" | path = '/archive/{}/sql' . format ( self . _instance )
req = archive_pb2 . ExecuteSqlRequest ( )
req . statement = statement
response = self . _client . post_proto ( path = path , data = req . SerializeToString ( ) )
message = archive_pb2 . ExecuteSqlResponse ( )
message . ParseFromString ( response . content )
if mess... |
def calc_rets ( returns , weights ) :
"""Calculate continuous return series for futures instruments . These consist
of weighted underlying instrument returns , who ' s weights can vary over
time .
Parameters
returns : pandas . Series or dict
A Series of instrument returns with a MultiIndex where the top l... | # NOQA
if not isinstance ( returns , dict ) :
returns = { "" : returns }
if not isinstance ( weights , dict ) :
weights = { "" : weights }
generic_superset = [ ]
for root in weights :
generic_superset . extend ( weights [ root ] . columns . tolist ( ) )
if len ( set ( generic_superset ) ) != len ( generic_s... |
def encode ( self ) :
"""Encodes matrix
: return : Encoder used""" | encoder = LabelEncoder ( )
# encoder
values = self . get_as_list ( )
encoded = encoder . fit_transform ( values )
# long list of encoded
n_columns = len ( self . matrix [ 0 ] )
n_rows = len ( self . matrix )
self . matrix = [ encoded [ i : i + n_columns ] for i in range ( 0 , n_rows * n_columns , n_columns ) ]
return e... |
def house ( self ) :
"""Returns the object ' s house .""" | house = self . chart . houses . getObjectHouse ( self . obj )
return house |
def get_steps_from_feature_description ( self , description ) :
"""get all steps defined in the feature description associated to each action
: param description : feature description""" | self . init_actions ( )
label_exists = EMPTY
for row in description :
if label_exists != EMPTY : # in case of a line with a comment , it is removed
if "#" in row :
row = row [ 0 : row . find ( "#" ) ] . strip ( )
if any ( row . startswith ( x ) for x in KEYWORDS ) :
self . ac... |
def evaluate ( self , flux , xo , yo , a , b , c ) :
"""Evaluate the Gaussian model
Parameters
flux : tf . Variable
xo , yo : tf . Variable , tf . Variable
Center coordiantes of the Gaussian .
a , b , c : tf . Variable , tf . Variable
Parameters that control the rotation angle
and the stretch along th... | dx = self . x - xo
dy = self . y - yo
psf = tf . exp ( - ( a * dx ** 2 + 2 * b * dx * dy + c * dy ** 2 ) )
psf_sum = tf . reduce_sum ( psf )
return flux * psf / psf_sum |
def nltides_coefs ( amplitude , n , m1 , m2 ) :
"""Calculate the coefficents needed to compute the
shift in t ( f ) and phi ( f ) due to non - linear tides .
Parameters
amplitude : float
Amplitude of effect
n : float
Growth dependence of effect
m1 : float
Mass of component 1
m2 : float
Mass of c... | # Use 100.0 Hz as a reference frequency
f_ref = 100.0
# Calculate chirp mass
mc = mchirp_from_mass1_mass2 ( m1 , m2 )
mc *= lal . lal . MSUN_SI
# Calculate constants in phasing
a = ( 96. / 5. ) * ( lal . lal . G_SI * lal . lal . PI * mc * f_ref / lal . lal . C_SI ** 3. ) ** ( 5. / 3. )
b = 6. * amplitude
t_of_f_factor ... |
def __batch_evaluate ( self , test_events ) :
"""Evaluate the current model by using the given test events .
Args :
test _ events ( list of Event ) : Current model is evaluated by these events .
Returns :
float : Mean Percentile Rank for the test set .""" | percentiles = np . zeros ( len ( test_events ) )
all_items = set ( self . item_buffer )
for i , e in enumerate ( test_events ) : # check if the data allows users to interact the same items repeatedly
unobserved = all_items
if not self . repeat : # make recommendation for all unobserved items
unobserved ... |
def camera_position ( self , camera_location ) :
"""Set camera position of all active render windows""" | if camera_location is None :
return
if isinstance ( camera_location , str ) :
camera_location = camera_location . lower ( )
if camera_location == 'xy' :
self . view_xy ( )
elif camera_location == 'xz' :
self . view_xz ( )
elif camera_location == 'yz' :
self . view_yz ( )
... |
def as_alias_handler ( alias_list ) :
"""Returns a list of all the names that will be called .""" | list_ = list ( )
for alias in alias_list :
if alias . asname :
list_ . append ( alias . asname )
else :
list_ . append ( alias . name )
return list_ |
def federation ( self ) :
"""returns the class that controls federation""" | url = self . _url + "/federation"
return _Federation ( url = url , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port ) |
def systemdef ( meta , surface_tilt , surface_azimuth , albedo , modules_per_string , strings_per_inverter ) :
'''Generates a dict of system parameters used throughout a simulation .
Parameters
meta : dict
meta dict either generated from a TMY file using readtmy2 or
readtmy3 , or a dict containing at least ... | try :
name = meta [ 'Name' ]
except KeyError :
name = meta [ 'City' ]
system = { 'surface_tilt' : surface_tilt , 'surface_azimuth' : surface_azimuth , 'albedo' : albedo , 'modules_per_string' : modules_per_string , 'strings_per_inverter' : strings_per_inverter , 'latitude' : meta [ 'latitude' ] , 'longitude' : ... |
def ossos_release_with_metadata ( ) :
"""Wrap the objects from the Version Releases together with the objects instantiated from fitting their mpc lines""" | # discoveries = ossos _ release _ parser ( )
discoveries = [ ]
observations = ossos_discoveries ( )
for obj in observations :
discov = [ n for n in obj [ 0 ] . mpc_observations if n . discovery . is_discovery ] [ 0 ]
tno = parameters . tno ( )
tno . dist = obj [ 1 ] . distance
tno . ra_discov = discov .... |
def get_aspect ( self , xspan , yspan ) :
"""Computes the aspect ratio of the plot""" | if isinstance ( self . aspect , ( int , float ) ) :
return self . aspect
elif self . aspect == 'square' :
return 1
elif self . aspect == 'equal' :
return xspan / yspan
return 1 |
def hierarchy ( intervals_hier , labels_hier , levels = None , ax = None , ** kwargs ) :
'''Plot a hierarchical segmentation
Parameters
intervals _ hier : list of np . ndarray
A list of segmentation intervals . Each element should be
an n - by - 2 array of segment intervals , in the format returned by
: f... | # This will break if a segment label exists in multiple levels
if levels is None :
levels = list ( range ( len ( intervals_hier ) ) )
# Get the axes handle
ax , _ = __get_axes ( ax = ax )
# Count the pre - existing patches
n_patches = len ( ax . patches )
for ints , labs , key in zip ( intervals_hier [ : : - 1 ] , ... |
def save ( self ) :
"""Saves changes made to the locally cached DesignDocument object ' s data
structures to the remote database . If the design document does not
exist remotely then it is created in the remote database . If the object
does exist remotely then the design document is updated remotely . In
ei... | if self . views :
if self . get ( 'language' , None ) != QUERY_LANGUAGE :
for view_name , view in self . iterviews ( ) :
if isinstance ( view , QueryIndexView ) :
raise CloudantDesignDocumentException ( 104 , view_name )
else :
for view_name , view in self . iterviews... |
def get_last_next ( self , date ) :
"""Provide the last and next leap - second events relative to a date
Args :
date ( float ) : Date in MJD
Return :
tuple :""" | past , future = ( None , None ) , ( None , None )
for mjd , value in reversed ( self . data ) :
if mjd <= date :
past = ( mjd , value )
break
future = ( mjd , value )
return past , future |
def pull_buildpack ( url ) :
"""Update a buildpack in its shared location , then make a copy into the
current directory , using an md5 of the url .""" | defrag = _defrag ( urllib . parse . urldefrag ( url ) )
with lock_or_wait ( defrag . url ) :
bp = update_buildpack ( url )
dest = bp . basename + '-' + hash_text ( defrag . url )
shutil . copytree ( bp . folder , dest )
# Make the buildpack dir writable , per
# https : / / bitbucket . org / yougov / velocir... |
def set_illuminant ( self , illuminant ) :
"""Validates and sets the color ' s illuminant .
. . note : : This only changes the illuminant . It does no conversion
of the color ' s coordinates . For this , you ' ll want to refer to
: py : meth : ` XYZColor . apply _ adaptation < colormath . color _ objects . XY... | illuminant = illuminant . lower ( )
if illuminant not in color_constants . ILLUMINANTS [ self . observer ] :
raise InvalidIlluminantError ( illuminant )
self . illuminant = illuminant |
def check ( self , url_data ) :
"""Parse PDF data .""" | # XXX user authentication from url _ data
password = ''
data = url_data . get_content ( )
# PDFParser needs a seekable file object
fp = StringIO ( data )
try :
parser = PDFParser ( fp )
doc = PDFDocument ( parser , password = password )
for ( pageno , page ) in enumerate ( PDFPage . create_pages ( doc ) , s... |
def write_metadata ( self , f , dsetgrp , data , type_string , options , attributes = None ) :
"""Writes an object to file .
Writes the metadata for a Python object ` data ` to file at ` name `
in h5py . Group ` grp ` . Metadata is written to HDF5
Attributes . Existing Attributes that are not being used are
... | if attributes is None :
attributes = dict ( )
# Make sure we have a complete type _ string .
if options . store_python_metadata and 'Python.Type' not in attributes :
attributes [ 'Python.Type' ] = ( 'string' , self . get_type_string ( data , type_string ) )
set_attributes_all ( dsetgrp , attributes , discard_ot... |
def getParser ( ) :
"Creates and returns the argparse parser object ." | parser = argparse . ArgumentParser ( formatter_class = argparse . RawDescriptionHelpFormatter , description = __description__ )
parser . add_argument ( 'output' , help = 'Target volume.' )
parser . add_argument ( 'inputs' , nargs = '+' , help = 'Source volume(s).' )
parser . add_argument ( '-o' , '--operation' , dest =... |
def get ( self , section , option , default = None ) :
"""Get a parameter value and return a string .
If default is specified and section or option are not defined
in the file , they are created and set to default , which is
then the return value .""" | with self . _lock :
if not self . _config . has_option ( section , option ) :
if default is not None :
self . _set ( section , option , default )
return default
return self . _config . get ( section , option ) |
def weave_class ( klass , aspect , methods = NORMAL_METHODS , subclasses = True , lazy = False , owner = None , name = None , aliases = True , bases = True , bag = BrokenBag ) :
"""Low - level weaver for classes .
. . warning : : You should not use this directly .""" | assert isclass ( klass ) , "Can't weave %r. Must be a class." % klass
if bag . has ( klass ) :
return Nothing
entanglement = Rollback ( )
method_matches = make_method_matcher ( methods )
logdebug ( "weave_class (klass=%r, methods=%s, subclasses=%s, lazy=%s, owner=%s, name=%s, aliases=%s, bases=%s)" , klass , method... |
def _compute_k ( self , tau ) :
r"""Evaluate the kernel directly at the given values of ` tau ` .
Parameters
tau : : py : class : ` Matrix ` , ( ` M ` , ` D ` )
` M ` inputs with dimension ` D ` .
Returns
k : : py : class : ` Array ` , ( ` M ` , )
: math : ` k ( \ tau ) ` ( less the : math : ` \ sigma ^... | y , r2l2 = self . _compute_y ( tau , return_r2l2 = True )
k = 2.0 ** ( 1.0 - self . nu ) / scipy . special . gamma ( self . nu ) * y ** ( self . nu / 2.0 ) * scipy . special . kv ( self . nu , scipy . sqrt ( y ) )
k [ r2l2 == 0 ] = 1.0
return k |
def create_collection ( self , name , codec_options = None , read_preference = None , write_concern = None , read_concern = None , session = None , ** kwargs ) :
"""Create a new : class : ` ~ pymongo . collection . Collection ` in this
database .
Normally collection creation is automatic . This method should
... | with self . __client . _tmp_session ( session ) as s :
if name in self . list_collection_names ( filter = { "name" : name } , session = s ) :
raise CollectionInvalid ( "collection %s already exists" % name )
return Collection ( self , name , True , codec_options , read_preference , write_concern , read_... |
def get_completions ( self , document , complete_event ) :
"""Yield completions""" | # Detect a file handle
m = HSYM_RE . match ( document . text_before_cursor )
if m :
text = m . group ( 1 )
doc = Document ( text , len ( text ) )
for c in self . path_completer . get_completions ( doc , complete_event ) :
yield c
else : # Get word / text before cursor .
word_before_cursor = docu... |
def update ( self , friendly_name = values . unset , default_service_role_sid = values . unset , default_channel_role_sid = values . unset , default_channel_creator_role_sid = values . unset , read_status_enabled = values . unset , reachability_enabled = values . unset , typing_indicator_timeout = values . unset , cons... | return self . _proxy . update ( friendly_name = friendly_name , default_service_role_sid = default_service_role_sid , default_channel_role_sid = default_channel_role_sid , default_channel_creator_role_sid = default_channel_creator_role_sid , read_status_enabled = read_status_enabled , reachability_enabled = reachabilit... |
def get_curated ( self , collection_id ) :
"""Retrieve a single curated collection .
To view a user ’ s private collections , the ' read _ collections ' scope is required .
: param collection _ id [ string ] : The collections ’ s ID . Required .
: return : [ Collection ] : The Unsplash Collection .""" | url = "/collections/curated/%s" % collection_id
result = self . _get ( url )
return CollectionModel . parse ( result ) |
def descendants ( self , cl = None , noduplicates = True ) :
"""returns all descendants in the taxonomy""" | if not cl :
cl = self
if cl . children ( ) :
bag = [ ]
for x in cl . children ( ) :
if x . uri != cl . uri : # avoid circular relationships
bag += [ x ] + self . descendants ( x , noduplicates )
else :
bag += [ x ]
# finally :
if noduplicates :
return ... |
def estimate_complexity ( self , x , y , z , n ) :
"""calculates a rough guess of runtime based on product of parameters""" | num_calculations = x * y * z * n
run_time = num_calculations / 100000
# a 2014 PC does about 100k calcs in a second ( guess based on prior logs )
return self . show_time_as_short_string ( run_time ) |
def _update_record_with_id ( self , identifier , rtype , content ) :
"""Updates existing record with no sub - domain name changes""" | record = self . _create_request_record ( identifier , rtype , None , content , self . _get_lexicon_option ( 'ttl' ) , self . _get_lexicon_option ( 'priority' ) )
self . _request_modify_dns_record ( record ) |
def get_command_line_arguments ( ) :
"""Retrieves command line arguments .
: return : Namespace .
: rtype : Namespace""" | parser = argparse . ArgumentParser ( add_help = False )
parser . add_argument ( "-h" , "--help" , action = "help" , help = "'Displays this help message and exit.'" )
parser . add_argument ( "-t" , "--title" , type = unicode , dest = "title" , help = "'Package title.'" )
parser . add_argument ( "-i" , "--input" , type =... |
def create_queues ( self , manager = None ) :
"""Create the shared queues that will be used by alignak daemon
process and this module process .
But clear queues if they were already set before recreating new one .
Note :
If manager is None , then we are running the unit tests for the modules and
we must c... | self . clear_queues ( manager )
# If no Manager ( ) object , go with classic Queue ( )
if not manager :
self . from_q = Queue ( )
self . to_q = Queue ( )
else :
self . from_q = manager . Queue ( )
self . to_q = manager . Queue ( ) |
def _interactive_resolve ( self , pair ) :
"""Return ' local ' , ' remote ' , or ' skip ' to use local , remote resource or skip .""" | if self . resolve_all :
if self . verbose >= 5 :
self . _print_pair_diff ( pair )
return self . resolve_all
resolve = self . options . get ( "resolve" , "skip" )
assert resolve in ( "remote" , "ask" , "skip" )
if resolve == "ask" or self . verbose >= 5 :
self . _print_pair_diff ( pair )
if resolve i... |
def tls_session_update ( self , msg_str ) :
"""XXX Something should be done about the session ID here .""" | super ( SSLv2ServerHello , self ) . tls_session_update ( msg_str )
s = self . tls_session
client_cs = s . sslv2_common_cs
css = [ cs for cs in client_cs if cs in self . ciphers ]
s . sslv2_common_cs = css
s . sslv2_connection_id = self . connection_id
s . tls_version = self . version
if self . cert is not None :
s ... |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'text' ) and self . text is not None :
_dict [ 'text' ] = self . text
if hasattr ( self , 'tokens' ) and self . tokens is not None :
_dict [ 'tokens' ] = self . tokens
if hasattr ( self , 'readings' ) and self . readings is not None :
_dict [ 'readings' ] = self . readings
if... |
def replaceItemAtIndex ( self , newItem , oldItemIndex ) :
"""Removes the item at the itemIndex and insert a new item instead .""" | oldItem = self . getItem ( oldItemIndex )
childNumber = oldItem . childNumber ( )
parentIndex = oldItemIndex . parent ( )
self . deleteItemAtIndex ( oldItemIndex )
insertedIndex = self . insertItem ( newItem , position = childNumber , parentIndex = parentIndex )
return insertedIndex |
def prettify_json_file ( file_list ) :
"""prettify JSON testcase format""" | for json_file in set ( file_list ) :
if not json_file . endswith ( ".json" ) :
logger . log_warning ( "Only JSON file format can be prettified, skip: {}" . format ( json_file ) )
continue
logger . color_print ( "Start to prettify JSON file: {}" . format ( json_file ) , "GREEN" )
dir_path = o... |
def find_slot ( cls , ctx ) :
"""Finds an empty slot to set a hardware breakpoint .
@ see : clear _ bp , set _ bp
@ type ctx : dict ( str S { - > } int )
@ param ctx : Thread context dictionary .
@ rtype : int
@ return : Slot ( debug register ) for hardware breakpoint .""" | Dr7 = ctx [ 'Dr7' ]
slot = 0
for m in cls . enableMask :
if ( Dr7 & m ) == 0 :
return slot
slot += 1
return None |
def _skip_frame ( self ) :
"""Skip the next time frame""" | for line in self . _f :
if line == 'ITEM: ATOMS\n' :
break
for i in range ( self . num_atoms ) :
next ( self . _f ) |
def create_output_dir ( config : dict , output_root : str , default_model_name : str = 'Unnamed' ) -> str :
"""Create output _ dir under the given ` ` output _ root ` ` and
- dump the given config to YAML file under this dir
- register a file logger logging to a file under this dir
: param config : config to ... | logging . info ( 'Creating output dir' )
# create output dir
model_name = default_model_name
if 'name' not in config [ 'model' ] :
logging . warning ( '\tmodel.name not found in config, defaulting to: %s' , model_name )
else :
model_name = config [ 'model' ] [ 'name' ]
if not os . path . exists ( output_root ) ... |
def findLayer ( self , layerName ) :
"""Looks up the layer for this node based on the inputed layer name .
: param layerName | < str >
: return < XNodeLayer >""" | for layer in self . _layers :
if ( layer . name ( ) == layerName ) :
return layer
return None |
def get_attachments_ids ( self , ticket_id ) :
"""Get IDs of attachments for given ticket .
: param ticket _ id : ID of ticket
: returns : List of IDs ( type int ) of attachments belonging to given
ticket . Returns None if ticket does not exist .""" | attachments = self . get_attachments ( ticket_id )
return [ int ( at [ 0 ] ) for at in attachments ] if attachments else attachments |
def to_lal_ligotimegps ( gps ) :
"""Convert the given GPS time to a ` lal . LIGOTimeGPS ` object
Parameters
gps : ` ~ gwpy . time . LIGOTimeGPS ` , ` float ` , ` str `
input GPS time , can be anything parsable by : meth : ` ~ gwpy . time . to _ gps `
Returns
ligotimegps : ` lal . LIGOTimeGPS `
a SWIG - ... | gps = to_gps ( gps )
return lal . LIGOTimeGPS ( gps . gpsSeconds , gps . gpsNanoSeconds ) |
def push_state ( self ) :
"""Push a copy of the topmost state on top of the state stack ,
returns the new top .""" | new = dict ( self . states [ - 1 ] )
self . states . append ( new )
return self . state |
def get_fixed_block ( self , keys = [ ] , unbuffered = False ) :
"""Get the decoded " fixed block " of settings and min / max data .
A subset of the entire block can be selected by keys .""" | if unbuffered or not self . _fixed_block :
self . _fixed_block = self . _read_fixed_block ( )
format = self . fixed_format
# navigate down list of keys to get to wanted data
for key in keys :
format = format [ key ]
return _decode ( self . _fixed_block , format ) |
def remove_commits ( self , items , index , attribute , origin ) :
"""Delete documents that correspond to commits deleted in the Git repository
: param items : target items to be deleted
: param index : target index
: param attribute : name of the term attribute to search items
: param origin : name of the ... | es_query = '''
{
"query": {
"bool": {
"must": {
"term": {
"origin": "%s"
}
},
"filter": {
"terms": {
... |
def running_instances ( self , context , process_name ) :
"""Get a list of running instances .
Args :
context ( ` ResolvedContext ` ) : Context the process is running in .
process _ name ( str ) : Name of the process .
Returns :
List of ( ` subprocess . Popen ` , start - time ) 2 - tuples , where start _ ... | handle = ( id ( context ) , process_name )
it = self . processes . get ( handle , { } ) . itervalues ( )
entries = [ x for x in it if x [ 0 ] . poll ( ) is None ]
return entries |
def write ( self , string ) :
"""The write method for a CalcpkgOutput object - print the string""" | if ( "" == string or '\n' == string or '\r' == string ) :
return
# Filter out any \ r newlines .
string = string . replace ( "\r" , "" )
# if ' \ r \ n ' in string :
# string = util . replaceNewlines ( string , ' \ r \ n ' )
if self . printData :
print >> sys . __stdout__ , string
if self . logData :
self .... |
def instruction_ANDCC ( self , opcode , m , register ) :
"""Performs a logical AND between the condition code register and the
immediate byte specified in the instruction and places the result in the
condition code register .
source code forms : ANDCC # xx
CC bits " HNZVC " : ddddd""" | assert register == self . cc_register
old_cc = self . get_cc_value ( )
new_cc = old_cc & m
self . set_cc ( new_cc ) |
def get_arp_table ( self ) :
"""Get arp table information .
Return a list of dictionaries having the following set of keys :
* interface ( string )
* mac ( string )
* ip ( string )
* age ( float )
For example : :
' interface ' : ' MgmtEth0 / RSP0 / CPU0/0 ' ,
' mac ' : ' 5c : 5e : ab : da : 3c : f0 ... | arp_table = [ ]
command = 'show arp | exclude Incomplete'
output = self . _send_command ( command )
# Skip the first line which is a header
output = output . split ( '\n' )
output = output [ 1 : ]
for line in output :
if len ( line ) == 0 :
return { }
if len ( line . split ( ) ) == 5 : # Static ARP entr... |
def consecutive ( data , stepsize = 1 ) :
"""Converts array into chunks with consecutive elements of given step size .
http : / / stackoverflow . com / questions / 7352684 / how - to - find - the - groups - of - consecutive - elements - from - an - array - in - numpy""" | return np . split ( data , np . where ( np . diff ( data ) != stepsize ) [ 0 ] + 1 ) |
def lineage ( self ) :
"""Return all nodes between this node and the root , including this one .""" | if not self . parent :
return [ self ]
else :
L = self . parent . lineage ( )
L . append ( self )
return L |
def wrplt ( self , fout_dir , plt_ext = "png" ) :
"""Write png containing plot of GoSubDag .""" | # Ex basename
basename = self . grprobj . get_fout_base ( self . ntplt . hdrgo )
plt_pat = self . get_pltpat ( plt_ext )
fout_basename = plt_pat . format ( BASE = basename )
fout_plt = os . path . join ( fout_dir , fout_basename )
self . gosubdagplot . plt_dag ( fout_plt )
# Create Plot
return fout_plt |
def pillar_refresh ( self , force_refresh = False , notify = False ) :
'''Refresh the pillar''' | if self . connected :
log . debug ( 'Refreshing pillar. Notify: %s' , notify )
async_pillar = salt . pillar . get_async_pillar ( self . opts , self . opts [ 'grains' ] , self . opts [ 'id' ] , self . opts [ 'saltenv' ] , pillarenv = self . opts . get ( 'pillarenv' ) , )
try :
self . opts [ 'pillar' ... |
def BLASTcheck ( rid , baseURL = "http://blast.ncbi.nlm.nih.gov" ) :
"""Checks the status of a query .
: param rid : BLAST search request identifier . Allowed values : The Request ID ( RID ) returned when the search was submitted
: param baseURL : server url . Default = http : / / blast . ncbi . nlm . nih . gov... | URL = baseURL + "/Blast.cgi?"
URL = URL + "FORMAT_OBJECT=SearchInfo&RID=" + rid + "&CMD=Get"
response = requests . get ( url = URL )
r = response . content . split ( "\n" )
try :
status = [ s for s in r if "Status=" in s ] [ 0 ] . split ( "=" ) [ - 1 ]
ThereAreHits = [ s for s in r if "ThereAreHits=" in s ] [ 0... |
def get_glibc_version ( ) :
"""Returns :
Version as a pair of ints ( major , minor ) or None""" | # TODO : Look into a nicer way to get the version
try :
out = subprocess . Popen ( [ 'ldd' , '--version' ] , stdout = subprocess . PIPE ) . communicate ( ) [ 0 ]
except OSError :
return
match = re . search ( '([0-9]+)\.([0-9]+)\.?[0-9]*' , out )
try :
return map ( int , match . groups ( ) )
except Attribute... |
def parse ( self , elt , ps ) :
'''elt - - the DOM element being parsed
ps - - the ParsedSoap object .''' | self . checkname ( elt , ps )
if len ( _children ( elt ) ) == 0 :
href = _find_href ( elt )
if not href :
if self . nilled ( elt , ps ) is False :
return [ ]
if self . nillable is True :
return Nilled
raise EvaluateException ( 'Required string missing' , ps . Back... |
def get_levels ( version = None ) :
'''get _ levels returns a dictionary of levels ( key ) and values ( dictionaries with
descriptions and regular expressions for files ) for the user .
: param version : the version of singularity to use ( default is 2.2)
: param include _ files : files to add to the level , ... | valid_versions = [ '2.3' , '2.2' ]
if version is None :
version = "2.3"
version = str ( version )
if version not in valid_versions :
bot . error ( "Unsupported version %s, valid versions are %s" % ( version , "," . join ( valid_versions ) ) )
levels_file = os . path . abspath ( os . path . join ( get_installdir... |
def get_xml_str ( self , data ) :
"""Creates a string in XML Format using the provided data structure .
@ param : Dictionary of xml tags and their elements .
@ return : String of data in xml format .""" | responses = [ ]
for tag , value in data . items ( ) :
elem = Element ( tag )
if isinstance ( value , dict ) :
for value in self . get_xml_str ( value ) :
elem . append ( value )
elif isinstance ( value , list ) :
value = ', ' . join ( [ m for m in value ] )
elem . text = ... |
def xd ( self ) :
"""get xarray dataset file handle to LSM files""" | if self . _xd is None :
path_to_lsm_files = path . join ( self . lsm_input_folder_path , self . lsm_search_card )
self . _xd = super ( NWMtoGSSHA , self ) . xd
self . _xd . lsm . coords_projected = True
return self . _xd |
def dep2req ( name , imported_by ) :
"""Convert dependency to requirement .""" | lst = [ item for item in sorted ( imported_by ) if not item . startswith ( name ) ]
res = '%-15s # from: ' % name
imps = ', ' . join ( lst )
if len ( imps ) < WIDTH - 24 :
return res + imps
return res + imps [ : WIDTH - 24 - 3 ] + '...' |
def long2ip ( l , rfc1924 = False ) :
"""Convert a network byte order 128 - bit integer to a canonical IPv6
address .
> > > long2ip ( 2130706433)
' : : 7f00:1'
> > > long2ip ( 42540766411282592856904266426630537217)
'2001 : db8 : : 1:0:0:1'
> > > long2ip ( MIN _ IP )
> > > long2ip ( MAX _ IP )
' fff... | if MAX_IP < l or l < MIN_IP :
raise TypeError ( "expected int between %d and %d inclusive" % ( MIN_IP , MAX_IP ) )
if rfc1924 :
return long2rfc1924 ( l )
# format as one big hex value
hex_str = '%032x' % l
# split into double octet chunks without padding zeros
hextets = [ '%x' % int ( hex_str [ x : x + 4 ] , 16... |
def query_disease ( ) :
"""Returns list of diseases by query parameters
tags :
- Query functions
parameters :
- name : identifier
in : query
type : string
required : false
description : Disease identifier
default : DI - 03832
- name : ref _ id
in : query
type : string
required : false
de... | allowed_str_args = [ 'identifier' , 'ref_id' , 'ref_type' , 'name' , 'acronym' , 'description' ]
args = get_args ( request_args = request . args , allowed_str_args = allowed_str_args )
return jsonify ( query . disease ( ** args ) ) |
def notify ( self , instance , old , new ) :
"""Call all callback functions with the current value
Each callback will either be called using
callback ( new ) or callback ( old , new ) depending
on whether ` ` echo _ old ` ` was set to ` True ` when calling
: func : ` ~ echo . add _ callback `
Parameters
... | if self . _disabled . get ( instance , False ) :
return
for cback in self . _callbacks . get ( instance , [ ] ) :
cback ( new )
for cback in self . _2arg_callbacks . get ( instance , [ ] ) :
cback ( old , new ) |
def insert_local_var ( self , vname , vtype , position ) :
"Inserts a new local variable" | index = self . insert_id ( vname , SharedData . KINDS . LOCAL_VAR , [ SharedData . KINDS . LOCAL_VAR , SharedData . KINDS . PARAMETER ] , vtype )
self . table [ index ] . attribute = position |
def clear_cluster ( name ) :
'''Clears accumulated statistics on all nodes in the cluster .
. . code - block : : yaml
clear _ ats _ cluster :
trafficserver . clear _ cluster''' | ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' }
if __opts__ [ 'test' ] :
ret [ 'comment' ] = 'Clearing cluster statistics'
return ret
__salt__ [ 'trafficserver.clear_cluster' ] ( )
ret [ 'result' ] = True
ret [ 'comment' ] = 'Cleared cluster statistics'
return ret |
def _parse_tcp_line ( line ) :
'''Parse a single line from the contents of / proc / net / tcp or / proc / net / tcp6''' | ret = { }
comps = line . strip ( ) . split ( )
sl = comps [ 0 ] . rstrip ( ':' )
ret [ sl ] = { }
l_addr , l_port = comps [ 1 ] . split ( ':' )
r_addr , r_port = comps [ 2 ] . split ( ':' )
ret [ sl ] [ 'local_addr' ] = hex2ip ( l_addr , True )
ret [ sl ] [ 'local_port' ] = int ( l_port , 16 )
ret [ sl ] [ 'remote_addr... |
def _computeforceArray ( self , dr_dx , dtheta_dx , dphi_dx , R , z , phi ) :
"""NAME :
_ computeforceArray
PURPOSE :
evaluate the forces in the x direction for a given array of coordinates
INPUT :
dr _ dx - the derivative of r with respect to the chosen variable x
dtheta _ dx - the derivative of theta ... | R = nu . array ( R , dtype = float ) ;
z = nu . array ( z , dtype = float ) ;
phi = nu . array ( phi , dtype = float ) ;
shape = ( R * z * phi ) . shape
if shape == ( ) :
dPhi_dr , dPhi_dtheta , dPhi_dphi = self . _computeforce ( R , z , phi )
return dr_dx * dPhi_dr + dtheta_dx * dPhi_dtheta + dPhi_dphi * dphi_... |
def serialize_yaml_tofile ( filename , resource ) :
"""Serializes a K8S resource to YAML - formatted file .""" | stream = file ( filename , "w" )
yaml . dump ( resource , stream , default_flow_style = False ) |
def MP ( candidate , references , n ) :
"""calculate modified precision""" | counts = Counter ( ngrams ( candidate , n ) )
if not counts :
return 0
max_counts = { }
for reference in references :
reference_counts = Counter ( ngrams ( reference , n ) )
for ngram in counts :
max_counts [ ngram ] = max ( max_counts . get ( ngram , 0 ) , reference_counts [ ngram ] )
clipped_count... |
def extract_xyz_matrix_from_pdb ( pdb_lines , atoms_of_interest = backbone_atoms , expected_num_residues = None , expected_num_residue_atoms = None , fail_on_model_records = True , include_all_columns = False ) :
'''Returns a pandas dataframe of X , Y , Z coordinates for all chains in the PDB .
Note : This functi... | if fail_on_model_records and [ l for l in pdb_lines if l . startswith ( 'MODEL' ) ] :
raise Exception ( 'This function does not handle files with MODEL records. Please split those file by model first.' )
chain_ids = set ( [ l [ 21 ] for l in pdb_lines if l . startswith ( 'ATOM ' ) ] )
dataframes = [ ]
for chain_id... |
def get_alt_lengths ( self ) :
"""Returns the longest length of the variant . For deletions , return is negative ,
SNPs return 0 , and insertions are + . None return corresponds to no variant in interval
for specified individual""" | # this is a hack to store the # of individuals without having to actually store it
out = [ ]
for i in six . moves . range ( len ( self . genotype ) ) :
valid_alt = self . get_alt_length ( individual = i )
if not valid_alt :
out . append ( None )
else :
out . append ( max ( valid_alt ) - len ... |
def _unwrap_func ( cls , decorated_func ) :
'''This unwraps a decorated func , returning the inner wrapped func .
This may become unnecessary with Python 3.4 ' s inspect . unwrap ( ) .''' | if click is not None : # Workaround for click . command ( ) decorator not setting
# _ _ wrapped _ _
if isinstance ( decorated_func , click . Command ) :
return cls . _unwrap_func ( decorated_func . callback )
if hasattr ( decorated_func , '__wrapped__' ) : # Recursion : unwrap more if needed
return cls ... |
def add_eager_constraints ( self , models ) :
"""Set the constraints for an eager load of the relation .
: type models : list""" | table = self . _parent . get_table ( )
self . _query . where_in ( "%s.%s" % ( table , self . _first_key ) , self . get_keys ( models ) ) |
def publish ( self , clear_load ) :
'''This method sends out publications to the minions , it can only be used
by the LocalClient .''' | extra = clear_load . get ( 'kwargs' , { } )
publisher_acl = salt . acl . PublisherACL ( self . opts [ 'publisher_acl_blacklist' ] )
if publisher_acl . user_is_blacklisted ( clear_load [ 'user' ] ) or publisher_acl . cmd_is_blacklisted ( clear_load [ 'fun' ] ) :
log . error ( '%s does not have permissions to run %s.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.