signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_wegobject_by_id ( self , id ) :
'''Retrieve a ` Wegobject ` by the Id .
: param integer id : the Id of the ` Wegobject `
: rtype : : class : ` Wegobject `''' | def creator ( ) :
res = crab_gateway_request ( self . client , 'GetWegobjectByIdentificatorWegobject' , id )
if res == None :
raise GatewayResourceNotFoundException ( )
return Wegobject ( res . IdentificatorWegobject , res . AardWegobject , ( res . CenterX , res . CenterY ) , ( res . MinimumX , res ... |
def get_source ( self , objtxt ) :
"""Get object source""" | from spyder_kernels . utils . dochelpers import getsource
obj , valid = self . _eval ( objtxt )
if valid :
return getsource ( obj ) |
def start ( self ) :
"""Start the dev session . Attempt to use tornado first , then try
twisted""" | print ( "Starting debug client cwd: {}" . format ( os . getcwd ( ) ) )
print ( "Sys path: {}" . format ( sys . path ) )
# : Initialize the hotswapper
self . hotswap = Hotswapper ( debug = False )
if self . mode == 'server' :
self . server . start ( self )
else :
self . client . start ( self ) |
def get_data_by_slug_or_404 ( model , slug , kind = '' , ** kwargs ) :
"""Wrap get _ data _ by _ slug , abort 404 if missing data .""" | data = get_data_by_slug ( model , slug , kind , ** kwargs )
if not data :
abort ( 404 )
return data |
def check_support_ucannet ( cls , hw_info_ex ) :
"""Checks whether the module supports the usage of USB - CANnetwork driver .
: param HardwareInfoEx hw _ info _ ex :
Extended hardware information structure ( see method : meth : ` get _ hardware _ info ` ) .
: return : True when the module does support the usa... | return cls . check_is_systec ( hw_info_ex ) and cls . check_version_is_equal_or_higher ( hw_info_ex . m_dwFwVersionEx , 3 , 8 ) |
def setImage ( self , image = None , autoLevels = None , ** kargs ) :
"""Same this as ImageItem . setImage , but we don ' t update the drawing""" | profile = debug . Profiler ( )
gotNewData = False
if image is None :
if self . image is None :
return
else :
gotNewData = True
shapeChanged = ( self . image is None or image . shape != self . image . shape )
image = image . view ( np . ndarray )
if self . image is None or image . dtype != se... |
def inject_instance ( self , classkey = None , allow_override = False , verbose = VERBOSE_CLASS , strict = True ) :
"""Injects an instance ( self ) of type ( classkey )
with all functions registered to ( classkey )
call this in the _ _ init _ _ class function
Args :
self : the class instance
classkey : ke... | import utool as ut
if verbose :
print ( '[util_class] begin inject_instance' )
try :
if classkey is None : # Probably should depricate this block of code
# It tries to do too much
classkey = self . __class__
if classkey == 'ibeis.gui.models_and_views.IBEISTableView' : # HACK HACK HACK
... |
def _adjustSectionAlignment ( self , value , fileAlignment , sectionAlignment ) :
"""Align a value to C { SectionAligment } .
@ type value : int
@ param value : The value to be aligned .
@ type fileAlignment : int
@ param fileAlignment : The value to be used as C { FileAlignment } .
@ type sectionAlignmen... | if fileAlignment < consts . DEFAULT_FILE_ALIGNMENT :
if fileAligment != sectionAlignment :
print "FileAlignment does not match SectionAlignment."
if sectionAlignment < consts . DEFAULT_PAGE_SIZE :
sectionAlignment = fileAlignment
if sectionAlignment and value % sectionAlignment :
return sectionAlign... |
def compare_runtime ( test , decimal = 5 , options = None , verbose = False , context = None ) :
"""The function compares the expected output ( computed with
the model before being converted to ONNX ) and the ONNX output
produced with module * onnxruntime * .
: param test : dictionary with the following keys ... | if context is None :
context = { }
load = load_data_and_model ( test , ** context )
onx = test [ 'onnx' ]
if options is None :
if isinstance ( onx , str ) :
options = extract_options ( onx )
else :
options = { }
elif options is None :
options = { }
elif not isinstance ( options , dict ) ... |
def close ( self , autocommit = True ) :
"""Close the coordinator , leave the current group ,
and reset local generation / member _ id .
Keyword Arguments :
autocommit ( bool ) : If auto - commit is configured for this consumer ,
this optional flag causes the consumer to attempt to commit any
pending cons... | try :
if autocommit :
self . _maybe_auto_commit_offsets_sync ( )
finally :
super ( ConsumerCoordinator , self ) . close ( ) |
def play_track ( self , track_id = DEFAULT_TRACK_ID , position = 0 ) :
"""Plays a track at the given position .""" | self . publish ( action = 'playTrack' , resource = 'audioPlayback/player' , publish_response = False , properties = { 'trackId' : track_id , 'position' : position } ) |
def ovsdb_server_name ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
ovsdb_server = ET . SubElement ( config , "ovsdb-server" , xmlns = "urn:brocade.com:mgmt:brocade-tunnels" )
name = ET . SubElement ( ovsdb_server , "name" )
name . text = kwargs . pop ( 'name' )
callback = kwargs . pop ( 'callback' , self . _callback )
return callback ( config ) |
def rename_pipe ( self , old_name , new_name ) :
"""Rename a pipeline component .
old _ name ( unicode ) : Name of the component to rename .
new _ name ( unicode ) : New name of the component .
DOCS : https : / / spacy . io / api / language # rename _ pipe""" | if old_name not in self . pipe_names :
raise ValueError ( Errors . E001 . format ( name = old_name , opts = self . pipe_names ) )
if new_name in self . pipe_names :
raise ValueError ( Errors . E007 . format ( name = new_name , opts = self . pipe_names ) )
i = self . pipe_names . index ( old_name )
self . pipeli... |
def monitoring_plot ( ind , shap_values , features , feature_names = None ) :
"""Create a SHAP monitoring plot .
( Note this function is preliminary and subject to change ! ! )
A SHAP monitoring plot is meant to display the behavior of a model
over time . Often the shap _ values given to this plot explain the... | if str ( type ( features ) ) . endswith ( "'pandas.core.frame.DataFrame'>" ) :
if feature_names is None :
feature_names = features . columns
features = features . values
pl . figure ( figsize = ( 10 , 3 ) )
ys = shap_values [ : , ind ]
xs = np . arange ( len ( ys ) )
# np . linspace ( 0 , 12*2 , len ( y... |
def server ( self ) :
"""Connection to the server""" | if self . _server is None :
self . _server = bugzilla . Bugzilla ( url = self . parent . url )
return self . _server |
def sets ( self ) :
"""Get list of sets .""" | if self . cache :
return self . cache . get ( self . app . config [ 'OAISERVER_CACHE_KEY' ] ) |
def new_project ( ) :
"""New Project .""" | form = NewProjectForm ( )
if not form . validate_on_submit ( ) :
return jsonify ( errors = form . errors ) , 400
data = form . data
data [ 'slug' ] = slugify ( data [ 'name' ] )
data [ 'owner_id' ] = get_current_user_id ( )
id = add_instance ( 'project' , ** data )
if not id :
return jsonify ( errors = { 'name'... |
def admin_keywords_submit ( request ) :
"""Adds any new given keywords from the custom keywords field in the
admin , and returns their IDs for use when saving a model with a
keywords field .""" | keyword_ids , titles = [ ] , [ ]
remove = punctuation . replace ( "-" , "" )
# Strip punctuation , allow dashes .
for title in request . POST . get ( "text_keywords" , "" ) . split ( "," ) :
title = "" . join ( [ c for c in title if c not in remove ] ) . strip ( )
if title :
kw , created = Keyword . obj... |
def coords_to_vec ( lon , lat ) :
"""Converts longitute and latitude coordinates to a unit 3 - vector
return array ( 3 , n ) with v _ x [ i ] , v _ y [ i ] , v _ z [ i ] = directional cosines""" | phi = np . radians ( lon )
theta = ( np . pi / 2 ) - np . radians ( lat )
sin_t = np . sin ( theta )
cos_t = np . cos ( theta )
xVals = sin_t * np . cos ( phi )
yVals = sin_t * np . sin ( phi )
zVals = cos_t
# Stack them into the output array
out = np . vstack ( ( xVals , yVals , zVals ) ) . swapaxes ( 0 , 1 )
return o... |
def show ( commands , raw_text = True , ** kwargs ) :
'''Execute one or more show ( non - configuration ) commands .
commands
The commands to be executed .
raw _ text : ` ` True ` `
Whether to return raw text or structured data .
transport : ` ` https ` `
Specifies the type of connection transport to us... | ret = [ ]
if raw_text :
method = 'cli_ascii'
key = 'msg'
else :
method = 'cli'
key = 'body'
response_list = _cli_command ( commands , method = method , ** kwargs )
ret = [ response [ key ] for response in response_list if response ]
return ret |
def assert_numbers_almost_equal ( self , actual_val , expected_val , allowed_delta = 0.0001 , failure_message = 'Expected numbers to be within {} of each other: "{}" and "{}"' ) :
"""Asserts that two numbers are within an allowed delta of each other""" | assertion = lambda : abs ( expected_val - actual_val ) <= allowed_delta
self . webdriver_assert ( assertion , unicode ( failure_message ) . format ( allowed_delta , actual_val , expected_val ) ) |
def generate_py_units ( data ) :
"""Generate the list of units in units . py .""" | units = collections . defaultdict ( list )
for unit in sorted ( data . units , key = lambda a : a . name ) :
if unit . unit_id in static_data . UNIT_TYPES :
units [ unit . race ] . append ( unit )
def print_race ( name , race ) :
print ( "class %s(enum.IntEnum):" % name )
print ( ' """%s units."""'... |
def get ( self , key ) :
"""Get an item from the cache
Args :
key : item key
Returns :
the value of the item or None if the item isn ' t in the cache""" | data = self . _store . get ( key )
if not data :
return None
value , expire = data
if expire and time . time ( ) > expire :
del self . _store [ key ]
return None
return value |
def _typecheck_fsnative ( path ) :
"""Args :
path ( object )
Returns :
bool : if path is a fsnative""" | if not isinstance ( path , fsnative_type ) :
return False
if PY3 or is_win :
if u"\x00" in path :
return False
if is_unix :
try :
path . encode ( _encoding , "surrogateescape" )
except UnicodeEncodeError :
return False
elif b"\x00" in path :
return False
r... |
def remove ( self ) :
"""Remove authenticator
. . note : :
After removing authenticator Steam Guard will be set to email codes
. . warning : :
Doesn ' t work via : class : ` . SteamClient ` . Disabled by Valve
: raises : : class : ` SteamAuthenticatorError `""" | if not self . secrets :
raise SteamAuthenticatorError ( "No authenticator secrets available?" )
if not isinstance ( self . backend , MobileWebAuth ) :
raise SteamAuthenticatorError ( "Only available via MobileWebAuth" )
resp = self . _send_request ( 'RemoveAuthenticator' , { 'steamid' : self . backend . steam_i... |
def assemble_cyjs ( ) :
"""Assemble INDRA Statements and return Cytoscape JS network .""" | if request . method == 'OPTIONS' :
return { }
response = request . body . read ( ) . decode ( 'utf-8' )
body = json . loads ( response )
stmts_json = body . get ( 'statements' )
stmts = stmts_from_json ( stmts_json )
cja = CyJSAssembler ( )
cja . add_statements ( stmts )
cja . make_model ( grouping = True )
model_s... |
def get_sensors ( self ) :
"""Get sensors as a dictionary of format ` ` { name : status } ` `""" | return { i . name : i . status for i in self . system . sensors } |
def comment_from_tag ( tag ) :
"""Convenience function to create a full - fledged comment for a
given tag , for example it is convenient to assign a Comment
to a ReturnValueSymbol .""" | if not tag :
return None
comment = Comment ( name = tag . name , meta = { 'description' : tag . description } , annotations = tag . annotations )
return comment |
def list_projects ( self ) :
"""Returns the list of projects owned by user .""" | data = self . _run ( url_path = "projects/list" )
projects = data [ 'result' ] . get ( 'projects' , [ ] )
return [ self . _project_formatter ( item ) for item in projects ] |
def _get_stitch_report_path ( self ) :
"""Checks if stitch report label / path is set . Returns absolute path .""" | if self . Parameters [ '-r' ] . isOn ( ) :
stitch_path = self . _absolute ( str ( self . Parameters [ '-r' ] . Value ) )
return stitch_path
elif self . Parameters [ '-r' ] . isOff ( ) :
return None |
def list_tab ( user ) :
'''Return the contents of the specified user ' s crontab
CLI Example :
. . code - block : : bash
salt ' * ' cron . list _ tab root''' | data = raw_cron ( user )
ret = { 'pre' : [ ] , 'crons' : [ ] , 'special' : [ ] , 'env' : [ ] }
flag = False
comment = None
identifier = None
for line in data . splitlines ( ) :
if line == '# Lines below here are managed by Salt, do not edit' :
flag = True
continue
if flag :
commented_cro... |
def DbGetClassList ( self , argin ) :
"""Get Tango class list with a specified filter
: param argin : Filter
: type : tango . DevString
: return : Class list
: rtype : tango . DevVarStringArray""" | self . _log . debug ( "In DbGetClassList()" )
server = replace_wildcard ( argin )
return self . db . get_class_list ( server ) |
def edge_statistics ( docgraph ) :
"""print basic statistics about an edge , e . g . layer / attribute counts""" | print "Edge statistics\n==============="
layer_counts = Counter ( )
attrib_counts = Counter ( )
source_counts = Counter ( )
target_counts = Counter ( )
for source , target , edge_attrs in docgraph . edges_iter ( data = True ) :
for layer in edge_attrs [ 'layers' ] :
layer_counts [ layer ] += 1
for attri... |
def add_check ( self , check_item ) :
"""Adds a check universally .""" | self . checks . append ( check_item )
for other in self . others :
other . add_check ( check_item ) |
def specs_from_graph ( graph : nx . Graph ) :
"""Generate a Specs object from a NetworkX graph with placeholder values for the actual specs .
: param graph : The graph""" | qspecs = [ QubitSpecs ( id = q , fRO = 0.90 , f1QRB = 0.99 , T1 = 30e-6 , T2 = 30e-6 , fActiveReset = 0.99 ) for q in graph . nodes ]
especs = [ EdgeSpecs ( targets = ( q1 , q2 ) , fBellState = 0.90 , fCZ = 0.90 , fCZ_std_err = 0.05 , fCPHASE = 0.80 ) for q1 , q2 in graph . edges ]
return Specs ( qspecs , especs ) |
def count_tables ( filename_or_fobj , encoding = "utf-8" , table_tag = "table" ) :
"""Read a file passed by arg and return your table HTML tag count .""" | source = Source . from_file ( filename_or_fobj , plugin_name = "html" , mode = "rb" , encoding = encoding )
html = source . fobj . read ( ) . decode ( source . encoding )
html_tree = document_fromstring ( html )
tables = html_tree . xpath ( "//{}" . format ( table_tag ) )
result = len ( tables )
if source . should_clos... |
def _string_to_byte_list ( self , data ) :
"""Creates a hex digest of the input string given to create the image ,
if it ' s not already hexadecimal
Returns :
Length 16 list of rgb value range integers
( each representing a byte of the hex digest )""" | bytes_length = 16
m = self . digest ( )
m . update ( str . encode ( data ) )
hex_digest = m . hexdigest ( )
return list ( int ( hex_digest [ num * 2 : num * 2 + 2 ] , bytes_length ) for num in range ( bytes_length ) ) |
def delete_source ( self , id ) :
"""Delete a source from the catalog
Parameters
id : int
The id of the source in the catalog""" | # Set the index
self . catalog . set_index ( 'id' )
# Exclude the unwanted source
self . catalog = self . catalog [ self . catalog . id != id ]
# Remove the records from the catalogs
for cat_name in self . catalogs :
new_cat = getattr ( self , cat_name ) [ getattr ( self , cat_name ) . source_id != id ]
print (... |
def parse_parametrs ( p ) :
"""Parses the parameters given from POST or websocket reqs
expecting the parameters as : " 11 | par1 = ' asd ' | 6 | par2 = 1"
returns a dict like { par1 : ' asd ' , par2:1}""" | ret = { }
while len ( p ) > 1 and p . count ( '|' ) > 0 :
s = p . split ( '|' )
l = int ( s [ 0 ] )
# length of param field
if l > 0 :
p = p [ len ( s [ 0 ] ) + 1 : ]
field_name = p . split ( '|' ) [ 0 ] . split ( '=' ) [ 0 ]
field_value = p [ len ( field_name ) + 1 : l ]
... |
def ParseApplicationResourceUsage ( self , parser_mediator , cache = None , database = None , table = None , ** unused_kwargs ) :
"""Parses the application resource usage table .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvf... | self . _ParseGUIDTable ( parser_mediator , cache , database , table , self . _APPLICATION_RESOURCE_USAGE_VALUES_MAP , SRUMApplicationResourceUsageEventData ) |
def decline_weak_masculine_noun ( ns : str , gs : str , np : str ) :
"""Gives the full declension of weak masculine nouns .
> > > decline _ weak _ masculine _ noun ( " goði " , " goða " , " goðar " )
goði
goða
goða
goða
goðar
goða
goðum
goða
> > > decline _ weak _ masculine _ noun ( " hluti " , ... | # nominative singular
print ( ns )
# accusative singular
print ( gs )
# dative singular
print ( gs )
# genitive singular
print ( gs )
# nominative plural
print ( np )
# accusative plural
print ( np [ : - 1 ] )
# dative plural
if len ( np ) > 3 and np [ - 3 ] == "v" :
print ( apply_u_umlaut ( np [ : - 3 ] ) + "um" )... |
def check_implicit_rules ( self ) :
"""if you are using flask classy are using the standard index , new , put , post , etc . . . type routes , we will
automatically check the permissions for you""" | if not self . request_is_managed_by_flask_classy ( ) :
return
if self . method_is_explictly_overwritten ( ) :
return
class_name , action = request . endpoint . split ( ':' )
clazz = [ classy_class for classy_class in self . flask_classy_classes if classy_class . __name__ == class_name ] [ 0 ]
Condition ( action... |
def as_list ( self ) :
"""Returns GO annotation as a flat list ( in GAF 2.1 format order ) .""" | go_id = self . go_term . id
qual_str = '|' . join ( self . qualifier )
db_ref_str = '|' . join ( self . db_ref )
taxon_str = '|' . join ( self . taxon )
# with _ from is currently left as a string
# with _ from = ' | ' . join ( )
with_from_str = self . with_from or ''
db_name_str = self . db_name or ''
db_syn_str = '|'... |
def get_ports ( proto = 'tcp' , direction = 'in' ) :
'''Lists ports from csf . conf based on direction and protocol .
e . g . - TCP _ IN , TCP _ OUT , UDP _ IN , UDP _ OUT , etc . .
CLI Example :
. . code - block : : bash
salt ' * ' csf . allow _ port 22 proto = ' tcp ' direction = ' in ' ''' | proto = proto . upper ( )
direction = direction . upper ( )
results = { }
_validate_direction_and_proto ( direction , proto )
directions = build_directions ( direction )
for direction in directions :
option = '{0}_{1}' . format ( proto , direction )
results [ direction ] = _csf_to_list ( option )
return results |
def convolve2d_disk ( fn , r , sig , nstep = 200 ) :
"""Evaluate the convolution f ' ( r ) = f ( r ) * g ( r ) where f ( r ) is
azimuthally symmetric function in two dimensions and g is a
step function given by :
g ( r ) = H ( 1 - r / s )
Parameters
fn : function
Input function that takes a single radia... | r = np . array ( r , ndmin = 1 )
sig = np . array ( sig , ndmin = 1 )
rmin = r - sig
rmax = r + sig
rmin [ rmin < 0 ] = 0
delta = ( rmax - rmin ) / nstep
redge = rmin [ ... , np . newaxis ] + delta [ ... , np . newaxis ] * np . linspace ( 0 , nstep , nstep + 1 )
rp = 0.5 * ( redge [ ... , 1 : ] + redge [ ... , : - 1 ] ... |
def _comm_changed ( self , change ) :
"""Called when the comm is changed .""" | if change [ 'new' ] is None :
return
self . _model_id = self . model_id
self . comm . on_msg ( self . _handle_msg )
Widget . widgets [ self . model_id ] = self |
def from_cmyk ( c , m , y , k , alpha = 1.0 , wref = _DEFAULT_WREF ) :
"""Create a new instance based on the specifed CMYK values .
Parameters :
The Cyan component value [ 0 . . . 1]
The Magenta component value [ 0 . . . 1]
The Yellow component value [ 0 . . . 1]
The Black component value [ 0 . . . 1]
:... | return Color ( cmy_to_rgb ( * cmyk_to_cmy ( c , m , y , k ) ) , 'rgb' , alpha , wref ) |
def delete ( self , url ) :
"""Http delete method wrapper , to support delete .""" | try :
res = requests . delete ( url , headers = self . headers )
return json . loads ( res . text )
except Exception as e :
print ( e )
return "error" |
def compute_freq ( self , csd = False ) :
"""Compute frequency domain analysis .
Returns
list of dict
each item is a dict where ' data ' is an instance of ChanFreq for a
single segment of signal , ' name ' is the event type , if applicable ,
' times ' is a tuple of the start and end times in sec , ' durat... | progress = QProgressDialog ( 'Computing frequency' , 'Abort' , 0 , len ( self . data ) - 1 , self )
progress . setWindowModality ( Qt . ApplicationModal )
freq = self . frequency
prep = freq [ 'prep' ] . get_value ( )
scaling = freq [ 'scaling' ] . get_value ( )
log_trans = freq [ 'log_trans' ] . get_value ( )
# sides ... |
def start ( self ) :
"""Start the daemon""" | if self . _already_running ( ) :
message = 'pid file %s already exists. Daemon already running?\n'
sys . stderr . write ( message % self . pid_file )
return 0
self . set_gid ( )
self . set_uid ( )
# Create log files ( if configured ) with the new user / group . Creating
# them as root would allow symlink ex... |
def endpoint_show ( endpoint_id ) :
"""Executor for ` globus endpoint show `""" | client = get_client ( )
res = client . get_endpoint ( endpoint_id )
formatted_print ( res , text_format = FORMAT_TEXT_RECORD , fields = GCP_FIELDS if res [ "is_globus_connect" ] else STANDARD_FIELDS , ) |
def xor_ ( * validation_func # type : ValidationFuncs
) : # type : ( . . . ) - > Callable
"""A ' xor ' validation function : returns ` True ` if exactly one of the provided validators returns ` True ` . All exceptions
will be silently caught . In case of failure , a global ` XorTooManySuccess ` or ` AllValidators... | validation_func = _process_validation_function_s ( list ( validation_func ) , auto_and_wrapper = False )
if len ( validation_func ) == 1 :
return validation_func [ 0 ]
# simplification for single validation function case
else :
def xor_v_ ( x ) :
ok_validators = [ ]
for val_func in validatio... |
def _record_buffer ( records , buffer_size = DEFAULT_BUFFER_SIZE ) :
"""Buffer for transform functions which require multiple passes through data .
Value returned by context manager is a function which returns an iterator
through records .""" | with tempfile . SpooledTemporaryFile ( buffer_size , mode = 'wb+' ) as tf :
pickler = pickle . Pickler ( tf )
for record in records :
pickler . dump ( record )
def record_iter ( ) :
tf . seek ( 0 )
unpickler = pickle . Unpickler ( tf )
while True :
try :
... |
def assert_gt ( left , right , message = None , extra = None ) :
"""Raises an AssertionError if left _ hand < = right _ hand .""" | assert left > right , _assert_fail_message ( message , left , right , "<=" , extra ) |
def check ( self ) :
"""Check if the detector changed and call sync ( ) accordingly .
If the sleep time has elapsed , this method will see if the attached
detector has had a state change and call sync ( ) accordingly .""" | if self . needs_check ( ) :
if self . has_state_changed ( ) :
LOG . debug ( "state changed, syncing..." )
self . sync ( )
elif self . needs_sync ( ) :
LOG . debug ( "forcing sync after %s seconds" , self . forceipchangedetection_sleep )
self . lastforce = time . time ( )
... |
def allreduce_ring_single_shard ( xs , devices , reduction_fn_string = "SUM" ) :
"""Compute the reduction of all Tensors and put the result everywhere .
Performance - optimized for a ring of devices .
Args :
xs : a list of n tf . Tensors
devices : a list of strings
reduction _ fn _ string : " SUM " or " M... | n = len ( xs )
binary_reduction = mtf . binary_reduction_fn ( reduction_fn_string )
assert len ( devices ) == n , "devices must be a list of length len(xs)"
if n == 1 :
return xs
result = [ None ] * n
if n % 2 == 0 :
left_center = n // 2 - 1
right_center = left_center + 1
else :
left_center = n // 2
... |
def produces ( * content_types ) :
"""Define content types produced by an endpoint .""" | def inner ( o ) :
if not all ( isinstance ( content_type , _compat . string_types ) for content_type in content_types ) :
raise ValueError ( "In parameter not a valid value." )
try :
getattr ( o , 'produces' ) . update ( content_types )
except AttributeError :
setattr ( o , 'produces... |
def paragraphs ( self ) :
"""Immutable sequence of | _ Paragraph | instances corresponding to the
paragraphs in this text frame . A text frame always contains at least
one paragraph .""" | return tuple ( [ _Paragraph ( p , self ) for p in self . _txBody . p_lst ] ) |
def visit_SetComp ( self , node : ast . SetComp ) -> Any :
"""Compile the set comprehension as a function and call it .""" | result = self . _execute_comprehension ( node = node )
for generator in node . generators :
self . visit ( generator . iter )
self . recomputed_values [ node ] = result
return result |
def cap_list ( caps ) :
"""Given a cap string , return a list of cap , value .""" | out = [ ]
caps = caps . split ( )
for cap in caps : # turn modifier chars into named modifiers
mods = [ ]
while len ( cap ) > 0 and cap [ 0 ] in cap_modifiers :
attr = cap [ 0 ]
cap = cap [ 1 : ]
mods . append ( cap_modifiers [ attr ] )
# either give string value or None if not speci... |
def get_session ( user_agent = None , user_agent_config_yaml = None , user_agent_lookup = None , ** kwargs ) : # type : ( Optional [ str ] , Optional [ str ] , Optional [ str ] , Any ) - > requests . Session
"""Set up and return Session object that is set up with retrying . Requires either global user agent to be s... | s = requests . Session ( )
ua = kwargs . get ( 'full_agent' )
if not ua :
ua = UserAgent . get ( user_agent , user_agent_config_yaml , user_agent_lookup , ** kwargs )
s . headers [ 'User-Agent' ] = ua
extra_params = os . getenv ( 'EXTRA_PARAMS' )
if extra_params is not None :
extra_params_dict = dict ( )
if... |
def _upstart_is_disabled ( name ) :
'''An Upstart service is assumed disabled if a manual stanza is
placed in / etc / init / [ name ] . override .
NOTE : An Upstart service can also be disabled by placing " manual "
in / etc / init / [ name ] . conf .''' | files = [ '/etc/init/{0}.conf' . format ( name ) , '/etc/init/{0}.override' . format ( name ) ]
for file_name in filter ( os . path . isfile , files ) :
with salt . utils . files . fopen ( file_name ) as fp_ :
if re . search ( r'^\s*manual' , salt . utils . stringutils . to_unicode ( fp_ . read ( ) ) , re .... |
def read_dataset ( dname ) :
"""Read example datasets .
Parameters
dname : string
Name of dataset to read ( without extension ) .
Must be a valid dataset present in pingouin . datasets
Returns
data : pd . DataFrame
Dataset
Examples
Load the ANOVA dataset
> > > from pingouin import read _ dataset... | # Check extension
d , ext = op . splitext ( dname )
if ext . lower ( ) == '.csv' :
dname = d
# Check that dataset exist
if dname not in dts [ 'dataset' ] . values :
raise ValueError ( 'Dataset does not exist. Valid datasets names are' , dts [ 'dataset' ] . values )
# Load dataset
return pd . read_csv ( op . joi... |
def insert ( self , table , row ) :
"""Add new row . Row must be a dict or implement the mapping interface .
> > > import getpass
> > > s = DB ( dbname = ' test ' , user = getpass . getuser ( ) , host = ' localhost ' ,
. . . password = ' ' )
> > > s . execute ( ' drop table if exists t2 ' )
> > > s . exec... | ( sql , values ) = sqlinsert ( table , row )
self . execute ( sql , values ) |
async def ebsUsage ( self , * args , ** kwargs ) :
"""See the current EBS volume usage list
Lists current EBS volume usage by returning a list of objects
that are uniquely defined by { region , volumetype , state } in the form :
region : string ,
volumetype : string ,
state : string ,
totalcount : integ... | return await self . _makeApiCall ( self . funcinfo [ "ebsUsage" ] , * args , ** kwargs ) |
def offer_random ( pool , answer , rationale , student_id , options ) :
"""The random selection algorithm . The same as simple algorithm""" | offer_simple ( pool , answer , rationale , student_id , options ) |
def HEAD ( self , rest_path_list , ** kwargs ) :
"""Send a HEAD request . See requests . sessions . request for optional parameters .
: returns : Response object""" | kwargs . setdefault ( "allow_redirects" , False )
return self . _request ( "HEAD" , rest_path_list , ** kwargs ) |
def schedule_host_svc_checks ( self , host , check_time ) :
"""Schedule a check on all services of a host
Format of the line that triggers function call : :
SCHEDULE _ HOST _ SVC _ CHECKS ; < host _ name > ; < check _ time >
: param host : host to check
: type host : alignak . object . host . Host
: param... | for service_id in host . services :
service = self . daemon . services [ service_id ]
self . schedule_svc_check ( service , check_time )
self . send_an_element ( service . get_update_status_brok ( ) ) |
def filter_props ( has_props_cls , input_dict , include_immutable = True ) :
"""Split a dictionary based keys that correspond to Properties
Returns :
* * ( props _ dict , others _ dict ) * * - Tuple of two dictionaries . The first contains
key / value pairs from the input dictionary that correspond to the
P... | props_dict = { k : v for k , v in iter ( input_dict . items ( ) ) if ( k in has_props_cls . _props and ( include_immutable or any ( hasattr ( has_props_cls . _props [ k ] , att ) for att in ( 'required' , 'new_name' ) ) ) ) }
others_dict = { k : v for k , v in iter ( input_dict . items ( ) ) if k not in props_dict }
re... |
def setEditable ( self , state ) :
"""Sets whether or not the user can edit the items in the list by
typing .
: param state | < bool >""" | self . _editable = state
if state :
self . setEditTriggers ( self . AllEditTriggers )
else :
self . setEditTriggers ( self . NoEditTriggers ) |
def get_plugins_qs ( cls ) :
"""Returns query set of all plugins belonging to plugin point .
Example : :
for plugin _ instance in MyPluginPoint . get _ plugins _ qs ( ) :
print ( plugin _ instance . get _ plugin ( ) . name )""" | if is_plugin_point ( cls ) :
point_pythonpath = cls . get_pythonpath ( )
return Plugin . objects . filter ( point__pythonpath = point_pythonpath , status = ENABLED ) . order_by ( 'index' )
else :
raise Exception ( _ ( 'This method is only available to plugin point ' 'classes.' ) ) |
def set_chat_photo ( self , chat_id , photo ) :
"""Use this method to set a new profile photo for the chat . Photos can ' t be changed for private chats . The bot must be an administrator in the chat for this to work and must have the appropriate admin rights . Returns True on success .
Note : In regular groups (... | from pytgbot . api_types . sendable . files import InputFile
assert_type_or_raise ( chat_id , ( int , unicode_type ) , parameter_name = "chat_id" )
assert_type_or_raise ( photo , InputFile , parameter_name = "photo" )
result = self . do ( "setChatPhoto" , chat_id = chat_id , photo = photo )
if self . return_python_obje... |
def run ( self , pcap ) :
"""Runs snort against the supplied pcap .
: param pcap : Filepath to pcap file to scan
: returns : tuple of version , list of alerts""" | proc = Popen ( self . _snort_cmd ( pcap ) , stdout = PIPE , stderr = PIPE , universal_newlines = True )
stdout , stderr = proc . communicate ( )
if proc . returncode != 0 :
raise Exception ( "\n" . join ( [ "Execution failed return code: {0}" . format ( proc . returncode ) , stderr or "" ] ) )
return ( parse_versio... |
def python_object_name ( item , module = True ) :
"""takes a python object and returns its import path .
: param item : the source object
: param module : bool - defaults to ` ` True ` ` - whether the object name should be prefixed by its module name .""" | if not isinstance ( item , type ) :
return python_object_name ( type ( item ) )
return br'.' . join ( filter ( is_valid_python_name , ( module and item . __module__ , item . __name__ ) ) ) |
def clone ( self , data = None , shared_data = True , new_type = None , * args , ** overrides ) :
"""Clones the object , overriding data and parameters .
Args :
data : New data replacing the existing data
shared _ data ( bool , optional ) : Whether to use existing data
new _ type ( optional ) : Type to cast... | if 'datatype' not in overrides :
datatypes = [ self . interface . datatype ] + self . datatype
overrides [ 'datatype' ] = list ( util . unique_iterator ( datatypes ) )
return super ( Dataset , self ) . clone ( data , shared_data , new_type , * args , ** overrides ) |
def tables ( self ) :
"""Print the existing tables in a database
: example : ` ` ds . tables ( ) ` `""" | if self . _check_db ( ) == False :
return
try :
pmodels = self . _tables ( )
if pmodels is None :
return
num = len ( pmodels )
s = "s"
if num == 1 :
s = ""
msg = "Found " + colors . bold ( str ( num ) ) + " table" + s + ":\n"
msg += "\n" . join ( pmodels )
self . info... |
def connect ( self , origin = None ) :
"""Connects to the server .
: param origin : ( Optional ) The origin .""" | self . logger . debug ( 'Establish connection...' )
if self . connected :
self . logger . warning ( 'Connection already established. Return...' )
return
if origin is not None :
self . origin = origin
self . auto_reconnect = True
self . ws_thread = threading . Thread ( name = "APIConnectionThread_{}" . forma... |
def update_or_create_candidate ( self , candidate , aggregable = True , uncontested = False ) :
"""Create a CandidateElection .""" | candidate_election , c = CandidateElection . objects . update_or_create ( candidate = candidate , election = self , defaults = { "aggregable" : aggregable , "uncontested" : uncontested } , )
return candidate_election |
def plot_simseries ( self , ** kwargs : Any ) -> None :
"""Plot the | IOSequence . series | of the | Sim | sequence object .
See method | Node . plot _ allseries | for further information .""" | self . __plot_series ( [ self . sequences . sim ] , kwargs ) |
def FindByName ( cls , name ) :
"""Find an installed VirtualTile by name .
This function searches for installed virtual tiles
using the pkg _ resources entry _ point ` iotile . virtual _ tile ` .
If name is a path ending in . py , it is assumed to point to
a module on disk and loaded directly rather than us... | if name . endswith ( '.py' ) :
return cls . LoadFromFile ( name )
reg = ComponentRegistry ( )
for _name , tile in reg . load_extensions ( 'iotile.virtual_tile' , name_filter = name , class_filter = VirtualTile ) :
return tile
raise ArgumentError ( "VirtualTile could not be found by name" , name = name ) |
def check_deleted_nodes ( self ) :
"""delete imported nodes that are not present in the old database""" | imported_nodes = Node . objects . filter ( data__contains = [ 'imported' ] )
deleted_nodes = [ ]
for node in imported_nodes :
if OldNode . objects . filter ( pk = node . pk ) . count ( ) == 0 :
user = node . user
deleted_nodes . append ( node )
node . delete ( )
# delete user if ther... |
def addInputPort ( self , node , name , i : Union [ Value , RtlSignalBase ] , side = PortSide . WEST ) :
"""Add and connect input port on subnode
: param node : node where to add input port
: param name : name of newly added port
: param i : input value
: param side : side where input port should be added""... | root = self . node
port = node . addPort ( name , PortType . INPUT , side )
netCtxs = self . netCtxs
if isinstance ( i , LPort ) :
root . addEdge ( i , port )
elif isConst ( i ) :
i = i . staticEval ( )
c , wasThereBefore = self . netCtxs . getDefault ( i )
if not wasThereBefore :
v = ValueAsLNo... |
def signal_handler ( sign , frame ) :
"""Capture Ctrl + C .""" | LOG . info ( '%s => %s' , sign , frame )
click . echo ( 'Bye' )
sys . exit ( 0 ) |
def copyto ( self , query ) :
"""Gets data from a table into a Response object that can be iterated
: param query : The " COPY { table _ name [ ( column _ name [ , . . . ] ) ] | ( query ) }
TO STDOUT [ WITH ( option [ , . . . ] ) ] " query to execute
: type query : str
: return : response object
: rtype :... | url = self . api_url + '/copyto'
params = { 'api_key' : self . api_key , 'q' : query }
try :
response = self . client . send ( url , http_method = 'GET' , params = params , stream = True )
response . raise_for_status ( )
except CartoRateLimitException as e :
raise e
except HTTPError as e :
if 400 <= res... |
def export ( self ) :
"""Make the actual request to the Import API ( exporting is part of the
Import API ) to export a map visualization as a . carto file
: return : A URL pointing to the . carto file
: rtype : str
: raise : CartoException
. . warning : : Non - public API . It may change with no previous ... | export_job = ExportJob ( self . client , self . get_id ( ) )
export_job . run ( )
export_job . refresh ( )
count = 0
while export_job . state in ( "exporting" , "enqueued" , "pending" ) :
if count >= MAX_NUMBER_OF_RETRIES :
raise CartoException ( _ ( "Maximum number of retries exceeded \
... |
def convert_to_ip ( self ) :
"""Convert all Data Collections of this EPW object to IP units .
This is useful when one knows that all graphics produced from this
EPW should be in Imperial units .""" | if not self . is_data_loaded :
self . _import_data ( )
if self . is_ip is False :
for coll in self . _data :
coll . convert_to_ip ( )
self . _is_ip = True |
def load_sampleset ( self , f , name ) :
'''Read the sampleset from using the HDF5 format . Name is usually in { train , test } .''' | self . encoder_x = np . array ( f [ name + '_encoder_x' ] )
self . decoder_x = np . array ( f [ name + '_decoder_x' ] )
self . decoder_y = np . array ( f [ name + '_decoder_y' ] ) |
def moveThreads ( self , location , thread_ids ) :
"""Moves threads to specifed location
: param location : models . ThreadLocation : INBOX , PENDING , ARCHIVED or OTHER
: param thread _ ids : Thread IDs to move . See : ref : ` intro _ threads `
: return : Whether the request was successful
: raises : FBcha... | thread_ids = require_list ( thread_ids )
if location == ThreadLocation . PENDING :
location = ThreadLocation . OTHER
if location == ThreadLocation . ARCHIVED :
data_archive = dict ( )
data_unpin = dict ( )
for thread_id in thread_ids :
data_archive [ "ids[{}]" . format ( thread_id ) ] = "true"
... |
def log_likelihood_bits ( eval_data , predictions , scores , learner = 'ignored' ) :
'''Return the log likelihood of each correct output in base 2 ( bits ) ,
computed from the scores in ` scores ` ( which should be in base e , nats ) .
> > > bits = log _ likelihood _ bits ( None , None , [ np . log ( 0.5 ) , np... | return ( np . array ( scores ) / np . log ( 2.0 ) ) . tolist ( ) |
def create_balancer ( name , port , protocol , profile , algorithm = None , members = None , ** libcloud_kwargs ) :
'''Create a new load balancer instance
: param name : Name of the new load balancer ( required )
: type name : ` ` str ` `
: param port : Port the load balancer should listen on , defaults to 80... | if algorithm is None :
algorithm = Algorithm . ROUND_ROBIN
else :
if isinstance ( algorithm , six . string_types ) :
algorithm = _algorithm_maps ( ) [ algorithm ]
starting_members = [ ]
if members is not None :
if isinstance ( members , list ) :
for m in members :
starting_member... |
def _exponential_kamb ( cos_dist , sigma = 3 ) :
"""Kernel function from Vollmer for exponential smoothing .""" | n = float ( cos_dist . size )
f = 2 * ( 1.0 + n / sigma ** 2 )
count = np . exp ( f * ( cos_dist - 1 ) )
units = np . sqrt ( n * ( f / 2.0 - 1 ) / f ** 2 )
return count , units |
def _parse_config_options ( config : Mapping [ str , Union [ ResourceOptions , Mapping [ str , Any ] ] ] = None ) :
"""Parse CORS configuration ( default or per - route )
: param config :
Mapping from Origin to Resource configuration ( allowed headers etc )
defined either as mapping or ` ResourceOptions ` ins... | if config is None :
return { }
if not isinstance ( config , collections . abc . Mapping ) :
raise ValueError ( "Config must be mapping, got '{}'" . format ( config ) )
parsed = { }
options_keys = { "allow_credentials" , "expose_headers" , "allow_headers" , "max_age" }
for origin , options in config . items ( ) ... |
def sliced_wasserstein ( PD1 , PD2 , M = 50 ) :
"""Implementation of Sliced Wasserstein distance as described in
Sliced Wasserstein Kernel for Persistence Diagrams by Mathieu Carriere , Marco Cuturi , Steve Oudot ( https : / / arxiv . org / abs / 1706.03358)
Parameters
PD1 : np . array size ( m , 2)
Persist... | diag_theta = np . array ( [ np . cos ( 0.25 * np . pi ) , np . sin ( 0.25 * np . pi ) ] , dtype = np . float32 )
l_theta1 = [ np . dot ( diag_theta , x ) for x in PD1 ]
l_theta2 = [ np . dot ( diag_theta , x ) for x in PD2 ]
if ( len ( l_theta1 ) != PD1 . shape [ 0 ] ) or ( len ( l_theta2 ) != PD2 . shape [ 0 ] ) :
... |
def get_git_tree ( self , sha , recursive = github . GithubObject . NotSet ) :
""": calls : ` GET / repos / : owner / : repo / git / trees / : sha < http : / / developer . github . com / v3 / git / trees > ` _
: param sha : string
: param recursive : bool
: rtype : : class : ` github . GitTree . GitTree `""" | assert isinstance ( sha , ( str , unicode ) ) , sha
assert recursive is github . GithubObject . NotSet or isinstance ( recursive , bool ) , recursive
url_parameters = dict ( )
if recursive is not github . GithubObject . NotSet and recursive : # GitHub API requires the recursive parameter be set to 1.
url_parameters... |
def minmax ( self , minimum = None , maximum = None ) :
"""Min / Max
Sets or gets the minimum and / or maximum values for the Node . For
getting , returns { " minimum " : mixed , " maximum " : mixed }
Arguments :
minimum { mixed } - - The minimum value
maximum { mixed } - - The maximum value
Raises :
... | # If neither min or max is set , this is a getter
if minimum is None and maximum is None :
return { "minimum" : self . _minimum , "maximum" : self . _maximum } ;
# If the minimum is set
if minimum != None : # If the current type is a date , datetime , ip , or time
if self . _type in [ 'base64' , 'date' , 'datet... |
def get_subject_with_file_validation ( jwt_bu64 , cert_path ) :
"""Same as get _ subject _ with _ local _ validation ( ) except that the signing certificate
is read from a local PEM file .""" | cert_obj = d1_common . cert . x509 . deserialize_pem_file ( cert_path )
return get_subject_with_local_validation ( jwt_bu64 , cert_obj ) |
def _build_tree ( self , position , momentum , slice_var , direction , depth , stepsize , position0 , momentum0 ) :
"""Recursively builds a tree for proposing new position and momentum""" | if depth == 0 :
position_bar , momentum_bar , candidate_set_size , accept_set_bool = self . _initalize_tree ( position , momentum , slice_var , direction * stepsize )
alpha = min ( 1 , self . _acceptance_prob ( position , position_bar , momentum , momentum_bar ) )
return ( position_bar , momentum_bar , posi... |
def summary ( title , sentences = 0 , chars = 0 , auto_suggest = True , redirect = True ) :
'''Plain text summary of the page .
. . note : : This is a convenience wrapper - auto _ suggest and redirect are enabled by default
Keyword arguments :
* sentences - if set , return the first ` sentences ` sentences ( ... | # use auto _ suggest and redirect to get the correct article
# also , use page ' s error checking to raise DisambiguationError if necessary
page_info = page ( title , auto_suggest = auto_suggest , redirect = redirect )
title = page_info . title
pageid = page_info . pageid
query_params = { 'prop' : 'extracts' , 'explain... |
def load_stats ( self ) :
"""Fetches the MAL media statistics page and sets the current media ' s statistics attributes .
: rtype : : class : ` . Media `
: return : current media object .""" | stats_page = self . session . session . get ( u'http://myanimelist.net/' + self . __class__ . __name__ . lower ( ) + u'/' + str ( self . id ) + u'/' + utilities . urlencode ( self . title ) + u'/stats' ) . text
self . set ( self . parse_stats ( utilities . get_clean_dom ( stats_page ) ) )
return self |
def format ( self , record ) :
"""Apply little arrow and colors to the record .
Arrow and colors are only applied to sphinxcontrib . versioning log statements .
: param logging . LogRecord record : The log record object to log .""" | formatted = super ( ColorFormatter , self ) . format ( record )
if self . verbose or not record . name . startswith ( self . SPECIAL_SCOPE ) :
return formatted
# Arrow .
formatted = '=> ' + formatted
# Colors .
if not self . colors :
return formatted
if record . levelno >= logging . ERROR :
formatted = str ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.