signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_settings ( self ) :
"""GetSettings .
[ Preview API ]
: rtype : : class : ` < NotificationAdminSettings > < azure . devops . v5_0 . notification . models . NotificationAdminSettings > `""" | response = self . _send ( http_method = 'GET' , location_id = 'cbe076d8-2803-45ff-8d8d-44653686ea2a' , version = '5.0-preview.1' )
return self . _deserialize ( 'NotificationAdminSettings' , response ) |
def validate_supported_quil ( program : Program ) -> None :
"""Ensure that a program is supported Quil which can run on any QPU , otherwise raise a ValueError .
We support a global RESET before any gates , and MEASUREs on each qubit after any gates
on that qubit . PRAGMAs and DECLAREs are always allowed , and a... | gates_seen = False
measured_qubits : Set [ int ] = set ( )
for i , instr in enumerate ( program . instructions ) :
if isinstance ( instr , Pragma ) or isinstance ( instr , Declare ) :
continue
elif isinstance ( instr , Halt ) :
if i != len ( program . instructions ) - 1 :
raise Value... |
def display ( self , image ) :
"""Takes a 1 - bit : py : mod : ` PIL . Image ` and dumps it to the ST7567
LCD display""" | assert ( image . mode == self . mode )
assert ( image . size == self . size )
image = self . preprocess ( image )
set_page_address = 0xB0
image_data = image . getdata ( )
pixels_per_page = self . width * 8
buf = bytearray ( self . width )
for y in range ( 0 , int ( self . _pages * pixels_per_page ) , pixels_per_page ) ... |
def _getThread ( self , given_thread_id = None , given_thread_type = None ) :
"""Checks if thread ID is given , checks if default is set and returns correct values
: raises ValueError : If thread ID is not given and there is no default
: return : Thread ID and thread type
: rtype : tuple""" | if given_thread_id is None :
if self . _default_thread_id is not None :
return self . _default_thread_id , self . _default_thread_type
else :
raise ValueError ( "Thread ID is not set" )
else :
return given_thread_id , given_thread_type |
def GetBlockByHeight ( self , height ) :
"""Get a block by its height .
Args :
height ( int ) : the height of the block to retrieve .
Returns :
neo . Core . Block : block instance .""" | hash = self . GetBlockHash ( height )
if hash is not None :
return self . GetBlockByHash ( hash ) |
def uploadByParts ( self , registerID , filePath , commit = True ) :
"""loads the data by small parts . If commit is set to true ,
then parts will be merged together . If commit is false , the
function will return the registerID so a manual commit can occur .
If the user ' s file is over 10mbs , the uploadByP... | url = self . _url + "/%s/uploadPart" % registerID
params = { "f" : "json" }
with open ( filePath , 'rb' ) as f :
mm = mmap . mmap ( f . fileno ( ) , 0 , access = mmap . ACCESS_READ )
size = 1000000
steps = int ( os . fstat ( f . fileno ( ) ) . st_size / size )
if os . fstat ( f . fileno ( ) ) . st_size ... |
def create_widget ( self ) :
"""Create the underlying widget .""" | d = self . declaration
style = d . style if d . style else ( '@attr/borderlessButtonStyle' if d . flat else '@attr/buttonStyle' )
self . widget = Button ( self . get_context ( ) , None , style ) |
def delete_group ( self , group ) :
"""Group was deleted .""" | try :
lgroup = self . _get_group ( group . name )
delete ( lgroup , database = self . _database )
except ObjectDoesNotExist : # it doesn ' t matter if it doesn ' t exist
pass |
def context_range ( self , context ) :
"""Return the 1 - offset , right - open range of lines spanned by
a particular context name .
Parameters
context : str
Raises
ValueError , if context is not present in the file .""" | if not context . startswith ( self . prefix ) :
context = self . prefix + '.' + context
lo = hi = None
for idx , line_context in enumerate ( self . lines , 1 ) : # context is hierarchical - - context spans itself
# and any suffix .
if line_context . startswith ( context ) :
lo = lo or idx
hi = i... |
def patience_sort ( xs ) :
'''Patience sort an iterable , xs .
This function generates a series of pairs ( x , pile ) , where " pile "
is the 0 - based index of the pile " x " should be placed on top of .
Elements of " xs " must be less - than comparable .''' | pile_tops = list ( )
for x in xs :
pile = bisect . bisect_left ( pile_tops , x )
if pile == len ( pile_tops ) :
pile_tops . append ( x )
else :
pile_tops [ pile ] = x
yield x , pile |
def notify_event_nowait ( self , conn_string , name , event ) :
"""Notify an event .
This will move the notification to the background event loop and
return immediately . It is useful for situations where you cannot
await notify _ event but keep in mind that it prevents back - pressure
when you are notifyin... | if self . _loop . stopping :
self . _logger . debug ( "Ignoring notification %s from %s because loop is shutting down" , name , conn_string )
return
self . _loop . log_coroutine ( self . _notify_event_internal , conn_string , name , event ) |
def direct_callback ( self , event ) :
"""This function is called for every OS keyboard event and decides if the
event should be blocked or not , and passes a copy of the event to
other , non - blocking , listeners .
There are two ways to block events : remapped keys , which translate
events by suppressing ... | # Pass through all fake key events , don ' t even report to other handlers .
if self . is_replaying :
return True
if not all ( hook ( event ) for hook in self . blocking_hooks ) :
return False
event_type = event . event_type
scan_code = event . scan_code
# Update tables of currently pressed keys and modifiers .... |
def _turn ( self , speed , degrees , brake = True , block = True ) :
"""Rotate in place ' degrees ' . Both wheels must turn at the same speed for us
to rotate in place .""" | # The distance each wheel needs to travel
distance_mm = ( abs ( degrees ) / 360 ) * self . circumference_mm
# The number of rotations to move distance _ mm
rotations = distance_mm / self . wheel . circumference_mm
log . debug ( "%s: turn() degrees %s, distance_mm %s, rotations %s, degrees %s" % ( self , degrees , dista... |
def to_file_path ( self , path_prefix ) :
"""Write the embedding matrix and the vocab to < path _ prefix > . npy and < path _ prefix > . vocab .
: param ( str ) path _ prefix : path prefix of the saved files""" | with self . _path_prefix_to_files ( path_prefix , 'w' ) as ( array_file , vocab_file ) :
self . to_files ( array_file , vocab_file ) |
def rebuild ( self , ** kwargs ) :
'''Repopulate the node - tracking data structures . Shouldn ' t
really ever be needed .''' | self . nodes = [ ]
self . node_types = [ ]
self . id_dict = { }
self . type_dict = { }
self . add_node ( self . root ) |
def ip4_address ( self ) :
"""Returns the IPv4 address of the network interface .
If multiple interfaces are provided ,
the address of the first found is returned .""" | if self . _ip4_address is None and self . network is not None :
self . _ip4_address = self . _get_ip_address ( libvirt . VIR_IP_ADDR_TYPE_IPV4 )
return self . _ip4_address |
def cursor ( self ) :
"""Returns a cursor for the currently assembled query , creating it if
it doesn ' t already exist .""" | if not self . _active_cursor :
self . _active_cursor = self . model . find ( self . query , self . projection or None , ** self . options )
return self . _active_cursor |
def get_ticket_for_sns_token ( self ) :
"""This is a shortcut for getting the sns _ token , as a post data of
request body .""" | self . logger . info ( "%s\t%s" % ( self . request_method , self . request_url ) )
return { "openid" : self . get_openid ( ) , "persistent_code" : self . get_persistent_code ( ) , } |
def parse ( self , data , extent , desc_tag ) : # type : ( bytes , int , UDFTag ) - > None
'''Parse the passed in data into a UDF Anchor Volume Structure .
Parameters :
data - The data to parse .
extent - The extent that this descriptor currently lives at .
desc _ tag - A UDFTag object that represents the D... | if self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'Anchor Volume Structure already initialized' )
( tag_unused , self . main_vd_length , self . main_vd_extent , self . reserve_vd_length , self . reserve_vd_extent ) = struct . unpack_from ( self . FMT , data , 0 )
self . desc_tag = desc_tag
se... |
def plot_comp ( df_var , fig = None , ax = None , ** kwargs ) :
"""Short summary .
Parameters
df _ var : pd . DataFrame
DataFrame containing variables to plot with datetime as index
Returns
MPL . figure
figure showing 1:1 line plot""" | if fig is None and ax is None :
fig , ax = plt . subplots ( )
elif fig is None :
fig = ax . get_figure ( )
elif ax is None :
ax = fig . gca ( )
# plt . clf ( )
# plt . cla ( )
# ax = sns . regplot (
# x = ' Obs ' , y = ' Sim ' ,
# data = df _ var ,
# fit _ reg = True )
# add regression expression
df_var_fit... |
def invoke ( self , ctx ) :
"""Given a context , this invokes the attached callback ( if it exists )
in the right way .""" | if self . callback is not None :
loop = asyncio . get_event_loop ( )
return loop . run_until_complete ( self . async_invoke ( ctx ) ) |
def create_platform ( platform ) :
'''. . versionadded : : 2019.2.0
Create a new device platform
platform
String of device platform , e . g . , ` ` junos ` `
CLI Example :
. . code - block : : bash
salt myminion netbox . create _ platform junos''' | nb_platform = get_ ( 'dcim' , 'platforms' , slug = slugify ( platform ) )
if nb_platform :
return False
else :
payload = { 'name' : platform , 'slug' : slugify ( platform ) }
plat = _add ( 'dcim' , 'platforms' , payload )
if plat :
return { 'dcim' : { 'platforms' : payload } }
else :
... |
def parse_cmd ( self , tree , inp_cmd = None ) :
"""Extract command and options from string .
The tree argument should contain a specifically formatted dict
which describes the available commands , options , arguments and
callbacks to methods for completion of arguments .
TODO : document dict format
The i... | # reset state from previous execution
self . exe = None
self . arg = None
self . exe_options = { }
self . children = tree [ 'children' ]
self . key = tree [ 'children' ]
option_parsing = False
self . _scoop_rest_arguments = False
if inp_cmd is not None :
self . inp_cmd = inp_cmd
# iterate the list of inputted comma... |
def program_files ( self , executable ) :
"""Determine the file paths to be adopted""" | if self . _get_version ( ) == 6 :
paths = self . REQUIRED_PATHS_6
elif self . _get_version ( ) > 6 :
paths = self . REQUIRED_PATHS_7_1
return paths |
def _set_role ( self , v , load = False ) :
"""Setter method for role , mapped from YANG variable / role ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ role is considered as a private
method . Backends looking to populate this variable should
do so vi... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = role . role , is_container = 'container' , presence = False , yang_name = "role" , rest_name = "role" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extensions ... |
def email ( value , allow_empty = False , ** kwargs ) :
"""Validate that ` ` value ` ` is a valid email address .
. . note : :
Email address validation is . . . complicated . The methodology that we have
adopted here is * generally * compliant with
` RFC 5322 < https : / / tools . ietf . org / html / rfc532... | # pylint : disable = too - many - branches , too - many - statements , R0914
if not value and not allow_empty :
raise errors . EmptyValueError ( 'value (%s) was empty' % value )
elif not value :
return None
if not isinstance ( value , basestring ) :
raise errors . CannotCoerceError ( 'value must be a valid ... |
def validate_query ( query ) :
"""Simple helper function to indicate whether a search query is a
valid FTS5 query . Note : this simply looks at the characters being
used , and is not guaranteed to catch all problematic queries .""" | tokens = _quote_re . findall ( query )
for token in tokens :
if token . startswith ( '"' ) and token . endswith ( '"' ) :
continue
if set ( token ) & _invalid_ascii :
return False
return True |
def Import ( context , request ) :
"""Beckman Coulter Access 2 analysis results""" | infile = request . form [ 'rochecobas_taqman_model48_file' ]
fileformat = request . form [ 'rochecobas_taqman_model48_format' ]
artoapply = request . form [ 'rochecobas_taqman_model48_artoapply' ]
override = request . form [ 'rochecobas_taqman_model48_override' ]
instrument = request . form . get ( 'instrument' , None ... |
def path_tails ( self , rr_id : str ) -> str :
"""Return path to tails file for input revocation registry identifier .
: param rr _ id : revocation registry identifier of interest
: return : path to tails file for input revocation registry identifier""" | return Tails . linked ( self . _dir_tails , rr_id ) |
def Docker ( ) :
"""Get Docker setup information""" | docker_info = { 'server' : { } , 'env' : '' , 'type' : '' , 'os' : '' }
# get docker server version
try :
d_client = docker . from_env ( )
docker_info [ 'server' ] = d_client . version ( )
except Exception as e : # pragma : no cover
logger . error ( "Can't get docker info " + str ( e ) )
# get operating sys... |
async def call_cmd_async ( cmdlist , stdin = None , env = None ) :
"""Given a command , call that command asynchronously and return the output .
This function only handles ` OSError ` when creating the subprocess , any
other exceptions raised either durring subprocess creation or while
exchanging data with th... | termenc = urwid . util . detected_encoding
cmdlist = [ s . encode ( termenc ) for s in cmdlist ]
environment = os . environ . copy ( )
if env is not None :
environment . update ( env )
logging . debug ( 'ENV = %s' , environment )
logging . debug ( 'CMD = %s' , cmdlist )
try :
proc = await asyncio . create_subpr... |
def get_vexrc ( options , environ ) :
"""Get a representation of the contents of the config file .
: returns :
a Vexrc instance .""" | # Complain if user specified nonexistent file with - - config .
# But we don ' t want to complain just because ~ / . vexrc doesn ' t exist .
if options . config and not os . path . exists ( options . config ) :
raise exceptions . InvalidVexrc ( "nonexistent config: {0!r}" . format ( options . config ) )
filename = ... |
def validate_properties ( props , required ) :
"""Ensures the key set contains the base supported properties for a Parser
: param props : a set of property names to validate against those supported""" | props = set ( props )
required = set ( required or _supported_props )
if len ( required . intersection ( props ) ) < len ( required ) :
missing = required - props
raise ValidationError ( 'Missing property names: {props}' , props = ',' . join ( missing ) , missing = missing ) |
def add_term ( self , t ) :
"""Add a term to this section and set it ' s ownership . Should only be used on root level terms""" | if t not in self . terms :
if t . parent_term_lc == 'root' :
self . terms . append ( t )
self . doc . add_term ( t , add_section = False )
t . set_ownership ( )
else :
raise GenerateError ( "Can only add or move root-level terms. Term '{}' parent is '{}' " . format ( t , t . pare... |
def verify_draft_url ( url ) :
"""Return ` ` True ` ` if the given URL has a valid draft mode HMAC in its
querystring .""" | url = urlparse . urlparse ( url )
# QueryDict requires a bytestring as its first argument
query = QueryDict ( force_bytes ( url . query ) )
# TODO Support legacy ' edit ' param name for now
preview_hmac = query . get ( 'preview' ) or query . get ( 'edit' )
if preview_hmac :
salt , hmac = preview_hmac . split ( ':' ... |
def _getusers ( self , ids = None , names = None , match = None ) :
"""Return a list of users that match criteria .
: kwarg ids : list of user ids to return data on
: kwarg names : list of user names to return data on
: kwarg match : list of patterns . Returns users whose real name or
login name match the p... | params = { }
if ids :
params [ 'ids' ] = self . _listify ( ids )
if names :
params [ 'names' ] = self . _listify ( names )
if match :
params [ 'match' ] = self . _listify ( match )
if not params :
raise BugzillaError ( '_get() needs one of ids, ' ' names, or match kwarg.' )
return self . _proxy . User .... |
def attention_bias_local ( length , max_backward , max_forward ) :
"""Create an bias tensor to be added to attention logits .
A position may attend to positions at most max _ distance from it ,
forward and backwards .
This does not actually save any computation .
Args :
length : int
max _ backward : int... | band = common_layers . ones_matrix_band_part ( length , length , max_backward , max_forward , out_shape = [ 1 , 1 , length , length ] )
return - 1e9 * ( 1.0 - band ) |
def get_proficiency_search_session ( self , proxy ) :
"""Gets the ` ` OsidSession ` ` associated with the proficiency search service .
: param proxy : a proxy
: type proxy : ` ` osid . proxy . Proxy ` `
: return : a ` ` ProficiencySearchSession ` `
: rtype : ` ` osid . learning . ProficiencySearchSession ` ... | if not self . supports_proficiency_search ( ) :
raise Unimplemented ( )
try :
from . import sessions
except ImportError :
raise OperationFailed ( )
proxy = self . _convert_proxy ( proxy )
try :
session = sessions . ProficiencySearchSession ( proxy = proxy , runtime = self . _runtime )
except AttributeEr... |
def format ( self , formatter , link_resolver , output ) :
"""Banana banana""" | if not self . title and self . name :
title = os . path . splitext ( self . name ) [ 0 ]
self . title = os . path . basename ( title ) . replace ( '-' , ' ' )
self . formatted_contents = u''
self . build_path = os . path . join ( formatter . get_output_folder ( self ) , self . link . ref )
if self . ast :
o... |
def _save_json_file ( self , file , val , pretty = False , compact = True , sort = True , encoder = None ) :
"""Save data to json file
: param file : Writable file or path to file
: type file : FileIO | str | unicode
: param val : Value or struct to save
: type val : None | int | float | str | list | dict
... | try :
save_json_file ( file , val , pretty , compact , sort , encoder )
except :
self . exception ( "Failed to save to {}" . format ( file ) )
raise IOError ( "Saving file failed" ) |
def hostname ( self , value ) :
"""The hostname where the log message was created .
Should be the first part of the hostname , or
an IP address . Should NOT be set to a fully
qualified domain name .""" | if value is None :
value = socket . gethostname ( )
self . _hostname = value |
def items ( stream , ** kwargs ) :
"""External facing items . Will return item from stream as available .
Currently waits in loop waiting for next item . Can pass keywords that
json . loads accepts ( such as object _ pairs _ hook )""" | for s in yield_json ( stream ) :
yield json . loads ( s , ** kwargs ) |
def summarize ( self , geom , stat = None ) :
"""Returns a new RasterQuerySet with subsetted / summarized ndarrays .
Arguments :
geom - - geometry for masking or spatial subsetting
Keyword args :
stat - - any numpy summary stat method as str ( min / max / mean / etc )""" | if not hasattr ( geom , 'num_coords' ) :
raise TypeError ( 'Need OGR or GEOS geometry, %s found' % type ( geom ) )
clone = self . _clone ( )
for obj in clone :
arr = obj . array ( geom )
if arr is not None :
if stat :
arr = agg_dims ( arr , stat )
try :
arr = arr . sq... |
def select_config_sections ( configfile_sections , desired_section_patterns ) :
"""Select a subset of the sections in a configuration file by using
a list of section names of list of section name patters
( supporting : mod : ` fnmatch ` wildcards ) .
: param configfile _ sections : List of config section name... | for section_name in configfile_sections :
for desired_section_pattern in desired_section_patterns :
if fnmatch ( section_name , desired_section_pattern ) :
yield section_name |
def import_end_event_to_graph ( diagram_graph , process_id , process_attributes , element ) :
"""Adds to graph the new element that represents BPMN end event .
End event inherits sequence of eventDefinitionRef from Event type .
Separate methods for each event type are required since each of them has different v... | end_event_definitions = { 'messageEventDefinition' , 'signalEventDefinition' , 'escalationEventDefinition' , 'errorEventDefinition' , 'compensateEventDefinition' , 'terminateEventDefinition' }
BpmnDiagramGraphImport . import_flow_node_to_graph ( diagram_graph , process_id , process_attributes , element )
BpmnDiagramGra... |
def peek ( self , deserialized_tx ) :
"""Peeks into first tx and sets self attrs or raise .""" | self . batch_id = deserialized_tx . object . batch_id
self . prev_batch_id = deserialized_tx . object . prev_batch_id
self . producer = deserialized_tx . object . producer
if self . batch_history . exists ( batch_id = self . batch_id ) :
raise BatchAlreadyProcessed ( f"Batch {self.batch_id} has already been process... |
def write_xml_document ( self , document ) :
"""Writes a string representation of an
` ` ElementTree ` ` object to the output stream .
: param document : An ` ` ElementTree ` ` object .""" | self . _out . write ( ET . tostring ( document ) )
self . _out . flush ( ) |
def available_method ( method_name ) :
'''ruturn the method for earliest package in ` ` pkg _ preferences ` ` , if package is available ( based on : meth : ` pkg _ available ` )''' | pkg_prefs_copy = list ( pkg_prefs )
if method_name in method_prefs :
pkg_prefs_copy = [ method_prefs [ method_name ] ] + pkg_prefs_copy
for pkg in pkg_prefs_copy :
if pkg in pkgs :
if method_name in dir ( pkgs [ pkg ] ) :
return getattr ( pkgs [ pkg ] , method_name )
nl . notify ( 'Error: Co... |
def deleteOTPK ( self , otpk_pub ) :
"""Delete a one - time pre key , either publicly visible or hidden .
: param otpk _ pub : The public key of the one - time pre key to delete , encoded as a
bytes - like object .""" | self . __checkSPKTimestamp ( )
for otpk in self . __otpks :
if otpk . pub == otpk_pub :
self . __otpks . remove ( otpk )
for otpk in self . __hidden_otpks :
if otpk . pub == otpk_pub :
self . __hidden_otpks . remove ( otpk )
self . __refillOTPKs ( ) |
def create_submission ( student_item_dict , answer , submitted_at = None , attempt_number = None ) :
"""Creates a submission for assessment .
Generic means by which to submit an answer for assessment .
Args :
student _ item _ dict ( dict ) : The student _ item this
submission is associated with . This is us... | student_item_model = _get_or_create_student_item ( student_item_dict )
if attempt_number is None :
try :
submissions = Submission . objects . filter ( student_item = student_item_model ) [ : 1 ]
except DatabaseError :
error_message = u"An error occurred while filtering submissions for student it... |
def join ( self , iterable ) :
"""Return a string which is the concatenation of the strings in the iterable .
: param iterable : Join items in this iterable .""" | return self . __class__ ( super ( ColorStr , self ) . join ( iterable ) , keep_tags = True ) |
def warning ( self ) :
"""Checks Stimulus for any warning conditions
: returns : str - - warning message , if any , 0 otherwise""" | signals , docs , overs = self . expandedStim ( )
if np . any ( np . array ( overs ) > 0 ) :
msg = 'Stimuli in this test are over the maximum allowable \
voltage output. They will be rescaled with a maximum \
undesired attenuation of {:.2f}dB.' . format ( np . amax ( overs ) )
ret... |
def run_from_argv ( self , prog , subcommand , global_options , argv ) :
"""Set up any environment changes requested , then run this command .""" | self . prog_name = prog
parser = self . create_parser ( prog , subcommand )
options , args = parser . parse_args ( argv )
self . global_options = global_options
self . options = options
self . args = args
self . execute ( args , options , global_options ) |
def Handle_Events ( self , events ) :
"""Handle events from poll ( )
: events : A list of tuples form zmq . poll ( )
: type events : list
: returns : None""" | for e in events :
sock = e [ 0 ]
event_type = e [ 1 ]
if event_type == zmq . POLLIN :
msg = sock . recv ( )
reply = self . Handle_Receive ( msg )
sock . send ( reply )
elif event_type == zmq . POLLOUT :
pass
# FIXME - - handle this correctly
elif event_type ==... |
def search_in_workspace ( self , workspace , params = { } , ** options ) :
"""The search endpoint allows you to build complex queries to find and fetch exactly the data you need from Asana . For a more comprehensive description of all the query parameters and limitations of this endpoint , see our [ long - form doc... | path = "/workspaces/%s/tasks/search" % ( workspace )
return self . client . get_collection ( path , params , ** options ) |
def on_channel_open ( self , channel ) :
"""Input channel creation callback
Queue declaration done here
Args :
channel : input channel""" | self . in_channel . exchange_declare ( exchange = 'input_exc' , type = 'topic' , durable = True )
channel . queue_declare ( callback = self . on_input_queue_declare , queue = self . INPUT_QUEUE_NAME ) |
def get ( self , * args , ** kwargs ) :
"""Return the single item from the filtered queryset .""" | assert not args
assert list ( kwargs . keys ( ) ) == [ 'pk' ]
pk = kwargs [ 'pk' ]
model_name = self . model . __name__
object_spec = ( model_name , pk , None )
instances = self . cache . get_instances ( ( object_spec , ) )
try :
model_data = instances [ ( model_name , pk ) ] [ 0 ]
except KeyError :
raise self ... |
def run_kernel ( self , func , gpu_args , threads , grid ) :
"""runs the OpenCL kernel passed as ' func '
: param func : An OpenCL Kernel
: type func : pyopencl . Kernel
: param gpu _ args : A list of arguments to the kernel , order should match the
order in the code . Allowed values are either variables in... | global_size = ( grid [ 0 ] * threads [ 0 ] , grid [ 1 ] * threads [ 1 ] , grid [ 2 ] * threads [ 2 ] )
local_size = threads
event = func ( self . queue , global_size , local_size , * gpu_args )
event . wait ( ) |
def smoothed_hazard_confidence_intervals_ ( self , bandwidth , hazard_ = None ) :
"""Parameters
bandwidth : float
the bandwidth to use in the Epanechnikov kernel . > 0
hazard _ : numpy array
a computed ( n , ) numpy array of estimated hazard rates . If none , uses ` ` smoothed _ hazard _ ` `""" | if hazard_ is None :
hazard_ = self . smoothed_hazard_ ( bandwidth ) . values [ : , 0 ]
timeline = self . timeline
z = inv_normal_cdf ( 1 - self . alpha / 2 )
self . _cumulative_sq . iloc [ 0 ] = 0
var_hazard_ = self . _cumulative_sq . diff ( ) . fillna ( self . _cumulative_sq . iloc [ 0 ] )
C = var_hazard_ . value... |
def create_repository ( self , repository , body , params = None ) :
"""Registers a shared file system repository .
` < http : / / www . elastic . co / guide / en / elasticsearch / reference / current / modules - snapshots . html > ` _
: arg repository : A repository name
: arg body : The repository definitio... | for param in ( repository , body ) :
if param in SKIP_IN_PATH :
raise ValueError ( "Empty value passed for a required argument." )
return self . transport . perform_request ( 'PUT' , _make_path ( '_snapshot' , repository ) , params = params , body = body ) |
def create ( ctx , archive_name , authority_name , versioned = True , tag = None , helper = False ) :
'''Create an archive''' | tags = list ( tag )
_generate_api ( ctx )
args , kwargs = _parse_args_and_kwargs ( ctx . args )
assert len ( args ) == 0 , 'Unrecognized arguments: "{}"' . format ( args )
var = ctx . obj . api . create ( archive_name , authority_name = authority_name , versioned = versioned , metadata = kwargs , tags = tags , helper =... |
def consume ( self , source ) :
"""Parse source and consume tokens from tinycss2.
Arguments :
source ( string ) : Source content to parse .
Returns :
dict : Retrieved rules .""" | manifest = OrderedDict ( )
rules = parse_stylesheet ( source , skip_comments = True , skip_whitespace = True , )
for rule in rules : # Gather rule selector + properties
name = self . digest_prelude ( rule )
# Ignore everything out of styleguide namespace
if not name . startswith ( RULE_BASE_PREFIX ) :
... |
def purge ( self , ignore_ignores ) :
"""Delete everything that shown up on status .""" | command = [ 'status' , '--xml' ]
if ignore_ignores :
command . append ( '--no-ignore' )
d = self . _dovccmd ( command , collectStdout = True )
@ d . addCallback
def parseAndRemove ( stdout ) :
files = [ ]
for filename in self . getUnversionedFiles ( stdout , self . keep_on_purge ) :
filename = self ... |
def _get_translation ( self , ims_width , ims_height ) :
"""Returns x and y for a bitmap translation""" | # Get cell attributes
cell_attributes = self . code_array . cell_attributes [ self . key ]
justification = cell_attributes [ "justification" ]
vertical_align = cell_attributes [ "vertical_align" ]
angle = cell_attributes [ "angle" ]
scale_x , scale_y = self . _get_scalexy ( ims_width , ims_height )
scale = min ( scale_... |
def load_dom ( self , domtree , initialize = True ) :
"""Load manifest from DOM tree .
If initialize is True ( default ) , reset existing attributes first .""" | if domtree . nodeType == Node . DOCUMENT_NODE :
rootElement = domtree . documentElement
elif domtree . nodeType == Node . ELEMENT_NODE :
rootElement = domtree
else :
raise InvalidManifestError ( "Invalid root element node type " + str ( rootElement . nodeType ) + " - has to be one of (DOCUMENT_NODE, " "ELEM... |
def _find_types ( pkgs ) :
'''Form a package names list , find prefixes of packages types .''' | return sorted ( { pkg . split ( ':' , 1 ) [ 0 ] for pkg in pkgs if len ( pkg . split ( ':' , 1 ) ) == 2 } ) |
def maps_get_default_rules_output_rules_rbridgeid ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
maps_get_default_rules = ET . Element ( "maps_get_default_rules" )
config = maps_get_default_rules
output = ET . SubElement ( maps_get_default_rules , "output" )
rules = ET . SubElement ( output , "rules" )
rbridgeid = ET . SubElement ( rules , "rbridgeid" )
rbridgeid . text = kwargs ... |
def moderators ( self , limit = None ) :
"""GETs moderators for this subreddit . Calls : meth : ` narwal . Reddit . moderators ` .
: param limit : max number of items to return""" | return self . _reddit . moderators ( self . display_name , limit = limit ) |
def median_grouped ( name , num , minimum = 0 , maximum = 0 , ref = None ) :
'''Calculates the grouped mean of the ` ` num ` ` most recent values . Requires a
list .
USAGE :
. . code - block : : yaml
foo :
calc . median _ grouped :
- name : myregentry
- num : 5''' | return calc ( name = name , num = num , oper = 'median_grouped' , minimum = minimum , maximum = maximum , ref = ref ) |
def from_conll ( this_class , stream ) :
"""Construct a Corpus . stream is an iterable over strings where
each string is a line in CoNLL - X format .""" | stream = iter ( stream )
corpus = this_class ( )
while 1 : # read until we get an empty sentence
sentence = Sentence . from_conll ( stream )
if sentence :
corpus . append ( sentence )
else :
break
return corpus |
def parseParams ( string ) :
"""Parse parameters""" | all = params_re . findall ( string )
allParameters = [ ]
for tup in all :
paramList = [ tup [ 0 ] ]
# tup looks like ( name , valuesString )
for pair in param_values_re . findall ( tup [ 1 ] ) : # pair looks like ( ' ' , value ) or ( value , ' ' )
if pair [ 0 ] != '' :
paramList . append... |
def querysets_from_title_prefix ( title_prefix = None , model = DEFAULT_MODEL , app = DEFAULT_APP ) :
"""Return a list of Querysets from a list of model numbers""" | if title_prefix is None :
title_prefix = [ None ]
filter_dicts = [ ]
model_list = [ ]
if isinstance ( title_prefix , basestring ) :
title_prefix = title_prefix . split ( ',' )
elif not isinstance ( title_prefix , dict ) :
title_prefix = title_prefix
if isinstance ( title_prefix , ( list , tuple ) ) :
fo... |
def explain_weights_df ( estimator , ** kwargs ) : # type : ( . . . ) - > pd . DataFrame
"""Explain weights and export them to ` ` pandas . DataFrame ` ` .
All keyword arguments are passed to : func : ` eli5 . explain _ weights ` .
Weights of all features are exported by default .""" | kwargs = _set_defaults ( kwargs )
return format_as_dataframe ( eli5 . explain_weights ( estimator , ** kwargs ) ) |
def from_callback ( cls , cb , nx = None , nparams = None , ** kwargs ) :
"""Generate a SymbolicSys instance from a callback .
Parameters
cb : callable
Should have the signature ` ` cb ( x , p , backend ) - > list of exprs ` ` .
nx : int
Number of unknowns , when not given it is deduced from ` ` kwargs [ ... | if kwargs . get ( 'x_by_name' , False ) :
if 'names' not in kwargs :
raise ValueError ( "Need ``names`` in kwargs." )
if nx is None :
nx = len ( kwargs [ 'names' ] )
elif nx != len ( kwargs [ 'names' ] ) :
raise ValueError ( "Inconsistency between nx and length of ``names``." )
if kw... |
def get_equipment ( self , ** kwargs ) :
"""Return list environments related with environment vip""" | uri = 'api/v3/equipment/'
uri = self . prepare_url ( uri , kwargs )
return super ( ApiEquipment , self ) . get ( uri ) |
def calculate_size ( name , function ) :
"""Calculates the request payload size""" | data_size = 0
data_size += calculate_size_str ( name )
data_size += calculate_size_data ( function )
return data_size |
def kraus_iscomplete ( kraus : Kraus ) -> bool :
"""Returns True if the collection of ( weighted ) Kraus operators are
complete . ( Which is necessary for a CPTP map to preserve trace )""" | qubits = kraus . qubits
N = kraus . qubit_nb
ident = Gate ( np . eye ( 2 ** N ) , qubits )
# FIXME
tensors = [ ( op . H @ op @ ident ) . asoperator ( ) for op in kraus . operators ]
tensors = [ t * w for t , w in zip ( tensors , kraus . weights ) ]
tensor = reduce ( np . add , tensors )
res = Gate ( tensor , qubits )
r... |
def trend ( self , ** kwargs ) :
'''Calculate a trend for all series in the group . See the
` TimeSeries . trend ( ) ` method for more information .''' | return DataFrame ( { name : series . trend ( ** kwargs ) for name , series in self . groups . iteritems ( ) } ) |
def get_state ( key , namespace = None , table_name = None , environment = None , layer = None , stage = None , shard_id = None , consistent = True , deserializer = json . loads , wait_exponential_multiplier = 500 , wait_exponential_max = 5000 , stop_max_delay = 10000 ) :
"""Get Lambda state value ( s ) .""" | if table_name is None :
table_name = _state_table_name ( environment = environment , layer = layer , stage = stage )
if not table_name :
msg = ( "Can't produce state table name: unable to get state " "item '{}'" . format ( key ) )
logger . error ( msg )
raise StateTableError ( msg )
return
dynamodb ... |
def allocate ( self , handles , initial = False , params = { } ) :
"""Call from main thread . Initiate a request for more environments""" | assert all ( re . search ( '^\d+$' , h ) for h in handles ) , "All handles must be numbers: {}" . format ( handles )
self . requests . put ( ( 'allocate' , ( handles , initial , params ) ) ) |
def vm_update ( name , kwargs = None , call = None ) :
'''Replaces the user template contents .
. . versionadded : : 2016.3.0
name
The name of the VM to update .
path
The path to a file containing new user template contents . Syntax within the
file can be the usual attribute = value or XML . Can be used... | if call != 'action' :
raise SaltCloudSystemExit ( 'The vm_update action must be called with -a or --action.' )
if kwargs is None :
kwargs = { }
path = kwargs . get ( 'path' , None )
data = kwargs . get ( 'data' , None )
update_type = kwargs . get ( 'update_type' , None )
update_args = [ 'replace' , 'merge' ]
if... |
def get_by_type ( self , _type ) :
"""Return all of the instances of : class : ` ComponentType ` ` ` _ type ` ` .""" | r = { }
for k , v in self . items ( ) :
if get_component_type ( k ) is _type :
r [ k ] = v
return r |
def run_hybrid ( wf , selector , workers ) :
"""Returns the result of evaluating the workflow ; runs through several
supplied workers in as many threads .
: param wf :
Workflow to compute
: type wf : : py : class : ` Workflow ` or : py : class : ` PromisedObject `
: param selector :
A function selecting... | worker = hybrid_threaded_worker ( selector , workers )
return Scheduler ( ) . run ( worker , get_workflow ( wf ) ) |
def fraction_fpr ( fg_vals , bg_vals , fpr = 0.01 ) :
"""Computes the fraction positives at a specific FPR ( default 1 % ) .
Parameters
fg _ vals : array _ like
The list of values for the positive set .
bg _ vals : array _ like
The list of values for the negative set .
fpr : float , optional
The FPR (... | fg_vals = np . array ( fg_vals )
s = scoreatpercentile ( bg_vals , 100 - 100 * fpr )
return len ( fg_vals [ fg_vals >= s ] ) / float ( len ( fg_vals ) ) |
def check_config ( self , config ) :
"""Check the config file for required fields and validity .
@ param config : The config dict .
@ return : True if valid , error string if invalid paramaters where
encountered .""" | validation = ""
required = [ "name" , "currency" , "IBAN" , "BIC" ]
for config_item in required :
if config_item not in config :
validation += config_item . upper ( ) + "_MISSING "
if not validation :
return True
else :
raise Exception ( "Config file did not validate. " + validation ) |
def __loadSetting ( self ) :
"""读取策略配置""" | with open ( self . settingfilePath , 'rb' ) as f :
df = f . read ( )
f . close ( )
if type ( df ) is not str :
df = ft . str_utf8 ( df )
self . _global_settings = json . loads ( df )
if self . _global_settings is None or 'frame' not in self . _global_settings :
raise Exception ( "set... |
def has_scheduled_methods ( cls ) :
"""Decorator ; use this on a class for which some methods have been
decorated with : func : ` schedule ` or : func : ` schedule _ hint ` . Those methods
are then tagged with the attribute ` _ _ member _ of _ _ ` , so that we may
serialise and retrieve the correct method . T... | for member in cls . __dict__ . values ( ) :
if hasattr ( member , '__wrapped__' ) :
member . __wrapped__ . __member_of__ = cls
return cls |
def on_key_down ( self , event ) :
'''handle keyboard input''' | state = self . state
# send all key events to the parent
if self . mouse_pos :
latlon = self . coordinates ( self . mouse_pos . x , self . mouse_pos . y )
selected = self . selected_objects ( self . mouse_pos )
state . event_queue . put ( SlipKeyEvent ( latlon , event , selected ) )
c = event . GetUniChar (... |
def _init_read_gz ( self ) :
"""Initialize for reading a gzip compressed fileobj .""" | self . cmp = self . zlib . decompressobj ( - self . zlib . MAX_WBITS )
self . dbuf = b""
# taken from gzip . GzipFile with some alterations
if self . __read ( 2 ) != b"\037\213" :
raise ReadError ( "not a gzip file" )
if self . __read ( 1 ) != b"\010" :
raise CompressionError ( "unsupported compression method" ... |
def initialize_from_matrix ( cls , matrix , column ) :
"""Create vector from matrix
: param Matrix matrix : The Matrix , which should be used to create the vector .
: param integer column : The column of the matrix , which should be used
to create the new vector .
: raise : Raises an : py : exc : ` IndexErr... | vec = Vector ( matrix . get_height ( ) )
for row in xrange ( matrix . get_height ( ) ) :
vec . set_value ( 0 , row , matrix . get_value ( column , row ) )
return vec |
def correct_segmentation ( segments , clusters , min_time ) :
"""Corrects the predicted segmentation
This process prevents over segmentation
Args :
segments ( : obj : ` list ` of : obj : ` list ` of : obj : ` Point ` ) :
segments to correct
min _ time ( int ) : minimum required time for segmentation""" | # segments = [ points for points in segments if len ( points ) > 1]
result_segments = [ ]
prev_segment = None
for i , segment in enumerate ( segments ) :
if len ( segment ) >= 1 :
continue
cluster = clusters [ i ]
if prev_segment is None :
prev_segment = segment
else :
cluster_dt... |
def eval_field ( field , asc ) :
"""Evaluate a field for sorting purpose .
: param field : Field definition ( string , dict or callable ) .
: param asc : ` ` True ` ` if order is ascending , ` ` False ` ` if descending .
: returns : Dictionary with the sort field query .""" | if isinstance ( field , dict ) :
if asc :
return field
else : # Field should only have one key and must have an order subkey .
field = copy . deepcopy ( field )
key = list ( field . keys ( ) ) [ 0 ]
field [ key ] [ 'order' ] = reverse_order ( field [ key ] [ 'order' ] )
r... |
def with_sample_weight ( clf , sample_weight , fit_params ) :
"""Return fit _ params with added " sample _ weight " argument .
Unlike ` fit _ params [ ' sample _ weight ' ] = sample _ weight ` it
handles a case where ` ` clf ` ` is a pipeline .""" | param_name = _get_classifier_prefix ( clf ) + "sample_weight"
params = { param_name : sample_weight }
params . update ( fit_params )
return params |
def search_for_files ( run_name , raw_extension = None , cellpy_file_extension = None , raw_file_dir = None , cellpy_file_dir = None , prm_filename = None , file_name_format = None , cache = None ) :
"""Searches for files ( raw - data files and cellpy - files ) .
Args :
run _ name ( str ) : run - file identific... | time_00 = time . time ( )
cellpy_file_extension = "h5"
res_extension = "res"
version = 0.1
# might include searching and removing " . " in extensions
# should include extension definitions in prm file ( version 0.6)
logger . debug ( f"searching for {run_name}" )
if raw_extension is None :
raw_extension = res_extens... |
def get_value ( self , value ) :
"""Replace variable names with placeholders ( e . g . ' : v1 ' )""" | next_key = ":v%d" % self . _next_value
self . _next_value += 1
self . _values [ next_key ] = value
return next_key |
def send_mail ( subject , body_text , addr_from , recipient_list , fail_silently = False , auth_user = None , auth_password = None , attachments = None , body_html = None , html_message = None , connection = None , headers = None ) :
"""Sends a multipart email containing text and html versions which
are encrypted... | # Make sure only one HTML option is specified
if body_html is not None and html_message is not None : # pragma : no cover
raise ValueError ( "You cannot specify body_html and html_message at " "the same time. Please only use html_message." )
# Push users to update their code
if body_html is not None : # pragma : no... |
def load_config ( path ) :
"""Load the config value from various arguments .""" | config = ConfigParser ( )
if len ( config . read ( path ) ) == 0 :
stderr_and_exit ( "Couldn't load config {0}\n" . format ( path ) )
if not config . has_section ( 'walls' ) :
stderr_and_exit ( 'Config missing [walls] section.\n' )
# Print out all of the missing keys
keys = [ 'api_key' , 'api_secret' , 'tags' ,... |
def transform_to_geographic ( this_spec_meas_df , samp_df , samp , coord = "0" ) :
"""Transform decs / incs to geographic coordinates .
Calls pmag . dogeo _ V for the heavy lifting
Parameters
this _ spec _ meas _ df : pandas dataframe of measurements for a single specimen
samp _ df : pandas dataframe of sam... | # we could return the type of coordinates ACTUALLY used
# transform geographic
decs = this_spec_meas_df [ 'dir_dec' ] . values . tolist ( )
incs = this_spec_meas_df [ 'dir_inc' ] . values . tolist ( )
or_info , az_type = pmag . get_orient ( samp_df , samp , data_model = 3 )
if 'azimuth' in or_info . keys ( ) and cb . n... |
def patterns ( instance , options ) :
"""Ensure that the syntax of the pattern of an indicator is valid , and that
objects and properties referenced by the pattern are valid .""" | if instance [ 'type' ] != 'indicator' or 'pattern' not in instance :
return
pattern = instance [ 'pattern' ]
if not isinstance ( pattern , string_types ) :
return
# This error already caught by schemas
errors = pattern_validator ( pattern )
# Check pattern syntax
if errors :
for e in errors :
yi... |
def keep_alive ( self ) :
"""Return : data : ` True ` if any reader ' s : attr : ` Side . keep _ alive ` attribute
is : data : ` True ` , or any : class : ` Context ` is still registered that is
not the master . Used to delay shutdown while some important work is in
progress ( e . g . log draining ) .""" | it = ( side . keep_alive for ( _ , ( side , _ ) ) in self . poller . readers )
return sum ( it , 0 ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.