signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def valid_paths ( self , * args ) :
"""Validate that given paths are not the same .
Args :
( string ) : Path to validate .
Raises :
boussole . exceptions . SettingsInvalidError : If there is more than one
occurence of the same path .
Returns :
bool : ` ` True ` ` if paths are validated .""" | for i , path in enumerate ( args , start = 0 ) :
cp = list ( args )
current = cp . pop ( i )
if current in cp :
raise SettingsInvalidError ( "Multiple occurences finded for " "path: {}" . format ( current ) )
return True |
def execute ( self , conn , logical_file_name , transaction = False ) :
"""simple execute""" | if not conn :
dbsExceptionHandler ( "dbsException-db-conn-failed" , "Oracle/FileBuffer/DeleteDupicates. Expects db connection from upper layer." )
print ( self . sql )
self . dbi . processData ( self . sql , logical_file_name , conn , transaction ) |
def remove_item ( self , item ) :
"""Remove ( and un - index ) an object
: param item : object to remove
: type item : alignak . objects . item . Item
: return : None""" | self . unindex_item ( item )
self . items . pop ( item . uuid , None ) |
def asFloat ( self , maxval = 1.0 ) :
"""Return image pixels as per : meth : ` asDirect ` method , but scale
all pixel values to be floating point values between 0.0 and
* maxval * .""" | x , y , pixels , info = self . asDirect ( )
sourcemaxval = 2 ** info [ 'bitdepth' ] - 1
del info [ 'bitdepth' ]
info [ 'maxval' ] = float ( maxval )
factor = float ( maxval ) / float ( sourcemaxval )
def iterfloat ( ) :
for row in pixels :
yield map ( factor . __mul__ , row )
return x , y , iterfloat ( ) , ... |
def set_ ( device , minor , flag , state ) :
'''Changes a flag on the partition with number < minor > .
A flag can be either " on " or " off " ( make sure to use proper quoting , see
: ref : ` YAML Idiosyncrasies < yaml - idiosyncrasies > ` ) . Some or all of these
flags will be available , depending on what ... | _validate_device ( device )
try :
int ( minor )
except Exception :
raise CommandExecutionError ( 'Invalid minor number passed to partition.set' )
if flag not in VALID_PARTITION_FLAGS :
raise CommandExecutionError ( 'Invalid flag passed to partition.set' )
if state not in set ( [ 'on' , 'off' ] ) :
raise... |
def insert ( self , i , item_weight ) :
"""Insert an item with the given weight in the sequence""" | item , weight = item_weight
self . _seq . insert ( i , item )
self . weight += weight |
def transitDurationCircular ( P , R_s , R_p , a , i ) :
r"""Estimation of the primary transit time . Assumes a circular orbit .
. . math : :
T _ \ text { dur } = \ frac { P } { \ pi } \ sin ^ { - 1}
\ left [ \ frac { R _ \ star } { a } \ frac { \ sqrt { ( 1 + k ) ^ 2 + b ^ 2 } } { \ sin { a } } \ right ]
Wh... | if i is nan :
i = 90 * aq . deg
i = i . rescale ( aq . rad )
k = R_p / R_s
# lit reference for eclipsing binaries
b = ( a * cos ( i ) ) / R_s
duration = ( P / pi ) * arcsin ( ( ( R_s * sqrt ( ( 1 + k ) ** 2 - b ** 2 ) ) / ( a * sin ( i ) ) ) . simplified )
return duration . rescale ( aq . min ) |
def parse_poi_query ( north , south , east , west , amenities = None , timeout = 180 , maxsize = '' ) :
"""Parse the Overpass QL query based on the list of amenities .
Parameters
north : float
Northernmost coordinate from bounding box of the search area .
south : float
Southernmost coordinate from boundin... | if amenities : # Overpass QL template
query_template = ( '[out:json][timeout:{timeout}]{maxsize};((node["amenity"~"{amenities}"]({south:.6f},' '{west:.6f},{north:.6f},{east:.6f});(._;>;););(way["amenity"~"{amenities}"]({south:.6f},' '{west:.6f},{north:.6f},{east:.6f});(._;>;););(relation["amenity"~"{amenities}"]' '... |
def add_debugged_source_file ( self , debugged_source_file ) :
"""Add a DebuggedSourceFile proto .""" | # TODO ( cais ) : Should the key include a host name , for certain distributed
# cases ?
key = debugged_source_file . file_path
self . _source_file_host [ key ] = debugged_source_file . host
self . _source_file_last_modified [ key ] = debugged_source_file . last_modified
self . _source_file_bytes [ key ] = debugged_sou... |
def get_analysisrequests_section ( self ) :
"""Returns the section dictionary related with Analysis
Requests , that contains some informative panels ( like
ARs to be verified , ARs to be published , etc . )""" | out = [ ]
catalog = getToolByName ( self . context , CATALOG_ANALYSIS_REQUEST_LISTING )
query = { 'portal_type' : "AnalysisRequest" , 'is_active' : True }
# Check if dashboard _ cookie contains any values to query
# elements by
query = self . _update_criteria_with_filters ( query , 'analysisrequests' )
# Active Samples... |
def handle_abort ( self , obj ) :
"""Handle an incoming ` ` Data ` ` abort processing request .
. . IMPORTANT : :
This only makes manager ' s state consistent and doesn ' t
affect Data object in any way . Any changes to the Data
must be applied over ` ` handle _ update ` ` method .
: param obj : The Chann... | async_to_sync ( consumer . send_event ) ( { WorkerProtocol . COMMAND : WorkerProtocol . ABORT , WorkerProtocol . DATA_ID : obj [ ExecutorProtocol . DATA_ID ] , WorkerProtocol . FINISH_COMMUNICATE_EXTRA : { 'executor' : getattr ( settings , 'FLOW_EXECUTOR' , { } ) . get ( 'NAME' , 'resolwe.flow.executors.local' ) , } , ... |
def get_local_filter_directives ( ast , current_schema_type , inner_vertex_fields ) :
"""Get all filter directives that apply to the current field .
This helper abstracts away the fact that some vertex field filtering operators apply on the
inner scope ( the scope of the inner vertex field on which they are app... | result = [ ]
if ast . directives : # it ' ll be None if the AST has no directives at that node
for directive_obj in ast . directives : # Of all filters that appear * on the field itself * , only the ones that apply
# to the outer scope are not considered " local " and are not to be returned .
if directi... |
def plotMDS ( data , theOrders , theLabels , theColors , theSizes , theMarkers , options ) :
"""Plot the MDS data .
: param data : the data to plot ( MDS values ) .
: param theOrders : the order of the populations to plot .
: param theLabels : the names of populations to plot .
: param theColors : the color... | # Do the import
import matplotlib as mpl
if options . format != "X11" and mpl . get_backend ( ) != "agg" :
mpl . use ( "Agg" )
import matplotlib . pyplot as plt
if options . format != "X11" :
plt . ioff ( )
fig = plt . figure ( )
ax = fig . add_subplot ( 111 )
# The plot
plotObject = [ ]
labels = [ ]
for i , in... |
def with_indent ( self , indent = 0 ) :
"""Substitute in the docstring of a function with indented : attr : ` params `
Parameters
indent : int
The number of spaces that the substitution should be indented
Returns
function
Wrapper that takes a function as input and substitutes it ' s
` ` _ _ doc _ _ ` ... | def replace ( func ) :
doc = func . __doc__ and self . with_indents ( func . __doc__ , indent = indent , stacklevel = 4 )
return self . _set_object_doc ( func , doc )
return replace |
def check ( self , diff ) :
"""Check that the name of the subpackage within contrib is valid
The package name must match ` ` user _ [ a - zA - Z0-9 _ ] + ` ` .""" | relative_path = relative_to_contrib ( diff , self . project )
subpackage_name = relative_path . parts [ 0 ]
assert re_test ( SUBPACKAGE_NAME_REGEX , subpackage_name ) |
def link ( self , path , pkg ) :
"""Link the package in the current directory .""" | # Check if a custom linker exists to handle linking this package
# for ep in pkg _ resources . iter _ entry _ points ( group = " enaml _ native _ linker " ) :
# if ep . name . replace ( " - " , ' _ ' ) = = pkg . replace ( " - " , ' _ ' ) :
# linker = ep . load ( )
# print ( " Custom linker { } found for ' { } ' . Linki... |
def get_rate_from_db ( currency : str ) -> Decimal :
"""Fetch currency conversion rate from the database""" | from . models import ConversionRate
try :
rate = ConversionRate . objects . get_rate ( currency )
except ConversionRate . DoesNotExist : # noqa
raise ValueError ( 'No conversion rate for %s' % ( currency , ) )
return rate . rate |
def validate_srec_checksum ( srec ) :
"""Validate if the checksum of the supplied s - record is valid
Returns : True if valid , False if not""" | checksum = srec [ len ( srec ) - 2 : ]
# Strip the original checksum and compare with the computed one
if compute_srec_checksum ( srec [ : len ( srec ) - 2 ] ) == int ( checksum , 16 ) :
return True
else :
return False |
def disable_validation ( self , field_name ) :
"""Disable the validation rules for a field""" | field = self . field_dict . get ( field_name )
if not field :
raise exceptions . FieldNotFound ( 'Field not found: \'%s\' when trying to disable validation' % field_name )
field . validators = [ ] |
def draw_line ( self , line_pts , color = "#ff0000" , robot_coordinates = False , relative_to_first = False , arrow = True , scale = ( 1 , 1 ) , ** kwargs ) :
""": param line _ pts : A list of ( x , y ) pairs to draw . ( x , y ) are in field units
which are measured in feet
: param color : The color of the line... | def _defer ( ) : # called later because the field might not exist yet
px_per_ft = UserRenderer . _global_ui . field . px_per_ft
if arrow :
kwargs [ "arrow" ] = "last"
sx , sy = scale
line = DrawableLine ( [ ( x * px_per_ft * sx , y * px_per_ft * sy ) for x , y in line_pts ] , color , kwargs , )
... |
def cmd_flashbootloader ( self , args ) :
'''flash bootloader''' | self . master . mav . command_long_send ( self . settings . target_system , 0 , mavutil . mavlink . MAV_CMD_FLASH_BOOTLOADER , 0 , 0 , 0 , 0 , 0 , 290876 , 0 , 0 ) |
def ramp_to_volume ( self , volume , ramp_type = 'SLEEP_TIMER_RAMP_TYPE' ) :
"""Smoothly change the volume .
There are three ramp types available :
* ` ` ' SLEEP _ TIMER _ RAMP _ TYPE ' ` ` ( default ) : Linear ramp from the
current volume up or down to the new volume . The ramp rate is
1.25 steps per secon... | response = self . renderingControl . RampToVolume ( [ ( 'InstanceID' , 0 ) , ( 'Channel' , 'Master' ) , ( 'RampType' , ramp_type ) , ( 'DesiredVolume' , volume ) , ( 'ResetVolumeAfter' , False ) , ( 'ProgramURI' , '' ) ] )
return int ( response [ 'RampTime' ] ) |
def add_expansion ( self , expansion_node ) :
"""Add a child expansion node to the type node ' s expansions .
If an expansion node with the same name is already present in type node ' s expansions , the new and existing
expansion node ' s children are merged .
: param expansion _ node : The expansion node to ... | # Check for existing expansion node with the same name
existing_expansion_node = self . get_expansion ( expansion_node . name )
if existing_expansion_node : # Expansion node exists with the same name , merge child expansions .
for child_expansion in expansion_node . expansions :
existing_expansion_node . ad... |
def preprocess_keyevent ( self , event ) :
"""Pre - process keypress event :
return True if event is accepted , false otherwise""" | # Copy must be done first to be able to copy read - only text parts
# ( otherwise , right below , we would remove selection
# if not on current line )
ctrl = event . modifiers ( ) & Qt . ControlModifier
meta = event . modifiers ( ) & Qt . MetaModifier
# meta = ctrl in OSX
if event . key ( ) == Qt . Key_C and ( ( Qt . M... |
def PrependStructSlot ( self , v , x , d ) :
"""PrependStructSlot prepends a struct onto the object at vtable slot ` o ` .
Structs are stored inline , so nothing additional is being added .
In generated code , ` d ` is always 0.""" | N . enforce_number ( d , N . UOffsetTFlags )
if x != d :
self . assertStructIsInline ( x )
self . Slot ( v ) |
def write_xmlbif ( self , filename ) :
"""Write the xml data into the file .
Parameters
filename : Name of the file .
Examples
> > > writer = XMLBIFWriter ( model )
> > > writer . write _ xmlbif ( test _ file )""" | with open ( filename , 'w' ) as fout :
fout . write ( self . __str__ ( ) ) |
def lpr_kurtosis ( frame , lpcorder = 10 ) :
"""frame : windowed signal
return kurtosis of linear prediction residual from input signal""" | c = lpc ( frame , lpcorder )
coef = c [ 1 : ] [ : : - 1 ] * - 1
residuals = [ ]
for i in xrange ( frame . size - 10 ) :
residuals . append ( frame [ i + 10 ] - np . sum ( frame [ i : i + 10 ] * coef ) )
residuals = np . array ( residuals )
return calc_kurtosis ( residuals ) |
def destroy ( self , force = False ) :
"""Like shutdown ( ) , but also removes all accounts , hosts , etc . , and
does not restart the queue . In other words , the queue can no longer
be used after calling this method .
: type force : bool
: param force : Whether to wait until all jobs were processed .""" | try :
if not force :
self . join ( )
finally :
self . _dbg ( 2 , 'Destroying queue...' )
self . workqueue . destroy ( )
self . account_manager . reset ( )
self . completed = 0
self . total = 0
self . failed = 0
self . status_bar_length = 0
self . _dbg ( 2 , 'Queue destroyed.'... |
def create_attribute ( self , column = None , listType = None , namespace = None , network = None , atype = None , verbose = False ) :
"""Creates a new edge column .
: param column ( string , optional ) : Unique name of column
: param listType ( string , optional ) : Can be one of integer , long , double ,
or... | network = check_network ( self , network , verbose = verbose )
PARAMS = set_param ( [ "column" , "listType" , "namespace" , "network" , "type" ] , [ column , listType , namespace , network , atype ] )
response = api ( url = self . __url + "/create attribute" , PARAMS = PARAMS , method = "POST" , verbose = verbose )
ret... |
def align_unaligned_seqs ( seqs , moltype = DNA , params = None , accurate = False ) :
"""Aligns unaligned sequences
seqs : either list of sequence objects or list of strings
add _ seq _ names : boolean . if True , sequence names are inserted in the list
of sequences . if False , it assumes seqs is a list of ... | # create SequenceCollection object from seqs
seq_collection = SequenceCollection ( seqs , MolType = moltype )
# Create mapping between abbreviated IDs and full IDs
int_map , int_keys = seq_collection . getIntMap ( )
# Create SequenceCollection from int _ map .
int_map = SequenceCollection ( int_map , MolType = moltype ... |
def adjust_weights_recfile ( self , recfile = None , original_ceiling = True ) :
"""adjusts the weights by group of the observations based on the phi components
in a pest record file so that total phi is equal to the number of
non - zero weighted observations
Parameters
recfile : str
record file name . If... | if recfile is None :
recfile = self . filename . replace ( ".pst" , ".rec" )
assert os . path . exists ( recfile ) , "Pst.adjust_weights_recfile(): recfile not found: " + str ( recfile )
iter_components = pst_utils . get_phi_comps_from_recfile ( recfile )
iters = iter_components . keys ( )
iters . sort ( )
obs = se... |
def predictPhenos ( self , use_fixed = None , use_random = None ) :
"""predict the conditional mean ( BLUP )
Args :
use _ fixed : list of fixed effect indeces to use for predictions
use _ random : list of random effect indeces to use for predictions
Returns :
predictions ( BLUP )""" | assert self . noisPos is not None , 'No noise element'
assert self . init , 'GP not initialised'
assert self . Ntest is not None , 'VarianceDecomposition:: specify Ntest for predictions (method VarianceDecomposition::setTestSampleSize)'
use_fixed = list ( range ( self . n_fixedEffs ) )
use_random = list ( range ( self ... |
def get_required_args ( fn ) -> list :
"""Returns a list of required arguments for the function fn .
> > > def foo ( x , y , z = 100 ) : return x + y + z
> > > get _ required _ args ( foo )
[ ' x ' , ' y ' ]
> > > def bar ( x , y = 100 , * args , * * kwargs ) : return x
> > > get _ required _ args ( bar )... | sig = inspect . signature ( fn )
return [ name for name , param in sig . parameters . items ( ) if param . default == inspect . _empty and param . kind not in VAR_ARGS ] |
def _custom_token_stream ( self ) :
"""A wrapper for the BaseEnamlLexer ' s make _ token _ stream which allows
the stream to be customized by adding " token _ stream _ processors " .
A token _ stream _ processor is a generator function which takes the
token _ stream as it ' s single input argument and yields ... | token_stream = default_make_token_stream ( self )
for processor in _token_stream_processors :
token_stream = processor ( token_stream )
return token_stream |
def stSpectralRollOff ( X , c , fs ) :
"""Computes spectral roll - off""" | totalEnergy = numpy . sum ( X ** 2 )
fftLength = len ( X )
Thres = c * totalEnergy
# Ffind the spectral rolloff as the frequency position
# where the respective spectral energy is equal to c * totalEnergy
CumSum = numpy . cumsum ( X ** 2 ) + eps
[ a , ] = numpy . nonzero ( CumSum > Thres )
if len ( a ) > 0 :
mC = n... |
def qteSetWidgetFocusOrder ( self , widList : tuple ) :
"""Change the focus order of the widgets in this applet .
This method re - arranges the internal ( cyclic ) widget list so
that all widgets specified in ` ` widList ` ` will be focused in
the given order .
| Args |
* ` ` widList ` ` ( * * tuple * * )... | # A list with less than two entries cannot be re - ordered .
if len ( widList ) < 2 :
return
# Housekeeping : remove non - existing widgets from the admin structure .
self . qteAutoremoveDeletedWidgets ( )
# Remove all * * None * * widgets .
widList = [ _ for _ in widList if _ is not None ]
# Ensure that all widget... |
def getGroupsURL ( certfile , group ) :
"""given a certfile load a list of groups that user is a member of""" | GMS = "https://" + _SERVER + _GMS
certfile . seek ( 0 )
buf = certfile . read ( )
x509 = crypto . load_certificate ( crypto . FILETYPE_PEM , buf )
sep = ""
dn = ""
parts = [ ]
for i in x509 . get_issuer ( ) . get_components ( ) : # print i
if i [ 0 ] in parts :
continue
parts . append ( i [ 0 ] )
dn... |
def _construct_production_name ( glyph_name , data = None ) :
"""Return the production name for a glyph name from the GlyphData . xml
database according to the AGL specification .
This should be run only if there is no official entry with a production
name in it .
Handles single glyphs ( e . g . " brevecomb... | # At this point , we have already checked the data for the full glyph name , so
# directly go to the base name here ( e . g . when looking at " fi . alt " ) .
base_name , dot , suffix = glyph_name . partition ( "." )
glyphinfo = _lookup_attributes ( base_name , data )
if glyphinfo and glyphinfo . get ( "production" ) :... |
def root_dir ( self ) :
"""Root directory of this : class : ` Configurator ` .
Evaluated from the : attr : ` script ` attribute .""" | if self . cfg . script :
return os . path . dirname ( self . cfg . script ) |
def object_result ( self ) :
"""Get the object result object , assuming there is only one . Raises
an error if there is more than one .
: return : The result object
: raises ValueError : If there is more than one result""" | num_obj_results = len ( self . _object_results )
if num_obj_results < 1 :
return None
elif num_obj_results < 2 :
return self . _object_results [ 0 ]
else :
raise ValueError ( "There is more than one result; use 'object_results'" ) |
def get_element_location ( self , locator ) :
"""Get element location
Key attributes for arbitrary elements are ` id ` and ` name ` . See
` introduction ` for details about locating elements .""" | element = self . _element_find ( locator , True , True )
element_location = element . location
self . _info ( "Element '%s' location: %s " % ( locator , element_location ) )
return element_location |
def evaluate ( self , sequence ) :
"""Compute the lineage on the sequence .
: param sequence : Sequence to compute
: return : Evaluated sequence""" | last_cache_index = self . cache_scan ( )
transformations = self . transformations [ last_cache_index : ]
return self . engine . evaluate ( sequence , transformations ) |
def fromfd ( cls , fd ) :
"""Create a new epoll object from a given file descriptor
: param fd :
A pre - made file descriptor obtained from ` ` epoll _ create ( 2 ) ` ` or
` ` epoll _ create1(2 ) ` `
: raises ValueError :
If fd is not a valid file descriptor
: returns :
A new epoll object
. . note :... | if fd < 0 :
_err_closed ( )
self = cls . __new__ ( )
object . __init__ ( self )
self . _epfd = fd
return self |
def _playbook_arguments ( self ) :
"""Argument specific to playbook apps .
These arguments will be passed to every playbook app by default .
- - tc _ playbook _ db _ type type The DB type ( currently on Redis is supported ) .
- - tc _ playbook _ db _ context context The playbook context provided by TC .
- -... | self . add_argument ( '--tc_playbook_db_type' , default = self . _tc_playbook_db_type , help = 'Playbook DB type' )
self . add_argument ( '--tc_playbook_db_context' , default = self . _tc_playbook_db_context , help = 'Playbook DB Context' , )
self . add_argument ( '--tc_playbook_db_path' , default = self . _tc_playbook... |
def status ( name , sig = None ) :
'''Return the status for a service .
If the name contains globbing , a dict mapping service name to True / False
values is returned .
. . versionchanged : : 2018.3.0
The service name can now be a glob ( e . g . ` ` salt * ` ` )
Args :
name ( str ) : The name of the ser... | if sig :
return bool ( __salt__ [ 'status.pid' ] ( sig ) )
contains_globbing = bool ( re . search ( r'\*|\?|\[.+\]' , name ) )
if contains_globbing :
services = fnmatch . filter ( get_all ( ) , name )
else :
services = [ name ]
results = { }
for service in services :
cmd = _service_cmd ( service , 'stat... |
def InvokeMethod ( self , MethodName , ObjectName , Params = None , ** params ) : # pylint : disable = invalid - name
"""Invoke a method on a target instance or on a target class .
The methods that can be invoked are static and non - static methods
defined in a class ( also known as * extrinsic * methods ) .
... | exc = None
result_tuple = None
if self . _operation_recorders :
self . operation_recorder_reset ( )
self . operation_recorder_stage_pywbem_args ( method = 'InvokeMethod' , MethodName = MethodName , ObjectName = ObjectName , Params = Params , ** params )
try :
stats = self . statistics . start_timer ( 'Invok... |
def configure ( root_url , ** kwargs ) :
"""Notice that ` configure ` can either apply to the default configuration or
` Client . config ` , which is the configuration used by the current thread
since ` Client ` inherits form ` threading . local ` .""" | default = kwargs . pop ( 'default' , True )
kwargs [ 'client_agent' ] = 'example-client/' + __version__
if 'headers' not in kwargs :
kwargs [ 'headers' ] = { }
kwargs [ 'headers' ] [ 'Accept-Type' ] = 'application/json'
if default :
default_config . reset ( root_url , ** kwargs )
else :
Client . config = wa... |
def from_source ( cls , filename , args = None , unsaved_files = None , options = 0 , index = None ) :
"""Create a TranslationUnit by parsing source .
This is capable of processing source code both from files on the
filesystem as well as in - memory contents .
Command - line arguments that would be passed to ... | if args is None :
args = [ ]
if unsaved_files is None :
unsaved_files = [ ]
if index is None :
index = Index . create ( )
args_array = None
if len ( args ) > 0 :
args_array = ( c_char_p * len ( args ) ) ( * [ b ( x ) for x in args ] )
unsaved_array = None
if len ( unsaved_files ) > 0 :
unsaved_array... |
def closeEvent ( self , event ) :
"""things to be done when gui closes , like save the settings""" | self . save_config ( self . gui_settings [ 'gui_settings' ] )
self . script_thread . quit ( )
self . read_probes . quit ( )
event . accept ( )
print ( '\n\n======================================================' )
print ( '================= Closing B26 Python LAB =============' )
print ( '==============================... |
def _generate_examples ( self , filepaths ) :
"""Generate CIFAR examples as dicts .
Shared across CIFAR - { 10 , 100 } . Uses self . _ cifar _ info as
configuration .
Args :
filepaths ( list [ str ] ) : The files to use to generate the data .
Yields :
The cifar examples , as defined in the dataset info ... | label_keys = self . _cifar_info . label_keys
for path in filepaths :
for labels , np_image in _load_data ( path , len ( label_keys ) ) :
row = dict ( zip ( label_keys , labels ) )
row [ "image" ] = np_image
yield row |
def dict ( self ) :
'''The dict representation of this sentence .''' | return { 'raw' : self . raw , 'start' : self . start , 'end' : self . end , 'entities' : [ ( e . tag , e ) for e in self . entities ] , 'tokens' : self . tokens , 'words' : self . words , 'pos_tags' : self . pos_tags , 'language' : self . language . code , # TODO : ' polarity ' : self . polarity ,
} |
def strtype ( self ) :
"""Returns a string representing the type and kind of this value element .""" | if self . kind is not None :
return "{}({})" . format ( self . dtype , self . kind )
else :
return self . dtype |
def take ( self , indices , axis = 0 , out = None , mode = 'raise' ) :
"""Take elements from an array along an axis .
This function does the same thing as " fancy " indexing ( indexing arrays
using arrays ) ; however , it can be easier to use if you need elements
along a given axis .
Parameters
indices : ... | return take_haplotype_array ( self , indices , axis = axis , cls = type ( self ) , take = np . take , out = out , mode = mode ) |
def get ( self , item , not_found_value = None ) :
"Method like dict . get ( ) which can return specified value if key not found" | if item in self . keys :
return self . __data [ item ]
else :
return not_found_value |
def convert_basis ( basis_dict , fmt , header = None ) :
'''Returns the basis set data as a string representing
the data in the specified output format''' | # make converters case insensitive
fmt = fmt . lower ( )
if fmt not in _converter_map :
raise RuntimeError ( 'Unknown basis set format "{}"' . format ( fmt ) )
converter = _converter_map [ fmt ]
# Determine if the converter supports all the types in the basis _ dict
if converter [ 'valid' ] is not None :
ftypes... |
def read_frame ( location , channels , start_time = None , end_time = None , duration = None , check_integrity = True , sieve = None ) :
"""Read time series from frame data .
Using the ` location ` , which can either be a frame file " . gwf " or a
frame cache " . gwf " , read in the data for the given channel (... | if end_time and duration :
raise ValueError ( "end time and duration are mutually exclusive" )
if type ( location ) is list :
locations = location
else :
locations = [ location ]
cum_cache = locations_to_cache ( locations )
if sieve :
logging . info ( "Using frames that match regexp: %s" , sieve )
l... |
def listify ( generator_func ) :
'''Converts generator functions into list returning functions .
@ listify
def test ( ) :
yield 1
test ( )''' | def list_func ( * args , ** kwargs ) :
return degenerate ( generator_func ( * args , ** kwargs ) )
return list_func |
def temp44 ( msg ) :
"""Static air temperature .
Args :
msg ( String ) : 28 bytes hexadecimal message string
Returns :
float , float : temperature and alternative temperature in Celsius degree .
Note : Two values returns due to what seems to be an inconsistancy
error in ICAO 9871 ( 2008 ) Appendix A - 6... | d = hex2bin ( data ( msg ) )
sign = int ( d [ 23 ] )
value = bin2int ( d [ 24 : 34 ] )
if sign :
value = value - 1024
temp = value * 0.25
# celsius
temp = round ( temp , 2 )
temp_alternative = value * 0.125
# celsius
temp_alternative = round ( temp , 3 )
return temp , temp_alternative |
def merge ( self , other ) :
"""Merges another ParameterNode into the current node .
In case of child name conflict , the other node child will replace the current node child .""" | for child_name , child in other . children . items ( ) :
self . add_child ( child_name , child ) |
def load ( self , txt_fst_file_name ) :
"""Save the transducer in the text file format of OpenFST .
The format is specified as follows :
arc format : src dest ilabel olabel [ weight ]
final state format : state [ weight ]
lines may occur in any order except initial state must be first line
Args :
txt _ ... | with open ( txt_fst_file_name , 'r' ) as input_filename :
for line in input_filename :
line = line . strip ( )
split_line = line . split ( )
if len ( split_line ) == 1 :
self [ int ( split_line [ 0 ] ) ] . final = True
else :
self . add_arc ( int ( split_line ... |
def open ( self ) :
"""Open Socket and establish a connection .
: raises AMQPConnectionError : Raises if the connection
encountered an error .
: return :""" | self . _wr_lock . acquire ( )
self . _rd_lock . acquire ( )
try :
self . data_in = EMPTY_BUFFER
self . _running . set ( )
sock_addresses = self . _get_socket_addresses ( )
self . socket = self . _find_address_and_connect ( sock_addresses )
self . poller = Poller ( self . socket . fileno ( ) , self .... |
def _set_rp_cand_grp_prefix ( self , v , load = False ) :
"""Setter method for rp _ cand _ grp _ prefix , mapped from YANG variable / rbridge _ id / router / hide _ pim _ holder / pim / rp _ candidate / rp _ cand _ grp _ prefix ( list )
If this variable is read - only ( config : false ) in the
source YANG file ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "rp_cand_grp_prefix_ip rp_cand_grp_prefix_length" , rp_cand_grp_prefix . rp_cand_grp_prefix , yang_name = "rp-cand-grp-prefix" , rest_name = "group-range" , parent = self , is_container = 'list' , user_ordered ... |
def mac_access_list_standard_hide_mac_acl_std_seq_seq_id ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
mac = ET . SubElement ( config , "mac" , xmlns = "urn:brocade.com:mgmt:brocade-mac-access-list" )
access_list = ET . SubElement ( mac , "access-list" )
standard = ET . SubElement ( access_list , "standard" )
name_key = ET . SubElement ( standard , "name" )
name_key . text = kwargs . p... |
def show_command_line_usage ( parser , usage = False ) :
"""Show the command line help""" | help_header_message = get_command_header ( parser , "command" , usage )
loader = template . Loader ( os . path . join ( firenado . conf . ROOT , 'management' , 'templates' , 'help' ) )
command_template = " {0.name:15}{0.description:40}"
help_message = loader . load ( "main_command_help.txt" ) . generate ( command_cate... |
def revoke ( workers , qualification , by_name , reason , sandbox ) :
"""Revoke a qualification from 1 or more workers""" | if not ( workers and qualification ) :
raise click . BadParameter ( "Must specify a qualification ID or name, and at least one worker ID" )
mturk = _mturk_service_from_config ( sandbox )
if by_name :
result = mturk . get_qualification_type_by_name ( qualification )
if result is None :
raise click . ... |
def delete_credential ( self , identifier , credential_id = None ) :
"""Delete the object storage credential .
: param int id : The object storage account identifier .
: param int credential _ id : The credential id to be deleted .""" | credential = { 'id' : credential_id }
return self . client . call ( 'SoftLayer_Network_Storage_Hub_Cleversafe_Account' , 'credentialDelete' , credential , id = identifier ) |
def handle ( self , connection_id , message_content ) :
"""When the validator receives an AuthorizationChallengeSubmit message , it
will verify the public key against the signature . If the public key is
verified , the requested roles will be checked against the stored roles
to see if the public key is includ... | if self . _network . get_connection_status ( connection_id ) != ConnectionStatus . AUTH_CHALLENGE_REQUEST :
LOGGER . debug ( "Connection's previous message was not a" " AuthorizationChallengeRequest, Remove connection to" "%s" , connection_id )
return AuthorizationChallengeSubmitHandler . _network_violation_res... |
def is_holiday ( self , day , extra_holidays = None ) :
"""Return True if it ' s an holiday .
In addition to the regular holidays , you can add exceptions .
By providing ` ` extra _ holidays ` ` , you ' ll state that these dates * * are * *
holidays , even if not in the regular calendar holidays ( or weekends... | day = cleaned_date ( day )
if extra_holidays :
extra_holidays = tuple ( map ( cleaned_date , extra_holidays ) )
if extra_holidays and day in extra_holidays :
return True
return day in self . holidays_set ( day . year ) |
def update_all_files ( dk_api , kitchen , recipe_name , recipe_dir , message , dryrun = False ) :
"""reutrns a string .
: param dk _ api : - - api object
: param kitchen : string
: param recipe _ name : string - - kitchen name , string
: param recipe _ dir : string - path to the root of the directory
: pa... | rc = DKReturnCode ( )
if kitchen is None or recipe_name is None or message is None :
s = 'ERROR: DKCloudCommandRunner bad input parameters'
rc . set ( rc . DK_FAIL , s )
return rc
rc = dk_api . recipe_status ( kitchen , recipe_name , recipe_dir )
if not rc . ok ( ) :
rs = 'DKCloudCommand.update_all_file... |
def dump ( self ) :
"""Dump the cache ( for debugging )""" | for key in self . _store . keys ( ) :
print ( key , ':' , self . get ( key ) ) |
def round_to_05 ( n , exp = None , mode = 's' ) :
"""Round to the next 0.5 - value .
This function applies the round function ` func ` to round ` n ` to the
next 0.5 - value with respect to its exponent with base 10 ( i . e .
1.3e - 4 will be rounded to 1.5e - 4 ) if ` exp ` is None or with respect
to the g... | n = np . asarray ( n )
if exp is None :
exp = np . floor ( np . log10 ( np . abs ( n ) ) )
# exponent for base 10
ntmp = np . abs ( n ) / 10. ** exp
# mantissa for base 10
if mode == 's' :
n1 = ntmp
s = 1.
n2 = nret = np . floor ( ntmp )
else :
n1 = nret = np . ceil ( ntmp )
s = - 1.
n2 ... |
def featureSetsGenerator ( self , request ) :
"""Returns a generator over the ( featureSet , nextPageToken ) pairs
defined by the specified request .""" | dataset = self . getDataRepository ( ) . getDataset ( request . dataset_id )
return self . _topLevelObjectGenerator ( request , dataset . getNumFeatureSets ( ) , dataset . getFeatureSetByIndex ) |
def unnest ( c , elem , ignore_whitespace = False ) :
"""unnest the element from its parent within doc . MUTABLE CHANGES""" | parent = elem . getparent ( )
gparent = parent . getparent ( )
index = parent . index ( elem )
# put everything up to elem into a new parent element right before the current parent
preparent = etree . Element ( parent . tag )
preparent . text , parent . text = ( parent . text or '' ) , ''
for k in parent . attrib . key... |
def connect ( self ) :
"""Connect to MQTT server and wait for server to acknowledge""" | if not self . connect_attempted :
self . connect_attempted = True
self . client . connect ( self . host , port = self . port )
self . client . loop_start ( )
while not self . connected :
log . info ( 'waiting for MQTT connection...' )
time . sleep ( 1 ) |
def get_ca ( ca_name , as_text = False , cacert_path = None ) :
'''Get the certificate path or content
ca _ name
name of the CA
as _ text
if true , return the certificate content instead of the path
cacert _ path
absolute path to ca certificates root directory
CLI Example :
. . code - block : : bash... | set_ca_path ( cacert_path )
certp = '{0}/{1}/{1}_ca_cert.crt' . format ( cert_base_path ( ) , ca_name )
if not os . path . exists ( certp ) :
raise ValueError ( 'Certificate does not exist for {0}' . format ( ca_name ) )
else :
if as_text :
with salt . utils . files . fopen ( certp ) as fic :
... |
def _check_section ( cls , docstring , definition , context ) :
"""D4{05,06,10,11,13 } , D214 : Section name checks .
Check for valid section names . Checks that :
* The section name is properly capitalized ( D405 ) .
* The section is not over - indented ( D214 ) .
* The section name has no superfluous suff... | capitalized_section = context . section_name . title ( )
indentation = cls . _get_docstring_indent ( definition , docstring )
if ( context . section_name not in cls . SECTION_NAMES and capitalized_section in cls . SECTION_NAMES ) :
yield violations . D405 ( capitalized_section , context . section_name )
if leading_... |
def get_state ( self ) :
"""Get general information about the state of the class""" | return { "started" : ( True if self . background_process and self . background_process . is_alive ( ) else False ) , "paused" : self . _pause . value , "stopped" : self . _end . value , "tasks" : len ( self . current_tasks ) , "busy_tasks" : len ( self . busy_tasks ) , "free_tasks" : len ( self . free_tasks ) } |
def load_post ( self , wp_post_id ) :
"""Refresh local content for a single post from the the WordPress REST API .
This can be called from a webhook on the WordPress side when a post is updated .
: param wp _ post _ id : the wordpress post ID
: return : the fully loaded local post object""" | path = "sites/{}/posts/{}" . format ( self . site_id , wp_post_id )
response = self . get ( path )
if response . ok and response . text :
api_post = response . json ( )
self . get_ref_data_map ( bulk_mode = False )
self . load_wp_post ( api_post , bulk_mode = False )
# the post should exist in the db no... |
def pop ( self ) :
"""Pop the top frame from the stack . Return the new stack .""" | if self . next is None :
raise SimEmptyCallStackError ( "Cannot pop a frame from an empty call stack." )
new_list = self . next . copy ( { } )
if self . state is not None :
self . state . register_plugin ( 'callstack' , new_list )
self . state . history . recent_stack_actions . append ( CallStackAction ( ha... |
def start ( self , join = False ) :
"""when calling with join = True , must call it in main thread , or else , the Keyboard Interrupt won ' t be caputured .
: param join : default False , if hold on until the worker is stopped by Ctrl + C or other reasons .
: return :""" | Thread . start ( self )
if join :
try :
while self . is_alive ( ) :
self . join ( timeout = 60 )
self . logger . info ( "worker {0} exit unexpected, try to shutdown it" . format ( self . option . consumer_name ) )
self . shutdown ( )
except KeyboardInterrupt :
self . ... |
def postgis_path_to_uri ( path ) :
"""Convert layer path from QgsBrowserModel to full QgsDataSourceUri .
: param path : The layer path from QgsBrowserModel
: type path : string
: returns : layer uri .
: rtype : QgsDataSourceUri""" | connection_name = path . split ( '/' ) [ 1 ]
schema = path . split ( '/' ) [ 2 ]
table_name = path . split ( '/' ) [ 3 ]
settings = QSettings ( )
key = "/PostgreSQL/connections/" + connection_name
service = settings . value ( key + "/service" )
host = settings . value ( key + "/host" )
port = settings . value ( key + "... |
def service_response ( body , headers , status_code ) :
"""Constructs a Flask Response from the body , headers , and status _ code .
: param str body : Response body as a string
: param dict headers : headers for the response
: param int status _ code : status _ code for response
: return : Flask Response""... | response = Response ( body )
response . headers = headers
response . status_code = status_code
return response |
def ParsePageVisitRow ( self , parser_mediator , query , row , ** unused_kwargs ) :
"""Parses a visited row .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
query ( str ) : query that created the row .
row ( sqlite3 . ... | query_hash = hash ( query )
was_http_non_get = self . _GetRowValue ( query_hash , row , 'http_non_get' )
event_data = SafariHistoryPageVisitedEventData ( )
event_data . offset = self . _GetRowValue ( query_hash , row , 'id' )
event_data . query = query
event_data . title = self . _GetRowValue ( query_hash , row , 'titl... |
def _check ( self , sock_info ) :
"""This side - effecty function checks if this socket has been idle for
for longer than the max idle time , or if the socket has been closed by
some external network error , and if so , attempts to create a new
socket . If this connection attempt fails we raise the
Connecti... | idle_time_seconds = sock_info . idle_time_seconds ( )
# If socket is idle , open a new one .
if ( self . opts . max_idle_time_seconds is not None and idle_time_seconds > self . opts . max_idle_time_seconds ) :
sock_info . close ( )
return self . connect ( )
if ( self . _check_interval_seconds is not None and ( ... |
def is_following ( self , login ) :
"""Check if the authenticated user is following login .
: param str login : ( required ) , login of the user to check if the
authenticated user is checking
: returns : bool""" | json = False
if login :
url = self . _build_url ( 'user' , 'following' , login )
json = self . _boolean ( self . _get ( url ) , 204 , 404 )
return json |
def get_disorder_subseq_3D ( protein , pdbflex_keys_file , disorder_cutoff = 2 , disorder_condition = '>' ) :
"""DISORDERED REGION 3D""" | with open ( pdbflex_keys_file , 'r' ) as f :
pdbflex_keys = json . load ( f )
if protein . id not in pdbflex_keys :
log . warning ( '{}: no PDBFlex info available' . format ( protein . id ) )
final_repseq_sub , final_repseq_sub_resnums = ( None , [ ] )
else : # Gather disordered regions for all mapped PDBFl... |
def to_dict ( self ) :
"""Return a dictionary of the job stats .
Returns :
dict : Dictionary of the stats .""" | return { 'name' : self . name , 'id' : self . id , 'type' : self . type , 'workflow_id' : self . workflow_id , 'queue' : self . queue , 'start_time' : self . start_time , 'arguments' : self . arguments , 'acknowledged' : self . acknowledged , 'func_name' : self . func_name , 'hostname' : self . hostname , 'worker_name'... |
def count_moves_in_game_range ( self , game_begin , game_end ) :
"""Count the total moves in a game range .
Args :
game _ begin : integer , starting game
game _ end : integer , ending game
Uses the ` ct _ ` keyspace for rapid move summary .""" | rows = self . bt_table . read_rows ( ROWCOUNT_PREFIX . format ( game_begin ) , ROWCOUNT_PREFIX . format ( game_end ) , filter_ = bigtable_row_filters . ColumnRangeFilter ( METADATA , MOVE_COUNT , MOVE_COUNT ) )
return sum ( [ int ( r . cell_value ( METADATA , MOVE_COUNT ) ) for r in rows ] ) |
def generate_traffic ( self , start_page , destination_page , loops = 1 ) :
"""Similar to generate _ referral ( ) , but can do multiple loops .""" | for loop in range ( loops ) :
self . generate_referral ( start_page , destination_page )
time . sleep ( 0.05 ) |
def try_and_error ( * funcs ) :
"""Apply multiple validation functions
Parameters
` ` * funcs ` `
Validation functions to test
Returns
function""" | def validate ( value ) :
exc = None
for func in funcs :
try :
return func ( value )
except ( ValueError , TypeError ) as e :
exc = e
raise exc
return validate |
def prepare_notebook_context ( request , notebook_context ) :
"""Fill in notebook context with default values .""" | if not notebook_context :
notebook_context = { }
# Override notebook Jinja templates
if "extra_template_paths" not in notebook_context :
notebook_context [ "extra_template_paths" ] = [ os . path . join ( os . path . dirname ( __file__ ) , "server" , "templates" ) ]
# Furious invalid state follows if we let this... |
def on_save_interpretation_button ( self , event ) :
"""on the save button the interpretation is saved to pmag _ results _ table
data in all coordinate systems""" | if self . current_fit :
self . current_fit . saved = True
calculation_type = self . current_fit . get ( self . COORDINATE_SYSTEM ) [ 'calculation_type' ]
tmin = str ( self . tmin_box . GetValue ( ) )
tmax = str ( self . tmax_box . GetValue ( ) )
self . current_fit . put ( self . s , 'specimen' , sel... |
def filter_ ( f , x ) :
"""function version of filter , when ` x ` is a Functor of Monoid , it will call :
` reduce ( lambda e : e . extend , x . fmap ( f ) ) `""" | return reduce ( lambda e , v : e . extend ( v ) , x . fmap ( f ) ) |
def update_customer_group_by_id ( cls , customer_group_id , customer_group , ** kwargs ) :
"""Update CustomerGroup
Update attributes of CustomerGroup
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . update _ custom... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _update_customer_group_by_id_with_http_info ( customer_group_id , customer_group , ** kwargs )
else :
( data ) = cls . _update_customer_group_by_id_with_http_info ( customer_group_id , customer_group , ** kwargs )
return d... |
def reopen ( self ) :
"""Reopen the pooled connection .""" | # If the connection is already back in the pool ,
# get another connection from the pool ,
# otherwise reopen the underlying connection .
if self . _con :
self . _con . reopen ( )
else :
self . _con = self . _pool . connection ( ) |
def send_message_and_wait ( self , message , response_emsg , body_params = None , timeout = None , raises = False ) :
""". . versionchanged : : 0.8.4
Send a message to CM and wait for a defined answer .
: param message : a message instance
: type message : : class : ` . Msg ` , : class : ` . MsgProto `
: pa... | self . send ( message , body_params )
response = self . wait_event ( response_emsg , timeout , raises = raises )
if response is None :
return None
return response [ 0 ] . body |
def create_gzip_file ( filepath , overwrite ) :
'''Create a gzipped file in the same directory with a filepath . gz name .
: param filepath : A file to compress
: param overwrite : Whether the original file should be overwritten''' | compressed_path = filepath + '.gz'
with open ( filepath , 'rb' ) as uncompressed :
gzip_compress_obj = zlib . compressobj ( COMPRESSION_LEVEL , zlib . DEFLATED , WBITS )
uncompressed_data = uncompressed . read ( )
gzipped_data = gzip_compress_obj . compress ( uncompressed_data )
gzipped_data += gzip_com... |
def sarea_ ( self , col , x = None , y = None , rsum = None , rmean = None ) :
"""Get an stacked area chart""" | try :
charts = self . _multiseries ( col , x , y , "area" , rsum , rmean )
return hv . Area . stack ( charts )
except Exception as e :
self . err ( e , self . sarea_ , "Can not draw stacked area chart" ) |
def accelerated_proximal_gradient ( x , f , g , gamma , niter , callback = None , ** kwargs ) :
r"""Accelerated proximal gradient algorithm for convex optimization .
The method is known as " Fast Iterative Soft - Thresholding Algorithm "
( FISTA ) . See ` [ Beck2009 ] ` _ for more information .
Solves the con... | # Get and validate input
if x not in f . domain :
raise TypeError ( '`x` {!r} is not in the domain of `f` {!r}' '' . format ( x , f . domain ) )
if x not in g . domain :
raise TypeError ( '`x` {!r} is not in the domain of `g` {!r}' '' . format ( x , g . domain ) )
gamma , gamma_in = float ( gamma ) , gamma
if g... |
def push ( self , repository = None , tag = None ) :
"""Push image to registry . Raise exception when push fail .
: param repository : str , see constructor
: param tag : str , see constructor
: return : None""" | image = self
if repository or tag :
image = self . tag_image ( repository , tag )
for json_e in self . d . push ( repository = image . name , tag = image . tag , stream = True , decode = True ) :
logger . debug ( json_e )
status = graceful_get ( json_e , "status" )
if status :
logger . info ( st... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.