signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def loadGmesh ( filename , c = "gold" , alpha = 1 , wire = False , bc = None ) :
"""Reads a ` gmesh ` file format . Return an ` ` Actor ( vtkActor ) ` ` object .""" | if not os . path . exists ( filename ) :
colors . printc ( "~noentry Error in loadGmesh: Cannot find" , filename , c = 1 )
return None
f = open ( filename , "r" )
lines = f . readlines ( )
f . close ( )
nnodes = 0
index_nodes = 0
for i , line in enumerate ( lines ) :
if "$Nodes" in line :
index_node... |
def execute ( self , operation , * args , ** kwargs ) :
'''execute
High - level api : Supported operations are get , get _ config , get _ schema ,
dispatch , edit _ config , copy _ config , validate , commit , discard _ changes ,
delete _ config , lock , unlock , close _ session , kill _ session ,
poweroff ... | def pop_models ( ) :
models = kwargs . pop ( 'models' , None )
if models is None :
return None
else :
if isinstance ( models , str ) :
return [ models ]
else :
return models
def check_models ( models ) :
missing_models = set ( models ) - set ( self . model... |
def lint ( filename ) :
"""Lints an INI file , returning 0 in case of success .""" | config = ConfigParser . ConfigParser ( )
try :
config . read ( filename )
return 0
except ConfigParser . Error as error :
print ( 'Error: %s' % error )
return 1
except :
print ( 'Unexpected Error' )
return 2 |
def show_errors ( self ) :
"""Loop over configuration warnings and log them as INFO log
Loop over configuration errors and log them as INFO log
Note that the warnings and errors are logged on the fly during the configuration parsing .
It is not necessary to log as WARNING and ERROR in this function which is u... | if self . configuration_warnings :
logger . warning ( "Configuration warnings:" )
for msg in self . configuration_warnings :
logger . warning ( msg )
if self . configuration_errors :
logger . warning ( "Configuration errors:" )
for msg in self . configuration_errors :
logger . warning ( ... |
def _reset_on_error ( self , server_address , session ) :
"""On " not master " or " node is recovering " errors reset the server
according to the SDAM spec .
Unpin the session on transient transaction errors .""" | try :
try :
yield
except PyMongoError as exc :
if session and exc . has_error_label ( "TransientTransactionError" ) :
session . _unpin_mongos ( )
raise
except NetworkTimeout : # The socket has been closed . Don ' t reset the server .
# Server Discovery And Monitoring Spec : "... |
def _compute_kernel_matrix_in_portion ( self , X1 , X2 ) :
"""Compute kernel matrix for sklearn . svm . SVC with precomputed kernel .
The method generates the kernel matrix ( similarity matrix ) for
sklearn . svm . SVC with precomputed kernel . It first computes
the correlation from X , then normalizes the co... | kernel_matrix = np . zeros ( ( self . num_samples_ , self . num_samples_ ) , np . float32 , order = 'C' )
sr = 0
row_length = self . num_processed_voxels
num_voxels2 = X2 [ 0 ] . shape [ 1 ]
normalized_corr_data = None
while sr < self . num_voxels_ :
if row_length >= self . num_voxels_ - sr :
row_length = s... |
def get_apps ( self , offset = None , limit = None ) :
"""Retrieves apps in this project .
: param offset : Pagination offset .
: param limit : Pagination limit .
: return : Collection object .""" | params = { 'project' : self . id , 'offset' : offset , 'limit' : limit }
return self . _api . apps . query ( api = self . _api , ** params ) |
def recover_chain_id ( storage : SQLiteStorage ) -> ChainID :
"""We can reasonably assume , that any database has only one value for ` chain _ id ` at this point
in time .""" | action_init_chain = json . loads ( storage . get_state_changes ( limit = 1 , offset = 0 ) [ 0 ] )
assert action_init_chain [ '_type' ] == 'raiden.transfer.state_change.ActionInitChain'
return action_init_chain [ 'chain_id' ] |
def writeText ( self , filename = None ) :
"""Writes a text representation of this sequence to the given filename
( defaults to self . txtpath ) .""" | if filename is None :
filename = self . txtpath
with open ( filename , 'wt' ) as output :
self . printText ( output ) |
def progressbar ( total , pos , msg = "" ) :
"""Given a total and a progress position , output a progress bar
to stderr . It is important to not output anything else while
using this , as it relies soley on the behavior of carriage
return ( \\ r ) .
Can also take an optioal message to add after the
progre... | width = get_terminal_size ( ) [ 0 ] - 40
rel_pos = int ( float ( pos ) / total * width )
bar = '' . join ( [ "=" * rel_pos , "." * ( width - rel_pos ) ] )
# Determine how many digits in total ( base 10)
digits_total = len ( str ( total ) )
fmt_width = "%0" + str ( digits_total ) + "d"
fmt = "\r[" + fmt_width + "/" + fm... |
def _tool_from_string ( name ) :
"""Takes a string and returns a corresponding ` Tool ` instance .""" | known_tools = sorted ( _known_tools . keys ( ) )
if name in known_tools :
tool_fn = _known_tools [ name ]
if isinstance ( tool_fn , string_types ) :
tool_fn = _known_tools [ tool_fn ]
return tool_fn ( )
else :
matches , text = difflib . get_close_matches ( name . lower ( ) , known_tools ) , "sim... |
def pager_fatality_rates ( ) :
"""USGS Pager fatality estimation model .
Fatality rate ( MMI ) = cum . standard normal dist ( 1 / BETA * ln ( MMI / THETA ) ) .
Reference :
Jaiswal , K . S . , Wald , D . J . , and Hearne , M . ( 2009a ) .
Estimating casualties for large worldwide earthquakes using an empiric... | # Model coefficients
theta = 13.249
beta = 0.151
mmi_range = list ( range ( 2 , 11 ) )
fatality_rate = { mmi : 0 if mmi < 4 else log_normal_cdf ( mmi , median = theta , sigma = beta ) for mmi in mmi_range }
return fatality_rate |
def bgr2rgb ( self ) :
"""Converts data using the cv conversion .""" | new_data = cv2 . cvtColor ( self . raw_data , cv2 . COLOR_BGR2RGB )
return ColorImage ( new_data , frame = self . frame , encoding = 'rgb8' ) |
def dropna ( self , axis = 0 , how = "any" , thresh = None , subset = None , inplace = False ) :
"""Create a new DataFrame from the removed NA values from this one .
Args :
axis ( int , tuple , or list ) : The axis to apply the drop .
how ( str ) : How to drop the NA values .
' all ' : drop the label if all... | inplace = validate_bool_kwarg ( inplace , "inplace" )
if is_list_like ( axis ) :
axis = [ self . _get_axis_number ( ax ) for ax in axis ]
result = self
for ax in axis :
result = result . dropna ( axis = ax , how = how , thresh = thresh , subset = subset )
return self . _create_or_update_from_com... |
def user_return ( self , frame , return_value ) :
"""This function is called when a return trap is set here .""" | frame . f_locals [ '__return__' ] = return_value
self . message ( '--Return--' )
self . interaction ( frame , None ) |
def sanitize_git_path ( self , uri , ref = None ) :
"""Take a git URI and ref and converts it to a directory safe path .
Args :
uri ( string ) : git URI
( e . g . git @ github . com : foo / bar . git )
ref ( string ) : optional git ref to be appended to the path
Returns :
str : Directory name for the su... | if uri . endswith ( '.git' ) :
dir_name = uri [ : - 4 ]
# drop . git
else :
dir_name = uri
dir_name = self . sanitize_uri_path ( dir_name )
if ref is not None :
dir_name += "-%s" % ref
return dir_name |
def instantiate_from_data ( self , object_data ) :
"""Instantiate object from the supplied data , additional args may come from the environment""" | if isinstance ( object_data , dict ) and 'name' in object_data :
name = object_data [ 'name' ]
module = importlib . import_module ( name )
return self . resolve_and_call ( module . create , extra_env = object_data )
if isinstance ( object_data , dict ) and 'factory' in object_data :
factory = object_dat... |
def initial_state ( self , batch_size , dtype = tf . float32 , trainable = False , trainable_initializers = None , trainable_regularizers = None , name = None ) :
"""Builds the default start state tensor of zeros .""" | core_initial_state = self . _core . initial_state ( batch_size , dtype = dtype , trainable = trainable , trainable_initializers = trainable_initializers , trainable_regularizers = trainable_regularizers , name = name )
dropout_masks = [ None ] * len ( self . _dropout_state_size )
def set_dropout_mask ( index , state , ... |
def transaction_status ( transaction ) :
"""Returns a FormattedItem describing the given transaction .
: param item : An object capable of having an active transaction""" | if not transaction or not transaction . get ( 'transactionStatus' ) :
return blank ( )
return FormattedItem ( transaction [ 'transactionStatus' ] . get ( 'name' ) , transaction [ 'transactionStatus' ] . get ( 'friendlyName' ) ) |
def tear_down_plugs ( self ) :
"""Call tearDown ( ) on all instantiated plugs .
Note that initialize _ plugs must have been called before calling
this method , and initialize _ plugs must be called again after calling
this method if you want to access the plugs attribute again .
Any exceptions in tearDown (... | _LOG . debug ( 'Tearing down all plugs.' )
for plug_type , plug_instance in six . iteritems ( self . _plugs_by_type ) :
if plug_instance . uses_base_tear_down ( ) :
name = '<PlugTearDownThread: BasePlug No-Op for %s>' % plug_type
else :
name = '<PlugTearDownThread: %s>' % plug_type
thread = ... |
def start_time_distance ( item_a , item_b , max_value ) :
"""Absolute difference between the starting times of each item .
Args :
item _ a : STObject from the first set in TrackMatcher
item _ b : STObject from the second set in TrackMatcher
max _ value : Maximum distance value used as scaling value and uppe... | start_time_diff = np . abs ( item_a . times [ 0 ] - item_b . times [ 0 ] )
return np . minimum ( start_time_diff , max_value ) / float ( max_value ) |
def cancel_job ( self , job_id = None , job_name = None ) :
"""Cancel a running job .
Args :
job _ id ( str , optional ) : Identifier of job to be canceled .
job _ name ( str , optional ) : Name of job to be canceled .
Returns :
dict : JSON response for the job cancel operation .""" | return self . _delegator . cancel_job ( job_id = job_id , job_name = job_name ) |
def save ( self ) :
"""Store the session data in redis
: param method callback : The callback method to invoke when done""" | result = yield gen . Task ( RedisSession . _redis_client . set , self . _key , self . dumps ( ) )
LOGGER . debug ( 'Saved session %s (%r)' , self . id , result )
raise gen . Return ( result ) |
def allocate_ids ( self , incomplete_key , num_ids ) :
"""Allocate a list of IDs from a partial key .
: type incomplete _ key : : class : ` google . cloud . datastore . key . Key `
: param incomplete _ key : Partial key to use as base for allocated IDs .
: type num _ ids : int
: param num _ ids : The number... | if not incomplete_key . is_partial :
raise ValueError ( ( "Key is not partial." , incomplete_key ) )
incomplete_key_pb = incomplete_key . to_protobuf ( )
incomplete_key_pbs = [ incomplete_key_pb ] * num_ids
response_pb = self . _datastore_api . allocate_ids ( incomplete_key . project , incomplete_key_pbs )
allocate... |
def head_object ( request , pid ) :
"""MNRead . describe ( session , did ) → DescribeResponse .""" | sciobj = d1_gmn . app . models . ScienceObject . objects . get ( pid__did = pid )
response = django . http . HttpResponse ( )
d1_gmn . app . views . headers . add_sciobj_properties_headers_to_response ( response , sciobj )
d1_gmn . app . event_log . log_read_event ( pid , request )
return response |
async def set_ch_enable_bit ( self , ch_bit , timeout = OTGW_DEFAULT_TIMEOUT ) :
"""Control the CH enable status bit when overriding the control
setpoint . By default the CH enable bit is set after a call to
set _ control _ setpoint with a value other than 0 . With this
method , the bit can be manipulated .
... | if ch_bit not in [ 0 , 1 ] :
return None
cmd = OTGW_CMD_CONTROL_HEATING
status = { }
ret = await self . _wait_for_cmd ( cmd , ch_bit , timeout )
if ret is None :
return
ret = int ( ret )
status [ DATA_MASTER_CH_ENABLED ] = ret
self . _update_status ( status )
return ret |
def _getFromTime ( self , atDate = None ) :
"""What was the time of this event ? Due to time zones that depends what
day we are talking about . If no day is given , assume today .""" | if atDate is None :
atDate = timezone . localdate ( timezone = self . tz )
return getLocalTime ( atDate , self . time_from , self . tz ) |
def redeem ( self , account_code ) :
"""Redeem this gift card on the specified account code""" | redemption_path = '%s/redeem' % ( self . redemption_code )
if hasattr ( self , '_url' ) :
url = urljoin ( self . _url , '/redeem' )
else :
url = urljoin ( recurly . base_uri ( ) , self . collection_path + '/' + redemption_path )
recipient_account = _RecipientAccount ( account_code = account_code )
return self .... |
def upgrade_bcbio ( args ) :
"""Perform upgrade of bcbio to latest release , or from GitHub development version .
Handles bcbio , third party tools and data .""" | print ( "Upgrading bcbio" )
args = add_install_defaults ( args )
if args . upgrade in [ "stable" , "system" , "deps" , "development" ] :
if args . upgrade == "development" :
anaconda_dir = _update_conda_devel ( )
_check_for_conda_problems ( )
print ( "Upgrading bcbio-nextgen to latest develo... |
def serialize ( data ) :
"""Serialize a dict into a JSON formatted string .
This function enforces rules like the separator and order of keys .
This ensures that all dicts are serialized in the same way .
This is specially important for hashing data . We need to make sure that
everyone serializes their data... | return rapidjson . dumps ( data , skipkeys = False , ensure_ascii = False , sort_keys = True ) |
def replace_all ( text , dic ) :
"""Takes a string and dictionary . replaces all occurrences of i with j""" | for i , j in dic . iteritems ( ) :
text = text . replace ( i , j )
return text |
def sc_pan ( self , viewer , event , msg = True ) :
"""Interactively pan the image by scrolling motion .""" | if not self . canpan :
return True
# User has " Pan Reverse " preference set ?
rev = self . settings . get ( 'pan_reverse' , False )
direction = event . direction
if rev :
direction = math . fmod ( direction + 180.0 , 360.0 )
pan_accel = self . settings . get ( 'scroll_pan_acceleration' , 1.0 )
# Internal facto... |
def device_firmware_str ( self , indent ) :
"""Convenience to string method .""" | host_build_ns = self . host_firmware_build_timestamp
host_build_s = datetime . datetime . utcfromtimestamp ( host_build_ns / 1000000000 ) if host_build_ns != None else None
wifi_build_ns = self . wifi_firmware_build_timestamp
wifi_build_s = datetime . datetime . utcfromtimestamp ( wifi_build_ns / 1000000000 ) if wifi_b... |
def clone ( self , ignore = ( ) ) :
"""Clone this dag using a set of substitutions .
Traverse the dag in topological order .""" | nodes = [ clone ( node , self . substitutions , ignore ) for node in toposorted ( self . nodes , self . edges ) ]
return DAG ( nodes = nodes , substitutions = self . substitutions ) . build_edges ( ) |
def determine_file_type ( filename ) :
""": param filename : str
: rtype : FileType""" | if filename . endswith ( '.cls' ) :
return FileType . CLS
elif filename . endswith ( '.go' ) :
return FileType . GO
elif filename . endswith ( '.java' ) :
return FileType . JAVA
elif filename . endswith ( '.js' ) :
return FileType . JAVASCRIPT
elif filename . endswith ( '.php' ) :
return FileType . ... |
def rectangle ( self , rect , attr = None , fill = u' ' ) :
u'''Fill Rectangle .''' | x0 , y0 , x1 , y1 = rect
n = DWORD ( 0 )
if attr is None :
attr = self . attr
for y in range ( y0 , y1 ) :
pos = self . fixcoord ( x0 , y )
self . FillConsoleOutputAttribute ( self . hout , attr , x1 - x0 , pos , byref ( n ) )
self . FillConsoleOutputCharacterW ( self . hout , ord ( fill [ 0 ] ) , x1 - ... |
def load_TopHat ( self , wave_min , wave_max , pixels_per_bin = 100 ) :
"""Loads a top hat filter given wavelength min and max values
Parameters
wave _ min : astropy . units . quantity ( optional )
The minimum wavelength to use
wave _ max : astropy . units . quantity ( optional )
The maximum wavelength to... | # Get min , max , effective wavelengths and width
self . pixels_per_bin = pixels_per_bin
self . n_bins = 1
self . _wave_units = q . AA
wave_min = wave_min . to ( self . wave_units )
wave_max = wave_max . to ( self . wave_units )
# Create the RSR curve
self . _wave = np . linspace ( wave_min , wave_max , pixels_per_bin ... |
def get_scaled_cutout_wdhtdp_view ( shp , p1 , p2 , new_dims ) :
"""Like get _ scaled _ cutout _ wdht , but returns the view / slice to extract
from an image instead of the extraction itself .""" | x1 , y1 , z1 = p1
x2 , y2 , z2 = p2
new_wd , new_ht , new_dp = new_dims
x1 , y1 , x2 , y2 = int ( x1 ) , int ( y1 ) , int ( x2 ) , int ( y2 ) , int ( z1 ) , int ( z2 )
z1 , z2 , new_wd , new_ht = int ( z1 ) , int ( z2 ) , int ( new_wd ) , int ( new_ht )
# calculate dimensions of NON - scaled cutout
old_wd = x2 - x1 + 1... |
def export ( self , folder_path , format = None ) :
"""General purpose export method , gets file type
from filepath extension
Valid output formats currently are :
Trackline : trackline or trkl or * . trkl
Shapefile : shapefile or shape or shp or * . shp
NetCDF : netcdf or nc or * . nc""" | if format is None :
raise ValueError ( "Must export to a specific format, no format specified." )
format = format . lower ( )
if format == "trackline" or format [ - 4 : ] == "trkl" :
ex . Trackline . export ( folder = folder_path , particles = self . particles , datetimes = self . datetimes )
elif format == "sh... |
def _create_factor_rule ( tok ) :
"""Simple helper method for creating factor node objects based on node name .""" | if tok [ 0 ] == 'IPV4' :
return IPV4Rule ( tok [ 1 ] )
if tok [ 0 ] == 'IPV6' :
return IPV6Rule ( tok [ 1 ] )
if tok [ 0 ] == 'DATETIME' :
return DatetimeRule ( tok [ 1 ] )
if tok [ 0 ] == 'TIMEDELTA' :
return TimedeltaRule ( tok [ 1 ] )
if tok [ 0 ] == 'INTEGER' :
return IntegerRule ( tok [ 1 ] )
i... |
def p_expr_add_term ( self , args ) :
'expr : : = expr ADD _ OP term' | op = 'add' if args [ 1 ] . attr == '+' else 'subtract'
return AST ( op , [ args [ 0 ] , args [ 2 ] ] ) |
def add_constraints ( self ) :
"""Set the base constraints on the relation query .
: rtype : None""" | if self . _constraints :
foreign_key = getattr ( self . _parent , self . _foreign_key , None )
if foreign_key is None :
self . _query = None
else :
table = self . _related . get_table ( )
self . _query . where ( "{}.{}" . format ( table , self . _other_key ) , "=" , foreign_key ) |
def indent_line ( zerolevel , bracket_list , line , in_comment , in_symbol_region , options = None ) :
"""indent _ line ( zerolevel : int , bracket _ list : list , line : str , in _ comment : bool ,
in _ symbol _ region : bool , options : string | list )
Most important function in the indentation process . It u... | opts = parse_options ( options )
comment_line = re . search ( '^[ \t]*;' , line , re . M )
if opts . indent_comments : # We are allowed to indent comment lines
comment_line = False
if not opts . compact and bracket_list == [ ] and not in_comment : # If nocompact mode is on and there are no unclosed blocks , try to
... |
def extract_links ( bs4 ) :
"""Extracting links from BeautifulSoup object
: param bs4 : ` BeautifulSoup `
: return : ` list ` List of links""" | unique_links = list ( set ( [ anchor [ 'href' ] for anchor in bs4 . select ( 'a[href]' ) if anchor . has_attr ( 'href' ) ] ) )
# remove irrelevant link
unique_links = [ link for link in unique_links if link != '#' ]
# convert invalid link with adding ' http ' schema
return [ convert_invalid_url ( link ) for link in uni... |
def overlay_gateway_access_lists_mac_in_cg_mac_acl_in_name ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
overlay_gateway = ET . SubElement ( config , "overlay-gateway" , xmlns = "urn:brocade.com:mgmt:brocade-tunnels" )
name_key = ET . SubElement ( overlay_gateway , "name" )
name_key . text = kwargs . pop ( 'name' )
access_lists = ET . SubElement ( overlay_gateway , "access-lists" )
mac =... |
def RACCU_calc ( TOP , P , POP ) :
"""Calculate RACCU ( Random accuracy unbiased ) .
: param TOP : test outcome positive
: type TOP : int
: param P : condition positive
: type P : int
: param POP : population
: type POP : int
: return : RACCU as float""" | try :
result = ( ( TOP + P ) / ( 2 * POP ) ) ** 2
return result
except Exception :
return "None" |
def get_dataset ( self , key , info = None , out = None , xslice = None , yslice = None ) :
"""Load a dataset""" | if key in self . cache :
return self . cache [ key ]
# Type dictionary
typedict = { "af" : "flash_accumulation" , "afa" : "accumulated_flash_area" , "afr" : "flash_radiance" , "lgr" : "radiance" , "lef" : "radiance" , "lfl" : "radiance" }
# Get lightning data out of NetCDF container
logger . debug ( "Key: {}" . for... |
def main ( self ) :
"""Main beautifying function .""" | error = False
parser = argparse . ArgumentParser ( description = "A Bash beautifier for the masses, version {}" . format ( self . get_version ( ) ) , add_help = False )
parser . add_argument ( '--indent-size' , '-i' , nargs = 1 , type = int , default = 4 , help = "Sets the number of spaces to be used in " "indentation.... |
def _get_filekey ( self ) :
"""This method creates a key from a keyfile .""" | if not os . path . exists ( self . keyfile ) :
raise KPError ( 'Keyfile not exists.' )
try :
with open ( self . keyfile , 'rb' ) as handler :
handler . seek ( 0 , os . SEEK_END )
size = handler . tell ( )
handler . seek ( 0 , os . SEEK_SET )
if size == 32 :
return han... |
def league_info ( ) :
"""Returns a dictionary of league information""" | league = __get_league_object ( )
output = { }
for x in league . attrib :
output [ x ] = league . attrib [ x ]
return output |
def raw_of ( self , klass , name , ** attributes ) :
"""Get the raw attribute dict for a given named model .
: param klass : The class
: type klass : class
: param name : The type
: type name : str
: param attributes : The instance attributes
: type attributes : dict
: return : dict""" | return self . raw ( klass , _name = name , ** attributes ) |
def parse_port_from_tensorboard_output ( tensorboard_output : str ) -> int :
"""Parse tensorboard port from its outputted message .
: param tensorboard _ output : Output message of Tensorboard
in format TensorBoard 1.8.0 at http : / / martin - VirtualBox : 36869
: return : Returns the port TensorBoard is list... | search = re . search ( "at http://[^:]+:([0-9]+)" , tensorboard_output )
if search is not None :
port = search . group ( 1 )
return int ( port )
else :
raise UnexpectedOutputError ( tensorboard_output , "Address and port where Tensorboard has started," " e.g. TensorBoard 1.8.0 at http://martin-VirtualBox:36... |
def split_pks ( cols ) :
"""Returns a 2 - tuple of tuples of ( ( primary _ key _ cols ) , ( non _ primary _ key _ cols ) ) .""" | pks = [ ]
others = [ ]
for name , col in cols . items ( ) :
if col [ "is_primary_key" ] == "t" :
pks . append ( name )
else :
others . append ( name )
return ( tuple ( pks ) , tuple ( others ) ) |
def synset ( self ) :
"""Returns synset into which the given lemma belongs to .
Returns
Synset
Synset into which the given lemma belongs to .""" | return synset ( '%s.%s.%s.%s' % ( self . synset_literal , self . synset_pos , self . synset_sense , self . literal ) ) |
def _set_hundredgigabitethernet ( self , v , load = False ) :
"""Setter method for hundredgigabitethernet , mapped from YANG variable / interface / hundredgigabitethernet ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ hundredgigabitethernet is considered as a ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "name" , hundredgigabitethernet . hundredgigabitethernet , yang_name = "hundredgigabitethernet" , rest_name = "HundredGigabitEthernet" , parent = self , is_container = 'list' , user_ordered = True , path_helper... |
def mouse_handler ( self , cli , mouse_event ) :
"""Handle scoll and click events .""" | b = cli . current_buffer
def scroll_left ( ) :
b . complete_previous ( count = self . _rendered_rows , disable_wrap_around = True )
self . scroll = max ( 0 , self . scroll - 1 )
def scroll_right ( ) :
b . complete_next ( count = self . _rendered_rows , disable_wrap_around = True )
self . scroll = min ( ... |
def _associate_cnvkit_out ( ckouts , items , is_somatic = False ) :
"""Associate cnvkit output with individual items .""" | assert len ( ckouts ) == len ( items )
out = [ ]
upload_counts = collections . defaultdict ( int )
for ckout , data in zip ( ckouts , items ) :
ckout = copy . deepcopy ( ckout )
ckout [ "variantcaller" ] = "cnvkit"
if utils . file_exists ( ckout [ "cns" ] ) and _cna_has_values ( ckout [ "cns" ] ) :
... |
def c14n ( xml ) :
'''Applies c14n to the xml input
@ param xml : str
@ return : str''' | tree = etree . parse ( StringIO ( xml ) )
output = StringIO ( )
tree . write_c14n ( output , exclusive = False , with_comments = True , compression = 0 )
output . flush ( )
c14nized = output . getvalue ( )
output . close ( )
return c14nized |
def selected_canvas_explayer ( self ) :
"""Obtain the canvas exposure layer selected by user .
: returns : The currently selected map layer in the list .
: rtype : QgsMapLayer""" | if self . lstCanvasExpLayers . selectedItems ( ) :
item = self . lstCanvasExpLayers . currentItem ( )
else :
return None
try :
layer_id = item . data ( Qt . UserRole )
except ( AttributeError , NameError ) :
layer_id = None
# noinspection PyArgumentList
layer = QgsProject . instance ( ) . mapLayer ( lay... |
def triggered_token ( self ) -> 'CancelToken' :
"""Return the token which was triggered .
The returned token may be this token or one that it was chained with .""" | if self . _triggered . is_set ( ) :
return self
for token in self . _chain :
if token . triggered : # Use token . triggered _ token here to make the lookup recursive as self . _ chain may
# contain other chains .
return token . triggered_token
return None |
def set_short_url ( self ) :
"""Generates the ` ` short _ url ` ` attribute if the model does not
already have one . Used by the ` ` set _ short _ url _ for ` ` template
tag and ` ` TweetableAdmin ` ` .
If no sharing service is defined ( bitly is the one implemented ,
but others could be by overriding ` ` g... | if self . short_url == SHORT_URL_UNSET :
self . short_url = self . get_absolute_url_with_host ( )
elif not self . short_url :
self . short_url = self . generate_short_url ( )
self . save ( ) |
def insertCallSet ( self , callSet ) :
"""Inserts a the specified callSet into this repository .""" | try :
models . Callset . create ( id = callSet . getId ( ) , name = callSet . getLocalId ( ) , variantsetid = callSet . getParentContainer ( ) . getId ( ) , biosampleid = callSet . getBiosampleId ( ) , attributes = json . dumps ( callSet . getAttributes ( ) ) )
except Exception as e :
raise exceptions . RepoMan... |
def col2hue ( r , g , b ) :
"""Return hue value corresponding to given RGB color .""" | return round2 ( 180 / pi * atan2 ( sqrt ( 3 ) * ( g - b ) , 2 * r - g - b ) + 360 ) % 360 |
def get_ldap_users ( self ) :
"""Retrieve user data from LDAP server .""" | if ( not self . conf_LDAP_SYNC_USER ) :
return ( None , None )
user_keys = set ( self . conf_LDAP_SYNC_USER_ATTRIBUTES . keys ( ) )
user_keys . update ( self . conf_LDAP_SYNC_USER_EXTRA_ATTRIBUTES )
uri_users_server , users = self . ldap_search ( self . conf_LDAP_SYNC_USER_FILTER , user_keys , self . conf_LDAP_SYNC... |
def setOutputObject ( self , newOutput = output . CalcpkgOutput ( True , True ) ) :
"""Set an object where all output from calcpkg will be redirected to for this repository""" | self . output = newOutput |
def short_str ( self ) :
"""Return a string of the form " ver < url > " where ver is the distribution
version and URL is the distribution Home - Page url , or ' ' if neither
can be found .
: return : version and URL
: rtype : str""" | if self . version is None and self . url is None :
return ''
return '%s <%s>' % ( self . version , self . url ) |
def get_scalar_mirrored_target_option ( self , option_name , target ) :
"""Get the attribute ` field _ name ` from ` target ` if set , else from this subsystem ' s options .""" | mirrored_option_declaration = self . _mirrored_option_declarations [ option_name ]
return mirrored_option_declaration . get_mirrored_scalar_option_value ( target ) |
def calibrate_plunger ( self , top = None , bottom = None , blow_out = None , drop_tip = None ) :
"""Set calibration values for the pipette plunger .
This can be called multiple times as the user sets each value ,
or you can set them all at once .
Parameters
top : int
Touching but not engaging the plunger... | if top is not None :
self . plunger_positions [ 'top' ] = top
if bottom is not None :
self . plunger_positions [ 'bottom' ] = bottom
if blow_out is not None :
self . plunger_positions [ 'blow_out' ] = blow_out
if drop_tip is not None :
self . plunger_positions [ 'drop_tip' ] = drop_tip
return self |
def bare_except ( logical_line , noqa ) :
r"""When catching exceptions , mention specific exceptions whenever possible .
Okay : except Exception :
Okay : except BaseException :
E722 : except :""" | if noqa :
return
regex = re . compile ( r"except\s*:" )
match = regex . match ( logical_line )
if match :
yield match . start ( ) , "E722 do not use bare except'" |
def update_workflow_workitems ( cr , pool , ref_spec_actions ) :
"""Find all the workflow items from the target state to set them to
the wanted state .
When a workflow action is removed , from model , the objects whose states
are in these actions need to be set to another to be able to continue the
workflow... | workflow_workitems = pool [ 'workflow.workitem' ]
ir_model_data_model = pool [ 'ir.model.data' ]
for ( target_external_id , fallback_external_id ) in ref_spec_actions :
target_activity = ir_model_data_model . get_object ( cr , SUPERUSER_ID , target_external_id . split ( "." ) [ 0 ] , target_external_id . split ( ".... |
def _hm_read_address ( self ) :
"""Reads from the DCB and maps to yaml config file .""" | response = self . _hm_send_address ( self . address , 0 , 0 , 0 )
lookup = self . config [ 'keys' ]
offset = self . config [ 'offset' ]
keydata = { }
for i in lookup :
try :
kdata = lookup [ i ]
ddata = response [ i + offset ]
keydata [ i ] = { 'label' : kdata , 'value' : ddata }
except ... |
def list_all_options ( cls , ** kwargs ) :
"""List Options
Return a list of Options
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . list _ all _ options ( async = True )
> > > result = thread . get ( )
: param... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _list_all_options_with_http_info ( ** kwargs )
else :
( data ) = cls . _list_all_options_with_http_info ( ** kwargs )
return data |
def _apply_uncertainty_to_mfd ( self , mfd , value ) :
"""Modify ` ` mfd ` ` object with uncertainty value ` ` value ` ` .""" | if self . uncertainty_type == 'abGRAbsolute' :
a , b = value
mfd . modify ( 'set_ab' , dict ( a_val = a , b_val = b ) )
elif self . uncertainty_type == 'bGRRelative' :
mfd . modify ( 'increment_b' , dict ( value = value ) )
elif self . uncertainty_type == 'maxMagGRRelative' :
mfd . modify ( 'increment_m... |
def path_order ( x , y ) :
"""Helper for as _ path , below . Orders properties with the implicit ones
first , and within the two sections in alphabetical order of feature
name .""" | if x == y :
return 0
xg = get_grist ( x )
yg = get_grist ( y )
if yg and not xg :
return - 1
elif xg and not yg :
return 1
else :
if not xg :
x = feature . expand_subfeatures ( [ x ] )
y = feature . expand_subfeatures ( [ y ] )
if x < y :
return - 1
elif x > y :
r... |
def denormalize ( data ) :
'''denormalize ( data ) yield a denormalized version of the given JSON - friendly normalized data . This
is the inverse of the normalize ( obj ) function .
The normalize and denormalize functions use the reserved keyword ' _ _ type _ _ ' along with the
< obj > . normalize ( ) and < ... | if data is None :
return None
elif pimms . is_scalar ( data , ( 'number' , 'bool' , 'string' , 'unicode' ) ) :
return data
elif pimms . is_map ( data ) : # see if it ' s a non - native map
if normalize_type_key in data :
( mdl , cls ) = data [ normalize_type_key ]
if mdl is None :
... |
def write_byte ( self , i2c_addr , value , force = None ) :
"""Write a single byte to a device .
: param i2c _ addr : i2c address
: type i2c _ addr : int
: param value : value to write
: type value : int
: param force :
: type force : Boolean""" | self . _set_address ( i2c_addr , force = force )
msg = i2c_smbus_ioctl_data . create ( read_write = I2C_SMBUS_WRITE , command = value , size = I2C_SMBUS_BYTE )
ioctl ( self . fd , I2C_SMBUS , msg ) |
def keyPressEvent ( self , event ) :
"""Exits the modal window on an escape press .
: param event | < QtCore . QKeyPressEvent >""" | if event . key ( ) == QtCore . Qt . Key_Escape :
self . reject ( )
super ( XOverlayWidget , self ) . keyPressEvent ( event ) |
def finish ( ) : # type : ( ) - > None
"""Merge current feature branch into develop .""" | pretend = context . get ( 'pretend' , False )
if not pretend and ( git . staged ( ) or git . unstaged ( ) ) :
log . err ( "You have uncommitted changes in your repo!\n" "You need to stash them before you merge the hotfix branch" )
sys . exit ( 1 )
branch = git . current_branch ( refresh = True )
base = common .... |
def preloop ( self ) :
"""if the parser is not already set , loads the parser .""" | if not self . parser :
self . stdout . write ( "Welcome to imagemounter {version}" . format ( version = __version__ ) )
self . stdout . write ( "\n" )
self . parser = ImageParser ( )
for p in self . args . paths :
self . onecmd ( 'disk "{}"' . format ( p ) ) |
def run ( self ) : # pragma : no cover
"""Called by Sphinx to generate documentation for this directive .""" | if self . directive_name is None :
raise NotImplementedError ( 'directive_name must be implemented by ' 'subclasses of BaseDirective' )
env , state = self . _prepare_env ( )
state . doc_names . add ( env . docname )
directive_name = '<{}>' . format ( self . directive_name )
node = nodes . section ( )
node . documen... |
def hxbyterle_decode ( output_size , data ) :
"""Decode HxRLE data stream
If C - extension is not compiled it will use a ( slower ) Python equivalent
: param int output _ size : the number of items when ` ` data ` ` is uncompressed
: param str data : a raw stream of data to be unpacked
: return numpy . arra... | output = byterle_decoder ( data , output_size )
assert len ( output ) == output_size
return output |
def header ( self , text , level , raw = None ) :
"""Rendering header / heading tags like ` ` < h1 > ` ` ` ` < h2 > ` ` .
: param text : rendered text content for the header .
: param level : a number for the header level , for example : 1.
: param raw : raw text content of the header .""" | return '\n{0}\n{1}\n' . format ( text , self . hmarks [ level ] * column_width ( text ) ) |
def decodebytes ( input ) :
"""Decode base64 string to byte array .""" | py_version = sys . version_info [ 0 ]
if py_version >= 3 :
return _decodebytes_py3 ( input )
return _decodebytes_py2 ( input ) |
def reftrack_version_data ( rt , role ) :
"""Return the data for the version that is loaded by the reftrack
: param rt : the : class : ` jukeboxcore . reftrack . Reftrack ` holds the data
: type rt : : class : ` jukeboxcore . reftrack . Reftrack `
: param role : item data role
: type role : QtCore . Qt . It... | tfi = rt . get_taskfileinfo ( )
if not tfi :
return
return filesysitemdata . taskfileinfo_version_data ( tfi , role ) |
def get_instance ( self , payload ) :
"""Build an instance of PublishedTrackInstance
: param dict payload : Payload response from the API
: returns : twilio . rest . video . v1 . room . room _ participant . room _ participant _ published _ track . PublishedTrackInstance
: rtype : twilio . rest . video . v1 . ... | return PublishedTrackInstance ( self . _version , payload , room_sid = self . _solution [ 'room_sid' ] , participant_sid = self . _solution [ 'participant_sid' ] , ) |
def save_file ( self , path = None , filters = '*.dat' , force_extension = None , force_overwrite = False , header_only = False , delimiter = 'use current' , binary = None ) :
"""This will save all the header info and columns to an ascii file with
the specified path .
Parameters
path = None
Path for saving ... | # Make sure there isn ' t a problem later with no - column databoxes
if len ( self ) == 0 :
header_only = True
# This is the final path . We now write to a temporary file in the user
# directory , then move it to the destination . This ( hopefully ) fixes
# problems with sync programs .
if path in [ None ] :
pa... |
async def build_get_payment_sources_request ( wallet_handle : int , submitter_did : str , payment_address : str ) -> ( str , str ) :
"""Builds Indy request for getting sources list for payment address
according to this payment method .
: param wallet _ handle : wallet handle ( created by open _ wallet ) .
: p... | logger = logging . getLogger ( __name__ )
logger . debug ( "build_get_payment_sources_request: >>> wallet_handle: %r, submitter_did: %r, payment_address: %r" , wallet_handle , submitter_did , payment_address )
if not hasattr ( build_get_payment_sources_request , "cb" ) :
logger . debug ( "build_get_payment_sources_... |
def rule_function_not_found ( self , fun = None ) :
"""any function that does not exist will be added as a
dummy function that will gather inputs for easing into
the possible future implementation""" | sfun = str ( fun )
self . cry ( 'rule_function_not_found:' + sfun )
def not_found ( * a , ** k ) :
return ( sfun + ':rule_function_not_found' , k . keys ( ) )
return not_found |
def getCameraParams ( self ) :
'''value positions based on
http : / / docs . opencv . org / modules / imgproc / doc / geometric _ transformations . html # cv . InitUndistortRectifyMap''' | c = self . coeffs [ 'cameraMatrix' ]
fx = c [ 0 ] [ 0 ]
fy = c [ 1 ] [ 1 ]
cx = c [ 0 ] [ 2 ]
cy = c [ 1 ] [ 2 ]
k1 , k2 , p1 , p2 , k3 = tuple ( self . coeffs [ 'distortionCoeffs' ] . tolist ( ) [ 0 ] )
return fx , fy , cx , cy , k1 , k2 , k3 , p1 , p2 |
def find_pip ( pip_version = None , python_version = None ) :
"""Find a pip exe using the given python version .
Returns :
2 - tuple :
str : pip executable ;
` ResolvedContext ` : Context containing pip , or None if we fell back
to system pip .""" | pip_exe = "pip"
try :
context = create_context ( pip_version , python_version )
except BuildError as e : # fall back on system pip . Not ideal but at least it ' s something
from rez . backport . shutilwhich import which
pip_exe = which ( "pip" )
if pip_exe :
print_warning ( "pip rez package coul... |
def add_infos ( self , * keyvals , ** kwargs ) :
"""Adds the given info and returns a dict composed of just this added info .""" | kv_pairs = [ ]
for key , val in keyvals :
key = key . strip ( )
val = str ( val ) . strip ( )
if ':' in key :
raise ValueError ( 'info key "{}" must not contain a colon.' . format ( key ) )
kv_pairs . append ( ( key , val ) )
for k , v in kv_pairs :
if k in self . _info :
raise Value... |
def getFeatures ( self , referenceName = None , start = None , end = None , startIndex = None , maxResults = None , featureTypes = None , parentId = None , name = None , geneSymbol = None ) :
"""method passed to runSearchRequest to fulfill the request
: param str referenceName : name of reference ( ex : " chr1 " ... | with self . _db as dataSource :
features = dataSource . searchFeaturesInDb ( startIndex , maxResults , referenceName = referenceName , start = start , end = end , parentId = parentId , featureTypes = featureTypes , name = name , geneSymbol = geneSymbol )
for feature in features :
gaFeature = self . _gaF... |
def remove_system ( self , system ) :
'''Removes system from world and kills system''' | if system in self . _systems :
self . _systems . remove ( system )
else :
raise UnmanagedSystemError ( system ) |
def get_free_shipping_promotion_by_id ( cls , free_shipping_promotion_id , ** kwargs ) :
"""Find FreeShippingPromotion
Return single instance of FreeShippingPromotion by its ID .
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > t... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _get_free_shipping_promotion_by_id_with_http_info ( free_shipping_promotion_id , ** kwargs )
else :
( data ) = cls . _get_free_shipping_promotion_by_id_with_http_info ( free_shipping_promotion_id , ** kwargs )
return data |
def validate_token ( self , token ) :
'''retrieve a subject based on a token . Valid means we return a participant
invalid means we return None''' | from expfactory . database . models import Participant
p = Participant . query . filter ( Participant . token == token ) . first ( )
if p is not None :
if p . token . endswith ( ( 'finished' , 'revoked' ) ) :
p = None
else :
p = p . id
return p |
def validate_meta ( meta ) :
"""Validates Linguist Meta attribute .""" | if not isinstance ( meta , ( dict , ) ) :
raise TypeError ( 'Model Meta "linguist" must be a dict' )
required_keys = ( "identifier" , "fields" )
for key in required_keys :
if key not in meta :
raise KeyError ( 'Model Meta "linguist" dict requires %s to be defined' , key )
if not isinstance ( meta [ "fie... |
def transform_txn_for_ledger ( txn ) :
'''Makes sure that we have integer as keys after possible deserialization from json
: param txn : txn to be transformed
: return : transformed txn''' | txn_data = get_payload_data ( txn )
txn_data [ AUDIT_TXN_LEDGERS_SIZE ] = { int ( k ) : v for k , v in txn_data [ AUDIT_TXN_LEDGERS_SIZE ] . items ( ) }
txn_data [ AUDIT_TXN_LEDGER_ROOT ] = { int ( k ) : v for k , v in txn_data [ AUDIT_TXN_LEDGER_ROOT ] . items ( ) }
txn_data [ AUDIT_TXN_STATE_ROOT ] = { int ( k ) : v ... |
def lint ( self , commit ) :
"""Lint the last commit in a given git context by applying all ignore , title , body and commit rules .""" | LOG . debug ( "Linting commit %s" , commit . sha or "[SHA UNKNOWN]" )
LOG . debug ( "Commit Object\n" + ustr ( commit ) )
# Apply config rules
for rule in self . configuration_rules :
rule . apply ( self . config , commit )
# Skip linting if this is a special commit type that is configured to be ignored
ignore_comm... |
def icosahedron ( ) :
"""Create an icosahedron , a 20 faced polyhedron .
Returns
ico : trimesh . Trimesh
Icosahederon centered at the origin .""" | t = ( 1.0 + 5.0 ** .5 ) / 2.0
vertices = [ - 1 , t , 0 , 1 , t , 0 , - 1 , - t , 0 , 1 , - t , 0 , 0 , - 1 , t , 0 , 1 , t , 0 , - 1 , - t , 0 , 1 , - t , t , 0 , - 1 , t , 0 , 1 , - t , 0 , - 1 , - t , 0 , 1 ]
faces = [ 0 , 11 , 5 , 0 , 5 , 1 , 0 , 1 , 7 , 0 , 7 , 10 , 0 , 10 , 11 , 1 , 5 , 9 , 5 , 11 , 4 , 11 , 10 , ... |
def calendar ( self , request ) :
"""Return a calendar page to be loaded in an iframe .""" | context = { 'is_popup' : bool ( int ( request . GET . get ( '_popup' , 0 ) ) ) , }
return TemplateResponse ( request , 'admin/icekit_events/eventbase/calendar.html' , context ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.