signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def setup_for_bottle ( auth , app , send_email = None , render = None , session = None , request = None , urloptions = None ) :
import bottle
auth . request = request or bottle . request
if session is not None :
auth . session = session
if send_email :
auth . send_email = send_email
... | @ bottle . hook ( 'before_request' )
def after_request ( ) :
auth . session = session or getattr ( bottle . request , 'session' ) or bottle . request . environ . get ( 'beaker.session' )
assert auth . session , 'Session not found'
# By doing this , ` ` bottle . request ` ` now has a ` ` user ` ` attribute
... |
def _Execute ( client , global_endpoint_manager , function , * args , ** kwargs ) :
"""Exectutes the function with passed parameters applying all retry policies
: param object client :
Document client instance
: param object global _ endpoint _ manager :
Instance of _ GlobalEndpointManager class
: param f... | # instantiate all retry policies here to be applied for each request execution
endpointDiscovery_retry_policy = endpoint_discovery_retry_policy . _EndpointDiscoveryRetryPolicy ( client . connection_policy , global_endpoint_manager , * args )
resourceThrottle_retry_policy = resource_throttle_retry_policy . _ResourceThro... |
def _process_phendesc ( self , limit ) :
"""The description of the resulting phenotypes
with the genotype + environment
: param limit :
: return :""" | if self . test_mode :
graph = self . testgraph
else :
graph = self . graph
model = Model ( graph )
raw = '/' . join ( ( self . rawdir , 'phendesc' ) )
LOG . info ( "processing G2P" )
line_counter = 0
with open ( raw , 'r' ) as f :
filereader = csv . reader ( f , delimiter = '\t' , quotechar = '\"' )
f .... |
def db_file ( self , value ) :
"""Setter for _ db _ file attribute""" | assert not os . path . isfile ( value ) , "%s already exists" % value
self . _db_file = value |
def get_addresses ( self , account_id , ** params ) :
"""https : / / developers . coinbase . com / api / v2 # list - addresses""" | response = self . _get ( 'v2' , 'accounts' , account_id , 'addresses' , params = params )
return self . _make_api_object ( response , Address ) |
def sqlvm_list ( client , resource_group_name = None ) :
'''Lists all SQL virtual machines in a resource group or subscription .''' | if resource_group_name : # List all sql vms in the resource group
return client . list_by_resource_group ( resource_group_name = resource_group_name )
# List all sql vms in the subscription
return client . list ( ) |
def set_sampling_strategy ( self , sensor_name , strategy_and_params ) :
"""Set a sampling strategy for a specific sensor .
Parameters
sensor _ name : string
The specific sensor .
strategy _ and _ params : seq of str or str
As tuple contains ( < strat _ name > , [ < strat _ parm1 > , . . . ] ) where the s... | sensors_strategies = { }
try :
sensor_obj = self . sensor . get ( sensor_name )
yield sensor_obj . set_sampling_strategy ( strategy_and_params )
sensors_strategies [ sensor_obj . normalised_name ] = ( True , sensor_obj . sampling_strategy )
except Exception :
sensors_strategies [ sensor_obj . normalised... |
def record ( self , auth , resource , entries , options = { } , defer = False ) :
"""Records a list of historical entries to the resource specified .
Note : This API is depricated , use recordbatch instead .
Calls a function that bulids a request that writes a list of historical entries to the
specified resou... | return self . _call ( 'record' , auth , [ resource , entries , options ] , defer ) |
def evaluate ( self ) :
"""Evaluate functional value of previous iteration .""" | if self . opt [ 'AccurateDFid' ] :
DX = self . reconstruct ( )
S = self . xstep . S
dfd = ( np . linalg . norm ( self . xstep . W * ( DX - S ) ) ** 2 ) / 2.0
if self . xmethod == 'fista' :
X = self . xstep . getcoef ( )
else :
X = self . xstep . var_y1 ( )
rl1 = np . sum ( np . a... |
def _core_semantics ( self , lex_chains , concept_weights ) :
"""Returns the n representative lexical chains for a document .""" | chain_scores = [ self . _score_chain ( lex_chain , adj_submat , concept_weights ) for lex_chain , adj_submat in lex_chains ]
scored_chains = zip ( lex_chains , chain_scores )
scored_chains = sorted ( scored_chains , key = lambda x : x [ 1 ] , reverse = True )
thresh = ( self . alpha / len ( lex_chains ) ) * sum ( chain... |
def add ( self , elt ) :
"""Generic function to add objects to the daemon internal lists .
Manage Broks , External commands
: param elt : object to add
: type elt : alignak . AlignakObject
: return : None""" | # external commands may be received as a dictionary when pushed from the WebUI
if isinstance ( elt , dict ) and 'my_type' in elt and elt [ 'my_type' ] == "externalcommand" :
if 'cmd_line' not in elt :
logger . debug ( "Received a bad formated external command: %s. " "No cmd_line!" , elt )
return
... |
def _validate_recurse_directive_types ( current_schema_type , field_schema_type , context ) :
"""Perform type checks on the enclosing type and the recursed type for a recurse directive .
Args :
current _ schema _ type : GraphQLType , the schema type at the current location
field _ schema _ type : GraphQLType ... | # Get the set of all allowed types in the current scope .
type_hints = context [ 'type_equivalence_hints' ] . get ( field_schema_type )
type_hints_inverse = context [ 'type_equivalence_hints_inverse' ] . get ( field_schema_type )
allowed_current_types = { field_schema_type }
if type_hints and isinstance ( type_hints , ... |
def get_option_choices ( opt_name , opt_value , default_value , all_choices ) :
"""Generate possible choices for the option ` opt _ name `
limited to ` opt _ value ` value with default value
as ` default _ value `""" | choices = [ ]
if isinstance ( opt_value , six . string_types ) :
choices = [ opt_value ]
elif isinstance ( opt_value , ( list , tuple ) ) :
choices = list ( opt_value )
elif opt_value is None :
choices = default_value
else :
raise InvalidOption ( 'Option %s has invalid' ' value: %s' % ( opt_name , opt_v... |
def unzip_file_if_necessary ( self , source_file ) :
"""Unzip file if zipped .""" | if source_file . endswith ( ".gz" ) :
self . print_message ( "Decompressing '%s'" % source_file )
subprocess . check_call ( [ "gunzip" , "--force" , source_file ] )
source_file = source_file [ : - len ( ".gz" ) ]
return source_file |
def get_lt ( hdr ) :
"""Obtain the LTV and LTM keyword values .
Note that this returns the values just as read from the header ,
which means in particular that the LTV values are for one - indexed
pixel coordinates .
LTM keywords are the diagonal elements of MWCS linear
transformation matrix , while LTV '... | ltm = ( hdr . get ( 'LTM1_1' , 1.0 ) , hdr . get ( 'LTM2_2' , 1.0 ) )
if ltm [ 0 ] <= 0 or ltm [ 1 ] <= 0 :
raise ValueError ( '(LTM1_1, LTM2_2) = {0} is invalid' . format ( ltm ) )
ltv = ( hdr . get ( 'LTV1' , 0.0 ) , hdr . get ( 'LTV2' , 0.0 ) )
return ltm , ltv |
def _fmt_auto ( cls , x , ** kw ) :
"""auto formatting class - method .""" | f = cls . _to_float ( x )
if abs ( f ) > 1e8 :
fn = cls . _fmt_exp
else :
if f - round ( f ) == 0 :
fn = cls . _fmt_int
else :
fn = cls . _fmt_float
return fn ( x , ** kw ) |
def _make_kde ( self , use_sklearn = False , bandwidth = None , rtol = 1e-6 , sig_clip = 50 , no_sig_clip = False , cov_all = True , ** kwargs ) :
"""Creates KDE objects for 3 - d shape parameter distribution
KDE represents likelihood as function of trapezoidal
shape parameters ( log ( delta ) , T , T / tau ) .... | try : # define points that are ok to use
first_ok = ( ( self . stars [ 'slope' ] > 0 ) & ( self . stars [ 'duration' ] > 0 ) & ( self . stars [ 'duration' ] < self . period ) & ( self . depth > 0 ) )
except KeyError :
logging . warning ( 'Must do trapezoid fits before making KDE.' )
return
self . empty = Fa... |
def get_table_info ( self , tablename ) :
"""Returns information about fields of a specific table
Returns : OrderedDict ( ( " fieldname " , MyDBRow ) , . . . ) )
* * Note * * Fields " caption " and " tooltip " are added to rows using information in moldb . gui _ info""" | conn = self . __get_conn ( )
ret = a99 . get_table_info ( conn , tablename )
if len ( ret ) == 0 :
raise RuntimeError ( "Cannot get info for table '{}'" . format ( tablename ) )
more = self . gui_info . get ( tablename )
for row in ret . values ( ) :
caption , tooltip = None , None
if more :
info = ... |
def fetch_new_release_category ( self , category_id , terr = KKBOXTerritory . TAIWAN ) :
'''Fetches new release categories by given ID .
: param category _ id : the station ID .
: type category _ id : str
: param terr : the current territory .
: return : API response .
: rtype : list
See ` https : / / d... | url = 'https://api.kkbox.com/v1.1/new-release-categories/%s' % category_id
url += '?' + url_parse . urlencode ( { 'territory' : terr } )
return self . http . _post_data ( url , None , self . http . _headers_with_access_token ( ) ) |
def format ( self ) :
"""format this object to string ( byte array ) to send data to server .""" | if any ( x not in ( 0 , 1 ) for x in [ self . fin , self . rsv1 , self . rsv2 , self . rsv3 ] ) :
raise ValueError ( "not 0 or 1" )
if self . opcode not in ABNF . OPCODES :
raise ValueError ( "Invalid OPCODE" )
length = len ( self . data )
if length >= ABNF . LENGTH_63 :
raise ValueError ( "data is too long... |
def get_field ( self , schema ) :
"""Get the requested type definition from the schema and return the
appropriate : class : ` ~ eulxml . xmlmap . fields . Field ` .
: param schema : instance of : class : ` eulxml . xmlmap . core . XsdSchema `
: rtype : : class : ` eulxml . xmlmap . fields . Field `""" | type = schema . get_type ( self . schema_type )
logger . debug ( 'Found schema type %s; base type %s, restricted values %s' % ( self . schema_type , type . base_type ( ) , type . restricted_values ) )
kwargs = { }
if type . restricted_values : # field has a restriction with enumerated values - pass as choices to field
... |
def render_ ( cls , data = { } , template_ = None , layout_ = None , ** kwargs ) :
"""To render data to the associate template file of the action view
: param data : The context data to pass to the template
: param template _ : The file template to use . By default it will map the classname / action . html
: ... | if not template_ :
stack = inspect . stack ( ) [ 1 ]
module = inspect . getmodule ( cls ) . __name__
module_name = module . split ( "." ) [ - 1 ]
action_name = stack [ 3 ]
# The method being called in the class
view_name = cls . __name__
# The name of the class without View
if view_name ... |
def checkTimeout ( self , now ) :
"""Compare current time with last _ update time , and raise an exception
if we ' re over the timeout time .""" | log . debug ( "checking for timeout on session %s" , self )
if now - self . last_update > self . timeout :
raise TftpTimeout ( "Timeout waiting for traffic" ) |
def get ( self , count , offset = 0 , _options = None ) :
'''Fetch all Plaid institutions , using / institutions / all .
: param int count : Number of institutions to fetch .
: param int offset : Number of institutions to skip .''' | options = _options or { }
return self . client . post ( '/institutions/get' , { 'count' : count , 'offset' : offset , 'options' : options , } ) |
def get_matches_lineno ( code , fn_name ) :
"Return a list of line number corresponding to the definition of function with the name fn _ name" | class Walker ( ast . NodeVisitor ) :
def __init__ ( self ) :
self . _hits = set ( )
# pylint : disable = E0213 , E1102
def onvisit ( fn ) :
def wrap ( self , node ) :
fn ( self , node )
super ( Walker , self ) . generic_visit ( node )
return wrap
@ onvisit... |
def _get_installation_key ( self , project , user_id = None , install_id = None , reprime = False ) :
"""Get the auth token for a project or installation id .""" | installation_id = install_id
if project is not None :
installation_id = self . installation_map . get ( project , { } ) . get ( "installation_id" )
if not installation_id :
if reprime : # prime installation map and try again without refreshing
self . _prime_install_map ( )
return self . _get_ins... |
def _visible_in_diff ( merge_result , context_lines = 3 ) :
"""Collects the set of lines that should be visible in a diff with a certain number of context lines""" | i = old_line = new_line = 0
while i < len ( merge_result ) :
line_or_conflict = merge_result [ i ]
if isinstance ( line_or_conflict , tuple ) :
yield old_line , new_line , line_or_conflict
old_line += len ( line_or_conflict [ 0 ] )
new_line += len ( line_or_conflict [ 1 ] )
else :
... |
def _read_dna ( self , l , lowercase = False ) :
"""Read DNA from a 2bit file where each base is encoded in 2bit
(4 bases per byte ) .
Parameters
l : tuple
Location tuple
Returns
list
Array of base chars""" | file = os . path . join ( self . dir , l . chr + ".dna.2bit" )
if not os . path . exists ( file ) :
return [ ]
if file != self . __file :
print ( 'Caching {}...' . format ( file ) )
self . __file = file
# Load file into memory
f = open ( file , 'rb' )
self . __data = f . read ( )
f . close (... |
def wrap_kwargs_to_initdict ( init_kwargs_fn : InitKwargsFnType , typename : str , check_result : bool = True ) -> InstanceToInitDictFnType :
"""Wraps a function producing a ` ` KwargsDict ` ` , making it into a function
producing an ` ` InitDict ` ` .""" | def wrapper ( obj : Instance ) -> InitDict :
result = init_kwargs_fn ( obj )
if check_result :
if not isinstance ( result , dict ) :
raise ValueError ( "Class {} failed to provide a kwargs dict and " "provided instead: {}" . format ( typename , repr ( result ) ) )
return kwargs_to_initdi... |
def provides_resource ( obj ) :
"""Checks if the given type or instance provides the
: class : ` everest . resources . interfaces . IResource ` interface .""" | if isinstance ( obj , type ) :
obj = object . __new__ ( obj )
return IResource in provided_by ( obj ) |
def get_object_attrs ( obj ) :
"""Get the attributes of an object using dir .
This filters protected attributes""" | attrs = [ k for k in dir ( obj ) if not k . startswith ( '__' ) ]
if not attrs :
attrs = dir ( obj )
return attrs |
def search ( taxonKey = None , repatriated = None , kingdomKey = None , phylumKey = None , classKey = None , orderKey = None , familyKey = None , genusKey = None , subgenusKey = None , scientificName = None , country = None , publishingCountry = None , hasCoordinate = None , typeStatus = None , recordNumber = None , la... | url = gbif_baseurl + 'occurrence/search'
args = { 'taxonKey' : taxonKey , 'repatriated' : repatriated , 'kingdomKey' : kingdomKey , 'phylumKey' : phylumKey , 'classKey' : classKey , 'orderKey' : orderKey , 'familyKey' : familyKey , 'genusKey' : genusKey , 'subgenusKey' : subgenusKey , 'scientificName' : scientificName ... |
def sign ( self , storepass = None , keypass = None , keystore = None , apk = None , alias = None , name = 'app' ) :
"""Signs ( jarsign and zipalign ) a target apk file based on keystore information , uses default debug keystore file by default .
: param storepass ( str ) : keystore file storepass
: param keypa... | target = self . get_target ( )
build_tool = android_helper . get_highest_build_tool ( target . split ( '-' ) [ 1 ] )
if keystore is None :
( keystore , storepass , keypass , alias ) = android_helper . get_default_keystore ( )
dist = '%s/%s.apk' % ( '/' . join ( apk . split ( '/' ) [ : - 1 ] ) , name )
android_helpe... |
def main ( ) :
"""NAME
dia _ vgp . py
DESCRIPTION
converts declination inclination alpha95 to virtual geomagnetic pole , dp and dm
SYNTAX
dia _ vgp . py [ - h ] [ - i ] [ - f FILE ] [ < filename ]
OPTIONS
- h prints help message and quits
- i interactive data entry
- f FILE to specify file name on... | if '-h' in sys . argv :
print ( main . __doc__ )
sys . exit ( )
if '-i' in sys . argv : # if one is - i
while 1 :
try :
ans = input ( "Input Declination: <cntrl-D to quit> " )
Dec = float ( ans )
# assign input to Dec , after conversion to floating point
... |
def get_service_regex ( base_url , service_url , sub_service ) :
"""Get the regex for a given service .
: param base _ url : string - Base URI
: param service _ url : string - Service URI under the Base URI
: param sub _ service : boolean - is the Service URI for a sub - service ?
: returns : Python Regex o... | # if the specified service _ url is already a regex
# then just use . Otherwise create what we need
if StackInABoxService . is_regex ( service_url ) :
logger . debug ( 'StackInABoxService: Received regex {0} for use...' . format ( service_url . pattern ) )
# Validate the regex against StackInABoxService require... |
def parse_FreqDist ( self , f ) :
"""Parse HOMER tagdirectory petag . FreqDistribution _ 1000 file .""" | parsed_data = dict ( )
firstline = True
for l in f [ 'f' ] :
if firstline :
firstline = False
continue
else :
s = l . split ( "\t" )
if len ( s ) > 1 :
k = s [ 0 ] . strip ( )
if k . startswith ( "More than " ) :
k = re . sub ( "More than "... |
def __substitute_objects ( self , value , context_dict ) :
"""recursively substitute value with the context _ dict""" | if type ( value ) == dict :
return dict ( [ ( k , self . __substitute_objects ( v , context_dict ) ) for k , v in value . items ( ) ] )
elif type ( value ) == str :
try :
return value % context_dict
except KeyError :
e = sys . exc_info ( ) [ 1 ]
logger . warn ( "Could not specialize ... |
def write_model ( self , file , model , pretty = False ) :
"""Write a given model to file .
Args :
file : File - like object open for writing .
model : Instance of : class : ` NativeModel ` to write .
pretty : Whether to format the XML output for readability .""" | ET . register_namespace ( 'mathml' , MATHML_NS )
ET . register_namespace ( 'xhtml' , XHTML_NS )
ET . register_namespace ( 'fbc' , FBC_V2 )
# Load compound information
compound_name = { }
compound_properties = { }
for compound in model . compounds :
compound_name [ compound . id ] = ( compound . name if compound . n... |
def perform_batch_reply ( self , * , callback : Callable [ ... , str ] , lookback_limit : int , target_handle : str , ) -> List [ OutputRecord ] :
"""Performs batch reply on target account .
Looks up the recent messages of the target user ,
applies the callback ,
and replies with
what the callback generates... | self . log . info ( f"Attempting to batch reply to mastodon user {target_handle}" )
# target handle should be able to be provided either as @ user or @ user @ domain
# note that this produces an empty first chunk
handle_chunks = target_handle . split ( "@" )
target_base_handle = handle_chunks [ 1 ]
records : List [ Out... |
def neighbor_get ( self , route_type , address , format = 'json' ) :
"""This method returns the BGP adj - RIB - in / adj - RIB - out information
in a json format .
` ` route _ type ` ` This parameter is necessary for only received - routes
and sent - routes .
- received - routes : paths received and not wit... | show = { 'format' : format , }
if route_type == 'sent-routes' or route_type == 'received-routes' :
show [ 'params' ] = [ 'neighbor' , route_type , address , 'all' ]
else :
show [ 'params' ] = [ 'neighbor' , 'received-routes' , address , 'all' ]
return call ( 'operator.show' , ** show ) |
def add_nat_rule ( port , source_interface , dest_interface ) :
"""Adds a NAT rule to iptables
: param port : String or int port number
: param source _ interface : String ( e . g . 1)
: param dest _ interface : String ( e . g . 0:0)
: return : None
: raises : TypeError , OSError""" | log = logging . getLogger ( mod_logger + '.add_nat_rule' )
# Validate args
if not isinstance ( source_interface , basestring ) :
msg = 'source_interface argument must be a string'
log . error ( msg )
raise TypeError ( msg )
if not isinstance ( dest_interface , basestring ) :
msg = 'dest_interface argume... |
def get_commits_last_modified_lines ( self , commit : Commit , modification : Modification = None ) -> Set [ str ] :
"""Given the Commit object , returns the set of commits that last
" touched " the lines that are modified in the files included in the
commit . It applies SZZ .
The algorithm works as follow : ... | buggy_commits = set ( )
if modification is not None :
modifications = [ modification ]
else :
modifications = commit . modifications
for mod in modifications :
path = mod . new_path
if mod . change_type == ModificationType . RENAME or mod . change_type == ModificationType . DELETE :
path = mod .... |
def benchmark ( self , func , gpu_args , instance , times , verbose ) :
"""benchmark the kernel instance""" | logging . debug ( 'benchmark ' + instance . name )
logging . debug ( 'thread block dimensions x,y,z=%d,%d,%d' , * instance . threads )
logging . debug ( 'grid dimensions x,y,z=%d,%d,%d' , * instance . grid )
time = None
try :
time = self . dev . benchmark ( func , gpu_args , instance . threads , instance . grid , t... |
def get_cluster_custom_object_status ( self , group , version , plural , name , ** kwargs ) : # noqa : E501
"""get _ cluster _ custom _ object _ status # noqa : E501
read status of the specified cluster scoped custom object # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asy... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . get_cluster_custom_object_status_with_http_info ( group , version , plural , name , ** kwargs )
# noqa : E501
else :
( data ) = self . get_cluster_custom_object_status_with_http_info ( group , version , plural , name ... |
def getMaintenanceTypes ( self ) :
"""Return the current list of maintenance types""" | types = [ ( 'Preventive' , safe_unicode ( _ ( 'Preventive' ) ) . encode ( 'utf-8' ) ) , ( 'Repair' , safe_unicode ( _ ( 'Repair' ) ) . encode ( 'utf-8' ) ) , ( 'Enhancement' , safe_unicode ( _ ( 'Enhancement' ) ) . encode ( 'utf-8' ) ) ]
return DisplayList ( types ) |
def update ( self , state , tnow ) :
'''update the threat state''' | self . state = state
self . update_time = tnow |
def change_port_speed ( self , hardware_id , public , speed ) :
"""Allows you to change the port speed of a server ' s NICs .
: param int hardware _ id : The ID of the server
: param bool public : Flag to indicate which interface to change .
True ( default ) means the public interface .
False indicates the ... | if public :
return self . client . call ( 'Hardware_Server' , 'setPublicNetworkInterfaceSpeed' , speed , id = hardware_id )
else :
return self . client . call ( 'Hardware_Server' , 'setPrivateNetworkInterfaceSpeed' , speed , id = hardware_id ) |
def number_of_bases_above_threshold ( high_quality_base_count , base_count_cutoff = 2 , base_fraction_cutoff = None ) :
"""Finds if a site has at least two bases of high quality , enough that it can be considered
fairly safe to say that base is actually there .
: param high _ quality _ base _ count : Dictionary... | # make a dict by dictionary comprehension where values are True or False for each base depending on whether the count meets the threshold .
# Method differs depending on whether absolute or fraction cutoff is specified
if base_fraction_cutoff :
total_hq_base_count = sum ( high_quality_base_count . values ( ) )
... |
def _AtNonLeaf ( self , attr_value , path ) :
"""Called when at a non - leaf value . Should recurse and yield values .""" | try : # Check first for iterables
# If it ' s a dictionary , we yield it
if isinstance ( attr_value , dict ) :
yield attr_value
else : # If it ' s an iterable , we recurse on each value .
for sub_obj in attr_value :
for value in self . Expand ( sub_obj , path [ 1 : ] ) :
... |
def log_cmd ( context , sampleinfo , sacct , quiet , config ) :
"""Log an analysis .
CONFIG : MIP config file for an analysis""" | log_analysis = LogAnalysis ( context . obj [ 'store' ] )
try :
new_run = log_analysis ( config , sampleinfo = sampleinfo , sacct = sacct )
except MissingFileError as error :
click . echo ( click . style ( f"Skipping, missing Sacct file: {error.message}" , fg = 'yellow' ) )
return
except KeyError as error :
... |
def _push_processor ( self , proc , index = None ) :
"""Pushes a processor onto the processor stack . Processors are
objects with proc _ request ( ) , proc _ response ( ) , and / or
proc _ exception ( ) methods , which can intercept requests ,
responses , and exceptions . When a method invokes the send ( )
... | if index is None :
self . _procstack . append ( proc )
else :
self . _procstack . insert ( index , proc ) |
def search ( self , index , query , ** kwargs ) :
"""Perform full - text searches
. . versionadded : : 2.0.9
. . warning : :
The full - text search API is experimental and subject to change
: param str index : Name of the index to query
: param couchbase . fulltext . SearchQuery query : Query to issue
:... | itercls = kwargs . pop ( 'itercls' , _FTS . SearchRequest )
iterargs = itercls . mk_kwargs ( kwargs )
params = kwargs . pop ( 'params' , _FTS . Params ( ** kwargs ) )
body = _FTS . make_search_body ( index , query , params )
return itercls ( body , self , ** iterargs ) |
def register ( self , key , initializer : callable , param = None ) :
'''Add resolver to container''' | if not callable ( initializer ) :
raise DependencyError ( 'Initializer {0} is not callable' . format ( initializer ) )
if key not in self . _initializers :
self . _initializers [ key ] = { }
self . _initializers [ key ] [ param ] = initializer |
def remove_all ( self , * tagnames ) :
"""Remove all child elements whose tagname ( e . g . ' a : p ' ) appears in
* tagnames * .""" | for tagname in tagnames :
matching = self . findall ( qn ( tagname ) )
for child in matching :
self . remove ( child ) |
def averageSequenceAccuracy ( self , minOverlap , maxOverlap , firstStat = 0 , lastStat = None ) :
"""For each object , decide whether the TM uniquely classified it by checking
that the number of predictedActive cells are in an acceptable range .""" | numCorrectSparsity = 0.0
numCorrectClassifications = 0.0
numStats = 0.0
# For each object or sequence we classify every point or element
# A sequence element is considered correctly classified only if the number
# of predictedActive cells is within a reasonable range and if the KNN
# Classifier correctly classifies the... |
def find_documents ( self , sentence , limit = None , must_sort = True , search_type = 'fuzzy' ) :
"""Returns all the documents matching the given keywords
Arguments :
sentence - - - a sentenced query
Returns :
An array of document ( doc objects )""" | sentence = sentence . strip ( )
sentence = strip_accents ( sentence )
if sentence == u"" :
return self . get_all_docs ( )
result_list_list = [ ]
total_results = 0
for query_parser in self . search_param_list [ search_type ] :
query = query_parser [ "query_parser" ] . parse ( sentence )
sortedby = None
i... |
def _parse_value ( self , write_token = True , override = None ) :
"""Convert string repr of Fortran type to equivalent Python type .""" | v_str = self . prior_token
# Construct the complex string
if v_str == '(' :
v_re = self . token
self . _update_tokens ( write_token )
assert self . token == ','
self . _update_tokens ( write_token )
v_im = self . token
self . _update_tokens ( write_token )
assert self . token == ')'
self... |
def disable_vxlan_feature ( self , nexus_host ) :
"""Disable VXLAN on the switch .""" | # Removing the " feature nv overlay " configuration also
# removes the " interface nve " configuration .
starttime = time . time ( )
# Do CLI ' no feature nv overlay '
self . send_edit_string ( nexus_host , snipp . PATH_VXLAN_STATE , ( snipp . BODY_VXLAN_STATE % "disabled" ) )
# Do CLI ' no feature vn - segment - vlan ... |
def get_parameters ( self ) :
"""gets from all wrapped processors""" | d = { }
for p in self . processors :
parameter_names = list ( p . PARAMETERS . keys ( ) )
parameter_values = [ getattr ( p , n ) for n in parameter_names ]
d . update ( dict ( zip ( parameter_names , parameter_values ) ) )
return d |
def getheader ( self , which , use_hash = None , polish = True ) :
"""Get a formatted header .""" | header = getheader ( which , use_hash = use_hash , target = self . target , no_tco = self . no_tco , strict = self . strict , )
if polish :
header = self . polish ( header )
return header |
def create_conf_file ( self , data , directory = None ) :
"""Create local config file from given data ( list of lines ) in
the directory ( or current directory if not given ) .""" | data . insert ( 0 , "# this file is automatically created by setup.py" )
data . insert ( 0 , "# -*- coding: iso-8859-1 -*-" )
if directory is None :
directory = os . getcwd ( )
filename = self . get_conf_filename ( directory )
# add metadata
metanames = ( "name" , "version" , "author" , "author_email" , "maintainer... |
def ks_significance ( fg_pos , bg_pos = None ) :
"""Computes the - log10 of Kolmogorov - Smirnov p - value of position distribution .
Parameters
fg _ pos : array _ like
The list of values for the positive set .
bg _ pos : array _ like , optional
The list of values for the negative set .
Returns
p : fl... | p = ks_pvalue ( fg_pos , max ( fg_pos ) )
if p > 0 :
return - np . log10 ( p )
else :
return np . inf |
def generate_property_deprecation_message ( to_be_removed_in_version , old_name , new_name , new_attribute , module_name = 'Client' ) :
"""Generate a message to be used when warning about the use of deprecated properties .
: param to _ be _ removed _ in _ version : Version of this module the deprecated property w... | message = "Call to deprecated property '{name}'. This property will be removed in version '{version}'" . format ( name = old_name , version = to_be_removed_in_version , )
message += " Please use the '{new_name}' property on the '{module_name}.{new_attribute}' attribute moving forward." . format ( new_name = new_name , ... |
def _call ( self , x , out = None ) :
"""Scale ` ` x ` ` and write to ` ` out ` ` if given .""" | if out is None :
out = self . scalar * x
else :
out . lincomb ( self . scalar , x )
return out |
def GetLocation ( location = None , alias = None , session = None ) :
"""Returns a list of anti - affinity policies within a specific location .
> > > clc . v2 . AntiAffinity . GetLocation ( " VA1 " )
[ < clc . APIv2 . anti _ affinity . AntiAffinity object at 0x105eeded0 > ]""" | if not location :
location = clc . v2 . Account . GetLocation ( session = session )
return ( AntiAffinity . GetAll ( alias = alias , location = location , session = session ) ) |
def subscribe ( self , path , callback , * args ) :
"""Subscribe to changes in a given attribute and call
` ` callback ( future , value , * args ) ` ` when it changes
Returns :
Future : A single Future which will resolve to the result""" | request = Subscribe ( self . _get_next_id ( ) , path , delta = False )
request . set_callback ( self . _q . put )
# If self is in args , then make weak version of it
saved_args = [ ]
for arg in args :
if arg is self :
saved_args . append ( weakref . proxy ( self ) )
else :
saved_args . append ( ... |
def update ( self ) :
"""Update CPU stats using the input method .""" | # Grab stats into self . stats
if self . input_method == 'local' :
stats = self . update_local ( )
elif self . input_method == 'snmp' :
stats = self . update_snmp ( )
else :
stats = self . get_init_value ( )
# Update the stats
self . stats = stats
return self . stats |
async def dispatch_request ( self , request_context : Optional [ RequestContext ] = None , ) -> ResponseReturnValue :
"""Dispatch the request to the view function .
Arguments :
request _ context : The request context , optional as Flask
omits this argument .""" | request_ = ( request_context or _request_ctx_stack . top ) . request
if request_ . routing_exception is not None :
raise request_ . routing_exception
if request_ . method == 'OPTIONS' and request_ . url_rule . provide_automatic_options :
return await self . make_default_options_response ( )
handler = self . vie... |
def highlight_spaces ( self , text , offset = 0 ) :
"""Make blank space less apparent by setting the foreground alpha .
This only has an effect when ' Show blank space ' is turned on .
Derived classes could call this function at the end of
highlightBlock ( ) .""" | flags_text = self . document ( ) . defaultTextOption ( ) . flags ( )
show_blanks = flags_text & QTextOption . ShowTabsAndSpaces
if show_blanks :
format_leading = self . formats . get ( "leading" , None )
format_trailing = self . formats . get ( "trailing" , None )
match = self . BLANKPROG . search ( text , ... |
def add ( self , key , metric , ** dims ) :
"""Adds custom metric instances to the registry with dimensions
which are not created with their constructors default arguments""" | return super ( MetricsRegistry , self ) . add ( self . metadata . register ( key , ** dims ) , metric ) |
def power_source_str ( self ) :
"""String representation of current power source .""" | if DeviceInfo . ATTR_POWER_SOURCE not in self . raw :
return None
return DeviceInfo . VALUE_POWER_SOURCES . get ( self . power_source , 'Unknown' ) |
def carry_over_color ( lines ) :
"""Given a sequence of lines , for each line that contains a ANSI color escape
sequence without a reset , add a reset to the end of that line and copy all
colors in effect at the end of it to the beginning of the next line .""" | lines2 = [ ]
in_effect = ''
for s in lines :
s = in_effect + s
in_effect = ''
m = re . search ( COLOR_BEGIN_RGX + '(?:(?!' + COLOR_END_RGX + ').)*$' , s )
if m :
s += '\033[m'
in_effect = '' . join ( re . findall ( COLOR_BEGIN_RGX , m . group ( 0 ) ) )
lines2 . append ( s )
return li... |
def end_of_paragraph ( self , count = 1 , after = False ) :
"""Return the end of the current paragraph . ( Relative cursor position . )""" | def match_func ( text ) :
return not text or text . isspace ( )
line_index = self . find_next_matching_line ( match_func = match_func , count = count )
if line_index :
add = 0 if after else 1
return max ( 0 , self . get_cursor_down_position ( count = line_index ) - add )
else :
return len ( self . text_... |
def nullable ( self , ctype : ContentType ) -> bool :
"""Override the superclass method .""" | return self . left . nullable ( ctype ) or self . right . nullable ( ctype ) |
def _GetEventData ( self , parser_mediator , record_index , evt_record , recovered = False ) :
"""Retrieves event data from the Windows EventLog ( EVT ) record .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
record _ in... | event_data = WinEvtRecordEventData ( )
try :
event_data . record_number = evt_record . identifier
except OverflowError as exception :
parser_mediator . ProduceExtractionWarning ( ( 'unable to read record identifier from event record: {0:d} ' 'with error: {1!s}' ) . format ( record_index , exception ) )
try :
... |
def check_all_params_are_keyword ( method ) :
"""Raises CooperativeError if method any parameter that is not a
named keyword parameter""" | args , varargs , keywords , defaults = inspect . getargspec ( method )
# Always have self , thus the - 1
if len ( args or [ ] ) - 1 != len ( defaults or [ ] ) :
raise CooperativeError , "Init has positional parameters " + str ( args [ 1 : ] )
if varargs :
raise CooperativeError , "Init has variadic positional p... |
def add_variables_to_context ( generator ) :
'''Adds useful iterable variables to template context''' | context = generator . context
# minimize attr lookup
context [ 'relpath_to_site' ] = relpath_to_site
context [ 'main_siteurl' ] = _MAIN_SITEURL
context [ 'main_lang' ] = _MAIN_LANG
context [ 'lang_siteurls' ] = _SITE_DB
current_lang = generator . settings [ 'DEFAULT_LANG' ]
extra_siteurls = _SITE_DB . copy ( )
extra_si... |
def highlight_current_line ( editor ) :
"""Highlights given editor current line .
: param editor : Document editor .
: type editor : QWidget
: return : Method success .
: rtype : bool""" | format = editor . language . theme . get ( "accelerator.line" )
if not format :
return False
extra_selections = editor . extraSelections ( ) or [ ]
if not editor . isReadOnly ( ) :
selection = QTextEdit . ExtraSelection ( )
selection . format . setBackground ( format . background ( ) )
selection . forma... |
def write_metadata ( self ) :
"""Write all ID3v2.4 tags to file from self . metadata""" | import mutagen
from mutagen import id3
id3 = id3 . ID3 ( self . filename )
for tag in self . metadata . keys ( ) :
value = self . metadata [ tag ]
frame = mutagen . id3 . Frames [ tag ] ( 3 , value )
try :
id3 . add ( frame )
except :
raise IOError ( 'EncoderError: cannot tag "' + tag + ... |
def _extract_key_val ( kv , delimiter = '=' ) :
'''Extract key and value from key = val string .
Example :
> > > _ extract _ key _ val ( ' foo = bar ' )
( ' foo ' , ' bar ' )''' | pieces = kv . split ( delimiter )
key = pieces [ 0 ]
val = delimiter . join ( pieces [ 1 : ] )
return key , val |
def update ( self , workspace , params = { } , ** options ) :
"""A specific , existing workspace can be updated by making a PUT request on
the URL for that workspace . Only the fields provided in the data block
will be updated ; any unspecified fields will remain unchanged .
Currently the only field that can ... | path = "/workspaces/%s" % ( workspace )
return self . client . put ( path , params , ** options ) |
def set_color ( self , value , callb = None , duration = 0 , rapid = False ) :
"""Convenience method to set the colour status of the device
This method will send a LightSetColor message to the device , and request callb be executed
when an ACK is received . The default callback will simply cache the value .
:... | if len ( value ) == 4 :
mypartial = partial ( self . resp_set_light , color = value )
if callb :
mycallb = lambda x , y : ( mypartial ( y ) , callb ( x , y ) )
else :
mycallb = lambda x , y : mypartial ( y )
# try :
if rapid :
self . fire_and_forget ( LightSetColor , { "color... |
def setdefault ( self , key , value ) :
"""We may not always be connected to an app , but we still need
to provide a way to the base environment to set it ' s defaults .""" | try :
super ( FlaskConfigStorage , self ) . setdefault ( key , value )
except RuntimeError :
self . _defaults . __setitem__ ( key , value ) |
def get_outcome_for_state_name ( self , name ) :
"""Returns the final outcome of the child state specified by name .
Note : This is utility function that is used by the programmer to make a decision based on the final outcome
of its child states . A state is not uniquely specified by the name , but as the progr... | return_value = None
for state_id , name_outcome_tuple in self . final_outcomes_dict . items ( ) :
if name_outcome_tuple [ 0 ] == name :
return_value = name_outcome_tuple [ 1 ]
break
return return_value |
def _remove_deprecated_options ( self , old_version ) :
"""Remove options which are present in the . ini file but not in defaults""" | old_defaults = self . _load_old_defaults ( old_version )
for section in old_defaults . sections ( ) :
for option , _ in old_defaults . items ( section , raw = self . raw ) :
if self . get_default ( section , option ) is NoDefault :
try :
self . remove_option ( section , option )
... |
def make_multi_metatile ( parent , tiles , date_time = None ) :
"""Make a metatile containing a list of tiles all having the same layer ,
with coordinates relative to the given parent . Set date _ time to a 6 - tuple
of ( year , month , day , hour , minute , second ) to set the timestamp for
members . Otherwi... | assert parent is not None , "Parent tile must be provided and not None to make a metatile."
if len ( tiles ) == 0 :
return [ ]
if date_time is None :
date_time = gmtime ( ) [ 0 : 6 ]
layer = tiles [ 0 ] [ 'layer' ]
buf = StringIO . StringIO ( )
with zipfile . ZipFile ( buf , mode = 'w' ) as z :
for tile in ... |
def parse_version ( v ) :
"""Take a string version and conver it to a tuple ( for easier comparison ) , e . g . :
"1.2.3 " - - > ( 1 , 2 , 3)
"1.2 " - - > ( 1 , 2 , 0)
"1 " - - > ( 1 , 0 , 0)""" | parts = v . split ( "." )
# Pad the list to make sure there is three elements so that we get major , minor , point
# comparisons that default to " 0 " if not given . I . e . " 1.2 " - - > ( 1 , 2 , 0)
parts = ( parts + 3 * [ '0' ] ) [ : 3 ]
return tuple ( int ( x ) for x in parts ) |
def Size ( self ) :
"""Get the total size in bytes of the object .
Returns :
int : size .""" | corrected_hashes = list ( map ( lambda i : UInt256 ( data = binascii . unhexlify ( i ) ) , self . HashStart ) )
return GetVarSize ( corrected_hashes ) + self . hash_stop . Size |
def plot_walks ( self , parameters = None , truth = None , extents = None , display = False , filename = None , chains = None , convolve = None , figsize = None , plot_weights = True , plot_posterior = True , log_weight = None ) : # pragma : no cover
"""Plots the chain walk ; the parameter values as a function of s... | chains , parameters , truth , extents , _ = self . _sanitise ( chains , parameters , truth , extents )
n = len ( parameters )
extra = 0
if plot_weights :
plot_weights = plot_weights and np . any ( [ np . any ( c . weights != 1.0 ) for c in chains ] )
plot_posterior = plot_posterior and np . any ( [ c . posterior is... |
def get_path ( self , repo ) :
"""Return the path for the repo""" | if repo . endswith ( '.git' ) :
repo = repo . split ( '.git' ) [ 0 ]
org , name = repo . split ( '/' ) [ - 2 : ]
path = self . plugins_dir
path = join ( path , org , name )
return path , org , name |
def validate_io ( f = DECORATED , none_policy = None , # type : int
_out_ = None , # type : ValidationFuncs
** kw_validation_funcs # type : ValidationFuncs
) :
"""A function decorator to add input validation prior to the function execution . It should be called with named
arguments : for each function arg name , ... | return decorate_several_with_validation ( f , none_policy = none_policy , _out_ = _out_ , ** kw_validation_funcs ) |
async def ask_async ( self , patch_stdout : bool = False , kbi_msg : str = DEFAULT_KBI_MESSAGE ) -> Any :
"""Ask the question using asyncio and return user response .""" | if self . should_skip_question :
return self . default
try :
sys . stdout . flush ( )
return await self . unsafe_ask_async ( patch_stdout )
except KeyboardInterrupt :
print ( "\n{}\n" . format ( kbi_msg ) )
return None |
def get_gene_substitution_language ( ) -> ParserElement :
"""Build a gene substitution parser .""" | parser_element = gsub_tag + nest ( dna_nucleotide ( GSUB_REFERENCE ) , ppc . integer ( GSUB_POSITION ) , dna_nucleotide ( GSUB_VARIANT ) , )
parser_element . setParseAction ( _handle_gsub )
return parser_element |
def AND ( queryArr , exclude = None ) :
"""create a combined query with multiple items on which to perform an AND operation
@ param queryArr : a list of items on which to perform an AND operation . Items can be either a CombinedQuery or BaseQuery instances .
@ param exclude : a instance of BaseQuery , CombinedQ... | assert isinstance ( queryArr , list ) , "provided argument as not a list"
assert len ( queryArr ) > 0 , "queryArr had an empty list"
q = CombinedQuery ( )
q . setQueryParam ( "$and" , [ ] )
for item in queryArr :
assert isinstance ( item , ( CombinedQuery , BaseQuery ) ) , "item in the list was not a CombinedQuery ... |
def reset_x ( self , x , copy = True ) :
"""reset self . _ _ x private attribute
Parameters
x : numpy . ndarray
copy : bool
flag to make a copy of ' x ' . Defaule is True
Note
makes a copy of ' x ' argument""" | assert x . shape == self . shape
if copy :
self . __x = x . copy ( )
else :
self . __x = x |
def _encode_request ( self , request ) :
"""Encode a request object""" | obj = request_to_dict ( request , self . spider )
return self . serializer . dumps ( obj ) |
def enabled_plugins ( installed_only = True ) :
'''. . versionadded : : 0.21
Parameters
installed _ only : bool , optional
Only consider enabled plugins that are installed in the Conda
environment .
Returns
list
List of properties corresponding to each plugin that is * * enabled * * .
If : data : ` ... | enabled_path = MICRODROP_CONDA_PLUGINS . joinpath ( 'enabled' )
if not enabled_path . isdir ( ) :
return [ ]
# Construct list of property dictionaries , one per enabled plugin
# directory .
enabled_plugins_ = [ ]
for plugin_path_i in enabled_path . dirs ( ) :
if not installed_only or _islinklike ( plugin_path_i... |
def _clear_context ( bin_env = None ) :
'''Remove the cached pip version''' | contextkey = 'pip.version'
if bin_env is not None :
contextkey = '{0}.{1}' . format ( contextkey , bin_env )
__context__ . pop ( contextkey , None ) |
def parse ( self , rrstr ) : # type : ( bytes ) - > None
'''Parse a Rock Ridge Child Link record out of a string .
Parameters :
rrstr - The string to parse the record out of .
Returns :
Nothing .''' | if self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'CL record already initialized!' )
# We assume that the caller has already checked the su _ entry _ version ,
# so we don ' t bother .
( su_len , su_entry_version_unused , child_log_block_num_le , child_log_block_num_be ) = struct . unpack_fro... |
def _set_igmps_interface ( self , v , load = False ) :
"""Setter method for igmps _ interface , mapped from YANG variable / interface _ vlan / vlan / ip / igmpVlan / snooping / igmps _ mrouter / igmps _ interface ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "igmps_if_type igmps_value" , igmps_interface . igmps_interface , yang_name = "igmps-interface" , rest_name = "interface" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.