signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def Sign ( verifiable , keypair ) :
"""Sign the ` verifiable ` object with the private key from ` keypair ` .
Args :
verifiable :
keypair ( neocore . KeyPair ) :
Returns :
bool : True if successfully signed . False otherwise .""" | prikey = bytes ( keypair . PrivateKey )
hashdata = verifiable . GetHashData ( )
res = Crypto . Default ( ) . Sign ( hashdata , prikey )
return res |
def hwm93 ( Z , latitude = 0 , longitude = 0 , day = 0 , seconds = 0 , f107 = 150. , f107_avg = 150. , geomagnetic_disturbance_index = 4 ) :
r'''Horizontal Wind Model 1993 , for calculating wind velocity in the
atmosphere as a function of time of year , longitude and latitude , solar
activity and earth ' s geom... | try :
from . optional . hwm93 import gws5
except : # pragma : no cover
raise ImportError ( no_gfortran_error )
slt_hour = seconds / 3600. + longitude / 15.
ans = gws5 ( day , seconds , Z / 1000. , latitude , longitude , slt_hour , f107 , f107_avg , geomagnetic_disturbance_index )
return tuple ( ans . tolist ( )... |
def parse_resultsline ( self , line ) :
"""Parses result lines""" | split_row = [ token . strip ( ) for token in line . split ( '\t' ) ]
if len ( split_row ) == 1 :
self . _currentanalysiskw = split_row [ 0 ]
return 0
# ' Average \ t \ t - - - - - \ t - - - - - \ t - - - - - \ t - - - - - \ t - - - - - \ t \ t - - - - - \ t \ t \ t \ t - - - - - '
elif split_row [ 0 ] == 'Avera... |
def message_user ( self , username , domain , subject , message ) :
"""Currently use send _ message _ chat and discard subject , because headline messages are not stored by
mod _ offline .""" | jid = '%s@%s' % ( username , domain )
if self . api_version <= ( 14 , 7 ) : # TODO : it ' s unclear when send _ message was introduced
command = 'send_message_chat'
args = domain , '%s@%s' % ( username , domain ) , message
else :
command = 'send_message'
args = 'chat' , domain , jid , subject , message
... |
def do_asg ( self , args ) :
"""Go to the specified auto scaling group . asg - h for detailed help""" | parser = CommandArgumentParser ( "asg" )
parser . add_argument ( dest = 'asg' , help = 'asg index or name' ) ;
args = vars ( parser . parse_args ( args ) )
print "loading auto scaling group {}" . format ( args [ 'asg' ] )
try :
index = int ( args [ 'asg' ] )
asgSummary = self . wrappedStack [ 'resourcesByTypeIn... |
def infer_table_schema ( sparql_results_json ) :
"""Infer Table Schema from SPARQL results JSON
SPARQL JSON Results Spec :
https : / / www . w3 . org / TR / 2013 / REC - sparql11 - results - json - 20130321
: param sparql _ results _ json : SPARQL JSON results of a query
: returns : A schema descriptor for ... | if ( 'results' in sparql_results_json and 'bindings' in sparql_results_json [ 'results' ] and len ( sparql_results_json [ 'results' ] [ 'bindings' ] ) > 0 ) : # SQL results include metadata , SPARQL results don ' t
result_metadata = sparql_results_json . get ( 'metadata' , [ ] )
metadata_names = [ item [ 'name'... |
def set ( self , key , val ) :
"""Sets a value in a key .
Args :
key ( str ) : Key for the value .
val : Value to set .
Returns :
Retrieved value .""" | self . _create_file_if_none_exists ( )
with open ( self . filename , 'r+b' ) as file_object :
cache_pickle = pickle . load ( file_object )
cache_pickle [ key ] = val
file_object . seek ( 0 )
pickle . dump ( cache_pickle , file_object ) |
def granular_markings_circular_refs ( instance ) :
"""Ensure that marking definitions do not contain circular references ( ie .
they do not reference themselves in the ` granular _ markings ` property ) .""" | if instance [ 'type' ] != 'marking-definition' :
return
if 'granular_markings' in instance :
for marking in instance [ 'granular_markings' ] :
if 'marking_ref' in marking and marking [ 'marking_ref' ] == instance [ 'id' ] :
yield JSONError ( "`granular_markings` cannot contain any " "referen... |
def teehtml ( table , source = None , encoding = None , errors = 'strict' , caption = None , vrepr = text_type , lineterminator = '\n' , index_header = False , tr_style = None , td_styles = None , truncate = None ) :
"""Return a table that writes rows to a Unicode HTML file as they are
iterated over .""" | source = write_source_from_arg ( source )
return TeeHTMLView ( table , source = source , encoding = encoding , errors = errors , caption = caption , vrepr = vrepr , lineterminator = lineterminator , index_header = index_header , tr_style = tr_style , td_styles = td_styles , truncate = truncate ) |
def do_translate ( parser , token ) :
"""This will mark a string for translation and will
translate the string for the current language .
Usage : :
{ % trans " this is a test " % }
This will mark the string for translation so it will
be pulled out by mark - messages . py into the . po files
and will run... | bits = token . split_contents ( )
if len ( bits ) < 2 :
raise TemplateSyntaxError ( "'%s' takes at least one argument" % bits [ 0 ] )
message_string = parser . compile_filter ( bits [ 1 ] )
remaining = bits [ 2 : ]
noop = False
asvar = None
message_context = None
seen = set ( )
invalid_context = { 'as' , 'noop' }
w... |
def clear_end_date ( self ) :
"""Clears the end date .
raise : NoAccess - ` ` Metadata . isRequired ( ) ` ` or
` ` Metadata . isReadOnly ( ) ` ` is ` ` true ` `
* compliance : mandatory - - This method must be implemented . *""" | if ( self . get_end_date_metadata ( ) . is_read_only ( ) or self . get_end_date_metadata ( ) . is_required ( ) ) :
raise errors . NoAccess ( )
self . _my_map [ 'endDate' ] = self . _mdata [ 'end_date' ] [ 'default_date_time_values' ] [ 0 ] |
def load_js ( abspath , default = dict ( ) , compress = False , enable_verbose = True ) :
"""Load Json from file . If file are not exists , returns ` ` default ` ` .
: param abspath : File path . Use absolute path as much as you can . File
extension has to be ` ` . json ` ` or ` ` . gz ` ` . ( for compressed Js... | abspath = str ( abspath )
# try stringlize
if compress : # check extension name
if os . path . splitext ( abspath ) [ 1 ] != ".gz" :
raise Exception ( "compressed json has to use extension '.gz'!" )
else :
if os . path . splitext ( abspath ) [ 1 ] != ".json" :
raise Exception ( "file extension a... |
async def process_frame ( self , frame ) :
"""Update nodes via frame , usually received by house monitor .""" | if isinstance ( frame , FrameNodeStatePositionChangedNotification ) :
if frame . node_id not in self . pyvlx . nodes :
return
node = self . pyvlx . nodes [ frame . node_id ]
if isinstance ( node , OpeningDevice ) :
node . position = Position ( frame . current_position )
await node . ... |
def register_cffi_externs ( self ) :
"""Registers the @ _ extern _ decl methods with our ffi instance .""" | for field_name , _ in self . _extern_fields . items ( ) :
bound_method = getattr ( self , field_name )
self . _ffi . def_extern ( ) ( bound_method ) |
def init_argparser_optional_advice ( self , argparser , default = [ ] , help = ( 'a comma separated list of packages to retrieve optional ' 'advice from; the provided packages should have registered ' 'the appropriate entry points for setting up the advices for ' 'the toolchain; refer to documentation for the specified... | argparser . add_argument ( '--optional-advice' , default = default , required = False , dest = ADVICE_PACKAGES , action = StoreRequirementList , metavar = '<advice>[,<advice>[...]]' , help = help ) |
def search ( self , session , rdef = None ) :
'''taobao . logistics . address . search 查询卖家地址库
通过此接口查询卖家地址库 ,''' | request = TOPRequest ( 'taobao.logistics.address.search' )
if rdef != None :
request [ 'rdef' ] = rdef
self . create ( self . execute ( request , session ) , fields = [ 'addresses' , ] , models = { 'addresses' : AddressResult } )
return self . addresses |
def remove_neighbours ( self ) :
"""Removes from the MOC instance the HEALPix cells located at its border .
The depth of the HEALPix cells removed is equal to the maximum depth of the MOC instance .
Returns
moc : ` ~ mocpy . moc . MOC `
self minus its HEALPix cells located at its border .""" | # Get the HEALPix cells of the MOC at its max depth
ipix = self . _best_res_pixels ( )
hp = HEALPix ( nside = ( 1 << self . max_order ) , order = 'nested' )
# Extend it to include the max depth neighbor cells .
extend_ipix = AbstractMOC . _neighbour_pixels ( hp , ipix )
# Get only the max depth HEALPix cells lying at t... |
def get_grade_entries_on_date ( self , from_ , to ) :
"""Gets a ` ` GradeEntryList ` ` effective during the entire given date range inclusive but not confined to the date range .
arg : from ( osid . calendaring . DateTime ) : start of date range
arg : to ( osid . calendaring . DateTime ) : end of date range
r... | # Implemented from template for
# osid . relationship . RelationshipLookupSession . get _ relationships _ on _ date
grade_entry_list = [ ]
for grade_entry in self . get_grade_entries ( ) :
if overlap ( from_ , to , grade_entry . start_date , grade_entry . end_date ) :
grade_entry_list . append ( grade_entry... |
def run_kwarg_scan ( ModelClass , model_kwarg_sets , t_output_every , t_upto , force_resume = True , parallel = False ) :
"""Run many models with the same parameters but variable ` field ` .
For each ` val ` in ` vals ` , a new model will be made , and run up to a time .
The output directory is automatically ge... | task_runner = _TaskRunner ( ModelClass , t_output_every , t_upto , force_resume )
run_func ( task_runner , model_kwarg_sets , parallel ) |
def lately ( self , count = 15 ) :
"""Show ` ` count ` ` most - recently modified files by mtime
Yields :
tuple : ( strftime - formatted mtime , self . fpath - relative file path )""" | excludes = '|' . join ( ( '*.pyc' , '*.swp' , '*.bak' , '*~' ) )
cmd = ( '''find . -printf "%%T@ %%p\\n" ''' '''| egrep -v '%s' ''' '''| sort -n ''' '''| tail -n %d''' ) % ( excludes , count )
op = self . sh ( cmd , shell = True )
for l in op . split ( '\n' ) :
l = l . strip ( )
if not l :
continue
... |
def prepare ( self ) :
'''Run the preparation sequence required to start a salt syndic minion .
If sub - classed , don ' t * * ever * * forget to run :
super ( YourSubClass , self ) . prepare ( )''' | super ( Syndic , self ) . prepare ( )
try :
if self . config [ 'verify_env' ] :
verify_env ( [ self . config [ 'pki_dir' ] , self . config [ 'cachedir' ] , self . config [ 'sock_dir' ] , self . config [ 'extension_modules' ] , ] , self . config [ 'user' ] , permissive = self . config [ 'permissive_pki_acces... |
def value_counts ( self , dropna = True ) :
"""Returns a Series containing counts of each category .
Every category will have an entry , even those with a count of 0.
Parameters
dropna : boolean , default True
Don ' t include counts of NaN .
Returns
counts : Series
See Also
Series . value _ counts""... | from pandas import Index , Series
# compute counts on the data with no nans
data = self . _data [ ~ self . _mask ]
value_counts = Index ( data ) . value_counts ( )
array = value_counts . values
# TODO ( extension )
# if we have allow Index to hold an ExtensionArray
# this is easier
index = value_counts . index . astype... |
def getFileDialogFilter ( self ) :
"""Returns a filter that can be used in open file dialogs ,
for example : ' All files ( * ) ; ; Txt ( * . txt ; * . text ) ; ; netCDF ( * . nc ; * . nc4 ) '""" | filters = [ ]
for regRti in self . items :
filters . append ( regRti . getFileDialogFilter ( ) )
return ';;' . join ( filters ) |
def coefficient_between_units ( unit_a , unit_b ) :
"""A helper to get the coefficient between two units .
: param unit _ a : The first unit .
: type unit _ a : safe . definitions . units
: param unit _ b : The second unit .
: type unit _ b : safe . definitions . units
: return : The coefficient between t... | for mapping in unit_mapping :
if unit_a == mapping [ 0 ] and unit_b == mapping [ 1 ] :
return mapping [ 2 ]
if unit_a == mapping [ 1 ] and unit_b == mapping [ 0 ] :
return 1 / mapping [ 2 ]
return None |
def _import ( func ) :
"""Return the namespace path to the function""" | func_name = func . __name__
# from foo . bar import func / / func ( )
# WARNING : May be broken in IPython , in which case the widget will use a fallback
if func_name in globals ( ) :
return func_name
# import foo . bar / / foo . bar . func ( )
module_name = func . __module__
submodules = module_name . split ( '.' ... |
def modify ( self , ** kwargs ) :
"""Modify a contact .
Returns status message
Optional Parameters :
* name - - Contact name
Type : String
* email - - Contact email address
Type : String
* cellphone - - Cellphone number , without the country code part . In
some countries you are supposed to exclude ... | # Warn user about unhandled parameters
for key in kwargs :
if key not in [ 'email' , 'cellphone' , 'countrycode' , 'countryiso' , 'defaultsmsprovider' , 'directtwitter' , 'twitteruser' , 'name' ] :
sys . stderr . write ( "'%s'" % key + ' is not a valid argument ' + 'of <PingdomContact>.modify()\n' )
respons... |
def longestorf ( args ) :
"""% prog longestorf fastafile
Find longest ORF for each sequence in fastafile .""" | p = OptionParser ( longestorf . __doc__ )
p . add_option ( "--ids" , action = "store_true" , help = "Generate table with ORF info [default: %default]" )
opts , args = p . parse_args ( args )
if len ( args ) != 1 :
sys . exit ( not p . print_help ( ) )
fastafile , = args
pf = fastafile . rsplit ( "." , 1 ) [ 0 ]
orf... |
def mock_open ( mock = None , read_data = '' ) :
"""A helper function to create a mock to replace the use of ` open ` . It works
for ` open ` called directly or used as a context manager .
The ` mock ` argument is the mock object to configure . If ` None ` ( the
default ) then a ` MagicMock ` will be created ... | def _readlines_side_effect ( * args , ** kwargs ) :
if handle . readlines . return_value is not None :
return handle . readlines . return_value
return list ( _state [ 0 ] )
def _read_side_effect ( * args , ** kwargs ) :
if handle . read . return_value is not None :
return handle . read . ret... |
def get_method_by_idx ( self , idx ) :
"""Return a specific method by using an index
: param idx : the index of the method
: type idx : int
: rtype : None or an : class : ` EncodedMethod ` object""" | if self . __cached_methods_idx == None :
self . __cached_methods_idx = { }
for i in self . classes . class_def :
for j in i . get_methods ( ) :
self . __cached_methods_idx [ j . get_method_idx ( ) ] = j
try :
return self . __cached_methods_idx [ idx ]
except KeyError :
return None |
def linRegressUsingMasked2dArrays ( xVals , arrays , badMask = None , zeroOffset = False , calcError = False ) :
"""if you have multiple 2d arrays each with position given by
xVals [ array - index ]
and you want to do a linear regression on all cells
but you also might mask different areas in each 2darray
z... | assert arrays . ndim == 3 , 'need multiple 2d arrays'
if badMask is not None :
assert arrays . shape == badMask . shape , 'mask needs to have same shape'
s = arrays . shape
# flatten to create array of 1d arrays :
y = arrays . reshape ( s [ 0 ] , s [ 1 ] * s [ 2 ] ) . astype ( float )
s = s [ 1 : ]
if zeroOffset :
... |
def daily ( location = 'Fresno, CA' , years = 1 , use_cache = True , verbosity = 1 ) :
"""Retrieve weather for the indicated airport code or ' City , ST ' string .
> > > df = daily ( ' Camas , WA ' , verbosity = - 1)
> > > 365 < = len ( df ) < = 365 * 2 + 1
True
Sacramento data has gaps ( airport KMCC ) :
... | this_year = datetime . date . today ( ) . year
if isinstance ( years , ( int , float ) ) : # current ( incomplete ) year doesn ' t count in total number of years
# so 0 would return this calendar year ' s weather data
years = np . arange ( 0 , int ( years ) + 1 )
years = sorted ( years )
if not all ( 1900 <= yr <= ... |
def _CreateComplexTypeFromData ( self , elem_type , type_is_override , data , set_type_attrs ) :
"""Initialize a SOAP element with specific data .
Args :
elem _ type : The type of the element to create .
type _ is _ override : A boolean specifying if the type is being overridden .
data : The data to hydrate... | elem_arguments = dict ( elem_type . elements )
# A post order traversal of the original data , need to instantiate from
# the bottom up .
instantiated_arguments = { k : self . _PackArgumentsHelper ( elem_arguments [ k ] , v , set_type_attrs ) for k , v in data if k != 'xsi_type' }
if set_type_attrs :
found_type_att... |
def _bootstrap_debian ( name , ** kwargs ) :
'''Bootstrap a Debian Linux container''' | version = kwargs . get ( 'version' , False )
if not version :
if __grains__ [ 'os' ] . lower ( ) == 'debian' :
version = __grains__ [ 'osrelease' ]
else :
version = 'stable'
release_blacklist = [ 'hamm' , 'slink' , 'potato' , 'woody' , 'sarge' , 'etch' , 'lenny' , 'squeeze' , 'wheezy' ]
if versi... |
def merge_tree ( initial_config = None , initial_path = None , merge_config = None , merge_path = None , saltenv = 'base' ) :
'''Return the merge tree of the ` ` initial _ config ` ` with the ` ` merge _ config ` ` ,
as a Python dictionary .
initial _ config
The initial configuration sent as text . This argum... | merge_tree = tree ( config = merge_config , path = merge_path , saltenv = saltenv )
initial_tree = tree ( config = initial_config , path = initial_path , saltenv = saltenv )
return salt . utils . dictupdate . merge ( initial_tree , merge_tree ) |
def rebind_calculations ( portal ) :
"""Rebind calculations of active analyses . The analysis Calculation ( an
HistoryAwareField ) cannot resolve DependentServices""" | logger . info ( "Rebinding calculations to analyses ..." )
review_states = [ "sample_due" , "attachment_due" , "sample_received" , "to_be_verified" ]
calcs = { }
brains = api . search ( dict ( portal_type = "Calculation" ) , "bika_setup_catalog" )
for calc in brains :
calc = api . get_object ( calc )
calc . set... |
def kldiv ( p , q , distp = None , distq = None , scale_factor = 1 ) :
"""Computes the Kullback - Leibler divergence between two distributions .
Parameters
p : Matrix
The first probability distribution
q : Matrix
The second probability distribution
distp : fixmat
If p is None , distp is used to comput... | assert q != None or distq != None , "Either q or distq have to be given"
assert p != None or distp != None , "Either p or distp have to be given"
try :
if p == None :
p = compute_fdm ( distp , scale_factor = scale_factor )
if q == None :
q = compute_fdm ( distq , scale_factor = scale_factor )
ex... |
def varintSize ( value ) :
"""Compute the size of a varint value .""" | if value <= 0x7f :
return 1
if value <= 0x3fff :
return 2
if value <= 0x1fffff :
return 3
if value <= 0xfffffff :
return 4
if value <= 0x7ffffffff :
return 5
if value <= 0x3ffffffffff :
return 6
if value <= 0x1ffffffffffff :
return 7
if value <= 0xffffffffffffff :
return 8
if value <= 0x... |
def modify_schema ( self , field_schema ) :
"""Modify field schema .""" | if self . minimum_value :
field_schema [ 'minLength' ] = self . minimum_value
if self . maximum_value :
field_schema [ 'maxLength' ] = self . maximum_value |
def start_span ( self , operation_name = None , child_of = None , references = None , tags = None , start_time = None , ignore_active_span = False ) :
"""Starts and returns a new : class : ` Span ` representing a unit of work .
Starting a root : class : ` Span ` ( a : class : ` Span ` with no causal
references ... | return self . _noop_span |
def str_to_bool ( val ) :
"""Helper function to turn a string representation of " true " into
boolean True .""" | if isinstance ( val , str ) :
val = val . lower ( )
return val in [ "true" , "on" , "yes" , True ] |
def delete_feature_base ( dbpath , set_object , name ) :
"""Generic function which deletes a feature from a database
Parameters
dbpath : string , path to SQLite database file
set _ object : object ( either TestSet or TrainSet ) which is stored in the database
name : string , name of the feature to be delete... | engine = create_engine ( 'sqlite:////' + dbpath )
session_cl = sessionmaker ( bind = engine )
session = session_cl ( )
tmp_object = session . query ( set_object ) . get ( 1 )
if tmp_object . features is not None and name in tmp_object . features :
for i in session . query ( set_object ) . order_by ( set_object . id... |
def create_mapping ( self , mapped_class , configuration = None ) :
"""Creates a new mapping for the given mapped class and representer
configuration .
: param configuration : configuration for the new data element class .
: type configuration : : class : ` RepresenterConfiguration `
: returns : newly creat... | cfg = self . __configuration . copy ( )
if not configuration is None :
cfg . update ( configuration )
provided_ifcs = provided_by ( object . __new__ ( mapped_class ) )
if IMemberResource in provided_ifcs :
base_data_element_class = self . member_data_element_base_class
elif ICollectionResource in provided_ifcs ... |
def delete ( self , url , headers = None , kwargs = None ) :
"""Make a DELETE request .
To make a DELETE request pass , ` ` url ` `
: param url : ` ` str ` `
: param headers : ` ` dict ` `
: param kwargs : ` ` dict ` `""" | return self . _request ( method = 'delete' , url = url , headers = headers , kwargs = kwargs ) |
def create_braintree_gateway ( cls , braintree_gateway , ** kwargs ) :
"""Create BraintreeGateway
Create a new BraintreeGateway
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . create _ braintree _ gateway ( braint... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _create_braintree_gateway_with_http_info ( braintree_gateway , ** kwargs )
else :
( data ) = cls . _create_braintree_gateway_with_http_info ( braintree_gateway , ** kwargs )
return data |
def getTmpFilename ( self , tmp_dir = "/tmp" , prefix = 'tmp' , suffix = '.fasta' , include_class_id = False , result_constructor = FilePath ) :
"""Define Tmp filename to contain . fasta suffix , since pplacer requires
the suffix to be . fasta""" | return super ( Pplacer , self ) . getTmpFilename ( tmp_dir = tmp_dir , prefix = prefix , suffix = suffix , include_class_id = include_class_id , result_constructor = result_constructor ) |
def gen_tx ( self ) :
"""Generate a : class : ` Transaction
< stellar _ base . transaction . Transaction > ` object from the list of
operations contained within this object .
: return : A transaction representing all of the operations that have
been appended to this builder .
: rtype : : class : ` Transac... | if not self . address :
raise StellarAddressInvalidError ( 'Transaction does not have any source address.' )
if self . sequence is None :
raise SequenceError ( 'No sequence is present, maybe not funded?' )
tx = Transaction ( source = self . address , sequence = self . sequence , time_bounds = self . time_bounds... |
def map_psmnrcol_to_quantcol ( quantcols , psmcols , tablefn_map ) :
"""This function yields tuples of table filename , isobaric quant column
and if necessary number - of - PSM column""" | if not psmcols :
for fn in quantcols :
for qcol in quantcols [ fn ] :
yield ( tablefn_map [ fn ] , qcol )
else :
for fn in quantcols :
for qcol , psmcol in zip ( quantcols [ fn ] , psmcols [ fn ] ) :
yield ( tablefn_map [ fn ] , qcol , psmcol ) |
def CheckEmails ( self , checkTypo = False , fillWrong = True ) :
'''Checks Emails in List Wether they are Correct or not''' | self . wrong_emails = [ ]
for email in self . emails :
if self . CheckEmail ( email , checkTypo ) is False :
self . wrong_emails . append ( email ) |
def request_chunked ( self , method , url , body = None , headers = None ) :
"""Alternative to the common request method , which sends the
body with chunked encoding and not as one block""" | headers = HTTPHeaderDict ( headers if headers is not None else { } )
skip_accept_encoding = 'accept-encoding' in headers
skip_host = 'host' in headers
self . putrequest ( method , url , skip_accept_encoding = skip_accept_encoding , skip_host = skip_host )
for header , value in headers . items ( ) :
self . putheader... |
def split_n ( string , seps , reg = False ) :
r"""Split strings into n - dimensional list .
from torequests . utils import split _ n
ss = ' ' ' a b c d e f 1 2 3 4 5 6
a b c d e f 1 2 3 4 5 6
a b c d e f 1 2 3 4 5 6 ' ' '
print ( split _ n ( ss , ( ' \ n ' , ' ' , ' ' ) ) )
# [ [ [ ' a ' , ' b ' , ' c '... | deep = len ( seps )
if not deep :
return string
return [ split_n ( i , seps [ 1 : ] ) for i in _re_split_mixin ( string , seps [ 0 ] , reg = reg ) ] |
def rekey_multi ( self , keys , nonce = None , recovery_key = False ) :
"""Enter multiple recovery key shares to progress the rekey of the Vault .
If the threshold number of recovery key shares is reached , Vault will complete the rekey .
: param keys : Specifies multiple recovery share keys .
: type keys : l... | result = None
for key in keys :
result = self . rekey ( key = key , nonce = nonce , recovery_key = recovery_key , )
if result . get ( 'complete' ) :
break
return result |
def _parse_logging ( log_values : dict , service_config : dict ) :
"""Parse log key .
Args :
log _ values ( dict ) : logging configuration values
service _ config ( dict ) : Service specification""" | for log_key , log_value in log_values . items ( ) :
if 'driver' in log_key :
service_config [ 'log_driver' ] = log_value
if 'options' in log_key :
service_config [ 'log_driver_options' ] = log_value |
def xor_app ( parser , cmd , args ) : # pragma : no cover
"""Xor a value with a key .""" | parser . add_argument ( '-d' , '--dec' , help = 'interpret the key as a decimal integer' , dest = 'type' , action = 'store_const' , const = int )
parser . add_argument ( '-x' , '--hex' , help = 'interpret the key as an hexadecimal integer' , dest = 'type' , action = 'store_const' , const = lambda v : int ( v , 16 ) )
p... |
def GET_did ( self , path_info , did ) :
"""Get a user profile .
Reply the profile on success
Return 404 on failure to load""" | try :
did_info = parse_DID ( did )
assert did_info [ 'name_type' ] in ( 'name' , 'subdomain' )
except Exception as e :
if BLOCKSTACK_DEBUG :
log . exception ( e )
return self . _reply_json ( { 'error' : 'Invalid DID' } , status_code = 400 )
blockstackd_url = get_blockstackd_url ( )
resp = blocks... |
def timing_since ( self , stat , start , sample_rate = 1 ) :
"""Log timing information as the number of microseconds since the provided time float
> > > start = time . time ( )
> > > # do stuff
> > > statsd _ client . timing _ since ( ' some . time ' , start )""" | self . timing ( stat , int ( ( time . time ( ) - start ) * 1000000 ) , sample_rate ) |
def _create_path ( self , * args ) :
"""Create the URL path with the Fred endpoint and given arguments .""" | args = filter ( None , args )
path = self . endpoint + '/' . join ( args )
return path |
def makePalette ( color1 , color2 , N , hsv = True ) :
"""Generate N colors starting from ` color1 ` to ` color2 `
by linear interpolation HSV in or RGB spaces .
: param int N : number of output colors .
: param color1 : first rgb color .
: param color2 : second rgb color .
: param bool hsv : if ` False `... | if hsv :
color1 = rgb2hsv ( color1 )
color2 = rgb2hsv ( color2 )
c1 = np . array ( getColor ( color1 ) )
c2 = np . array ( getColor ( color2 ) )
cols = [ ]
for f in np . linspace ( 0 , 1 , N - 1 , endpoint = True ) :
c = c1 * ( 1 - f ) + c2 * f
if hsv :
c = np . array ( hsv2rgb ( c ) )
cols ... |
def _set_mep_id ( self , v , load = False ) :
"""Setter method for mep _ id , mapped from YANG variable / protocol / cfm / domain _ name / ma _ name / cfm _ ma _ sub _ commands / mep / mep _ id ( uint32)
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ mep _ id is consid... | parent = getattr ( self , "_parent" , None )
if parent is not None and load is False :
raise AttributeError ( "Cannot set keys directly when" + " within an instantiated list" )
if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = Restricted... |
def repo ( name : str , owner : str ) -> snug . Query [ dict ] :
"""a repo lookup by owner and name""" | request = snug . GET ( f'https://api.github.com/repos/{owner}/{name}' )
response = yield request
return json . loads ( response . content ) |
def missing_dependencies ( ) :
"""Return the status of missing dependencies ( if any )""" | missing_deps = [ ]
for dependency in DEPENDENCIES :
if not dependency . check ( ) and not dependency . optional :
missing_deps . append ( dependency )
if missing_deps :
return status ( deps = missing_deps , linesep = '<br>' )
else :
return "" |
def chunk_sequence ( sequence , chunk_length ) :
"""Yield successive n - sized chunks from l .""" | for index in range ( 0 , len ( sequence ) , chunk_length ) :
yield sequence [ index : index + chunk_length ] |
def log_entries_in_range ( entries , start , end ) :
'''filter out entries before start and after end''' | start = _timestamp_from_string ( start )
end = _timestamp_from_string ( end )
for entry in entries :
log_timestamp = entry . get ( 'timestamp' , 0 )
if log_timestamp >= start and log_timestamp <= end :
yield entry |
def generate_parameters ( self , parameter_id ) :
"""Returns a set of trial graph config , as a serializable object .
An example configuration :
` ` ` json
" shared _ id " : [
"4a11b2ef9cb7211590dfe81039b27670 " ,
"370af04de24985e5ea5b3d72b12644c9 " ,
"11f646e9f650f5f3fedc12b6349ec60f " ,
"0604e5350b9... | logger . debug ( 'acquiring lock for param {}' . format ( parameter_id ) )
self . thread_lock . acquire ( )
logger . debug ( 'lock for current thread acquired' )
if not self . population :
logger . debug ( "the len of poplution lower than zero." )
raise Exception ( 'The population is empty' )
pos = - 1
for i in... |
def GetSysFeeAmountByHeight ( self , height ) :
"""Get the system fee for the specified block .
Args :
height ( int ) : block height .
Returns :
int :""" | hash = self . GetBlockHash ( height )
return self . GetSysFeeAmount ( hash ) |
def dragDropFilter ( self ) :
"""Returns a drag and drop filter method . If set , the method should \
accept 2 arguments : a QWidget and a drag / drop event and process it .
: usage | from projexui . qt . QtCore import QEvent
| class MyWidget ( QWidget ) :
| def _ _ init _ _ ( self , parent ) :
| super ( ... | filt = None
if ( self . _dragDropFilterRef ) :
filt = self . _dragDropFilterRef ( )
if ( not filt ) :
self . _dragDropFilterRef = None
return filt |
def dump_wcxf ( self , C_out , scale_out , fmt = 'yaml' , stream = None , ** kwargs ) :
"""Return a string representation of the Wilson coefficients ` C _ out `
in WCxf format . If ` stream ` is specified , export it to a file .
` fmt ` defaults to ` yaml ` , but can also be ` json ` .
Note that the Wilson co... | wc = self . get_wcxf ( C_out , scale_out )
return wc . dump ( fmt = fmt , stream = stream , ** kwargs ) |
def main ( ) :
"""Github repositories downloaded command line""" | parser = argparse . ArgumentParser ( description = __doc__ )
parser . add_argument ( 'githubtoken' , help = "Github OAuth token, see https://developer.github.com/v3/oauth/" )
parser . add_argument ( 'destination' , help = "location of the downloaded repos" )
parser . add_argument ( '-n' , '--nbrepo' , help = "number of... |
def add_callback ( self , callback = None , errorback = None ) :
"""Adds a callback that will be called when the upload
finishes successfully or when error is raised .""" | self . _callback = callback
self . _errorback = errorback |
def resources_to_link ( self , resources ) :
"""If this API Event Source refers to an explicit API resource , resolve the reference and grab
necessary data from the explicit API""" | rest_api_id = self . RestApiId
if isinstance ( rest_api_id , dict ) and "Ref" in rest_api_id :
rest_api_id = rest_api_id [ "Ref" ]
# If RestApiId is a resource in the same template , then we try find the StageName by following the reference
# Otherwise we default to a wildcard . This stage name is solely used to co... |
def truncate ( self , path , length , fh = None ) :
"Download existing path , truncate and reupload" | try :
f = self . _getpath ( path )
except JFS . JFSError :
raise OSError ( errno . ENOENT , '' )
if isinstance ( f , ( JFS . JFSFile , JFS . JFSFolder ) ) and f . is_deleted ( ) :
raise OSError ( errno . ENOENT )
data = StringIO ( f . read ( ) )
data . truncate ( length )
try :
self . client . up ( path... |
def check_subsequent_web_request ( self , item_session : ItemSession , is_redirect : bool = False ) -> Tuple [ bool , str ] :
'''Check URL filters and scripting hook .
Returns :
tuple : ( bool , str )''' | verdict , reason , test_info = self . consult_filters ( item_session . request . url_info , item_session . url_record , is_redirect = is_redirect )
# TODO : provide an option to change this
if item_session . is_virtual :
verdict = True
verdict , reason = self . consult_hook ( item_session , verdict , reason , test_... |
def get_collection ( self , request , ** kwargs ) :
"""Handles get requests for the list of objects .""" | qs = self . queryset ( request , ** kwargs )
if self . display_collection_fields :
display_fields = self . display_collection_fields
else :
display_fields = self . display_fields
if self . paginate_by is not None :
page = request . GET . get ( 'page' , 1 )
paginator = Paginator ( qs , self . paginate_by... |
def change_meta ( self , para , new_value , log = True ) :
"""Changes the meta data
This function does nothing if None is passed as new _ value .
To set a certain value to None pass the str ' None '
Parameters
para : str
Meta data entry to change
new _ value : str
New value
log : boolean , optional ... | if not new_value :
return
para = para . lower ( )
if para == 'history' :
raise ValueError ( 'History can only be extended - use method "note"' )
old_value = self . _content . get ( para , None )
if new_value == old_value :
return
self . _content [ para ] = new_value
if old_value and log :
self . _add_hi... |
def __build_dataframe ( self , timing , project_name = None , org_name = None ) :
"""Build a DataFrame from a time bucket .
: param timing :
: param project _ name :
: param org _ name :
: return :""" | date_list = [ ]
uuid_list = [ ]
name_list = [ ]
contribs_list = [ ]
latest_ts_list = [ ]
logger . debug ( self . __log_prefix + " timing: " + timing . key_as_string )
for author in timing [ self . AUTHOR_UUID ] . buckets :
latest_ts_list . append ( timing [ self . LATEST_TS ] . value_as_string )
date_list . app... |
def literal_struct ( cls , elems ) :
"""Construct a literal structure constant made of the given members .""" | tys = [ el . type for el in elems ]
return cls ( types . LiteralStructType ( tys ) , elems ) |
def _createdby_data ( self , ws ) :
"""Returns a dict that represents the user who created the ws
Keys : username , fullmame , email""" | username = ws . getOwner ( ) . getUserName ( )
return { 'username' : username , 'fullname' : to_utf8 ( self . user_fullname ( username ) ) , 'email' : to_utf8 ( self . user_email ( username ) ) } |
async def _return_exported_sender ( self , sender ) :
"""Returns a borrowed exported sender . If all borrows have
been returned , the sender is cleanly disconnected .""" | async with self . _borrow_sender_lock :
dc_id = sender . dc_id
n , _ = self . _borrowed_senders [ dc_id ]
n -= 1
self . _borrowed_senders [ dc_id ] = ( n , sender )
if not n :
self . _log [ __name__ ] . info ( 'Disconnecting borrowed sender for DC %d' , dc_id )
await sender . disconn... |
def uniform ( low : Number , high : Number = None , size : Optional [ List [ int ] ] = None ) -> FloatOrTensor :
"Draw 1 or shape = ` size ` random floats from uniform dist : min = ` low ` , max = ` high ` ." | if high is None :
high = low
return random . uniform ( low , high ) if size is None else torch . FloatTensor ( * listify ( size ) ) . uniform_ ( low , high ) |
def convert_1x_args ( bucket , ** kwargs ) :
"""Converts arguments for 1 . x constructors to their 2 . x forms""" | host = kwargs . pop ( 'host' , 'localhost' )
port = kwargs . pop ( 'port' , None )
if not 'connstr' in kwargs and 'connection_string' not in kwargs :
kwargs [ 'connection_string' ] = _build_connstr ( host , port , bucket )
return kwargs |
def print_stats ( self , clsname = None , limit = 1.0 ) :
"""Write tracked objects to stdout . The output can be filtered and
pruned . Only objects are printed whose classname contain the substring
supplied by the ` clsname ` argument . The output can be pruned by
passing a ` limit ` value .
: param clsname... | if self . tracker :
self . tracker . stop_periodic_snapshots ( )
if not self . sorted :
self . sort_stats ( )
_sorted = self . sorted
if clsname :
_sorted = [ to for to in _sorted if clsname in to . classname ]
if limit < 1.0 :
limit = max ( 1 , int ( len ( self . sorted ) * limit ) )
_sorted = _sorted ... |
def parse_veto_definer ( veto_def_filename ) :
"""Parse a veto definer file from the filename and return a dictionary
indexed by ifo and veto definer category level .
Parameters
veto _ def _ filename : str
The path to the veto definer file
Returns :
parsed _ definition : dict
Returns a dictionary firs... | from glue . ligolw import table , lsctables , utils as ligolw_utils
from glue . ligolw . ligolw import LIGOLWContentHandler as h
lsctables . use_in ( h )
indoc = ligolw_utils . load_filename ( veto_def_filename , False , contenthandler = h )
veto_table = table . get_table ( indoc , 'veto_definer' )
ifo = veto_table . g... |
def calculate_perimeters ( labels , indexes ) :
"""Count the distances between adjacent pixels in the perimeters of the labels""" | # Create arrays that tell whether a pixel is like its neighbors .
# index = 0 is the pixel - 1 , - 1 from the pixel of interest , 1 is - 1,0 , etc .
m = table_idx_from_labels ( labels )
pixel_score = __perimeter_scoring [ m ]
return fixup_scipy_ndimage_result ( scind . sum ( pixel_score , labels , np . array ( indexes ... |
def view ( self , options = None , ** kwds ) :
"""Endpoint : / photo / < id > [ / < options > ] / view . json
Requests all properties of this photo .
Can be used to obtain URLs for the photo at a particular size ,
by using the " returnSizes " parameter .
Updates the photo ' s fields with the response .
Th... | result = self . _client . photo . view ( self , options , ** kwds )
self . _replace_fields ( result . get_fields ( ) ) |
def get_name ( modality_type , value = None ) :
"""Gets default name for transformations ; if none available , return value .""" | # For legacy reasons , modalities vary in their naming scheme . Future plans are
# to remove any need for get _ name . We do not recommend using it .
if modality_type == ModalityType . AUDIO :
return lambda model_hparams , vocab_size : "audio_modality"
elif modality_type == ModalityType . AUDIO_SPECTRAL :
retur... |
def parseExtensionArgs ( self , args , strict = False ) :
"""Parse the unqualified simple registration request
parameters and add them to this object .
This method is essentially the inverse of
C { L { getExtensionArgs } } . This method restores the serialized simple
registration request fields .
If you a... | for list_name in [ 'required' , 'optional' ] :
required = ( list_name == 'required' )
items = args . get ( list_name )
if items :
for field_name in items . split ( ',' ) :
try :
self . requestField ( field_name , required , strict )
except ValueError :
... |
def __init_go2nt_w_usr ( self , gos_all , usr_go2nt , prt_flds_all ) :
"""Combine GO object fields and format _ txt .""" | assert usr_go2nt , "go2nt HAS NO ELEMENTS"
from goatools . nt_utils import get_unique_fields
go2nts = [ usr_go2nt , self . gosubdag . go2nt , self . _get_go2nthdridx ( gos_all ) ]
usr_nt_flds = next ( iter ( usr_go2nt . values ( ) ) ) . _fields
# Get any single value from a dict
flds = get_unique_fields ( [ usr_nt_flds... |
def database_caller_creator ( self , name = None ) :
'''creates a couchdb database
returns the related connection object
which will be later used to spawn the cursor''' | couch = couchdb . Server ( )
if name :
db = couch . create ( name )
else :
n = 'couchdb_' + lower_str_generator ( self )
db = couch . create ( n )
logger . warning ( 'couchdb database created with the name: %s' , n , extra = d )
return db |
def _possible_issuers ( self , cert ) :
"""Returns a generator that will list all possible issuers for the cert
: param cert :
An asn1crypto . x509 . Certificate object to find the issuer of""" | issuer_hashable = cert . issuer . hashable
if issuer_hashable not in self . _subject_map :
return
for issuer in self . _subject_map [ issuer_hashable ] : # Info from the authority key identifier extension can be used to
# eliminate possible options when multiple keys with the same
# subject exist , such as during a... |
def _runner ( self , job , runtime_context ) :
"""Job running thread .""" | try :
job . run ( runtime_context )
except WorkflowException as err :
_logger . exception ( "Got workflow error" )
self . exceptions . append ( err )
except Exception as err : # pylint : disable = broad - except
_logger . exception ( "Got workflow error" )
self . exceptions . append ( WorkflowExcept... |
def generate_megaman_manifold ( sampling = 2 , nfolds = 2 , rotate = True , random_state = None ) :
"""Generate a manifold of the megaman data""" | X , c = generate_megaman_data ( sampling )
for i in range ( nfolds ) :
X = np . hstack ( [ _make_S_curve ( x ) for x in X . T ] )
if rotate :
rand = check_random_state ( random_state )
R = rand . randn ( X . shape [ 1 ] , X . shape [ 1 ] )
U , s , VT = np . linalg . svd ( R )
X = np . dot ( X , U )
... |
def deliver_slice ( schedule ) :
"""Given a schedule , delivery the slice as an email report""" | if schedule . email_format == SliceEmailReportFormat . data :
email = _get_slice_data ( schedule )
elif schedule . email_format == SliceEmailReportFormat . visualization :
email = _get_slice_visualization ( schedule )
else :
raise RuntimeError ( 'Unknown email report format' )
subject = __ ( '%(prefix)s %(t... |
def light_curve_gradient ( self , t , texp = 0.0 , tol = 1e-8 , maxdepth = 4 ) :
"""Get the light curve evaluated at a list of times using the current
model .
: param t :
The times where the light curve should be evaluated ( in days ) .
: param tol :
The stopping criterion for the exposure time integratio... | t = np . atleast_1d ( t )
if len ( self . bodies ) == 0 :
grad = np . zeros ( ( len ( t ) , 5 ) , dtype = float )
grad [ : , 0 ] = 1.0
return self . central . flux + np . zeros_like ( t ) , grad [ : , self . unfrozen ]
f , df = CythonSolver ( ) . kepler_gradient ( len ( self . bodies ) , self . _get_params ... |
def _delete_device_from_device_group ( self , device ) :
'''Remove device from device service cluster group .
: param device : ManagementRoot object - - device to delete from group''' | device_name = get_device_info ( device ) . name
dg = pollster ( self . _get_device_group ) ( device )
device_to_remove = dg . devices_s . devices . load ( name = device_name , partition = self . partition )
device_to_remove . delete ( ) |
async def close_connection ( self ) -> None :
"""7.1.1 . Close the WebSocket Connection
When the opening handshake succeeds , : meth : ` connection _ open ` starts
this coroutine in a task . It waits for the data transfer phase to
complete then it closes the TCP connection cleanly .
When the opening handsha... | try : # Wait for the data transfer phase to complete .
if hasattr ( self , "transfer_data_task" ) :
try :
await self . transfer_data_task
except asyncio . CancelledError :
pass
# Cancel the keepalive ping task .
if hasattr ( self , "keepalive_ping_task" ) :
se... |
def name ( self ) :
"""Gets name string from the symbol , this function only works for non - grouped symbol .
Returns
value : str
The name of this symbol , returns ` ` None ` ` for grouped symbol .""" | ret = ctypes . c_char_p ( )
success = ctypes . c_int ( )
check_call ( _LIB . MXSymbolGetName ( self . handle , ctypes . byref ( ret ) , ctypes . byref ( success ) ) )
if success . value != 0 :
return py_str ( ret . value )
else :
return None |
def disclaim_key_flags ( ) :
"""Declares that the current module will not define any more key flags .
Normally , the module that calls the DEFINE _ xxx functions claims the
flag to be its key flag . This is undesirable for modules that
define additional DEFINE _ yyy functions with its own flag parsers and
s... | globals_for_caller = sys . _getframe ( 1 ) . f_globals
# pylint : disable = protected - access
module , _ = _helpers . get_module_object_and_name ( globals_for_caller )
_helpers . disclaim_module_ids . add ( id ( module ) ) |
def delete_wallet ( self , wallet_name ) :
"""Delete a wallet .
@ param the name of the wallet .
@ return a success string from the plans server .
@ raise ServerError via make _ request .""" | return make_request ( '{}wallet/{}' . format ( self . url , wallet_name ) , method = 'DELETE' , timeout = self . timeout , client = self . _client ) |
def params ( self ) :
"""Get set of parameters by names .
: rtype : dict""" | result = { }
for content in list ( self . values ( ) ) :
if isinstance ( content , CompositeModelElement ) :
cparams = content . params
for cpname in cparams :
cparam = cparams [ cpname ]
if cpname in result :
result [ cpname ] . update ( cparam )
... |
def _nonblocking_read ( self ) :
"""Returns the number of characters read and adds them to self . unprocessed _ bytes""" | with Nonblocking ( self . in_stream ) :
if PY3 :
try :
data = os . read ( self . in_stream . fileno ( ) , READ_SIZE )
except BlockingIOError :
return 0
if data :
self . unprocessed_bytes . extend ( data [ i : i + 1 ] for i in range ( len ( data ) ) )
... |
def get_datafeeds ( self , datafeed_id = None , params = None ) :
"""` < http : / / www . elastic . co / guide / en / elasticsearch / reference / current / ml - get - datafeed . html > ` _
: arg datafeed _ id : The ID of the datafeeds to fetch
: arg allow _ no _ datafeeds : Whether to ignore if a wildcard expre... | return self . transport . perform_request ( "GET" , _make_path ( "_ml" , "datafeeds" , datafeed_id ) , params = params ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.