signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def api_upload ( service , encData , encMeta , keys ) :
'''Uploads data to Send .
Caution ! Data is uploaded as given , this function will not encrypt it for you''' | service += 'api/upload'
files = requests_toolbelt . MultipartEncoder ( fields = { 'file' : ( 'blob' , encData , 'application/octet-stream' ) } )
pbar = progbar ( files . len )
monitor = requests_toolbelt . MultipartEncoderMonitor ( files , lambda files : pbar . update ( monitor . bytes_read - pbar . n ) )
headers = { '... |
def get_git_cleaned_branch_name ( path ) :
"""Get the git branch name of the current HEAD in path . The branch name is
scrubbed to conform to PEP - 440.
PEP - 440 Local version identifiers shall only consist out of :
- ASCII letters ( [ a - zA - Z ] )
- ASCII digits ( [ 0-9 ] )
- periods ( . )
https : /... | # Get name of current branch ( or ' HEAD ' for a detached HEAD )
branch_name = run_cmd ( path , 'git' , 'rev-parse' , '--abbrev-ref' , 'HEAD' )
branch_name = re . sub ( r"[^A-Za-z0-9]+" , "." , branch_name . strip ( ) )
return branch_name |
def put_watch ( self , id , body = None , params = None ) :
"""` < http : / / www . elastic . co / guide / en / elasticsearch / reference / current / watcher - api - put - watch . html > ` _
: arg id : Watch ID
: arg body : The watch
: arg active : Specify whether the watch is in / active by default
: arg i... | if id in SKIP_IN_PATH :
raise ValueError ( "Empty value passed for a required argument 'id'." )
return self . transport . perform_request ( "PUT" , _make_path ( "_watcher" , "watch" , id ) , params = params , body = body ) |
def find_dates ( text , source = False , index = False , strict = False , base_date = None ) :
"""Extract datetime strings from text
: param text :
A string that contains one or more natural language or literal
datetime strings
: type text : str | unicode
: param source :
Return the original string segm... | date_finder = DateFinder ( base_date = base_date )
return date_finder . find_dates ( text , source = source , index = index , strict = strict ) |
def TeArraySizeCheck ( self ) :
"""Checks that Te and q0 array sizes are compatible
For finite difference solution .""" | # Only if they are both defined and are arrays
# Both being arrays is a possible bug in this check routine that I have
# intentionally introduced
if type ( self . Te ) == np . ndarray and type ( self . qs ) == np . ndarray : # Doesn ' t touch non - arrays or 1D arrays
if type ( self . Te ) is np . ndarray :
... |
def assembly ( self , value ) :
"""The assembly property .
Args :
value ( string ) . the property value .""" | if value == self . _defaults [ 'assembly' ] and 'assembly' in self . _values :
del self . _values [ 'assembly' ]
else :
self . _values [ 'assembly' ] = value |
def weighted_pairwise_distances ( X , w , metric = 'euclidean' , w_pow = 0.5 ) :
r"""Given a feature matrix ` ` X ` ` with weights ` ` w ` ` , calculates the modified
distance metric : math : ` \ tilde { d } ( p , q ) = d ( p , q ) / ( w ( p ) w ( q ) N ^ 2 ) ^ p ` , where
: math : ` N ` is the length of ` ` X ... | if sklearn is None :
raise ImportError ( "This function requires scikit-learn." )
base_metric = sklearn . metrics . pairwise . pairwise_distances ( X , metric = metric )
N = w . shape [ 0 ]
w_matrix = outer_product ( w ) * N ** 2
return base_metric / ( w_matrix ** w_pow ) |
def get_path_type ( path_ ) :
r"""returns if a path is a file , directory , link , or mount""" | path_type = ''
if isfile ( path_ ) :
path_type += 'file'
if isdir ( path_ ) :
path_type += 'directory'
if islink ( path_ ) :
path_type += 'link'
if ismount ( path_ ) :
path_type += 'mount'
return path_type |
def topic_subscribers_data_message ( self , topic_name = None , condition = None , collapse_key = None , delay_while_idle = False , time_to_live = None , restricted_package_name = None , low_priority = False , dry_run = False , data_message = None , content_available = None , timeout = 5 , extra_notification_kwargs = N... | if extra_kwargs is None :
extra_kwargs = { }
payload = self . parse_payload ( topic_name = topic_name , condition = condition , collapse_key = collapse_key , delay_while_idle = delay_while_idle , time_to_live = time_to_live , restricted_package_name = restricted_package_name , low_priority = low_priority , dry_run ... |
def register_incoming_conn ( self , conn ) :
"""Add incoming connection into the heap .""" | assert conn , "conn is required"
conn . set_outbound_pending_change_callback ( self . _on_conn_change )
self . connections . appendleft ( conn )
self . _set_on_close_cb ( conn )
self . _on_conn_change ( ) |
def fetch_file ( self , in_path , out_path ) :
'''save a remote file to the specified path''' | vvv ( "FETCH %s TO %s" % ( in_path , out_path ) , host = self . host )
data = dict ( mode = 'fetch' , in_path = in_path )
data = utils . jsonify ( data )
data = utils . encrypt ( self . key , data )
self . socket . send ( data )
response = self . socket . recv ( )
response = utils . decrypt ( self . key , response )
re... |
def extract_subsection ( im , shape ) :
r"""Extracts the middle section of a image
Parameters
im : ND - array
Image from which to extract the subsection
shape : array _ like
Can either specify the size of the extracted section or the fractional
size of the image to extact .
Returns
image : ND - arra... | # Check if shape was given as a fraction
shape = sp . array ( shape )
if shape [ 0 ] < 1 :
shape = sp . array ( im . shape ) * shape
center = sp . array ( im . shape ) / 2
s_im = [ ]
for dim in range ( im . ndim ) :
r = shape [ dim ] / 2
lower_im = sp . amax ( ( center [ dim ] - r , 0 ) )
upper_im = sp ... |
def get_content_type ( self , content_type ) :
"""Get all the items of the given content type related to this item .""" | qs = self . get_queryset ( )
return qs . filter ( content_type__name = content_type ) |
def err_response ( reqid , code , msg , data = None ) :
"""Formats a JSON - RPC error as a dict with keys : ' jsonrpc ' , ' id ' , ' error '""" | err = { "code" : code , "message" : msg }
if data :
err [ "data" ] = data
return { "jsonrpc" : "2.0" , "id" : reqid , "error" : err } |
def __check_msg_for_headers ( self , msg , ** email_headers ) :
"""Checks an Email . Message object for the headers in email _ headers .
Following are acceptable header names : [ ' Delivered - To ' ,
' Received ' , ' Return - Path ' , ' Received - SPF ' ,
' Authentication - Results ' , ' DKIM - Signature ' , ... | all_headers_found = False
email_headers [ 'Delivered-To' ] = email_headers [ 'To' ]
email_headers . pop ( 'To' )
all_headers_found = all ( k in msg . keys ( ) for k in email_headers )
return all_headers_found |
def fire_lifecycle_event ( self , new_state ) :
"""Called when instance ' s state changes .
: param new _ state : ( Lifecycle State ) , the new state of the instance .""" | if new_state == LIFECYCLE_STATE_SHUTTING_DOWN :
self . is_live = False
self . state = new_state
self . logger . info ( self . _git_info + "HazelcastClient is %s" , new_state , extra = self . _logger_extras )
for listener in list ( self . _listeners . values ( ) ) :
try :
listener ( new_state )
excep... |
def error ( self , msg ) :
'''Raise a ConfigParseError at the current input position''' | if self . finished ( ) :
raise ConfigParseError ( "Unexpected end of input; %s" % ( msg , ) )
else :
t = self . peek ( )
raise ConfigParseError ( "Unexpected token %s; %s" % ( t , msg ) ) |
def query ( self , sql , * args , ** kwargs ) :
"""Executes an SQL SELECT query and returns rows generator .
: param sql : query to execute
: param args : parameters iterable
: param kwargs : parameters iterable
: return : rows generator
: rtype : generator""" | with self . locked ( ) as conn :
for row in conn . query ( sql , * args , ** kwargs ) :
yield row |
def get_user_details ( self , response ) :
"""Complete with additional information from environment , as available .""" | result = { 'username' : response [ self . ENV_USERNAME ] , 'email' : response . get ( self . ENV_EMAIL , None ) , 'first_name' : response . get ( self . ENV_FIRST_NAME , None ) , 'last_name' : response . get ( self . ENV_LAST_NAME , None ) }
if result [ 'first_name' ] and result [ 'last_name' ] :
result [ 'fullname... |
def save ( self ) :
"""Send this object ' s mutable values to the server in a PUT request""" | resp = self . _client . put ( type ( self ) . api_endpoint , model = self , data = self . _serialize ( ) )
if 'error' in resp :
return False
return True |
def get_course_list_name ( curriculum_abbr , course_number , section_id , quarter , year , joint = False ) :
"""Return the list address of UW course email list""" | prefix = "multi_" if ( joint is True ) else ""
return COURSE_LIST_NAME . format ( prefix = prefix , curr_abbr = _get_list_name_curr_abbr ( curriculum_abbr ) , course_no = course_number , section_id = section_id . lower ( ) , quarter = quarter . lower ( ) [ : 2 ] , year = str ( year ) [ - 2 : ] ) |
def ccifrm ( frclss , clssid , lenout = _default_len_out ) :
"""Return the frame name , frame ID , and center associated with
a given frame class and class ID .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / ccifrm _ c . html
: param frclss : Class of frame .
: type frclss :... | frclss = ctypes . c_int ( frclss )
clssid = ctypes . c_int ( clssid )
lenout = ctypes . c_int ( lenout )
frcode = ctypes . c_int ( )
frname = stypes . stringToCharP ( lenout )
center = ctypes . c_int ( )
found = ctypes . c_int ( )
libspice . ccifrm_c ( frclss , clssid , lenout , ctypes . byref ( frcode ) , frname , cty... |
def _generate_move ( cls , char , width = None , fill_char = None , bounce = False , reverse = True , back_char = None ) :
"""Yields strings that simulate movement of a character from left
to right . For use with ` BarSet . from _ char ` .
Arguments :
char : Character to move across the progress bar .
width... | width = width or cls . default_width
char = str ( char )
filler = str ( fill_char or cls . default_fill_char ) * ( width - len ( char ) )
rangeargs = RangeMoveArgs ( ( 0 , width , 1 ) , ( width , 0 , - 1 ) , )
if reverse : # Reverse the arguments for range to start from the right .
# Not using swap , because the stoppi... |
def load_version ( filename = 'fuzzyhashlib/version.py' ) :
"""Parse a _ _ version _ _ number from a source file""" | with open ( filename ) as source :
text = source . read ( )
match = re . search ( r"^__version__ = ['\"]([^'\"]*)['\"]" , text )
if not match :
msg = "Unable to find version number in {}" . format ( filename )
raise RuntimeError ( msg )
version = match . group ( 1 )
return version |
def get_selected_state ( self ) :
"""Returns the current selected state""" | form_key = "{}_review_state" . format ( self . form_id )
return self . request . get ( form_key , "default" ) |
def _process_items ( items , user_conf , error_protocol ) :
"""Parse metadata . Remove processed and sucessfully parsed items .
Returns sucessfully processed items .""" | def process_meta ( item , error_protocol ) :
try :
return item . _parse ( )
except Exception , e :
error_protocol . append ( "Can't parse %s: %s" % ( item . _get_filenames ( ) [ 0 ] , e . message ) )
if isinstance ( item , DataPair ) :
return item . ebook_file
# process all i... |
def __load_omitted_parcov ( self ) :
"""private : set the omitted _ parcov attribute""" | if self . omitted_parcov_arg is None and self . omitted_par_arg is None :
raise Exception ( "ErrVar.__load_omitted_parcov: " + "both omitted args are None" )
# try to set omitted _ parcov by extracting from base parcov
if self . omitted_parcov_arg is None and self . omitted_par_arg is not None : # check to see if o... |
def _update_solution_data ( self , s ) :
"""Returns the voltage angle and generator set - point vectors .""" | x = s [ "x" ]
# Va _ var = self . om . get _ var ( " Va " )
# Vm _ var = self . om . get _ var ( " Vm " )
# Pg _ var = self . om . get _ var ( " Pg " )
# Qg _ var = self . om . get _ var ( " Qg " )
Va = x [ self . _Va . i1 : self . _Va . iN + 1 ]
Vm = x [ self . _Vm . i1 : self . _Vm . iN + 1 ]
Pg = x [ self . _Pg . i1... |
def _get_method ( self , rdata ) :
"""Returns jsonrpc request ' s method value .
InvalidRequestError will be raised if it ' s missing or is wrong type .
MethodNotFoundError will be raised if a method with given method name
does not exist .""" | if 'method' in rdata :
if not isinstance ( rdata [ 'method' ] , basestring ) :
raise InvalidRequestError
else :
raise InvalidRequestError
if rdata [ 'method' ] not in self . method_data . keys ( ) :
raise MethodNotFoundError
return rdata [ 'method' ] |
def do_get_acls ( self , params ) :
"""\x1b [1mNAME \x1b [0m
get _ acls - Gets ACLs for a given path
\x1b [1mSYNOPSIS \x1b [0m
get _ acls < path > [ depth ] [ ephemerals ]
\x1b [1mOPTIONS \x1b [0m
* depth : - 1 is no recursion , 0 is infinite recursion , N > 0 is up to N levels ( default : 0)
* ephemera... | def replace ( plist , oldv , newv ) :
try :
plist . remove ( oldv )
plist . insert ( 0 , newv )
except ValueError :
pass
for path , acls in self . _zk . get_acls_recursive ( params . path , params . depth , params . ephemerals ) :
replace ( acls , READ_ACL_UNSAFE [ 0 ] , "WORLD_READ"... |
def slugify_argument ( func ) :
"""Wraps a function that returns a string , adding the ' slugify ' argument .
> > > slugified _ fn = slugify _ argument ( lambda * args , * * kwargs : " YOU ARE A NICE LADY " )
> > > slugified _ fn ( )
' YOU ARE A NICE LADY '
> > > slugified _ fn ( slugify = True )
' you - ... | @ six . wraps ( func )
def wrapped ( * args , ** kwargs ) :
if "slugify" in kwargs and kwargs [ 'slugify' ] :
return _slugify ( func ( * args , ** kwargs ) )
else :
return func ( * args , ** kwargs )
return wrapped |
def split_linear_constraints ( A , l , u ) :
"""Returns the linear equality and inequality constraints .""" | ieq = [ ]
igt = [ ]
ilt = [ ]
ibx = [ ]
for i in range ( len ( l ) ) :
if abs ( u [ i ] - l [ i ] ) <= EPS :
ieq . append ( i )
elif ( u [ i ] > 1e10 ) and ( l [ i ] > - 1e10 ) :
igt . append ( i )
elif ( l [ i ] <= - 1e10 ) and ( u [ i ] < 1e10 ) :
ilt . append ( i )
elif ( abs ... |
def epochs ( self ) :
"""Get epochs as generator
Returns
list of dict
each epoch is defined by start _ time and end _ time ( in s in reference
to the start of the recordings ) and a string of the sleep stage ,
and a string of the signal quality .
If you specify stages _ of _ interest , only epochs belon... | if self . rater is None :
raise IndexError ( 'You need to have at least one rater' )
for one_epoch in self . rater . iterfind ( 'stages/epoch' ) :
epoch = { 'start' : int ( one_epoch . find ( 'epoch_start' ) . text ) , 'end' : int ( one_epoch . find ( 'epoch_end' ) . text ) , 'stage' : one_epoch . find ( 'stage... |
def get_filter_rule ( self , _filter , way = 'in' ) :
"""Return the filter rule
: param : _ filter a zobjects . FilterRule or the filter name
: param : way string discribing if filter is for ' in ' or ' out ' messages
: returns : a zobjects . FilterRule""" | if isinstance ( _filter , zobjects . FilterRule ) :
_filter = _filter . name
for f in self . get_filter_rules ( way = way ) :
if f . name == _filter :
return f
return None |
def write ( self , f , grp , name , data , type_string , options ) :
"""Writes an object ' s metadata to file .
Writes the Python object ' data ' to ' name ' in h5py . Group ' grp ' .
. . versionchanged : : 0.2
Arguements changed .
Parameters
f : h5py . File
The HDF5 file handle that is open .
grp : h... | raise NotImplementedError ( 'Can' 't write data type: ' + str ( type ( data ) ) ) |
def save ( self , parameterstep = None , simulationstep = None ) :
"""Save all defined auxiliary control files .
The target path is taken from the | ControlManager | object stored
in module | pub | . Hence we initialize one and override its
| property | ` currentpath ` with a simple | str | object defining th... | par = parametertools . Parameter
for ( modelname , var2aux ) in self :
for filename in var2aux . filenames :
with par . parameterstep ( parameterstep ) , par . simulationstep ( simulationstep ) :
lines = [ parametertools . get_controlfileheader ( modelname , parameterstep , simulationstep ) ]
... |
def request_examples ( self , attack_config , criteria , run_counts , batch_size ) :
"""Returns a numpy array of integer example indices to run in the next batch .""" | raise NotImplementedError ( str ( type ( self ) ) + "needs to implement request_examples" ) |
def _bar ( self , target_name , current , total ) :
"""Make a progress bar out of info , which looks like :
(1/2 ) : [ # # # # # ] 100 % master . zip""" | bar_len = 30
if total is None :
state = 0
percent = "?% "
else :
total = int ( total )
state = int ( ( 100 * current ) / total ) if current < total else 100
percent = str ( state ) + "% "
if self . _n_total > 1 :
num = "({}/{}): " . format ( self . _n_finished + 1 , self . _n_total )
else :
... |
def after_epoch ( self , epoch_id : int , epoch_data : EpochData ) -> None :
"""Call : py : meth : ` _ on _ plateau _ action ` if the ` ` long _ term ` `
variable mean is lower / greater than the ` ` short _ term ` ` mean .""" | super ( ) . after_epoch ( epoch_id = epoch_id , epoch_data = epoch_data )
self . _saved_loss . append ( epoch_data [ self . _stream ] [ self . _variable ] [ OnPlateau . _AGGREGATION ] )
long_mean = np . mean ( self . _saved_loss [ - self . _long_term : ] )
short_mean = np . mean ( self . _saved_loss [ - self . _short_t... |
def detachPanel ( self ) :
"""Detaches the current panel as a floating window .""" | from projexui . widgets . xviewwidget import XViewDialog
dlg = XViewDialog ( self . _viewWidget , self . _viewWidget . viewTypes ( ) )
size = self . _currentPanel . size ( )
dlg . viewWidget ( ) . currentPanel ( ) . snagViewFromPanel ( self . _currentPanel )
dlg . resize ( size )
dlg . show ( ) |
def present ( name , running = None , clone_from = None , snapshot = False , profile = None , network_profile = None , template = None , options = None , image = None , config = None , fstype = None , size = None , backing = None , vgname = None , lvname = None , thinpool = None , path = None ) :
'''. . versionchan... | ret = { 'name' : name , 'result' : True , 'comment' : 'Container \'{0}\' already exists' . format ( name ) , 'changes' : { } }
if not any ( ( template , image , clone_from ) ) : # Take a peek into the profile to see if there is a clone source there .
# Otherwise , we ' re assuming this is a template / image creation . ... |
def parse_combo ( self , combo , modes_set , modifiers_set , pfx ) :
"""Parse a string into a mode , a set of modifiers and a trigger .""" | mode , mods , trigger = None , set ( [ ] ) , combo
if '+' in combo :
if combo . endswith ( '+' ) : # special case : probably contains the keystroke ' + '
trigger , combo = '+' , combo [ : - 1 ]
if '+' in combo :
items = set ( combo . split ( '+' ) )
else :
items = set... |
def fix_nonref_positions ( in_file , ref_file ) :
"""Fix Genotyping VCF positions where the bases are all variants .
The plink / pseq output does not handle these correctly , and
has all reference / variant bases reversed .""" | ignore_chrs = [ "." ]
ref2bit = twobit . TwoBitFile ( open ( ref_file ) )
out_file = in_file . replace ( "-raw.vcf" , ".vcf" )
with open ( in_file ) as in_handle :
with open ( out_file , "w" ) as out_handle :
for line in in_handle :
if line . startswith ( "#" ) :
out_handle . wri... |
def bbox_vert_aligned_center ( box1 , box2 ) :
"""Returns true if the center of both boxes is within 5 pts""" | if not ( box1 and box2 ) :
return False
return abs ( ( ( box1 . right + box1 . left ) / 2.0 ) - ( ( box2 . right + box2 . left ) / 2.0 ) ) <= 5 |
def context ( self , context ) :
"""Sets the context that Selenium commands are running in using
a ` with ` statement . The state of the context on the server is
saved before entering the block , and restored upon exiting it .
: param context : Context , may be one of the class properties
` CONTEXT _ CHROME... | initial_context = self . execute ( 'GET_CONTEXT' ) . pop ( 'value' )
self . set_context ( context )
try :
yield
finally :
self . set_context ( initial_context ) |
def register ( self , type_ , handler ) :
"""注册事件处理函数监听""" | # 尝试获取该事件类型对应的处理函数列表 , 若无defaultDict会自动创建新的list
handlerList = self . __handlers [ type_ ]
# 若要注册的处理器不在该事件的处理器列表中 , 则注册该事件
if handler not in handlerList :
handlerList . append ( handler ) |
def _getter ( self ) :
"""Return a function object suitable for the " get " side of the property
descriptor . This default getter returns the child element with
matching tag name or | None | if not present .""" | def get_child_element ( obj ) :
return obj . find ( qn ( self . _nsptagname ) )
get_child_element . __doc__ = ( '``<%s>`` child element or |None| if not present.' % self . _nsptagname )
return get_child_element |
def verify ( cls , user_id , verification_hash ) :
"""Verify a user using the verification hash
The verification hash is removed from the user once verified
: param user _ id : the user ID
: param verification _ hash : the verification hash
: returns : a User instance""" | user = yield cls . get ( user_id )
# If user does not have verification hash then this means they have already been verified
if 'verification_hash' not in user . _resource :
raise Return ( user )
if user . verification_hash != verification_hash :
raise exceptions . ValidationError ( 'Invalid verification hash' ... |
def ceafe ( clusters , gold_clusters ) :
"""Computes the Constrained EntityAlignment F - Measure ( CEAF ) for evaluating coreference .
Gold and predicted mentions are aligned into clusterings which maximise a metric - in
this case , the F measure between gold and predicted clusters .
< https : / / www . seman... | clusters = [ cluster for cluster in clusters if len ( cluster ) != 1 ]
scores = np . zeros ( ( len ( gold_clusters ) , len ( clusters ) ) )
for i , gold_cluster in enumerate ( gold_clusters ) :
for j , cluster in enumerate ( clusters ) :
scores [ i , j ] = Scorer . phi4 ( gold_cluster , cluster )
matching =... |
def reduced_matrix_element ( fine_statei , fine_statej , convention = 1 ) :
r"""Return the reduced matrix element of the position operator in Bohr \
radii .
We have two available conventions for this
1 . - [ Racah ] _ and [ Edmonds74 ] _
. . math : :
\ langle \ gamma _ i , J _ i , M _ i | \ hat { T } ^ k ... | if fine_statei == fine_statej :
return 0.0
t = Transition ( fine_statei , fine_statej )
einsteinAij = t . einsteinA
omega0 = t . omega
Ji = fine_statei . j ;
Jj = fine_statej . j
factor = sqrt ( 3 * Pi * hbar * c ** 3 * epsilon0 ) / e
if omega0 < 0 :
rij = factor * sqrt ( ( 2 * Jj + 1 ) * einsteinAij / omega0 *... |
def IterAssociatorInstances ( self , InstanceName , AssocClass = None , ResultClass = None , Role = None , ResultRole = None , IncludeQualifiers = None , IncludeClassOrigin = None , PropertyList = None , FilterQueryLanguage = None , FilterQuery = None , OperationTimeout = None , ContinueOnError = None , MaxObjectCount ... | # noqa : E501
# Must be positive integer gt zero
_validateIterCommonParams ( MaxObjectCount , OperationTimeout )
# Common variable for pull result tuple used by pulls and finally :
pull_result = None
try : # try / finally block to allow iter . close ( )
if ( self . _use_assoc_inst_pull_operations is None or self . ... |
def verify_cot_signatures ( chain ) :
"""Verify the signatures of the chain of trust artifacts populated in ` ` download _ cot ` ` .
Populate each link . cot with the chain of trust json body .
Args :
chain ( ChainOfTrust ) : the chain of trust to add to .
Raises :
CoTError : on failure .""" | for link in chain . links :
unsigned_path = link . get_artifact_full_path ( 'public/chain-of-trust.json' )
ed25519_signature_path = link . get_artifact_full_path ( 'public/chain-of-trust.json.sig' )
verify_link_ed25519_cot_signature ( chain , link , unsigned_path , ed25519_signature_path ) |
def savestate ( self , state , chain = - 1 ) :
"""Store a dictionnary containing the state of the Model and its
StepMethods .""" | cur_chain = self . _chains [ chain ]
if hasattr ( cur_chain , '_state_' ) :
cur_chain . _state_ [ 0 ] = state
else :
s = self . _h5file . create_vlarray ( cur_chain , '_state_' , tables . ObjectAtom ( ) , title = 'The saved state of the sampler' , filters = self . filter )
s . append ( state )
self . _h5fil... |
def clean_add_strdec ( * args , prec = 28 ) :
"""add two columns that contain numbers as strings""" | # load modules
import pandas as pd
import numpy as np
import re
from decimal import Decimal , getcontext
getcontext ( ) . prec = prec
# initialize result as 0.0
def proc_elem ( * args ) :
t = Decimal ( '0.0' )
for a in args :
if isinstance ( a , str ) :
a = re . sub ( '[^0-9\.\-]+' , '' , a ... |
def sendcmd ( self , cmd = 'AT' , timeout = 1.0 ) :
"""send command , wait for response . returns response from modem .""" | import time
if self . write ( cmd ) :
while self . get_response ( ) == '' and timeout > 0 :
time . sleep ( 0.1 )
timeout -= 0.1
return self . get_lines ( ) |
def get_term_category_frequencies ( self , scatterchartdata ) :
'''Parameters
scatterchartdata : ScatterChartData
Returns
pd . DataFrame''' | df = self . term_category_freq_df . rename ( columns = { c : c + ' freq' for c in self . term_category_freq_df } )
df . index . name = 'term'
return df |
def append ( self , state , symbol , action , destinationstate , production = None ) :
"""Appends a new rule""" | if action not in ( None , "Accept" , "Shift" , "Reduce" ) :
raise TypeError
rule = { "action" : action , "dest" : destinationstate }
if action == "Reduce" :
if rule is None :
raise TypeError ( "Expected production parameter" )
rule [ "rule" ] = production
while isinstance ( symbol , TerminalSymbol )... |
def create_random ( cls , length , ** kwargs ) :
"""Return a new instance of this gene class with random DNA ,
with characters chosen from ` ` GENETIC _ MATERIAL _ OPTIONS ` ` .
length : the number of characters in the randomized DNA
* * kwargs : forwarded to the ` ` cls ` ` constructor""" | dna = '' . join ( [ random . choice ( cls . GENETIC_MATERIAL_OPTIONS ) for _ in range ( length ) ] )
return cls ( dna , ** kwargs ) |
def _dispatch_command ( reactor , cfg , command ) :
"""Internal helper . This calls the given command ( a no - argument
callable ) with the Config instance in cfg and interprets any
errors for the user .""" | cfg . timing . add ( "command dispatch" )
cfg . timing . add ( "import" , when = start , which = "top" ) . finish ( when = top_import_finish )
try :
yield maybeDeferred ( command )
except ( WrongPasswordError , NoTorError ) as e :
msg = fill ( "ERROR: " + dedent ( e . __doc__ ) )
print ( msg , file = cfg . ... |
def reversed ( self ) :
"""returns a copy of the CubicBezier object with its orientation
reversed .""" | new_cub = CubicBezier ( self . end , self . control2 , self . control1 , self . start )
if self . _length_info [ 'length' ] :
new_cub . _length_info = self . _length_info
new_cub . _length_info [ 'bpoints' ] = ( self . end , self . control2 , self . control1 , self . start )
return new_cub |
def get_scheduling_block ( sub_array_id , block_id ) :
"""Return the list of scheduling blocks instances associated with the sub
array""" | block_ids = DB . get_sub_array_sbi_ids ( sub_array_id )
if block_id in block_ids :
block = DB . get_block_details ( [ block_id ] ) . __next__ ( )
return block , HTTPStatus . OK
return dict ( error = "unknown id" ) , HTTPStatus . NOT_FOUND |
def _convert_content ( self , rdtype , content ) :
"""Converts type dependent record content into well formed and fully qualified
content for domain zone and returns content .""" | if rdtype == 'TXT' :
if content [ 0 ] != '"' :
content = '"' + content
if content [ - 1 ] != '"' :
content += '"'
if rdtype in ( 'CNAME' , 'MX' , 'NS' , 'SRV' ) :
if content [ - 1 ] != '.' :
content = self . _fqdn_name ( content )
return content |
def make_unique_endings ( strings_collection ) :
"""Make each string in the collection end with a unique character .
Essential for correct builiding of a generalized annotated suffix tree .
Returns the updated strings collection , encoded in Unicode .
max strings _ collection ~ 1.100.000""" | res = [ ]
for i in range ( len ( strings_collection ) ) : # NOTE ( msdubov ) : a trick to handle ' narrow ' python installation issues .
hex_code = hex ( consts . String . UNICODE_SPECIAL_SYMBOLS_START + i )
hex_code = r"\U" + "0" * ( 8 - len ( hex_code ) + 2 ) + hex_code [ 2 : ]
res . append ( strings_coll... |
def _crossover ( self , ind ) :
"""Used by the evolution process to generate a new individual .
Notes
This is a tweaked version of the classical DE crossover
algorithm , the main difference that candidate parameters are
generated using a lognormal distribution . Bound handling is
achieved by resampling wh... | if self . neighbours :
a , b , c = random . sample ( [ self . population [ i ] for i in ind . neighbours ] , 3 )
else :
a , b , c = random . sample ( self . population , 3 )
y = self . toolbox . clone ( a )
y . ident = ind . ident
y . neighbours = ind . neighbours
del y . fitness . values
# y should now be a co... |
def notify ( request ) :
'''This view gets a POST request from the Javascript part of the
AutoreloadPanel that contains a body that looks like : :
template = / full / path / to / template . html & template = / another / template . eml : 123456789&
media = / static / url / to / a / file : 133456780 & media = h... | def get_resources ( names , resource_class ) :
resources = [ ]
for name in names :
timestamp = None
if ':' in name :
name , timestamp = name . split ( ':' , 1 )
try :
timestamp = float ( timestamp )
except ( ValueError , TypeError ) :
... |
def get_backup ( self , id_or_uri ) :
"""Get the details for the backup from an Artifact Bundle .
Args :
id _ or _ uri : ID or URI of the Artifact Bundle .
Returns :
Dict : Backup for an Artifacts Bundle .""" | uri = self . BACKUPS_PATH + '/' + extract_id_from_uri ( id_or_uri )
return self . _client . get ( id_or_uri = uri ) |
def setup_recent_files_menu ( self ) :
"""Setup the recent files menu and manager""" | self . recent_files_manager = widgets . RecentFilesManager ( 'pyQode' , 'notepad' )
self . menu_recents = widgets . MenuRecentFiles ( self . menuFile , title = 'Recents' , recent_files_manager = self . recent_files_manager )
self . menu_recents . open_requested . connect ( self . open_file )
self . menuFile . insertMen... |
def interact_gridsearch_result_images ( show_result_func , cfgdict_list , cfglbl_list , cfgresult_list , score_list = None , fnum = None , figtitle = '' , unpack = False , max_plots = 25 , verbose = True , precision = 3 , scorelbl = 'score' , onclick_func = None ) :
"""helper function for visualizing results of gri... | assert callable ( show_result_func ) , 'NEED FUNCTION GOT: %r' % ( show_result_func , )
import utool as ut
import plottool as pt
from plottool import plot_helpers as ph
from plottool import interact_helpers as ih
if verbose :
print ( 'Plotting gridsearch results figtitle=%r' % ( figtitle , ) )
if score_list is None... |
def get_transactions ( self , date_from : datetime , date_to : datetime ) -> List [ Transaction ] :
"""Returns account transactions""" | assert isinstance ( date_from , datetime )
assert isinstance ( date_to , datetime )
# fix up the parameters as we need datetime
dt_from = Datum ( )
dt_from . from_datetime ( date_from )
dt_from . start_of_day ( )
dt_to = Datum ( )
dt_to . from_datetime ( date_to )
dt_to . end_of_day ( )
query = ( self . book . session ... |
def numeric_function_clean_dataframe ( self , axis ) :
"""Preprocesses numeric functions to clean dataframe and pick numeric indices .
Args :
axis : ' 0 ' if columns and ' 1 ' if rows .
Returns :
Tuple with return value ( if any ) , indices to apply func to & cleaned Manager .""" | result = None
query_compiler = self
# If no numeric columns and over columns , then return empty Series
if not axis and len ( self . index ) == 0 :
result = pandas . Series ( dtype = np . int64 )
nonnumeric = [ col for col , dtype in zip ( self . columns , self . dtypes ) if not is_numeric_dtype ( dtype ) ]
if len ... |
def add ( self , elt ) :
"""Generic function to add objects to the daemon internal lists .
Manage Broks , External commands
: param elt : objects to add
: type elt : alignak . AlignakObject
: return : None""" | if isinstance ( elt , Brok ) : # For brok , we tag the brok with our instance _ id
elt . instance_id = self . instance_id
if elt . type == 'monitoring_log' : # The brok is a monitoring event
with self . events_lock :
self . events . append ( elt )
statsmgr . counter ( 'events' , 1 )
... |
def vm_ip ( cls , vm_id ) :
"""Return the first usable ip address for this vm .
Returns a ( version , ip ) tuple .""" | vm_info = cls . info ( vm_id )
for iface in vm_info [ 'ifaces' ] :
if iface [ 'type' ] == 'private' :
continue
for ip in iface [ 'ips' ] :
return ip [ 'version' ] , ip [ 'ip' ] |
def txn2data ( self , txn : dict ) -> str :
"""Given ledger transaction , return its data json .
: param txn : transaction as dict
: return : transaction data json""" | rv_json = json . dumps ( { } )
if self == Protocol . V_13 :
rv_json = json . dumps ( txn [ 'result' ] . get ( 'data' , { } ) )
else :
rv_json = json . dumps ( ( txn [ 'result' ] . get ( 'data' , { } ) or { } ) . get ( 'txn' , { } ) )
# " data " : null for no such txn
return rv_json |
def p_joinx ( self , t ) : # todo : support join types http : / / www . postgresql . org / docs / 9.4 / static / queries - table - expressions . html # QUERIES - JOIN
"""joinx : fromtable jointype fromtable
| fromtable jointype fromtable kw _ on expression
| fromtable jointype fromtable kw _ using ' ( ' namelis... | if len ( t ) == 4 :
t [ 0 ] = JoinX ( t [ 1 ] , t [ 3 ] , None , t [ 2 ] )
elif len ( t ) == 6 :
t [ 0 ] = JoinX ( t [ 1 ] , t [ 3 ] , t [ 5 ] , t [ 2 ] )
else :
raise NotImplementedError ( 'todo: join .. using' ) |
def editLogSettings ( self , logLevel = "WARNING" , logDir = None , maxLogFileAge = 90 , maxErrorReportsCount = 10 ) :
"""The log settings are for the entire site .
Inputs :
logLevel - Can be one of [ OFF , SEVERE , WARNING , INFO , FINE ,
VERBOSE , DEBUG ] .
logDir - File path to the root of the log direct... | lURL = self . _url + "/settings/edit"
allowed_levels = ( "OFF" , "SEVERE" , "WARNING" , "INFO" , "FINE" , "VERBOSE" , "DEBUG" )
currentSettings = self . logSettings
currentSettings [ "f" ] = "json"
if logLevel . upper ( ) in allowed_levels :
currentSettings [ 'logLevel' ] = logLevel . upper ( )
if logDir is not Non... |
def TypeFactory ( v ) :
"""Ensure ` v ` is a valid Type .
This function is used to convert user - specified types into
internal types for the verification engine . It allows Type
subclasses , Type subclass instances , Python type , and user - defined
classes to be passed . Returns an instance of the type of... | if v is None :
return Nothing ( )
elif issubclass ( type ( v ) , Type ) :
return v
elif issubclass ( v , Type ) :
return v ( )
elif issubclass ( type ( v ) , type ) :
return Generic ( v )
else :
raise InvalidTypeError ( "Invalid type %s" % v ) |
def view ( self , * args , ** kwargs ) :
"""Decorator to automatically apply as _ view decorator and register it .""" | def decorator ( f ) :
kwargs . setdefault ( "view_class" , self . view_class )
return self . add_view ( as_view ( * args , ** kwargs ) ( f ) )
return decorator |
def user_requests ( self , id , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / core / requests # list - requests" | api_path = "/api/v2/users/{id}/requests.json"
api_path = api_path . format ( id = id )
return self . call ( api_path , ** kwargs ) |
def save_module ( self , obj ) :
"""Save a module as an import""" | mod_name = obj . __name__
# If module is successfully found then it is not a dynamically created module
if hasattr ( obj , '__file__' ) :
is_dynamic = False
else :
try :
_find_module ( mod_name )
is_dynamic = False
except ImportError :
is_dynamic = True
self . modules . add ( obj )
i... |
def _wcut ( l , windowsize , stepsize ) :
"""Parameters
l - The length of the input array
windowsize - the size of each window of samples
stepsize - the number of samples to move the window each step
Returns
The length the input array should be so that leftover samples are ignored""" | end = l - windowsize
if l <= windowsize :
return 0 , 0
elif end % stepsize :
l = windowsize + ( ( end // stepsize ) * stepsize )
return l , l - ( windowsize - stepsize ) |
def write_to ( self , group , append = False ) :
"""Write stored features to a given group""" | if self . sparsetodense :
self . data = [ x . todense ( ) if sp . issparse ( x ) else x for x in self . data ]
nframes = sum ( [ d . shape [ 0 ] for d in self . data ] )
dim = self . _group_dim ( group )
feats = np . concatenate ( self . data , axis = 0 )
if append :
nframes_group = group [ self . name ] . shap... |
def delegate ( self , fn , * args , ** kwargs ) :
"""Return the given operation as an asyncio future .""" | callback = functools . partial ( fn , * args , ** kwargs )
coro = self . loop . run_in_executor ( self . subexecutor , callback )
return asyncio . ensure_future ( coro ) |
def strip_key_strings ( pofile ) :
"""Removes all entries in PO which are key strings .
These entries should appear only in messages . po , not in any other po files .""" | newlist = [ entry for entry in pofile if not is_key_string ( entry . msgid ) ]
del pofile [ : ]
pofile += newlist |
def send_data ( self , endpoint = None , ** kwargs ) :
"""Sends data to the API .
This call is similar to ` ` fetch ` ` , but * * sends * * data to the API instead
of retrieving it .
Returned data will appear in the ` ` items ` ` key of the resulting
dictionary .
Sending data * * requires * * that the ` `... | if not endpoint :
raise ValueError ( 'No end point provided.' )
if not self . token :
raise ValueError ( 'A write token has not been set. This is required for all MetaSmoke API routes. This can\n' 'be set by setting the "token" parameter of your SmokeAPI object.' )
self . _endpoint = endpoint
params = { "key" :... |
def log_flush_for_interval ( self , log_type , interval ) :
"""Flush logs for an interval of time .
Args :
log _ type ( str ) : Only documented type is " policies " . This
will be applied by default if nothing is passed .
interval ( str ) : Combination of " Zero " , " One " , " Two " ,
" Three " , " Six "... | if not log_type :
log_type = "policies"
# The XML for the / logflush basic endpoint allows spaces
# instead of " + " , so do a replace here just in case .
interval = interval . replace ( " " , "+" )
flush_url = "{}/{}/interval/{}" . format ( self . url , log_type , interval )
self . jss . delete ( flush_url ) |
def get_commands_from ( self , args ) :
"""We have to code the key names for each depth . This method scans
for each level and returns a list of the command arguments .""" | commands = [ ]
for i in itertools . count ( 0 ) :
try :
commands . append ( getattr ( args , self . arg_label_fmt % i ) )
except AttributeError :
break
return commands |
async def expose ( self , application ) :
""": param application string :
Application holds the placeholder name of the application that must
be exposed .""" | application = self . resolve ( application )
log . info ( 'Exposing %s' , application )
return await self . model . applications [ application ] . expose ( ) |
def channel_names ( self , usecols = None ) :
"""Attempt to extract the channel names from the data
file . Return a list with names . Return None on failed attempt .
usecols : A list with columns to use . If present , the returned
list will include only names for columns requested . It will
align with the c... | # Search from [ rts - 1 ] and up ( last row before data ) . Split respective
# row on datdel . Accept consecutive elements starting with alphas
# character after strip . If the count of elements equals the data count
# on row rts + 1 , accept it as the channel names .
if self . decdel == '.' :
datcnt = self . match... |
def stop_proxying ( self , signal_source , * signal_names , weak_ref = False ) :
""": meth : ` . WSignalProxyProto . stop _ proxying ` implementation""" | callback = self . __callback if weak_ref is False else self . __weak_ref_callback
for signal_name in signal_names :
signal_source . remove_callback ( signal_name , callback ) |
def exception ( # type : ignore
self , msg , * args , exc_info = True , ** kwargs ) -> Task :
"""Convenience method for logging an ERROR with exception information .""" | return self . error ( msg , * args , exc_info = exc_info , ** kwargs ) |
def xpathNextParent ( self , cur ) :
"""Traversal function for the " parent " direction The parent
axis contains the parent of the context node , if there is
one .""" | if cur is None :
cur__o = None
else :
cur__o = cur . _o
ret = libxml2mod . xmlXPathNextParent ( self . _o , cur__o )
if ret is None :
raise xpathError ( 'xmlXPathNextParent() failed' )
__tmp = xmlNode ( _obj = ret )
return __tmp |
def remove_dups ( head ) :
"""Time Complexity : O ( N )
Space Complexity : O ( N )""" | hashset = set ( )
prev = Node ( )
while head :
if head . val in hashset :
prev . next = head . next
else :
hashset . add ( head . val )
prev = head
head = head . next |
def save_session ( self , sid , session , namespace = None ) :
"""Store the user session for a client .
The only difference with the : func : ` socketio . Server . save _ session `
method is that when the ` ` namespace ` ` argument is not given the
namespace associated with the class is used .""" | return self . server . save_session ( sid , session , namespace = namespace or self . namespace ) |
def set_replication_enabled ( status , host = None , core_name = None ) :
'''MASTER ONLY
Sets the master to ignore poll requests from the slaves . Useful when you
don ' t want the slaves replicating during indexing or when clearing the
index .
status : boolean
Sets the replication status to the specified ... | if not _is_master ( ) and _get_none_or_value ( host ) is None :
return _get_return_dict ( False , errors = [ 'Only minions configured as master can run this' ] )
cmd = 'enablereplication' if status else 'disablereplication'
if _get_none_or_value ( core_name ) is None and _check_for_cores ( ) :
ret = _get_return... |
def SRU_Compute_CPU ( activation_type , d , bidirectional = False , scale_x = 1 ) :
"""CPU version of the core SRU computation .
Has the same interface as SRU _ Compute _ GPU ( ) but is a regular Python function
instead of a torch . autograd . Function because we don ' t implement backward ( )
explicitly .""" | def sru_compute_cpu ( u , x , bias , init = None , mask_h = None ) :
bidir = 2 if bidirectional else 1
length = x . size ( 0 ) if x . dim ( ) == 3 else 1
batch = x . size ( - 2 )
k = u . size ( - 1 ) // d // bidir
if mask_h is None :
mask_h = 1
u = u . view ( length , batch , bidir , d ,... |
def serialize_all ( nodes , stream = None , Dumper = Dumper , canonical = None , indent = None , width = None , allow_unicode = None , line_break = None , encoding = None , explicit_start = None , explicit_end = None , version = None , tags = None ) :
"""Serialize a sequence of representation trees into a YAML stre... | getvalue = None
if stream is None :
if encoding is None :
stream = io . StringIO ( )
else :
stream = io . BytesIO ( )
getvalue = stream . getvalue
dumper = Dumper ( stream , canonical = canonical , indent = indent , width = width , allow_unicode = allow_unicode , line_break = line_break , en... |
def _extract_email ( data ) :
"""{ ' elements ' : [ { ' handle ' : ' urn : li : emailAddress : 319371470 ' ,
' handle ~ ' : { ' emailAddress ' : ' raymond . penners @ intenct . nl ' } } ] }""" | ret = ''
elements = data . get ( 'elements' , [ ] )
if len ( elements ) > 0 :
ret = elements [ 0 ] . get ( 'handle~' , { } ) . get ( 'emailAddress' , '' )
return ret |
def migrate ( self , host , port , key , destination_db , timeout , copy = False , replace = False ) :
"""Atomically transfer a key from a source Redis instance to a
destination Redis instance . On success the key is deleted from the
original instance and is guaranteed to exist in the target instance .
The co... | command = [ b'MIGRATE' , host , ascii ( port ) . encode ( 'ascii' ) , key , ascii ( destination_db ) . encode ( 'ascii' ) , ascii ( timeout ) . encode ( 'ascii' ) ]
if copy is True :
command . append ( b'COPY' )
if replace is True :
command . append ( b'REPLACE' )
return self . _execute ( command , b'OK' ) |
def from_xml ( cls , xml_bytes ) :
"""Create an instance of this from XML bytes .
@ param xml _ bytes : C { str } bytes of XML to parse
@ return : an instance of L { MultipartInitiationResponse }""" | root = XML ( xml_bytes )
return cls ( root . findtext ( 'Bucket' ) , root . findtext ( 'Key' ) , root . findtext ( 'UploadId' ) ) |
def standard_program_header ( self , title , length , line = 32768 ) :
"""Generates a standard header block of PROGRAM type""" | self . save_header ( self . HEADER_TYPE_BASIC , title , length , param1 = line , param2 = length ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.