signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def make_vocab_from_args ( args : argparse . Namespace ) :
"""Just converts from an ` ` argparse . Namespace ` ` object to params .""" | parameter_path = args . param_path
overrides = args . overrides
serialization_dir = args . serialization_dir
params = Params . from_file ( parameter_path , overrides )
make_vocab_from_params ( params , serialization_dir ) |
def reindex_variables ( variables : Mapping [ Any , Variable ] , sizes : Mapping [ Any , int ] , indexes : Mapping [ Any , pd . Index ] , indexers : Mapping , method : Optional [ str ] = None , tolerance : Any = None , copy : bool = True , ) -> 'Tuple[OrderedDict[Any, Variable], OrderedDict[Any, pd.Index]]' :
"""Co... | from . dataarray import DataArray
# create variables for the new dataset
reindexed = OrderedDict ( )
# type : OrderedDict [ Any , Variable ]
# build up indexers for assignment along each dimension
int_indexers = { }
new_indexes = OrderedDict ( indexes )
masked_dims = set ( )
unchanged_dims = set ( )
for dim , indexer i... |
def artist_commentary_list ( self , text_matches = None , post_id = None , post_tags_match = None , original_present = None , translated_present = None ) :
"""list artist commentary .
Parameters :
text _ matches ( str ) :
post _ id ( int ) :
post _ tags _ match ( str ) : The commentary ' s post ' s tags mat... | params = { 'search[text_matches]' : text_matches , 'search[post_id]' : post_id , 'search[post_tags_match]' : post_tags_match , 'search[original_present]' : original_present , 'search[translated_present]' : translated_present }
return self . _get ( 'artist_commentaries.json' , params ) |
def stratHeun ( f , G , y0 , tspan , dW = None ) :
"""Use the Stratonovich Heun algorithm to integrate Stratonovich equation
dy = f ( y , t ) dt + G ( y , t ) \ circ dW ( t )
where y is the d - dimensional state vector , f is a vector - valued function ,
G is an d x m matrix - valued function giving the noise... | ( d , m , f , G , y0 , tspan , dW , __ ) = _check_args ( f , G , y0 , tspan , dW , None )
N = len ( tspan )
h = ( tspan [ N - 1 ] - tspan [ 0 ] ) / ( N - 1 )
# allocate space for result
y = np . zeros ( ( N , d ) , dtype = type ( y0 [ 0 ] ) )
if dW is None : # pre - generate Wiener increments ( for m independent Wiener... |
def value ( self ) :
"""Return the node value , if we ' re a leaf node .
Examples :
> > > c = Configuration ( " test " )
> > > c [ ' x ' ] = { " y " : { " value " : None } , " z " : { " value " : 2 } }
> > > c [ ' x ' ] [ ' y ' ] . value = = None
True
> > > c [ ' x ' ] [ ' z ' ] . value
> > > c [ ' x ... | def validate ( node_value ) :
if hasattr ( node_value , 'validate' ) :
node_value . validate ( )
return node_value
if 'value' in self . node :
return validate ( self . node [ 'value' ] )
return self |
def register_token ( self , * args , ** kwargs ) :
"""Register token
Accepts :
- token _ name [ string ]
- contract _ address [ hex string ]
- blockchain [ string ] token ' s blockchain ( QTUMTEST , ETH )
Returns dictionary with following fields :
- success [ Bool ]""" | client = HTTPClient ( self . withdraw_server_address + self . withdraw_endpoint )
if check_sig :
return client . request ( 'register_token' , self . signature_validator . sign ( kwargs ) )
else :
return client . request ( 'register_token' , kwargs ) |
def _mp_run_check ( tasks , results , options ) :
"""a helper function for multiprocessing with DistReport .""" | try :
for index , change in iter ( tasks . get , None ) : # this is the part that takes up all of our time and
# produces side - effects like writing out files for all of
# the report formats .
change . check ( )
# rather than serializing the completed change ( which
# could be rathe... |
async def _set_persistent_menu ( self ) :
"""Define the persistent menu for all pages""" | page = self . settings ( )
if 'menu' in page :
await self . _send_to_messenger_profile ( page , { 'persistent_menu' : page [ 'menu' ] , } )
logger . info ( 'Set menu for page %s' , page [ 'page_id' ] ) |
def arches ( self ) :
"""Return a list of architectures for this task .
: returns : a list of arch strings ( eg [ " ppc64le " , " x86_64 " ] ) . The list
is empty if this task has no arches associated with it .""" | if self . method == 'image' :
return self . params [ 2 ]
if self . arch :
return [ self . arch ]
return [ ] |
def right_click_zijderveld ( self , event ) :
"""toggles between zoom and pan effects for the zijderveld on right
click
Parameters
event : the wx . MouseEvent that triggered the call of this function
Alters
zijderveld _ setting , toolbar1 setting""" | if event . LeftIsDown ( ) or event . ButtonDClick ( ) :
return
elif self . zijderveld_setting == "Zoom" :
self . zijderveld_setting = "Pan"
try :
self . toolbar1 . pan ( 'off' )
except TypeError :
pass
elif self . zijderveld_setting == "Pan" :
self . zijderveld_setting = "Zoom"
t... |
def get_map_data ( self ) :
"""Returns a serializable data set describing the map location""" | return { 'containerSelector' : '#' + self . get_map_element_id ( ) , 'center' : self . map_center_description , 'marker' : self . map_marker_description or self . map_center_description , 'zoom' : self . map_zoom , 'href' : self . get_map_href ( ) , 'key' : getattr ( settings , 'GOOGLE_MAPS_API_KEY' , '' ) , # Python '... |
def load_yaml_by_path ( cls , path , log_debug = False ) :
"""Load a yaml file that is at given path ,
if the path is not a string , it is assumed it ' s a file - like object""" | try :
if isinstance ( path , six . string_types ) :
return yaml . load ( open ( path , 'r' ) , Loader = Loader ) or { }
else :
return yaml . load ( path , Loader = Loader ) or { }
except ( yaml . scanner . ScannerError , yaml . parser . ParserError ) as e :
log_level = logging . DEBUG if log... |
def create_job_id ( self , data ) :
"""Create a new job id and reference ( refs / aetros / job / < id > ) by creating a new commit with empty tree . That
root commit is the actual job id . A reference is then created to the newest ( head ) commit of this commit history .
The reference will always be updated onc... | self . add_file ( 'aetros/job.json' , simplejson . dumps ( data , indent = 4 ) )
tree_id = self . write_tree ( )
self . job_id = self . command_exec ( [ 'commit-tree' , '-m' , "JOB_CREATED" , tree_id ] ) [ 0 ] . decode ( 'utf-8' ) . strip ( )
out , code , err = self . command_exec ( [ 'show-ref' , self . ref_head ] , a... |
def csl_styles ( ** kwargs ) :
'''Get list of styles from https : / / github . com / citation - style - language / styles
: param kwargs : any additional arguments will be passed on to ` requests . get `
: return : list , of CSL styles
Usage : :
from habanero import cn
cn . csl _ styles ( )''' | base = "https://api.github.com/repos/citation-style-language/styles"
tt = requests . get ( base + '/commits?per_page=1' , ** kwargs )
tt . raise_for_status ( )
check_json ( tt )
commres = tt . json ( )
sha = commres [ 0 ] [ 'sha' ]
sty = requests . get ( base + "/git/trees/" + sha , ** kwargs )
sty . raise_for_status (... |
def get_inner_text ( text , entities ) :
"""Gets the inner text that ' s surrounded by the given entities .
For instance : text = ' hey ! ' , entity = MessageEntityBold ( 2 , 2 ) - > ' y ! ' .
: param text : the original text .
: param entities : the entity or entities that must be matched .
: return : a si... | text = add_surrogate ( text )
result = [ ]
for e in entities :
start = e . offset
end = e . offset + e . length
result . append ( del_surrogate ( text [ start : end ] ) )
return result |
def isPe64 ( self ) :
"""Determines if the current L { PE } instance is a PE64 file .
@ rtype : bool
@ return : C { True } if the current L { PE } instance is a PE64 file . Otherwise , returns C { False } .""" | if self . ntHeaders . optionalHeader . magic . value == consts . PE64 :
return True
return False |
def mk_kwargs ( cls , kwargs ) :
"""Pop recognized arguments from a keyword list .""" | ret = { }
kws = [ 'row_factory' , 'body' , 'parent' ]
for k in kws :
if k in kwargs :
ret [ k ] = kwargs . pop ( k )
return ret |
def get_kde_home_dir ( ) :
"""Return KDE home directory or None if not found .""" | if os . environ . get ( "KDEHOME" ) :
kde_home = os . path . abspath ( os . environ [ "KDEHOME" ] )
else :
home = os . environ . get ( "HOME" )
if not home : # $ HOME is not set
return
kde3_home = os . path . join ( home , ".kde" )
kde4_home = os . path . join ( home , ".kde4" )
if fileu... |
def __find_smallest ( self ) :
"""Find the smallest uncovered value in the matrix .""" | minval = sys . maxsize
for i in range ( self . n ) :
for j in range ( self . n ) :
if ( not self . row_covered [ i ] ) and ( not self . col_covered [ j ] ) :
if minval > self . C [ i ] [ j ] :
minval = self . C [ i ] [ j ]
return minval |
def get_next_pid ( self , namespace = None , count = None ) :
"""Request next available pid or pids from Fedora , optionally in a specified
namespace . Calls : meth : ` ApiFacade . getNextPID ` .
. . deprecated : : 0.14
Mint pids for new objects with
: func : ` eulfedora . models . DigitalObject . get _ def... | # this method should no longer be needed - default pid logic moved to DigitalObject
warnings . warn ( """get_next_pid() method is deprecated; you should mint new pids via DigitalObject or ApiFacade.getNextPID() instead.""" , DeprecationWarning )
kwargs = { }
if namespace :
kwargs [ 'namespace' ] = namespace
elif se... |
def getiddfile ( versionid ) :
"""find the IDD file of the E + installation""" | vlist = versionid . split ( '.' )
if len ( vlist ) == 1 :
vlist = vlist + [ '0' , '0' ]
elif len ( vlist ) == 2 :
vlist = vlist + [ '0' ]
ver_str = '-' . join ( vlist )
eplus_exe , _ = eppy . runner . run_functions . install_paths ( ver_str )
eplusfolder = os . path . dirname ( eplus_exe )
iddfile = '{}/Energy+... |
def images ( self ) :
"""This method returns the listing image .
: return :""" | try :
uls = self . _ad_page_content . find ( "ul" , { "class" : "smi-gallery-list" } )
except Exception as e :
if self . _debug :
logging . error ( "Error getting images. Error message: " + e . args [ 0 ] )
return
images = [ ]
if uls is None :
return
for li in uls . find_all ( 'li' ) :
if li... |
def DefineStdSpectraForUnits ( ) :
"""Define ` ` StdSpectrum ` ` attribute for all the supported
: ref : ` pysynphot - flux - units ` .
This is automatically done on module import . The attribute
stores the source spectrum necessary for normalization in
the corresponding flux unit .
For ` ` photlam ` ` , ... | # Linear flux - density units
units . Flam . StdSpectrum = FlatSpectrum ( 1 , fluxunits = 'flam' )
units . Fnu . StdSpectrum = FlatSpectrum ( 1 , fluxunits = 'fnu' )
units . Photlam . StdSpectrum = FlatSpectrum ( 1 , fluxunits = 'photlam' )
units . Photnu . StdSpectrum = FlatSpectrum ( 1 , fluxunits = 'photnu' )
units ... |
def decrypt ( self , token , key , cek = None ) :
"""Decrypts a JWT
: param token : The JWT
: param key : A key to use for decrypting
: param cek : Ephemeral cipher key
: return : The decrypted message""" | if not isinstance ( token , JWEnc ) :
jwe = JWEnc ( ) . unpack ( token )
else :
jwe = token
self . jwt = jwe . encrypted_key ( )
jek = jwe . encrypted_key ( )
_decrypt = RSAEncrypter ( self . with_digest ) . decrypt
_alg = jwe . headers [ "alg" ]
if cek :
pass
elif _alg == "RSA-OAEP" :
cek = _decrypt ( ... |
def open_telemetry_logs ( logpath_telem , logpath_telem_raw ) :
'''open log files''' | if opts . append_log or opts . continue_mode :
mode = 'a'
else :
mode = 'w'
mpstate . logfile = open ( logpath_telem , mode = mode )
mpstate . logfile_raw = open ( logpath_telem_raw , mode = mode )
print ( "Log Directory: %s" % mpstate . status . logdir )
print ( "Telemetry log: %s" % logpath_telem )
# use a se... |
def resolvePrefix ( self , prefix , default = Namespace . default ) :
"""Resolve the specified prefix to a namespace . The I { nsprefixes } is
searched . If not found , it walks up the tree until either resolved or
the top of the tree is reached . Searching up the tree provides for
inherited mappings .
@ pa... | n = self
while n is not None :
if prefix in n . nsprefixes :
return ( prefix , n . nsprefixes [ prefix ] )
if prefix in self . specialprefixes :
return ( prefix , self . specialprefixes [ prefix ] )
n = n . parent
return default |
def get_thumbsdir ( self , path ) :
"""path :
path of the source image""" | # Thumbsdir could be a callable
# In that case , the path is built on the fly , based on the source path
thumbsdir = self . thumbsdir
if callable ( self . thumbsdir ) :
thumbsdir = self . thumbsdir ( path )
return thumbsdir |
def proccesser_markdown ( lowstate_item , config , ** kwargs ) :
'''Takes low state data and returns a dict of proccessed data
that is by default used in a jinja template when rendering a markdown highstate _ doc .
This ` lowstate _ item _ markdown ` given a lowstate item , returns a dict like :
. . code - bl... | # TODO : switch or . . . ext call .
s = lowstate_item
state_function = '{0}.{1}' . format ( s [ 'state' ] , s [ 'fun' ] )
id_full = '{0}: {1}' . format ( s [ 'state' ] , s [ '__id__' ] )
# TODO : use salt defined STATE _ REQUISITE _ IN _ KEYWORDS
requisites = ''
if s . get ( 'watch' ) :
requisites += 'run or update... |
def parse_tokens ( self , tokens ) :
"""Parse a sequence of tokens
returns tuple of ( parsed tokens , suggestions )""" | if len ( tokens ) == 1 :
return list ( ) , tokens , { "kubectl" : self . ast . help }
else :
tokens . reverse ( )
parsed , unparsed , suggestions = self . treewalk ( self . ast , parsed = list ( ) , unparsed = tokens )
if not suggestions and unparsed : # TODO : @ vogxn : This is hack until we include expected v... |
def read ( self , files = None ) :
"""Read settings from given config files .
@ raises : LinkCheckerError on syntax errors in the config file ( s )""" | if files is None :
cfiles = [ ]
else :
cfiles = files [ : ]
if not cfiles :
userconf = get_user_config ( )
if os . path . isfile ( userconf ) :
cfiles . append ( userconf )
# filter invalid files
filtered_cfiles = [ ]
for cfile in cfiles :
if not os . path . isfile ( cfile ) :
log . ... |
def reverse_char ( self , hints ) :
"""Return QuerySet of objects from SQLAlchemy of results .
Parameters
hints : list of str
strings to lookup
Returns
: class : ` sqlalchemy . orm . query . Query ` :
reverse matches""" | if isinstance ( hints , string_types ) :
hints = [ hints ]
Unihan = self . sql . base . classes . Unihan
columns = Unihan . __table__ . columns
return self . sql . session . query ( Unihan ) . filter ( or_ ( * [ column . contains ( hint ) for column in columns for hint in hints ] ) ) |
def equalize_adaptive_clahe ( image , ntiles = 8 , clip_limit = 0.01 ) :
"""Return contrast limited adaptive histogram equalized image .
The return value is normalised to the range 0 to 1.
: param image : numpy array or : class : ` jicimagelib . image . Image ` of dtype float
: param ntiles : number of tile r... | # Convert input for skimage .
skimage_float_im = normalise ( image )
if np . all ( skimage_float_im ) :
raise ( RuntimeError ( "Cannot equalise when there is no variation." ) )
normalised = skimage . exposure . equalize_adapthist ( skimage_float_im , ntiles_x = ntiles , ntiles_y = ntiles , clip_limit = clip_limit )... |
def command ( self , cmd , progress_hook = None , * args , ** kwargs ) :
"""Execute a model command .
: param cmd : Name of the command .
: param progress _ hook : A function to which progress updates are passed .""" | cmds = cmd . split ( None , 1 )
# split commands and simulations
sim_names = cmds [ 1 : ]
# simulations
if not sim_names :
sim_names = self . cmd_layer . reg . iterkeys ( )
for sim_name in sim_names :
sim_cmd = getattr ( self . cmd_layer . reg [ sim_name ] , cmd )
sim_cmd ( self , progress_hook = progress_h... |
def _trna_annotation ( data ) :
"""use tDRmapper to quantify tRNAs""" | trna_ref = op . join ( dd . get_srna_trna_file ( data ) )
name = dd . get_sample_name ( data )
work_dir = utils . safe_makedir ( os . path . join ( dd . get_work_dir ( data ) , "trna" , name ) )
in_file = op . basename ( data [ "clean_fastq" ] )
tdrmapper = os . path . join ( os . path . dirname ( sys . executable ) , ... |
def activate_ ( self , n_buffer , image_dimensions , shmem_name ) :
"""Shared mem info is given . Now we can create the shmem client""" | self . active = True
self . image_dimensions = image_dimensions
self . client = ShmemRGBClient ( name = shmem_name , n_ringbuffer = n_buffer , # size of ring buffer
width = image_dimensions [ 0 ] , height = image_dimensions [ 1 ] , # client timeouts if nothing has been received in 1000 milliseconds
mstimeout = 1000 , v... |
def show_minimum_needs_configuration ( self ) :
"""Show the minimum needs dialog .""" | # import here only so that it is AFTER i18n set up
from safe . gui . tools . minimum_needs . needs_manager_dialog import ( NeedsManagerDialog )
dialog = NeedsManagerDialog ( parent = self . iface . mainWindow ( ) , dock = self . dock_widget )
dialog . exec_ ( ) |
def reassign_ids ( doc , verbose = False ) :
"""Assign new IDs to all rows in all LSC tables in doc so that there
are no collisions when the LIGO _ LW elements are merged .""" | # Can ' t simply run reassign _ ids ( ) on doc because we need to
# construct a fresh old - - > new mapping within each LIGO _ LW block .
for n , elem in enumerate ( doc . childNodes ) :
if verbose :
print >> sys . stderr , "reassigning row IDs: %.1f%%\r" % ( 100.0 * ( n + 1 ) / len ( doc . childNodes ) ) ,... |
def add_unique_runid ( testcase , run_id = None ) :
"""Adds run id to the test description .
The ` run _ id ` runs makes the descriptions unique between imports and force Polarion
to update every testcase every time .""" | testcase [ "description" ] = '{}<br id="{}"/>' . format ( testcase . get ( "description" ) or "" , run_id or id ( add_unique_runid ) ) |
def read_handle ( url , cache = None , mode = "rb" ) :
"""Read from any URL with a file handle .
Use this to get a handle to a file rather than eagerly load the data :
with read _ handle ( url ) as handle :
result = something . load ( handle )
result . do _ something ( )
When program execution leaves this... | scheme = urlparse ( url ) . scheme
if cache == 'purge' :
_purge_cached ( url )
cache = None
if _is_remote ( scheme ) and cache is None :
cache = True
log . debug ( "Cache not specified, enabling because resource is remote." )
if cache :
handle = _read_and_cache ( url , mode = mode )
else :
if sc... |
def redo ( self ) :
"""Re - sync the change recorded in this trigger log .
Creates a ` ` NEW ` ` live trigger log from the data in this archived trigger log and sets
the state of this archived instance to ` ` REQUEUED ` ` .
. . seealso : : : meth : ` . TriggerLog . redo `
Returns :
The : class : ` . Trigg... | trigger_log = self . _to_live_trigger_log ( state = TRIGGER_LOG_STATE [ 'NEW' ] )
trigger_log . save ( force_insert = True )
# make sure we get a fresh row
self . state = TRIGGER_LOG_STATE [ 'REQUEUED' ]
self . save ( update_fields = [ 'state' ] )
return trigger_log |
def capture_termination_signal ( please_stop ) :
"""WILL SIGNAL please _ stop WHEN THIS AWS INSTANCE IS DUE FOR SHUTDOWN""" | def worker ( please_stop ) :
seen_problem = False
while not please_stop :
request_time = ( time . time ( ) - timer . START ) / 60
# MINUTES
try :
response = requests . get ( "http://169.254.169.254/latest/meta-data/spot/termination-time" )
seen_problem = False
... |
def _request_login ( self , method , ** kwargs ) :
"""Send a treq HTTP POST request to / ssllogin
: param method : treq method to use , for example " treq . post " or
" treq _ kerberos . post " .
: param kwargs : kwargs to pass to treq or treq _ kerberos , for example
" auth " or " agent " .
: returns : d... | url = self . url + '/ssllogin'
# Build the XML - RPC HTTP request body by hand and send it with
# treq .
factory = KojiQueryFactory ( path = None , host = None , method = 'sslLogin' )
payload = factory . payload
try :
response = yield method ( url , data = payload , ** kwargs )
except ResponseFailed as e :
fail... |
def get_control_connection_host ( self ) :
"""Returns the control connection host metadata .""" | connection = self . control_connection . _connection
endpoint = connection . endpoint if connection else None
return self . metadata . get_host ( endpoint ) if endpoint else None |
def drawFrom ( self , cumsum , r ) :
"""Draws a value from a cumulative sum .
Parameters :
cumsum : array
Cumulative sum from which shall be drawn .
Returns :
int : Index of the cumulative sum element drawn .""" | a = cumsum . rsplit ( )
if len ( a ) > 1 :
b = eval ( a [ 0 ] ) [ int ( a [ 1 ] ) ]
else :
b = eval ( a [ 0 ] )
return np . nonzero ( b >= r ) [ 0 ] [ 0 ] |
def get_ir_reciprocal_mesh ( mesh , cell , is_shift = None , is_time_reversal = True , symprec = 1e-5 , is_dense = False ) :
"""Return k - points mesh and k - point map to the irreducible k - points .
The symmetry is serched from the input cell .
Parameters
mesh : array _ like
Uniform sampling mesh numbers ... | _set_no_error ( )
lattice , positions , numbers , _ = _expand_cell ( cell )
if lattice is None :
return None
if is_dense :
dtype = 'uintp'
else :
dtype = 'intc'
grid_mapping_table = np . zeros ( np . prod ( mesh ) , dtype = dtype )
grid_address = np . zeros ( ( np . prod ( mesh ) , 3 ) , dtype = 'intc' )
if... |
def collect ( basepath , exclude = None , processPlugins = True ) :
"""Collects all the packages associated with the inputted filepath .
: param module | < module >
: return ( [ < str > pkg , . . ] , [ ( < str > path , < str > relpath ) , . . ] data )""" | if exclude is None :
exclude = [ '.py' , '.pyc' , '.pyo' , '.css' , '.exe' ]
imports = [ ]
datas = [ ]
# walk the folder structure looking for all packages and data files
basename = os . path . basename ( basepath )
basepath = os . path . abspath ( basepath )
baselen = len ( basepath ) - len ( basename )
plugfiles ... |
def convertToFree ( stream , length_limit = True ) :
"""Convert stream from fixed source form to free source form .""" | linestack = [ ]
for line in stream :
convline = FortranLine ( line , length_limit )
if convline . is_regular :
if convline . isContinuation and linestack :
linestack [ 0 ] . continueLine ( )
for l in linestack :
yield str ( l )
linestack = [ ]
linestack . appe... |
def determine_version ( self , request , api_version = None ) :
"""Determines the appropriate version given the set api _ version , the request header , and URL query params""" | if api_version is False :
api_version = None
for version in self . versions :
if version and "v{0}" . format ( version ) in request . path :
api_version = version
break
request_version = set ( )
if api_version is not None :
request_version . add ( api_version )
version_header... |
def cell_type_specificity ( ax ) :
'''make an imshow of the intranetwork connectivity''' | masked_array = np . ma . array ( params . T_yX , mask = params . T_yX == 0 )
# cmap = plt . get _ cmap ( ' hot ' , 20)
# cmap . set _ bad ( ' k ' , 0.5)
# im = ax . imshow ( masked _ array , cmap = cmap , vmin = 0 , interpolation = ' nearest ' )
im = ax . pcolormesh ( masked_array , cmap = cmap , vmin = 0 , )
# interpo... |
def get_argument_values ( type_def : Union [ GraphQLField , GraphQLDirective ] , node : Union [ FieldNode , DirectiveNode ] , variable_values : Dict [ str , Any ] = None , ) -> Dict [ str , Any ] :
"""Get coerced argument values based on provided definitions and nodes .
Prepares an dict of argument values given a... | coerced_values : Dict [ str , Any ] = { }
arg_defs = type_def . args
arg_nodes = node . arguments
if not arg_defs or arg_nodes is None :
return coerced_values
arg_node_map = { arg . name . value : arg for arg in arg_nodes }
for name , arg_def in arg_defs . items ( ) :
arg_type = arg_def . type
argument_node... |
def _parse_CHANLIMIT ( value ) :
"""> > > res = FeatureSet . _ parse _ CHANLIMIT ( ' ibe : 250 , xyz : 100 ' )
> > > len ( res )
> > > res [ ' x ' ]
100
> > > res [ ' i ' ] = = res [ ' b ' ] = = res [ ' e ' ] = = 250
True""" | pairs = map ( string_int_pair , value . split ( ',' ) )
return dict ( ( target , number ) for target_keys , number in pairs for target in target_keys ) |
def from_dict ( cls , d ) :
"""Reconstructs the SimplestChemenvStrategy object from a dict representation of the SimplestChemenvStrategy object
created using the as _ dict method .
: param d : dict representation of the SimplestChemenvStrategy object
: return : StructureEnvironments object""" | return cls ( distance_cutoff = d [ "distance_cutoff" ] , angle_cutoff = d [ "angle_cutoff" ] , additional_condition = d [ "additional_condition" ] , continuous_symmetry_measure_cutoff = d [ "continuous_symmetry_measure_cutoff" ] , symmetry_measure_type = d [ "symmetry_measure_type" ] ) |
def XOR ( classical_reg1 , classical_reg2 ) :
"""Produce an exclusive OR instruction .
: param classical _ reg1 : The first classical register , which gets modified .
: param classical _ reg2 : The second classical register or immediate value .
: return : A ClassicalOr instance .""" | left , right = unpack_reg_val_pair ( classical_reg1 , classical_reg2 )
return ClassicalExclusiveOr ( left , right ) |
def main ( ) :
'''monica helps you order food from the timeline''' | arguments = docopt ( __doc__ , version = __version__ )
if arguments [ 'configure' ] and flag :
configure ( )
if arguments [ 'cuisine' ] :
if arguments [ 'list' ] :
cuisine ( 'list' )
else :
cuisine ( arguments [ '<cuisine-id>' ] )
elif arguments [ 'surprise' ] :
surprise ( )
elif argumen... |
def register_optionables ( self , optionables ) :
"""Registers the given subsystem types .
: param optionables : The Optionable types to register .
: type optionables : : class : ` collections . Iterable ` containing
: class : ` pants . option . optionable . Optionable ` subclasses .""" | if not isinstance ( optionables , Iterable ) :
raise TypeError ( 'The optionables must be an iterable, given {}' . format ( optionables ) )
optionables = tuple ( optionables )
if not optionables :
return
invalid_optionables = [ s for s in optionables if not isinstance ( s , type ) or not issubclass ( s , Option... |
def hexstr ( text ) :
'''Ensure a string is valid hex .
Args :
text ( str ) : String to normalize .
Examples :
Norm a few strings :
hexstr ( ' 0xff00 ' )
hexstr ( ' ff00 ' )
Notes :
Will accept strings prefixed by ' 0x ' or ' 0X ' and remove them .
Returns :
str : Normalized hex string .''' | text = text . strip ( ) . lower ( )
if text . startswith ( ( '0x' , '0X' ) ) :
text = text [ 2 : ]
if not text :
raise s_exc . BadTypeValu ( valu = text , name = 'hexstr' , mesg = 'No string left after stripping' )
try : # checks for valid hex width and does character
# checking in C without using regex
s_c... |
def create_application ( self , team_id , name , url = None ) :
"""Creates an application under a given team .
: param team _ id : Team identifier .
: param name : The name of the new application being created .
: param url : The url of where the application is located .""" | params = { 'name' : name }
if url :
params [ 'url' ] = url
return self . _request ( 'POST' , 'rest/teams/' + str ( team_id ) + '/applications/new' , params ) |
def ExpandGroups ( path ) :
"""Performs group expansion on a given path .
For example , given path ` foo / { bar , baz } / { quux , norf } ` this method will yield
` foo / bar / quux ` , ` foo / bar / norf ` , ` foo / baz / quux ` , ` foo / baz / norf ` .
Args :
path : A path to expand .
Yields :
Paths ... | precondition . AssertType ( path , Text )
chunks = [ ]
offset = 0
for match in PATH_GROUP_REGEX . finditer ( path ) :
chunks . append ( [ path [ offset : match . start ( ) ] ] )
chunks . append ( match . group ( "alts" ) . split ( "," ) )
offset = match . end ( )
chunks . append ( [ path [ offset : ] ] )
fo... |
def tempfilename ( ** kwargs ) :
"""Reserve a temporary file for future use .
This is useful if you want to get a temporary file name , write to it in the
future and ensure that if an exception is thrown the temporary file is removed .""" | kwargs . update ( delete = False )
try :
f = NamedTemporaryFile ( ** kwargs )
f . close ( )
yield f . name
except Exception :
if os . path . exists ( f . name ) : # Ensure we clean up after ourself
os . unlink ( f . name )
raise |
def _is_pingable ( ip ) :
"""Checks whether an IP address is reachable by pinging .
Use linux utils to execute the ping ( ICMP ECHO ) command .
Sends 5 packets with an interval of 0.2 seconds and timeout of 1
seconds . Runtime error implies unreachability else IP is pingable .
: param ip : IP to check
: r... | ping_cmd = [ 'ping' , '-c' , '5' , '-W' , '1' , '-i' , '0.2' , ip ]
try :
linux_utils . execute ( ping_cmd , check_exit_code = True )
return True
except RuntimeError :
LOG . warning ( "Cannot ping ip address: %s" , ip )
return False |
def assign_properties ( thing ) :
"""Assign properties to an object .
When creating something via a post request ( e . g . a node ) , you can pass the
properties of the object in the request . This function gets those values
from the request and fills in the relevant columns of the table .""" | details = request_parameter ( parameter = "details" , optional = True )
if details :
setattr ( thing , "details" , loads ( details ) )
for p in range ( 5 ) :
property_name = "property" + str ( p + 1 )
property = request_parameter ( parameter = property_name , optional = True )
if property :
seta... |
def complete ( self ) :
"""Complete credentials are valid and are either two - legged or include a token .""" | return self . valid and ( self . access_token or self . refresh_token or self . type == 2 ) |
def calcinds ( data , threshold , ignoret = None ) :
"""Find indexes for data above ( or below ) given threshold .""" | inds = [ ]
for i in range ( len ( data [ 'time' ] ) ) :
snr = data [ 'snrs' ] [ i ]
time = data [ 'time' ] [ i ]
if ( threshold >= 0 and snr > threshold ) :
if ignoret :
incl = [ t0 for ( t0 , t1 ) in ignoret if np . round ( time ) . astype ( int ) in range ( t0 , t1 ) ]
logg... |
def tobam_cl ( data , out_file , is_paired = False ) :
"""Prepare command line for producing de - duplicated sorted output .
- If no deduplication , sort and prepare a BAM file .
- If paired , then use samblaster and prepare discordant outputs .
- If unpaired , use biobambam ' s bammarkduplicates""" | do_dedup = _check_dedup ( data )
umi_consensus = dd . get_umi_consensus ( data )
with file_transaction ( data , out_file ) as tx_out_file :
if not do_dedup :
yield ( sam_to_sortbam_cl ( data , tx_out_file ) , tx_out_file )
elif umi_consensus :
yield ( _sam_to_grouped_umi_cl ( data , umi_consensu... |
def igetattr ( self , name , context = None , class_context = True ) :
"""Infer the possible values of the given variable .
: param name : The name of the variable to infer .
: type name : str
: returns : The inferred possible values .
: rtype : iterable ( NodeNG or Uninferable )""" | # set lookup name since this is necessary to infer on import nodes for
# instance
context = contextmod . copy_context ( context )
context . lookupname = name
try :
attr = self . getattr ( name , context , class_context = class_context ) [ 0 ]
for inferred in bases . _infer_stmts ( [ attr ] , context , frame = s... |
def email ( self , to , msg ) :
"""Quickly send an email from a default address . Calls : py : meth : ` gmail _ email ` .
* * stored credential name : GMAIL _ EMAIL *
: param string to : The email address to send the email to .
: param msg : The content of the email . See : py : meth : ` gmail _ email ` .""" | logging . debug ( 'Emailing someone' )
return self . gmail_email ( self . _credentials [ 'GMAIL_EMAIL' ] , to , msg ) |
def build_subtree_strut ( self , result , * args , ** kwargs ) :
"""Returns a dictionary in form of
{ node : Resource , children : { node _ id : Resource } }
: param result :
: return :""" | items = list ( result )
root_elem = { "node" : None , "children" : OrderedDict ( ) }
if len ( items ) == 0 :
return root_elem
for _ , node in enumerate ( items ) :
new_elem = { "node" : node . Resource , "children" : OrderedDict ( ) }
path = list ( map ( int , node . path . split ( "/" ) ) )
parent_node... |
def read_hdf5_timeseries ( h5f , path = None , start = None , end = None , ** kwargs ) :
"""Read a ` TimeSeries ` from HDF5""" | # read data
kwargs . setdefault ( 'array_type' , TimeSeries )
series = read_hdf5_array ( h5f , path = path , ** kwargs )
# crop if needed
if start is not None or end is not None :
return series . crop ( start , end )
return series |
def evaluate_model_single_recording_preloaded ( preprocessing_queue , feature_list , model , output_semantics , recording , recording_id = None ) :
"""Evaluate a model for a single recording , after everything has been loaded .
Parameters
preprocessing _ queue : list
List of all preprocessing objects .
feat... | handwriting = handwritten_data . HandwrittenData ( recording , raw_data_id = recording_id )
handwriting . preprocessing ( preprocessing_queue )
x = handwriting . feature_extraction ( feature_list )
import nntoolkit . evaluate
model_output = nntoolkit . evaluate . get_model_output ( model , [ x ] )
return nntoolkit . ev... |
def output ( self , mode = 'file' , forced = False , context = None ) :
"""The general output method , override in subclass if you need to do
any custom modification . Calls other mode specific methods or simply
returns the content directly .""" | output = '\n' . join ( self . filter_input ( forced , context = context ) )
if not output :
return ''
if settings . COMPRESS_ENABLED or forced :
filtered_output = self . filter_output ( output )
return self . handle_output ( mode , filtered_output , forced )
return output |
def verify_telesign_callback_signature ( api_key , signature , json_str ) :
"""Verify that a callback was made by TeleSign and was not sent by a malicious client by verifying the signature .
: param api _ key : the TeleSign API api _ key associated with your account .
: param signature : the TeleSign Authorizat... | your_signature = b64encode ( HMAC ( b64decode ( api_key ) , json_str . encode ( "utf-8" ) , sha256 ) . digest ( ) ) . decode ( "utf-8" )
if len ( signature ) != len ( your_signature ) :
return False
# avoid timing attack with constant time equality check
signatures_equal = True
for x , y in zip ( signature , your_s... |
def arping ( net , timeout = 2 , cache = 0 , verbose = None , ** kargs ) :
"""Send ARP who - has requests to determine which hosts are up
arping ( net , [ cache = 0 , ] [ iface = conf . iface , ] [ verbose = conf . verb ] ) - > None
Set cache = True if you want arping to modify internal ARP - Cache""" | if verbose is None :
verbose = conf . verb
ans , unans = srp ( Ether ( dst = "ff:ff:ff:ff:ff:ff" ) / ARP ( pdst = net ) , verbose = verbose , filter = "arp and arp[7] = 2" , timeout = timeout , iface_hint = net , ** kargs )
ans = ARPingResult ( ans . res )
if cache and ans is not None :
for pair in ans :
... |
def calc_file_md5 ( filepath , chunk_size = None ) :
"""Calculate a file ' s md5 checksum . Use the specified chunk _ size for IO or the
default 256KB
: param filepath :
: param chunk _ size :
: return :""" | if chunk_size is None :
chunk_size = 256 * 1024
md5sum = hashlib . md5 ( )
with io . open ( filepath , 'r+b' ) as f :
datachunk = f . read ( chunk_size )
while datachunk is not None and len ( datachunk ) > 0 :
md5sum . update ( datachunk )
datachunk = f . read ( chunk_size )
return md5sum . ... |
def evpn_next_hop_unchanged ( self , ** kwargs ) :
"""Configure next hop unchanged for an EVPN neighbor .
You probably don ' t want this method . You probably want to configure
an EVPN neighbor using ` BGP . neighbor ` . That will configure next - hop
unchanged automatically .
Args :
ip _ addr ( str ) : I... | callback = kwargs . pop ( 'callback' , self . _callback )
args = dict ( rbridge_id = kwargs . pop ( 'rbridge_id' , '1' ) , evpn_neighbor_ipv4_address = kwargs . pop ( 'ip_addr' ) )
next_hop_unchanged = getattr ( self . _rbridge , 'rbridge_id_router_router_bgp_address_' 'family_l2vpn_evpn_neighbor_evpn_' 'neighbor_ipv4_... |
def make_dropdown_widget ( cls , description = 'Description' , options = [ 'Label 1' , 'Label 2' ] , value = 'Label 1' , file_path = None , layout = Layout ( ) , handler = None ) :
"Return a Dropdown widget with specified ` handler ` ." | dd = widgets . Dropdown ( description = description , options = options , value = value , layout = layout )
if file_path is not None :
dd . file_path = file_path
if handler is not None :
dd . observe ( handler , names = [ 'value' ] )
return dd |
def __get_timemachine ( self ) :
"""Return a TimeMachine for the object on which this action was
performed and at the time of this action .""" | if not self . __timemachine :
self . __timemachine = TimeMachine ( self . object_uid , step = self . id , )
return self . __timemachine . at ( self . id ) |
def write_line ( self , fix = True ) :
"""Output line containing values to console and csv file .
Only committed values are written to css file .
: param bool fix : to commit measurement values""" | cells = [ ]
csv_values = [ ]
for m in self . values ( ) :
cells . append ( m . render_value ( fix = fix ) )
if isinstance ( m , MultiMetric ) :
for sub in m . values ( ) :
csv_values . append ( sub . to_csv ( ) )
else :
csv_values . append ( m . to_csv ( ) )
if fix :
... |
def consume ( self , service_agreement_id , did , service_definition_id , consumer_account , destination , index = None ) :
"""Consume the asset data .
Using the service endpoint defined in the ddo ' s service pointed to by service _ definition _ id .
Consumer ' s permissions is checked implicitly by the secret... | ddo = self . resolve ( did )
if index is not None :
assert isinstance ( index , int ) , logger . error ( 'index has to be an integer.' )
assert index >= 0 , logger . error ( 'index has to be 0 or a positive integer.' )
return self . _asset_consumer . download ( service_agreement_id , service_definition_id , ddo... |
def parse_insert_metrics ( fn ) :
"""Parse the output from Picard ' s CollectInsertSizeMetrics and return as pandas
Series .
Parameters
filename : str of filename or file handle
Filename of the Picard output you want to parse .
Returns
metrics : pandas . Series
Insert size metrics .
hist : pandas . ... | with open ( fn ) as f :
lines = [ x . strip ( ) . split ( '\t' ) for x in f . readlines ( ) ]
index = lines [ 6 ]
vals = lines [ 7 ]
for i in range ( len ( index ) - len ( vals ) ) :
vals . append ( np . nan )
for i , v in enumerate ( vals ) :
if type ( v ) == str :
try :
vals [ i ] = in... |
def summary ( self , prn = None , lfilter = None ) :
"""prints a summary of each SndRcv packet pair
prn : function to apply to each packet pair instead of lambda s , r : " % s = = > % s " % ( s . summary ( ) , r . summary ( ) )
lfilter : truth function to apply to each packet pair to decide whether it will be d... | for s , r in self . res :
if lfilter is not None :
if not lfilter ( s , r ) :
continue
if prn is None :
print ( self . _elt2sum ( ( s , r ) ) )
else :
print ( prn ( s , r ) ) |
def checkForSave ( self ) :
"""Checks to see if the current document has been modified and should be saved .
: return < bool >""" | # if the file is not modified , then save is not needed
if ( not self . isModified ( ) ) :
return True
options = QMessageBox . Yes | QMessageBox . No | QMessageBox . Cancel
question = 'Would you like to save your changes to %s?' % self . windowTitle ( )
answer = QMessageBox . question ( None , 'Save Changes' , ques... |
def _phiforce ( self , R , phi = 0. , t = 0. ) :
"""NAME :
_ phiforce
PURPOSE :
evaluate the azimuthal force
INPUT :
phi
OUTPUT :
F _ phi ( R ( , \ phi , t ) )
HISTORY :
2016-06-02 - Written - Bovy ( UofT )""" | return self . _Pot . phiforce ( R , 0. , phi = phi , t = t , use_physical = False ) |
def inspect ( self ) :
"""Inspect access attempt , used for catpcha flow
: return :""" | last_attempt = self . get_last_failed_access_attempt ( ip_address = self . ip , captcha_enabled = True , captcha_passed = False , is_expired = False )
if last_attempt is None and not self . request . user . is_authenticated ( ) : # create a new entry
user_access = self . _FailedAccessAttemptModel ( ip_address = sel... |
def export_curves_stats ( self , aids , key ) :
""": returns : a dictionary rlzi - > record of dtype loss _ curve _ dt""" | oq = self . dstore [ 'oqparam' ]
stats = oq . hazard_stats ( ) . items ( )
# pair ( name , func )
stat2idx = { stat [ 0 ] : s for s , stat in enumerate ( stats ) }
if 'loss_curves-stats' in self . dstore : # classical _ risk
dset = self . dstore [ 'loss_curves-stats' ]
data = dset [ aids ]
# shape ( A , S )... |
def from_e164 ( text , origin = public_enum_domain ) :
"""Convert an E . 164 number in textual form into a Name object whose
value is the ENUM domain name for that number .
@ param text : an E . 164 number in textual form .
@ type text : str
@ param origin : The domain in which the number should be construc... | parts = [ d for d in text if d . isdigit ( ) ]
parts . reverse ( )
return dns . name . from_text ( '.' . join ( parts ) , origin = origin ) |
def crop_to_bounds ( self , val ) :
"""Return the given value cropped to be within the hard bounds
for this parameter .
If a numeric value is passed in , check it is within the hard
bounds . If it is larger than the high bound , return the high
bound . If it ' s smaller , return the low bound . In either ca... | # Currently , values outside the bounds are silently cropped to
# be inside the bounds ; it may be appropriate to add a warning
# in such cases .
if _is_number ( val ) :
if self . bounds is None :
return val
vmin , vmax = self . bounds
if vmin is not None :
if val < vmin :
return... |
def capture_event ( self , event , hint = None , scope = None ) : # type : ( Dict [ str , Any ] , Any , Scope ) - > Optional [ str ]
"""Captures an event .
This takes the ready made event and an optoinal hint and scope . The
hint is internally used to further customize the representation of the
error . When p... | if self . transport is None :
return None
if hint is None :
hint = { }
rv = event . get ( "event_id" )
if rv is None :
event [ "event_id" ] = rv = uuid . uuid4 ( ) . hex
if not self . _should_capture ( event , hint , scope ) :
return None
event = self . _prepare_event ( event , hint , scope )
# type : i... |
def get_interfaces ( self , socket_connection = None ) :
"""Returns the a list of Interface objects the service implements .""" | if not socket_connection :
socket_connection = self . open_connection ( )
close_socket = True
else :
close_socket = False
# noinspection PyUnresolvedReferences
_service = self . handler ( self . _interfaces [ "org.varlink.service" ] , socket_connection )
self . info = _service . GetInfo ( )
if close_socket ... |
def get_properties ( self ) :
"""Return the properties of this Configuration object .
The Dictionary object returned is a private copy for the caller and may
be changed without influencing the stored configuration .
If called just after the configuration is created and before update has
been called , this m... | with self . __lock :
if self . __deleted :
raise ValueError ( "{0} has been deleted" . format ( self . __pid ) )
elif not self . __updated : # Fresh configuration
return None
# Filter a copy of the properties
props = self . __properties . copy ( )
try :
del props [ services .... |
def pkill ( pattern , user = None , signal = 15 , full = False ) :
'''Kill processes matching a pattern .
. . code - block : : bash
salt ' * ' ps . pkill pattern [ user = username ] [ signal = signal _ number ] \ [ full = ( true | false ) ]
pattern
Pattern to search for in the process list .
user
Limit ... | killed = [ ]
for proc in psutil . process_iter ( ) :
name_match = pattern in ' ' . join ( _get_proc_cmdline ( proc ) ) if full else pattern in _get_proc_name ( proc )
user_match = True if user is None else user == _get_proc_username ( proc )
if name_match and user_match :
try :
proc . se... |
def from_hdf ( cls , fp , template_hash , root = None , load_to_memory = True , load_now = False ) :
"""Load a compressed waveform from the given hdf file handler .
The waveform is retrieved from :
` fp [ ' [ { root } / ] compressed _ waveforms / { template _ hash } / { param } ' ] ` ,
where ` param ` is the ... | if root is None :
root = ''
else :
root = '%s/' % ( root )
group = '%scompressed_waveforms/%s' % ( root , str ( template_hash ) )
fp_group = fp [ group ]
sample_points = fp_group [ 'sample_points' ]
amp = fp_group [ 'amplitude' ]
phase = fp_group [ 'phase' ]
if load_now :
sample_points = sample_points [ : ]... |
def replace ( self , refobj , reference , taskfileinfo ) :
"""Replace the given reference with the given taskfileinfo
: param refobj : the refobj that is linked to the reference
: param reference : the reference object . E . g . in Maya a reference node
: param taskfileinfo : the taskfileinfo that will replac... | jbfile = JB_File ( taskfileinfo )
filepath = jbfile . get_fullpath ( )
cmds . file ( filepath , loadReference = reference )
ns = cmds . referenceQuery ( reference , namespace = True )
# query the actual new namespace
content = cmds . namespaceInfo ( ns , listOnlyDependencyNodes = True , dagPath = True )
# get the conte... |
def create ( self , ** kwargs ) :
"""Creates a new statement matching the keyword arguments specified .
Returns the created statement .""" | Statement = self . get_model ( 'statement' )
if 'tags' in kwargs :
kwargs [ 'tags' ] = list ( set ( kwargs [ 'tags' ] ) )
if 'search_text' not in kwargs :
kwargs [ 'search_text' ] = self . tagger . get_bigram_pair_string ( kwargs [ 'text' ] )
if 'search_in_response_to' not in kwargs :
if kwargs . get ( 'in_... |
def get_last_components_by_type ( component_types , topic_id , db_conn = None ) :
"""For each component type of a topic , get the last one .""" | db_conn = db_conn or flask . g . db_conn
schedule_components_ids = [ ]
for ct in component_types :
where_clause = sql . and_ ( models . COMPONENTS . c . type == ct , models . COMPONENTS . c . topic_id == topic_id , models . COMPONENTS . c . export_control == True , models . COMPONENTS . c . state == 'active' )
... |
def assert_or_raise ( stmt : bool , exception : Exception , * exception_args , ** exception_kwargs ) -> None :
"""If the statement is false , raise the given exception .""" | if not stmt :
raise exception ( * exception_args , ** exception_kwargs ) |
def LSLS ( self , params ) :
"""LSLS [ Ra , ] Ra , Rc
LSLS [ Ra , ] Rb , # imm5
Logical shift left Rb by Rc or imm5 and store the result in Ra
imm5 is [ 0 , 31]
In the register shift , the first two operands must be the same register
Ra , Rb , and Rc must be low registers
If Ra is omitted , then it is a... | # This instruction allows for an optional destination register
# If it is omitted , then it is assumed to be Rb
# As defined in http : / / infocenter . arm . com / help / index . jsp ? topic = / com . arm . doc . dui0662b / index . html
try :
Ra , Rb , Rc = self . get_three_parameters ( self . THREE_PARAMETER_COMMA... |
def bus_factor ( self , ignore_globs = None , include_globs = None , by = 'projectd' ) :
"""An experimental heuristic for truck factor of a repository calculated by the current distribution of blame in
the repository ' s primary branch . The factor is the fewest number of contributors whose contributions make up ... | if by == 'file' :
raise NotImplementedError ( 'File-wise bus factor' )
elif by == 'projectd' :
blame = self . blame ( ignore_globs = ignore_globs , include_globs = include_globs , by = 'repository' )
blame = blame . sort_values ( by = [ 'loc' ] , ascending = False )
total = blame [ 'loc' ] . sum ( )
... |
def crc ( self ) :
"""A zlib . crc32 or zlib . adler32 checksum
of the current data .
Returns
crc : int , checksum from zlib . crc32 or zlib . adler32""" | if self . _modified_c or not hasattr ( self , '_hashed_crc' ) :
if self . flags [ 'C_CONTIGUOUS' ] :
self . _hashed_crc = crc32 ( self )
else : # the case where we have sliced our nice
# contiguous array into a non - contiguous block
# for example ( note slice * after * track operation ) :
#... |
def with_mfa ( self , mfa_token ) :
"""Set the MFA token for the next request .
` mfa _ token ` s are only good for one request . Use this method to chain into
the protected action you want to perform .
Note : Only useful for Application authentication .
Usage :
account . with _ mfa ( application . totp .... | if hasattr ( mfa_token , '__call__' ) : # callable ( ) is unsupported by 3.1 and 3.2
self . context . mfa_token = mfa_token . __call__ ( )
else :
self . context . mfa_token = mfa_token
return self |
def load_family_details ( self , pheno_covar ) :
"""Load family data updating the pheno _ covar with family ids found .
: param pheno _ covar : Phenotype / covariate object
: return : None""" | file = open ( self . fam_details )
header = file . readline ( )
format = file . readline ( )
self . file_index = 0
mask_components = [ ]
# 1s indicate an individual is to be masked out
for line in file :
words = line . strip ( ) . split ( )
indid = ":" . join ( words [ 0 : 2 ] )
if DataParser . valid_indid ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.