signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def apply_T4 ( word ) : # OPTIMIZE
'''An agglutination diphthong that ends in / u , y / usually contains a
syllable boundary when - C # or - CCV follow , e . g . , [ lau . ka . us ] ,
[ va . ka . ut . taa ] .''' | WORD = _split_consonants_and_vowels ( word )
for k , v in WORD . iteritems ( ) :
if len ( v ) == 2 and v . endswith ( ( 'u' , 'y' ) ) :
if WORD . get ( k + 2 , 0 ) :
if not WORD . get ( k + 3 , 0 ) :
if len ( WORD [ k + 2 ] ) == 1 and is_consonant ( WORD [ k + 2 ] ) :
... |
def copy ( self ) :
"""Return a new Project instance , deep - copying all the attributes .""" | p = Project ( )
p . name = self . name
p . path = self . path
p . _plugin = self . _plugin
p . stage = self . stage . copy ( )
p . stage . project = p
for sprite in self . sprites :
s = sprite . copy ( )
s . project = p
p . sprites . append ( s )
for actor in self . actors :
if isinstance ( actor , Spri... |
def get_result ( db , result_id ) :
""": param db :
a : class : ` openquake . server . dbapi . Db ` instance
: param result _ id :
a result ID
: returns : ( job _ id , job _ status , datadir , datastore _ key )""" | job = db ( 'SELECT job.*, ds_key FROM job, output WHERE ' 'oq_job_id=job.id AND output.id=?x' , result_id , one = True )
return ( job . id , job . status , job . user_name , os . path . dirname ( job . ds_calc_dir ) , job . ds_key ) |
def order ( order_book_id , quantity , price = None , style = None ) :
"""全品种通用智能调仓函数
如果不指定 price , 则相当于下 MarketOrder
如果 order _ book _ id 是股票 , 等同于调用 order _ shares
如果 order _ book _ id 是期货 , 则进行智能下单 :
* quantity 表示调仓量
* 如果 quantity 为正数 , 则先平 Sell 方向仓位 , 再开 Buy 方向仓位
* 如果 quantity 为负数 , 则先平 Buy 反向仓位 , 再... | style = cal_style ( price , style )
orders = Environment . get_instance ( ) . portfolio . order ( order_book_id , quantity , style )
if isinstance ( orders , Order ) :
return [ orders ]
return orders |
def help ( file = None ) :
"""Print out syntax help for running astrodrizzle
Parameters
file : str ( Default = None )
If given , write out help to the filename specified by this parameter
Any previously existing file with this name will be deleted before
writing out the help .""" | helpstr = getHelpAsString ( docstring = True , show_ver = True )
if file is None :
print ( helpstr )
else :
if os . path . exists ( file ) :
os . remove ( file )
f = open ( file , mode = 'w' )
f . write ( helpstr )
f . close ( ) |
def del_view_menu ( self , name ) :
"""Deletes a ViewMenu from the backend
: param name :
name of the ViewMenu""" | obj = self . find_view_menu ( name )
if obj :
try :
obj . delete ( )
except Exception as e :
log . error ( c . LOGMSG_ERR_SEC_DEL_PERMISSION . format ( str ( e ) ) ) |
def match_replace ( cls , ops , kwargs ) :
"""Match and replace a full operand specification to a function that
provides a replacement for the whole expression
or raises a : exc : ` . CannotSimplify ` exception .
E . g .
First define an operation : :
> > > class Invert ( Operation ) :
. . . _ rules = Or... | expr = ProtoExpr ( ops , kwargs )
if LOG :
logger = logging . getLogger ( 'QNET.create' )
for key , rule in cls . _rules . items ( ) :
pat , replacement = rule
match_dict = match_pattern ( pat , expr )
if match_dict :
try :
replaced = replacement ( ** match_dict )
if LOG ... |
def parse_factor_line ( line ) :
"""function to parse a factor file line . Used by fac2real ( )
Parameters
line : ( str )
a factor line from a factor file
Returns
inode : int
the inode of the grid node
itrans : int
flag for transformation of the grid node
fac _ data : dict
a dictionary of point ... | raw = line . strip ( ) . split ( )
inode , itrans , nfac = [ int ( i ) for i in raw [ : 3 ] ]
fac_data = { int ( raw [ ifac ] ) - 1 : float ( raw [ ifac + 1 ] ) for ifac in range ( 4 , 4 + nfac * 2 , 2 ) }
# fac _ data = { }
# for ifac in range ( 4,4 + nfac * 2,2 ) :
# pnum = int ( raw [ ifac ] ) - 1 # zero based to sy... |
def getStateCode ( self , state ) :
"""Calculates the state code for a specific state or set of states .
We transform the states so that they are nonnegative and take an inner product .
The resulting number is unique because we use numeral system with a large enough base .""" | return np . dot ( state - self . minvalues , self . statecode ) |
def data ( self ) :
"""Values in request body .""" | if self . _data is None :
self . _data = self . arg_container ( )
if isinstance ( self . fieldstorage . value , list ) :
for k in self . fieldstorage . keys ( ) :
fname = self . fieldstorage [ k ] . filename
if fname :
self . _data [ k ] = ( fname , self . fieldst... |
def msg_curse ( self , args = None , max_width = None ) :
"""Return the dict to display in the curse interface .""" | # Init the return message
ret = [ ]
# Only process if stats exist and plugin not disabled
if not self . stats or self . is_disable ( ) :
return ret
# Build the string message
# Header
msg = '{}' . format ( 'SWAP' )
ret . append ( self . curse_add_line ( msg , "TITLE" ) )
msg = ' {:3}' . format ( self . trend_msg ( ... |
def _read_data_handler ( length , whence , ctx , skip = False , stream_event = ION_STREAM_INCOMPLETE_EVENT ) :
"""Creates a co - routine for retrieving data up to a requested size .
Args :
length ( int ) : The minimum length requested .
whence ( Coroutine ) : The co - routine to return to after the data is sa... | trans = None
queue = ctx . queue
if length > ctx . remaining :
raise IonException ( 'Length overrun: %d bytes, %d remaining' % ( length , ctx . remaining ) )
# Make sure to check the queue first .
queue_len = len ( queue )
if queue_len > 0 : # Any data available means we can only be incomplete .
stream_event = ... |
def eval ( source , optimize = True , output = sys . stdout , input = sys . stdin , steps = - 1 ) :
"""Compiles and runs program , returning the values on the stack .
To return the machine instead , see execute ( ) .
Args :
optimize : Whether to optimize the code after parsing it .
output : Stream which pro... | machine = execute ( source , optimize = optimize , output = output , input = input , steps = steps )
ds = machine . stack
if len ( ds ) == 0 :
return None
elif len ( ds ) == 1 :
return ds [ - 1 ]
else :
return ds |
def from_json ( cls , data ) :
"""Create a location from a dictionary .
Args :
data : {
" city " : " - " ,
" latitude " : 0,
" longitude " : 0,
" time _ zone " : 0,
" elevation " : 0}""" | optional_keys = ( 'city' , 'state' , 'country' , 'latitude' , 'longitude' , 'time_zone' , 'elevation' , 'station_id' , 'source' )
for key in optional_keys :
if key not in data :
data [ key ] = None
return cls ( data [ 'city' ] , data [ 'state' ] , data [ 'country' ] , data [ 'latitude' ] , data [ 'longitude... |
def set_stats_params ( self , address = None , enable_http = None , minify = None , no_cores = None , no_metrics = None , push_interval = None ) :
"""Enables stats server on the specified address .
* http : / / uwsgi . readthedocs . io / en / latest / StatsServer . html
: param str | unicode address : Address /... | self . _set ( 'stats-server' , address )
self . _set ( 'stats-http' , enable_http , cast = bool )
self . _set ( 'stats-minified' , minify , cast = bool )
self . _set ( 'stats-no-cores' , no_cores , cast = bool )
self . _set ( 'stats-no-metrics' , no_metrics , cast = bool )
self . _set ( 'stats-pusher-default-freq' , pu... |
def load ( self , * modules ) :
"""Load one or more modules .
Args :
modules : Either a string full path to a module or an actual module
object .""" | for module in modules :
if isinstance ( module , six . string_types ) :
try :
module = get_object ( module )
except Exception as e :
self . errors [ module ] = e
continue
self . modules [ module . __package__ ] = module
for ( loader , module_name , is_pkg ... |
def extend ( self , itemseq ) :
"""Add sequence of elements to end of ParseResults list of elements .
Example : :
patt = OneOrMore ( Word ( alphas ) )
# use a parse action to append the reverse of the matched strings , to make a palindrome
def make _ palindrome ( tokens ) :
tokens . extend ( reversed ( [ ... | if isinstance ( itemseq , ParseResults ) :
self += itemseq
else :
self . __toklist . extend ( itemseq ) |
def diskwarp ( src_ds , res = None , extent = None , t_srs = None , r = 'cubic' , outdir = None , dst_fn = None , dst_ndv = None , verbose = True ) :
"""Helper function that calls warp for single input Dataset with output to disk ( GDAL GeoTiff Driver )""" | if dst_fn is None :
dst_fn = os . path . splitext ( src_ds . GetFileList ( ) [ 0 ] ) [ 0 ] + '_warp.tif'
if outdir is not None :
dst_fn = os . path . join ( outdir , os . path . basename ( dst_fn ) )
driver = iolib . gtif_drv
dst_ds = warp ( src_ds , res , extent , t_srs , r , driver , dst_fn , dst_ndv = dst_nd... |
def stop ( self ) :
"""Stops the external measurement program and returns the measurement result ,
if the measurement was running .""" | consumed_energy = collections . defaultdict ( dict )
if not self . is_running ( ) :
return None
# cpu - energy - meter expects SIGINT to stop and report its result
self . _measurement_process . send_signal ( signal . SIGINT )
( out , err ) = self . _measurement_process . communicate ( )
assert self . _measurement_p... |
def _sane_version_list ( version ) :
"""Ensure the major and minor are int .
Parameters
version : list
Version components
Returns
version : list
List of components where first two components has been sanitised""" | v0 = str ( version [ 0 ] )
if v0 : # Test if the major is a number .
try :
v0 = v0 . lstrip ( "v" ) . lstrip ( "V" )
# Handle the common case where tags have v before major .
v0 = int ( v0 )
except ValueError :
v0 = None
if v0 is None :
version = [ 0 , 0 ] + version
else :
... |
def match_filtered_identities ( self , fa , fb ) :
"""Determine if two filtered identities are the same .
The method compares the email addresses of each filtered identity
to check if they are the same . When the given filtered identities
are the same object or share the same UUID , this will also
produce a... | if not isinstance ( fa , EmailIdentity ) :
raise ValueError ( "<fa> is not an instance of UniqueIdentity" )
if not isinstance ( fb , EmailIdentity ) :
raise ValueError ( "<fb> is not an instance of EmailNameIdentity" )
if fa . uuid and fb . uuid and fa . uuid == fb . uuid :
return True
if fa . email in self... |
def plot_survival ( self , on , how = "os" , survival_units = "Days" , strata = None , ax = None , ci_show = False , with_condition_color = "#B38600" , no_condition_color = "#A941AC" , with_condition_label = None , no_condition_label = None , color_map = None , label_map = None , color_palette = "Set2" , threshold = No... | assert how in [ "os" , "pfs" ] , "Invalid choice of survival plot type %s" % how
cols , df = self . as_dataframe ( on , return_cols = True , ** kwargs )
plot_col = self . plot_col_from_cols ( cols = cols , only_allow_one = True )
df = filter_not_null ( df , plot_col )
results = plot_kmf ( df = df , condition_col = plot... |
def parse_udiff ( diff , patterns = None , parent = '.' ) :
"""Return a dictionary of matching lines .""" | # For each file of the diff , the entry key is the filename ,
# and the value is a set of row numbers to consider .
rv = { }
path = nrows = None
for line in diff . splitlines ( ) :
if nrows :
if line [ : 1 ] != '-' :
nrows -= 1
continue
if line [ : 3 ] == '@@ ' :
hunk_match =... |
def setCurrentInspectorRegItem ( self , regItem ) :
"""Sets the current inspector given an InspectorRegItem""" | check_class ( regItem , InspectorRegItem , allow_none = True )
self . inspectorTab . setCurrentRegItem ( regItem ) |
def validate ( self , path , schema , value , results ) :
"""Validates a given value against this rule .
: param path : a dot notation path to the value .
: param schema : a schema this rule is called from
: param value : a value to be validated .
: param results : a list with validation results to add new ... | name = path if path != None else "value"
found = [ ]
for prop in self . _properties :
property_value = ObjectReader . get_property ( value , prop )
if property_value != None :
found . append ( prop )
if len ( found ) == 0 :
results . append ( ValidationResult ( path , ValidationResultType . Error , ... |
def pad_funcs ( self , high ) :
'''Turns dot delimited function refs into function strings''' | for name in high :
if not isinstance ( high [ name ] , dict ) :
if isinstance ( high [ name ] , six . string_types ) : # Is this is a short state ? It needs to be padded !
if '.' in high [ name ] :
comps = high [ name ] . split ( '.' )
if len ( comps ) >= 2 : # Me... |
def _partition_query ( cls , table_name , limit = 0 , order_by = None , filters = None ) :
"""Returns a partition query
: param table _ name : the name of the table to get partitions from
: type table _ name : str
: param limit : the number of partitions to be returned
: type limit : int
: param order _ b... | limit_clause = 'LIMIT {}' . format ( limit ) if limit else ''
order_by_clause = ''
if order_by :
l = [ ]
# noqa : E741
for field , desc in order_by :
l . append ( field + ' DESC' if desc else '' )
order_by_clause = 'ORDER BY ' + ', ' . join ( l )
where_clause = ''
if filters :
l = [ ]
# ... |
def _shape_repr ( shape ) :
"""Return a platform independent reprensentation of an array shape
Under Python 2 , the ` long ` type introduces an ' L ' suffix when using the
default % r format for tuples of integers ( typically used to store the shape
of an array ) .
Under Windows 64 bit ( and Python 2 ) , th... | if len ( shape ) == 0 :
return "()"
joined = ", " . join ( "%d" % e for e in shape )
if len ( shape ) == 1 : # special notation for singleton tuples
joined += ','
return "(%s)" % joined |
def get_asset_admin_session ( self , * args , ** kwargs ) :
"""Gets an asset administration session for creating , updating and
deleting assets .
return : ( osid . repository . AssetAdminSession ) - an
AssetAdminSession
raise : OperationFailed - unable to complete request
raise : Unimplemented - supports ... | if not self . supports_asset_admin ( ) :
raise Unimplemented ( )
try :
from . import sessions
except ImportError :
raise
# OperationFailed ( )
try :
session = sessions . AssetAdminSession ( proxy = self . _proxy , runtime = self . _runtime , ** kwargs )
except AttributeError :
raise
# Operat... |
def calc_hexversion ( major = 0 , minor = 0 , micro = 0 , releaselevel = 'dev' , serial = 0 ) :
"""Calculate the hexadecimal version number from the tuple version _ info :
: param major : integer
: param minor : integer
: param micro : integer
: param relev : integer or string
: param serial : integer
:... | try :
releaselevel = int ( releaselevel )
except ValueError :
releaselevel = RELEASE_LEVEL_VALUE . get ( releaselevel , 0 )
hex_version = int ( serial )
hex_version |= releaselevel * 1 << 4
hex_version |= int ( micro ) * 1 << 8
hex_version |= int ( minor ) * 1 << 16
hex_version |= int ( major ) * 1 << 24
return... |
def uninstall ( self , tool : Tool , force : bool = False , noprune : bool = False ) -> None :
"""Uninstalls all Docker images associated with this tool .
See : ` BuildManager . uninstall `""" | self . __installation . build . uninstall ( tool . image , force = force , noprune = noprune ) |
def dotter ( ) :
"""Prints formatted time to stdout at the start of a line , as well as a " . "
whenever the length of the line is equal or lesser than 80 " . " long""" | # Use a global variable
global globalcount
if globalcount <= 80 :
sys . stdout . write ( '.' )
globalcount += 1
else :
sys . stdout . write ( '\n.' )
globalcount = 1 |
def command_getkeys ( self , command , * args , encoding = 'utf-8' ) :
"""Extract keys given a full Redis command .""" | return self . execute ( b'COMMAND' , b'GETKEYS' , command , * args , encoding = encoding ) |
def get_containers ( self ) :
"""Return available containers .""" | permitted = lambda c : settings . container_permitted ( c . name )
return [ c for c in self . _get_containers ( ) if permitted ( c ) ] |
def put_zonefiles ( hostport , zonefile_data_list , timeout = 30 , my_hostport = None , proxy = None ) :
"""Push one or more zonefiles to the given server .
Each zone file in the list must be base64 - encoded
Return { ' status ' : True , ' saved ' : [ . . . ] } on success
Return { ' error ' : . . . } on error... | assert hostport or proxy , 'need either hostport or proxy'
saved_schema = { 'type' : 'object' , 'properties' : { 'saved' : { 'type' : 'array' , 'items' : { 'type' : 'integer' , 'minimum' : 0 , 'maximum' : 1 , } , 'minItems' : len ( zonefile_data_list ) , 'maxItems' : len ( zonefile_data_list ) } , } , 'required' : [ 's... |
def ordered ( seq , keys = None , default = True , warn = False ) :
"""Return an iterator of the seq where keys are used to break ties in
a conservative fashion : if , after applying a key , there are no ties
then no other keys will be computed .
Two default keys will be applied if 1 ) keys are not provided o... | d = defaultdict ( list )
if keys :
if not isinstance ( keys , ( list , tuple ) ) :
keys = [ keys ]
keys = list ( keys )
f = keys . pop ( 0 )
for a in seq :
d [ f ( a ) ] . append ( a )
else :
if not default :
raise ValueError ( 'if default=False then keys must be provided' )
... |
def removeChild ( self , position ) :
"""Removes the child at the position ' position '
Calls the child item finalize to close its resources before removing it .""" | assert 0 <= position <= len ( self . childItems ) , "position should be 0 < {} <= {}" . format ( position , len ( self . childItems ) )
self . childItems [ position ] . finalize ( )
self . childItems . pop ( position ) |
def normal_prior ( value , mean , sigma ) :
"""Normal prior distribution .""" | return - 0.5 * ( 2 * np . pi * sigma ) - ( value - mean ) ** 2 / ( 2.0 * sigma ) |
def reset_time ( self , time , true_anom , elongan , eincl ) :
"""TODO : add documentation""" | self . true_anom = true_anom
self . elongan = elongan
self . eincl = eincl
self . time = time
self . populated_at_time = [ ]
self . reset ( )
return |
def load ( value : Any , type_ : Type [ T ] , ** kwargs ) -> T :
"""Quick function call to load data into a type .
It is useful to avoid creating the Loader object ,
in case only the default parameters are used .""" | from . import dataloader
loader = dataloader . Loader ( ** kwargs )
return loader . load ( value , type_ ) |
def list_returner_functions ( * args , ** kwargs ) : # pylint : disable = unused - argument
'''List the functions for all returner modules . Optionally , specify a returner
module or modules from which to list .
. . versionadded : : 2014.7.0
CLI Example :
. . code - block : : bash
salt ' * ' sys . list _ ... | # NOTE : * * kwargs is used here to prevent a traceback when garbage
# arguments are tacked on to the end .
returners_ = salt . loader . returners ( __opts__ , [ ] )
if not args : # We ' re being asked for all functions
return sorted ( returners_ )
names = set ( )
for module in args :
if '*' in module or '.' in... |
def _data_dep_init ( self , inputs ) :
"""Data dependent initialization for eager execution .""" | with tf . variable_scope ( "data_dep_init" ) : # Generate data dependent init values
activation = self . layer . activation
self . layer . activation = None
x_init = self . layer . call ( inputs )
m_init , v_init = tf . moments ( x_init , self . norm_axes )
scale_init = 1. / tf . sqrt ( v_init + 1e-... |
def locus ( args ) :
"""% prog locus bamfile
Extract selected locus from a list of TREDs for validation , and run lobSTR .""" | from jcvi . formats . sam import get_minibam
# See ` Format - lobSTR - database . ipynb ` for a list of TREDs for validation
INCLUDE = [ "HD" , "SBMA" , "SCA1" , "SCA2" , "SCA8" , "SCA17" , "DM1" , "DM2" , "FXTAS" ]
db_choices = ( "hg38" , "hg19" )
p = OptionParser ( locus . __doc__ )
p . add_option ( "--tred" , choice... |
def resizeEvent ( self , event ) :
"""Overloads the resize event to auto - resize the rich text label to the
size of this QPushButton .
: param event | < QResizeEvent >""" | super ( XPushButton , self ) . resizeEvent ( event )
if self . _richTextLabel :
self . _richTextLabel . resize ( event . size ( ) ) |
def _get_dbid2goids ( associations ) :
"""Return gene2go data for user - specified taxids .""" | id2gos = cx . defaultdict ( set )
for ntd in associations :
id2gos [ ntd . DB_ID ] . add ( ntd . GO_ID )
return dict ( id2gos ) |
def results ( self , times = 'all' , t_precision = 12 , ** kwargs ) :
r"""Fetches the calculated quantity from the algorithm and returns it as
an array .
Parameters
times : scalar or list
Time steps to be returned . The default value is ' all ' which results
in returning all time steps . If a scalar is gi... | if 'steps' in kwargs . keys ( ) :
times = kwargs [ 'steps' ]
t_pre = t_precision
quantity = self . settings [ 'quantity' ]
q = [ k for k in list ( self . keys ( ) ) if quantity in k ]
if times == 'all' :
t = q
elif type ( times ) in [ float , int ] :
n = int ( - dc ( str ( round ( times , t_pre ) ) ) . as_t... |
def BIC ( self , data = None ) :
'''BIC on the passed data . If passed data is None ( default ) , calculates BIC
on the model ' s assigned data''' | # NOTE : in principle this method computes the BIC only after finding the
# maximum likelihood parameters ( or , of course , an EM fixed - point as an
# approximation ! )
assert data is None and len ( self . states_list ) > 0 , 'Must have data to get BIC'
if data is None :
return - 2 * sum ( self . log_likelihood (... |
def processResponse ( self , arg , replytype , ** kw ) :
"""Parameters :
arg - - deferred
replytype - - typecode""" | if self . debug :
log . msg ( '--->PROCESS REQUEST\n%s' % arg , debug = 1 )
for h in self . handlers :
arg . addCallback ( h . processResponse , ** kw )
arg . addCallback ( self . parseResponse , replytype ) |
def p_substr_assignment ( p ) :
"""statement : LET ID arg _ list EQ expr""" | if p [ 3 ] is None or p [ 5 ] is None :
return
# There were errors
p [ 0 ] = None
entry = SYMBOL_TABLE . access_call ( p [ 2 ] , p . lineno ( 2 ) )
if entry is None :
return
if entry . class_ == CLASS . unknown :
entry . class_ = CLASS . var
assert entry . class_ == CLASS . var and entry . type_ == TYPE . s... |
def absent ( name , service_name , auth = None , ** kwargs ) :
'''Ensure an endpoint does not exists
name
Interface name
url
URL of the endpoint
service _ name
Service name or ID
region
The region name to assign the endpoint''' | ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : '' }
__salt__ [ 'keystoneng.setup_clouds' ] ( auth )
success , val = _ , endpoint = _common ( ret , name , service_name , kwargs )
if not success :
return val
if endpoint :
if __opts__ [ 'test' ] is True :
ret [ 'result' ] = None
... |
def cov ( x , y , keepdims = 0 ) :
"""Returns the estimated covariance of the values in the passed
array ( i . e . , N - 1 ) . Dimension can equal None ( ravel array first ) , an
integer ( the dimension over which to operate ) , or a sequence ( operate
over multiple dimensions ) . Set keepdims = 1 to return a... | n = len ( x )
xmn = mean ( x )
ymn = mean ( y )
xdeviations = [ 0 ] * len ( x )
ydeviations = [ 0 ] * len ( y )
for i in range ( len ( x ) ) :
xdeviations [ i ] = x [ i ] - xmn
ydeviations [ i ] = y [ i ] - ymn
ss = 0.0
for i in range ( len ( xdeviations ) ) :
ss = ss + xdeviations [ i ] * ydeviations [ i ]... |
def remove ( self , element , multiplicity = None ) :
"""Removes an element from the multiset .
If no multiplicity is specified , the element is completely removed from the multiset :
> > > ms = Multiset ( ' aabbbc ' )
> > > ms . remove ( ' a ' )
> > > sorted ( ms )
[ ' b ' , ' b ' , ' b ' , ' c ' ]
If ... | _elements = self . _elements
if element not in _elements :
raise KeyError
old_multiplicity = _elements . get ( element , 0 )
if multiplicity is None or multiplicity >= old_multiplicity :
del _elements [ element ]
self . _total -= old_multiplicity
elif multiplicity < 0 :
raise ValueError ( "Multiplicity ... |
def get_database_users ( self ) :
"""Get list of database users .""" | url = "db/{0}/users" . format ( self . _database )
response = self . request ( url = url , method = 'GET' , expected_response_code = 200 )
return response . json ( ) |
def reset ( all = False , vms = False , switches = False ) :
'''Reset the running state of VMM or a subsystem .
all :
Reset the running state .
switches :
Reset the configured switches .
vms :
Reset and terminate all VMs .
CLI Example :
. . code - block : : bash
salt ' * ' vmctl . reset all = True... | ret = False
cmd = [ 'vmctl' , 'reset' ]
if all :
cmd . append ( 'all' )
elif vms :
cmd . append ( 'vms' )
elif switches :
cmd . append ( 'switches' )
result = __salt__ [ 'cmd.run_all' ] ( cmd , output_loglevel = 'trace' , python_shell = False )
if result [ 'retcode' ] == 0 :
ret = True
else :
raise ... |
def confirmMapIdentity ( self , subject , vendorSpecific = None ) :
"""See Also : confirmMapIdentityResponse ( )
Args :
subject :
vendorSpecific :
Returns :""" | response = self . confirmMapIdentityResponse ( subject , vendorSpecific )
return self . _read_boolean_response ( response ) |
def _equation_of_time ( t ) :
"""Find the difference between apparent and mean solar time
Parameters
t : ` ~ astropy . time . Time `
times ( array )
Returns
ret1 : ` ~ astropy . units . Quantity `
the equation of time""" | # Julian centuries since J2000.0
T = ( t - Time ( "J2000" ) ) . to ( u . year ) . value / 100
# obliquity of ecliptic ( Meeus 1998 , eq 22.2)
poly_pars = ( 84381.448 , 46.8150 , 0.00059 , 0.001813 )
eps = u . Quantity ( polyval ( T , poly_pars ) , u . arcsec )
y = np . tan ( eps / 2 ) ** 2
# Sun ' s mean longitude ( Me... |
def get_current_context_id ( ) :
"""Identifis which context it is ( greenlet , stackless , or thread ) .
: returns : the identifier of the current context .""" | global get_current_context_id
if greenlet is not None :
if stackless is None :
get_current_context_id = greenlet . getcurrent
return greenlet . getcurrent ( )
return greenlet . getcurrent ( ) , stackless . getcurrent ( )
elif stackless is not None :
get_current_context_id = stackless . getcu... |
def get_email_content ( file_path ) :
"""Email content in file
: param file _ path : Path to file with email text
: return : Email text ( html formatted )""" | with open ( file_path , "r" ) as in_file :
text = str ( in_file . read ( ) )
return text . replace ( "\n\n" , "<br>" ) |
def search_records ( self , domain , record_type , name = None , data = None ) :
"""Returns a list of all records configured for the specified domain that
match the supplied search criteria .""" | search_params = [ ]
if name :
search_params . append ( "name=%s" % name )
if data :
search_params . append ( "data=%s" % data )
query_string = "&" . join ( search_params )
dom_id = utils . get_id ( domain )
uri = "/domains/%s/records?type=%s" % ( dom_id , record_type )
if query_string :
uri = "%s&%s" % ( ur... |
def get_job_list ( self , project_name ) :
"""Get the list of pending , running and finished jobs of some project .
: param project _ name : the project name
: return : a dictionary that list inculde job name and status
example :
{ " status " : " ok " ,
" pending " : [ { " id " : " 78391cc0fcaf11e1b009080... | url , method = self . command_set [ 'listjobs' ] [ 0 ] , self . command_set [ 'listjobs' ] [ 1 ]
data = { 'project' : project_name }
response = http_utils . request ( url , method_type = method , data = data , return_type = http_utils . RETURN_JSON )
if response is None :
logging . warning ( '%s failure: not found ... |
def plots_from_files ( imspaths , figsize = ( 10 , 5 ) , rows = 1 , titles = None , maintitle = None ) :
"""Plots images given image files .
Arguments :
im _ paths ( list ) : list of paths
figsize ( tuple ) : figure size
rows ( int ) : number of rows
titles ( list ) : list of titles
maintitle ( string )... | f = plt . figure ( figsize = figsize )
if maintitle is not None :
plt . suptitle ( maintitle , fontsize = 16 )
for i in range ( len ( imspaths ) ) :
sp = f . add_subplot ( rows , ceildiv ( len ( imspaths ) , rows ) , i + 1 )
sp . axis ( 'Off' )
if titles is not None :
sp . set_title ( titles [ i... |
def setRect ( self , rect ) :
"""Sets the rect for this node , ensuring that the width and height meet the minimum requirements .
: param rect < QRectF >""" | mwidth = self . minimumWidth ( )
mheight = self . minimumHeight ( )
if ( rect . width ( ) < mwidth ) :
rect . setWidth ( mwidth )
if ( rect . height ( ) < mheight ) :
rect . setHeight ( mheight )
return super ( XNode , self ) . setRect ( rect ) |
def checkgrad ( f , fprime , x , * args , ** kw_args ) :
"""Analytical gradient calculation using a 3 - point method""" | LG . debug ( "Checking gradient ..." )
import numpy as np
# using machine precision to choose h
eps = np . finfo ( float ) . eps
step = np . sqrt ( eps ) * ( x . min ( ) )
# shake things up a bit by taking random steps for each x dimension
h = step * np . sign ( np . random . uniform ( - 1 , 1 , x . size ) )
f_ph = f (... |
def update ( self ) :
'''Draws directly to the terminal any UI elements in the tree that are
marked as having been updated . UI elements may have marked themselves
as updated if , for example , notable attributes have been altered , or
the : attr : ` updated ` element may be set to ` ` True ` ` explicitly by ... | super ( ) . update ( self . default_format , terminal = self . terminal , styles = self . style ) |
def filter_stack ( graph , head , filters ) :
"""Perform a walk in a depth - first order starting
at * head * .
Returns ( visited , removes , orphans ) .
* visited : the set of visited nodes
* removes : the list of nodes where the node
data does not all * filters *
* orphans : tuples of ( last _ good , ... | visited , removes , orphans = set ( [ head ] ) , set ( ) , set ( )
stack = deque ( [ ( head , head ) ] )
get_data = graph . node_data
get_edges = graph . out_edges
get_tail = graph . tail
while stack :
last_good , node = stack . pop ( )
data = get_data ( node )
if data is not None :
for filtfunc in ... |
def _sort_to_str ( self ) :
"""Before exec query , this method transforms sort dict string
from
{ " name " : " asc " , " timestamp " : " desc " }
to
" name asc , timestamp desc " """ | params_list = [ ]
timestamp = ""
for k , v in self . _solr_params [ 'sort' ] . items ( ) :
if k != "timestamp" :
params_list . append ( " " . join ( [ k , v ] ) )
else :
timestamp = v
params_list . append ( " " . join ( [ 'timestamp' , timestamp ] ) )
self . _solr_params [ 'sort' ] = ", " . join... |
def _actor_from_game_image ( self , name , game_image ) :
"""Return an actor object matching the one in the game image .
Note :
Health and mana are based on measured percentage of a fixed maximum
rather than the actual maximum in the game .
Arguments :
name : must be ' player ' or ' opponent '
game _ im... | HEALTH_MAX = 100
MANA_MAX = 40
# get the set of tools for investigating this actor
tools = { 'player' : self . _player_tools , 'opponent' : self . _oppnt_tools } [ name ]
# setup the arguments to be set :
args = [ name ]
# health :
t , l , b , r = tools [ 'health_region' ] . region_in ( game_image )
health_image = game... |
def scan_sequence ( self , frame , direction ) :
"""Search in one reading frame""" | orf_start = None
for c , index in self . codons ( frame ) :
if ( c not in self . stop and ( c in self . start or not self . start ) and orf_start is None ) :
orf_start = index
elif c in self . stop and orf_start is not None :
self . _update_longest ( orf_start , index + 3 , direction , frame )
... |
def _package_conf_ordering ( conf , clean = True , keep_backup = False ) :
'''Move entries in the correct file .''' | if conf in SUPPORTED_CONFS :
rearrange = [ ]
path = BASE_PATH . format ( conf )
backup_files = [ ]
for triplet in salt . utils . path . os_walk ( path ) :
for file_name in triplet [ 2 ] :
file_path = '{0}/{1}' . format ( triplet [ 0 ] , file_name )
cp = triplet [ 0 ] [ le... |
def skip_status ( * skipped ) :
"""Decorator to skip this call if we ' re in one of the skipped states .""" | def decorator ( func ) :
@ functools . wraps ( func )
def _skip_status ( self , * args , ** kwargs ) :
if self . status not in skipped :
return func ( self , * args , ** kwargs )
return _skip_status
return decorator |
def topics ( self ) :
""": return : the list of topics we interfaced with ( not the list of all available topics )""" | topics = self . interface . publishers . copy ( )
topics . update ( self . interface . subscribers )
return topics |
def raise_ssl_error ( code , nested = None ) :
"""Raise an SSL error with the given error code""" | err_string = str ( code ) + ": " + _ssl_errors [ code ]
if nested :
raise SSLError ( code , err_string + str ( nested ) )
raise SSLError ( code , err_string ) |
def calculate_fuzzy_chi ( alpha , square_map , right_eigenvectors ) :
"""Calculate the membership matrix ( chi ) from parameters alpha .
Parameters
alpha : ndarray
Parameters of objective function ( e . g . flattened A )
square _ map : ndarray
Mapping from square indices ( i , j ) to flat indices ( k ) . ... | # Convert parameter vector into matrix A
A = to_square ( alpha , square_map )
# Make A feasible .
A = fill_A ( A , right_eigenvectors )
# Calculate the fuzzy membership matrix .
chi_fuzzy = np . dot ( right_eigenvectors , A )
# Calculate the microstate mapping .
mapping = np . argmax ( chi_fuzzy , 1 )
return A , chi_fu... |
def ajax_delete_analysis_attachment ( self ) :
"""Endpoint for attachment delete in WS""" | form = self . request . form
attachment_uid = form . get ( "attachment_uid" , None )
if not attachment_uid :
return "error"
attachment = api . get_object_by_uid ( attachment_uid , None )
if attachment is None :
return "Could not resolve attachment UID {}" . format ( attachment_uid )
# handle delete via the Atta... |
def parse_time ( value : Union [ time , str ] ) -> time :
"""Parse a time / string and return a datetime . time .
This function doesn ' t support time zone offsets .
Raise ValueError if the input is well formatted but not a valid time .
Raise ValueError if the input isn ' t well formatted , in particular if i... | if isinstance ( value , time ) :
return value
match = time_re . match ( value )
if not match :
raise errors . TimeError ( )
kw = match . groupdict ( )
if kw [ 'microsecond' ] :
kw [ 'microsecond' ] = kw [ 'microsecond' ] . ljust ( 6 , '0' )
kw_ = { k : int ( v ) for k , v in kw . items ( ) if v is not None ... |
def Run ( self , args ) :
"""Reads a buffer on the client and sends it to the server .""" | # Make sure we limit the size of our output
if args . length > constants . CLIENT_MAX_BUFFER_SIZE :
raise RuntimeError ( "Can not read buffers this large." )
try :
fd = vfs . VFSOpen ( args . pathspec , progress_callback = self . Progress )
fd . Seek ( args . offset )
offset = fd . Tell ( )
data = f... |
def server_add ( s_name , s_ip , s_state = None , ** connection_args ) :
'''Add a server
Note : The default server state is ENABLED
CLI Example :
. . code - block : : bash
salt ' * ' netscaler . server _ add ' serverName ' ' serverIpAddress '
salt ' * ' netscaler . server _ add ' serverName ' ' serverIpAd... | ret = True
if server_exists ( s_name , ** connection_args ) :
return False
nitro = _connect ( ** connection_args )
if nitro is None :
return False
server = NSServer ( )
server . set_name ( s_name )
server . set_ipaddress ( s_ip )
if s_state is not None :
server . set_state ( s_state )
try :
NSServer . a... |
def get_abstracts ( self , refresh = True ) :
"""Return a list of ScopusAbstract objects using ScopusSearch .""" | return [ ScopusAbstract ( eid , refresh = refresh ) for eid in self . get_document_eids ( refresh = refresh ) ] |
def get_iam_policy ( self , client = None ) :
"""Retrieve the IAM policy for the bucket .
See
https : / / cloud . google . com / storage / docs / json _ api / v1 / buckets / getIamPolicy
If : attr : ` user _ project ` is set , bills the API request to that project .
: type client : : class : ` ~ google . cl... | client = self . _require_client ( client )
query_params = { }
if self . user_project is not None :
query_params [ "userProject" ] = self . user_project
info = client . _connection . api_request ( method = "GET" , path = "%s/iam" % ( self . path , ) , query_params = query_params , _target_object = None , )
return Po... |
def _validate_inputs ( actual_inputs , required_inputs , keypath = None ) :
"""Validate inputs . Raise exception if something is missing .
args :
actual _ inputs : the object / dictionary passed to a subclass of
PublishablePayload
required _ inputs : the object / dictionary containing keys ( and subkeys )
... | actual_keys = set ( actual_inputs . keys ( ) )
required_keys = set ( required_inputs . keys ( ) )
if actual_keys . intersection ( required_keys ) != required_keys :
prefix = '%s.' if keypath else ''
output_keys = { '%s%s' % ( prefix , key ) for key in required_keys }
raise Exception ( "Missing input fields.... |
def export ( target_folder , source_folders = None , class_type = 'all' , raise_errors = False ) :
"""exports the existing scripts / instruments ( future : probes ) into folder as . b26 files
Args :
target _ folder : target location of created . b26 script files
source _ folder : singel path or list of paths ... | if class_type not in ( 'all' , 'scripts' , 'instruments' , 'probes' ) :
print ( 'unknown type to export' )
return
if not os . path . isdir ( target_folder ) :
try :
os . mkdir ( target_folder )
except :
print ( ( target_folder , ' is invalid target folder' ) )
target_folder = Non... |
def _handle_job_set ( function ) :
"""A decorator for handling ` taskhandle . JobSet ` \ s
A decorator for handling ` taskhandle . JobSet ` \ s for ` do ` and ` undo `
methods of ` Change ` \ s .""" | def call ( self , job_set = taskhandle . NullJobSet ( ) ) :
job_set . started_job ( str ( self ) )
function ( self )
job_set . finished_job ( )
return call |
def _GetSupportedFilesInDir ( self , fileDir , fileList , supportedFormatList , ignoreDirList ) :
"""Recursively get all supported files given a root search directory .
Supported file extensions are given as a list , as are any directories which
should be ignored .
The result will be appended to the given fil... | goodlogging . Log . Info ( "CLEAR" , "Parsing file directory: {0}" . format ( fileDir ) )
if os . path . isdir ( fileDir ) is True :
for globPath in glob . glob ( os . path . join ( fileDir , '*' ) ) :
if util . FileExtensionMatch ( globPath , supportedFormatList ) :
newFile = tvfile . TVFile ( ... |
def _derive_charge ( self , config ) :
"""Use a temperature window to identify the roast charge .
The charge will manifest as a sudden downward trend on the temperature .
Once found , we save it and avoid overwriting . The charge is needed in
order to derive the turning point .
: param config : Current snap... | if self . _roast . get ( 'charge' ) :
return None
self . _window . append ( config )
time , temp = list ( ) , list ( )
for x in list ( self . _window ) :
time . append ( x [ 'time' ] )
temp . append ( x [ 'bean_temp' ] )
slope , intercept , r_value , p_value , std_err = linregress ( time , temp )
if slope <... |
def flatten_array ( grid ) :
"""Takes a multi - dimensional array and returns a 1 dimensional array with the
same contents .""" | grid = [ grid [ i ] [ j ] for i in range ( len ( grid ) ) for j in range ( len ( grid [ i ] ) ) ]
while type ( grid [ 0 ] ) is list :
grid = flatten_array ( grid )
return grid |
def getPerfInfo ( rh , useridlist ) :
"""Get the performance information for a userid
Input :
Request Handle
Userid to query < - may change this to a list later .
Output :
Dictionary containing the following :
overallRC - overall return code , 0 : success , non - zero : failure
rc - RC returned from S... | rh . printSysLog ( "Enter vmUtils.getPerfInfo, userid: " + useridlist )
parms = [ "-T" , rh . userid , "-c" , "1" ]
results = invokeSMCLI ( rh , "Image_Performance_Query" , parms )
if results [ 'overallRC' ] != 0 : # SMCLI failed .
rh . printLn ( "ES" , results [ 'response' ] )
rh . printSysLog ( "Exit vmUtils.... |
def to_primitive ( self , context = None ) :
""". . versionadded : : 1.3.0""" | primitive = super ( ValueConstant , self ) . to_primitive ( context )
value = self . value
if hasattr ( value , 'isoformat' ) :
value = value . isoformat ( )
elif callable ( value ) :
value = value ( )
primitive [ 'value' ] = value
return primitive |
def init_original_response ( self ) :
"""Get the original response for comparing , confirm is _ cookie _ necessary""" | no_cookie_resp = None
self . is_cookie_necessary = True
if 'json' in self . request :
self . request [ 'data' ] = json . dumps ( self . request . pop ( 'json' ) ) . encode ( self . encoding )
r1 = self . req . request ( retry = self . retry , timeout = self . timeout , ** self . request )
if 'headers' in self . req... |
def lowercase ( self ) :
"""Lowercase all strings in this tree .
Works recursively and in - place .""" | if len ( self . children ) > 0 :
for child in self . children :
child . lowercase ( )
else :
self . text = self . text . lower ( ) |
def communityvisibilitystate ( self ) :
"""Return the Visibility State of the Users Profile""" | if self . _communityvisibilitystate == None :
return None
elif self . _communityvisibilitystate in self . VisibilityState :
return self . VisibilityState [ self . _communityvisibilitystate ]
else : # Invalid State
return None |
def imagetransformer_b12l_4h_b128_uncond_dr03_tpu ( ) :
"""TPU config for cifar 10.""" | hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet ( )
update_hparams_for_tpu ( hparams )
hparams . batch_size = 2
hparams . num_heads = 4
# heads are expensive on tpu
hparams . num_decoder_layers = 12
hparams . block_length = 128
hparams . hidden_size = 256
hparams . filter_size = 2048
hparams . layer_preproce... |
def _reset_bbox ( self ) :
"""This function should only be called internally . It resets
the viewers bounding box based on changes to pan or scale .""" | scale_x , scale_y = self . get_scale_xy ( )
pan_x , pan_y = self . get_pan ( coord = 'data' ) [ : 2 ]
win_wd , win_ht = self . get_window_size ( )
# NOTE : need to set at least a minimum 1 - pixel dimension on
# the window or we get a scale calculation exception . See github
# issue 431
win_wd , win_ht = max ( 1 , win_... |
def getPythonVarName ( name ) :
"""Get the python variable name""" | return SUB_REGEX . sub ( '' , name . replace ( '+' , '_' ) . replace ( '-' , '_' ) . replace ( '.' , '_' ) . replace ( ' ' , '' ) . replace ( '/' , '_' ) ) . upper ( ) |
def childKeys ( self ) :
"""Returns the list of child keys for this settings instance .
: return [ < str > , . . ]""" | if self . _customFormat :
return self . _customFormat . childKeys ( )
else :
return super ( XSettings , self ) . childKeys ( ) |
def update_entry_line ( self , key = None ) :
"""Updates the entry line
Parameters
key : 3 - tuple of Integer , defaults to current cell
\t Cell to which code the entry line is updated""" | if key is None :
key = self . actions . cursor
cell_code = self . GetTable ( ) . GetValue ( * key )
post_command_event ( self , self . EntryLineMsg , text = cell_code ) |
def register ( self , request , ** kwargs ) :
"""Create and immediately log in a new user .
Only require a email to register , username is generated
automatically and a password is random generated and emailed
to the user .
Activation is still required for account uses after specified number
of days .""" | if Site . _meta . installed :
site = Site . objects . get_current ( )
else :
site = RequestSite ( request )
email = kwargs [ 'email' ]
# Generate random password
password = User . objects . make_random_password ( )
# Generate username based off of the email supplied
username = sha_constructor ( str ( email ) ) ... |
def _evaluate ( self , R , z , phi = 0. , t = 0. ) :
"""NAME :
_ evaluate
PURPOSE :
evaluate the potential at R , z , phi
INPUT :
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT :
Phi ( R , z , phi )
HISTORY :
2011-04-10 - Started - Bovy ( NYU )
2018... | # Cylindrical distance
Rdist = _cylR ( R , phi , self . _orb . R ( t ) , self . _orb . phi ( t ) )
# Evaluate potential
return evaluatePotentials ( self . _pot , Rdist , self . _orb . z ( t ) - z , use_physical = False ) |
def atlas_inventory_count_missing ( inv1 , inv2 ) :
"""Find out how many bits are set in inv2
that are not set in inv1.""" | count = 0
common = min ( len ( inv1 ) , len ( inv2 ) )
for i in xrange ( 0 , common ) :
for j in xrange ( 0 , 8 ) :
if ( ( 1 << ( 7 - j ) ) & ord ( inv2 [ i ] ) ) != 0 and ( ( 1 << ( 7 - j ) ) & ord ( inv1 [ i ] ) ) == 0 :
count += 1
if len ( inv1 ) < len ( inv2 ) :
for i in xrange ( len ( i... |
def _ParseDocstring ( function ) :
"""Parses the functions docstring into a dictionary of type checks .""" | if not function . __doc__ :
return { }
type_check_dict = { }
for match in param_regexp . finditer ( function . __doc__ ) :
param_str = match . group ( 1 ) . strip ( )
param_splitted = param_str . split ( " " )
if len ( param_splitted ) >= 2 :
type_str = " " . join ( param_splitted [ : - 1 ] )
... |
async def send ( self , metric ) :
"""Transform metric to JSON bytestring and send to server .
Args :
metric ( dict ) : Complete metric to send as JSON .""" | message = json . dumps ( metric ) . encode ( 'utf-8' )
await self . loop . create_datagram_endpoint ( lambda : UDPClientProtocol ( message ) , remote_addr = ( self . ip , self . port ) ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.