signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _boto_conn_kwargs ( self ) :
"""Generate keyword arguments for boto3 connection functions .
If ` ` self . account _ id ` ` is defined , this will call
: py : meth : ` ~ . _ get _ sts _ token ` to get STS token credentials using
` boto3 . STS . Client . assume _ role < https : / / boto3 . readthedocs . org... | kwargs = { 'region_name' : self . region }
if self . account_id is not None :
logger . debug ( "Connecting for account %s role '%s' with STS " "(region: %s)" , self . account_id , self . account_role , self . region )
credentials = self . _get_sts_token ( )
kwargs [ 'aws_access_key_id' ] = credentials . acc... |
def fstab_add ( dev , mp , fs , options = None ) :
"""Adds the given device entry to the / etc / fstab file""" | return Fstab . add ( dev , mp , fs , options = options ) |
def map_data ( self , cached = False ) :
'''Create a data map of what to execute on''' | ret = { 'create' : { } }
pmap = self . map_providers_parallel ( cached = cached )
exist = set ( )
defined = set ( )
rendered_map = copy . deepcopy ( self . rendered_map )
for profile_name , nodes in six . iteritems ( rendered_map ) :
if profile_name not in self . opts [ 'profiles' ] :
msg = ( 'The required ... |
def check_uniqueness ( self , * args ) :
"""For a unique index , check if the given args are not used twice
For the parameters , seen BaseIndex . check _ uniqueness""" | self . get_unique_index ( ) . check_uniqueness ( * self . prepare_args ( args , transform = False ) ) |
def set_rgb_color ( self , red , green , blue , effect = EFFECT_SUDDEN , transition_time = MIN_TRANSITION_TIME ) :
"""Set the color of the bulb using rgb code . The bulb must be switched on .
: param red : Red component of the color between 0 and 255
: param green : Green component of the color between 0 and 25... | # Check bulb state
if self . is_off ( ) :
raise Exception ( "set_rgb_color can't be used if the bulb is off. Turn it on first" )
# Input validation
schema = Schema ( { 'red' : All ( int , Range ( min = 0 , max = 255 ) ) , 'green' : All ( int , Range ( min = 0 , max = 255 ) ) , 'blue' : All ( int , Range ( min = 0 ,... |
def corrpix_deform_delta ( area_um , px_um = 0.34 ) :
"""Deformation correction term for pixelation effects
The contour in RT - DC measurements is computed on a
pixelated grid . Due to sampling problems , the measured
deformation is overestimated and must be corrected .
The correction formula is described i... | # A triple - exponential decay can be used to correct for pixelation
# for apparent cell areas between 10 and 1250μm2.
# For 99 different radii between 0.4 μm and 20 μm circular objects were
# simulated on a pixel grid with the pixel resolution of 340 nm / pix . At
# each radius 1000 random starting points were created... |
def iter_fields ( self , schema : Schema ) -> Iterable [ Tuple [ str , Field ] ] :
"""Iterate through marshmallow schema fields .
Generates : name , field pairs""" | for name in sorted ( schema . fields . keys ( ) ) :
field = schema . fields [ name ]
yield field . dump_to or name , field |
def get_fake ( locale = None ) :
"""Return a shared faker factory used to generate fake data""" | if locale is None :
locale = Faker . default_locale
if not hasattr ( Maker , '_fake_' + locale ) :
Faker . _fake = faker . Factory . create ( locale )
return Faker . _fake |
def convert_to_env_data ( mgr , env_paths , validator_func , activate_func , name_template , display_name_template , name_prefix ) :
"""Converts a list of paths to environments to env _ data .
env _ data is a structure { name - > ( ressourcedir , kernel spec ) }""" | env_data = { }
for venv_dir in env_paths :
venv_name = os . path . split ( os . path . abspath ( venv_dir ) ) [ 1 ]
kernel_name = name_template . format ( name_prefix + venv_name )
kernel_name = kernel_name . lower ( )
if kernel_name in env_data :
mgr . log . debug ( "Found duplicate env kernel:... |
def rpc_refactor ( self , filename , method , args ) :
"""Return a list of changes from the refactoring action .
A change is a dictionary describing the change . See
elpy . refactor . translate _ changes for a description .""" | try :
from elpy import refactor
except :
raise ImportError ( "Rope not installed, refactorings unavailable" )
if args is None :
args = ( )
ref = refactor . Refactor ( self . project_root , filename )
return ref . get_changes ( method , * args ) |
def init_from_condition_json ( self , condition_json ) :
"""Init the condition values from a condition json .
: param condition _ json : dict""" | self . name = condition_json [ 'name' ]
self . timelock = condition_json [ 'timelock' ]
self . timeout = condition_json [ 'timeout' ]
self . contract_name = condition_json [ 'contractName' ]
self . function_name = condition_json [ 'functionName' ]
self . parameters = [ Parameter ( p ) for p in condition_json [ 'paramet... |
def render ( self , parsed , page = False , minify = False ) :
"""Render complete markup .
parsed ( list ) : Dependency parses to render .
page ( bool ) : Render parses wrapped as full HTML page .
minify ( bool ) : Minify HTML markup .
RETURNS ( unicode ) : Rendered SVG or HTML markup .""" | # Create a random ID prefix to make sure parses don ' t receive the
# same ID , even if they ' re identical
id_prefix = uuid . uuid4 ( ) . hex
rendered = [ ]
for i , p in enumerate ( parsed ) :
if i == 0 :
settings = p . get ( "settings" , { } )
self . direction = settings . get ( "direction" , DEFA... |
def _format_kwargs ( func ) :
"""Decorator to handle formatting kwargs to the proper names expected by
the associated function . The formats dictionary string keys will be used as
expected function kwargs and the value list of strings will be renamed to
the associated key string .""" | formats = { }
formats [ 'blk' ] = [ "blank" ]
formats [ 'dft' ] = [ "default" ]
formats [ 'hdr' ] = [ "header" ]
formats [ 'hlp' ] = [ "help" ]
formats [ 'msg' ] = [ "message" ]
formats [ 'shw' ] = [ "show" ]
formats [ 'vld' ] = [ "valid" ]
@ wraps ( func )
def inner ( * args , ** kwargs ) :
for k in formats . keys... |
def __vciFormatError ( library_instance , function , HRESULT ) :
"""Format a VCI error and attach failed function and decoded HRESULT
: param CLibrary library _ instance :
Mapped instance of IXXAT vcinpl library
: param callable function :
Failed function
: param HRESULT HRESULT :
HRESULT returned by vc... | buf = ctypes . create_string_buffer ( constants . VCI_MAX_ERRSTRLEN )
ctypes . memset ( buf , 0 , constants . VCI_MAX_ERRSTRLEN )
library_instance . vciFormatError ( HRESULT , buf , constants . VCI_MAX_ERRSTRLEN )
return "function {} failed ({})" . format ( function . _name , buf . value . decode ( 'utf-8' , 'replace' ... |
def main ( ) :
"""The command line interface for the ` ` pip - accel ` ` program .""" | arguments = sys . argv [ 1 : ]
# If no arguments are given , the help text of pip - accel is printed .
if not arguments :
usage ( )
sys . exit ( 0 )
# If no install subcommand is given we pass the command line straight
# to pip without any changes and exit immediately afterwards .
if 'install' not in arguments ... |
def _update ( self , ** kwargs ) :
"""Use separate URL for updating the source file .""" | if 'content' in kwargs :
content = kwargs . pop ( 'content' )
path = self . _construct_path_to_source_content ( )
self . _http . put ( path , json . dumps ( { 'content' : content } ) )
super ( Resource , self ) . _update ( ** kwargs ) |
def put_files ( self , files , content_type = None , compress = None , cache_control = None , block = True ) :
"""Put lots of files at once and get a nice progress bar . It ' ll also wait
for the upload to complete , just like get _ files .
Required :
files : [ ( filepath , content ) , . . . . ]""" | for path , content in tqdm ( files , disable = ( not self . progress ) , desc = "Uploading" ) :
content = compression . compress ( content , method = compress )
self . _interface . put_file ( path , content , content_type , compress , cache_control = cache_control )
return self |
def get_host_lock ( url ) :
"""Get lock object for given URL host .""" | hostname = get_hostname ( url )
return host_locks . setdefault ( hostname , threading . Lock ( ) ) |
def state_dict ( self ) -> Dict [ str , Any ] :
"""Returns the state of the scheduler as a ` ` dict ` ` .""" | return { key : value for key , value in self . __dict__ . items ( ) if key != 'optimizer' } |
def log_response ( self , response ) :
"""Helper method provided to enable the logging of responses in case if
the : attr : ` HttpProtocol . access _ log ` is enabled .
: param response : Response generated for the current request
: type response : : class : ` sanic . response . HTTPResponse ` or
: class : ... | if self . access_log :
extra = { "status" : getattr ( response , "status" , 0 ) }
if isinstance ( response , HTTPResponse ) :
extra [ "byte" ] = len ( response . body )
else :
extra [ "byte" ] = - 1
extra [ "host" ] = "UNKNOWN"
if self . request is not None :
if self . reques... |
def rows ( self , min_x = None , min_y = None , max_x = None , max_y = None ) :
"""Returns a list of the current : class : ` Canvas ` object lines .
: param min _ x : ( optional ) minimum x coordinate of the canvas
: param min _ y : ( optional ) minimum y coordinate of the canvas
: param max _ x : ( optional ... | if not self . chars . keys ( ) :
return [ ]
minrow = min_y // 4 if min_y != None else min ( self . chars . keys ( ) )
maxrow = ( max_y - 1 ) // 4 if max_y != None else max ( self . chars . keys ( ) )
mincol = min_x // 2 if min_x != None else min ( min ( x . keys ( ) ) for x in self . chars . values ( ) )
maxcol = (... |
def skimage_sinogram_space ( geometry , volume_space , sinogram_space ) :
"""Create a range adapted to the skimage radon geometry .""" | padded_size = int ( np . ceil ( volume_space . shape [ 0 ] * np . sqrt ( 2 ) ) )
det_width = volume_space . domain . extent [ 0 ] * np . sqrt ( 2 )
skimage_detector_part = uniform_partition ( - det_width / 2.0 , det_width / 2.0 , padded_size )
skimage_range_part = geometry . motion_partition . insert ( 1 , skimage_dete... |
def inception_v3_arg_scope ( weight_decay = 0.00004 , stddev = 0.1 , batch_norm_var_collection = 'moving_vars' ) :
"""Defines the default InceptionV3 arg scope .
Args :
weight _ decay : The weight decay to use for regularizing the model .
stddev : The standard deviation of the trunctated normal weight initial... | batch_norm_params = { # Decay for the moving averages .
'decay' : 0.9997 , # epsilon to prevent 0s in variance .
'epsilon' : 0.001 , # collection containing update _ ops .
'updates_collections' : tf . GraphKeys . UPDATE_OPS , # collection containing the moving mean and moving variance .
'variables_collections' : { 'bet... |
def _mirror_groups ( self ) :
"""Mirrors the user ' s LDAP groups in the Django database and updates the
user ' s membership .""" | target_group_names = frozenset ( self . _get_groups ( ) . get_group_names ( ) )
current_group_names = frozenset ( self . _user . groups . values_list ( 'name' , flat = True ) . iterator ( ) )
if target_group_names != current_group_names :
existing_groups = list ( Group . objects . filter ( name__in = target_group_n... |
def get_object_class ( object_type , vendor_id = 0 ) :
"""Return the class associated with an object type .""" | if _debug :
get_object_class . _debug ( "get_object_class %r vendor_id=%r" , object_type , vendor_id )
# find the klass as given
cls = registered_object_types . get ( ( object_type , vendor_id ) )
if _debug :
get_object_class . _debug ( " - direct lookup: %s" , repr ( cls ) )
# if the class isn ' t found and... |
def show ( request , pollId ) :
"""Show a poll . We send informations about votes only if the user is an administrator""" | # Get the poll
curDB . execute ( 'SELECT id, title, description FROM Poll WHERE id = ? ORDER BY title' , ( pollId , ) )
poll = curDB . fetchone ( )
if poll is None :
return { }
responses = [ ]
totalVotes = 0
votedFor = 0
# Compute the list of responses
curDB . execute ( 'SELECT id, title FROM Response WHERE pollId ... |
def toggle_sensor ( request , sensorname ) :
"""This is used only if websocket fails""" | if service . read_only :
service . logger . warning ( "Could not perform operation: read only mode enabled" )
raise Http404
source = request . GET . get ( 'source' , 'main' )
sensor = service . system . namespace [ sensorname ]
sensor . status = not sensor . status
service . system . flush ( )
return HttpRespon... |
def list_servers ( backend , socket = DEFAULT_SOCKET_URL , objectify = False ) :
'''List servers in haproxy backend .
backend
haproxy backend
socket
haproxy stats socket , default ` ` / var / run / haproxy . sock ` `
CLI Example :
. . code - block : : bash
salt ' * ' haproxy . list _ servers mysql''' | ha_conn = _get_conn ( socket )
ha_cmd = haproxy . cmds . listServers ( backend = backend )
return ha_conn . sendCmd ( ha_cmd , objectify = objectify ) |
def run_serial ( target , jobs , n = 1 , ** kwargs ) :
"""Evaluate the given function with each set of arguments , and return a list of results .
This function does in series .
Parameters
target : function
A function to be evaluated . The function must accepts three arguments ,
which are a list of argumen... | return [ [ target ( copy . copy ( job ) , i + 1 , j + 1 ) for j in range ( n ) ] for i , job in enumerate ( jobs ) ] |
def a_send_password ( password , ctx ) :
"""Send the password text .
Before sending the password local echo is disabled .
If password not provided it disconnects from the device and raises ConnectionAuthenticationError exception .""" | if password :
ctx . ctrl . send_command ( password , password = True )
return True
else :
ctx . ctrl . disconnect ( )
raise ConnectionAuthenticationError ( "Password not provided" , ctx . ctrl . hostname ) |
def InitHttp ( api_endpoint = None , page_size = None , auth = None , proxies = None , verify = None , cert = None , trust_env = True ) :
"""Inits an GRR API object with a HTTP connector .""" | connector = http_connector . HttpConnector ( api_endpoint = api_endpoint , page_size = page_size , auth = auth , proxies = proxies , verify = verify , cert = cert , trust_env = trust_env )
return GrrApi ( connector = connector ) |
async def message_fields ( self , msg , fields ) :
"""Load / dump individual message fields
: param msg :
: param fields :
: param field _ archiver :
: return :""" | for field in fields :
try :
self . tracker . push_field ( field [ 0 ] )
await self . message_field ( msg , field )
self . tracker . pop ( )
except Exception as e :
raise helpers . ArchiveException ( e , tracker = self . tracker ) from e
return msg |
def fake2db_mysql_initiator ( self , host , port , password , username , number_of_rows , name = None , custom = None ) :
'''Main handler for the operation''' | rows = number_of_rows
if name :
cursor , conn = self . database_caller_creator ( host , port , password , username , name )
else :
cursor , conn = self . database_caller_creator ( host , port , password , username )
if custom :
self . custom_db_creator ( rows , cursor , conn , custom )
cursor . close ( ... |
def create ( request ) :
"""Create a new poll""" | errors = [ ]
success = False
listOfResponses = [ '' , '' , '' ]
# 3 Blank lines by default
title = ''
description = ''
id = ''
if request . method == 'POST' : # User saved the form
# Retrieve parameters
title = request . form . get ( 'title' )
description = request . form . get ( 'description' )
listOfRespo... |
def rvs ( self , size = 1 , iteration = 1 ) :
"""Sample the random variable , using the preallocated samples if
possible .
Parameters
size : int
The number of samples to generate .
iteration : int
The location in the preallocated sample array to start sampling
from .
Returns
: obj : ` numpy . ndar... | if self . num_prealloc_samples_ > 0 :
samples = [ ]
for i in range ( size ) :
samples . append ( self . prealloc_samples_ [ ( iteration + i ) % self . num_prealloc_samples_ ] )
if size == 1 :
return samples [ 0 ]
return samples
# generate a new sample
return self . sample ( size = size ) |
def update ( self ) :
"""Update reviewers ' anomalous scores and products ' summaries .
Returns :
maximum absolute difference between old summary and new one , and
old anomalous score and new one .""" | w = self . _weight_generator ( self . reviewers )
diff_p = max ( p . update_summary ( w ) for p in self . products )
diff_a = max ( r . update_anomalous_score ( ) for r in self . reviewers )
return max ( diff_p , diff_a ) |
def create_manifest ( self , cart_name , manifests ) :
"""` cart _ name ` - Name of this release cart
` manifests ` - a list of manifest files""" | cart = juicer . common . Cart . Cart ( cart_name )
for manifest in manifests :
cart . add_from_manifest ( manifest , self . connectors )
cart . save ( )
return cart |
def execute ( self , env , args ) :
"""Creates a new task .
` env `
Runtime ` ` Environment ` ` instance .
` args `
Arguments object from arg parser .""" | task_name = args . task_name
clone_task = args . clone_task
if not env . task . create ( task_name , clone_task ) :
raise errors . FocusError ( u'Could not create task "{0}"' . format ( task_name ) )
# open in task config in editor
if not args . skip_edit :
task_config = env . task . get_config_path ( task_name... |
def listMigrationRequests ( self , migration_request_id = "" , block_name = "" , dataset = "" , user = "" , oldest = False ) :
"""get the status of the migration
migratee : can be dataset or block _ name""" | conn = self . dbi . connection ( )
migratee = ""
try :
if block_name :
migratee = block_name
elif dataset :
migratee = dataset
result = self . mgrlist . execute ( conn , migration_url = "" , migration_input = migratee , create_by = user , migration_request_id = migration_request_id , oldest ... |
def OpenChildren ( self , children = None , mode = "r" , limit = None , chunk_limit = 100000 , age = NEWEST_TIME ) :
"""Yields AFF4 Objects of all our direct children .
This method efficiently returns all attributes for our children directly , in
a few data store round trips . We use the directory indexes to qu... | if children is None : # No age passed here to avoid ignoring indexes that were updated
# to a timestamp greater than the object ' s age .
subjects = list ( self . ListChildren ( ) )
else :
subjects = list ( children )
subjects . sort ( )
result_count = 0
# Read at most limit children at a time .
while subjects ... |
def from_list ( cls , l ) :
"""Return a Point instance from a given list""" | if len ( l ) == 3 :
x , y , z = map ( float , l )
return cls ( x , y , z )
elif len ( l ) == 2 :
x , y = map ( float , l )
return cls ( x , y )
else :
raise AttributeError |
def _async_tqdm ( * args , ** kwargs ) :
"""Wrapper around Tqdm which can be updated in threads .
Usage :
with utils . async _ tqdm ( . . . ) as pbar :
# pbar can then be modified inside a thread
# pbar . update _ total ( 3)
# pbar . update ( )
Args :
* args : args of tqdm
* * kwargs : kwargs of tqd... | with tqdm_lib . tqdm ( * args , ** kwargs ) as pbar :
pbar = _TqdmPbarAsync ( pbar )
yield pbar
pbar . clear ( )
# pop pbar from the active list of pbar
print ( ) |
def get_rows ( self ) :
"""Attempt to load the statistic from the database .
: return : Number of entries for the statistic""" | rows = [ ]
if check_table_exists ( self . tracker . dbcon_master , self . name ) :
rows . extend ( get_rows ( self . tracker . dbcon_master , self . name ) )
if self . tracker . dbcon_part and check_table_exists ( self . tracker . dbcon_part , self . name ) :
rows . extend ( get_rows ( self . tracker . dbcon_pa... |
def _collapse_cursor ( self , parts ) :
"""Act on any CursorMoveUp commands by deleting preceding tokens""" | final_parts = [ ]
for part in parts : # Throw out empty string tokens ( " " )
if not part :
continue
# Go back , deleting every token in the last ' line '
if part == CursorMoveUp :
if final_parts :
final_parts . pop ( )
while final_parts and '\n' not in final_parts [ - 1 ... |
def get_tool_context ( self , tool_alias ) :
"""Given a visible tool alias , return the name of the context it
belongs to .
Args :
tool _ alias ( str ) : Tool alias to search for .
Returns :
( str ) : Name of the context that exposes a visible instance of this
tool alias , or None if the alias is not av... | tools_dict = self . get_tools ( )
data = tools_dict . get ( tool_alias )
if data :
return data [ "context_name" ]
return None |
def load_from_arpa_str ( self , arpa_str ) :
"""Initialize N - gram model by reading an ARPA language model string .
Parameters
arpa _ str : str
A string in ARPA language model file format""" | data_found = False
end_found = False
in_ngram_block = 0
for i , line in enumerate ( arpa_str . split ( "\n" ) ) :
if not end_found :
if not data_found :
if "\\data\\" in line :
data_found = True
else :
if in_ngram_block == 0 :
if line . startsw... |
def _SerializeEntries ( entries ) :
"""Serializes given triplets of python and wire values and a descriptor .""" | output = [ ]
for python_format , wire_format , type_descriptor in entries :
if wire_format is None or ( python_format and type_descriptor . IsDirty ( python_format ) ) :
wire_format = type_descriptor . ConvertToWireFormat ( python_format )
precondition . AssertIterableType ( wire_format , bytes )
ou... |
def generate_rst_docs ( directory , classes , missing_objects = None ) :
"""Generate documentation for tri . declarative APIs
: param directory : directory to write the . rst files into
: param classes : list of classes to generate documentation for
: param missing _ objects : tuple of objects to count as mis... | doc_by_filename = _generate_rst_docs ( classes = classes , missing_objects = missing_objects )
# pragma : no mutate
for filename , doc in doc_by_filename : # pragma : no mutate
with open ( directory + filename , 'w' ) as f2 : # pragma : no mutate
f2 . write ( doc ) |
def estimate_bitstring_probs ( results ) :
"""Given an array of single shot results estimate the probability distribution over all bitstrings .
: param np . array results : A 2d array where the outer axis iterates over shots
and the inner axis over bits .
: return : An array with as many axes as there are qub... | nshots , nq = np . shape ( results )
outcomes = np . array ( [ int ( "" . join ( map ( str , r ) ) , 2 ) for r in results ] )
probs = np . histogram ( outcomes , bins = np . arange ( - .5 , 2 ** nq , 1 ) ) [ 0 ] / float ( nshots )
return _bitstring_probs_by_qubit ( probs ) |
def replace_certificate_signing_request_status ( self , name , body , ** kwargs ) : # noqa : E501
"""replace _ certificate _ signing _ request _ status # noqa : E501
replace status of the specified CertificateSigningRequest # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asy... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . replace_certificate_signing_request_status_with_http_info ( name , body , ** kwargs )
# noqa : E501
else :
( data ) = self . replace_certificate_signing_request_status_with_http_info ( name , body , ** kwargs )
# ... |
def inceptionv3 ( num_classes = 1000 , pretrained = 'imagenet' ) :
r"""Inception v3 model architecture from
` " Rethinking the Inception Architecture for Computer Vision " < http : / / arxiv . org / abs / 1512.00567 > ` _ .""" | model = models . inception_v3 ( pretrained = False )
if pretrained is not None :
settings = pretrained_settings [ 'inceptionv3' ] [ pretrained ]
model = load_pretrained ( model , num_classes , settings )
# Modify attributs
model . last_linear = model . fc
del model . fc
def features ( self , input ) : # 299 x 2... |
def coverage ( self ) :
"""Get the fraction of a subject is matched by its set of reads .
@ return : The C { float } fraction of a subject matched by its reads .""" | if self . _targetLength == 0 :
return 0.0
coverage = 0
for ( intervalType , ( start , end ) ) in self . walk ( ) :
if intervalType == self . FULL : # Adjust start and end to ignore areas where the read falls
# outside the target .
coverage += ( min ( end , self . _targetLength ) - max ( 0 , start ) ... |
def __rename_directory ( self , source , target ) :
"""Renames a directory using given source and target names .
: param source : Source file .
: type source : unicode
: param target : Target file .
: type target : unicode""" | for node in itertools . chain ( self . __script_editor . model . get_project_nodes ( source ) , self . __script_editor . model . get_directory_nodes ( source ) ) :
self . __script_editor . model . unregister_project_nodes ( node )
self . __script_editor . unregister_node_path ( node )
self . __rename_path (... |
def store ( self , value , ptr , align = None ) :
"""Store value to pointer , with optional guaranteed alignment :
* ptr = name""" | if not isinstance ( ptr . type , types . PointerType ) :
raise TypeError ( "cannot store to value of type %s (%r): not a pointer" % ( ptr . type , str ( ptr ) ) )
if ptr . type . pointee != value . type :
raise TypeError ( "cannot store %s to %s: mismatching types" % ( value . type , ptr . type ) )
st = instruc... |
def get_process_path ( tshark_path = None , process_name = "tshark" ) :
"""Finds the path of the tshark executable . If the user has provided a path
or specified a location in config . ini it will be used . Otherwise default
locations will be searched .
: param tshark _ path : Path of the tshark binary
: ra... | config = get_config ( )
possible_paths = [ config . get ( process_name , "%s_path" % process_name ) ]
# Add the user provided path to the search list
if tshark_path is not None :
possible_paths . insert ( 0 , tshark_path )
# Windows search order : configuration file ' s path , common paths .
if sys . platform . sta... |
def _patch_expand_paths ( self , settings , name , value ) :
"""Apply ` ` SettingsPostProcessor . _ patch _ expand _ path ` ` to each element in
list .
Args :
settings ( dict ) : Current settings .
name ( str ) : Setting name .
value ( list ) : List of paths to patch .
Returns :
list : Patched path li... | return [ self . _patch_expand_path ( settings , name , item ) for item in value ] |
def _deserialize ( self , value , environment = None ) :
"""A collection traverses over something to deserialize its value .""" | if not isinstance ( value , CollectionABC ) :
raise exc . Invalid ( self )
items_class = self . items . __class__
invalids = [ ]
# traverse items and match against validated struct
collection = self . collection_type ( )
for i , subvalue in enumerate ( value ) :
item = items_class ( name = i )
try :
... |
def modify_area ( self , pid , xmin , xmax , zmin , zmax , value ) :
"""Modify the given dataset in the rectangular area given by the
parameters and assign all parameters inside this area the given value .
Partially contained elements are treated as INSIDE the area , i . e . , they
are assigned new values .
... | area_polygon = shapgeo . Polygon ( ( ( xmin , zmax ) , ( xmax , zmax ) , ( xmax , zmin ) , ( xmin , zmin ) ) )
self . modify_polygon ( pid , area_polygon , value ) |
def main ( args ) :
'''For command line experimentation . Sample output :
$ python l2cs . py ' foo : bar AND baz : bork '
Lucene input : foo : bar AND baz : bork
Parsed representation : And ( [ Term ( u ' foo ' , u ' bar ' ) , Term ( u ' baz ' , u ' bork ' ) ] )
Lucene form : ( foo : bar AND baz : bork )
... | args = [ unicode ( u , 'utf-8' ) for u in args [ 1 : ] ]
schema = __sample_schema ( ) if "--schema" in args else None
if schema :
args . pop ( args . index ( "--schema" ) )
query = u' ' . join ( args )
print "Lucene input:" , query
parser = __sample_parser ( schema = schema )
parsed = parser . parse ( query )
print... |
def get_uplink_dvportgroup ( dvs_ref ) :
'''Returns the uplink distributed virtual portgroup of a distributed virtual
switch ( dvs )
dvs _ ref
The dvs reference''' | dvs_name = get_managed_object_name ( dvs_ref )
log . trace ( 'Retrieving uplink portgroup of dvs \'%s\'' , dvs_name )
traversal_spec = vmodl . query . PropertyCollector . TraversalSpec ( path = 'portgroup' , skip = False , type = vim . DistributedVirtualSwitch )
service_instance = get_service_instance_from_managed_obje... |
def parse ( cls , fptr , offset = 0 , length = 0 ) :
"""Parse a codestream box .
Parameters
fptr : file
Open file object .
offset : int
Start position of box in bytes .
length : int
Length of the box in bytes .
Returns
ContiguousCodestreamBox
Instance of the current contiguous codestream box .""... | main_header_offset = fptr . tell ( )
if config . get_option ( 'parse.full_codestream' ) :
codestream = Codestream ( fptr , length , header_only = False )
else :
codestream = None
box = cls ( codestream , main_header_offset = main_header_offset , length = length , offset = offset )
box . _filename = fptr . name
... |
def plot_eigh2 ( self , colorbar = True , cb_orientation = 'vertical' , cb_label = None , ax = None , show = True , fname = None , ** kwargs ) :
"""Plot the second eigenvalue of the horizontal tensor .
Usage
x . plot _ eigh2 ( [ tick _ interval , xlabel , ylabel , ax , colorbar ,
cb _ orientation , cb _ label... | if cb_label is None :
cb_label = self . _eigh2_label
if self . eigh2 is None :
self . compute_eigh ( )
if ax is None :
fig , axes = self . eigh2 . plot ( colorbar = colorbar , cb_orientation = cb_orientation , cb_label = cb_label , show = False , ** kwargs )
if show :
fig . show ( )
if fname... |
def _body_builder ( self , kwargs ) :
"""Helper method to construct the appropriate SOAP - body to call a
FritzBox - Service .""" | p = { 'action_name' : self . name , 'service_type' : self . service_type , 'arguments' : '' , }
if kwargs :
arguments = [ self . argument_template % { 'name' : k , 'value' : v } for k , v in kwargs . items ( ) ]
p [ 'arguments' ] = '' . join ( arguments )
body = self . body_template . strip ( ) % p
return body |
def Serialize ( self , writer ) :
"""Serialize object .
Args :
writer ( neo . IO . BinaryWriter ) :""" | writer . WriteHashes ( self . HashStart )
if self . HashStop is not None :
writer . WriteUInt256 ( self . HashStop ) |
def create_example ( self , workspace_id , intent , text , mentions = None , ** kwargs ) :
"""Create user input example .
Add a new user input example to an intent .
This operation is limited to 1000 requests per 30 minutes . For more information ,
see * * Rate limiting * * .
: param str workspace _ id : Un... | if workspace_id is None :
raise ValueError ( 'workspace_id must be provided' )
if intent is None :
raise ValueError ( 'intent must be provided' )
if text is None :
raise ValueError ( 'text must be provided' )
if mentions is not None :
mentions = [ self . _convert_model ( x , Mention ) for x in mentions ... |
def blockdiag_parser ( preprocessor , tag , markup ) :
"""Blockdiag parser""" | m = DOT_BLOCK_RE . search ( markup )
if m : # Get diagram type and code
diagram = m . group ( 'diagram' ) . strip ( )
code = markup
# Run command
output = diag ( code , diagram )
if output : # Return Base64 encoded image
return '<span class="blockdiag" style="align: center;"><img src="data:i... |
def _parse_patterns ( self , pattern ) :
"""Parse patterns .""" | self . pattern = [ ]
self . npatterns = None
npattern = [ ]
for p in pattern :
if _wcparse . is_negative ( p , self . flags ) : # Treat the inverse pattern as a normal pattern if it matches , we will exclude .
# This is faster as compiled patterns usually compare the include patterns first ,
# and then the ... |
def get_chunk ( self , x , z ) :
"""Return a chunk specified by the chunk coordinates x , z . Raise InconceivedChunk
if the chunk is not yet generated . To get the raw NBT data , use get _ nbt .""" | return self . chunkclass ( self . get_nbt ( x , z ) ) |
def name_match ( self , elt ) :
'''Simple boolean test to see if we match the element name .
Parameters :
elt - - the DOM element being parsed''' | return self . pname == elt . localName and self . nspname in [ None , '' , elt . namespaceURI ] |
def prj_view_user ( self , * args , ** kwargs ) :
"""View the , in the user table view selected , user .
: returns : None
: rtype : None
: raises : None""" | if not self . cur_prj :
return
i = self . prj_user_tablev . currentIndex ( )
item = i . internalPointer ( )
if item :
user = item . internal_data ( )
self . view_user ( user ) |
def __isValidFilename ( self , filename ) :
"""Determine whether filename is valid""" | if filename and isinstance ( filename , string_types ) :
if re . match ( r'^[\w\d\_\-\.]+$' , filename , re . I ) :
if self . __isValidTGZ ( filename ) or self . __isValidZIP ( filename ) :
return True
return False |
def __set_type ( self , stats , sensor_type ) :
"""Set the plugin type .
4 types of stats is possible in the sensors plugin :
- Core temperature : ' temperature _ core '
- Fan speed : ' fan _ speed '
- HDD temperature : ' temperature _ hdd '
- Battery capacity : ' battery '""" | for i in stats : # Set the sensors type
i . update ( { 'type' : sensor_type } )
# also add the key name
i . update ( { 'key' : self . get_key ( ) } )
return stats |
def get_river_index ( self , river_id ) :
"""This method retrieves the river index in the netCDF
dataset corresponding to the river ID .
Parameters
river _ id : int
The ID of the river segment .
Returns
int :
The index of the river ID ' s in the file .
Example : :
from RAPIDpy import RAPIDDataset ... | try :
return np . where ( self . get_river_id_array ( ) == river_id ) [ 0 ] [ 0 ]
except IndexError :
raise IndexError ( "ERROR: River ID {0} not found in dataset " "..." . format ( river_id ) ) |
def datetimeAt ( self , x ) :
"""Returns the datetime at the inputed x position .
: return < QDateTime >""" | gantt = self . ganttWidget ( )
dstart = gantt . dateTimeStart ( )
distance = int ( x / float ( gantt . cellWidth ( ) ) )
# calculate the time for a minute
if scale == gantt . Timescale . Minute :
return dstart . addSecs ( distance )
# calculate the time for an hour
elif scale == gantt . Timescale . Hour :
retur... |
def df2unstack ( df , coln = 'columns' , idxn = 'index' , col = 'value' ) :
"""will be deprecated""" | return dmap2lin ( df , idxn = idxn , coln = coln , colvalue_name = col ) |
def dump_memory_map ( memoryMap , mappedFilenames = None , bits = None ) :
"""Dump the memory map of a process . Optionally show the filenames for
memory mapped files as well .
@ type memoryMap : list ( L { win32 . MemoryBasicInformation } )
@ param memoryMap : Memory map returned by L { Process . get _ memor... | if not memoryMap :
return ''
table = Table ( )
if mappedFilenames :
table . addRow ( "Address" , "Size" , "State" , "Access" , "Type" , "File" )
else :
table . addRow ( "Address" , "Size" , "State" , "Access" , "Type" )
# For each memory block in the map . . .
for mbi in memoryMap : # Address and size of me... |
def get_index ( cls , model , via_class = False ) :
'''Returns the index name ( as a string ) for the given model as a class or a string .
: param model : model name or model class if via _ class set to True .
: param via _ class : set to True if parameter model is a class .
: raise KeyError : If the provided... | try :
return cls . _model_to_index [ model ] if via_class else cls . _model_name_to_index [ model ]
except KeyError :
raise KeyError ( 'Could not find any index defined for model {}. Is the model in one of the model index modules of BUNGIESEARCH["INDICES"]?' . format ( model ) ) |
def create_network ( self , name , admin_state_up = True , router_ext = None , network_type = None , physical_network = None , segmentation_id = None , shared = None , vlan_transparent = None ) :
'''Creates a new network''' | body = { 'name' : name , 'admin_state_up' : admin_state_up }
if router_ext :
body [ 'router:external' ] = router_ext
if network_type :
body [ 'provider:network_type' ] = network_type
if physical_network :
body [ 'provider:physical_network' ] = physical_network
if segmentation_id :
body [ 'provider:segme... |
def _parse_output_keys ( val ) :
"""Parse expected output keys from string , handling records .""" | out = { }
for k in val . split ( "," ) : # record output
if ":" in k :
name , attrs = k . split ( ":" )
out [ name ] = attrs . split ( ";" )
else :
out [ k ] = None
return out |
def get_related_coref_relationships ( self , content_id , min_strength = None ) :
'''Follow coreference relationships to get full related graph .
: rtype : dict mapping related identifier to list of documents
coref to that identifier .''' | related_labels = self . rel_label_store . get_related ( content_id , min_strength = min_strength )
related_cids = [ rel_label . other ( content_id ) for rel_label in related_labels ]
related_cid_to_idents = { }
for cid in related_cids :
conn_labels = self . label_store . directly_connected ( cid )
idents = [ la... |
def set_credentials ( self , client_id = None , client_secret = None ) :
"""set given credentials and reset the session""" | self . _client_id = client_id
self . _client_secret = client_secret
# make sure to reset session due to credential change
self . _session = None |
def plot_s_bcr ( fignum , Bcr , S , sym ) :
"""function to plot Squareness , Coercivity of remanence
Parameters
_ _ _ _ _
fignum : matplotlib figure number
Bcr : list or array coercivity of remenence values
S : list or array of ratio of saturation remanence to saturation
sym : matplotlib symbol ( e . g ... | plt . figure ( num = fignum )
plt . plot ( Bcr , S , sym )
plt . xlabel ( 'Bcr' )
plt . ylabel ( 'Mr/Ms' )
plt . title ( 'Squareness-Bcr Plot' )
bounds = plt . axis ( )
plt . axis ( [ 0 , bounds [ 1 ] , 0 , 1 ] ) |
def check_restructuredtext ( self ) :
"""Checks if the long string fields are reST - compliant .""" | # Warn that this command is deprecated
# Don ' t use self . warn ( ) because it will cause the check to fail .
Command . warn ( self , "This command has been deprecated. Use `twine check` instead: " "https://packaging.python.org/guides/making-a-pypi-friendly-readme" "#validating-restructuredtext-markup" )
data = self .... |
def send_event_to_salt ( self , result ) :
'''This function identifies whether the engine is running on the master
or the minion and sends the data to the master event bus accordingly .
: param result : It ' s a dictionary which has the final data and topic .''' | if result [ 'send' ] :
data = result [ 'data' ]
topic = result [ 'topic' ]
# If the engine is run on master , get the event bus and send the
# parsed event .
if __opts__ [ '__role' ] == 'master' :
event . get_master_event ( __opts__ , __opts__ [ 'sock_dir' ] ) . fire_event ( data , topic )
... |
def is_dynamic ( * p ) : # TODO : Explain this better
"""True if all args are dynamic ( e . g . Strings , dynamic arrays , etc )
The use a ptr ( ref ) and it might change during runtime .""" | from symbols . type_ import Type
try :
for i in p :
if i . scope == SCOPE . global_ and i . is_basic and i . type_ != Type . string :
return False
return True
except :
pass
return False |
def connect ( self , host_or_hosts , port_or_ports = 7051 , rpc_timeout = None , admin_timeout = None , ) :
"""Pass - through connection interface to the Kudu client
Parameters
host _ or _ hosts : string or list of strings
If you have multiple Kudu masters for HA , pass a list
port _ or _ ports : int or lis... | self . client = kudu . connect ( host_or_hosts , port_or_ports , rpc_timeout_ms = rpc_timeout , admin_timeout_ms = admin_timeout , ) |
def resize_droplet ( self , droplet_id , size ) :
"""This method allows you to resize a specific droplet to a different size .
This will affect the number of processors and memory allocated to the droplet .
Required parameters :
droplet _ id :
Integer , this is the id of your droplet that you want to resize... | if not droplet_id :
raise DOPException ( 'droplet_id is required to resize a droplet!' )
params = { }
size_id = size . get ( 'size_id' )
if size_id :
params . update ( { 'size_id' : size_id } )
else :
size_slug = size . get ( 'size_slug' )
if size_slug :
params . update ( { 'size_slug' : size_sl... |
def get_xpath ( self , node , type = Tag . XPATH , instance = True ) :
'''get _ xpath
High - level api : Given a config or schema node , get _ xpath returns an
xpath of the node , which starts from the model root . Each identifier
uses the ` prefix : tagname ` notation if argument ' type ' is not specified . ... | return Composer ( self , node ) . get_xpath ( type , instance = instance ) |
def device_configuration ( self , pending = False , use_included = False ) :
"""Get a specific device configuration .
A device can have at most one loaded and one pending device
configuration . This returns that device _ configuration based on
a given flag .
Keyword Args :
pending ( bool ) : Fetch the pen... | device_configs = self . device_configurations ( use_included = use_included )
for device_config in device_configs :
if device_config . is_loaded ( ) is not pending :
return device_config
return None |
def add_repo_to_team ( self , auth , team_id , repo_name ) :
"""Add or update repo from team .
: param auth . Authentication auth : authentication object , must be admin - level
: param str team _ id : Team ' s id
: param str repo _ name : Name of the repo to be added to the team
: raises NetworkFailure : i... | url = "/admin/teams/{t}/repos/{r}" . format ( t = team_id , r = repo_name )
self . put ( url , auth = auth ) |
def filename_match ( filename ) :
"""Check if options . filename contains a pattern that matches filename .
If options . filename is unspecified , this always returns True .""" | if not options . filename :
return True
for pattern in options . filename :
if fnmatch ( filename , pattern ) :
return True |
def associate_hosting_device_with_config_agent ( self , client , config_agent_id , body ) :
"""Associates a hosting _ device with a config agent .""" | return client . post ( ( ConfigAgentHandlingHostingDevice . resource_path + CFG_AGENT_HOSTING_DEVICES ) % config_agent_id , body = body ) |
def namespace ( self , mid : ModuleId ) -> YangIdentifier :
"""Return the namespace corresponding to a module or submodule .
Args :
mid : Module identifier .
Raises :
ModuleNotRegistered : If ` mid ` is not registered in the data model .""" | try :
mdata = self . modules [ mid ]
except KeyError :
raise ModuleNotRegistered ( * mid ) from None
return mdata . main_module [ 0 ] |
def show_summary ( self , ** kwargs ) :
"""Print a short summary with the status of the flow and a counter task _ status - - > number _ of _ tasks
Args :
stream : File - like object , Default : sys . stdout
Example :
Status Count
Completed 10
< Flow , node _ id = 27163 , workdir = flow _ gwconv _ ecutep... | stream = kwargs . pop ( "stream" , sys . stdout )
stream . write ( "\n" )
table = list ( self . status_counter . items ( ) )
s = tabulate ( table , headers = [ "Status" , "Count" ] )
stream . write ( s + "\n" )
stream . write ( "\n" )
stream . write ( "%s, num_tasks=%s, all_ok=%s\n" % ( str ( self ) , self . num_tasks ... |
def calculate_hamming_distance ( num1 : int , num2 : int ) -> int :
"""This Python function computes the Hamming distance between two provided integers .
Examples :
> > > calculate _ hamming _ distance ( 4 , 8)
> > > calculate _ hamming _ distance ( 2 , 4)
> > > calculate _ hamming _ distance ( 1 , 2)
Arg... | bitwise_xor = num1 ^ num2
hamming_dist = 0
while bitwise_xor > 0 :
hamming_dist += bitwise_xor & 1
bitwise_xor >>= 1
return hamming_dist |
def get_for_objects ( self , queryset ) :
"""Get log entries for the objects in the specified queryset .
: param queryset : The queryset to get the log entries for .
: type queryset : QuerySet
: return : The LogAction objects for the objects in the given queryset .
: rtype : QuerySet""" | if not isinstance ( queryset , QuerySet ) or queryset . count ( ) == 0 :
return self . none ( )
content_type = ContentType . objects . get_for_model ( queryset . model )
primary_keys = queryset . values_list ( queryset . model . _meta . pk . name , flat = True )
if isinstance ( primary_keys [ 0 ] , integer_types ) ... |
def paintEvent ( self , event ) :
"""Overloads the paint event to support rendering of hints if there are
no items in the tree .
: param event | < QPaintEvent >""" | super ( XTextEdit , self ) . paintEvent ( event )
if self . document ( ) . isEmpty ( ) and self . hint ( ) :
text = self . hint ( )
rect = self . rect ( )
# modify the padding on the rect
rect . setX ( 4 )
rect . setY ( 4 )
align = int ( Qt . AlignLeft | Qt . AlignTop )
# setup the coloring ... |
def diff ( self , n = 1 ) :
"""Differentiate ( n - th derivative , where the default n is 1 ) .""" | d = self . _data
for unused in xrange ( n ) :
d = OrderedDict ( ( k - 1 , k * v ) for k , v in iteritems ( d ) if k != 0 )
return Poly ( d , zero = self . zero ) |
def api2_formula ( req ) :
"""A simple ` GET ` - , URL - based API to OpenFisca , making the assumption of computing formulas for a single person .
Combination
You can compute several formulas at once by combining the paths and joining them with ` + ` .
Example :
/ salaire _ super _ brut + salaire _ net _ a... | API_VERSION = '2.1.0'
wsgihelpers . track ( req . url . decode ( 'utf-8' ) )
params = dict ( req . GET )
data = dict ( )
try :
extensions_header = req . headers . get ( 'X-Openfisca-Extensions' )
tax_benefit_system = model . get_cached_composed_reform ( reform_keys = extensions_header . split ( ',' ) , tax_bene... |
def blt ( f : List [ SYM ] , x : List [ SYM ] ) -> Dict [ str , Any ] :
"""Sort equations by dependence""" | J = ca . jacobian ( f , x )
nblock , rowperm , colperm , rowblock , colblock , coarserow , coarsecol = J . sparsity ( ) . btf ( )
return { 'J' : J , 'nblock' : nblock , 'rowperm' : rowperm , 'colperm' : colperm , 'rowblock' : rowblock , 'colblock' : colblock , 'coarserow' : coarserow , 'coarsecol' : coarsecol } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.