signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def means ( self ) :
"""_ MeanMeasure object providing access to means values .
None when the cube response does not contain a mean measure .""" | mean_measure_dict = ( self . _cube_dict . get ( "result" , { } ) . get ( "measures" , { } ) . get ( "mean" ) )
if mean_measure_dict is None :
return None
return _MeanMeasure ( self . _cube_dict , self . _all_dimensions ) |
def read_core_registers_raw ( self , reg_list ) :
"""Read one or more core registers
Read core registers in reg _ list and return a list of values .
If any register in reg _ list is a string , find the number
associated to this register in the lookup table CORE _ REGISTER .""" | # convert to index only
reg_list = [ register_name_to_index ( reg ) for reg in reg_list ]
# Sanity check register values
for reg in reg_list :
if reg not in CORE_REGISTER . values ( ) :
raise ValueError ( "unknown reg: %d" % reg )
elif is_fpu_register ( reg ) and ( not self . has_fpu ) :
raise V... |
def OpenMessageDialog ( self , Username , Text = u'' ) :
"""Opens " Send an IM Message " dialog .
: Parameters :
Username : str
Message target .
Text : unicode
Message text .""" | self . OpenDialog ( 'IM' , Username , tounicode ( Text ) ) |
def _generate_SAX ( self ) :
"""Generate SAX representation for all values of the time series .""" | sections = { }
self . value_min = self . time_series . min ( )
self . value_max = self . time_series . max ( )
# Break the whole value range into different sections .
section_height = ( self . value_max - self . value_min ) / self . precision
for section_number in range ( self . precision ) :
sections [ section_num... |
def get_nowait_from_queue ( queue ) :
"""Collect all immediately available items from a queue""" | data = [ ]
for _ in range ( queue . qsize ( ) ) :
try :
data . append ( queue . get_nowait ( ) )
except q . Empty :
break
return data |
def get_exp_of_biosample ( biosample_rec ) :
"""Determines whether the biosample is part of a ChipseqExperiment or SingleCellSorting
Experiment , and if so , returns the associated experiment as a models . Model instance that
is one of those two classes . The biosample is determined to be part of a ChipseqExper... | chip_exp_id = biosample_rec . chipseq_experiment_id
ssc_id = biosample_rec . sorting_biosample_single_cell_sorting_id
if chip_exp_id :
return { "type" : "chipseq_experiment" , "record" : models . ChipseqExperiment ( chip_exp_id ) }
elif ssc_id :
return { "type" : "single_cell_sorting" , "record" : models . Sing... |
def normalised_autocorrelation_function ( chain , index = 0 , burn = None , limit = None , fig = None , figsize = None ) :
"""Plot the autocorrelation function for each parameter of a sampler chain .
: param chain :
The sampled parameter values .
: type chain :
: class : ` numpy . ndarray `
: param index ... | factor = 2.0
lbdim = 0.2 * factor
trdim = 0.2 * factor
whspace = 0.10
dimy = lbdim + factor + trdim
dimx = lbdim + factor + trdim
if fig is None :
fig , ax = plt . subplots ( figsize = figsize )
else :
ax = fig . axes [ 0 ]
lm = lbdim / dimx
bm = lbdim / dimy
trm = ( lbdim + factor ) / dimy
fig . subplots_adjus... |
def do_load ( self , design , init = False ) : # type : ( str , bool ) - > None
"""Load a design name , running the child LoadHooks .
Args :
design : Name of the design json file , without extension
init : Passed to the LoadHook to tell the children if this is being
run at Init or not""" | if design :
filename = self . _validated_config_filename ( design )
with open ( filename , "r" ) as f :
text = f . read ( )
structure = json_decode ( text )
else :
structure = { }
# Attributes and Children used to be merged , support this
attributes = structure . get ( "attributes" , structure )... |
def gen_binder_url ( fpath , binder_conf , gallery_conf ) :
"""Generate a Binder URL according to the configuration in conf . py .
Parameters
fpath : str
The path to the ` . py ` file for which a Binder badge will be generated .
binder _ conf : dict or None
The Binder configuration dictionary . See ` gen ... | # Build the URL
fpath_prefix = binder_conf . get ( 'filepath_prefix' )
link_base = binder_conf . get ( 'notebooks_dir' )
# We want to keep the relative path to sub - folders
relative_link = os . path . relpath ( fpath , gallery_conf [ 'src_dir' ] )
path_link = os . path . join ( link_base , replace_py_ipynb ( relative_... |
def run_pyvcf ( args ) :
"""Main program entry point after parsing arguments""" | # open VCF reader
reader = vcf . Reader ( filename = args . input_vcf )
# optionally , open VCF writer
writer = None
# read through input VCF file , optionally also writing out
start = time . clock ( )
num = 0
for num , r in enumerate ( reader ) :
if num % 10000 == 0 :
print ( num , "" . join ( map ( str , ... |
def set_visible_func ( self , visible_func ) :
"""Set the function to decide visibility of an item
: param visible _ func : A callable that returns a boolean result to
decide if an item should be visible , for
example : :
def is _ visible ( item ) :
return True""" | self . model_filter . set_visible_func ( self . _internal_visible_func , visible_func , )
self . _visible_func = visible_func
self . model_filter . refilter ( ) |
def _set_remap ( self , v , load = False ) :
"""Setter method for remap , mapped from YANG variable / cee _ map / remap ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ remap is considered as a private
method . Backends looking to populate this variable s... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = remap . remap , is_container = 'container' , presence = False , yang_name = "remap" , rest_name = "remap" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extensi... |
def parse_result_format ( result_format ) :
"""This is a simple helper utility that can be used to parse a string result _ format into the dict format used
internally by great _ expectations . It is not necessary but allows shorthand for result _ format in cases where
there is no need to specify a custom partia... | if isinstance ( result_format , string_types ) :
result_format = { 'result_format' : result_format , 'partial_unexpected_count' : 20 }
else :
if 'partial_unexpected_count' not in result_format :
result_format [ 'partial_unexpected_count' ] = 20
return result_format |
def persist_one ( self , file_base64_content , filename , extension , mime , is_private = True ) :
"""Загружает файл в облако
: type origin : string Принимает значения ROBOT , USER""" | return self . __app . api_call ( "MediaService" , "persist_one" , locals ( ) , { } ) |
def parse_auth_response ( self , auth_response ) :
"""Parse the auth response and return the tenant , token , and username .
: param auth _ response : the full object returned from an auth call
: returns : ` ` dict ` `""" | auth_dict = dict ( )
auth_response = auth_response . json ( )
LOG . debug ( 'Authentication Response Body [ %s ]' , auth_response )
access = auth_response . get ( 'access' )
access_token = access . get ( 'token' )
access_tenant = access_token . get ( 'tenant' )
access_user = access . get ( 'user' )
auth_dict [ 'os_toke... |
def setSystemProperty ( cls , key , value ) :
"""Set a Java system property , such as spark . executor . memory . This must
must be invoked before instantiating SparkContext .""" | SparkContext . _ensure_initialized ( )
SparkContext . _jvm . java . lang . System . setProperty ( key , value ) |
def set_threshold_override ( self , service_name , limit_name , warn_percent = None , warn_count = None , crit_percent = None , crit_count = None ) :
"""Set a manual override on the threshold ( used for determining
warning / critical status ) for a specific limit . See
: py : class : ` ~ . AwsLimitChecker ` for... | self . services [ service_name ] . set_threshold_override ( limit_name , warn_percent = warn_percent , warn_count = warn_count , crit_percent = crit_percent , crit_count = crit_count ) |
def ConsultarRemito ( self , cod_remito = None , id_req = None , tipo_comprobante = None , punto_emision = None , nro_comprobante = None ) :
"Obtener los datos de un remito generado" | print ( self . client . help ( "consultarRemito" ) )
response = self . client . consultarRemito ( authRequest = { 'token' : self . Token , 'sign' : self . Sign , 'cuitRepresentada' : self . Cuit } , codRemito = cod_remito , idReq = id_req , tipoComprobante = tipo_comprobante , puntoEmision = punto_emision , nroComproba... |
def filedata ( self ) :
"""Property providing access to the : class : ` . FileDataAPI `""" | if self . _filedata_api is None :
self . _filedata_api = self . get_filedata_api ( )
return self . _filedata_api |
def PROFILE_DOPPLER ( sg0 , GamD , sg ) :
"""# Doppler profile .
# Input parameters :
# sg0 : Unperturbed line position in cm - 1 ( Input ) .
# GamD : Doppler HWHM in cm - 1 ( Input )
# sg : Current WaveNumber of the Computation in cm - 1 ( Input ) .""" | return cSqrtLn2divSqrtPi * exp ( - cLn2 * ( ( sg - sg0 ) / GamD ) ** 2 ) / GamD |
def getAttrib ( self , attribId ) :
"""return the requested attribute
@ param attribId : attribute id like SCARD _ ATTR _ VENDOR _ NAME""" | Observable . setChanged ( self )
Observable . notifyObservers ( self , CardConnectionEvent ( 'attrib' , [ attribId ] ) )
data = self . doGetAttrib ( attribId )
if self . errorcheckingchain is not None :
self . errorcheckingchain [ 0 ] ( data )
return data |
def _format_strings ( self ) :
"""we by definition have DO NOT have a TZ""" | values = self . values
return [ val . strftime ( '%Y-%m-%d %H:%M:%S' ) if val is not None else self . nat_rep for val in values ] |
def received_sig_option_changed ( self , option , value ) :
"""Called when sig _ option _ changed is received .
If option being changed is autosave _ mapping , then synchronize new
mapping with all editor stacks except the sender .""" | if option == 'autosave_mapping' :
for editorstack in self . editorstacks :
if editorstack != self . sender ( ) :
editorstack . autosave_mapping = value
self . sig_option_changed . emit ( option , value ) |
def quic_graph_lasso ( X , num_folds , metric ) :
"""Run QuicGraphicalLasso with mode = ' default ' and use standard scikit
GridSearchCV to find the best lambda .
Primarily demonstrates compatibility with existing scikit tooling .""" | print ( "QuicGraphicalLasso + GridSearchCV with:" )
print ( " metric: {}" . format ( metric ) )
search_grid = { "lam" : np . logspace ( np . log10 ( 0.01 ) , np . log10 ( 1.0 ) , num = 100 , endpoint = True ) , "init_method" : [ "cov" ] , "score_metric" : [ metric ] , }
model = GridSearchCV ( QuicGraphicalLasso ( ) ,... |
def _dict_of_results ( self ) :
"""Get the dictionary representation of results
: return : dict ( str - > dict ( str - > str ) )""" | result_json = { }
result_list = [ ]
for r in self . results :
result_list . append ( { 'name' : r . check_name , 'ok' : r . ok , 'status' : r . status , 'description' : r . description , 'message' : r . message , 'reference_url' : r . reference_url , 'logs' : r . logs , } )
result_json [ "checks" ] = result_list
re... |
def engage ( self , height ) :
"""Move the magnet to a specific height , in mm from home position""" | if height > MAX_ENGAGE_HEIGHT or height < 0 :
raise ValueError ( 'Invalid engage height. Should be 0 to {}' . format ( MAX_ENGAGE_HEIGHT ) )
self . _driver . move ( height )
self . _engaged = True |
def board_name ( default ) :
"""Returns the boards name ( if available ) .""" | try :
import board
try :
name = board . name
except AttributeError : # There was a board . py file , but it didn ' t have an name attribute
# We also ignore this as an error
name = default
except ImportError : # No board . py file on the pyboard - not an error
name = default
except B... |
def logger_add ( self , loggerclass ) :
"""Add a new logger type to the known loggers .""" | self . loggers [ loggerclass . LoggerName ] = loggerclass
self [ loggerclass . LoggerName ] = { } |
def find_known_dependencies ( self , requirement ) :
"""Find the known dependencies of a Python package .
: param requirement : A : class : ` . Requirement ` object .
: returns : A list of strings with system package names .""" | logger . info ( "Checking for known dependencies of %s .." , requirement . name )
known_dependencies = sorted ( self . dependencies . get ( requirement . name . lower ( ) , [ ] ) )
if known_dependencies :
logger . info ( "Found %s: %s" , pluralize ( len ( known_dependencies ) , "known dependency" , "known dependenc... |
def _get_template_name ( self ) :
'''Find template name .
: returns : string of template name
: raises : NonextantTemplateNameException''' | start_pattern = r"sys application template\s+" r"(\/[\w\.\-]+\/)?" r"(?P<name>[\w\.\-]+)\s*\{"
template_start = re . search ( start_pattern , self . template_str )
if template_start :
return template_start . group ( 'name' )
raise NonextantTemplateNameException ( 'Template name not found.' ) |
def calculate_backend ( name_from_env , backends = None ) :
"""Calculates which backend to use with the following algorithm :
- Try to read the GOLESS _ BACKEND environment variable .
Usually ' gevent ' or ' stackless ' .
If a value is set but no backend is available or it fails to be created ,
this functio... | if backends is None :
backends = _default_backends
if name_from_env :
if name_from_env not in backends :
raise RuntimeError ( 'Invalid backend %r specified. Valid backends are: %s' % ( name_from_env , _default_backends . keys ( ) ) )
# Allow this to raise , since it was explicitly set from the envir... |
def RLS ( anchors , W , r , print_out = False , grid = None , num_points = 10 ) :
"""Range least squares ( RLS ) using grid search .
Algorithm written by A . Beck , P . Stoica in " Approximate and Exact solutions of Source Localization Problems " .
: param anchors : anchor points
: param r2 : squared distance... | def cost_function ( arr ) :
X = np . c_ [ arr ]
r_measured = np . linalg . norm ( anchors - X )
mse = np . linalg . norm ( r_measured - r ) ** 2
return mse
if grid is None :
grid = [ np . min ( anchors , axis = 0 ) , np . max ( anchors , axis = 0 ) ]
d = anchors . shape [ 1 ]
x = np . linspace ( gri... |
def ConnectTo ( self , appName , data = None ) :
"""Exceptional error is handled in zdde Init ( ) method , so the exception
must be re - raised""" | global number_of_apps_communicating
self . ddeServerName = appName
try :
self . ddec = DDEClient ( self . ddeServerName , self . ddeClientName )
# establish conversation
except DDEError :
raise
else :
number_of_apps_communicating += 1 |
def set_mode ( self , mode ) :
'''Set the global mode of the rejester system .
This must be one of the constants : attr : ` TERMINATE ` ,
: attr : ` RUN ` , or : attr : ` IDLE ` . : attr : ` TERMINATE ` instructs any
running workers to do an orderly shutdown , completing current
jobs then exiting . : attr :... | if mode not in [ self . TERMINATE , self . RUN , self . IDLE ] :
raise ProgrammerError ( 'mode=%r is not recognized' % mode )
with self . registry . lock ( identifier = self . worker_id ) as session :
session . set ( 'modes' , 'mode' , mode )
logger . info ( 'set mode to %s' , mode ) |
def transform_array ( rot_mtx , vec_array ) :
'''transform _ array ( matrix , vector _ array ) - > vector _ array''' | return map ( lambda x , m = rot_mtx : transform ( m , x ) , vec_array ) |
def cache_context ( self , context ) :
'''Cache the given context to disk''' | if not os . path . isdir ( os . path . dirname ( self . cache_path ) ) :
os . mkdir ( os . path . dirname ( self . cache_path ) )
with salt . utils . files . fopen ( self . cache_path , 'w+b' ) as cache :
self . serial . dump ( context , cache ) |
async def UserCredentials ( self , user_clouds ) :
'''user _ clouds : typing . Sequence [ ~ UserCloud ]
Returns - > typing . Sequence [ ~ StringsResult ]''' | # map input types to rpc msg
_params = dict ( )
msg = dict ( type = 'Cloud' , request = 'UserCredentials' , version = 3 , params = _params )
_params [ 'user-clouds' ] = user_clouds
reply = await self . rpc ( msg )
return reply |
def add_user_to_group ( group , role , email ) :
"""Add a user to a group the caller owns
Args :
group ( str ) : Group name
role ( str ) : Role of user for group ; either ' member ' or ' admin '
email ( str ) : Email of user or group to add
Swagger :
https : / / api . firecloud . org / # ! / Groups / ad... | uri = "groups/{0}/{1}/{2}" . format ( group , role , email )
return __put ( uri ) |
def get ( self , key , default = None ) :
"""Get a value from the dictionary .
Args :
key ( str ) : The dictionary key .
default ( any ) : The default to return if the key is not in the
dictionary . Defaults to None .
Returns :
str or any : The dictionary value or the default if the key is not
in the ... | retval = self . __getitem__ ( key )
if not retval :
retval = default
return retval |
def _infer_shape ( self , dimensions ) :
"""Replaces the - 1 wildcard in the output shape vector .
This function infers the correct output shape given the input dimensions .
Args :
dimensions : List of input non - batch dimensions .
Returns :
Tuple of non - batch output dimensions .""" | # Size of input
n = np . prod ( dimensions )
# Size of output where defined
m = np . prod ( abs ( np . array ( self . _shape ) ) )
# Replace wildcard
v = np . array ( self . _shape )
v [ v == - 1 ] = n // m
return tuple ( v ) |
def cmd_posvel ( self , args ) :
'''posvel mapclick vN vE vD''' | ignoremask = 511
latlon = None
try :
latlon = self . module ( 'map' ) . click_position
except Exception :
pass
if latlon is None :
print ( "set latlon to zeros" )
latlon = [ 0 , 0 ]
else :
ignoremask = ignoremask & 504
print ( "found latlon" , ignoremask )
vN = 0
vE = 0
vD = 0
if ( len ( args ) ... |
def disconnect_all ( self ) :
"""Disconnect all nodes
: return :""" | rhs = 'b:' + self . definition [ 'node_class' ] . __label__
rel = _rel_helper ( lhs = 'a' , rhs = rhs , ident = 'r' , ** self . definition )
q = 'MATCH (a) WHERE id(a)={self} MATCH ' + rel + ' DELETE r'
self . source . cypher ( q ) |
def congestionControl ( Cause_presence = 0 ) :
"""CONGESTION CONTROL Section 9.3.4""" | a = TpPd ( pd = 0x3 )
b = MessageType ( mesType = 0x39 )
# 00111001
c = CongestionLevelAndSpareHalfOctets ( )
packet = a / b / c
if Cause_presence is 1 :
e = CauseHdr ( ieiC = 0x08 , eightBitC = 0x0 )
packet = packet / e
return packet |
def write ( self , s ) :
"""Process text , writing it to the virtual screen while handling
ANSI escape codes .""" | if isinstance ( s , bytes ) :
s = self . _decode ( s )
for c in s :
self . process ( c ) |
def setIfMissing ( self , key , value ) :
"""Set a configuration property , if not already set .""" | if self . get ( key ) is None :
self . set ( key , value )
return self |
def _calculate_checksum ( value ) :
"""4.12 Checksum Calculation from an unsigned short input""" | # CRC
polynomial = 0x131
# / / P ( x ) = x ^ 8 + x ^ 5 + x ^ 4 + 1 = 100110001
crc = 0xFF
# calculates 8 - Bit checksum with given polynomial
for byteCtr in [ ord ( x ) for x in struct . pack ( ">H" , value ) ] :
crc ^= byteCtr
for bit in range ( 8 , 0 , - 1 ) :
if crc & 0x80 :
crc = ( crc <... |
def _calculate_eltorito_boot_info_table_csum ( self , data_fp , data_len ) : # type : ( BinaryIO , int ) - > int
'''An internal method to calculate the checksum for an El Torito Boot Info
Table . This checksum is a simple 32 - bit checksum over all of the data
in the boot file , starting right after the Boot In... | # Here we want to read the boot file so we can calculate the checksum
# over it .
num_sectors = utils . ceiling_div ( data_len , self . pvd . logical_block_size ( ) )
csum = 0
curr_sector = 0
while curr_sector < num_sectors :
block = data_fp . read ( self . pvd . logical_block_size ( ) )
block = block . ljust (... |
def parsemsg ( s ) : # stolen from twisted . words
"""Breaks a message from an IRC server into its prefix , command , and arguments .""" | prefix = ''
trailing = [ ]
if not s :
raise Exception ( "Empty line." )
if s [ 0 ] == ':' :
prefix , s = s [ 1 : ] . split ( ' ' , 1 )
if s . find ( ' :' ) != - 1 :
s , trailing = s . split ( ' :' , 1 )
args = s . split ( )
args . append ( trailing )
else :
args = s . split ( )
command = args . ... |
def command_list_arscons ( self ) :
'''command line as list''' | cmd = [ ]
cmd += [ 'scons' ]
if self . arduino_home :
cmd += [ 'ARDUINO_HOME=' + self . arduino_home ]
# if os . environ . get ( ' ARDUINO _ HOME ' , None ) :
# cmd + = [ ' ARDUINO _ HOME = ' + os . environ . get ( ' ARDUINO _ HOME ' ) ]
if self . avr_home :
cmd += [ 'AVR_HOME=' + self . avr_home ]
if self . bo... |
def months_between ( date1 , date2 , roundOff = True ) :
"""Returns number of months between dates date1 and date2.
If date1 is later than date2 , then the result is positive .
If date1 and date2 are on the same day of month , or both are the last day of month ,
returns an integer ( time of day will be ignore... | sc = SparkContext . _active_spark_context
return Column ( sc . _jvm . functions . months_between ( _to_java_column ( date1 ) , _to_java_column ( date2 ) , roundOff ) ) |
def _tumor_normal_stats ( rec , somatic_info , vcf_rec ) :
"""Retrieve depth and frequency of tumor and normal samples .""" | out = { "normal" : { "alt" : None , "depth" : None , "freq" : None } , "tumor" : { "alt" : 0 , "depth" : 0 , "freq" : None } }
if hasattr ( vcf_rec , "samples" ) :
samples = [ ( s , { } ) for s in vcf_rec . samples ]
for fkey in [ "AD" , "AO" , "RO" , "AF" , "DP" ] :
try :
for i , v in enume... |
def open ( name ) :
"""name : str or file or file - like or pathlib . Path
File to be opened""" | with builtins . open ( name , mode = 'r' ) as fd :
data = json . load ( fd )
return loads ( data ) |
def _purge ( self ) :
"""Trim the cache down to max _ size by evicting the
least - recently - used entries .""" | if len ( self . cache ) <= self . max_size :
return
cache = self . cache
refcount = self . refcount
queue = self . queue
max_size = self . max_size
# purge least recently used entries , using refcount to count entries
# that appear multiple times in the queue
while len ( cache ) > max_size :
refc = 1
while ... |
def form_valid ( self , form ) :
"""If the request is ajax , save the form and return a json response .
Otherwise return super as expected .""" | self . object = form . save ( commit = False )
self . pre_save ( )
self . object . save ( )
if hasattr ( form , 'save_m2m' ) :
form . save_m2m ( )
self . post_save ( )
if self . request . is_ajax ( ) :
return self . render_json_response ( self . get_success_result ( ) )
return HttpResponseRedirect ( self . get_... |
def OnMacroToolbarToggle ( self , event ) :
"""Macro toolbar toggle event handler""" | self . main_window . macro_toolbar . SetGripperVisible ( True )
macro_toolbar_info = self . main_window . _mgr . GetPane ( "macro_toolbar" )
self . _toggle_pane ( macro_toolbar_info )
event . Skip ( ) |
def set_mt_wcs ( self , image ) :
"""Reset the WCS for this image based on the WCS information from
another imageObject .""" | for chip in range ( 1 , self . _numchips + 1 , 1 ) :
sci_chip = self . _image [ self . scienceExt , chip ]
ref_chip = image . _image [ image . scienceExt , chip ]
# Do we want to keep track of original WCS or not ? No reason now . . .
sci_chip . wcs = ref_chip . wcs . copy ( ) |
def get_usb_controller_count_by_type ( self , type_p ) :
"""Returns the number of USB controllers of the given type attached to the VM .
in type _ p of type : class : ` USBControllerType `
return controllers of type int""" | if not isinstance ( type_p , USBControllerType ) :
raise TypeError ( "type_p can only be an instance of type USBControllerType" )
controllers = self . _call ( "getUSBControllerCountByType" , in_p = [ type_p ] )
return controllers |
def xfrange ( start , stop = None , step = 1 ) :
"""Iterate through an arithmetic progression .
: param start : Starting number .
: type start : float , int , long
: param stop : Stopping number .
: type stop : float , int , long
: param step : Stepping size .
: type step : float , int , long""" | if stop is None :
stop = start
start = 0.0
start = float ( start )
while start < stop :
yield start
start += step |
def flatten_top_level_keys ( data , top_level_keys ) :
"""Helper method to flatten a nested dict of dicts ( one level )
Example :
{ ' a ' : { ' b ' : ' bbb ' } } becomes { ' a _ - _ b ' : ' bbb ' }
The separator ' _ - _ ' gets formatted later for the column headers
Args :
data : the dict to flatten
top ... | flattened_data = { }
for top_level_key in top_level_keys :
if data [ top_level_key ] is None :
flattened_data [ top_level_key ] = None
else :
for key in data [ top_level_key ] :
flattened_data [ '{}_-_{}' . format ( top_level_key , key ) ] = data [ top_level_key ] [ key ]
return flat... |
def sample ( self , qubits : List [ ops . Qid ] , repetitions : int = 1 ) -> np . ndarray :
"""Samples from the system at this point in the computation .
Note that this does not collapse the wave function .
Args :
qubits : The qubits to be sampled in an order that influence the
returned measurement results ... | raise NotImplementedError ( ) |
def redirect_stream ( system , target ) :
"""Redirect Unix streams
If None , redirect Stream to / dev / null , else redirect to target .
: param system : ether sys . stdin , sys . stdout , or sys . stderr
: type system : file object
: param target : File like object , or None
: type target : None , File O... | if target is None :
target_fd = os . open ( os . devnull , os . O_RDWR )
else :
target_fd = target . fileno ( )
try :
os . dup2 ( target_fd , system . fileno ( ) )
except OSError as err :
raise DaemonError ( 'Could not redirect {0} to {1}: {2}' . format ( system , target , err ) ) |
def list_build_configuration_set_records ( page_size = 200 , page_index = 0 , sort = "" , q = "" ) :
"""List all build configuration set records .""" | data = list_build_configuration_set_records_raw ( page_size , page_index , sort , q )
if data :
return utils . format_json_list ( data ) |
def num_failures ( self ) :
"""Return the number of failures in the window .""" | min_time = time . time ( ) - self . window
while self . failures and self . failures [ 0 ] < min_time :
self . failures . popleft ( )
return len ( self . failures ) |
def every_other ( x , name = None ) :
"""Drops every other value from the tensor and returns a 1D tensor .
This is useful if you are running multiple inputs through a model tower
before splitting them and you want to line it up with some other data .
Args :
x : the target tensor .
name : the name for this... | with tf . name_scope ( name , 'every_other' , [ x ] ) as scope :
x = tf . convert_to_tensor ( x , name = 'x' )
return tf . reshape ( tf . slice ( tf . reshape ( x , [ - 1 , 2 ] ) , [ 0 , 0 ] , [ - 1 , 1 ] ) , [ - 1 ] , name = scope ) |
def get_storage ( self , contract_hash , storage_key , id = None , endpoint = None ) :
"""Returns a storage item of a specified contract
Args :
contract _ hash : ( str ) hash of the contract to lookup , for example ' d7678dd97c000be3f33e9362e673101bac4ca654'
storage _ key : ( str ) storage key to lookup , for... | result = self . _call_endpoint ( GET_STORAGE , params = [ contract_hash , binascii . hexlify ( storage_key . encode ( 'utf-8' ) ) . decode ( 'utf-8' ) ] , id = id , endpoint = endpoint )
try :
return bytearray ( binascii . unhexlify ( result . encode ( 'utf-8' ) ) )
except Exception as e :
raise NEORPCException... |
def tkr_vox2ras ( img , zooms = None ) :
'''tkr _ vox2ras ( img ) yields the FreeSurfer tkr VOX2RAS matrix for the given nibabel image object
img . The img must have a get _ shape ( ) method and header member with a get _ zooms ( ) method .
tkr _ vox2ras ( hdr ) operates on a nibabel image header object .
tkr... | if zooms is not None : # let ' s assume that they passed shape , zooms
shape = img
else :
try :
img = img . header
except Exception :
pass
try :
( shape , zooms ) = ( img . get_data_shape ( ) , img . get_zooms ( ) )
except Exception :
raise ValueError ( 'single argume... |
def compile_update ( self , query , values ) :
"""Compile an update statement into SQL
: param query : A QueryBuilder instance
: type query : QueryBuilder
: param values : The update values
: type values : dict
: return : The compiled update
: rtype : str""" | sql = super ( MySqlQueryGrammar , self ) . compile_update ( query , values )
if query . orders :
sql += ' %s' % self . _compile_orders ( query , query . orders )
if query . limit_ :
sql += ' %s' % self . _compile_limit ( query , query . limit_ )
return sql . rstrip ( ) |
def setViewMode ( self , viewMode ) :
"""Sets the view mode for this widget to the inputed mode .
: param viewMode | < QListWidget . ViewMode >""" | ddrop_mode = self . dragDropMode ( )
super ( XMultiTagEdit , self ) . setViewMode ( viewMode )
self . setDragDropMode ( ddrop_mode ) |
def open ( self ) :
"""Open the device .""" | self . _serial . port = self . _port
self . _serial . baudrate = self . _baud
self . _serial . timeout = self . _timeout
self . _serial . open ( )
self . _serial . flushInput ( )
self . _serial . flushOutput ( ) |
def recv ( self , packet , interface ) :
"""run incoming packet through the filters , then place it in its inq""" | # the packet is piped into the first filter , then the result of that into the second filter , etc .
for f in self . filters :
if not packet :
break
packet = f . tr ( packet , interface )
if packet : # if the packet wasn ' t dropped by a filter , log the recv and place it in the interface ' s inq
# self... |
def augment_tensor ( matrix , ndim = None ) :
"""Increase the dimensionality of a tensor ,
splicing it into an identity matrix of a higher
dimension . Useful for generalizing
transformation matrices .""" | s = matrix . shape
if ndim is None :
ndim = s [ 0 ] + 1
arr = N . identity ( ndim )
arr [ : s [ 0 ] , : s [ 1 ] ] = matrix
return arr |
def read_raw_data ( self , f ) :
"""Read signal data from file""" | if not self . toc [ "kTocRawData" ] :
return
f . seek ( self . data_position )
total_data_size = self . next_segment_offset - self . raw_data_offset
log . debug ( "Reading %d bytes of data at %d in %d chunks" % ( total_data_size , f . tell ( ) , self . num_chunks ) )
for chunk in range ( self . num_chunks ) :
i... |
def _request_next_buffer ( self ) :
"""Request next buffer .
Requires self . _ offset and self . _ buffer are in consistent state .""" | self . _buffer_future = None
next_offset = self . _offset + self . _buffer . remaining ( )
if next_offset != self . _file_size :
self . _buffer_future = self . _get_segment ( next_offset , self . _buffer_size ) |
def get_title ( self , entry ) :
"""Return the title with word count and number of comments .""" | title = _ ( '%(title)s (%(word_count)i words)' ) % { 'title' : entry . title , 'word_count' : entry . word_count }
reaction_count = int ( entry . comment_count + entry . pingback_count + entry . trackback_count )
if reaction_count :
return ungettext_lazy ( '%(title)s (%(reactions)i reaction)' , '%(title)s (%(reacti... |
def calc_signal_spatial ( self ) :
"""Calculate the spatial signal probability for each catalog object .
Parameters :
None
Returns :
u _ spatial : array of spatial probabilities per object""" | # Calculate the surface intensity
self . surface_intensity_sparse = self . calc_surface_intensity ( )
# Calculate the probability per object - by - object level
self . surface_intensity_object = self . kernel . pdf ( self . catalog . lon , self . catalog . lat )
# Spatial component of signal probability
u_spatial = sel... |
def _request ( self , process = None , wait = None ) :
"""helper for building pvRequests
: param str process : Control remote processing . May be ' true ' , ' false ' , ' passive ' , or None .
: param bool wait : Wait for all server processing to complete .""" | opts = [ ]
if process is not None :
opts . append ( 'process=%s' % process )
if wait is not None :
if wait :
opts . append ( 'wait=true' )
else :
opts . append ( 'wait=false' )
return 'field()record[%s]' % ( ',' . join ( opts ) ) |
def no ( mytype , argnums = ( 1 , ) ) :
"""A shortcut for the disallow _ types decorator that disallows only one type
( in any position in argnums ) .
Example use :
> > > class newstr ( object ) :
. . . @ no ( ' bytes ' )
. . . def _ _ add _ _ ( self , other ) :
. . . pass
> > > newstr ( u ' 1234 ' ) ... | if isinstance ( argnums , Integral ) :
argnums = ( argnums , )
disallowed_types = [ mytype ] * len ( argnums )
return disallow_types ( argnums , disallowed_types ) |
def slugify ( string , repchar = '_' ) :
"""replaces all non - alphanumeric chars in the string with the given repchar .
: param string : the source string
: param repchar :""" | slug_regex = re . compile ( r'(^[{0}._-]+|[^a-z-A-Z0-9_.-]+|[{0}._-]+$)' . format ( repchar ) )
strip_regex = re . compile ( r'[{0}._-]+' . format ( repchar ) )
transformations = [ lambda x : slug_regex . sub ( repchar , x ) , lambda x : strip_regex . sub ( repchar , x ) , lambda x : x . strip ( repchar ) , lambda x : ... |
def get_institute_trend_graph_url ( institute , start , end ) :
"""Institute trend graph for machine category .""" | filename = get_institute_trend_graph_filename ( institute , start , end )
urls = { 'graph_url' : urlparse . urljoin ( GRAPH_URL , filename + ".png" ) , 'data_url' : urlparse . urljoin ( GRAPH_URL , filename + ".csv" ) , }
return urls |
def convert_from_rosetta ( self , residue_id , to_scheme ) :
'''A simpler conversion function to convert from Rosetta numbering without requiring the chain identifier .''' | assert ( type ( residue_id ) == types . IntType )
# Find the chain _ id associated with the residue _ id
# Scan * all * sequences without breaking out to make sure that we do not have any duplicate maps
chain_id = None
for c , sequence in self . rosetta_sequences . iteritems ( ) :
for id , r in sequence :
i... |
def set_stream_logger ( name = 'margaritashotgun' , level = logging . INFO , format_string = None ) :
"""Add a stream handler for the provided name and level to the logging module .
> > > import margaritashotgun
> > > margaritashotgun . set _ stream _ logger ( ' marsho ' , logging . DEBUG )
: type name : stri... | if format_string is None :
format_string = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
time_format = "%Y-%m-%dT%H:%M:%S"
logger = logging . getLogger ( name )
logger . setLevel ( level )
handler = logging . StreamHandler ( )
handler . setLevel ( level )
formatter = logging . Formatter ( format_string , t... |
def _get_page_title ( self , page ) :
"""Open the rst file ` page ` and extract its title .""" | fname = os . path . join ( SOURCE_PATH , '{}.rst' . format ( page ) )
option_parser = docutils . frontend . OptionParser ( components = ( docutils . parsers . rst . Parser , ) )
doc = docutils . utils . new_document ( '<doc>' , option_parser . get_default_values ( ) )
with open ( fname ) as f :
data = f . read ( )
... |
def _file_like ( self , full_path ) :
"""Return the appropriate file object .""" | magic = self . _match_magic ( full_path )
if magic is not None :
return magic . file_like ( full_path , self . encoding )
else :
return open ( full_path , 'rb' ) |
def fetch_pdb ( pdbid ) :
"""Get the newest entry from the RCSB server for the given PDB ID . Exits with ' 1 ' if PDB ID is invalid .""" | pdbid = pdbid . lower ( )
write_message ( '\nChecking status of PDB ID %s ... ' % pdbid )
state , current_entry = check_pdb_status ( pdbid )
# Get state and current PDB ID
if state == 'OBSOLETE' :
write_message ( 'entry is obsolete, getting %s instead.\n' % current_entry )
elif state == 'CURRENT' :
write_messag... |
def merge_files ( sources , destination ) :
"""Copy content of multiple files into a single file .
: param list ( str ) sources : source file names ( paths )
: param str destination : destination file name ( path )
: return :""" | with open ( destination , 'w' ) as hout :
for f in sources :
if os . path . exists ( f ) :
with open ( f ) as hin :
shutil . copyfileobj ( hin , hout )
else :
logger . warning ( 'File is missing: {}' . format ( f ) ) |
def cov_from_trace ( self , trace = slice ( None ) ) :
"""Define the jump distribution covariance matrix from the object ' s
stored trace .
: Parameters :
- ` trace ` : slice or int
A slice for the stochastic object ' s trace in the last chain , or a
an integer indicating the how many of the last samples ... | n = [ ]
for s in self . stochastics :
n . append ( s . trace . length ( ) )
n = set ( n )
if len ( n ) > 1 :
raise ValueError ( 'Traces do not have the same length.' )
elif n == 0 :
raise AttributeError ( 'Stochastic has no trace to compute covariance.' )
else :
n = n . pop ( )
if not isinstance ( trace... |
def _set_request_user_id_metric ( self , request ) :
"""Add request _ user _ id metric
Metrics :
request _ user _ id""" | if hasattr ( request , 'user' ) and hasattr ( request . user , 'id' ) and request . user . id :
monitoring . set_custom_metric ( 'request_user_id' , request . user . id ) |
def print_report_on_all_logs ( ) -> None :
"""Use : func : ` print ` to report information on all logs .""" | d = { }
# noinspection PyUnresolvedReferences
for name , obj in logging . Logger . manager . loggerDict . items ( ) :
d [ name ] = get_log_report ( obj )
rootlogger = logging . getLogger ( )
d [ '(root logger)' ] = get_log_report ( rootlogger )
print ( json . dumps ( d , sort_keys = True , indent = 4 , separators =... |
def get_menu_items_for_rendering ( self ) :
"""Return a list of ' menu items ' to be included in the context for
rendering the current level of the menu .
The responsibility for sourcing , priming , and modifying menu items is
split between three methods : ` ` get _ raw _ menu _ items ( ) ` ` ,
` ` prime _ ... | items = self . get_raw_menu_items ( )
# Allow hooks to modify the raw list
for hook in hooks . get_hooks ( 'menus_modify_raw_menu_items' ) :
items = hook ( items , ** self . common_hook_kwargs )
# Prime and modify the menu items accordingly
items = self . modify_menu_items ( self . prime_menu_items ( items ) )
if i... |
def nein ( x ) :
"this is ' not ' but not is a keyword so it ' s ' nein '" | if not isinstance ( x , ( bool , ThreeVL ) ) :
raise TypeError ( type ( x ) )
return not x if isinstance ( x , bool ) else ThreeVL ( dict ( t = 'f' , f = 't' , u = 'u' ) [ x . value ] ) |
def match ( self , expr ) -> MatchDict :
"""Match the given expression ( recursively )
Returns a : class : ` MatchDict ` instance that maps any wildcard names to
the expressions that the corresponding wildcard pattern matches . For
( sub - ) pattern that have a ` mode ` attribute other than ` Pattern . single... | res = MatchDict ( )
if self . _has_non_single_arg :
if self . _non_single_arg_on_left :
res . merge_lists = 1
else :
res . merge_lists = - 1
if self . head is not None :
if not isinstance ( expr , self . head ) :
res . reason = ( "%s is not an instance of %s" % ( repr ( expr ) , self... |
def _find_realname ( self , post_input ) :
"""Returns the most appropriate name to identify the user""" | # First , try the full name
if "lis_person_name_full" in post_input :
return post_input [ "lis_person_name_full" ]
if "lis_person_name_given" in post_input and "lis_person_name_family" in post_input :
return post_input [ "lis_person_name_given" ] + post_input [ "lis_person_name_family" ]
# Then the email
if "li... |
def traceback ( cls , error = None , debug = True , trace = True ) :
"""prints the trace
: param error : a message preceding the trace
: param debug : prints it if debug is set to true
: param trace :
: return :""" | # TODO : if debug :
Error . msg ( error = error , debug = debug , trace = trace ) |
def _to_narrow ( self , terms , data , mask , dates , symbols ) :
"""Convert raw computed pipeline results into a DataFrame for public APIs .
Parameters
terms : dict [ str - > Term ]
Dict mapping column names to terms .
data : dict [ str - > ndarray [ ndim = 2 ] ]
Dict mapping column names to computed res... | assert len ( dates ) == 1
if not mask . any ( ) : # Manually handle the empty DataFrame case . This is a workaround
# to pandas failing to tz _ localize an empty dataframe with a
# MultiIndex . It also saves us the work of applying a known - empty
# mask to each array .
# Slicing ` dates ` here to preserve pandas metad... |
def get ( self , server ) :
"""Retrieve credentials for ` server ` . If no credentials are found ,
a ` StoreError ` will be raised .""" | if not isinstance ( server , six . binary_type ) :
server = server . encode ( 'utf-8' )
data = self . _execute ( 'get' , server )
result = json . loads ( data . decode ( 'utf-8' ) )
# docker - credential - pass will return an object for inexistent servers
# whereas other helpers will exit with returncode ! = 0 . Fo... |
def is_velar ( c , lang ) :
"""Is the character a velar""" | o = get_offset ( c , lang )
return ( o >= VELAR_RANGE [ 0 ] and o <= VELAR_RANGE [ 1 ] ) |
def parse_selinux ( parts ) :
"""Parse part of an ls output line that is selinux .
Args :
parts ( list ) : A four element list of strings representing the initial
parts of an ls line after the permission bits . The parts are owner
group , selinux info , and the path .
Returns :
A dict containing owner ,... | owner , group = parts [ : 2 ]
selinux = parts [ 2 ] . split ( ":" )
lsel = len ( selinux )
path , link = parse_path ( parts [ - 1 ] )
result = { "owner" : owner , "group" : group , "se_user" : selinux [ 0 ] , "se_role" : selinux [ 1 ] if lsel > 1 else None , "se_type" : selinux [ 2 ] if lsel > 2 else None , "se_mls" : ... |
def int_to_roman ( num ) :
"""https : / / stackoverflow . com / questions / 42875103 / integer - to - roman - number
https : / / stackoverflow . com / questions / 33486183 / convert - from - numbers - to - roman - notation""" | conv = ( ( "M" , 1000 ) , ( "CM" , 900 ) , ( "D" , 500 ) , ( "CD" , 400 ) , ( "C" , 100 ) , ( "XC" , 90 ) , ( "L" , 50 ) , ( "XL" , 40 ) , ( "X" , 10 ) , ( "IX" , 9 ) , ( "V" , 5 ) , ( "IV" , 4 ) , ( "I" , 1 ) )
roman = ""
i = 0
while num > 0 :
while conv [ i ] [ 1 ] > num :
i += 1
roman += conv [ i ] [... |
def _dtype ( cls , tensor : tf . Tensor ) -> tf . Tensor :
'''Converts ` tensor ` to tf . float32 datatype if needed .''' | if tensor . dtype != tf . float32 :
tensor = tf . cast ( tensor , tf . float32 )
return tensor |
def send_signal ( self , s ) :
"""Send a signal to the daemon process .
The signal must have been enabled using the ` ` signals ` `
parameter of : py : meth : ` Service . _ _ init _ _ ` . Otherwise , a
` ` ValueError ` ` is raised .""" | self . _get_signal_event ( s )
# Check if signal has been enabled
pid = self . get_pid ( )
if not pid :
raise ValueError ( 'Daemon is not running.' )
os . kill ( pid , s ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.