signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def Log ( self , frame ) :
"""Captures the minimal application states , formats it and logs the message .
Args :
frame : Python stack frame of breakpoint hit .
Returns :
None on success or status message on error .""" | # Return error if log methods were not configured globally .
if not self . _log_message :
return { 'isError' : True , 'description' : { 'format' : LOG_ACTION_NOT_SUPPORTED } }
if self . _quota_recovery_start_time :
ms_elapsed = ( time . time ( ) - self . _quota_recovery_start_time ) * 1000
if ms_elapsed > s... |
def config_read ( ) :
"""Read config info from config file .""" | config_file = ( u"{0}config.ini" . format ( CONFIG_DIR ) )
if not os . path . isfile ( config_file ) :
config_make ( config_file )
config = configparser . ConfigParser ( allow_no_value = True )
try :
config . read ( config_file , encoding = 'utf-8' )
except IOError :
print ( "Error reading config file: {}" ... |
def _build_ufunc ( func ) :
"""Return a ufunc that works with lazy arrays""" | def larray_compatible_ufunc ( x ) :
if isinstance ( x , larray ) :
y = deepcopy ( x )
y . apply ( func )
return y
else :
return func ( x )
return larray_compatible_ufunc |
def get_context_data ( self , ** kwargs ) :
"""Add the current author in context .""" | context = super ( BaseAuthorDetail , self ) . get_context_data ( ** kwargs )
context [ 'author' ] = self . author
return context |
def main ( ) :
"""NAME
sort _ specimens . py
DESCRIPTION
Reads in a pmag _ specimen formatted file and separates it into different components ( A , B . . . etc . )
SYNTAX
sort _ specimens . py [ - h ] [ command line options ]
INPUT
takes pmag _ specimens . txt formatted input file
OPTIONS
- h : pr... | dir_path = '.'
inspec = "pmag_specimens.txt"
if '-WD' in sys . argv :
ind = sys . argv . index ( '-WD' )
dir_path = sys . argv [ ind + 1 ]
if '-h' in sys . argv :
print ( main . __doc__ )
sys . exit ( )
if '-f' in sys . argv :
ind = sys . argv . index ( '-f' )
inspec = sys . argv [ ind + 1 ]
bas... |
def upgrade ( self , using = None , ** kwargs ) :
"""Upgrade the index to the latest format .
Any additional keyword arguments will be passed to
` ` Elasticsearch . indices . upgrade ` ` unchanged .""" | return self . _get_connection ( using ) . indices . upgrade ( index = self . _name , ** kwargs ) |
def beholder ( func ) :
"""[ ClassMethod ] Behold extraction procedure .""" | @ functools . wraps ( func )
def behold ( self , proto , length , * args , ** kwargs ) :
seek_cur = self . _file . tell ( )
try :
return func ( proto , length , * args , ** kwargs )
except Exception :
from pcapkit . protocols . raw import Raw
error = traceback . format_exc ( limit = ... |
def insert ( self , key , value ) :
"""Insert a key - value pair in the list .
The pair is inserted at the correct location so that the list remains
sorted on * key * . If a pair with the same key is already in the list ,
then the pair is appended after all other pairs with that key .""" | self . _find_lte ( key )
node = self . _create_node ( key , value )
self . _insert ( node ) |
def get_tx_info ( self , tx_ac , alt_ac , alt_aln_method ) :
"""return a single transcript info for supplied accession ( tx _ ac , alt _ ac , alt _ aln _ method ) , or None if not found
: param tx _ ac : transcript accession with version ( e . g . , ' NM _ 000051.3 ' )
: type tx _ ac : str
: param alt _ ac : ... | rows = self . _fetchall ( self . _queries [ 'tx_info' ] , [ tx_ac , alt_ac , alt_aln_method ] )
if len ( rows ) == 0 :
raise HGVSDataNotAvailableError ( "No tx_info for (tx_ac={tx_ac},alt_ac={alt_ac},alt_aln_method={alt_aln_method})" . format ( tx_ac = tx_ac , alt_ac = alt_ac , alt_aln_method = alt_aln_method ) )
e... |
def get_metric_statistics ( self , period , start_time , end_time , metric_name , namespace , statistics , dimensions = None , unit = None ) :
"""Get time - series data for one or more statistics of a given metric .
: type period : integer
: param period : The granularity , in seconds , of the returned datapoin... | params = { 'Period' : period , 'MetricName' : metric_name , 'Namespace' : namespace , 'StartTime' : start_time . isoformat ( ) , 'EndTime' : end_time . isoformat ( ) }
self . build_list_params ( params , statistics , 'Statistics.member.%d' )
if dimensions :
self . build_dimension_param ( dimensions , params )
retur... |
def LockedRead ( self ) :
"""Acquire an interprocess lock and dump cache contents .
This method safely acquires the locks then reads a string
from the cache file . If the file does not exist and cannot
be created , it will return None . If the locks cannot be
acquired , this will also return None .
Return... | file_contents = None
with self . _thread_lock :
if not self . _EnsureFileExists ( ) :
return None
with self . _process_lock_getter ( ) as acquired_plock :
if not acquired_plock :
return None
with open ( self . _filename , 'rb' ) as f :
file_contents = f . read ( )... |
def _generate_ipaddressfield ( self , ** kwargs ) :
"""Currently only IPv4 fields .""" | field = kwargs [ 'field' ]
if field . default != NOT_PROVIDED :
return self . _generate_field_with_default ( ** kwargs )
num_octets = 4
octets = [ str ( random . randint ( 0 , 255 ) ) for n in range ( num_octets ) ]
return '.' . join ( octets ) |
def _pretty_alignment_out_file_name ( self ) :
"""Checks file name is set for pretty alignment output .
Returns absolute path .""" | if self . Parameters [ '-E' ] . isOn ( ) :
pretty_alignment = self . _absolute ( str ( self . Parameters [ '-E' ] . Value ) )
else :
raise ValueError ( "No pretty-=alignment (flag -E) output path specified" )
return pretty_alignment |
def spawn ( self ) :
"""Spawn the fake executable using subprocess . Popen .""" | self . _process = subprocess . Popen ( [ self . path ] , stdout = subprocess . PIPE , stderr = subprocess . STDOUT )
self . addCleanup ( self . _process_kill ) |
def get_list ( key , * default , ** kwargs ) :
"""Return env var as a list .""" | separator = kwargs . get ( 'separator' , ' ' )
return get_env ( key , * default , coerce = lambda x : x . split ( separator ) ) |
def save ( self , * args , ** kwargs ) :
"""* * uid * * : : code : ` { levelcode } `""" | self . slug = slugify ( self . name )
self . uid = self . slug
super ( DivisionLevel , self ) . save ( * args , ** kwargs ) |
def __load ( self ) :
"""Loads dynamically the class that acts like a namespace for constants .""" | parts = self . __class_name . split ( '.' )
module_name = "." . join ( parts [ : - 1 ] )
module = __import__ ( module_name )
modules = [ ]
for comp in parts [ 1 : ] :
module = getattr ( module , comp )
modules . append ( module )
self . __module = modules [ - 2 ] |
async def sendAudio ( self , chat_id , audio , caption = None , parse_mode = None , duration = None , performer = None , title = None , disable_notification = None , reply_to_message_id = None , reply_markup = None ) :
"""See : https : / / core . telegram . org / bots / api # sendaudio
: param audio : Same as ` `... | p = _strip ( locals ( ) , more = [ 'audio' ] )
return await self . _api_request_with_file ( 'sendAudio' , _rectify ( p ) , 'audio' , audio ) |
def _filter_utr ( self , ex ) :
"""Filter out UTR regions from the exon list ( ie retain only coding regions ) .
Coding regions are defined by the thickStart and thickEnd attributes .
Parameters
ex : list of tuples
list of exon positions , [ ( ex1 _ start , ex1 _ end ) , . . . ]
Returns
filtered _ exons... | # define coding region
coding_start = int ( self . bed_tuple . thickStart )
coding_end = int ( self . bed_tuple . thickEnd )
if ( coding_end - coding_start ) < 3 : # coding regions should have at least one codon , otherwise the
# region is invalid and does not indicate an actually coding region
logger . debug ( '{0... |
def create_config ( config_path = "scriptworker.yaml" ) :
"""Create a config from DEFAULT _ CONFIG , arguments , and config file .
Then validate it and freeze it .
Args :
config _ path ( str , optional ) : the path to the config file . Defaults to
" scriptworker . yaml "
Returns :
tuple : ( config froze... | if not os . path . exists ( config_path ) :
print ( "{} doesn't exist! Exiting..." . format ( config_path ) , file = sys . stderr )
sys . exit ( 1 )
with open ( config_path , "r" , encoding = "utf-8" ) as fh :
secrets = safe_load ( fh )
config = dict ( deepcopy ( DEFAULT_CONFIG ) )
if not secrets . get ( "c... |
def is_softener ( self , let ) :
"""Является ли символ смягчающим .
: let : Объект буквы , которую пытаемся смягчить .""" | if let . letter in let . forever_hard :
return False
if not let . is_consonant ( ) :
return False
if self . letter in self . vovels_set_soft :
return True
if self . letter == 'ь' :
return True
if self . is_soft ( ) and ( let . letter in "дзнст" ) :
return True
if self . letter == 'ъ' :
if self .... |
def set_text ( self , val , base64encode = False ) :
"""Sets the text property of this instance .
: param val : The value of the text property
: param base64encode : Whether the value should be base64encoded
: return : The instance""" | # print ( " set _ text : % s " % ( val , ) )
if isinstance ( val , bool ) :
if val :
setattr ( self , "text" , "true" )
else :
setattr ( self , "text" , "false" )
elif isinstance ( val , int ) :
setattr ( self , "text" , "%d" % val )
elif isinstance ( val , six . string_types ) :
setattr... |
def find_max_sum_list ( nested_lists ) :
"""This function returns the sublist from a list of lists that has the maximum sum of its elements .
Examples :
> > > find _ max _ sum _ list ( [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 10 , 11 , 12 ] , [ 7 , 8 , 9 ] ] )
[10 , 11 , 12]
> > > find _ max _ sum _ list ( [ [ 3... | return max ( nested_lists , key = sum ) |
def use_plenary_authorization_view ( self ) :
"""Pass through to provider AuthorizationLookupSession . use _ plenary _ authorization _ view""" | self . _object_views [ 'authorization' ] = PLENARY
# self . _ get _ provider _ session ( ' authorization _ lookup _ session ' ) # To make sure the session is tracked
for session in self . _get_provider_sessions ( ) :
try :
session . use_plenary_authorization_view ( )
except AttributeError :
pass |
def search_artist ( self , artist_name , quiet = False , limit = 9 ) :
"""Search artist by artist name .
: params artist _ name : artist name .
: params quiet : automatically select the best one .
: params limit : artist count returned by weapi .
: return : a Artist object .""" | result = self . search ( artist_name , search_type = 100 , limit = limit )
if result [ 'result' ] [ 'artistCount' ] <= 0 :
LOG . warning ( 'Artist %s not existed!' , artist_name )
raise SearchNotFound ( 'Artist {} not existed.' . format ( artist_name ) )
else :
artists = result [ 'result' ] [ 'artists' ]
... |
def _audio_response_for_run ( self , tensor_events , run , tag , sample ) :
"""Builds a JSON - serializable object with information about audio .
Args :
tensor _ events : A list of image event _ accumulator . TensorEvent objects .
run : The name of the run .
tag : The name of the tag the audio entries all b... | response = [ ]
index = 0
filtered_events = self . _filter_by_sample ( tensor_events , sample )
content_type = self . _get_mime_type ( run , tag )
for ( index , tensor_event ) in enumerate ( filtered_events ) :
data = tensor_util . make_ndarray ( tensor_event . tensor_proto )
label = data [ sample , 1 ]
resp... |
def train_set_producer ( socket , train_archive , patch_archive , wnid_map ) :
"""Load / send images from the training set TAR file or patch images .
Parameters
socket : : class : ` zmq . Socket `
PUSH socket on which to send loaded images .
train _ archive : str or file - like object
Filename or file han... | patch_images = extract_patch_images ( patch_archive , 'train' )
num_patched = 0
with tar_open ( train_archive ) as tar :
for inner_tar_info in tar :
with tar_open ( tar . extractfile ( inner_tar_info . name ) ) as inner :
wnid = inner_tar_info . name . split ( '.' ) [ 0 ]
class_index... |
def get_route ( ip ) :
'''Return routing information for given destination ip
. . versionadded : : 2016.11.5
CLI Example : :
salt ' * ' network . get _ route 10.10.10.10''' | cmd = 'Find-NetRoute -RemoteIPAddress {0}' . format ( ip )
out = __salt__ [ 'cmd.run' ] ( cmd , shell = 'powershell' , python_shell = True )
regexp = re . compile ( r"^IPAddress\s+:\s(?P<source>[\d\.:]+)?.*" r"^InterfaceAlias\s+:\s(?P<interface>[\w\.\:\-\ ]+)?.*" r"^NextHop\s+:\s(?P<gateway>[\d\.:]+)" , flags = re . MU... |
def compile_pattern_list ( self , patterns ) :
'''This compiles a pattern - string or a list of pattern - strings .
Patterns must be a StringType , EOF , TIMEOUT , SRE _ Pattern , or a list of
those . Patterns may also be None which results in an empty list ( you
might do this if waiting for an EOF or TIMEOUT... | if patterns is None :
return [ ]
if not isinstance ( patterns , list ) :
patterns = [ patterns ]
# Allow dot to match \ n
compile_flags = re . DOTALL
if self . ignorecase :
compile_flags = compile_flags | re . IGNORECASE
compiled_pattern_list = [ ]
for idx , p in enumerate ( patterns ) :
if isinstance (... |
def _set_learning_mode ( self , v , load = False ) :
"""Setter method for learning _ mode , mapped from YANG variable / mac _ address _ table / learning _ mode ( enumeration )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ learning _ mode is considered as a private
m... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'conversational' : { 'value' : 1 } } , ) , is_leaf = True , yang_name = "learning-mode" , rest_name = "learning-mode" , parent =... |
def read ( self , handle ) :
'''Read and parse binary header data from a file handle .
This method reads exactly 512 bytes from the beginning of the given file
handle .
Parameters
handle : file handle
The given handle will be reset to 0 using ` seek ` and then 512 bytes
will be read to initialize the at... | handle . seek ( 0 )
( self . parameter_block , magic , self . point_count , self . analog_count , self . first_frame , self . last_frame , self . max_gap , self . scale_factor , self . data_block , self . analog_per_frame , self . frame_rate , _ , self . long_event_labels , self . label_block , _ ) = struct . unpack ( ... |
def spelling_suggestions ( self ) :
"""The list of spelling suggestions per misspelled word .""" | if not self . is_tagged ( WORDS ) :
self . tokenize_words ( )
return [ data [ SUGGESTIONS ] for data in vabamorf . spellcheck ( self . word_texts , suggestions = True ) ] |
def gradient_pred ( model , ref , ref_rc , alt , alt_rc , mutation_positions , out_annotation_all_outputs , output_filter_mask = None , out_annotation = None ) :
"""Gradient - based ( saliency ) variant effect prediction
Based on the idea of [ saliency maps ] ( https : / / arxiv . org / pdf / 1312.6034 . pdf ) th... | seqs = { "ref" : ref , "ref_rc" : ref_rc , "alt" : alt , "alt_rc" : alt_rc }
for k in seqs :
if not isinstance ( seqs [ k ] , ( list , tuple , np . ndarray ) ) :
raise Exception ( "At the moment only models with list, tuple or np.ndarray inputs are supported." )
assert np . all ( [ np . array ( get_seq_len ... |
def _from_bytes ( bytes , byteorder = "big" , signed = False ) :
"""This is the same functionality as ` ` int . from _ bytes ` ` in python 3""" | return int . from_bytes ( bytes , byteorder = byteorder , signed = signed ) |
def blocks ( self , start = None , stop = None ) :
"""Yields blocks starting from ` ` start ` ` .
: param int start : Starting block
: param int stop : Stop at this block
: param str mode : We here have the choice between
* " head " : the last block
* " irreversible " : the block that is confirmed by 2/3 ... | # Let ' s find out how often blocks are generated !
block_interval = self . config ( ) . get ( "STEEMIT_BLOCK_INTERVAL" )
if not start :
start = self . get_current_block_num ( )
# We are going to loop indefinitely
while True : # Get chain properies to identify the
head_block = self . get_current_block_num ( )
... |
async def request ( self , method , path , json = None ) :
"""Make a request to the API .""" | url = 'https://{}:{}/api/' . format ( self . host , self . port )
url += path . format ( site = self . site )
try :
async with self . session . request ( method , url , json = json ) as res :
if res . content_type != 'application/json' :
raise ResponseError ( 'Invalid content type: {}' . format ... |
def select_delta ( dist_post_update , current_iteration , clip_max , clip_min , d , theta , constraint ) :
"""Choose the delta at the scale of distance
between x and perturbed sample .""" | if current_iteration == 1 :
delta = 0.1 * ( clip_max - clip_min )
else :
if constraint == 'l2' :
delta = np . sqrt ( d ) * theta * dist_post_update
elif constraint == 'linf' :
delta = d * theta * dist_post_update
return delta |
def _dash_escape_text ( text : str ) -> str :
"""Add dash ' - ' ( 0x2D ) and space ' ' ( 0x20 ) as prefix on each line
: param text : Text to dash - escape
: return :""" | dash_escaped_text = str ( )
for line in text . splitlines ( True ) : # add dash ' - ' ( 0x2D ) and space ' ' ( 0x20 ) as prefix
dash_escaped_text += DASH_ESCAPE_PREFIX + line
return dash_escaped_text |
def pad_dialogues ( self , dialogues ) :
"""Pad the entire dataset .
This involves adding padding at the end of each sentence , and in the case of
a hierarchical model , it also involves adding padding at the end of each dialogue ,
so that every training sample ( dialogue ) has the same dimension .""" | self . log ( 'info' , 'Padding the dialogues ...' )
return [ self . pad_dialogue ( d ) for d in dialogues ] |
def make_request ( url , method = 'GET' , headers = None , timeout = 30 , ** kwargs ) :
"""A wrapper around requests to set defaults & call raise _ for _ status ( ) .""" | headers = headers or { }
headers [ 'User-Agent' ] = 'treeherder/{}' . format ( settings . SITE_HOSTNAME )
# Work around bug 1305768.
if 'queue.taskcluster.net' in url :
headers [ 'x-taskcluster-skip-cache' ] = 'true'
response = requests . request ( method , url , headers = headers , timeout = timeout , ** kwargs )
... |
def ipv4_generate_random ( total = 100 ) :
"""The generator to produce random , unique IPv4 addresses that are not
defined ( can be looked up using ipwhois ) .
Args :
total ( : obj : ` int ` ) : The total number of IPv4 addresses to generate .
Yields :
str : The next IPv4 address .""" | count = 0
yielded = set ( )
while count < total :
address = str ( IPv4Address ( random . randint ( 0 , 2 ** 32 - 1 ) ) )
if not ipv4_is_defined ( address ) [ 0 ] and address not in yielded :
count += 1
yielded . add ( address )
yield address |
def get_iter_returns ( self , jid , minions , timeout = None , tgt = '*' , tgt_type = 'glob' , expect_minions = False , block = True , ** kwargs ) :
'''Watch the event system and return job data as it comes in
: returns : all of the information for the JID''' | if not isinstance ( minions , set ) :
if isinstance ( minions , six . string_types ) :
minions = set ( [ minions ] )
elif isinstance ( minions , ( list , tuple ) ) :
minions = set ( list ( minions ) )
if timeout is None :
timeout = self . opts [ 'timeout' ]
gather_job_timeout = int ( kwargs ... |
def tocimobj ( type_ , value ) :
"""* * Deprecated : * * Return a CIM object representing the specified value and
type .
This function has been deprecated in pywbem 0.13 . Use
: func : ` ~ pywbem . cimvalue ` instead .
Parameters :
` type _ ` ( : term : ` string ` ) :
The CIM data type name for the CIM ... | if value is None or type_ is None :
return None
if type_ != 'string' and isinstance ( value , six . string_types ) and not value :
return None
# Lists of values
if isinstance ( value , list ) :
return [ tocimobj ( type_ , x ) for x in value ]
# Boolean type
if type_ == 'boolean' :
if isinstance ( value ... |
def export ( self , nidm_version , export_dir ) :
"""Create prov entities and activities .""" | # Create " Cluster definition criteria " entity
if isinstance ( self . connectivity , int ) :
if self . connectivity == 6 :
self . connectivity = NIDM_VOXEL6CONNECTED
elif self . connectivity == 18 :
self . connectivity = NIDM_VOXEL18CONNECTED
elif self . connectivity == 26 :
self . ... |
def _process_file ( self , path ) :
"""Parse and submit the metrics from a file""" | try :
f = open ( path )
for line in f :
self . _process_line ( line )
os . remove ( path )
except IOError as ex :
self . log . error ( "Could not open file `{path}': {error}" . format ( path = path , error = ex . strerror ) ) |
def _read_loop_polling ( self ) :
"""Read packets by polling the Engine . IO server .""" | while self . state == 'connected' :
self . logger . info ( 'Sending polling GET request to ' + self . base_url )
r = self . _send_request ( 'GET' , self . base_url + self . _get_url_timestamp ( ) )
if r is None :
self . logger . warning ( 'Connection refused by the server, aborting' )
self .... |
def set_keyvault_secret ( access_token , vault_uri , secret_name , secret_value ) :
'''Adds a secret to a key vault using the key vault URI .
Creates a new version if the secret already exists .
Args :
access _ token ( str ) : A valid Azure authentication token .
vault _ uri ( str ) : Vault URI e . g . http... | endpoint = '' . join ( [ vault_uri , '/secrets/' , secret_name , '?api-version=' , '7.0' ] )
current_time = datetime . datetime . now ( ) . isoformat ( )
attributes = { 'created' : current_time , 'enabled' : True , 'exp' : None , 'nbf' : None , 'recoveryLevel' : 'Purgeable' , 'updated' : current_time }
secret_body = { ... |
def captureOutput ( func , * args , ** kwargs ) :
"""Runs the specified function and arguments , and returns the
tuple ( stdout , stderr ) as strings .""" | stdout = sys . stdout
sys . stdout = StringIO . StringIO ( )
stderr = sys . stderr
sys . stderr = StringIO . StringIO ( )
try :
func ( * args , ** kwargs )
stdoutOutput = sys . stdout . getvalue ( )
stderrOutput = sys . stderr . getvalue ( )
finally :
sys . stdout . close ( )
sys . stdout = stdout
... |
def ncores_used ( self ) :
"""Returns the number of cores used in this moment .
A core is used if there ' s a job that is running on it .""" | return sum ( task . manager . num_cores for task in self if task . status == task . S_RUN ) |
def updateSeriesAttributes ( request ) :
'''This function handles the filtering of available series classes and seriesteachers when a series
is chosen on the Substitute Teacher reporting form .''' | if request . method == 'POST' and request . POST . get ( 'event' ) :
series_option = request . POST . get ( 'event' ) or None
seriesClasses = EventOccurrence . objects . filter ( event__id = series_option )
seriesTeachers = SeriesTeacher . objects . filter ( event__id = series_option )
else : # Only return ... |
def new ( template , target = None , name = None ) :
"""Function for creating a template script or tool .
: param template : template to be used ; one of TEMPLATES
: param target : type of script / tool to be created
: param name : name of the new script / tool""" | if template not in TEMPLATES :
raise ValueError ( "Template argument must be one of the followings: {}" . format ( ", " . join ( TEMPLATES ) ) )
if target is not None and target not in TARGETS . keys ( ) :
raise ValueError ( "Target argument must be one of the followings: {}" . format ( TARGETS . keys ( ) ) )
n... |
def _is_always_unsatisfied ( self ) :
"""Returns whether this requirement is always unsatisfied
This would happen in cases where we can ' t determine the version
from the filename .""" | # If this is a github sha tarball , then it is always unsatisfied
# because the url has a commit sha in it and not the version
# number .
url = self . _url ( )
if url :
filename = filename_from_url ( url )
if filename . endswith ( ARCHIVE_EXTENSIONS ) :
filename , ext = splitext ( filename )
if ... |
def import_single_vpn_path_to_all_vrfs ( self , vpn_path , path_rts = None ) :
"""Imports * vpn _ path * to qualifying VRF tables .
Import RTs of VRF table is matched with RTs from * vpn4 _ path * and if we
have any common RTs we import the path into VRF .""" | LOG . debug ( 'Importing path %s to qualifying VRFs' , vpn_path )
# If this path has no RTs we are done .
if not path_rts :
LOG . info ( 'Encountered a path with no RTs: %s' , vpn_path )
return
# We match path RTs with all VRFs that are interested in them .
interested_tables = set ( )
# Get route family of VRF ... |
def battery_reported ( self , voltage , rawVoltage ) :
"""Battery reported .""" | self . _update_attribute ( BATTERY_PERCENTAGE_REMAINING , voltage )
self . _update_attribute ( self . BATTERY_VOLTAGE_ATTR , int ( rawVoltage / 100 ) ) |
def get_commands ( mod ) :
"""Find commands from a module""" | import inspect
import types
commands = { }
def check ( c ) :
return ( inspect . isclass ( c ) and issubclass ( c , Command ) and c is not Command and not issubclass ( c , CommandManager ) )
for name in dir ( mod ) :
c = getattr ( mod , name )
if check ( c ) :
commands [ c . name ] = c
return command... |
def tell_sender_to_stop ( self , m ) :
'''send a stop packet ( if we haven ' t sent one in the last second )''' | now = time . time ( )
if now - self . time_last_stop_packet_sent < 1 :
return
if self . log_settings . verbose :
print ( "DFLogger: Sending stop packet" )
self . time_last_stop_packet_sent = now
self . master . mav . remote_log_block_status_send ( m . get_srcSystem ( ) , m . get_srcComponent ( ) , mavutil . mav... |
def calculate_tx_fee ( tx_cost_constants , num_inputs , num_outputs ) :
"""The course grained ( hard - coded value ) of something like 0.0001 BTC works great for standard transactions
( one input , one output ) . However , it will cause a lag in more complex or large transactions . So we calculate the
raw tx fe... | tx_size = calculate_raw_tx_size_with_op_return ( num_inputs , num_outputs )
tx_fee = tx_cost_constants . satoshi_per_byte * tx_size
return max ( tx_fee , tx_cost_constants . get_recommended_fee_coin ( ) ) |
def validate_upload_file ( ctx , opts , owner , repo , filepath , skip_errors ) :
"""Validate parameters for requesting a file upload .""" | filename = click . format_filename ( filepath )
basename = os . path . basename ( filename )
click . echo ( "Checking %(filename)s file upload parameters ... " % { "filename" : click . style ( basename , bold = True ) } , nl = False , )
context_msg = "Failed to validate upload parameters!"
with handle_api_exceptions ( ... |
def __add_token_to_document ( self , token , token_id , connected ) :
"""adds a token to the document graph as a node with the given ID .
Parameters
token : str
the token to be added to the document graph
token _ id : int
the node ID of the token to be added , which must not yet
exist in the document gr... | regex_match = ANNOTATED_ANAPHORA_REGEX . search ( token )
if regex_match : # token is annotated
unannotated_token = regex_match . group ( 'token' )
unicode_token = ensure_unicode ( unannotated_token )
annotation = regex_match . group ( 'annotation' )
anno_type = ANNOTATION_TYPES [ annotation ]
certa... |
def delete ( self , key ) :
"""Adds deletion of the entity with given key to the mutation buffer .
If mutation buffer reaches its capacity then this method commit all pending
mutations from the buffer and emties it .
Args :
key : key of the entity which should be deleted""" | self . _cur_batch . delete ( key )
self . _num_mutations += 1
if self . _num_mutations >= MAX_MUTATIONS_IN_BATCH :
self . commit ( )
self . begin ( ) |
def restore ( self , state ) :
"""Restore the contents of this virtual stream walker .
Args :
state ( dict ) : The previously serialized state .
Raises :
ArgumentError : If the serialized state does not have
a matching selector .""" | reading = state . get ( u'reading' )
if reading is not None :
reading = IOTileReading . FromDict ( reading )
selector = DataStreamSelector . FromString ( state . get ( u'selector' ) )
if self . selector != selector :
raise ArgumentError ( "Attempted to restore a VirtualStreamWalker with a different selector" , ... |
def get_results ( self ) :
"""Returns the segmentation summary data .
This data is normalized , to eliminate differences in what is stored
for different types of segmentation analyses .
The following fields are output :
* has _ template - True if the segmentation found template data .
* has _ complement -... | summary = self . _get_summary_data ( )
if summary is None :
results = { 'has_template' : False , 'has_complement' : False }
else :
results = { }
if 'has_template' in summary :
results [ 'has_template' ] = bool ( summary [ 'has_template' ] )
else :
results [ 'has_template' ] = True if sum... |
def check_ressources ( sess ) :
"""check the Ressources of the Fortinet Controller
all thresholds are currently hard coded . should be fine .""" | # get the data
cpu_value = get_data ( sess , cpu_oid , helper )
memory_value = get_data ( sess , memory_oid , helper )
filesystem_value = get_data ( sess , filesystem_oid , helper )
helper . add_summary ( "Controller Status" )
helper . add_long_output ( "Controller Ressources - CPU: %s%%" % cpu_value )
helper . add_met... |
def name ( self ) :
"""Use the first line of docs string unless name set .""" | if self . _name :
return self . _name
return [ line . strip ( ) for line in self . __doc__ . split ( "\n" ) if line . strip ( ) ] [ 0 ] |
def get_command ( arguments ) :
"""Extract the first argument from arguments parsed by docopt .
: param arguments parsed by docopt :
: return : command""" | return [ k for k , v in arguments . items ( ) if not k . startswith ( '-' ) and v is True ] [ 0 ] |
def get_file_uuid ( fpath , hasher = None , stride = 1 ) :
"""Creates a uuid from the hash of a file""" | if hasher is None :
hasher = hashlib . sha1 ( )
# 20 bytes of output
# hasher = hashlib . sha256 ( ) # 32 bytes of output
# sha1 produces a 20 byte hash
hashbytes_20 = get_file_hash ( fpath , hasher = hasher , stride = stride )
# sha1 produces 20 bytes , but UUID requires 16 bytes
hashbytes_16 = hashbytes_2... |
def to_dict ( self , omit = ( ) ) :
"""Return a ( shallow ) copy of self cast to a dictionary ,
optionally omitting some key / value pairs .""" | result = self . __dict__ . copy ( )
for key in omit :
if key in result :
del result [ key ]
return result |
def dump_tree ( node , name = None , initial_indent = '' , indentation = ' ' , maxline = 120 , maxmerged = 80 , # Runtime optimization
iter_node = iter_node , special = ast . AST , list = list , isinstance = isinstance , type = type , len = len ) :
"""Dumps an AST or similar structure :
- Pretty - prints with ... | def dump ( node , name = None , indent = '' ) :
level = indent + indentation
name = name and name + '=' or ''
values = list ( iter_node ( node ) )
if isinstance ( node , list ) :
prefix , suffix = '%s[' % name , ']'
elif values :
prefix , suffix = '%s%s(' % ( name , type ( node ) . _... |
def find_service_by_type ( self , service_type ) :
"""Get service for a given service type .
: param service _ type : Service type , ServiceType
: return : Service""" | for service in self . _services :
if service_type == service . type :
return service
return None |
def populate ( self , structure , prec = 1e-5 , maxiter = 200 , verbose = False , precond = True , vsym = True ) :
"""Takes a partially populated tensor , and populates the non - zero
entries according to the following procedure , iterated until
the desired convergence ( specified via prec ) is achieved .
1 .... | if precond : # Generate the guess from populated
sops = SpacegroupAnalyzer ( structure ) . get_symmetry_operations ( )
guess = Tensor ( np . zeros ( self . shape ) )
mask = abs ( self ) > prec
guess [ mask ] = self [ mask ]
def merge ( old , new ) :
gmask = np . abs ( old ) > prec
nm... |
def validate ( cls , schema , obj ) :
"""Validate specified JSON object obj with specified schema .
: param schema :
Schema to validate against
: type schema :
: class : ` json _ schema _ validator . schema . Schema `
: param obj :
JSON object to validate
: rtype :
bool
: returns :
True on succe... | if not isinstance ( schema , Schema ) :
raise ValueError ( "schema value {0!r} is not a Schema" " object" . format ( schema ) )
self = cls ( )
self . validate_toplevel ( schema , obj )
return True |
def set_rows ( self , ids ) :
"""Set the rows of the table .""" | # NOTE : make sure we have integers and not np . generic objects .
assert all ( isinstance ( i , int ) for i in ids )
# Determine the sort column and dir to set after the rows .
sort_col , sort_dir = self . current_sort
default_sort_col , default_sort_dir = self . default_sort
sort_col = sort_col or default_sort_col
so... |
def _endLineupsNode ( self , name , content ) :
"""Process the end of a node under xtvd / lineups""" | if name == 'map' :
if not self . _error :
self . _importer . new_mapping ( self . _lineupId , self . _stationId , self . _channel , self . _channelMinor , self . _validFrom , self . _validTo , self . _onAirFrom , self . _onAirTo ) |
def calc_qvr_v1 ( self ) :
"""Calculate the discharge of both outer embankments after
Manning - Strickler .
Required control parameters :
| EKV |
| SKV |
| Gef |
Required flux sequence :
| AVR |
| UVR |
Calculated flux sequence :
| QVR |
Examples :
For appropriate strictly positive values : ... | con = self . parameters . control . fastaccess
flu = self . sequences . fluxes . fastaccess
for i in range ( 2 ) :
if ( flu . avr [ i ] > 0. ) and ( flu . uvr [ i ] > 0. ) :
flu . qvr [ i ] = ( con . ekv [ i ] * con . skv [ i ] * flu . avr [ i ] ** ( 5. / 3. ) / flu . uvr [ i ] ** ( 2. / 3. ) * con . gef **... |
def init_registry_from_json ( mongo , filename , clear_collection = False ) :
"""Initialize a model registry with a list of model definitions that are
stored in a given file in Json format .
Parameters
mongo : scodata . MongoDBFactory
Connector for MongoDB
filename : string
Path to file containing model... | # Read model definition file ( JSON )
with open ( filename , 'r' ) as f :
models = json . load ( f )
init_registry ( mongo , models , clear_collection ) |
def Validate ( self , value , ** _ ) :
"""Validates a python format representation of the value .""" | if isinstance ( value , rdfvalue . RDFString ) : # TODO ( hanuszczak ) : Use ` str ` here .
return Text ( value )
if isinstance ( value , Text ) :
return value
if isinstance ( value , bytes ) :
return value . decode ( "utf-8" )
raise type_info . TypeValueError ( "Not a valid unicode string: %r" % value ) |
def calculate_manual_reading ( basic_data : BasicMeterData ) -> Reading :
"""Calculate the interval between two manual readings""" | t_start = basic_data . previous_register_read_datetime
t_end = basic_data . current_register_read_datetime
read_start = basic_data . previous_register_read
read_end = basic_data . current_register_read
value = basic_data . quantity
uom = basic_data . uom
quality_method = basic_data . current_quality_method
return Readi... |
def iter_tokens ( cls , blob ) :
"""Iterate over tokens found in blob contents
: param blob : Input string with python file contents
: return : token iterator""" | readline_func = io . StringIO ( blob . decode ( 'utf-8' ) ) . readline
return tokenize . generate_tokens ( readline_func ) |
def eagerload_includes ( self , query , qs ) :
"""Use eagerload feature of sqlalchemy to optimize data retrieval for include querystring parameter
: param Query query : sqlalchemy queryset
: param QueryStringManager qs : a querystring manager to retrieve information from url
: return Query : the query with in... | for include in qs . include :
joinload_object = None
if '.' in include :
current_schema = self . resource . schema
for obj in include . split ( '.' ) :
try :
field = get_model_field ( current_schema , obj )
except Exception as e :
raise Inv... |
def get_diaginfo ( diaginfo_file ) :
"""Read an output ' s diaginfo . dat file and parse into a DataFrame for
use in selecting and parsing categories .
Parameters
diaginfo _ file : str
Path to diaginfo . dat
Returns
DataFrame containing the category information .""" | widths = [ rec . width for rec in diag_recs ]
col_names = [ rec . name for rec in diag_recs ]
dtypes = [ rec . type for rec in diag_recs ]
usecols = [ name for name in col_names if not name . startswith ( '-' ) ]
diag_df = pd . read_fwf ( diaginfo_file , widths = widths , names = col_names , dtypes = dtypes , comment =... |
def _get_handler_from_keyword ( self , keyword ) :
'''Gets the Robot Framework handler associated with the given keyword''' | if EXECUTION_CONTEXTS . current is None :
raise RobotNotRunningError ( 'Cannot access execution context' )
return EXECUTION_CONTEXTS . current . get_handler ( keyword ) |
def _display_choices ( self , choices ) :
"""Prints a mapping of numbers to choices and returns the
mapping as a dictionary .""" | print ( "Choose the number of the correct choice:" )
choice_map = { }
for i , choice in enumerate ( choices ) :
i = str ( i )
print ( '{}) {}' . format ( i , format . indent ( choice , ' ' * ( len ( i ) + 2 ) ) . strip ( ) ) )
choice = format . normalize ( choice )
choice_map [ i ] = choice
return choic... |
def regex_match_any ( self , line , codes = None ) :
"""Match any regex .""" | for selector in self . regex_selectors :
for match in selector . regex . finditer ( line ) :
if codes and match . lastindex : # Currently the group name must be ' codes '
try :
disabled_codes = match . group ( 'codes' )
except IndexError :
return True
... |
def get_subscription_attributes ( SubscriptionArn , region = None , key = None , keyid = None , profile = None ) :
'''Returns all of the properties of a subscription .
CLI example : :
salt myminion boto3 _ sns . get _ subscription _ attributes somesubscription region = us - west - 1''' | conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
try :
ret = conn . get_subscription_attributes ( SubscriptionArn = SubscriptionArn )
return ret [ 'Attributes' ]
except botocore . exceptions . ClientError as e :
log . error ( 'Failed to list attributes for SNS subscriptio... |
def margin ( text ) :
r"""Add a margin to both ends of each line in the string .
Example :
> > > margin ( ' line1 \ nline2 ' )
' line1 \ n line2 '""" | lines = str ( text ) . split ( '\n' )
return '\n' . join ( ' {} ' . format ( l ) for l in lines ) |
def postProcessing ( arr , method = 'KW replace + Gauss' , mask = None ) :
'''Post process measured flat field [ arr ] .
Depending on the measurement , different
post processing [ method ] s are beneficial .
The available methods are presented in
K . Bedrich , M . Bokalic et al . :
ELECTROLUMINESCENCE IMA... | assert method in ppMETHODS , 'post processing method (%s) must be one of %s' % ( method , ppMETHODS )
if method == 'POLY replace' :
return polyfit2dGrid ( arr , mask , order = 2 , replace_all = True )
elif method == 'KW replace' :
return function ( arr , mask , replace_all = True )
elif method == 'POLY repair' ... |
def handle_import_error ( caught_exc , name ) :
"""Allow or re - raise an import error .
This is to distinguish between expected and unexpected import errors .
If the module is not found , it simply means the Cython / Fortran speedups
were not built with the package . If the error message is different , e . g... | for template in TEMPLATES :
expected_msg = template . format ( name )
if caught_exc . args == ( expected_msg , ) :
return
raise caught_exc |
def filter_greys_using_image ( image , target ) :
"""Filter out any values in target not in image
: param image : image containing values to appear in filtered image
: param target : the image to filter
: rtype : 2d : class : ` numpy . ndarray ` containing only value in image
and with the same dimensions as... | maskbase = numpy . array ( range ( 256 ) , dtype = numpy . uint8 )
mask = numpy . where ( numpy . in1d ( maskbase , numpy . unique ( image ) ) , maskbase , 0 )
return mask [ target ] |
def show_image ( kwargs , call = None ) :
'''Show the details from Parallels concerning an image''' | if call != 'function' :
raise SaltCloudSystemExit ( 'The show_image function must be called with -f or --function.' )
items = query ( action = 'template' , command = kwargs [ 'image' ] )
if 'error' in items :
return items [ 'error' ]
ret = { }
for item in items :
ret . update ( { item . attrib [ 'name' ] : ... |
def update ( self ) :
"""Update all local variable names to match OnShape .""" | uri = self . parent . uri
script = r"""
function(context, queries) {
return getVariable(context, "measurements");
}
"""
self . res = c . evaluate_featurescript ( uri . as_dict ( ) , script ) |
def is_process_running ( process_name ) :
"""Check if a process with the given name is running .
Args :
( str ) : Process name , e . g . " Sublime Text "
Returns :
( bool ) : True if the process is running""" | is_running = False
# On systems with pgrep , check if the given process is running
if os . path . isfile ( '/usr/bin/pgrep' ) :
dev_null = open ( os . devnull , 'wb' )
returncode = subprocess . call ( [ '/usr/bin/pgrep' , process_name ] , stdout = dev_null )
is_running = bool ( returncode == 0 )
return is_r... |
def make_grid ( xx , yy ) :
"""Returns two n - by - n matrices . The first one contains all the x values
and the second all the y values of a cartesian product between ` xx ` and ` yy ` .""" | n = len ( xx )
xx , yy = np . meshgrid ( xx , yy )
grid = np . array ( [ xx . ravel ( ) , yy . ravel ( ) ] ) . T
x = grid [ : , 0 ] . reshape ( n , n )
y = grid [ : , 1 ] . reshape ( n , n )
return x , y |
def from_dict ( input_dict ) :
"""Instantiate an object of a derived class using the information
in input _ dict ( built by the to _ dict method of the derived class ) .
More specifically , after reading the derived class from input _ dict ,
it calls the method _ build _ from _ input _ dict of the derived cla... | import copy
input_dict = copy . deepcopy ( input_dict )
likelihood_class = input_dict . pop ( 'class' )
input_dict [ "name" ] = str ( input_dict [ "name" ] )
name = input_dict . pop ( 'name' )
import GPy
likelihood_class = eval ( likelihood_class )
return likelihood_class . _build_from_input_dict ( likelihood_class , i... |
def _MessageToJsonObject ( self , message ) :
"""Converts message to an object according to Proto3 JSON Specification .""" | message_descriptor = message . DESCRIPTOR
full_name = message_descriptor . full_name
if _IsWrapperMessage ( message_descriptor ) :
return self . _WrapperMessageToJsonObject ( message )
if full_name in _WKTJSONMETHODS :
return methodcaller ( _WKTJSONMETHODS [ full_name ] [ 0 ] , message ) ( self )
js = { }
retur... |
def pytwis_command_processor ( twis , auth_secret , args ) :
"""Process the parsed command .
Parameters
twis : Pytwis
A Pytwis instance which interacts with the Redis database of the Twitter toy clone .
auth _ secret : str
The authentication secret of a logged - in user .
args :
The parsed command out... | command = args [ pytwis_clt_constants . ARG_COMMAND ]
if command == pytwis_clt_constants . CMD_REGISTER :
succeeded , result = twis . register ( args [ pytwis_clt_constants . ARG_USERNAME ] , args [ pytwis_clt_constants . ARG_PASSWORD ] )
if succeeded :
print ( 'Registered {}' . format ( args [ pytwis_c... |
def hash ( file ) :
"""Hashes file using SHA - 256.
: param file : name of file to be hashed
: type file : str
: rtype : str
: raises check50 . Failure : if ` ` file ` ` does not exist""" | exists ( file )
log ( _ ( "hashing {}..." ) . format ( file ) )
# https : / / stackoverflow . com / a / 22058673
with open ( file , "rb" ) as f :
sha256 = hashlib . sha256 ( )
for block in iter ( lambda : f . read ( 65536 ) , b"" ) :
sha256 . update ( block )
return sha256 . hexdigest ( ) |
def adjust_for_length ( self , key , r , kwargs ) :
"""Converts the response to a string and compares its length to a max
length specified in settings . If the response is too long , an error is
logged , and an abbreviated response is returned instead .""" | length = len ( str ( kwargs ) )
if length > settings . defaults [ "max_detail_length" ] :
self . _log_length_error ( key , length )
r [ "max_detail_length_error" ] = length
return r
return kwargs |
def where ( self , cond , value , other = None , subset = None , ** kwargs ) :
"""Apply a function elementwise , updating the HTML
representation with a style which is selected in
accordance with the return value of a function .
. . versionadded : : 0.21.0
Parameters
cond : callable
` ` cond ` ` should ... | if other is None :
other = ''
return self . applymap ( lambda val : value if cond ( val ) else other , subset = subset , ** kwargs ) |
def bss_eval ( reference_sources , estimated_sources , window = 2 * 44100 , hop = 1.5 * 44100 , compute_permutation = False , filters_len = 512 , framewise_filters = False , bsseval_sources_version = False ) :
"""BSS _ EVAL version 4.
Measurement of the separation quality for estimated source signals
in terms o... | # assuming input is in shape ( nsampl ) or ( nsrc , nsampl )
estimated_sources = np . atleast_3d ( estimated_sources )
reference_sources = np . atleast_3d ( reference_sources )
# validate input
validate ( reference_sources , estimated_sources )
# If empty matrices were supplied , return empty lists ( special case )
if ... |
def gather_sources_and_dependencies ( globs , base_dir = None ) :
"""Scan the given globals for modules and return them as dependencies .""" | experiment_path , main = get_main_file ( globs )
base_dir = base_dir or experiment_path
gather_sources = source_discovery_strategies [ SETTINGS [ 'DISCOVER_SOURCES' ] ]
sources = gather_sources ( globs , base_dir )
if main is not None :
sources . add ( main )
gather_dependencies = dependency_discovery_strategies [ ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.