signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def create_folder_if_not_exists ( folder_path ) :
"""Creates a folder if it does not exists .""" | folder_path = tilde_expansion ( folder_path )
folder_path = "" . join ( [ folder_path , '/' ] ) if not folder_path [ - 1 ] == '/' else folder_path
direc = os . path . dirname ( folder_path )
if not folder_exists ( direc ) :
os . makedirs ( direc ) |
def on_helpButton ( self , event , page = None ) :
"""shows html help page""" | # for use on the command line :
path = find_pmag_dir . get_pmag_dir ( )
# for use with pyinstaller
# path = self . main _ frame . resource _ dir
help_page = os . path . join ( path , 'dialogs' , 'help_files' , page )
# if using with py2app , the directory structure is flat ,
# so check to see where the resource actuall... |
def start_tcp_server ( self , ip , port , name = None , timeout = None , protocol = None , family = 'ipv4' ) :
"""Starts a new TCP server to given ` ip ` and ` port ` .
Server can be given a ` name ` , default ` timeout ` and a ` protocol ` .
` family ` can be either ipv4 ( default ) or ipv6 . Notice that you h... | self . _start_server ( TCPServer , ip , port , name , timeout , protocol , family ) |
def write ( self , filename , compress = True , catalog_format = "QUAKEML" ) :
"""Write the tribe to a file using tar archive formatting .
: type filename : str
: param filename :
Filename to write to , if it exists it will be appended to .
: type compress : bool
: param compress :
Whether to compress t... | if catalog_format not in CAT_EXT_MAP . keys ( ) :
raise TypeError ( "{0} is not supported" . format ( catalog_format ) )
if not os . path . isdir ( filename ) :
os . makedirs ( filename )
self . _par_write ( filename )
tribe_cat = Catalog ( )
for t in self . templates :
if t . event is not None :
tr... |
def _create_route ( self , env , item ) :
"""Constructs a route and adds it to the environment .
Args :
env ( dict ) : The environment of defined symbols . A new key is added
corresponding to the name of this new route .
item ( AstRouteDef ) : Raw route definition from the parser .
Returns :
stone . api... | if item . name in env :
if isinstance ( env [ item . name ] , ApiRoutesByVersion ) :
if item . version in env [ item . name ] . at_version :
existing_dt = env [ item . name ] . at_version [ item . version ]
raise InvalidSpec ( 'Route %s at version %d already defined (%s:%d).' % ( quo... |
def run_suite ( case , config , summary ) :
"""Run the full suite of validation tests""" | m = _load_case_module ( case , config )
result = m . run ( case , config )
summary [ case ] = _summarize_result ( m , result )
_print_summary ( m , case , summary )
if result [ 'Type' ] == 'Book' :
for name , page in six . iteritems ( result [ 'Data' ] ) :
functions . create_page_from_template ( "validation... |
def dereference ( self ) :
"""Instruct all children to perform dereferencing .""" | all = [ ]
indexes = { }
for child in self . children :
child . content ( all )
deplist = DepList ( )
for x in all :
x . qualify ( )
midx , deps = x . dependencies ( )
item = ( x , tuple ( deps ) )
deplist . add ( item )
indexes [ x ] = midx
for x , deps in deplist . sort ( ) :
midx = indexes... |
def main ( ) :
"""Cli entrypoint .""" | if len ( sys . argv ) == 2 :
fname = sys . argv [ 1 ]
data = json . load ( open ( fname , 'rb' ) )
else :
data = json . loads ( sys . stdin . read ( ) )
print ( pydeps2reqs ( data ) ) |
def handle_error ( self , request : BaseRequest , status : int = 500 , exc : Optional [ BaseException ] = None , message : Optional [ str ] = None ) -> StreamResponse :
"""Handle errors .
Returns HTTP response with specific status code . Logs additional
information . It always closes current connection .""" | self . log_exception ( "Error handling request" , exc_info = exc )
ct = 'text/plain'
if status == HTTPStatus . INTERNAL_SERVER_ERROR :
title = '{0.value} {0.phrase}' . format ( HTTPStatus . INTERNAL_SERVER_ERROR )
msg = HTTPStatus . INTERNAL_SERVER_ERROR . description
tb = None
if self . debug :
... |
def proc_decorator ( req_set ) :
"""Decorator that provides the wrapped function with an attribute ' actual _ kwargs '
containing just those keyword arguments actually passed in to the function .""" | def decorator ( func ) :
@ wraps ( func )
def inner ( self , * args , ** kwargs ) :
proc = func . __name__ . lower ( )
inner . proc_decorator = kwargs
self . logger . debug ( "processing proc:{}" . format ( func . __name__ ) )
self . logger . debug ( req_set )
self . logg... |
def message ( self , message , source , point , ln ) :
"""Creates the - - strict Coconut error message .""" | message += " (disable --strict to dismiss)"
return super ( CoconutStyleError , self ) . message ( message , source , point , ln ) |
def list_management_certificates ( kwargs = None , conn = None , call = None ) :
'''. . versionadded : : 2015.8.0
List management certificates associated with the subscription
CLI Example :
. . code - block : : bash
salt - cloud - f list _ management _ certificates my - azure name = my _ management''' | if call != 'function' :
raise SaltCloudSystemExit ( 'The list_management_certificates function must be called with -f or --function.' )
if not conn :
conn = get_conn ( )
data = conn . list_management_certificates ( )
ret = { }
for item in data . subscription_certificates :
ret [ item . subscription_certific... |
def __update_siblings_active_labels_states ( self , active_label ) :
"""Updates given * * Active _ QLabel * * Widget siblings states .
: param active _ label : Active label .
: type active _ label : Active _ QLabel""" | LOGGER . debug ( "> Clicked 'Active_QLabel': '{0}'." . format ( active_label ) )
for item in self . __active_labels :
if item is active_label :
continue
umbra . ui . common . signals_blocker ( item , item . set_checked , False ) |
def point_is_valid ( generator , x , y ) :
"""Is ( x , y ) a valid public key based on the specified generator ?""" | # These are the tests specified in X9.62.
n = generator . order ( )
curve = generator . curve ( )
if x < 0 or n <= x or y < 0 or n <= y :
return False
if not curve . contains_point ( x , y ) :
return False
if not n * ellipticcurve . Point ( curve , x , y ) == ellipticcurve . INFINITY :
return False
return T... |
def on_change ( self , * callbacks ) :
'''Provide callbacks to invoke if the document or any Model reachable
from its roots changes .''' | for callback in callbacks :
if callback in self . _callbacks :
continue
_check_callback ( callback , ( 'event' , ) )
self . _callbacks [ callback ] = callback |
async def sonar_config ( self , command ) :
"""This method configures 2 pins to support HC - SR04 Ping devices .
This is a FirmataPlus feature .
: param command : { " method " : " sonar _ config " , " params " : [ TRIGGER _ PIN , ECHO _ PIN , PING _ INTERVAL ( default = 50 ) ,
MAX _ DISTANCE ( default = 200 c... | trigger = int ( command [ 0 ] )
echo = int ( command [ 1 ] )
interval = int ( command [ 2 ] )
max_dist = int ( command [ 3 ] )
await self . core . sonar_config ( trigger , echo , self . sonar_callback , interval , max_dist ) |
def get_import_stacklevel ( import_hook ) :
"""Returns the stacklevel value for warnings . warn ( ) for when the warning
gets emitted by an imported module , but the warning should point at the
code doing the import .
Pass import _ hook = True if the warning gets generated by an import hook
( warn ( ) gets ... | py_version = sys . version_info [ : 2 ]
if py_version <= ( 3 , 2 ) : # 2.7 included
return 4 if import_hook else 2
elif py_version == ( 3 , 3 ) :
return 8 if import_hook else 10
elif py_version == ( 3 , 4 ) :
return 10 if import_hook else 8
else : # fixed again in 3.5 + , see https : / / bugs . python . org... |
def _internal_kv_put ( key , value , overwrite = False ) :
"""Globally associates a value with a given binary key .
This only has an effect if the key does not already have a value .
Returns :
already _ exists ( bool ) : whether the value already exists .""" | worker = ray . worker . get_global_worker ( )
if worker . mode == ray . worker . LOCAL_MODE :
exists = key in _local
if not exists or overwrite :
_local [ key ] = value
return exists
if overwrite :
updated = worker . redis_client . hset ( key , "value" , value )
else :
updated = worker . red... |
def run ( ) :
"""Run the script in sys . argv [ 1 ] as if it had
been invoked naturally .""" | __builtins__
script_name = sys . argv [ 1 ]
namespace = dict ( __file__ = script_name , __name__ = '__main__' , __doc__ = None , )
sys . argv [ : ] = sys . argv [ 1 : ]
open_ = getattr ( tokenize , 'open' , open )
script = open_ ( script_name ) . read ( )
norm_script = script . replace ( '\\r\\n' , '\\n' )
code = compi... |
def ApprovalFind ( object_id , token = None ) :
"""Find approvals issued for a specific client .""" | user = getpass . getuser ( )
object_id = rdfvalue . RDFURN ( object_id )
try :
approved_token = security . Approval . GetApprovalForObject ( object_id , token = token , username = user )
print ( "Found token %s" % str ( approved_token ) )
return approved_token
except access_control . UnauthorizedAccess :
... |
def on_stop ( self ) :
"""stop the service""" | LOGGER . debug ( "rabbitmq.Service.on_stop" )
self . is_started = False
try :
self . channel . stop_consuming ( )
except Exception as e :
LOGGER . warn ( "rabbitmq.Service.on_stop - Exception raised while stoping consuming" )
try :
self . channel . close ( )
except Exception as e :
LOGGER . warn ( "rabb... |
def save_to_file ( self , out_file ) :
"""Saves correlation matrix of selected headers
: param out _ file : Output file""" | correlation_matrix = self . get_correlation_matrix_from_columns ( )
cr_plot . create_correlation_matrix_plot ( correlation_matrix , self . title , self . headers_to_test )
fig = pyplot . gcf ( )
# get reference to figure
fig . set_size_inches ( 23.4 , 23.4 )
pyplot . savefig ( out_file , dpi = 120 ) |
def duration ( self ) :
"""If the start and end times of the job are defined , return a timedelta ,
else return None""" | try :
start , end = self . hmget ( 'start' , 'end' )
return parse ( end ) - parse ( start )
except :
return None |
def cov ( args ) :
"""% prog cov chrA01 chrC01 chr . sizes data AN . CN . 1x1 . lifted . anchors . simple
Plot coverage graphs between homeologs , the middle panel show the
homeologous gene pairs . Allow multiple chromosomes to multiple chromosomes .""" | p = OptionParser ( cov . __doc__ )
p . add_option ( "--order" , default = "swede,kale,h165,yudal,aviso,abu,bristol,bzh" , help = "The order to plot the tracks, comma-separated" )
p . add_option ( "--reverse" , default = False , action = "store_true" , help = "Plot the order in reverse" )
p . add_option ( "--gauge_step"... |
def _get_dispatches_for_update ( filter_kwargs ) :
"""Distributed friendly version using ` ` select for update ` ` .""" | dispatches = Dispatch . objects . prefetch_related ( 'message' ) . filter ( ** filter_kwargs ) . select_for_update ( ** GET_DISPATCHES_ARGS [ 1 ] ) . order_by ( '-message__time_created' )
try :
dispatches = list ( dispatches )
except NotSupportedError :
return None
except DatabaseError : # Probably locked . Tha... |
def _do_for ( self , rule , p_selectors , p_parents , p_children , scope , media , c_lineno , c_property , c_codestr , code , name ) :
"""Implements @ for""" | var , _ , name = name . partition ( 'from' )
frm , _ , through = name . partition ( 'through' )
if not through :
frm , _ , through = frm . partition ( 'to' )
frm = self . calculate ( frm , rule [ CONTEXT ] , rule [ OPTIONS ] , rule )
through = self . calculate ( through , rule [ CONTEXT ] , rule [ OPTIONS ] , rule ... |
def isns_isns_vrf_isns_discovery_domain_isns_discovery_domain_name ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
isns = ET . SubElement ( config , "isns" , xmlns = "urn:brocade.com:mgmt:brocade-isns" )
isns_vrf = ET . SubElement ( isns , "isns-vrf" )
isns_vrf_instance_key = ET . SubElement ( isns_vrf , "isns-vrf-instance" )
isns_vrf_instance_key . text = kwargs . pop ( 'isns_vrf_instance' )
isns... |
def pre_handler ( self , cmd ) :
"""Hook for logic before each handler starts .""" | if self . _finished :
return
if self . interesting_commit and cmd . name == 'commit' :
if cmd . mark == self . interesting_commit :
print ( cmd . to_string ( ) )
self . _finished = True
return
if cmd . name in self . parsed_params :
fields = self . parsed_params [ cmd . name ]
str = ... |
def get_completion_args ( self , is_completion = False , comp_line = None ) : # pylint : disable = no - self - use
"""Get the args that will be used to tab completion if completion is active .""" | is_completion = is_completion or os . environ . get ( ARGCOMPLETE_ENV_NAME )
comp_line = comp_line or os . environ . get ( 'COMP_LINE' )
# The first item is the exe name so ignore that .
return comp_line . split ( ) [ 1 : ] if is_completion and comp_line else None |
def getCancelURL ( self ) :
"""Get the URL to cancel this request .
Useful for creating a " Cancel " button on a web form so that operation
can be carried out directly without another trip through the server .
( Except you probably want to make another trip through the server so
that it knows that the user ... | if not self . return_to :
raise NoReturnToError
if self . immediate :
raise ValueError ( "Cancel is not an appropriate response to " "immediate mode requests." )
response = Message ( self . message . getOpenIDNamespace ( ) )
response . setArg ( OPENID_NS , 'mode' , 'cancel' )
return response . toURL ( self . re... |
def doit ( self , classes = None , recursive = True , indices = None , max_terms = None , ** kwargs ) :
"""Write out the indexed sum explicitly
If ` classes ` is None or : class : ` IndexedSum ` is in ` classes ` ,
( partially ) write out the indexed sum in to an explicit sum of terms .
If ` recursive ` is Tr... | return super ( ) . doit ( classes , recursive , indices = indices , max_terms = max_terms , ** kwargs ) |
def _find_git_info ( self , gitdir ) :
"""Find information about the git repository , if this file is in a clone .
: param gitdir : path to the git repo ' s . git directory
: type gitdir : str
: returns : information about the git clone
: rtype : dict""" | res = { 'remotes' : None , 'tag' : None , 'commit' : None , 'dirty' : None }
try :
logger . debug ( 'opening %s as git.Repo' , gitdir )
repo = Repo ( path = gitdir , search_parent_directories = False )
res [ 'commit' ] = repo . head . commit . hexsha
res [ 'dirty' ] = repo . is_dirty ( untracked_files =... |
def birth ( self ) :
'''Create the individual ( compute the spline curve )''' | spline = scipy . interpolate . splrep ( self . x , self . y )
self . y_int = scipy . interpolate . splev ( self . x_int , spline ) |
def preprocess_french ( trans , fr_nlp , remove_brackets_content = True ) :
"""Takes a list of sentences in french and preprocesses them .""" | if remove_brackets_content :
trans = pangloss . remove_content_in_brackets ( trans , "[]" )
# Not sure why I have to split and rejoin , but that fixes a Spacy token
# error .
trans = fr_nlp ( " " . join ( trans . split ( ) [ : ] ) )
# trans = fr _ nlp ( trans )
trans = " " . join ( [ token . lower_ for token in tra... |
def id ( self , id ) :
"""Sets the id of this ServicePackageQuotaHistoryReservation .
Reservation ID .
: param id : The id of this ServicePackageQuotaHistoryReservation .
: type : str""" | if id is None :
raise ValueError ( "Invalid value for `id`, must not be `None`" )
if id is not None and len ( id ) > 250 :
raise ValueError ( "Invalid value for `id`, length must be less than or equal to `250`" )
if id is not None and len ( id ) < 1 :
raise ValueError ( "Invalid value for `id`, length must ... |
def get_all_firmwares ( self , filter = '' , start = 0 , count = - 1 , query = '' , sort = '' ) :
"""Gets a list of firmware inventory across all servers . To filter the returned data , specify a filter
expression to select a particular server model , component name , and / or component firmware version .
Note ... | uri = self . URI + "/*/firmware"
return self . _helper . get_all ( start , count , filter , query , sort , '' , '' , uri ) |
def ppc ( self , nsims = 1000 , T = np . mean ) :
"""Computes posterior predictive p - value
Parameters
nsims : int ( default : 1000)
How many draws for the PPC
T : function
A discrepancy measure - e . g . np . mean , np . std , np . max
Returns
- float ( posterior predictive p - value )""" | if self . latent_variables . estimation_method not in [ 'BBVI' , 'M-H' ] :
raise Exception ( "No latent variables estimated!" )
else :
lv_draws = self . draw_latent_variables ( nsims = nsims )
sigmas = [ self . _model ( lv_draws [ : , i ] ) [ 0 ] for i in range ( nsims ) ]
data_draws = np . array ( [ fa... |
def ecp_dict_to_objects ( ecp_dict , custom_map = None , verbose = 0 ) :
"""Given an ecp dictionary , build a dictionary of sfsi objects
: param ecp _ dict : dict , engineering consistency project dictionary
: param custom : dict , used to load custom objects , { model type : custom object }
: param verbose :... | if custom_map is None :
custom_map = { }
obj_map = { "soil-soil" : soils . Soil , "soil-critical_soil" : soils . CriticalSoil , "soil-soil_critical" : soils . CriticalSoil , # deprecated type
"soil-stress_dependent_soil" : soils . StressDependentSoil , "soil-soil_stress_dependent" : soils . StressDependentSoil , "s... |
def combine_comments ( comments ) :
'''Given a list of comments , or a comment submitted as a string , return a
single line of text containing all of the comments .''' | if isinstance ( comments , list ) :
for idx in range ( len ( comments ) ) :
if not isinstance ( comments [ idx ] , six . string_types ) :
comments [ idx ] = six . text_type ( comments [ idx ] )
else :
if not isinstance ( comments , six . string_types ) :
comments = [ six . text_type ... |
def send_last_message ( self , msg , connection_id = None ) :
"""Should be used instead of send _ message , when you want to close the
connection once the message is sent .
: param msg : protobuf validator _ pb2 . Message""" | zmq_identity = None
if connection_id is not None and self . _connections is not None :
if connection_id in self . _connections :
connection_info = self . _connections . get ( connection_id )
if connection_info . connection_type == ConnectionType . ZMQ_IDENTITY :
zmq_identity = connection... |
def wget ( url ) :
"""Download the page into a string""" | import urllib . parse
request = urllib . request . urlopen ( url )
filestring = request . read ( )
return filestring |
def print_maps ( map_type = None , number = None ) :
"""Print maps by type and / or number of defined colors .
Parameters
map _ type : { ' Sequential ' , ' Diverging ' , ' Qualitative ' } , optional
Filter output by map type . By default all maps are printed .
number : int , optional
Filter output by numb... | if not map_type and not number :
print_all_maps ( )
elif map_type :
print_maps_by_type ( map_type , number )
else :
s = ( 'Invalid parameter combination. ' 'number without map_type is not supported.' )
raise ValueError ( s ) |
def n4_bias_field_correction ( image , mask = None , shrink_factor = 4 , convergence = { 'iters' : [ 50 , 50 , 50 , 50 ] , 'tol' : 1e-07 } , spline_param = 200 , verbose = False , weight_mask = None ) :
"""N4 Bias Field Correction
ANTsR function : ` n4BiasFieldCorrection `
Arguments
image : ANTsImage
image ... | if image . pixeltype != 'float' :
image = image . clone ( 'float' )
iters = convergence [ 'iters' ]
tol = convergence [ 'tol' ]
if mask is None :
mask = get_mask ( image )
N4_CONVERGENCE_1 = '[%s, %.10f]' % ( 'x' . join ( [ str ( it ) for it in iters ] ) , tol )
N4_SHRINK_FACTOR_1 = str ( shrink_factor )
if ( n... |
def _decrypt_ciphertext ( cipher , translate_newlines = False ) :
'''Given a blob of ciphertext as a bytestring , try to decrypt
the cipher and return the decrypted string . If the cipher cannot be
decrypted , log the error , and return the ciphertext back out .''' | if translate_newlines :
cipher = cipher . replace ( r'\n' , '\n' )
if hasattr ( cipher , 'encode' ) :
cipher = cipher . encode ( __salt_system_encoding__ )
# Decryption
data_key = _base64_plaintext_data_key ( )
plain_text = fernet . Fernet ( data_key ) . decrypt ( cipher )
if hasattr ( plain_text , 'decode' ) :... |
def MI_parse_args ( self , args , ingore_index2 = False , allow_new = False ) :
'''Parse the arguments for indexing in MIDict .
Full syntax : ` ` d [ index1 : key , index2 ] ` ` .
` ` index2 ` ` can be flexible indexing ( int , list , slice etc . ) as in ` ` IndexDict ` ` .
Short syntax :
* d [ key ] < = = ... | empty = len ( self . indices ) == 0
if empty and not allow_new :
raise KeyError ( 'Item not found (dictionary is empty): %s' % ( args , ) )
names = force_list ( self . indices . keys ( ) )
Nargs = len ( args ) if isinstance ( args , tuple ) else 1
_default = object ( )
index1 = index2 = _default
if isinstance ( arg... |
def get ( self , key , default = None ) :
"""Gets @ key from : prop : key _ prefix , defaulting to @ default""" | try :
return self [ key ]
except KeyError :
return default or self . _default |
def frames ( self ) :
"""Retrieve the next frame from the image directory and convert it to a ColorImage ,
a DepthImage , and an IrImage .
Parameters
skip _ registration : bool
If True , the registration step is skipped .
Returns
: obj : ` tuple ` of : obj : ` ColorImage ` , : obj : ` DepthImage ` , : o... | if not self . _running :
raise RuntimeError ( 'VirtualKinect2 device pointing to %s not runnning. Cannot read frames' % ( self . _path_to_images ) )
if self . _im_index > self . _num_images :
raise RuntimeError ( 'VirtualKinect2 device is out of images' )
# read images
color_filename = os . path . join ( self .... |
def validatePrivate ( self , field , value ) :
"""validate a private field value""" | if field not in self . arangoPrivates :
raise ValueError ( "%s is not a private field of collection %s" % ( field , self ) )
if field in self . _fields :
self . _fields [ field ] . validate ( value )
return True |
def clear ( self , exclude = None ) :
"""Remove all elements in the cache .""" | if exclude is None :
self . cache = { }
else :
self . cache = { k : v for k , v in self . cache . items ( ) if k in exclude } |
def xml ( self ) :
"""Serialise the document to XML .
Returns :
lxml . etree . Element
See also :
: meth : ` Document . xmlstring `""" | self . pendingvalidation ( )
E = ElementMaker ( namespace = "http://ilk.uvt.nl/folia" , nsmap = { 'xml' : "http://www.w3.org/XML/1998/namespace" , 'xlink' : "http://www.w3.org/1999/xlink" } )
attribs = { }
attribs [ '{http://www.w3.org/XML/1998/namespace}id' ] = self . id
# if self . version :
# attribs [ ' version ' ]... |
def run ( self ) :
"""Interact with the blockchain peer ,
until we get a socket error or we
exit the loop explicitly .
The order of operations is :
* send version
* receive version
* send verack
* send getdata
* receive blocks
* for each block :
* for each transaction with nulldata :
* for eac... | log . debug ( "Segwit support: {}" . format ( get_features ( 'segwit' ) ) )
self . begin ( )
try :
self . loop ( )
except socket . error , se :
if not self . finished : # unexpected
log . exception ( se )
return False
# fetch remaining sender transactions
try :
self . fetch_sender_txs ( )
ex... |
def uncancel_confirmation ( self , confirmation_id ) :
"""Uncancelles an confirmation
: param confirmation _ id : the confirmation id""" | return self . _create_put_request ( resource = CONFIRMATIONS , billomat_id = confirmation_id , command = UNCANCEL , ) |
def _asynciostacks ( * args , ** kwargs ) : # pragma : no cover
'''A signal handler used to print asyncio task stacks and thread stacks .''' | print ( 80 * '*' )
print ( 'Asyncio tasks stacks:' )
tasks = asyncio . all_tasks ( _glob_loop )
for task in tasks :
task . print_stack ( )
print ( 80 * '*' )
print ( 'Faulthandler stack frames per thread:' )
faulthandler . dump_traceback ( )
print ( 80 * '*' ) |
def _left_hand_total_velocity ( self ) :
"""Returns the total eef velocity ( linear + angular ) in the base frame as a numpy
array of shape ( 6 , )""" | # Use jacobian to translate joint velocities to end effector velocities .
Jp = self . sim . data . get_body_jacp ( "left_hand" ) . reshape ( ( 3 , - 1 ) )
Jp_joint = Jp [ : , self . _ref_joint_vel_indexes [ 7 : ] ]
Jr = self . sim . data . get_body_jacr ( "left_hand" ) . reshape ( ( 3 , - 1 ) )
Jr_joint = Jr [ : , self... |
def process_entry ( self , entry ) :
"""Process a single entry with the chosen Corrections .
Args :
entry : A ComputedEntry object .
Returns :
An adjusted entry if entry is compatible , otherwise None is
returned .""" | try :
corrections = self . get_corrections_dict ( entry )
except CompatibilityError :
return None
entry . correction = sum ( corrections . values ( ) )
return entry |
def getRfree ( self ) :
'''Returns an array of size self . AgentCount with self . Rboro or self . Rsave in each entry , based
on whether self . aNrmNow > < 0.
Parameters
None
Returns
RfreeNow : np . array
Array of size self . AgentCount with risk free interest rate for each agent .''' | RfreeNow = self . Rboro * np . ones ( self . AgentCount )
RfreeNow [ self . aNrmNow > 0 ] = self . Rsave
return RfreeNow |
def laser_detunings ( Lij , Nl , i_d , I_nd , Nnd ) :
r"""This function returns the list of transitions i , j that each laser
produces as lists of length Ne , whose elements are all zero except for the
ith element = 1 and the jth element = - 1.
Also , it returns detuningsij , which contains the same informati... | Ne = len ( Lij )
detunings = [ [ ] for i in range ( Nl ) ]
detuningsij = [ [ ] for i in range ( Nl ) ]
detuning = [ 0 for i in range ( Nnd ) ]
for i in range ( 1 , Ne ) :
for j in range ( i ) :
for l in Lij [ i ] [ j ] :
det = detuning [ : ]
det [ I_nd ( i + 1 ) - 1 ] += 1 ;
... |
def get_assessment_offered_admin_session_for_bank ( self , bank_id , proxy ) :
"""Gets the ` ` OsidSession ` ` associated with the assessment offered admin service for the given bank .
arg : bank _ id ( osid . id . Id ) : the ` ` Id ` ` of the bank
arg : proxy ( osid . proxy . Proxy ) : a proxy
return : ( osi... | if not self . supports_assessment_offered_admin ( ) :
raise errors . Unimplemented ( )
# Also include check to see if the catalog Id is found otherwise raise errors . NotFound
# pylint : disable = no - member
return sessions . AssessmentOfferedAdminSession ( bank_id , proxy , self . _runtime ) |
def _get_url ( self , filename ) :
"""Returns url for cdn . urbanterror . info to pass to _ not _ wget ( ) .
http : / / cdn . urbanterror . info / urt / < major _ ver _ without _ . > / < release _ num > - < magic _ number > / q3ut4 / < filename >""" | return self . cdn_url . format ( self . mver , self . relnum , filename ) |
def to_text ( value , encoding = 'utf-8' ) :
"""Convert value to unicode , default encoding is utf - 8
: param value : Value to be converted
: param encoding : Desired encoding""" | if not value :
return ''
if isinstance ( value , six . text_type ) :
return value
if isinstance ( value , six . binary_type ) :
return value . decode ( encoding )
return six . text_type ( value ) |
def uuid5 ( namespace , name ) :
"""Generate a UUID from the SHA - 1 hash of a namespace UUID and a name .""" | import sha
hash = sha . sha ( namespace . bytes + name ) . digest ( )
return UUID ( bytes = hash [ : 16 ] , version = 5 ) |
def instruction_BGT ( self , opcode , ea ) :
"""Causes a branch if the N ( negative ) bit and V ( overflow ) bit are either
both set or both clear and the Z ( zero ) bit is clear . In other words ,
branch if the sign of a valid twos complement result is , or would be ,
positive and not zero . When used after ... | # Note these variantes are the same :
# not ( ( self . N ^ self . V ) = = 1 or self . Z = = 1)
# not ( ( self . N ^ self . V ) | self . Z )
# self . N = = self . V and self . Z = = 0
if not self . Z and self . N == self . V : # log . info ( " $ % x BGT branch to $ % x , because ( N = = V and Z = = 0 ) \ t | % s " % (
#... |
def update_with ( self , update_fn , * maps ) :
"""Return a new PMap with the items in Mappings maps inserted . If the same key is present in multiple
maps the values will be merged using merge _ fn going from left to right .
> > > from operator import add
> > > m1 = m ( a = 1 , b = 2)
> > > m1 . update _ w... | evolver = self . evolver ( )
for map in maps :
for key , value in map . items ( ) :
evolver . set ( key , update_fn ( evolver [ key ] , value ) if key in evolver else value )
return evolver . persistent ( ) |
def _z2deriv ( self , R , z , phi = 0. , t = 0. ) :
"""NAME :
_ z2deriv
PURPOSE :
evaluate the second vertical derivative for this potential
INPUT :
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT :
the second vertical derivative
HISTORY :
2015-02-13 -... | l , n = bovy_coords . Rz_to_lambdanu ( R , z , ac = self . _ac , Delta = self . _Delta )
jac = bovy_coords . Rz_to_lambdanu_jac ( R , z , Delta = self . _Delta )
hess = bovy_coords . Rz_to_lambdanu_hess ( R , z , Delta = self . _Delta )
dldz = jac [ 0 , 1 ]
dndz = jac [ 1 , 1 ]
d2ldz2 = hess [ 0 , 1 , 1 ]
d2ndz2 = hess... |
def encode_record_with_schema_id ( self , schema_id , record , is_key = False ) :
"""Encode a record with a given schema id . The record must
be a python dictionary .
: param int schema _ id : integer ID
: param dict record : An object to serialize
: param bool is _ key : If the record is a key
: returns ... | serialize_err = KeySerializerError if is_key else ValueSerializerError
# use slow avro
if schema_id not in self . id_to_writers : # get the writer + schema
try :
schema = self . registry_client . get_by_id ( schema_id )
if not schema :
raise serialize_err ( "Schema does not exist" )
... |
def _build_package_finder ( self , options , # type : Values
session , # type : PipSession
platform = None , # type : Optional [ str ]
python_versions = None , # type : Optional [ List [ str ] ]
abi = None , # type : Optional [ str ]
implementation = None # type : Optional [ str ]
) : # type : ( . . . ) - > PackageFind... | index_urls = [ options . index_url ] + options . extra_index_urls
if options . no_index :
logger . debug ( 'Ignoring indexes: %s' , ',' . join ( redact_password_from_url ( url ) for url in index_urls ) , )
index_urls = [ ]
return PackageFinder ( find_links = options . find_links , format_control = options . for... |
def _shared_solvers ( self , others ) :
"""Returns a sequence of the solvers that self and others share .""" | solvers_by_id = { id ( s ) : s for s in self . _solver_list }
common_solvers = set ( solvers_by_id . keys ( ) )
other_sets = [ { id ( s ) for s in cs . _solver_list } for cs in others ]
for o in other_sets :
common_solvers &= o
return [ solvers_by_id [ s ] for s in common_solvers ] |
def _set_fields ( self , fields ) :
"""Set or update the fields value .""" | super ( _BaseHNVModel , self ) . _set_fields ( fields )
if not self . resource_ref :
endpoint = self . _endpoint . format ( resource_id = self . resource_id , parent_id = self . parent_id , grandparent_id = self . grandparent_id )
self . resource_ref = re . sub ( "(/networking/v[0-9]+)" , "" , endpoint ) |
def set_var ( self , name , value , user = None ) :
"""Set a global or user variable
: param name : The name of the variable to set
: type name : str
: param value : The value of the variable to set
: type value : str
: param user : If defining a user variable , the user identifier
: type user : str
:... | # Set a user variable
if user is not None :
if user not in self . _users :
raise UserNotDefinedError
self . _users [ user ] . set_var ( name , value )
return
# Set a global variable
self . _global_vars [ name ] = value |
def entropy ( string ) :
"""Calculate the entropy of a string .""" | entropy = 0
for number in range ( 256 ) :
result = float ( string . encode ( 'utf-8' ) . count ( chr ( number ) ) ) / len ( string . encode ( 'utf-8' ) )
if result != 0 :
entropy = entropy - result * math . log ( result , 2 )
return entropy |
def swap_vowels ( text : str ) -> str :
"""This Python function inverses the vowels within the given string .
Examples :
swap _ vowels ( ' Python ' )
' Python '
swap _ vowels ( ' USA ' )
' ASU '
swap _ vowels ( ' ab ' )
' ab '
Args :
text ( str ) : Input string
Returns :
str : String with reve... | vowels = ''
for character in text :
if character in 'aeiouAEIOU' :
vowels += character
swap_string = ''
for character in text :
if character in 'aeiouAEIOU' :
swap_string += vowels [ - 1 ]
vowels = vowels [ : - 1 ]
else :
swap_string += character
return swap_string |
def main ( ) -> None :
"""Command - line handler for the ` ` find _ bad _ openxml ` ` tool .
Use the ` ` - - help ` ` option for help .""" | parser = ArgumentParser ( formatter_class = RawDescriptionHelpFormatter , description = """
Tool to scan rescued Microsoft Office OpenXML files (produced by the
find_recovered_openxml.py tool in this kit; q.v.) and detect bad (corrupted)
ones.
""" )
parser . add_argument ( "filename" , nargs = "*" , help = "Fil... |
def get_line_bad_footnotes ( line , tag = None , include_tags = None ) :
"""Return [ original _ line , url _ footnote1 , url _ footnote2 , . . . url _ footnoteN ] for N bad footnotes in the line""" | if tag is None or include_tags is None or tag in include_tags or any ( ( tag . startswith ( t ) for t in include_tags ) ) :
found_baddies = re_bad_footnotes . findall ( line )
return [ line ] + [ baddie [ 0 ] for baddie in found_baddies ]
return [ line ] |
def rangeChange ( self , pw , ranges ) :
"""Adjusts the stimulus signal to keep it at the top of a plot ,
after any ajustment to the axes ranges takes place .
This is a slot for the undocumented pyqtgraph signal sigRangeChanged .
From what I can tell the arguments are :
: param pw : reference to the emittin... | if hasattr ( ranges , '__iter__' ) : # adjust the stim signal so that it falls in the correct range
yrange_size = ranges [ 1 ] [ 1 ] - ranges [ 1 ] [ 0 ]
stim_x , stim_y = self . stimPlot . getData ( )
if stim_y is not None :
stim_height = yrange_size * STIM_HEIGHT
# take it to 0
sti... |
def get_config ( ) :
"""Create , populate and return the VersioneerConfig ( ) object .""" | # these strings are filled in when ' setup . py versioneer ' creates
# _ version . py
cfg = VersioneerConfig ( )
cfg . VCS = "git"
cfg . style = "pep440-post"
cfg . tag_prefix = ""
cfg . parentdir_prefix = "None"
cfg . versionfile_source = "canmatrix/_version.py"
cfg . verbose = False
return cfg |
def tee ( process , filter ) :
"""Read lines from process . stdout and echo them to sys . stdout .
Returns a list of lines read . Lines are not newline terminated .
The ' filter ' is a callable which is invoked for every line ,
receiving the line as argument . If the filter returns True , the
line is echoed... | lines = [ ]
while True :
line = process . stdout . readline ( )
if line :
if sys . version_info [ 0 ] >= 3 :
line = decode ( line )
stripped_line = line . rstrip ( )
if filter ( stripped_line ) :
sys . stdout . write ( line )
lines . append ( stripped_line... |
def any ( self , filetype , ** kwargs ) :
'''Checks if the local directory contains any of the type of file
Parameters
filetype : str
File type parameter .
Returns
any : bool
Boolean indicating if the any files exist in the expanded path on disk .''' | expanded_files = self . expand ( filetype , ** kwargs )
return any ( expanded_files ) |
def get_build_logs ( self , build_id , follow = False , build_json = None , wait_if_missing = False , decode = False ) :
"""provide logs from build
NOTE : Since atomic - reactor 1.6.25 , logs are always in UTF - 8 , so if
asked to decode , we assume that is the encoding in use . Otherwise , we
return the byte... | logs = self . os . logs ( build_id , follow = follow , build_json = build_json , wait_if_missing = wait_if_missing )
if decode and isinstance ( logs , GeneratorType ) :
return self . _decode_build_logs_generator ( logs )
# str or None returned from self . os . logs ( )
if decode and logs is not None :
logs = lo... |
def addDeviceNames ( self , remote ) :
"""If XML - API ( http : / / www . homematic - inside . de / software / addons / item / xmlapi ) is installed on CCU this function will add names to CCU devices""" | LOG . debug ( "RPCFunctions.addDeviceNames" )
# First try to get names from metadata when nur credentials are set
if self . remotes [ remote ] [ 'resolvenames' ] == 'metadata' :
for address in self . devices [ remote ] :
try :
name = self . devices [ remote ] [ address ] . _proxy . getMetadata (... |
def close_driver ( self ) :
"""Close current running instance of Webdriver .
Usage : :
driver = WTF _ WEBDRIVER _ MANAGER . new _ driver ( )
driver . get ( " http : / / the - internet . herokuapp . com " )
WTF _ WEBDRIVER _ MANAGER . close _ driver ( )""" | channel = self . __get_channel ( )
driver = self . __get_driver_for_channel ( channel )
if self . __config . get ( self . REUSE_BROWSER , True ) : # If reuse browser is set , we ' ll avoid closing it and just clear out the cookies ,
# and reset the location .
try :
driver . delete_all_cookies ( )
# ... |
def imp_print ( self , text , end ) :
"""Catch UnicodeEncodeError""" | try :
PRINT ( text , end = end )
except UnicodeEncodeError :
for i in text :
try :
PRINT ( i , end = "" )
except UnicodeEncodeError :
PRINT ( "?" , end = "" )
PRINT ( "" , end = end ) |
def add_to_favorites ( current ) :
"""Favorite a message
. . code - block : : python
# request :
' view ' : ' _ zops _ add _ to _ favorites ,
' key ' : key ,
# response :
' status ' : ' Created ' ,
' code ' : 201
' favorite _ key ' : key""" | msg = Message . objects . get ( current . input [ 'key' ] )
current . output = { 'status' : 'Created' , 'code' : 201 }
fav , new = Favorite . objects . get_or_create ( user_id = current . user_id , message = msg )
current . output [ 'favorite_key' ] = fav . key |
def remove_incompatible_items ( first_dict : MutableMapping [ K , V ] , second_dict : Mapping [ K , V ] , compat : Callable [ [ V , V ] , bool ] = equivalent ) -> None :
"""Remove incompatible items from the first dictionary in - place .
Items are retained if their keys are found in both dictionaries and the
va... | for k in list ( first_dict ) :
if k not in second_dict or not compat ( first_dict [ k ] , second_dict [ k ] ) :
del first_dict [ k ] |
def regex_condition ( func ) :
"""If a condition is given as string instead of a function , it is turned
into a regex - matching function .""" | @ wraps ( func )
def regex_condition_wrapper ( condition , * args , ** kwargs ) :
if isinstance ( condition , string_types ) :
condition = maybe | partial ( re . match , condition )
return func ( condition , * args , ** kwargs )
return regex_condition_wrapper |
def phonetic ( s , method , concat = True , encoding = 'utf-8' , decode_error = 'strict' ) :
"""Convert names or strings into phonetic codes .
The implemented algorithms are ` soundex
< https : / / en . wikipedia . org / wiki / Soundex > ` _ , ` nysiis
< https : / / en . wikipedia . org / wiki / New _ York _ ... | # encoding
if sys . version_info [ 0 ] == 2 :
s = s . apply ( lambda x : x . decode ( encoding , decode_error ) if type ( x ) == bytes else x )
if concat :
s = s . str . replace ( r"[\-\_\s]" , "" )
for alg in _phonetic_algorithms :
if method in alg [ 'argument_names' ] :
phonetic_callback = alg [ '... |
def get_facts ( self , date , end_date = None , search_terms = "" , ongoing_days = 0 ) :
"""Returns facts for the time span matching the optional filter criteria .
In search terms comma ( " , " ) translates to boolean OR and space ( " " )
to boolean AND .
Filter is applied to tags , categories , activity name... | facts = [ ]
if ongoing_days : # look for still ongoing activities
earlier_start = date - dt . timedelta ( days = ongoing_days )
earlier_end = date - dt . timedelta ( days = 1 )
earlier_facts = self . _get_facts ( earlier_start , earlier_end , search_terms = search_terms )
facts . extend ( fact for fact ... |
def _is_small_molecule ( pe ) :
"""Return True if the element is a small molecule""" | val = isinstance ( pe , _bp ( 'SmallMolecule' ) ) or isinstance ( pe , _bpimpl ( 'SmallMolecule' ) ) or isinstance ( pe , _bp ( 'SmallMoleculeReference' ) ) or isinstance ( pe , _bpimpl ( 'SmallMoleculeReference' ) )
return val |
def _comports ( ) :
'''Returns
pandas . DataFrame
Table containing descriptor , and hardware ID of each available COM
port , indexed by port ( e . g . , " COM4 " ) .''' | return ( pd . DataFrame ( list ( map ( list , serial . tools . list_ports . comports ( ) ) ) , columns = [ 'port' , 'descriptor' , 'hardware_id' ] ) . set_index ( 'port' ) ) |
def score_url ( self , url ) :
"""Give an url a score which can be used to choose preferred URLs
for a given project release .""" | t = urlparse ( url )
return ( t . scheme != 'https' , 'pypi.python.org' in t . netloc , posixpath . basename ( t . path ) ) |
def get_parent_bin_ids ( self , bin_id ) :
"""Gets the parent ` ` Ids ` ` of the given bin .
arg : bin _ id ( osid . id . Id ) : the ` ` Id ` ` of a bin
return : ( osid . id . IdList ) - the parent ` ` Ids ` ` of the bin
raise : NotFound - ` ` bin _ id ` ` is not found
raise : NullArgument - ` ` bin _ id ` ... | # Implemented from template for
# osid . resource . BinHierarchySession . get _ parent _ bin _ ids
if self . _catalog_session is not None :
return self . _catalog_session . get_parent_catalog_ids ( catalog_id = bin_id )
return self . _hierarchy_session . get_parents ( id_ = bin_id ) |
def register_observer ( self , observer , events = None ) :
"""Register a listener function .
: param observer : external listener function
: param events : tuple or list of relevant events ( default = None )""" | if events is not None and not isinstance ( events , ( tuple , list ) ) :
events = ( events , )
if observer in self . _observers :
LOG . warning ( "Observer '%r' already registered, overwriting for events" " %r" , observer , events )
self . _observers [ observer ] = events |
def _set_blob_metadata ( self , sd , metadata ) : # type : ( SyncCopy , blobxfer . models . synccopy . Descriptor , dict ) - > None
"""Set blob metadata
: param SyncCopy self : this
: param blobxfer . models . synccopy . Descriptor sd : synccopy descriptor
: param dict metadata : metadata dict
: param dict ... | blobxfer . operations . azure . blob . set_blob_metadata ( sd . dst_entity , metadata )
if blobxfer . util . is_not_empty ( sd . dst_entity . replica_targets ) :
for ase in sd . dst_entity . replica_targets :
blobxfer . operations . azure . blob . set_blob_metadata ( ase , metadata ) |
def send_records ( self , records , attempt = 0 ) :
"""Send records to the Kinesis stream .
Falied records are sent again with an exponential backoff decay .
Parameters
records : array
Array of formated records to send .
attempt : int
Number of times the records have been sent without success .""" | # If we already tried more times than we wanted , save to a file
if attempt > self . max_retries :
logger . warning ( 'Writing {} records to file' . format ( len ( records ) ) )
with open ( 'failed_records.dlq' , 'ab' ) as f :
for r in records :
f . write ( r . get ( 'Data' ) )
return
# ... |
def to_string ( interval , conv = repr , disj = ' | ' , sep = ',' , left_open = '(' , left_closed = '[' , right_open = ')' , right_closed = ']' , pinf = '+inf' , ninf = '-inf' ) :
"""Export given interval ( or atomic interval ) to string .
: param interval : an Interval or AtomicInterval instance .
: param conv... | interval = Interval ( interval ) if isinstance ( interval , AtomicInterval ) else interval
if interval . is_empty ( ) :
return '{}{}' . format ( left_open , right_open )
def _convert ( bound ) :
if bound == inf :
return pinf
elif bound == - inf :
return ninf
else :
return conv ( ... |
def time ( name = None ) :
"""Creates the grammar for a Time or Duration ( T ) field , accepting only
numbers in a certain pattern .
: param name : name for the field
: return : grammar for the date field""" | if name is None :
name = 'Time Field'
# Basic field
# This regex allows values from 00000 to 235959
field = pp . Regex ( '(0[0-9]|1[0-9]|2[0-3])[0-5][0-9][0-5][0-9]' )
# Parse action
field . setParseAction ( lambda t : datetime . datetime . strptime ( t [ 0 ] , '%H%M%S' ) . time ( ) )
# White spaces are not removed... |
def code_to_session ( self , js_code ) :
"""登录凭证校验 。 通过 wx . login ( ) 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程 。 更多使用方法详见 小程序登录
详情请参考
https : / / developers . weixin . qq . com / miniprogram / dev / api / code2Session . html
: param js _ code :
: return :""" | return self . _get ( 'sns/jscode2session' , params = { 'appid' : self . appid , 'secret' : self . secret , 'js_code' : js_code , 'grant_type' : 'authorization_code' } ) |
def check_serializable ( cls ) :
"""Throws an exception if Ray cannot serialize this class efficiently .
Args :
cls ( type ) : The class to be serialized .
Raises :
Exception : An exception is raised if Ray cannot serialize this class
efficiently .""" | if is_named_tuple ( cls ) : # This case works .
return
if not hasattr ( cls , "__new__" ) :
print ( "The class {} does not have a '__new__' attribute and is " "probably an old-stye class. Please make it a new-style class " "by inheriting from 'object'." )
raise RayNotDictionarySerializable ( "The class {} d... |
def great_circle_distance ( lon1 , lat1 , lon2 , lat2 ) :
"""Calculate the great circle distance between one or multiple pairs of
points given in spherical coordinates . Spherical coordinates are expected
in degrees . Angle definition follows standard longitude / latitude definition .
This uses the arctan ver... | # Convert to radians :
lat1 = np . array ( lat1 ) * np . pi / 180.0
lat2 = np . array ( lat2 ) * np . pi / 180.0
dlon = ( lon1 - lon2 ) * np . pi / 180.0
# Evaluate trigonometric functions that need to be evaluated more
# than once :
c1 = np . cos ( lat1 )
s1 = np . sin ( lat1 )
c2 = np . cos ( lat2 )
s2 = np . sin ( l... |
def enable_category_lists_editor ( self , request , editor_init_kwargs = None , additional_parents_aliases = None , lists_init_kwargs = None , handler_init_kwargs = None ) :
"""Enables editor functionality for categories of this object .
: param Request request : Django request object
: param dict editor _ init... | from . toolbox import CategoryRequestHandler
additional_parents_aliases = additional_parents_aliases or [ ]
lists_init_kwargs = lists_init_kwargs or { }
editor_init_kwargs = editor_init_kwargs or { }
handler_init_kwargs = handler_init_kwargs or { }
handler = CategoryRequestHandler ( request , self , ** handler_init_kwa... |
def import_keys ( self , keyspec ) :
"""The client needs it ' s own set of keys . It can either dynamically
create them or load them from local storage .
This method can also fetch other entities keys provided the
URL points to a JWKS .
: param keyspec :""" | for where , spec in keyspec . items ( ) :
if where == 'file' :
for typ , files in spec . items ( ) :
if typ == 'rsa' :
for fil in files :
_key = RSAKey ( key = import_private_rsa_key_from_file ( fil ) , use = 'sig' )
_kb = KeyBundle ( )
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.