signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def set_taker ( self , resource_id ) :
"""Sets the resource who will be taking this assessment .
arg : resource _ id ( osid . id . Id ) : the resource Id
raise : InvalidArgument - ` ` resource _ id ` ` is invalid
raise : NoAccess - ` ` Metadata . isReadOnly ( ) ` ` is ` ` true ` `
* compliance : mandatory -... | # Implemented from template for osid . resource . ResourceForm . set _ avatar _ template
if self . get_taker_metadata ( ) . is_read_only ( ) :
raise errors . NoAccess ( )
if not self . _is_valid_id ( resource_id ) :
raise errors . InvalidArgument ( )
self . _my_map [ 'takerId' ] = str ( resource_id ) |
def delete_after ( filename ) :
"""Decorator to be sure the file given by parameter is deleted after the
execution of the method .""" | def delete_after_decorator ( function ) :
def wrapper ( * args , ** kwargs ) :
try :
return function ( * args , ** kwargs )
finally :
if os . path . isfile ( filename ) :
os . remove ( filename )
if os . path . isdir ( filename ) :
... |
def markdown_single_text ( self , catalog , cdli_number ) :
"""Prints single text in file in markdown .
: param catalog : text ingested by cdli _ corpus
: param cdli _ number : text you wish to print
: return : output in filename . md""" | if cdli_number in catalog :
pnum = catalog [ cdli_number ] [ 'pnum' ]
edition = catalog [ cdli_number ] [ 'edition' ]
metadata = '\n\t' . join ( catalog [ cdli_number ] [ 'metadata' ] )
transliteration = '\n\t' . join ( catalog [ cdli_number ] [ 'transliteration' ] )
normalization = '\n\t' . join ( ... |
def locale ( self ) -> tornado . locale . Locale :
"""The locale for the current session .
Determined by either ` get _ user _ locale ` , which you can override to
set the locale based on , e . g . , a user preference stored in a
database , or ` get _ browser _ locale ` , which uses the ` ` Accept - Language ... | if not hasattr ( self , "_locale" ) :
loc = self . get_user_locale ( )
if loc is not None :
self . _locale = loc
else :
self . _locale = self . get_browser_locale ( )
assert self . _locale
return self . _locale |
def digicam_control_encode ( self , target_system , target_component , session , zoom_pos , zoom_step , focus_lock , shot , command_id , extra_param , extra_value ) :
'''Control on - board Camera Control System to take shots .
target _ system : System ID ( uint8 _ t )
target _ component : Component ID ( uint8 _... | return MAVLink_digicam_control_message ( target_system , target_component , session , zoom_pos , zoom_step , focus_lock , shot , command_id , extra_param , extra_value ) |
def register_handler ( self , callable_obj , entrypoint , methods = ( 'GET' , ) ) :
"""Register a handler callable to a specific route .
Args :
entrypoint ( str ) : The uri relative path .
methods ( tuple ) : A tuple of valid method strings .
callable _ obj ( callable ) : The callable object .
Returns :
... | router_obj = Route . wrap_callable ( uri = entrypoint , methods = methods , callable_obj = callable_obj )
if router_obj . is_valid :
self . _routes . add ( router_obj )
return self
raise RouteError ( # pragma : no cover
"Missing params: methods: {} - entrypoint: {}" . format ( methods , entrypoint ) ) |
def set_values ( self , x ) :
"""Updates self . theta parameter . No returns values""" | x = numpy . atleast_2d ( x )
x = x . real
# ahem
C_inv = self . __C_inv__
theta = numpy . dot ( x , C_inv )
self . theta = theta
return theta |
def __is_valid_for_dict_to_object_conversion ( strict_mode : bool , from_type : Type , to_type : Type ) -> bool :
"""Returns true if the provided types are valid for dict _ to _ object conversion
Explicitly declare that we are not able to parse collections nor able to create an object from a dictionary if the
o... | # right now we ' re stuck with the default logger . .
logr = default_logger
if to_type is None or is_any_type ( to_type ) : # explicitly handle the ' None ' ( joker ) or ' any ' type
return True
elif is_collection ( to_type , strict = True ) : # if the destination type is ' strictly a collection ' ( not a subclass ... |
def get_internal_project ( self , timeout : float = 1 ) -> typing . Union [ 'projects.Project' , None ] :
"""Attempts to return the internally loaded project . This function
prevents race condition issues where projects are loaded via threads
because the internal loop will try to continuously load the internal ... | count = int ( timeout / 0.1 )
for _ in range ( count ) :
project = self . internal_project
if project :
return project
time . sleep ( 0.1 )
return self . internal_project |
def can_subscribe_to_topic ( self , topic , user ) :
"""Given a topic , checks whether the user can add it to their subscription list .""" | # A user can subscribe to topics if they are authenticated and if they have the permission
# to read the related forum . Of course a user can subscribe only if they have not already
# subscribed to the considered topic .
return ( user . is_authenticated and not topic . has_subscriber ( user ) and self . _perform_basic_... |
def wait ( self ) :
"""It returns when an event which we have configured by set _ threshold happens .
Note that it blocks until then .""" | ret = os . read ( self . event_fd , 64 / 8 )
return struct . unpack ( 'Q' , ret ) |
def route ( self , path ) : # type : ( str ) - > Tuple [ Any , Callable ]
"""Returns the task handling the given request path .""" | logging . getLogger ( __name__ ) . debug ( "Routing path '%s'." , path )
cls = None
for strategy in self . _strategies :
if strategy . can_route ( path ) :
cls = strategy . route ( path )
break
if cls is None :
raise RoutingError ( path )
return self . _create_result ( cls ) |
def _calc_resp ( password_hash , server_challenge ) :
"""Generate the LM response given a 16 - byte password hash and the
challenge from the CHALLENGE _ MESSAGE
: param password _ hash : A 16 - byte password hash
: param server _ challenge : A random 8 - byte response generated by the
server in the CHALLENG... | # padding with zeros to make the hash 21 bytes long
password_hash += b'\x00' * ( 21 - len ( password_hash ) )
res = b''
dobj = DES ( DES . key56_to_key64 ( password_hash [ 0 : 7 ] ) )
res = res + dobj . encrypt ( server_challenge [ 0 : 8 ] )
dobj = DES ( DES . key56_to_key64 ( password_hash [ 7 : 14 ] ) )
res = res + d... |
def list_all_native_quantities ( self , with_info = False ) :
"""Return a list of all available native quantities in this catalog .
If * with _ info * is ` True ` , return a dict with quantity info .
See also : list _ all _ quantities""" | q = self . _native_quantities
return { k : self . get_quantity_info ( k ) for k in q } if with_info else list ( q ) |
def channels_voice_greeting_recording ( self , id , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / voice - api / greetings # get - greeting - audio - file" | api_path = "/api/v2/channels/voice/greetings/{id}/recording.mp3"
api_path = api_path . format ( id = id )
return self . call ( api_path , ** kwargs ) |
def draw_actions ( self ) :
"""Draw the actions so that they can be inspected for accuracy .""" | now = time . time ( )
for act in self . _past_actions :
if act . pos and now < act . deadline :
remain = ( act . deadline - now ) / ( act . deadline - act . time )
if isinstance ( act . pos , point . Point ) :
size = remain / 3
self . all_surfs ( _Surface . draw_circle , act ... |
def stage ( self ) :
"""Stage Redis and ThreatConnect data defined in profile .
Redis Data :
. . code - block : : javascript
" data " : [
" This is an example Source # 1 " ,
" This is an example Source # 2"
" variable " : " # App : 1234 : source ! StringArray "
Redis Array :
. . code - block : : jav... | for sd in self . staging_data :
if not isinstance ( sd , dict ) : # reported issue from qa where staging data is invalid
msg = 'Invalid staging data provided ({}).' . format ( sd )
sys . exit ( msg )
data_type = sd . get ( 'data_type' , 'redis' )
if data_type == 'redis' :
self . log ... |
def check_atd ( text ) :
"""Check for redundancies from After the Deadline .""" | err = "after_the_deadline.redundancy"
msg = "Redundancy. Use '{}' instead of '{}'."
redundancies = [ [ u"Bō" , [ "Bo Staff" ] ] , [ "Challah" , [ "Challah bread" ] ] , [ "Hallah" , [ "Hallah bread" ] ] , [ "Challah" , [ "Challah bread" ] ] , [ "I" , [ "I myself" , "I personally" ] ] , [ "Mount Fuji" , [ "Mount Fujiyama... |
def getscheme ( self , default = None ) :
"""Return the URI scheme in canonical ( lowercase ) form , or ` default `
if the original URI reference did not contain a scheme component .""" | scheme = self . scheme
if scheme is None :
return default
elif isinstance ( scheme , bytes ) :
return scheme . decode ( 'ascii' ) . lower ( )
else :
return scheme . lower ( ) |
def tab_insert ( self , e ) : # ( M - TAB )
u'''Insert a tab character .''' | cursor = min ( self . l_buffer . point , len ( self . l_buffer . line_buffer ) )
ws = ' ' * ( self . tabstop - ( cursor % self . tabstop ) )
self . insert_text ( ws )
self . finalize ( ) |
def _on_unexpected_disconnection ( self , success , result , failure_reason , context ) :
"""Callback function called when an unexpected disconnection occured ( meaning that we didn ' t previously send
a ` disconnect ` request ) .
It is executed in the baBLE working thread : should not be blocking .
Args :
... | connection_id = context [ 'connection_id' ]
self . _logger . warn ( 'Unexpected disconnection event, handle=%d, reason=0x%X, state=%s' , result [ 'connection_handle' ] , result [ 'code' ] , self . connections . get_state ( connection_id ) )
self . connections . unexpected_disconnect ( connection_id )
self . _trigger_ca... |
def stop ( self , dummy_signum = None , dummy_frame = None ) :
"""Shutdown process ( this method is also a signal handler )""" | logging . info ( 'Shutting down ...' )
self . socket . close ( )
sys . exit ( 0 ) |
def copy_files ( src_dir , dst_dir , filespec = '*' , recursive = False ) :
"""Copies any files matching filespec from src _ dir into dst _ dir .
If ` recursive ` is ` True ` , also copies any matching directories .""" | import os
from . modules import copyfiles
if src_dir == dst_dir :
raise RuntimeError ( 'copy_files() src and dst directories must be different.' )
if not os . path . isdir ( src_dir ) :
raise RuntimeError ( 'copy_files() src directory "{}" does not exist.' . format ( src_dir ) )
return { 'dependencies_fn' : cop... |
def _name_value_to_bson ( name , value , check_keys , opts ) :
"""Encode a single name , value pair .""" | # First see if the type is already cached . KeyError will only ever
# happen once per subtype .
try :
return _ENCODERS [ type ( value ) ] ( name , value , check_keys , opts )
except KeyError :
pass
# Second , fall back to trying _ type _ marker . This has to be done
# before the loop below since users could sub... |
def create_spot_instances ( launch_specs , spot_price = 26 , expiration_mins = 15 ) :
"""args :
spot _ price : default is $ 26 which is right above p3.16xlarge on demand price
expiration _ mins : this request only valid for this many mins from now""" | ec2c = get_ec2_client ( )
num_tasks = launch_specs [ 'MinCount' ] or 1
if 'MinCount' in launch_specs :
del launch_specs [ 'MinCount' ]
if 'MaxCount' in launch_specs :
del launch_specs [ 'MaxCount' ]
if 'TagSpecifications' in launch_specs :
try :
tags = launch_specs [ 'TagSpecifications' ] [ 0 ] [ 'T... |
def inverse_kinematics ( self , end_effector_transformation , q = None , max_iter = 1000 , tolerance = 0.05 , mask = numpy . ones ( 6 ) , use_pinv = False ) :
"""Computes the joint angles corresponding to the end effector transformation .
: param end _ effector _ transformation : the end effector homogeneous tran... | if q is None :
q = numpy . zeros ( ( len ( self . links ) , 1 ) )
q = numpy . matrix ( q . reshape ( - 1 , 1 ) )
best_e = numpy . ones ( 6 ) * numpy . inf
best_q = None
alpha = 1.0
for _ in range ( max_iter ) :
e = numpy . multiply ( transform_difference ( self . forward_kinematics ( q ) [ 0 ] , end_effector_tr... |
def add_operations ( self , root , definitions ) :
"""Add < operation / > children""" | dsop = Element ( 'operation' , ns = soapns )
for c in root . getChildren ( 'operation' ) :
op = Facade ( 'Operation' )
op . name = c . get ( 'name' )
sop = c . getChild ( 'operation' , default = dsop )
soap = Facade ( 'soap' )
soap . action = '"%s"' % sop . get ( 'soapAction' , default = '' )
so... |
def get_configuration ( self ) :
"""Returns a mapping of UID - > configuration""" | mapping = { }
settings = self . get_settings ( )
for record in self . context . getAnalyses ( ) :
uid = record . get ( "service_uid" )
setting = settings . get ( uid , { } )
config = { "partition" : record . get ( "partition" ) , "hidden" : setting . get ( "hidden" , False ) , }
mapping [ uid ] = config... |
def history ( self , channel_name , ** kwargs ) :
"""https : / / api . slack . com / methods / channels . history""" | channel_id = self . get_channel_id ( channel_name )
self . params . update ( { 'channel' : channel_id } )
if kwargs :
self . params . update ( kwargs )
return FromUrl ( 'https://slack.com/api/channels.history' , self . _requests ) ( data = self . params ) . get ( ) |
def _split_generators ( self , dl_manager ) :
"""Returns SplitGenerators .""" | # Download images and annotations that come in separate archives .
# Note , that the extension of archives is . tar . gz even though the actual
# archives format is uncompressed tar .
dl_paths = dl_manager . download_and_extract ( { "images" : tfds . download . Resource ( url = os . path . join ( _BASE_URL , "102flower... |
def add_methods ( methods_to_add ) :
'''use this to bulk add new methods to Generator''' | for i in methods_to_add :
try :
Generator . add_method ( * i )
except Exception as ex :
raise Exception ( 'issue adding {} - {}' . format ( repr ( i ) , ex ) ) |
def process_species ( self , limit ) :
"""Loop through the xml file and process the species .
We add elements to the graph , and store the
id - to - label in the label _ hash dict .
: param limit :
: return :""" | myfile = '/' . join ( ( self . rawdir , self . files [ 'data' ] [ 'file' ] ) )
fh = gzip . open ( myfile , 'rb' )
filereader = io . TextIOWrapper ( fh , newline = "" )
filereader . readline ( )
# remove the xml declaration line
for event , elem in ET . iterparse ( filereader ) : # iterparse is not deprecated
# Species ... |
def populate_all_metadata ( ) :
"""Create metadata instances for all models in seo _ models if empty .
Once you have created a single metadata instance , this will not run .
This is because it is a potentially slow operation that need only be
done once . If you want to ensure that everything is populated , ru... | for Metadata in registry . values ( ) :
InstanceMetadata = Metadata . _meta . get_model ( 'modelinstance' )
if InstanceMetadata is not None :
for model in Metadata . _meta . seo_models :
populate_metadata ( model , InstanceMetadata ) |
def generate_signed_url_v4 ( credentials , resource , expiration , api_access_endpoint = DEFAULT_ENDPOINT , method = "GET" , content_md5 = None , content_type = None , response_type = None , response_disposition = None , generation = None , headers = None , query_parameters = None , _request_timestamp = None , # for te... | ensure_signed_credentials ( credentials )
expiration_seconds = get_expiration_seconds_v4 ( expiration )
if _request_timestamp is None :
now = NOW ( )
request_timestamp = now . strftime ( "%Y%m%dT%H%M%SZ" )
datestamp = now . date ( ) . strftime ( "%Y%m%d" )
else :
request_timestamp = _request_timestamp
... |
def is_equal ( self , other_consonnant ) :
"""> > > v _ consonant = Consonant ( Place . labio _ dental , Manner . fricative , True , " v " , False )
> > > f _ consonant = Consonant ( Place . labio _ dental , Manner . fricative , False , " f " , False )
> > > v _ consonant . is _ equal ( f _ consonant )
False ... | return self . place == other_consonnant . place and self . manner == other_consonnant . manner and self . voiced == other_consonnant . voiced and self . geminate == other_consonnant . geminate |
def success ( request , message , extra_tags = '' , fail_silently = False ) :
"""Adds a message with the ` ` SUCCESS ` ` level .""" | add_message ( request , constants . SUCCESS , message , extra_tags = extra_tags , fail_silently = fail_silently ) |
def filter_convolve ( data , filters , filter_rot = False , method = 'scipy' ) :
r"""Filter convolve
This method convolves the input image with the wavelet filters
Parameters
data : np . ndarray
Input data , 2D array
filters : np . ndarray
Wavelet filters , 3D array
filter _ rot : bool , optional
Op... | if filter_rot :
return np . sum ( [ convolve ( coef , f , method = method ) for coef , f in zip ( data , rotate_stack ( filters ) ) ] , axis = 0 )
else :
return np . array ( [ convolve ( data , f , method = method ) for f in filters ] ) |
def add_sldId ( self , rId ) :
"""Return a reference to a newly created < p : sldId > child element having
its r : id attribute set to * rId * .""" | return self . _add_sldId ( id = self . _next_id , rId = rId ) |
def getPropagationBit ( self , t , p ) :
'''returns the propagation bit of a text value''' | try :
return self . validPropagations [ t ] [ p ] [ 'BITS' ]
except KeyError :
raise CommandExecutionError ( ( 'No propagation type of "{0}". It should be one of the following: {1}' ) . format ( p , ', ' . join ( self . validPropagations [ t ] ) ) ) |
def inputcooker_store_queue ( self , char ) :
"""Put the cooked data in the input queue ( with locking )""" | self . IQUEUELOCK . acquire ( )
if type ( char ) in [ type ( ( ) ) , type ( [ ] ) , type ( "" ) ] :
for v in char :
self . cookedq . append ( v )
else :
self . cookedq . append ( char )
self . IQUEUELOCK . release ( ) |
def to_shape_list ( region_list , coordinate_system = 'fk5' ) :
"""Converts a list of regions into a ` regions . ShapeList ` object .
Parameters
region _ list : python list
Lists of ` regions . Region ` objects
format _ type : str ( ' DS9 ' or ' CRTF ' )
The format type of the Shape object . Default is ' ... | shape_list = ShapeList ( )
for region in region_list :
coord = [ ]
if isinstance ( region , SkyRegion ) :
reg_type = region . __class__ . __name__ [ : - 9 ] . lower ( )
else :
reg_type = region . __class__ . __name__ [ : - 11 ] . lower ( )
for val in regions_attributes [ reg_type ] :
... |
def write_cyc ( fn , this , conv = 1.0 ) :
"""Write the lattice information to a cyc . dat file ( i . e . , tblmd input file )""" | lattice = this . get_cell ( )
f = paropen ( fn , "w" )
f . write ( "<------- Simulation box definition\n" )
f . write ( "<------- Barostat (on = 1, off = 0)\n" )
f . write ( " 0\n" )
f . write ( "<------- Box vectors (start)\n" )
f . write ( " %20.10f %20.10f %20.10f\n" % ( lattice [ 0 ] [ 0 ] * conv , lattice [ 1 ] ... |
def download_queue ( self , job_ids ) :
"""Downloads data of completed jobs .""" | if self . skip :
return None
url = "{}?jobtype=completed&jobIds={}" . format ( self . queue_url , "," . join ( str ( x ) for x in job_ids ) )
try :
response = self . session . get ( url , headers = { "Accept" : "application/json" } )
if response :
response = response . json ( )
else :
re... |
def get_options ( self ) :
"""A hook to override the flattened list of all options used to generate
option names and defaults .""" | return reduce ( list . __add__ , [ list ( option_list ) for option_list in self . get_option_lists ( ) ] , [ ] ) |
def html_result ( html : str , extraheaders : TYPE_WSGI_RESPONSE_HEADERS = None ) -> WSGI_TUPLE_TYPE :
"""Returns ` ` ( contenttype , extraheaders , data ) ` ` tuple for UTF - 8 HTML .""" | extraheaders = extraheaders or [ ]
return 'text/html; charset=utf-8' , extraheaders , html . encode ( "utf-8" ) |
def insert_fft_option_group ( parser ) :
"""Adds the options used to choose an FFT backend . This should be used
if your program supports the ability to select the FFT backend ; otherwise
you may simply call the fft and ifft functions and rely on default
choices . This function will also attempt to add any op... | fft_group = parser . add_argument_group ( "Options for selecting the" " FFT backend and controlling its performance" " in this program." )
# We have one argument to specify the backends . This becomes the default list used
# if none is specified for a particular call of fft ( ) of ifft ( ) . Note that this
# argument e... |
def lattice_array_to_unit_cell ( lattice_array ) :
"""Return crystallographic param . from unit cell lattice matrix .""" | cell_lengths = np . sqrt ( np . sum ( lattice_array ** 2 , axis = 0 ) )
gamma_r = np . arccos ( lattice_array [ 0 ] [ 1 ] / cell_lengths [ 1 ] )
beta_r = np . arccos ( lattice_array [ 0 ] [ 2 ] / cell_lengths [ 2 ] )
alpha_r = np . arccos ( lattice_array [ 1 ] [ 2 ] * np . sin ( gamma_r ) / cell_lengths [ 2 ] + np . co... |
def create_schema_from_xsd_directory ( directory , version ) :
"""Create and fill the schema from a directory which contains xsd
files . It calls fill _ schema _ from _ xsd _ file for each xsd file
found .""" | schema = Schema ( version )
for f in _get_xsd_from_directory ( directory ) :
logger . info ( "Loading schema %s" % f )
fill_schema_from_xsd_file ( f , schema )
return schema |
def _two_qubit_accumulate_into_scratch ( args : Dict [ str , Any ] ) :
"""Accumulates two qubit phase gates into the scratch shards .""" | index0 , index1 = args [ 'indices' ]
half_turns = args [ 'half_turns' ]
scratch = _scratch_shard ( args )
projector = _one_projector ( args , index0 ) * _one_projector ( args , index1 )
# Exp11 = exp ( - i pi | 11 > < 11 | half _ turns ) , but we accumulate phases as
# pi / 2.
scratch += 2 * half_turns * projector |
def security_cleanup ( app , appbuilder ) :
"""Cleanup unused permissions from views and roles .""" | _appbuilder = import_application ( app , appbuilder )
_appbuilder . security_cleanup ( )
click . echo ( click . style ( "Finished security cleanup" , fg = "green" ) ) |
def request_issuance ( self , csr ) :
"""Request a certificate .
Authorizations should have already been completed for all of the names
requested in the CSR .
Note that unlike ` acme . client . Client . request _ issuance ` , the certificate
resource will have the body data as raw bytes .
. . seealso : : ... | action = LOG_ACME_REQUEST_CERTIFICATE ( )
with action . context ( ) :
return ( DeferredContext ( self . _client . post ( self . directory [ csr ] , csr , content_type = DER_CONTENT_TYPE , headers = Headers ( { b'Accept' : [ DER_CONTENT_TYPE ] } ) ) ) . addCallback ( self . _expect_response , http . CREATED ) . addC... |
def show_instances ( server , cim_class ) :
"""Display the instances of the CIM _ Class defined by cim _ class . If the
namespace is None , use the interop namespace . Search all namespaces for
instances except for CIM _ RegisteredProfile""" | if cim_class == 'CIM_RegisteredProfile' :
for inst in server . profiles :
print ( inst . tomof ( ) )
return
for ns in server . namespaces :
try :
insts = server . conn . EnumerateInstances ( cim_class , namespace = ns )
if len ( insts ) :
print ( 'INSTANCES OF %s ns=%s' %... |
def unique ( self , sort = False ) :
"""Return unique set of values in image""" | unique_vals = np . unique ( self . numpy ( ) )
if sort :
unique_vals = np . sort ( unique_vals )
return unique_vals |
def get_arg_parse ( ) :
"""Parses the Command Line Arguments using argparse .""" | # Create parser object :
objParser = argparse . ArgumentParser ( )
# Add argument to namespace - config file path :
objParser . add_argument ( '-config' , required = True , metavar = '/path/to/config.csv' , help = 'Absolute file path of config file with \
parameters for pRF analysis. Ig... |
def run ( config , path = None , stop_on_error = True , just_tests = False ) :
"""Run sciunit tests for the given configuration .""" | if path is None :
path = os . getcwd ( )
prep ( config , path = path )
models = __import__ ( 'models' )
tests = __import__ ( 'tests' )
suites = __import__ ( 'suites' )
print ( '\n' )
for x in [ 'models' , 'tests' , 'suites' ] :
module = __import__ ( x )
assert hasattr ( module , x ) , "'%s' module requires ... |
def equal ( self , a , b , message = None ) :
"Check if two values are equal" | if a != b :
self . log_error ( "{} != {}" . format ( str ( a ) , str ( b ) ) , message )
return False
return True |
def toroidal ( target , mode = 'max' , r_toroid = 5e-6 , target_Pc = None , num_points = 1e2 , surface_tension = 'pore.surface_tension' , contact_angle = 'pore.contact_angle' , throat_diameter = 'throat.diameter' , touch_length = 'throat.touch_length' ) :
r"""Calculate the filling angle ( alpha ) for a given capill... | network = target . project . network
phase = target . project . find_phase ( target )
element , sigma , theta = _get_key_props ( phase = phase , diameter = throat_diameter , surface_tension = surface_tension , contact_angle = contact_angle )
x , R , rt , s , t = syp . symbols ( 'x, R, rt, s, t' )
# Equation of circle r... |
def _add_offsets_to_token_nodes ( self ) :
"""Adds primary text string onsets / offsets to all nodes that represent
tokens . In SaltDocuments , this data was stored in TextualRelation
edges only .""" | for edge_index in self . _textual_relation_ids :
token_node_index = self . edges [ edge_index ] . source
self . nodes [ token_node_index ] . onset = self . edges [ edge_index ] . onset
self . nodes [ token_node_index ] . offset = self . edges [ edge_index ] . offset |
def write_autoconf ( self , filename , header = "/* Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib) */\n" ) :
r"""Writes out symbol values as a C header file , matching the format used
by include / generated / autoconf . h in the kernel .
The ordering of the # defines matches the one generated... | with self . _open ( filename , "w" ) as f :
f . write ( header )
for sym in self . unique_defined_syms : # Note : _ write _ to _ conf is determined when the value is
# calculated . This is a hidden function call due to
# property magic .
val = sym . str_value
if sym . _write_to_conf :
... |
def change_and_save ( self , update_only_changed_fields = False , ** changed_fields ) :
"""Changes a given ` changed _ fields ` on this object , saves it and returns itself .
: param update _ only _ changed _ fields : only changed fields will be updated in the database .
: param changed _ fields : fields to cha... | change_and_save ( self , update_only_changed_fields = update_only_changed_fields , ** changed_fields )
return self |
def t_ID ( self , t ) :
r"""[ a - zA - Z _ ] [ a - zA - Z _ 0-9 ] *""" | # If the value is a reserved name , give it the appropriate type ( not ID )
if t . value in self . reserved :
t . type = self . reserved [ t . value ]
# If it ' s a function , give it the FUNC type
elif t . value in self . functions :
t . type = 'FUNC'
return t |
def authenticate ( self ) :
"""Authenticate into the UAA instance as the admin user .""" | # Make sure we ' ve stored uri for use
predix . config . set_env_value ( self . use_class , 'uri' , self . _get_uri ( ) )
self . uaac = predix . security . uaa . UserAccountAuthentication ( )
self . uaac . authenticate ( 'admin' , self . _get_admin_secret ( ) , use_cache = False )
self . is_admin = True |
def new ( self , fname = None , editorstack = None , text = None ) :
"""Create a new file - Untitled
fname = None - - > fname will be ' untitledXX . py ' but do not create file
fname = < basestring > - - > create file""" | # If no text is provided , create default content
empty = False
try :
if text is None :
default_content = True
text , enc = encoding . read ( self . TEMPLATE_PATH )
enc_match = re . search ( r'-*- coding: ?([a-z0-9A-Z\-]*) -*-' , text )
if enc_match :
enc = enc_match . gr... |
def database_path ( cls , project , instance , database ) :
"""Return a fully - qualified database string .""" | return google . api_core . path_template . expand ( "projects/{project}/instances/{instance}/databases/{database}" , project = project , instance = instance , database = database , ) |
def in6_getLocalUniquePrefix ( ) :
"""Returns a pseudo - randomly generated Local Unique prefix . Function
follows recommandation of Section 3.2.2 of RFC 4193 for prefix
generation .""" | # Extracted from RFC 1305 ( NTP ) :
# NTP timestamps are represented as a 64 - bit unsigned fixed - point number ,
# in seconds relative to 0h on 1 January 1900 . The integer part is in the
# first 32 bits and the fraction part in the last 32 bits .
# epoch = ( 1900 , 1 , 1 , 0 , 0 , 0 , 5 , 1 , 0)
# x = time . time ( ... |
def _categorize_successor ( self , state ) :
"""Append state into successor lists .
: param state : a SimState instance
: param target : The target ( of the jump / call / ret )
: return : The state""" | self . all_successors . append ( state )
target = state . scratch . target
# categorize the state
if o . APPROXIMATE_GUARDS in state . options and state . solver . is_false ( state . scratch . guard , exact = False ) :
if o . VALIDATE_APPROXIMATIONS in state . options :
if state . satisfiable ( ) :
... |
def create_authenticate_message ( self , user_name , password , domain_name = None , workstation = None , server_certificate_hash = None ) :
"""Create an NTLM AUTHENTICATE _ MESSAGE based on the Ntlm context and the previous messages sent and received
: param user _ name : The user name of the user we are trying ... | self . authenticate_message = AuthenticateMessage ( user_name , password , domain_name , workstation , self . challenge_message , self . ntlm_compatibility , server_certificate_hash )
self . authenticate_message . add_mic ( self . negotiate_message , self . challenge_message )
# Setups up the session _ security context... |
def update_resource_attribute ( resource_attr_id , is_var , ** kwargs ) :
"""Deletes a resource attribute and all associated data .""" | user_id = kwargs . get ( 'user_id' )
try :
ra = db . DBSession . query ( ResourceAttr ) . filter ( ResourceAttr . id == resource_attr_id ) . one ( )
except NoResultFound :
raise ResourceNotFoundError ( "Resource Attribute %s not found" % ( resource_attr_id ) )
ra . check_write_permission ( user_id )
ra . is_var... |
def text2class_txt_iterator ( source_txt_path , label_txt_path , class_strs = None ) :
"""Yield dicts for Text2ClassProblem . generate _ samples from lines of files .
Args :
source _ txt _ path : txt file with record per line .
label _ txt _ path : txt file with label per line , either as int or str . If
st... | if class_strs :
class_strs = dict ( [ ( s , i ) for i , s in enumerate ( class_strs ) ] )
for inputs , label in zip ( txt_line_iterator ( source_txt_path ) , txt_line_iterator ( label_txt_path ) ) :
label = label . strip ( )
if class_strs :
label = class_strs [ label ]
else :
label = int... |
def get_darwin_arches ( major , minor , machine ) :
"""Return a list of supported arches ( including group arches ) for
the given major , minor and machine architecture of a macOS machine .""" | arches = [ ]
def _supports_arch ( major , minor , arch ) : # Looking at the application support for macOS versions in the chart
# provided by https : / / en . wikipedia . org / wiki / OS _ X # Versions it appears
# our timeline looks roughly like :
# 10.0 - Introduces ppc support .
# 10.4 - Introduces ppc64 , i386 , an... |
def get_delete_url ( self ) :
"""Get model object delete url""" | return reverse ( 'trionyx:model-delete' , kwargs = { 'app' : self . get_app_label ( ) , 'model' : self . get_model_name ( ) , 'pk' : self . object . id } ) |
def buildDiscoveryURL ( self ) :
"""Return a discovery URL for this realm .
This function does not check to make sure that the realm is
valid . Its behaviour on invalid inputs is undefined .
@ rtype : str
@ returns : The URL upon which relying party discovery should be run
in order to verify the return _ ... | if self . wildcard : # Use " www . " in place of the star
assert self . host . startswith ( '.' ) , self . host
www_domain = 'www' + self . host
return '%s://%s%s' % ( self . proto , www_domain , self . path )
else :
return self . unparsed |
def _scheme_propagation ( self , scheme , definitions ) :
"""Will updated a scheme based on inheritance . This is defined in a scheme objects with ` ` ' inherit ' : ' $ definition ' ` ` .
Will also updated parent objects for nested inheritance .
Usage : :
> > > SCHEME = {
> > > ' thing1 ' : {
> > > ' inhe... | if not isinstance ( scheme , dict ) :
raise TypeError ( 'scheme must be a dict to propagate.' )
inherit_from = scheme . get ( 'inherit' )
if isinstance ( inherit_from , six . string_types ) :
if not inherit_from . startswith ( '$' ) :
raise AttributeError ( 'When inheriting from an object it must start ... |
def clear ( self ) -> None :
"""Destroys all running containers .""" | r = self . __api . delete ( 'containers' )
if r . status_code != 204 :
self . __api . handle_erroneous_response ( r ) |
def exit_with_error ( message ) :
"""Display formatted error message and exit call""" | click . secho ( message , err = True , bg = 'red' , fg = 'white' )
sys . exit ( 0 ) |
def add_node ( self , transformer , name = None , children = None , parent = None , parameters = { } , return_node = False ) :
'''Adds a node to the current graph .
Args :
transformer ( str , Transformer ) : The pliers Transformer to use at
the to - be - added node . Either a case - insensitive string giving ... | node = Node ( transformer , name , ** parameters )
self . nodes [ node . id ] = node
if parent is None :
self . roots . append ( node )
else :
parent = self . nodes [ parent . id ]
parent . add_child ( node )
if children is not None :
self . add_nodes ( children , parent = node )
if return_node :
re... |
def get_objectives_by_query ( self , objective_query = None ) :
"""Gets a list of Objectives matching the given objective query .
arg : objectiveQuery ( osid . learning . ObjectiveQuery ) : the
objective query
return : ( osid . learning . ObjectiveList ) - the returned
ObjectiveList
raise : NullArgument -... | if objective_query is None :
raise NullArgument ( )
if 'ancestorObjectiveId' in objective_query . _query_terms :
url_path = construct_url ( 'objectives' , bank_id = self . _objective_bank_id , obj_id = objective_query . _query_terms [ 'ancestorObjectiveId' ] . split ( '=' ) [ 1 ] )
url_path += '/children'
e... |
def validate_lv_districts ( session , nw ) :
'''Validate if total load of a grid in a pkl file is what expected from LV districts
Parameters
session : sqlalchemy . orm . session . Session
Database session
nw :
The network
Returns
DataFrame
compare _ by _ district
DataFrame
compare _ by _ loads''... | # config network intern variables
nw . _config = nw . import_config ( )
nw . _pf_config = nw . import_pf_config ( )
nw . _static_data = nw . import_static_data ( )
nw . _orm = nw . import_orm ( )
# rescue peak load from input table
lv_ditricts = [ dist . id_db for mv in nw . mv_grid_districts ( ) for la in mv . lv_load... |
def multi_dict ( pairs ) :
"""Given a set of key value pairs , create a dictionary .
If a key occurs multiple times , stack the values into an array .
Can be called like the regular dict ( pairs ) constructor
Parameters
pairs : ( n , 2 ) array of key , value pairs
Returns
result : dict , with all values... | result = collections . defaultdict ( list )
for k , v in pairs :
result [ k ] . append ( v )
return result |
def add_operation ( self , operation_type , operation , mode = None ) :
"""Add an operation to the version
: param mode : Name of the mode in which the operation is executed
: type mode : str
: param operation _ type : one of ' pre ' , ' post '
: type operation _ type : str
: param operation : the operati... | version_mode = self . _get_version_mode ( mode = mode )
if operation_type == 'pre' :
version_mode . add_pre ( operation )
elif operation_type == 'post' :
version_mode . add_post ( operation )
else :
raise ConfigurationError ( u"Type of operation must be 'pre' or 'post', got %s" % ( operation_type , ) ) |
def _on_changed ( self ) :
"""Update the tree items""" | self . _updating = True
to_collapse = [ ]
self . clear ( )
if self . _editor and self . _outline_mode and self . _folding_panel :
items , to_collapse = self . to_tree_widget_items ( self . _outline_mode . definitions , to_collapse = to_collapse )
if len ( items ) :
self . addTopLevelItems ( items )
... |
async def delete ( self , db ) :
'''Delete document''' | for i in self . connection_retries ( ) :
try :
return await db [ self . get_collection_name ( ) ] . delete_one ( { self . primary_key : self . pk } )
except ConnectionFailure as ex :
exceed = await self . check_reconnect_tries_and_wait ( i , 'delete' )
if exceed :
raise ex |
def visitInlineShapeOrRef ( self , ctx : ShExDocParser . InlineShapeOrRefContext ) :
"""inlineShapeOrRef : inlineShapeDefinition | shapeRef""" | if ctx . inlineShapeDefinition ( ) :
from pyshexc . parser_impl . shex_shape_definition_parser import ShexShapeDefinitionParser
shdef_parser = ShexShapeDefinitionParser ( self . context , self . label )
shdef_parser . visitChildren ( ctx )
self . expr = shdef_parser . shape
else :
self . expr = self... |
def _get_indices ( self , names ) :
"""Safe get multiple indices , translate keys for
datelike to underlying repr .""" | def get_converter ( s ) : # possibly convert to the actual key types
# in the indices , could be a Timestamp or a np . datetime64
if isinstance ( s , ( Timestamp , datetime . datetime ) ) :
return lambda key : Timestamp ( key )
elif isinstance ( s , np . datetime64 ) :
return lambda key : Timest... |
def reverseCommit ( self ) :
"""Reinsert the killed word .""" | if self . selectionPosOld is None :
return
# Shorthand .
wid = self . qteWidget
# Select , backup , and delete the selection .
wid . setSelection ( * self . selectionPosNew )
self . baseClass . replaceSelectedText ( self . oldText )
# Add the styling information .
line , col = self . selectionPosNew [ 0 : 2 ]
wid .... |
def _is_bounded_iterator_based ( self ) :
"""Iterator based check .
With respect to a certain variable / value A ,
- there must be at least one exit condition being A / / Iterator / / HasNext = = 0
- there must be at least one local that ticks the iterator next : A / / Iterator / / Next""" | # Condition 0
check_0 = lambda cond : ( isinstance ( cond , Condition ) and cond . op == Condition . Equal and cond . val1 == 0 and isinstance ( cond . val0 , AnnotatedVariable ) and cond . val0 . type == VariableTypes . HasNext )
check_0_results = [ ( check_0 ( stmt [ 0 ] ) , stmt [ 0 ] ) for stmt in self . loop_exit_... |
def getScoringVector ( self , profile ) :
"""Returns the scoring vector [ m - 1 , m - 2 , m - 3 , . . . , 0 ] where m is the number of candidates in the
election profile . This function is called by getCandScoresMap ( ) which is implemented in the
parent class .
: ivar Profile profile : A Profile object that ... | scoringVector = [ ]
score = profile . numCands - 1
for i in range ( 0 , profile . numCands ) :
scoringVector . append ( score )
score -= 1
return scoringVector |
def routes ( name , ** kwargs ) :
'''Manage network interface static routes .
name
Interface name to apply the route to .
kwargs
Named routes''' | ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : 'Interface {0} routes are up to date.' . format ( name ) , }
apply_routes = False
if 'test' not in kwargs :
kwargs [ 'test' ] = __opts__ . get ( 'test' , False )
# Build interface routes
try :
old = __salt__ [ 'ip.get_routes' ] ( name )
... |
def collect_conflicts_between_fragments ( context : ValidationContext , conflicts : List [ Conflict ] , cached_fields_and_fragment_names : Dict , compared_fragment_pairs : "PairSet" , are_mutually_exclusive : bool , fragment_name1 : str , fragment_name2 : str , ) -> None :
"""Collect conflicts between fragments .
... | # No need to compare a fragment to itself .
if fragment_name1 == fragment_name2 :
return
# Memoize so two fragments are not compared for conflicts more than once .
if compared_fragment_pairs . has ( fragment_name1 , fragment_name2 , are_mutually_exclusive ) :
return
compared_fragment_pairs . add ( fragment_name... |
def attr_chain ( obj , attr ) :
"""Follow an attribute chain .
If you have a chain of objects where a . foo - > b , b . foo - > c , etc ,
use this to iterate over all objects in the chain . Iteration is
terminated by getattr ( x , attr ) is None .
Args :
obj : the starting object
attr : the name of the ... | next = getattr ( obj , attr )
while next :
yield next
next = getattr ( next , attr ) |
def http_resource ( self , method , url , params = None , data = None ) :
"""Makes an HTTP request .""" | url = urllib_parse . urljoin ( self . url , url )
url = url if url . endswith ( "/" ) else url + "/"
headers = None
if method . lower ( ) in self . unsupported_methods :
headers = { "X-HTTP-Method-Override" : method . upper ( ) }
method = "POST"
r = self . session . request ( method , url , params = params , da... |
async def _async_register ( self ) : # pragma : no cover
"""Register the agent in the XMPP server from a coroutine .""" | metadata = aioxmpp . make_security_layer ( None , no_verify = not self . verify_security )
query = ibr . Query ( self . jid . localpart , self . password )
_ , stream , features = await aioxmpp . node . connect_xmlstream ( self . jid , metadata , loop = self . loop )
await ibr . register ( stream , query ) |
def broadcast_transaction ( self , hex_tx ) :
"""Dispatch a raw transaction to the network .""" | resp = self . obj . sendrawtransaction ( hex_tx )
if len ( resp ) > 0 :
return { 'transaction_hash' : resp , 'success' : True }
else :
return error_reply ( 'Invalid response from bitcoind.' ) |
def _is_address_executable ( self , address ) :
"""Check if the specific address is in one of the executable ranges .
: param int address : The address
: return : True if it ' s in an executable range , False otherwise""" | for r in self . _executable_address_ranges :
if r [ 0 ] <= address < r [ 1 ] :
return True
return False |
async def create_with_msgid ( source_id : str , connection : Connection , msg_id : str ) :
"""Create a credential based off of a known message id for a given connection .
: param source _ id : user defined id of object .
: param connection : connection handle of connection to receive offer from
: param msg _ ... | credential = Credential ( source_id , )
c_source_id = c_char_p ( source_id . encode ( 'utf-8' ) )
c_msg_id = c_char_p ( json . dumps ( msg_id ) . encode ( 'utf-8' ) )
c_connection_handle = c_uint32 ( connection . handle )
if not hasattr ( Credential . create_with_msgid , "cb" ) :
Credential . create_with_msgid . cb... |
def smooth_l1_distance ( labels , preds , delta = 1.0 ) :
"""Compute the smooth l1 _ distance .
: param labels : A float tensor of shape [ batch _ size , . . . , X ] representing the labels .
: param preds : A float tensor of shape [ batch _ size , . . . , X ] representing the predictions .
: param delta : ` ... | with tf . variable_scope ( "smooth_l1" ) :
return tf . reduce_sum ( tf . losses . huber_loss ( labels = labels , predictions = preds , delta = delta , loss_collection = None , reduction = tf . losses . Reduction . NONE ) , axis = - 1 ) |
def get_command ( domain_name , command_name ) :
"""Returns a closure function that dispatches message to the WebSocket .""" | def send_command ( self , ** kwargs ) :
return self . ws . send_message ( '{0}.{1}' . format ( domain_name , command_name ) , kwargs )
return send_command |
def reverse_lazy_with_query ( named_url , ** kwargs ) :
"Reverse named URL with GET query ( lazy version )" | q = QueryDict ( '' , mutable = True )
q . update ( kwargs )
return '{}?{}' . format ( reverse_lazy ( named_url ) , q . urlencode ( ) ) |
def _abort_batches ( self ) :
"""Go through incomplete batches and abort them .""" | error = Errors . IllegalStateError ( "Producer is closed forcefully." )
for batch in self . _incomplete . all ( ) :
tp = batch . topic_partition
# Close the batch before aborting
with self . _tp_locks [ tp ] :
batch . records . close ( )
batch . done ( exception = error )
self . deallocate (... |
def midpoint_refine_triangulation_by_vertices ( self , vertices ) :
"""return points defining a refined triangulation obtained by bisection of all edges
in the triangulation connected to any of the vertices in the list provided""" | mlons , mlats = self . segment_midpoints_by_vertices ( vertices = vertices )
lonv1 = np . concatenate ( ( self . lons , mlons ) , axis = 0 )
latv1 = np . concatenate ( ( self . lats , mlats ) , axis = 0 )
return lonv1 , latv1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.