signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def potentiallayers ( self , x , y , layers , aq = None ) :
'''Returns array of size len ( layers )
only used in building equations''' | if aq is None :
aq = self . model . aq . find_aquifer_data ( x , y )
pot = np . sum ( self . potential ( x , y , aq ) * aq . eigvec , 1 )
return pot [ layers ] |
def hash_file ( file_obj , hash_function = hashlib . md5 ) :
"""Get the hash of an open file - like object .
Parameters
file _ obj : file like object
hash _ function : function to use to hash data
Returns
hashed : str , hex version of result""" | # before we read the file data save the current position
# in the file ( which is probably 0)
file_position = file_obj . tell ( )
# create an instance of the hash object
hasher = hash_function ( )
# read all data from the file into the hasher
hasher . update ( file_obj . read ( ) )
# get a hex version of the result
has... |
def __validate_logical ( self , operator , definitions , field , value ) :
"""Validates value against all definitions and logs errors according
to the operator .""" | valid_counter = 0
_errors = errors . ErrorList ( )
for i , definition in enumerate ( definitions ) :
schema = { field : definition . copy ( ) }
for rule in ( 'allow_unknown' , 'type' ) :
if rule not in schema [ field ] and rule in self . schema [ field ] :
schema [ field ] [ rule ] = self . ... |
def parse_cell ( cell , rules ) :
"""Applies the rules to the bunch of text describing a cell .
@ param string cell
A network / cell from iwlist scan .
@ param dictionary rules
A dictionary of parse rules .
@ return dictionary
parsed networks .""" | parsed_cell = { }
for key in rules :
rule = rules [ key ]
parsed_cell . update ( { key : rule ( cell ) } )
return parsed_cell |
def handle ( self , state , message = False ) :
"""Handle a state update .
: param state : the new chat state
: type state : : class : ` ~ aioxmpp . chatstates . ChatState `
: param message : pass true to indicate that we handle the
: data : ` ACTIVE ` state that is implied by
sending a content message . ... | if message :
if state != chatstates_xso . ChatState . ACTIVE :
raise ValueError ( "Only the state ACTIVE can be sent with messages." )
elif self . _state == state :
return False
self . _state = state
return self . _strategy . sending |
def is_python_interpreter ( filename ) :
"""Evaluate wether a file is a python interpreter or not .""" | real_filename = os . path . realpath ( filename )
# To follow symlink if existent
if ( not osp . isfile ( real_filename ) or not is_python_interpreter_valid_name ( filename ) ) :
return False
elif is_pythonw ( filename ) :
if os . name == 'nt' : # pythonw is a binary on Windows
if not encoding . is_text... |
def generate_content_encoding ( self ) :
"""Means decoding value when it ' s encoded by base64.
. . code - block : : python
' contentEncoding ' : ' base64 ' ,""" | if self . _definition [ 'contentEncoding' ] == 'base64' :
with self . l ( 'if isinstance({variable}, str):' ) :
with self . l ( 'try:' ) :
self . l ( 'import base64' )
self . l ( '{variable} = base64.b64decode({variable})' )
with self . l ( 'except Exception:' ) :
... |
def cluster ( args ) :
"""% prog cluster prefix fastqfiles
Use ` vsearch ` to remove duplicate reads . This routine is heavily influenced
by PyRAD : < https : / / github . com / dereneaton / pyrad > .""" | p = OptionParser ( cluster . __doc__ )
add_consensus_options ( p )
p . set_align ( pctid = 95 )
p . set_outdir ( )
p . set_cpus ( )
opts , args = p . parse_args ( args )
if len ( args ) < 2 :
sys . exit ( not p . print_help ( ) )
prefix = args [ 0 ]
fastqfiles = args [ 1 : ]
cpus = opts . cpus
pctid = opts . pctid
... |
def get_votes ( self ) :
"""Get all votes for this election .""" | candidate_elections = CandidateElection . objects . filter ( election = self )
votes = None
for ce in candidate_elections :
votes = votes | ce . votes . all ( )
return votes |
def _request_modify_dns_record ( self , record ) :
"""Sends Modify _ DNS _ Record request""" | return self . _request_internal ( "Modify_DNS_Record" , domain = self . domain , record = record ) |
def merge_wcs_counts_cubes ( filelist ) :
"""Merge all the files in filelist , assuming that they WCS counts cubes""" | out_prim = None
out_ebounds = None
datalist_gti = [ ]
exposure_sum = 0.
nfiles = len ( filelist )
ngti = np . zeros ( nfiles , int )
for i , filename in enumerate ( filelist ) :
fin = fits . open ( filename )
sys . stdout . write ( '.' )
sys . stdout . flush ( )
if i == 0 :
out_prim = update_pri... |
def store ( self ) :
'''Return a thread local : class : ` dossier . store . Store ` client .''' | if self . _store is None :
config = global_config ( 'dossier.store' )
self . _store = self . create ( ElasticStore , config = config )
return self . _store |
def persist ( self , key ) :
"""Remove the existing timeout on key .""" | fut = self . execute ( b'PERSIST' , key )
return wait_convert ( fut , bool ) |
def main ( ) -> None :
"""Command - line processor . See ` ` - - help ` ` for details .""" | logging . basicConfig ( level = logging . DEBUG )
parser = argparse . ArgumentParser ( )
parser . add_argument ( "inputfile" , nargs = "?" , help = "Input file name" )
parser . add_argument ( "--availability" , nargs = '*' , help = "File extensions to check availability for (use a '.' prefix, " "and use the special ext... |
def fill_document ( doc ) :
"""Add a section , a subsection and some text to the document .
: param doc : the document
: type doc : : class : ` pylatex . document . Document ` instance""" | with doc . create ( Section ( 'A section' ) ) :
doc . append ( 'Some regular text and some ' )
doc . append ( italic ( 'italic text. ' ) )
with doc . create ( Subsection ( 'A subsection' ) ) :
doc . append ( 'Also some crazy characters: $&#{}' ) |
def compute_amount ( self ) :
"""Auto - assign and return the total amount for this tax .""" | self . amount = self . base_amount * self . aliquot / 100
return self . amount |
def _from_dict ( cls , _dict ) :
"""Initialize a RuntimeIntent object from a json dictionary .""" | args = { }
xtra = _dict . copy ( )
if 'intent' in _dict :
args [ 'intent' ] = _dict . get ( 'intent' )
del xtra [ 'intent' ]
else :
raise ValueError ( 'Required property \'intent\' not present in RuntimeIntent JSON' )
if 'confidence' in _dict :
args [ 'confidence' ] = _dict . get ( 'confidence' )
de... |
def _build_schema ( self , s ) :
"""Recursive schema builder , called by ` json _ schema ` .""" | w = self . _whatis ( s )
if w == self . IS_LIST :
w0 = self . _whatis ( s [ 0 ] )
js = { "type" : "array" , "items" : { "type" : self . _jstype ( w0 , s [ 0 ] ) } }
elif w == self . IS_DICT :
js = { "type" : "object" , "properties" : { key : self . _build_schema ( val ) for key , val in s . items ( ) } }
... |
def asdict ( self ) :
"""Return dict presentation of this service .
Useful for dumping the device information into JSON .""" | return { "methods" : { m . name : m . asdict ( ) for m in self . methods } , "protocols" : self . protocols , "notifications" : { n . name : n . asdict ( ) for n in self . notifications } , } |
def drag_events ( self ) :
"""Return a list of all mouse events in the current drag operation .
Returns None if there is no current drag operation .""" | if not self . is_dragging :
return None
event = self
events = [ ]
while True : # mouse _ press events can only be the start of a trail
if event is None or event . type == 'mouse_press' :
break
events . append ( event )
event = event . last_event
return events [ : : - 1 ] |
def _get_parameter_symbols ( self , n_counter , k_counter ) :
r"""Calculates parameters Y expressions and beta coefficients in
: math : ` X = { A ( \ beta _ 0 , \ beta _ 1 \ ldots \ beta _ n ) \ cdot Y } `
: param n _ counter : a list of : class : ` ~ means . core . descriptors . Moment ` \ s representing centr... | n_moment = self . max_order + 1
expectation_symbols = sp . Matrix ( [ n . symbol for n in k_counter if n . order == 1 ] )
n_species = len ( expectation_symbols )
# Create auxiliary symbolic species Y _ { ij } , for i , j = 0 . . . ( n - 1 ) and mirror , so that Y _ { ij } = Y _ { ji }
symbolic_species = sp . Matrix ( [... |
def resample ( self , destination = None , datasets = None , generate = True , unload = True , resampler = None , reduce_data = True , ** resample_kwargs ) :
"""Resample datasets and return a new scene .
Args :
destination ( AreaDefinition , GridDefinition ) : area definition to
resample to . If not specified... | to_resample_ids = [ dsid for ( dsid , dataset ) in self . datasets . items ( ) if ( not datasets ) or dsid in datasets ]
if destination is None :
destination = self . max_area ( to_resample_ids )
new_scn = self . copy ( datasets = to_resample_ids )
# we may have some datasets we asked for but don ' t exist yet
new_... |
def write_representative_sequences_file ( self , outname , outdir = None , set_ids_from_model = True ) :
"""Write all the model ' s sequences as a single FASTA file . By default , sets IDs to model gene IDs .
Args :
outname ( str ) : Name of the output FASTA file without the extension
outdir ( str ) : Path to... | if not outdir :
outdir = self . data_dir
if not outdir :
raise ValueError ( 'Output directory must be specified' )
outfile = op . join ( outdir , outname + '.faa' )
tmp = [ ]
for x in self . genes_with_a_representative_sequence :
repseq = x . protein . representative_sequence
copied_seq_record =... |
def build_system_components ( device_type , os_id , navigator_id ) :
"""For given os _ id build random platform and oscpu
components
Returns dict { platform _ version , platform , ua _ platform , oscpu }
platform _ version is OS name used in different places
ua _ platform goes to navigator . platform
plat... | if os_id == 'win' :
platform_version = choice ( OS_PLATFORM [ 'win' ] )
cpu = choice ( OS_CPU [ 'win' ] )
if cpu :
platform = '%s; %s' % ( platform_version , cpu )
else :
platform = platform_version
res = { 'platform_version' : platform_version , 'platform' : platform , 'ua_platform'... |
def register_app ( app_name , app_setting , web_application_setting , mainfile , package_space ) :
"""insert current project root path into sys path""" | from turbo import log
app_config . app_name = app_name
app_config . app_setting = app_setting
app_config . project_name = os . path . basename ( get_base_dir ( mainfile , 2 ) )
app_config . web_application_setting . update ( web_application_setting )
if app_setting . get ( 'session_config' ) :
app_config . session_... |
def _update_validation_response ( error , response ) :
"""Actualiza la respuesta por default acorde a un error de
validación .""" | new_response = response . copy ( )
# El status del catálogo entero será ERROR
new_response [ "status" ] = "ERROR"
# Adapto la información del ValidationError recibido a los fines
# del validador de DataJsons
error_info = { # Error Code 1 para " campo obligatorio faltante "
# Error Code 2 para " error en tipo o forma... |
def roles_accepted ( * role_names ) :
"""| This decorator ensures that the current user is logged in ,
| and has * at least one * of the specified roles ( OR operation ) .
Example : :
@ route ( ' / edit _ article ' )
@ roles _ accepted ( ' Writer ' , ' Editor ' )
def edit _ article ( ) : # User must be ' ... | # convert the list to a list containing that list .
# Because roles _ required ( a , b ) requires A AND B
# while roles _ required ( [ a , b ] ) requires A OR B
def wrapper ( view_function ) :
@ wraps ( view_function ) # Tells debuggers that is is a function wrapper
def decorator ( * args , ** kwargs ) :
... |
def dump_bulk ( cls , parent = None , keep_ids = True ) :
"""Dumps a tree branch to a python data structure .""" | cls = get_result_class ( cls )
# Because of fix _ tree , this method assumes that the depth
# and numchild properties in the nodes can be incorrect ,
# so no helper methods are used
qset = cls . _get_serializable_model ( ) . objects . all ( )
if parent :
qset = qset . filter ( path__startswith = parent . path )
ret... |
def listen ( self , callback = None , timeout = ( 5 , 300 ) ) :
"""Start the & listen long poll and return immediately .""" | if self . _running :
return False
# if self . devices ( ) is False :
# return False
self . _queue = Queue ( )
self . _running = True
self . _timeout = timeout
self . _callback_listen = callback
threading . Thread ( target = self . _thread_listen , args = ( ) ) . start ( )
threading . Thread ( target = self . _threa... |
def set_relocated_name ( self , name , rr_name ) : # type : ( str , str ) - > None
'''Set the name of the relocated directory on a Rock Ridge ISO . The ISO
must be a Rock Ridge one , and must not have previously had the relocated
name set .
Parameters :
name - The name for a relocated directory .
rr _ nam... | if not self . _initialized :
raise pycdlibexception . PyCdlibInvalidInput ( 'This object is not yet initialized; call either open() or new() to create an ISO' )
if not self . rock_ridge :
raise pycdlibexception . PyCdlibInvalidInput ( 'Can only set the relocated name on a Rock Ridge ISO' )
encoded_name = name .... |
def _generate_examples ( self , archive , directory ) :
"""Generate IMDB examples .""" | reg = re . compile ( os . path . join ( "^%s" % directory , "(?P<label>neg|pos)" , "" ) )
for path , imdb_f in archive :
res = reg . match ( path )
if not res :
continue
text = imdb_f . read ( ) . strip ( )
yield { "text" : text , "label" : res . groupdict ( ) [ "label" ] , } |
def process ( self , plugin , context , instance = None , action = None ) :
"""Transmit a ` process ` request to host
Arguments :
plugin ( PluginProxy ) : Plug - in to process
context ( ContextProxy ) : Filtered context
instance ( InstanceProxy , optional ) : Instance to process
action ( str , optional ) ... | plugin = plugin . to_json ( )
instance = instance . to_json ( ) if instance is not None else None
return self . _dispatch ( "process" , args = [ plugin , instance , action ] ) |
async def _init_clean ( self ) :
"""Must be called when the agent is starting""" | # Data about running containers
self . _containers_running = { }
self . _container_for_job = { }
self . _student_containers_running = { }
self . _student_containers_for_job = { }
self . _containers_killed = dict ( )
# Delete tmp _ dir , and recreate - it again
try :
await self . _ashutil . rmtree ( self . _tmp_dir ... |
def asStructTime ( self , tzinfo = None ) :
"""Return this time represented as a time . struct _ time .
tzinfo is a datetime . tzinfo instance coresponding to the desired
timezone of the output . If is is the default None , UTC is assumed .""" | dtime = self . asDatetime ( tzinfo )
if tzinfo is None :
return dtime . utctimetuple ( )
else :
return dtime . timetuple ( ) |
def make_cand_plot ( d , im , data , loclabel , version = 2 , snrs = [ ] , outname = '' ) :
"""Builds a new candidate plot , distinct from the original plots produced by make _ cand _ plot .
Expects phased , dedispersed data ( cut out in time , dual - pol ) , image , and metadata
version 2 is the new one ( than... | # given d , im , data , make plot
logger . info ( 'Plotting...' )
logger . debug ( '(image, data) shape: (%s, %s)' % ( str ( im . shape ) , str ( data . shape ) ) )
assert len ( loclabel ) == 6 , 'loclabel should have (scan, segment, candint, dmind, dtind, beamnum)'
scan , segment , candint , dmind , dtind , beamnum = ... |
def command_u2k ( string , vargs ) :
"""Print the Kirshenbaum ASCII string corresponding to the given Unicode IPA string .
: param str string : the string to act upon
: param dict vargs : the command line arguments""" | try :
l = KirshenbaumMapper ( ) . map_unicode_string ( unicode_string = string , ignore = vargs [ "ignore" ] , single_char_parsing = vargs [ "single_char_parsing" ] , return_as_list = True )
print ( vargs [ "separator" ] . join ( l ) )
except ValueError as exc :
print_error ( str ( exc ) ) |
def can_patch ( self , filename ) :
"""Check if specified filename can be patched . Returns None if file can
not be found among source filenames . False if patch can not be applied
clearly . True otherwise .
: returns : True , False or None""" | filename = abspath ( filename )
for p in self . items :
if filename == abspath ( p . source ) :
return self . _match_file_hunks ( filename , p . hunks )
return None |
def _convert_to_folder ( self , packages ) :
"""Silverstripe ' s page contains a list of composer packages . This
function converts those to folder names . These may be different due
to installer - name .
Implemented exponential backoff in order to prevent packager from
being overly sensitive about the numb... | url = 'http://packagist.org/p/%s.json'
with ThreadPoolExecutor ( max_workers = 12 ) as executor :
futures = [ ]
for package in packages :
future = executor . submit ( self . _get , url , package )
futures . append ( { 'future' : future , 'package' : package } )
folders = [ ]
for i , futu... |
def dump_options_header ( header , options ) :
"""The reverse function to : func : ` parse _ options _ header ` .
: param header : the header to dump
: param options : a dict of options to append .""" | segments = [ ]
if header is not None :
segments . append ( header )
for key , value in iteritems ( options ) :
if value is None :
segments . append ( key )
else :
segments . append ( "%s=%s" % ( key , quote_header_value ( value ) ) )
return "; " . join ( segments ) |
def _log_players ( self , players ) :
""": param players : list of catan . game . Player objects""" | self . _logln ( 'players: {0}' . format ( len ( players ) ) )
for p in self . _players :
self . _logln ( 'name: {0}, color: {1}, seat: {2}' . format ( p . name , p . color , p . seat ) ) |
def get_url ( width , height = None , background_color = "cccccc" , text_color = "969696" , text = None , random_background_color = False ) :
"""Craft the URL for a placeholder image .
You can customize the background color , text color and text using
the optional keyword arguments
If you want to use a random... | if random_background_color :
background_color = _get_random_color ( )
# If height is not provided , presume it is will be a square
if not height :
height = width
d = dict ( width = width , height = height , bcolor = background_color , tcolor = text_color )
url = URL % d
if text :
text = text . replace ( " "... |
def validate_character_instance_valid_for_arc ( sender , instance , action , reverse , pk_set , * args , ** kwargs ) :
'''Evaluate attempts to assign a character instance to ensure it is from same
outline .''' | if action == 'pre_add' :
if reverse : # Fetch arc definition through link .
for apk in pk_set :
arc_node = ArcElementNode . objects . get ( pk = apk )
if arc_node . parent_outline != instance . outline :
raise IntegrityError ( _ ( 'Character Instance and Arc Element m... |
def fire_event ( self , event_name , wait = False , * args , ** kwargs ) :
"""Fire an event to plugins .
PluginManager schedule @ asyncio . coroutinecalls for each plugin on method called " on _ " + event _ name
For example , on _ connect will be called on event ' connect '
Method calls are schedule in the as... | tasks = [ ]
event_method_name = "on_" + event_name
for plugin in self . _plugins :
event_method = getattr ( plugin . object , event_method_name , None )
if event_method :
try :
task = self . _schedule_coro ( event_method ( * args , ** kwargs ) )
tasks . append ( task )
... |
def sink_create ( self , project , sink_name , filter_ , destination , unique_writer_identity = False ) :
"""API call : create a sink resource .
See
https : / / cloud . google . com / logging / docs / reference / v2 / rest / v2 / projects . sinks / create
: type project : str
: param project : ID of the pro... | parent = "projects/%s" % ( project , )
sink_pb = LogSink ( name = sink_name , filter = filter_ , destination = destination )
created_pb = self . _gapic_api . create_sink ( parent , sink_pb , unique_writer_identity = unique_writer_identity )
return MessageToDict ( created_pb ) |
def Partial ( func , ** kwargs ) :
"""Allows the use of partially applied functions in the
configuration .""" | if isinstance ( func , str ) :
func = resolve_dotted_name ( func )
partial_func = partial ( func , ** kwargs )
update_wrapper ( partial_func , func )
return partial_func |
def download ( queries , user = None , pwd = None , email = None , pred_type = 'and' ) :
"""Spin up a download request for GBIF occurrence data .
: param queries : One or more of query arguments to kick of a download job .
See Details .
: type queries : str or list
: param pred _ type : ( character ) One of... | user = _check_environ ( 'GBIF_USER' , user )
pwd = _check_environ ( 'GBIF_PWD' , pwd )
email = _check_environ ( 'GBIF_EMAIL' , email )
if isinstance ( queries , str ) :
queries = [ queries ]
keyval = [ _parse_args ( z ) for z in queries ]
# USE GBIFDownload class to set up the predicates
req = GbifDownload ( user ,... |
def url ( self ) -> str :
"""path + query 的url""" | url_str = self . parse_url . path or ""
if self . parse_url . querystring is not None :
url_str += "?" + self . parse_url . querystring
return url_str |
def play ( quiet , session_file , shell , speed , prompt , commentecho ) :
"""Play a session file .""" | run ( session_file . readlines ( ) , shell = shell , speed = speed , quiet = quiet , test_mode = TESTING , prompt_template = prompt , commentecho = commentecho , ) |
def apply ( self , data ) :
"""Applies calibration solution to data array . Assumes structure of ( nint , nbl , nch , npol ) .""" | # find best skyfreq for each channel
skyfreqs = n . unique ( self . skyfreq [ self . select ] )
# one per spw
nch_tot = len ( self . freqs )
chan_bandnum = [ range ( nch_tot * i / len ( skyfreqs ) , nch_tot * ( i + 1 ) / len ( skyfreqs ) ) for i in range ( len ( skyfreqs ) ) ]
# divide chans by number of spw in solutio... |
def is_label_dataframe ( label , df ) :
"""check column label existance""" | setdiff = set ( label ) - set ( df . columns . tolist ( ) )
if len ( setdiff ) == 0 :
return True
else :
return False |
def flush_all ( self , time ) :
"""Send a command to server flush | delete all keys .
: param time : Time to wait until flush in seconds .
: type time : int
: return : True in case of success , False in case of failure
: rtype : bool""" | logger . info ( 'Flushing memcached' )
self . _send ( struct . pack ( self . HEADER_STRUCT + self . COMMANDS [ 'flush' ] [ 'struct' ] , self . MAGIC [ 'request' ] , self . COMMANDS [ 'flush' ] [ 'command' ] , 0 , 4 , 0 , 0 , 4 , 0 , 0 , time ) )
( magic , opcode , keylen , extlen , datatype , status , bodylen , opaque ... |
def translify ( in_string , strict = True ) :
"""Translify russian text
@ param in _ string : input string
@ type in _ string : C { unicode }
@ param strict : raise error if transliteration is incomplete .
( True by default )
@ type strict : C { bool }
@ return : transliterated string
@ rtype : C { st... | translit = in_string
for symb_in , symb_out in TRANSTABLE :
translit = translit . replace ( symb_in , symb_out )
if strict and any ( ord ( symb ) > 128 for symb in translit ) :
raise ValueError ( "Unicode string doesn't transliterate completely, " + "is it russian?" )
return translit |
def min ( self ) :
"""Return the minimum value in this histogram .
If there are no values in the histogram at all , return 10.
Returns :
int : The minimum value in the histogram .""" | if len ( self . _data ) == 0 :
return 10
return next ( iter ( sorted ( self . _data . keys ( ) ) ) ) |
def variant_filtration ( call_file , ref_file , vrn_files , data , items ) :
"""Filter variant calls using Variant Quality Score Recalibration .
Newer GATK with Haplotype calling has combined SNP / indel filtering .""" | caller = data [ "config" ] [ "algorithm" ] . get ( "variantcaller" )
if "gvcf" not in dd . get_tools_on ( data ) :
call_file = ploidy . filter_vcf_by_sex ( call_file , items )
if caller in [ "freebayes" ] :
return vfilter . freebayes ( call_file , ref_file , vrn_files , data )
elif caller in [ "platypus" ] :
... |
def _macros2pys ( self ) :
"""Writes macros to pys file
Format : < macro code line > \n""" | macros = self . code_array . dict_grid . macros
pys_macros = macros . encode ( "utf-8" )
self . pys_file . write ( pys_macros ) |
def get_experiment_spec ( self , matrix_declaration ) :
"""Returns an experiment spec for this group spec and the given matrix declaration .""" | parsed_data = Parser . parse ( self , self . _data , matrix_declaration )
del parsed_data [ self . HP_TUNING ]
validator . validate ( spec = self , data = parsed_data )
return ExperimentSpecification ( values = [ parsed_data , { 'kind' : self . _EXPERIMENT } ] ) |
def tie_properties ( self , class_list ) :
"""Runs through the classess and ties the properties to the class
args :
class _ list : a list of class names to run""" | log . setLevel ( self . log_level )
start = datetime . datetime . now ( )
log . info ( " Tieing properties to the class" )
for cls_name in class_list :
cls_obj = getattr ( MODULE . rdfclass , cls_name )
prop_dict = dict ( cls_obj . properties )
for prop_name , prop_obj in cls_obj . properties . items ( ) :
... |
def new_code_block ( self , ** kwargs ) :
"""Create a new code block .""" | proto = { 'content' : '' , 'type' : self . code , 'IO' : '' , 'attributes' : '' }
proto . update ( ** kwargs )
return proto |
def _call_method ( self , request ) :
"""Calls given method with given params and returns it value .""" | method = self . method_data [ request [ 'method' ] ] [ 'method' ]
params = request [ 'params' ]
result = None
try :
if isinstance ( params , list ) : # Does it have enough arguments ?
if len ( params ) < self . _man_args ( method ) :
raise InvalidParamsError ( 'not enough arguments' )
# ... |
def sample_storage_size ( self ) :
"""Get the storage size of the samples storage collection .""" | try :
coll_stats = self . database . command ( 'collStats' , 'fs.chunks' )
sample_storage_size = coll_stats [ 'size' ] / 1024.0 / 1024.0
return sample_storage_size
except pymongo . errors . OperationFailure :
return 0 |
def optimize ( self , ** kwargs ) :
"""Iteratively optimize the ROI model . The optimization is
performed in three sequential steps :
* Free the normalization of the N largest components ( as
determined from NPred ) that contain a fraction ` ` npred _ frac ` `
of the total predicted counts in the model and ... | loglevel = kwargs . pop ( 'loglevel' , self . loglevel )
timer = Timer . create ( start = True )
self . logger . log ( loglevel , 'Starting' )
loglike0 = - self . like ( )
self . logger . debug ( 'LogLike: %f' % loglike0 )
# Extract options from kwargs
config = copy . deepcopy ( self . config [ 'roiopt' ] )
config [ 'o... |
def in6_getscope ( addr ) :
"""Returns the scope of the address .""" | if in6_isgladdr ( addr ) or in6_isuladdr ( addr ) :
scope = IPV6_ADDR_GLOBAL
elif in6_islladdr ( addr ) :
scope = IPV6_ADDR_LINKLOCAL
elif in6_issladdr ( addr ) :
scope = IPV6_ADDR_SITELOCAL
elif in6_ismaddr ( addr ) :
if in6_ismgladdr ( addr ) :
scope = IPV6_ADDR_GLOBAL
elif in6_ismlladdr (... |
def format ( amount , currency = None ) :
"""Formats a decimal or Money object into an unambiguous string representation
for the purpose of invoices in English .
: param amount :
A Decimal or Money object
: param currency :
If the amount is a Decimal , the currency of the amount
: return :
A string re... | if currency is None and hasattr ( amount , 'currency' ) :
currency = amount . currency
# Allow Money objects
if not isinstance ( amount , Decimal ) and hasattr ( amount , 'amount' ) :
amount = amount . amount
if not isinstance ( currency , str_cls ) :
raise ValueError ( 'The currency specified is not a stri... |
def start_crawler ( self , index , daemonize = False ) :
"""Starts a crawler from the input - array .
: param int index : The array - index of the site
: param int daemonize : Bool if the crawler is supposed to be daemonized
( to delete the JOBDIR )""" | call_process = [ sys . executable , self . __single_crawler , self . cfg_file_path , self . json_file_path , "%s" % index , "%s" % self . shall_resume , "%s" % daemonize ]
self . log . debug ( "Calling Process: %s" , call_process )
crawler = Popen ( call_process , stderr = None , stdout = None )
crawler . communicate (... |
def update_delivery_note ( self , delivery_note_id , delivery_note_dict ) :
"""Updates a delivery note
: param delivery _ note _ id : the delivery note id
: param delivery _ note _ dict : dict
: return : dict""" | return self . _create_put_request ( resource = DELIVERY_NOTES , billomat_id = delivery_note_id , send_data = delivery_note_dict ) |
def refresh ( self ) :
'''Refresh the list and the screen''' | self . _screen . force_update ( )
self . _screen . refresh ( )
self . _update ( 1 ) |
def get_node_type ( self , node , parent = None ) :
"""If node is a document , the type is page .
If node is a binder with no parent , the type is book .
If node is a translucent binder , the type is either chapters ( only
contain pages ) or unit ( contains at least one translucent binder ) .""" | if isinstance ( node , CompositeDocument ) :
return 'composite-page'
elif isinstance ( node , ( Document , DocumentPointer ) ) :
return 'page'
elif isinstance ( node , Binder ) and parent is None :
return 'book'
for child in node :
if isinstance ( child , TranslucentBinder ) :
return 'unit'
retu... |
def _symbolic_product_helper ( ) :
"""Use SymPy to generate the 3D products for diffusion _ stencil _ 3d .""" | from sympy import symbols , Matrix
D11 , D12 , D13 , D21 , D22 , D23 , D31 , D32 , D33 = symbols ( 'D11, D12, D13, D21, D22, D23, D31, D32, D33' )
D = Matrix ( [ [ D11 , D12 , D13 ] , [ D21 , D22 , D23 ] , [ D31 , D32 , D33 ] ] )
grad = Matrix ( [ [ 'dx' , 'dy' , 'dz' ] ] ) . T
div = grad . T
a = div * D * grad
print (... |
def _set_interface_PO_ospf_conf ( self , v , load = False ) :
"""Setter method for interface _ PO _ ospf _ conf , mapped from YANG variable / interface / port _ channel / ip / interface _ PO _ ospf _ conf ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ int... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = interface_PO_ospf_conf . interface_PO_ospf_conf , is_container = 'container' , presence = False , yang_name = "interface-PO-ospf-conf" , rest_name = "" , parent = self , path_helper = self . _path_helper , extmethods = self .... |
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_rx_fdiscs ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
fcoe_get_interface = ET . Element ( "fcoe_get_interface" )
config = fcoe_get_interface
output = ET . SubElement ( fcoe_get_interface , "output" )
fcoe_intf_list = ET . SubElement ( output , "fcoe-intf-list" )
fcoe_intf_fcoe_port_id_key = ET . SubElement ( fcoe_intf_list , "fcoe-intf-f... |
def validate ( self ) :
"""validate : Makes sure document node contains at least one EPUB or PDF
Args : None
Returns : boolean indicating if document is valid""" | from . files import DocumentFile , EPubFile
try :
assert self . kind == content_kinds . DOCUMENT , "Assumption Failed: Node should be a document"
assert self . questions == [ ] , "Assumption Failed: Document should not have questions"
assert len ( self . files ) > 0 , "Assumption Failed: Document should hav... |
def nanopub_to_edges ( nanopub : dict = { } , rules : List [ str ] = [ ] , orthologize_targets : list = [ ] ) :
"""Process nanopub into edges and load into EdgeStore
Args :
nanopub : BEL Nanopub
rules : list of compute rules to process
orthologize _ targets : list of species in TAX : < int > format
Return... | # Collect input values # # # # #
nanopub_url = nanopub . get ( "source_url" , "" )
edge_dt = utils . dt_utc_formatted ( )
# don ' t want this in relation _ id
# Extract BEL Version and make sure we can process this
if nanopub [ "nanopub" ] [ "type" ] [ "name" ] . upper ( ) == "BEL" :
bel_version = nanopub [ "nanopu... |
def create ( self , name , ** kwargs ) :
"""Create new role
http : / / www . keycloak . org / docs - api / 3.4 / rest - api / index . html
# _ roles _ resource
: param str name : Name for the role
: param str description : ( optional )
: param str id : ( optional )
: param bool client _ role : ( optiona... | payload = OrderedDict ( name = name )
for key in ROLE_KWARGS :
if key in kwargs :
payload [ to_camel_case ( key ) ] = kwargs [ key ]
return self . _client . post ( url = self . _client . get_full_url ( self . get_path ( 'collection' , realm = self . _realm_name , id = self . _client_id ) ) , data = json . d... |
def unregister ( self , slug ) :
"""Unregisters the given url .
If a slug isn ' t already registered , this will raise NotRegistered .""" | if slug not in self . _registry :
raise NotRegistered ( 'The slug %s is not registered' % slug )
bundle = self . _registry [ slug ]
if bundle . _meta . model and bundle . _meta . primary_model_bundle :
self . unregister_model ( bundle . _meta . model )
del self . _registry [ slug ]
del self . _order [ slug ] |
def plot_edoses ( self , dos_pos = None , method = "gaussian" , step = 0.01 , width = 0.1 , ** kwargs ) :
"""Plot the band structure and the DOS .
Args :
dos _ pos : Index of the task from which the DOS should be obtained .
None is all DOSes should be displayed . Accepts integer or list of integers .
method... | if dos_pos is not None and not isinstance ( dos_pos , ( list , tuple ) ) :
dos_pos = [ dos_pos ]
from abipy . electrons . ebands import ElectronDosPlotter
plotter = ElectronDosPlotter ( )
for i , task in enumerate ( self . dos_tasks ) :
if dos_pos is not None and i not in dos_pos :
continue
with tas... |
def escape ( u ) :
"""Escape a string in an OAuth - compatible fashion .
TODO : verify whether this can in fact be used for OAuth 2""" | if not isinstance ( u , unicode_type ) :
raise ValueError ( 'Only unicode objects are escapable.' )
return quote ( u . encode ( 'utf-8' ) , safe = b'~' ) |
def folderitem ( self , obj , item , index ) :
"""Augment folder listing item with additional data""" | url = item . get ( "url" )
title = item . get ( "DocumentID" )
item [ "replace" ] [ "DocumentID" ] = get_link ( url , title )
item [ "FileDownload" ] = ""
item [ "replace" ] [ "FileDownload" ] = ""
file = self . get_file ( obj )
if file and file . get_size ( ) > 0 :
filename = file . filename
download_url = "{}... |
def build ( self , X , Y , w = None , edges = None ) :
"""Assigns data to this object and builds the Morse - Smale
Complex
@ In , X , an m - by - n array of values specifying m
n - dimensional samples
@ In , Y , a m vector of values specifying the output
responses corresponding to the m samples specified ... | super ( ContourTree , self ) . build ( X , Y , w , edges )
# Build the join and split trees that we will merge into the
# contour tree
joinTree = MergeTree ( debug = self . debug )
splitTree = MergeTree ( debug = self . debug )
joinTree . build_for_contour_tree ( self , True )
splitTree . build_for_contour_tree ( self ... |
def reset ( self ) :
"""Reset analyzer state""" | self . prevframe = None
self . wasmoving = False
self . t0 = 0
self . ismoving = False |
def hist ( self , * columns , overlay = True , bins = None , bin_column = None , unit = None , counts = None , group = None , side_by_side = False , width = 6 , height = 4 , ** vargs ) :
"""Plots one histogram for each column in columns . If no column is
specified , plot all columns .
Kwargs :
overlay ( bool ... | if counts is not None and bin_column is None :
warnings . warn ( "counts arg of hist is deprecated; use bin_column" )
bin_column = counts
if columns :
columns_included = list ( columns )
if bin_column is not None :
columns_included . append ( bin_column )
if group is not None :
colum... |
def items ( self ) :
"""Items are the discussions on the entries .""" | content_type = ContentType . objects . get_for_model ( Entry )
return comments . get_model ( ) . objects . filter ( content_type = content_type , is_public = True ) . order_by ( '-submit_date' ) [ : self . limit ] |
def build_permission_name ( model_class , prefix ) :
"""Build permission name for model _ class ( like ' app . add _ model ' ) .""" | model_name = model_class . _meta . object_name . lower ( )
app_label = model_class . _meta . app_label
action_name = prefix
perm = '%s.%s_%s' % ( app_label , action_name , model_name )
return perm |
def check_scicrunch_for_label ( self , label : str ) -> dict :
"""Sees if label with your user ID already exists
There are can be multiples of the same label in interlex , but there should only be one
label with your user id . Therefore you can create labels if there already techniqually
exist , but not if yo... | list_of_crude_matches = self . crude_search_scicrunch_via_label ( label )
for crude_match in list_of_crude_matches : # If labels match
if crude_match [ 'label' ] . lower ( ) . strip ( ) == label . lower ( ) . strip ( ) :
complete_data_of_crude_match = self . get_entity ( crude_match [ 'ilx' ] )
crud... |
def get_cache_settings ( self , service_id , version_number , name ) :
"""Get a specific cache settings object .""" | content = self . _fetch ( "/service/%s/version/%d/cache_settings/%s" % ( service_id , version_number , name ) )
return FastlyCacheSettings ( self , content ) |
def handle_starttag ( self , tag , attrs ) :
"""This method handles any HTML tags that have a matching
closing tag . So elements like < p > and < div > are handled
by this method .
@ param < string > tag
An html tag that has a separate closing tag such as < p >
< div > or < body >
@ param < tuple > attr... | dattrs = dict ( attrs )
# look for ' < link type = ' text / css ' rel = ' stylesheet ' href = ' . . . ' > tags
# to see if looking for link tags makes sense here , we need to know
# a little more about the implementation . Whether HTML parser looks for
# the trailing slash at the end of an element , or just knows which... |
def attribute_value ( self , doc : Document , attribute_name : str ) :
"""Access data using attribute name rather than the numeric indices
Returns : the value for the attribute""" | return doc . cdr_document . get ( self . header_translation_table [ attribute_name ] ) |
def add_cluster ( self , name , server = None , certificate_authority_data = None , ** attrs ) :
"""Add a cluster to config .""" | if self . cluster_exists ( name ) :
raise KubeConfError ( "Cluster with the given name already exists." )
clusters = self . get_clusters ( )
# Add parameters .
new_cluster = { 'name' : name , 'cluster' : { } }
attrs_ = new_cluster [ 'cluster' ]
if server is not None :
attrs_ [ 'server' ] = server
if certificate... |
def get_stack_frame ( N = 0 , strict = True ) :
"""Args :
N ( int ) : N = 0 means the frame you called this function in .
N = 1 is the parent frame .
strict ( bool ) : ( default = True )""" | frame_cur = inspect . currentframe ( )
for _ix in range ( N + 1 ) : # always skip the frame of this function
frame_next = frame_cur . f_back
if frame_next is None :
if strict :
raise AssertionError ( 'Frame level %r is root' % _ix )
else :
break
frame_cur = frame_next... |
def GetKeyByPath ( self , key_path ) :
"""Retrieves the key for a specific path .
Args :
key _ path ( str ) : Windows Registry key path .
Returns :
WinRegistryKey : Windows Registry key or None if not available .""" | key_path_upper = key_path . upper ( )
if key_path_upper . startswith ( self . _key_path_prefix_upper ) :
relative_key_path = key_path [ self . _key_path_prefix_length : ]
elif key_path . startswith ( definitions . KEY_PATH_SEPARATOR ) :
relative_key_path = key_path
key_path = '' . join ( [ self . _key_path_... |
def remove_time_dependent_effects ( self , ts ) :
"""Given a timeseries , apply inverse operations to obtain the original series of underlying errors .
Parameters
ts :
Time series of observations with this model ' s characteristics as a Numpy array
returns the time series with removed time - dependent effec... | destts = Vectors . dense ( np . array ( [ 0 ] * len ( ts ) ) )
result = self . _jmodel . removeTimeDependentEffects ( _py2java ( self . _ctx , Vectors . dense ( ts ) ) , _py2java ( self . _ctx , destts ) )
return _java2py ( self . _ctx , result . toArray ( ) ) |
def is_unstructured ( self , var ) :
"""Test if a variable is on an unstructered grid
Parameters
% ( CFDecoder . is _ triangular . parameters ) s
Returns
% ( CFDecoder . is _ triangular . returns ) s
Notes
Currently this is the same as : meth : ` is _ triangular ` method , but may
change in the future... | if str ( var . attrs . get ( 'grid_type' ) ) == 'unstructured' :
return True
xcoord = self . get_x ( var )
if xcoord is not None :
bounds = self . _get_coord_cell_node_coord ( xcoord )
if bounds is not None and bounds . shape [ - 1 ] > 2 :
return True |
def assign_indent_numbers ( lst , inum , dic = collections . defaultdict ( int ) ) :
"""Associate keywords with their respective indentation numbers""" | for i in lst :
dic [ i ] = inum
return dic |
def render_pull_base_image ( self ) :
"""Configure pull _ base _ image""" | phase = 'prebuild_plugins'
plugin = 'pull_base_image'
if self . user_params . parent_images_digests . value :
self . pt . set_plugin_arg ( phase , plugin , 'parent_images_digests' , self . user_params . parent_images_digests . value ) |
def _bsecurate_cli_elements_in_files ( args ) :
'''Handles the elements - in - files subcommand''' | data = curate . elements_in_files ( args . files )
return '\n' . join ( format_columns ( data . items ( ) ) ) |
def validate ( request : Union [ Dict , List ] , schema : dict ) -> Union [ Dict , List ] :
"""Wraps jsonschema . validate , returning the same object passed in .
Args :
request : The deserialized - from - json request .
schema : The jsonschema schema to validate against .
Raises :
jsonschema . Validation... | jsonschema_validate ( request , schema )
return request |
def film_search ( self , title ) :
"""film search using fuzzy matching""" | films = [ ]
# check for cache or update
if not hasattr ( self , 'film_list' ) :
self . get_film_list ( )
# iterate over films and check for fuzzy string match
for film in self . film_list :
strength = WRatio ( title , film [ 'title' ] )
if strength > 80 :
film . update ( { u'strength' : strength } )... |
def errbackForName ( self , instance , commandName , errorName ) :
"""Retrieve an errback - a callable object that accepts a L { Failure } as an
argument - that is exposed on the given instance , given an AMP
commandName and a name in that command ' s error mapping .""" | return super ( _AMPErrorExposer , self ) . get ( instance , ( commandName , errorName ) ) |
def remove_vip ( self , vip_request_ids ) :
"""Method to delete vip request
param vip _ request _ ids : vip _ request ids""" | uri = 'api/v3/vip-request/deploy/%s/' % vip_request_ids
return super ( ApiVipRequest , self ) . delete ( uri ) |
def list_members ( context , request ) :
"""Return the list of users in the group .""" | members = context . members ( )
return { 'users' : [ { 'username' : m . identifier , 'userid' : m . userid , 'roles' : context . get_member_roles ( m . userid ) , 'links' : [ rellink ( m , request ) ] } for m in members ] } |
def get_minions ( ) :
'''Return a list of minions''' | log . debug ( 'sqlite3 returner <get_minions> called' )
conn = _get_conn ( ret = None )
cur = conn . cursor ( )
sql = '''SELECT DISTINCT id FROM salt_returns'''
cur . execute ( sql )
data = cur . fetchall ( )
ret = [ ]
for minion in data :
ret . append ( minion [ 0 ] )
_close_conn ( conn )
return ret |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.