signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def register_on_guest_mouse ( self , callback ) :
"""Set the callback function to consume on guest mouse events .
Callback receives a IGuestMouseEvent object .
Example :
def callback ( event ) :
print ( ( " % s % s % s " % ( event . x , event . y , event . z ) )""" | event_type = library . VBoxEventType . on_guest_mouse
return self . event_source . register_callback ( callback , event_type ) |
def init_model_based_tags ( self , model ) :
"""Initializing the model based memory and NIC information tags .
It should be called just after instantiating a RIBCL object .
ribcl = ribcl . RIBCLOperations ( host , login , password , timeout ,
port , cacert = cacert )
model = ribcl . get _ product _ name ( )... | self . model = model
if 'G7' in self . model :
self . MEMORY_SIZE_TAG = "MEMORY_SIZE"
self . MEMORY_SIZE_NOT_PRESENT_TAG = "Not Installed"
self . NIC_INFORMATION_TAG = "NIC_INFOMATION"
else :
self . MEMORY_SIZE_TAG = "TOTAL_MEMORY_SIZE"
self . MEMORY_SIZE_NOT_PRESENT_TAG = "N/A"
self . NIC_INFOR... |
def update_case_task ( self , task ) :
""": Updates TheHive Task
: param case : The task to update . The task ' s ` id ` determines which Task to update .
: return :""" | req = self . url + "/api/case/task/{}" . format ( task . id )
# Choose which attributes to send
update_keys = [ 'title' , 'description' , 'status' , 'order' , 'user' , 'owner' , 'flag' , 'endDate' ]
data = { k : v for k , v in task . __dict__ . items ( ) if k in update_keys }
try :
return requests . patch ( req , h... |
def extract_examples_from_readme_rst ( indent = ' ' ) :
"""Extract examples from this project ' s README . rst file .
Parameters
indent : str
Prepend each line with this string . Should contain some number of spaces .
Returns
str
The examples .
Notes
Quite fragile , depends on named labels inside... | curr_dir = os . path . dirname ( os . path . abspath ( __file__ ) )
readme_path = os . path . join ( curr_dir , '..' , 'README.rst' )
try :
with open ( readme_path ) as fin :
lines = list ( fin )
start = lines . index ( '.. _doctools_before_examples:\n' )
end = lines . index ( ".. _doctools_after_ex... |
def warn ( callingClass , astr_key , ** kwargs ) :
'''Convenience dispatcher to the error _ exit ( ) method .
Will raise " warning " error , i . e . script processing continues .''' | kwargs [ 'exitToOS' ] = False
report ( callingClass , astr_key , ** kwargs ) |
def removeStepListener ( listener ) :
"""removeStepListener ( traci . StepListener ) - > bool
Remove the step listener from traci ' s step listener container .
Returns True if the listener was removed successfully , False if it wasn ' t registered .""" | if listener in _stepListeners :
_stepListeners . remove ( listener )
return True
warnings . warn ( "removeStepListener(listener): listener %s not registered as step listener" % str ( listener ) )
return False |
def deserialize ( self , serialized ) :
'''Deserialize a JSON macaroon depending on the format .
@ param serialized the macaroon in JSON format .
@ return the macaroon object .''' | deserialized = json . loads ( serialized )
if deserialized . get ( 'identifier' ) is None :
return self . _deserialize_v2 ( deserialized )
else :
return self . _deserialize_v1 ( deserialized ) |
def listen ( self ) :
'''Listen for events as they come in''' | try :
self . _pubsub . subscribe ( self . _channels )
for message in self . _pubsub . listen ( ) :
if message [ 'type' ] == 'message' :
yield message
finally :
self . _channels = [ ] |
def populate_translation_fields ( sender , kwargs ) :
"""When models are created or loaded from fixtures , replicates values
provided for translatable fields to some / all empty translation fields ,
according to the current population mode .
Population is performed only on keys ( field names ) present in kwar... | populate = mt_settings . AUTO_POPULATE
if not populate :
return
if populate is True : # What was meant by ` ` True ` ` is now called ` ` all ` ` .
populate = 'all'
opts = translator . get_options_for_model ( sender )
for key , val in list ( kwargs . items ( ) ) :
if key in opts . fields :
if populat... |
def generate_package_content ( self , package ) :
"""Generate package . rst text content .
{ { package _ name } }
. . automodule : : { { package _ name } }
: members :
sub packages and modules
. . toctree : :
: maxdepth : 1
{ { sub _ package _ name1 } } < { { sub _ package _ name1 } } / _ _ init _ _ >... | if isinstance ( package , Package ) :
return package . render ( ignored_package = self . ignored_package )
else : # pragma : no cover
raise Exception ( "%r is not a Package object" % package ) |
def robust_single_linkage ( X , cut , k = 5 , alpha = 1.4142135623730951 , gamma = 5 , metric = 'euclidean' , algorithm = 'best' , memory = Memory ( cachedir = None , verbose = 0 ) , leaf_size = 40 , core_dist_n_jobs = 4 , ** kwargs ) :
"""Perform robust single linkage clustering from a vector array
or distance m... | if not isinstance ( k , int ) or k < 1 :
raise ValueError ( 'k must be an integer greater than zero!' )
if not isinstance ( alpha , float ) or alpha < 1.0 :
raise ValueError ( 'alpha must be a float greater than or equal to 1.0!' )
if not isinstance ( gamma , int ) or gamma < 1 :
raise ValueError ( 'gamma m... |
def _fix_up ( self , cls , code_name ) :
"""Internal helper called to tell the property its name .
This is called by _ fix _ up _ properties ( ) which is called by
MetaModel when finishing the construction of a Model subclass .
The name passed in is the name of the class attribute to which the
Property is a... | self . _code_name = code_name
if self . _name is None :
self . _name = code_name |
def _search_inasafe_layer ( self ) :
"""Search for an inasafe layer in an active group .
: returns : A valid layer .
: rtype : QgsMapLayer
. . versionadded : : 4.3""" | selected_nodes = self . iface . layerTreeView ( ) . selectedNodes ( )
for selected_node in selected_nodes :
tree_layers = [ child for child in selected_node . children ( ) if ( isinstance ( child , QgsLayerTreeLayer ) ) ]
for tree_layer in tree_layers :
layer = tree_layer . layer ( )
keywords = ... |
def parse_mark_duplicate_metrics ( fn ) :
"""Parse the output from Picard ' s MarkDuplicates and return as pandas
Series .
Parameters
filename : str of filename or file handle
Filename of the Picard output you want to parse .
Returns
metrics : pandas . Series
Duplicate metrics .
hist : pandas . Seri... | with open ( fn ) as f :
lines = [ x . strip ( ) . split ( '\t' ) for x in f . readlines ( ) ]
metrics = pd . Series ( lines [ 7 ] , lines [ 6 ] )
m = pd . to_numeric ( metrics [ metrics . index [ 1 : ] ] )
metrics [ m . index ] = m . values
vals = np . array ( lines [ 11 : - 1 ] )
hist = pd . Series ( vals [ : , 1 ... |
def verify_resource_dict ( res_dict , is_create , attr_info ) :
"""Verifies required attributes are in resource dictionary , res _ dict .
Also checking that an attribute is only specified if it is allowed
for the given operation ( create / update ) .
Attribute with default values are considered to be optional... | if ( ( bc . NEUTRON_VERSION >= bc . NEUTRON_NEWTON_VERSION ) and 'tenant_id' in res_dict ) :
res_dict [ 'project_id' ] = res_dict [ 'tenant_id' ]
if is_create : # POST
for attr , attr_vals in six . iteritems ( attr_info ) :
if attr_vals [ 'allow_post' ] :
if 'default' not in attr_vals and at... |
def nhanesi ( display = False ) :
"""A nicely packaged version of NHANES I data with surivival times as labels .""" | X = pd . read_csv ( cache ( github_data_url + "NHANESI_subset_X.csv" ) )
y = pd . read_csv ( cache ( github_data_url + "NHANESI_subset_y.csv" ) ) [ "y" ]
if display :
X_display = X . copy ( )
X_display [ "Sex" ] = [ "Male" if v == 1 else "Female" for v in X [ "Sex" ] ]
return X_display , np . array ( y )
el... |
def convert_config_value ( self , value , label ) :
"""Converts all ' Truthy ' values to True and ' Falsy ' values to False .
Args :
value : Value to convert
label : Label of the config which this item was found .
Returns :""" | if isinstance ( value , six . string_types ) :
value = value . lower ( )
if value in self . TRUTHY_VALUES :
return True
elif value in self . FALSY_VALUES :
return False
else :
raise YapconfValueError ( "Cowardly refusing to interpret " "config value as a boolean. Name: " "{0}, Value: {1}" . format ( sel... |
def stop_tuning_job ( self , name ) :
"""Stop the Amazon SageMaker hyperparameter tuning job with the specified name .
Args :
name ( str ) : Name of the Amazon SageMaker hyperparameter tuning job .
Raises :
ClientError : If an error occurs while trying to stop the hyperparameter tuning job .""" | try :
LOGGER . info ( 'Stopping tuning job: {}' . format ( name ) )
self . sagemaker_client . stop_hyper_parameter_tuning_job ( HyperParameterTuningJobName = name )
except ClientError as e :
error_code = e . response [ 'Error' ] [ 'Code' ]
# allow to pass if the job already stopped
if error_code == ... |
def parse ( self ) :
"""parse data""" | url = self . config . get ( 'url' )
self . cnml = CNMLParser ( url )
self . parsed_data = self . cnml . getNodes ( ) |
def p_propertyDeclaration_4 ( p ) :
"""propertyDeclaration _ 4 : dataType propertyName array defaultValue ' ; '""" | p [ 0 ] = CIMProperty ( p [ 2 ] , p [ 4 ] , type = p [ 1 ] , is_array = True , array_size = p [ 3 ] ) |
def emergency ( self ) :
'''Sends the emergency command .''' | self . send ( at . REF ( at . REF . input . select ) ) |
def main_loop ( self , timeout = None ) :
"""Check if self . trigger _ event is set . If it is , then run our function . If not , return early .
: param timeout : How long to wait for a trigger event . Defaults to 0.
: return :""" | if self . trigger_event . wait ( timeout ) :
try :
self . func ( )
except Exception as e :
self . logger . warning ( "Got an exception running {func}: {e}" . format ( func = self . func , e = str ( e ) ) )
finally :
self . trigger_event . clear ( ) |
def convert_frame ( frame , body_encoding = None ) :
"""Convert a frame to a list of lines separated by newlines .
: param Frame frame : the Frame object to convert
: rtype : list ( str )""" | lines = [ ]
body = None
if frame . body :
if body_encoding :
body = encode ( frame . body , body_encoding )
else :
body = encode ( frame . body )
if HDR_CONTENT_LENGTH in frame . headers :
frame . headers [ HDR_CONTENT_LENGTH ] = len ( body )
if frame . cmd :
lines . append ( enc... |
def post_processor_affected_function ( exposure = None , hazard = None , classification = None , hazard_class = None ) :
"""Private function used in the affected postprocessor .
It returns a boolean if it ' s affected or not , or not exposed .
: param exposure : The exposure to use .
: type exposure : str
:... | if exposure == exposure_population [ 'key' ] :
affected = is_affected ( hazard , classification , hazard_class )
else :
classes = None
for hazard in hazard_classes_all :
if hazard [ 'key' ] == classification :
classes = hazard [ 'classes' ]
break
for the_class in classes ... |
def _write_to_datastore ( self ) :
"""Writes all submissions to datastore .""" | # Populate datastore
roots_and_submissions = zip ( [ ATTACKS_ENTITY_KEY , TARGET_ATTACKS_ENTITY_KEY , DEFENSES_ENTITY_KEY ] , [ self . _attacks , self . _targeted_attacks , self . _defenses ] )
client = self . _datastore_client
with client . no_transact_batch ( ) as batch :
for root_key , submissions in roots_and_s... |
def create_api_docs ( code_path , api_docs_path , max_depth = 2 ) :
"""Function for generating . rst file for all . py file in dir _ path folder .
: param code _ path : Path of the source code .
: type code _ path : str
: param api _ docs _ path : Path of the api documentation directory .
: type api _ docs ... | base_path = os . path . split ( code_path ) [ 0 ]
for package , subpackages , candidate_files in os . walk ( code_path ) : # Checking _ _ init _ _ . py file
if '__init__.py' not in candidate_files :
continue
# Creating directory for the package
package_relative_path = package . replace ( base_path +... |
def get_surface_boundaries ( self ) :
""": returns : ( min _ max lons , min _ max lats )""" | min_lon , min_lat , max_lon , max_lat = self . get_bounding_box ( )
return [ [ min_lon , max_lon ] ] , [ [ min_lat , max_lat ] ] |
def metrics ( self , name ) :
"""Return the metrics received under the given name""" | return [ MetricStub ( ensure_unicode ( stub . name ) , stub . type , stub . value , normalize_tags ( stub . tags ) , ensure_unicode ( stub . hostname ) , ) for stub in self . _metrics . get ( to_string ( name ) , [ ] ) ] |
def from_hive_file ( cls , fname , * args , ** kwargs ) :
"""Open a local JSON hive file and initialize from the hive contained
in that file , paying attention to the version keyword argument .""" | version = kwargs . pop ( 'version' , None )
require = kwargs . pop ( 'require_https' , True )
return cls ( Hive . from_file ( fname , version , require ) , * args , ** kwargs ) |
def ls ( sess_id_or_alias , path ) :
"""List files in a path of a running container .
SESSID : Session ID or its alias given when creating the session .
PATH : Path inside container .""" | with Session ( ) as session :
try :
print_wait ( 'Retrieving list of files in "{}"...' . format ( path ) )
kernel = session . Kernel ( sess_id_or_alias )
result = kernel . list_files ( path )
if 'errors' in result and result [ 'errors' ] :
print_fail ( result [ 'errors' ]... |
def setHint ( self , hint ) :
"""Sets the hint for this filepath .
: param hint | < str >""" | if self . normalizePath ( ) :
filepath = os . path . normpath ( nativestring ( hint ) )
else :
filepath = os . path . normpath ( nativestring ( hint ) ) . replace ( '\\' , '/' )
self . _filepathEdit . setHint ( hint ) |
def load_and_migrate ( ) -> Dict [ str , Path ] :
"""Ensure the settings directory tree is properly configured .
This function does most of its work on the actual robot . It will move
all settings files from wherever they happen to be to the proper
place . On non - robots , this mostly just loads . In additio... | if IS_ROBOT :
_migrate_robot ( )
base = infer_config_base_dir ( )
base . mkdir ( parents = True , exist_ok = True )
index = _load_with_overrides ( base )
return _ensure_paths_and_types ( index ) |
def _draw ( self ) :
"""Call the drawing API for the main menu widget with the current known
terminal size and the terminal .""" | self . _window . draw ( self . _width , self . _height , self . terminal ) |
def configure ( self , graph , spanning_tree ) :
"""Configure the filter .
@ type graph : graph
@ param graph : Graph .
@ type spanning _ tree : dictionary
@ param spanning _ tree : Spanning tree .""" | self . graph = graph
self . spanning_tree = spanning_tree |
def apply_patch ( document , patch ) :
"""Apply a Patch object to a document .""" | # pylint : disable = too - many - return - statements
op = patch . op
parent , idx = resolve_path ( document , patch . path )
if op == "add" :
return add ( parent , idx , patch . value )
elif op == "remove" :
return remove ( parent , idx )
elif op == "replace" :
return replace ( parent , idx , patch . value... |
def _read_ftdna_famfinder ( file ) :
"""Read and parse Family Tree DNA ( FTDNA ) " famfinder " file .
https : / / www . familytreedna . com
Parameters
file : str
path to file
Returns
pandas . DataFrame
individual ' s genetic data normalized for use with ` lineage `
str
name of data source""" | df = pd . read_csv ( file , comment = "#" , na_values = "-" , names = [ "rsid" , "chrom" , "pos" , "allele1" , "allele2" ] , index_col = 0 , dtype = { "chrom" : object } , )
# create genotype column from allele columns
df [ "genotype" ] = df [ "allele1" ] + df [ "allele2" ]
# delete allele columns
# http : / / stackove... |
def libvlc_media_list_player_play_item ( p_mlp , p_md ) :
'''Play the given media item .
@ param p _ mlp : media list player instance .
@ param p _ md : the media instance .
@ return : 0 upon success , - 1 if the media is not part of the media list .''' | f = _Cfunctions . get ( 'libvlc_media_list_player_play_item' , None ) or _Cfunction ( 'libvlc_media_list_player_play_item' , ( ( 1 , ) , ( 1 , ) , ) , None , ctypes . c_int , MediaListPlayer , Media )
return f ( p_mlp , p_md ) |
def _get_list ( self , key , operation , create = False ) :
"""Get ( and maybe create ) a list by name .""" | return self . _get_by_type ( key , operation , create , b'list' , [ ] ) |
def __ipv4_netmask ( value ) :
'''validate an IPv4 dotted quad or integer CIDR netmask''' | valid , errmsg = False , 'dotted quad or integer CIDR (0->32)'
valid , value , _ = __int ( value )
if not ( valid and 0 <= value <= 32 ) :
valid = salt . utils . validate . net . netmask ( value )
return ( valid , value , errmsg ) |
def __split_name ( self , name ) :
u"""Разделяет имя на сегменты по разделителям в self . separators
: param name : имя
: return : разделённое имя вместе с разделителями""" | def gen ( name , separators ) :
if len ( separators ) == 0 :
yield name
else :
segments = name . split ( separators [ 0 ] )
for subsegment in gen ( segments [ 0 ] , separators [ 1 : ] ) :
yield subsegment
for segment in segments [ 1 : ] :
for subsegment in... |
def generate_snapshot ( self , prov_dep ) : # type : ( MutableMapping [ Text , Any ] ) - > None
"""Copy all of the CWL files to the snapshot / directory .""" | self . self_check ( )
for key , value in prov_dep . items ( ) :
if key == "location" and value . split ( "/" ) [ - 1 ] :
filename = value . split ( "/" ) [ - 1 ]
path = os . path . join ( self . folder , SNAPSHOT , filename )
filepath = ''
if "file://" in value :
filepath... |
def add_comment ( node , text , location = 'above' ) :
"""Add a comment to the given node .
If the ` SourceWithCommentGenerator ` class is used these comments will be
output as part of the source code .
Note that a node can only contain one comment . Subsequent calls to
` add _ comment ` will ovverride the ... | anno . setanno ( node , 'comment' , dict ( location = location , text = text ) , safe = False )
return node |
def differential_pressure_meter_dP ( D , D2 , P1 , P2 , C = None , meter_type = ISO_5167_ORIFICE ) :
r'''Calculates either the non - recoverable pressure drop of a differential
pressure flow meter based on the geometry of the meter , measured pressures
of the meter , and for most models the meter discharge coef... | if meter_type == ISO_5167_ORIFICE :
dP = dP_orifice ( D = D , Do = D2 , P1 = P1 , P2 = P2 , C = C )
elif meter_type == LONG_RADIUS_NOZZLE :
dP = dP_orifice ( D = D , Do = D2 , P1 = P1 , P2 = P2 , C = C )
elif meter_type == ISA_1932_NOZZLE :
dP = dP_orifice ( D = D , Do = D2 , P1 = P1 , P2 = P2 , C = C )
eli... |
def consume_file ( self , filename ) :
"""Counts all kmers in all sequences in a FASTA / FASTQ file .""" | with screed . open ( filename ) as sequences :
for seq in sequences :
self . consume ( seq [ 'sequence' ] ) |
def set_xlimits ( self , min = None , max = None ) :
"""Set limits for the x - axis .
: param min : minimum value to be displayed . If None , it will be
calculated .
: param max : maximum value to be displayed . If None , it will be
calculated .""" | self . limits [ 'xmin' ] = min
self . limits [ 'xmax' ] = max |
def append_from_json ( self , json_string ) :
"""Creates a ` ` measurement . Measurement ` ` object from the supplied JSON string
and then appends it to the buffer
: param json _ string : the JSON formatted string""" | a_dict = json . loads ( json_string )
self . append_from_dict ( a_dict ) |
def _create_latent_variables ( self ) :
"""Creates model latent variables
Returns
None ( changes model attributes )""" | self . latent_variables . add_z ( 'Vol Constant' , fam . Normal ( 0 , 3 , transform = None ) , fam . Normal ( 0 , 3 ) )
for p_term in range ( self . p ) :
self . latent_variables . add_z ( 'p(' + str ( p_term + 1 ) + ')' , fam . Normal ( 0 , 0.5 , transform = 'logit' ) , fam . Normal ( 0 , 3 ) )
if p_term == 0 ... |
def get_objective_form_for_create ( self , objective_record_types ) :
"""Gets the objective form for creating new objectives .
A new form should be requested for each create transaction .
arg : objective _ record _ types ( osid . type . Type [ ] ) : array of
objective record types
return : ( osid . learning... | # Implemented from template for
# osid . resource . ResourceAdminSession . get _ resource _ form _ for _ create _ template
for arg in objective_record_types :
if not isinstance ( arg , ABCType ) :
raise errors . InvalidArgument ( 'one or more argument array elements is not a valid OSID Type' )
if objective_... |
def _syllabify ( word ) :
'''Syllabify the given word .''' | word = replace_umlauts ( word )
word , CONTINUE_VV , CONTINUE_VVV , applied_rules = apply_T1 ( word )
if CONTINUE_VV :
word , T2 = apply_T2 ( word )
word , T4 = apply_T4 ( word )
applied_rules += T2 + T4
if CONTINUE_VVV :
word , T5 = apply_T5 ( word )
word , T6 = apply_T6 ( word )
word , T7 = ap... |
def calc_transform ( src , dst_crs = None , resolution = None , dimensions = None , src_bounds = None , dst_bounds = None , target_aligned_pixels = False ) :
"""Output dimensions and transform for a reprojection .
Parameters
src : rasterio . io . DatasetReader
Data source .
dst _ crs : rasterio . crs . CRS ... | if resolution is not None :
if isinstance ( resolution , ( float , int ) ) :
resolution = ( float ( resolution ) , float ( resolution ) )
if target_aligned_pixels :
if not resolution :
raise ValueError ( 'target_aligned_pixels cannot be used without resolution' )
if src_bounds or dst_bounds ... |
def lineage ( expr , container = Stack ) :
"""Yield the path of the expression tree that comprises a column
expression .
Parameters
expr : Expr
An ibis expression . It must be an instance of
: class : ` ibis . expr . types . ColumnExpr ` .
container : Container , { Stack , Queue }
Stack for depth - fi... | if not isinstance ( expr , ir . ColumnExpr ) :
raise TypeError ( 'Input expression must be an instance of ColumnExpr' )
c = container ( [ ( expr , expr . _name ) ] )
seen = set ( )
# while we haven ' t visited everything
while c :
node , name = c . get ( )
if node not in seen :
seen . add ( node )
... |
def create_new_sticker_set ( self , user_id , name , title , png_sticker , emojis , contains_masks = None , mask_position = None ) :
"""Use this method to create new sticker set owned by a user . The bot will be able to edit the created sticker set . Returns True on success .
https : / / core . telegram . org / b... | from pytgbot . api_types . receivable . stickers import MaskPosition
from pytgbot . api_types . sendable . files import InputFile
assert_type_or_raise ( user_id , int , parameter_name = "user_id" )
assert_type_or_raise ( name , unicode_type , parameter_name = "name" )
assert_type_or_raise ( title , unicode_type , param... |
def add_data_file ( self , from_fp , timestamp = None , content_type = None ) : # type : ( IO , Optional [ datetime . datetime ] , Optional [ str ] ) - > Text
"""Copy inputs to data / folder .""" | self . self_check ( )
tmp_dir , tmp_prefix = os . path . split ( self . temp_prefix )
with tempfile . NamedTemporaryFile ( prefix = tmp_prefix , dir = tmp_dir , delete = False ) as tmp :
checksum = checksum_copy ( from_fp , tmp )
# Calculate hash - based file path
folder = os . path . join ( self . folder , DATA , ... |
def extract_values ( field_list = None , filter_arg_dict = None , out_stream = None ) :
"""Get list of dicts where each dict holds values from one SciObj .
Args :
field _ list : list of str
List of field names for which to return values . Must be strings from
FIELD _ NAME _ TO _ generate _ dict . keys ( ) .... | lookup_dict , generate_dict = _split_field_list ( field_list )
query , annotate_key_list = _create_query ( filter_arg_dict , generate_dict )
lookup_list = [ v [ "lookup_str" ] for k , v in lookup_dict . items ( ) ] + annotate_key_list
if out_stream is None :
return _create_sciobj_list ( query , lookup_list , lookup... |
def reduce_function ( op_func , input_tensor , axis = None , keepdims = None , name = None , reduction_indices = None ) :
"""This function used to be needed to support tf 1.4 and early , but support for tf 1.4 and earlier is now dropped .
: param op _ func : expects the function to handle eg : tf . reduce _ sum .... | warnings . warn ( "`reduce_function` is deprecated and may be removed on or after 2019-09-08." )
out = op_func ( input_tensor , axis = axis , keepdims = keepdims , name = name , reduction_indices = reduction_indices )
return out |
def p_referenceDeclaration ( p ) : # pylint : disable = line - too - long
"""referenceDeclaration : objectRef referenceName ' ; '
| objectRef referenceName defaultValue ' ; '
| qualifierList objectRef referenceName ' ; '
| qualifierList objectRef referenceName defaultValue ' ; '""" | # noqa : E501
quals = [ ]
dv = None
if isinstance ( p [ 1 ] , list ) : # qualifiers
quals = p [ 1 ]
cname = p [ 2 ]
pname = p [ 3 ]
if len ( p ) == 6 :
dv = p [ 4 ]
else :
cname = p [ 1 ]
pname = p [ 2 ]
if len ( p ) == 5 :
dv = p [ 3 ]
quals = OrderedDict ( [ ( x . name , x ... |
def popitem ( self , last = True ) :
"""Remove and return a ` ` ( key , value ) ` ` pair from the dictionary . If
last = True ( default ) then remove the * greatest * ` key ` from the
diciontary . Else , remove the * least * key from the dictionary .
If the dictionary is empty , calling ` popitem ` raises a
... | if not len ( self ) :
raise KeyError ( 'popitem(): dictionary is empty' )
key = self . _list_pop ( - 1 if last else 0 )
value = self . _pop ( key )
return ( key , value ) |
def saturation ( p ) :
"""Returns the saturation of a pixel , defined as the ratio of chroma to value .
: param p : A tuple of ( R , G , B ) values
: return : The saturation of a pixel , from 0 to 1""" | max_c = max ( p )
min_c = min ( p )
if max_c == 0 :
return 0
return ( max_c - min_c ) / float ( max_c ) |
def publish ( ** kwargs ) :
"""Runs the version task before pushing to git and uploading to pypi .""" | current_version = get_current_version ( )
click . echo ( 'Current version: {0}' . format ( current_version ) )
retry = kwargs . get ( "retry" )
debug ( 'publish: retry=' , retry )
if retry : # The " new " version will actually be the current version , and the
# " current " version will be the previous version .
new... |
def chunk_size ( self , value ) :
"""Set the blob ' s default chunk size .
: type value : int
: param value : ( Optional ) The current blob ' s chunk size , if it is set .
: raises : : class : ` ValueError ` if ` ` value ` ` is not ` ` None ` ` and is not a
multiple of 256 KB .""" | if value is not None and value > 0 and value % self . _CHUNK_SIZE_MULTIPLE != 0 :
raise ValueError ( "Chunk size must be a multiple of %d." % ( self . _CHUNK_SIZE_MULTIPLE , ) )
self . _chunk_size = value |
def map_all ( self , prot_alignment , nucl_sequences ) :
"""Convert protein sequences to nucleotide alignment""" | zipped = itertools . zip_longest ( prot_alignment , nucl_sequences )
for p , n in zipped :
if p is None :
raise ValueError ( "Exhausted protein sequences" )
elif n is None :
raise ValueError ( "Exhausted nucleotide sequences" )
yield self . map_alignment ( p , n ) |
def compute_CDR3_pgen ( self , CDR3_seq , V_usage_mask , J_usage_mask ) :
"""Compute Pgen for CDR3 ' amino acid ' sequence CDR3 _ seq from VJ model .
Conditioned on the already formatted V genes / alleles indicated in
V _ usage _ mask and the J genes / alleles in J _ usage _ mask .
Parameters
CDR3 _ seq : s... | # Genomic J alignment / matching ( contribution from P ( delJ | J ) ) , return Pi _ J and reduced J _ usage _ mask
Pi_J , r_J_usage_mask = self . compute_Pi_J ( CDR3_seq , J_usage_mask )
# Genomic V alignment / matching conditioned on J gene ( contribution from P ( V , J , delV ) ) , return Pi _ V _ given _ J
Pi_V_give... |
def createEditor ( self , parent , option , index ) :
"""Return the editor to be used for editing the data item with the given index .
Note that the index contains information about the model being used .
The editor ' s parent widget is specified by parent , and the item options by option .
This will set auto... | # close all editors
self . close_editors ( )
e = self . create_editor_widget ( parent , option , index )
if e :
self . _edit_widgets [ index ] = e
e . setAutoFillBackground ( True )
e . destroyed . connect ( partial ( self . editor_destroyed , index = index ) )
return e |
def create_manage_py ( self , apps ) :
"""Creates manage . py file , with a given list of installed apps .
: param list apps :""" | self . logger . debug ( 'Creating manage.py ...' )
with open ( self . _get_manage_py_path ( ) , mode = 'w' ) as f :
south_migration_modules = [ ]
for app in apps :
south_migration_modules . append ( "'%(app)s': '%(app)s.south_migrations'" % { 'app' : app } )
f . write ( MANAGE_PY % { 'apps_available... |
def quartus_prop ( self , buff : List [ str ] , intfName : str , name : str , value , escapeStr = True ) :
"""Set property on interface in Quartus TCL
: param buff : line buffer for output
: param intfName : name of interface to set property on
: param name : property name
: param value : property value
:... | if escapeStr and isinstance ( value , str ) :
value = '"%s"' % value
elif isinstance ( value , bool ) :
value = str ( value ) . lower ( )
else :
value = str ( value )
buff . append ( "set_interface_property %s %s %s" % ( intfName , name , value ) ) |
def remove_checksum ( path ) :
"""Remove the checksum of an image from cache if exists""" | path = '{}.md5sum' . format ( path )
if os . path . exists ( path ) :
os . remove ( path ) |
def leftAt ( self , offset = 0 ) :
"""Returns point in the center of the region ' s left side ( offset to the left
by negative ` ` offset ` ` )""" | return Location ( self . getX ( ) + offset , self . getY ( ) + ( self . getH ( ) / 2 ) ) |
def _record_key ( record : Record ) -> List [ Tuple [ Column , str ] ] :
"An orderable representation of this record ." | return sorted ( record . items ( ) ) |
def rows ( array ) :
"""Function to find the number of rows in an array .
Excel reference : https : / / support . office . com / en - ie / article / rows - function - b592593e - 3fc2-47f2 - bec1 - bda493811597
: param array : the array of which the rows should be counted .
: return : the number of rows .""" | if isinstance ( array , ( float , int ) ) :
rows = 1
# special case for A1 : A1 type ranges which for some reason only return an int / float
elif array is None :
rows = 1
# some A1 : A1 ranges return None ( issue with ref cell )
else :
rows = len ( array . values )
return rows |
def clone ( self ) :
"""clones a book from GITenberg ' s repo into the library
assumes you are authenticated to git clone from repo ?
returns True / False , message""" | logger . debug ( "Attempting to clone {0}" . format ( self . book_repo_name ) )
if self . path_exists ( ) :
return False , "Error: Local clone of {0} already exists" . format ( self . book_repo_name )
try :
self . local_repo = git . Repo . clone_from ( self . get_clone_url_ssh ( ) , self . library_book_dir ( ) ... |
def update ( self , cls , rid , partialrecord , user = 'undefined' ) :
"""Update existing record
> > > s = teststore ( )
> > > s . create ( ' tstoretest ' , { ' id ' : ' 1 ' , ' name ' : ' Toto ' } )
> > > r = s . get ( ' tstoretest ' , ' 1 ' )
> > > r [ ' age ' ]
> > > s . update ( ' tstoretest ' , ' 1 '... | self . validate_partial_record ( cls , partialrecord )
partialrecord [ UPDATE_DATE ] = self . nowstr ( )
partialrecord [ UPDATER ] = user
try :
updatecount = self . db . update ( cls , partialrecord , where = { ID : rid } )
if updatecount < 1 :
raise KeyError ( 'No such record' )
except ( psycopg2 . Int... |
def duration ( days = 0 , # type : float
seconds = 0 , # type : float
microseconds = 0 , # type : float
milliseconds = 0 , # type : float
minutes = 0 , # type : float
hours = 0 , # type : float
weeks = 0 , # type : float
years = 0 , # type : float
months = 0 , # type : float
) : # type : ( . . . ) - > Duration
"""C... | return Duration ( days = days , seconds = seconds , microseconds = microseconds , milliseconds = milliseconds , minutes = minutes , hours = hours , weeks = weeks , years = years , months = months , ) |
def create_snmp_manager ( self , manager , host , ** kwargs ) :
"""Create an SNMP manager .
: param manager : Name of manager to be created .
: type manager : str
: param host : IP address or DNS name of SNMP server to be used .
: type host : str
: param \ * \ * kwargs : See the REST API Guide on your arr... | data = { "host" : host }
data . update ( kwargs )
return self . _request ( "POST" , "snmp/{0}" . format ( manager ) , data ) |
def readconfig ( self , configpath = None ) :
""": param configpath : Optional bugzillarc path to read , instead of
the default list .
This function is called automatically from Bugzilla connect ( ) , which
is called at _ _ init _ _ if a URL is passed . Calling it manually is
just for passing in a non - sta... | cfg = _open_bugzillarc ( configpath or self . configpath )
if not cfg :
return
section = ""
log . debug ( "bugzillarc: Searching for config section matching %s" , self . url )
def _parse_hostname ( _u ) : # If http : / / example . com is passed , netloc = example . com path = " "
# If just example . com is passed ,... |
def _add_attr_values_from_insert_to_original ( original_code , insert_code , insert_code_list , attribute_name , op_list ) :
"""This function appends values of the attribute ` attribute _ name ` of the inserted code to the original values ,
and changes indexes inside inserted code . If some bytecode instruction i... | orig_value = getattr ( original_code , attribute_name )
insert_value = getattr ( insert_code , attribute_name )
orig_names_len = len ( orig_value )
code_with_new_values = list ( insert_code_list )
offset = 0
while offset < len ( code_with_new_values ) :
op = code_with_new_values [ offset ]
if op in op_list :
... |
def read_ipv6 ( self , length ) :
"""Read Internet Protocol version 6 ( IPv6 ) .
Structure of IPv6 header [ RFC 2460 ] :
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
| Version | Traffic Class | Flow Label |
| Payload Length | Next Header | Hop Limit |
+ Source Address +
+ De... | if length is None :
length = len ( self )
_htet = self . _read_ip_hextet ( )
_plen = self . _read_unpack ( 2 )
_next = self . _read_protos ( 1 )
_hlmt = self . _read_unpack ( 1 )
_srca = self . _read_ip_addr ( )
_dsta = self . _read_ip_addr ( )
ipv6 = dict ( version = _htet [ 0 ] , tclass = _htet [ 1 ] , label = _h... |
def get_portchannel_info_by_intf_output_lacp_actor_brcd_state ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_portchannel_info_by_intf = ET . Element ( "get_portchannel_info_by_intf" )
config = get_portchannel_info_by_intf
output = ET . SubElement ( get_portchannel_info_by_intf , "output" )
lacp = ET . SubElement ( output , "lacp" )
actor_brcd_state = ET . SubElement ( lacp , "actor-brcd-... |
def rs_generator_poly_all ( max_nsym , fcr = 0 , generator = 2 ) :
'''Generate all irreducible generator polynomials up to max _ nsym ( usually you can use n , the length of the message + ecc ) . Very useful to reduce processing time if you want to encode using variable schemes and nsym rates .''' | g_all = { }
g_all [ 0 ] = g_all [ 1 ] = [ 1 ]
for nsym in xrange ( max_nsym ) :
g_all [ nsym ] = rs_generator_poly ( nsym , fcr , generator )
return g_all |
def available_time_entries_impl ( self ) :
"""Creates the JSON object for the available time entries route response .
Returns :
The JSON object for the available time entries route response .""" | result = { }
if self . _db_connection_provider :
db = self . _db_connection_provider ( )
# For each run , pick a tag .
cursor = db . execute ( '''
SELECT
TagPickingTable.run_name,
Tensors.step,
Tensors.computed_time
FROM (/* For each run, pick any tag.... |
def node ( * nodes ) :
"""Selects and configures a list of nodes . ' all ' configures all nodes""" | chef . build_node_data_bag ( )
if not len ( nodes ) or nodes [ 0 ] == '' :
abort ( 'No node was given' )
elif nodes [ 0 ] == 'all' : # Fetch all nodes and add them to env . hosts
for node in lib . get_nodes ( env . chef_environment ) :
env . hosts . append ( node [ 'name' ] )
if not len ( env . host... |
def parse_latitude ( latitude , hemisphere ) :
"""Parse a NMEA - formatted latitude pair .
Args :
latitude ( str ) : Latitude in DDMM . MMMM
hemisphere ( str ) : North or South
Returns :
float : Decimal representation of latitude""" | latitude = int ( latitude [ : 2 ] ) + float ( latitude [ 2 : ] ) / 60
if hemisphere == 'S' :
latitude = - latitude
elif not hemisphere == 'N' :
raise ValueError ( 'Incorrect North/South value %r' % hemisphere )
return latitude |
def get ( self , url , parameters = None ) :
"""Convenience method for requesting to google with proper cookies / params .""" | if not self . access_token :
raise IOError ( "No authorized client available." )
if parameters is None :
parameters = { }
parameters . update ( { 'access_token' : self . access_token , 'alt' : 'json' } )
request = requests . get ( url + '?' + self . getParameters ( parameters ) )
if request . status_code != 200... |
def tmsh_mode ( self , delay_factor = 1 ) :
"""tmsh command is equivalent to config command on F5.""" | delay_factor = self . select_delay_factor ( delay_factor )
self . clear_buffer ( )
command = "{}tmsh{}" . format ( self . RETURN , self . RETURN )
self . write_channel ( command )
time . sleep ( 1 * delay_factor )
self . clear_buffer ( )
return None |
def aggregate ( self ) :
"""Aggregate all reports of the same type into a master report""" | for report in self . reportset :
printtime ( 'Processing {}' . format ( report . split ( '.' ) [ 0 ] ) , self . start )
# Initialise the header for each report - MLST is different , as the header is different for each
# MLST scheme . This provides a generic header instead
header = '' if report != 'mlst.... |
def datum_to_value ( self , instance , datum ) :
"""Convert a given MAAS - side datum to a Python - side value .
: param instance : The ` Object ` instance on which this field is
currently operating . This method should treat it as read - only , for
example to perform validation with regards to other fields .... | if datum is None :
return [ ]
if not isinstance ( datum , Sequence ) :
raise TypeError ( "datum must be a sequence, not %s" % type ( datum ) . __name__ )
# Get the class from the bound origin .
bound = getattr ( instance . _origin , "FilesystemGroupDevices" )
return bound ( ( get_device_object ( instance . _ori... |
def _read_config_file ( self ) :
"""read in the configuration file , a json file defined at self . config""" | try :
with open ( self . config , 'r' ) as f :
config_data = json . load ( f )
except FileNotFoundError :
config_data = { }
return config_data |
def get_queryset ( self ) :
"""Returns only objects which are accessible to the current user .
If user is not authenticated all public objects will be returned .
Model must implement AccessLevelManager !""" | return self . queryset . all ( ) . accessible_to ( user = self . request . user ) |
def nth_centered_hexagonal_num ( index ) :
"""Calculate the nth centered hexagonal number .
Examples :
> > > nth _ centered _ hexagonal _ num ( 10)
271
> > > nth _ centered _ hexagonal _ num ( 2)
> > > nth _ centered _ hexagonal _ num ( 9)
217
: param index : The nth position of the centered hexagonal... | return 3 * index * ( index - 1 ) + 1 |
def do_call ( self , path , method , body = None , headers = None ) :
"""Send an HTTP request to the REST API .
: param string path : A URL
: param string method : The HTTP method ( GET , POST , etc . ) to use
in the request .
: param string body : A string representing any data to be sent in the
body of ... | url = urljoin ( self . base_url , path )
try :
resp = requests . request ( method , url , data = body , headers = headers , auth = self . auth , timeout = self . timeout )
except requests . exceptions . Timeout as out :
raise NetworkError ( "Timeout while trying to connect to RabbitMQ" )
except requests . excep... |
def put ( self , url , request_data , content_type = None , auth_map = None ) :
"""Envia uma requisição PUT para a URL informada .
Se auth _ map é diferente de None , então deverá conter as
chaves NETWORKAPI _ PASSWORD e NETWORKAPI _ USERNAME para realizar
a autenticação na networkAPI .
As chaves e o... | try :
LOG . debug ( 'PUT %s\n%s' , url , request_data )
parsed_url = urlparse ( url )
if parsed_url . scheme == 'https' :
connection = HTTPSConnection ( parsed_url . hostname , parsed_url . port )
else :
connection = HTTPConnection ( parsed_url . hostname , parsed_url . port )
try :
... |
def prox_nuclear ( V , alpha ) :
r"""Proximal operator of the nuclear norm : cite : ` cai - 2010 - singular `
with parameter : math : ` \ alpha ` .
Parameters
v : array _ like
Input array : math : ` V `
alpha : float
Parameter : math : ` \ alpha `
Returns
X : ndarray
Output array
s : ndarray
S... | Usvd , s , Vsvd = sl . promote16 ( V , fn = np . linalg . svd , full_matrices = False )
ss = np . maximum ( 0 , s - alpha )
return np . dot ( Usvd , np . dot ( np . diag ( ss ) , Vsvd ) ) , ss |
def config ( ) :
"""Return sun configuration values""" | conf_args = { "INTERVAL" : 60 , "STANDBY" : 3 }
config_file = read_file ( "{0}{1}" . format ( conf_path , "sun.conf" ) )
for line in config_file . splitlines ( ) :
line = line . lstrip ( )
if line and not line . startswith ( "#" ) :
conf_args [ line . split ( "=" ) [ 0 ] ] = line . split ( "=" ) [ 1 ]
r... |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'tooling' ) and self . tooling is not None :
_dict [ 'tooling' ] = self . tooling . _to_dict ( )
if hasattr ( self , 'disambiguation' ) and self . disambiguation is not None :
_dict [ 'disambiguation' ] = self . disambiguation . _to_dict ( )
if hasattr ( self , 'human_agent_assis... |
def get_download_link ( self ) :
"""Get direct download link with soudcloud ' s redirect system .""" | url = None
if not self . get ( "downloadable" ) :
try :
url = self . client . get_location ( self . client . STREAM_URL % self . get ( "id" ) )
except serror as e :
print ( e )
if not url :
try :
url = self . client . get_location ( self . client . DOWNLOAD_URL % self . get ( "id" ) ... |
def login ( self , username = None , password = None ) :
"""Explicit Abode login .""" | if username is not None :
self . _cache [ CONST . ID ] = username
if password is not None :
self . _cache [ CONST . PASSWORD ] = password
if ( self . _cache [ CONST . ID ] is None or not isinstance ( self . _cache [ CONST . ID ] , str ) ) :
raise AbodeAuthenticationException ( ERROR . USERNAME )
if ( self .... |
def show_network_ip_availability ( self , network , ** _params ) :
"""Fetches IP availability information for a specified network""" | return self . get ( self . network_ip_availability_path % ( network ) , params = _params ) |
def render_header ( self , ctx , data ) :
"""Render any required static content in the header , from the C { staticContent }
attribute of this page .""" | if self . staticContent is None :
return ctx . tag
header = self . staticContent . getHeader ( )
if header is not None :
return ctx . tag [ header ]
else :
return ctx . tag |
def _validate_resolution_output_length ( path , entity_name , results , allow_mult = False , all_mult = False , ask_to_resolve = True ) :
""": param path : Path to the object that required resolution ; propagated from
command - line
: type path : string
: param entity _ name : Name of the object
: type enti... | if len ( results ) == 0 :
raise ValueError ( "'results' must be nonempty." )
# Caller wants ALL results , so return the entire results list
# At this point , do not care about the values of allow _ mult or all _ mult
if not ask_to_resolve :
return results
if len ( results ) > 1 : # The other way the caller can ... |
def paragraph_generator ( sentences = None ) :
"""Creates a generator for generating paragraphs .
: arg sentences : list or tuple of sentences you want to use ;
defaults to LOREM
: returns : generator
Example : :
from eadred . helpers import paragraph _ generator
gen = paragraph _ generator ( )
for i ... | if sentences is None :
sentences = LOREM
while True : # Paragraph consists of 1-7 sentences .
paragraph = [ random . choice ( sentences ) for num in range ( random . randint ( 1 , 7 ) ) ]
yield u' ' . join ( paragraph ) |
def while_until_true ( interval , max_attempts ) :
"""Decorator that executes a function until it returns True .
Executes wrapped function at every number of seconds specified by interval ,
until wrapped function either returns True or max _ attempts are exhausted ,
whichever comes 1st .
The difference betw... | def decorator ( f ) :
logger . debug ( "started" )
def sleep_looper ( * args , ** kwargs ) :
if max_attempts :
logger . debug ( f"Looping every {interval} seconds for " f"{max_attempts} attempts" )
else :
logger . debug ( f"Looping every {interval} seconds." )
i =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.