signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_permissions ( FunctionName , Qualifier = None , region = None , key = None , keyid = None , profile = None ) :
'''Get resource permissions for the given lambda function
Returns dictionary of permissions , by statement ID
CLI Example :
. . code - block : : bash
salt myminion boto _ lamba . get _ perm... | try :
conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
kwargs = { }
if Qualifier is not None :
kwargs [ 'Qualifier' ] = Qualifier
# The get _ policy call is not symmetric with add / remove _ permissions . So
# massage it until it is , for better ease of us... |
def t_ARTICLEHEADER ( self , token ) : # \ xef \ xbc \ x9a is the " fullwidth colon " used in Japanese for instance
ur'\ # \ # \ s + < article - ( ? P < number > [ A - Z0-9 ] + ) > < ( ? P < newtag > [ a - zA - Z0-9 - ] + ) > < ( ? P < oldtag > [ a - zA - Z0-9 - ] + ) > [ ] * ( ? P < name > [ ^ \ < ] + ? ) ( ? P < ... | number = token . lexer . lexmatch . group ( "number" ) . decode ( "utf8" )
newtag = token . lexer . lexmatch . group ( "newtag" ) . decode ( "utf8" )
oldtag = token . lexer . lexmatch . group ( "oldtag" ) . decode ( "utf8" )
name = token . lexer . lexmatch . group ( "name" ) . decode ( "utf8" )
sep = token . lexer . le... |
def update_ports ( self , ports , id_or_uri , timeout = - 1 ) :
"""Updates the interconnect ports .
Args :
id _ or _ uri : Can be either the interconnect id or the interconnect uri .
ports ( list ) : Ports to update .
timeout : Timeout in seconds . Wait for task completion by default . The timeout does not ... | resources = merge_default_values ( ports , { 'type' : 'port' } )
uri = self . _client . build_uri ( id_or_uri ) + "/update-ports"
return self . _client . update ( resources , uri , timeout ) |
def get_themes_directory ( theme_name = None , png = False ) :
"""Return an absolute path the to / themes directory""" | dir_themes = os . path . join ( get_file_directory ( ) , "themes" )
if theme_name is None :
return dir_themes
if theme_name in os . listdir ( dir_themes ) :
return dir_themes
dir = "png" if png is True else "gif"
return os . path . join ( get_file_directory ( ) , dir ) |
def list_ ( ) :
'''List installed Perl modules , and the version installed
CLI Example :
. . code - block : : bash
salt ' * ' cpan . list''' | ret = { }
cmd = 'cpan -l'
out = __salt__ [ 'cmd.run' ] ( cmd ) . splitlines ( )
for line in out :
comps = line . split ( )
ret [ comps [ 0 ] ] = comps [ 1 ]
return ret |
def extendable ( network , args , line_max ) :
"""Function that sets selected components extendable
' network ' for all lines , links and transformers
' german _ network ' for all lines , links and transformers located in Germany
' foreign _ network ' for all foreign lines , links and transformers
' transfo... | if 'network' in args [ 'extendable' ] :
network . lines . s_nom_extendable = True
network . lines . s_nom_min = network . lines . s_nom
if not line_max == None :
network . lines . s_nom_max = line_max * network . lines . s_nom
else :
network . lines . s_nom_max = float ( "inf" )
if n... |
def create_response ( self , data = None ) :
"""Create a response frame based on this frame .
: param data : Data section of response as bytearray . If None , request data section is kept .
: return : ModbusTCPFrame instance that represents a response""" | frame = deepcopy ( self )
if data is not None :
frame . data = data
frame . length = 2 + len ( frame . data )
return frame |
def _write_json ( obj , path ) : # type : ( object , str ) - > None
"""Writes a serializeable object as a JSON file""" | with open ( path , 'w' ) as f :
json . dump ( obj , f ) |
def chat ( self , message ) :
"""Send chat message as a broadcast .""" | if message :
action_chat = sc_pb . ActionChat ( channel = sc_pb . ActionChat . Broadcast , message = message )
action = sc_pb . Action ( action_chat = action_chat )
return self . act ( action ) |
def save_token ( self , access_token ) :
"""Stores the access token and additional data in redis .
See : class : ` oauth2 . store . AccessTokenStore ` .""" | self . write ( access_token . token , access_token . __dict__ )
unique_token_key = self . _unique_token_key ( access_token . client_id , access_token . grant_type , access_token . user_id )
self . write ( unique_token_key , access_token . __dict__ )
if access_token . refresh_token is not None :
self . write ( acces... |
def start_debugging ( ) :
"""Start a debugging session after catching an exception .
This prints the traceback and start ipdb session in the frame of the error .""" | exc_type , exc_value , exc_tb = sys . exc_info ( )
# If the exception has been annotated to be re - raised , raise the exception
if hasattr ( exc_value , '_ipdbugger_let_raise' ) :
raise_ ( * sys . exc_info ( ) )
print ( )
for line in traceback . format_exception ( exc_type , exc_value , exc_tb ) :
print ( colo... |
def y_subset ( y , query = None , aux = None , subset = None , dropna = False , outcome = 'true' , k = None , p = None , ascending = False , score = 'score' , p_of = 'notnull' ) :
"""Subset a model " y " dataframe
Args :
query : operates on y , or aux if present
subset : takes a dataframe or index thereof and... | if query is not None :
if aux is None :
y = y . query ( query )
else :
s = aux . ix [ y . index ]
if len ( s ) != len ( y ) :
logging . warning ( 'y not a subset of aux' )
y = y . ix [ s . query ( query ) . index ]
if subset is not None :
if hasattr ( subset , 'in... |
def replace_route ( route_table_id = None , destination_cidr_block = None , route_table_name = None , gateway_id = None , instance_id = None , interface_id = None , region = None , key = None , keyid = None , profile = None , vpc_peering_connection_id = None ) :
'''Replaces a route .
CLI Example :
. . code - bl... | if not _exactly_one ( ( route_table_name , route_table_id ) ) :
raise SaltInvocationError ( 'One (but not both) of route_table_id or route_table_name ' 'must be provided.' )
if destination_cidr_block is None :
raise SaltInvocationError ( 'destination_cidr_block is required.' )
try :
if route_table_name :
... |
def parse_chinese_morphemes ( seq , context = False ) :
"""Parse a Chinese syllable and return its basic structure .""" | # get the tokens
if isinstance ( seq , list ) :
tokens = [ s for s in seq ]
else :
tokens = lingpy . ipa2tokens ( seq , merge_vowels = False )
# get the sound classes according to the art - model
arts = [ int ( x ) for x in lingpy . tokens2class ( tokens , _art , cldf = True ) ]
# get the pro - string
prostring... |
def evaluate_inline_tail ( self , groups ) :
"""Evaluate inline comments at the tail of source code .""" | if self . lines :
self . line_comments . append ( [ groups [ 'line' ] [ 2 : ] . replace ( '\\\n' , '' ) , self . line_num , self . current_encoding ] ) |
def create ( self , fields ) :
"""Create the object only once .
So , you need loop to usage .
: param ` fields ` is dictionary fields .""" | try : # Cleaning the fields , and check if has ` ForeignKey ` type .
cleaned_fields = { }
for key , value in fields . items ( ) :
if type ( value ) is dict :
try :
if value [ 'type' ] == 'fk' :
fake_fk = self . fake_fk ( value [ 'field_name' ] )
... |
def PhenomModel ( self , r ) :
"""Fit to field map
A phenomenological fit by Ryan Bayes ( Glasgow ) to a field map
generated by Bob Wands ( FNAL ) . It assumes a 1 cm plate . This is dated
January 30th , 2012 . Not defined for r < = 0""" | if r <= 0 :
raise ValueError
field = self . B0 + self . B1 * G4 . m / r + self . B2 * math . exp ( - 1 * self . H * r / G4 . m )
return field |
def _calibrate_ir ( radiance , coefs ) :
"""Convert IR radiance to brightness temperature
Reference : [ IR ]
Args :
radiance : Radiance [ mW m - 2 cm - 1 sr - 1]
coefs : Dictionary of calibration coefficients . Keys :
n : The channel ' s central wavenumber [ cm - 1]
a : Offset [ K ]
b : Slope [ 1]
b... | logger . debug ( 'Calibrating to brightness temperature' )
# Compute brightness temperature using inverse Planck formula
n = coefs [ 'n' ]
bteff = C2 * n / xu . log ( 1 + C1 * n ** 3 / radiance . where ( radiance > 0 ) )
bt = xr . DataArray ( bteff * coefs [ 'b' ] + coefs [ 'a' ] )
# Apply BT threshold
return bt . wher... |
def setDeviceID ( self , value , device = DEFAULT_DEVICE_ID , message = True ) :
"""Set the hardware device number . This is only needed if more that one
device is on the same serial buss .
: Parameters :
value : ` int `
The device ID to set in the range of 0 - 127.
: Keywords :
device : ` int `
The d... | return self . _setDeviceID ( value , device , message ) |
def propagate ( p0 , angle , d , deg = True , bearing = False , r = r_earth_mean ) :
"""Given an initial point and angle , move distance d along the surface
Parameters
p0 : point - like ( or array of point - like ) [ lon , lat ] objects
angle : float ( or array of float )
bearing . Note that by default , 0 ... | single , ( p0 , angle , d ) = _to_arrays ( ( p0 , 2 ) , ( angle , 1 ) , ( d , 1 ) )
if deg :
p0 = np . radians ( p0 )
angle = np . radians ( angle )
if not bearing :
angle = np . pi / 2.0 - angle
lon0 , lat0 = p0 [ : , 0 ] , p0 [ : , 1 ]
angd = d / r
lat1 = arcsin ( sin ( lat0 ) * cos ( angd ) + cos ( lat0 ... |
def compare_and_set ( self , expect , update ) :
'''Atomically sets the value to ` update ` if the current value is equal to
` expect ` .
: param expect : The expected current value .
: param update : The value to set if and only if ` expect ` equals the
current value .''' | with self . _reference . get_lock ( ) :
if self . _reference . value == expect :
self . _reference . value = update
return True
return False |
def graph_from_dot_file ( path , encoding = None ) :
"""Load graphs from DOT file at ` path ` .
@ param path : to DOT file
@ param encoding : as passed to ` io . open ` .
For example , ` ' utf - 8 ' ` .
@ return : Graphs that result from parsing .
@ rtype : ` list ` of ` pydot . Dot `""" | with io . open ( path , 'rt' , encoding = encoding ) as f :
s = f . read ( )
if not PY3 :
s = unicode ( s )
graphs = graph_from_dot_data ( s )
return graphs |
def GET_blockchain_num_subdomains ( self , path_info , blockchain_name ) :
"""Handle GET / blockchains / : blockchainID / subdomains _ count
Takes ` all = true ` to include expired names
Reply with the number of names on this blockchain""" | if blockchain_name != 'bitcoin' : # not supported
self . _reply_json ( { 'error' : 'Unsupported blockchain' } , status_code = 404 )
return
blockstackd_url = get_blockstackd_url ( )
num_names = blockstackd_client . get_num_subdomains ( hostport = blockstackd_url )
if json_is_error ( num_names ) :
if json_is_... |
def watcher ( self ) -> Watcher :
"""Gives an access to action ' s watcher .
: return : Action ' s watcher instance .""" | if not hasattr ( self , "_watcher" ) :
self . _watcher = Watcher ( )
return self . _watcher |
def purge_old_logs ( delete_before_days = 7 ) :
"""Purges old logs from the database table""" | delete_before_date = timezone . now ( ) - timedelta ( days = delete_before_days )
logs_deleted = Log . objects . filter ( created_on__lte = delete_before_date ) . delete ( )
return logs_deleted |
def _setattr_url_map ( self ) :
'''Set an attribute on the local instance for each key / val in url _ map
CherryPy uses class attributes to resolve URLs .''' | if self . apiopts . get ( 'enable_sessions' , True ) is False :
url_blacklist = [ 'login' , 'logout' , 'minions' , 'jobs' ]
else :
url_blacklist = [ ]
urls = ( ( url , cls ) for url , cls in six . iteritems ( self . url_map ) if url not in url_blacklist )
for url , cls in urls :
setattr ( self , url , cls (... |
def thumbs_up_songs ( self , * , library = True , store = True ) :
"""Get a listing of ' Thumbs Up ' store songs .
Parameters :
library ( bool , Optional ) : Include ' Thumbs Up ' songs from library .
Default : True
generated ( bool , Optional ) : Include ' Thumbs Up ' songs from store .
Default : True
... | thumbs_up_songs = [ ]
if library is True :
thumbs_up_songs . extend ( song for song in self . songs ( ) if song . get ( 'rating' , '0' ) == '5' )
if store is True :
response = self . _call ( mc_calls . EphemeralTop )
thumbs_up_songs . extend ( response . body . get ( 'data' , { } ) . get ( 'items' , [ ] ) )... |
def setRoute ( self , vehID , edgeList ) :
"""setRoute ( string , list ) - > None
changes the vehicle route to given edges list .
The first edge in the list has to be the one that the vehicle is at at the moment .
example usage :
setRoute ( ' 1 ' , [ ' 1 ' , ' 2 ' , ' 4 ' , ' 6 ' , ' 7 ' ] )
this changes ... | if isinstance ( edgeList , str ) :
edgeList = [ edgeList ]
self . _connection . _beginMessage ( tc . CMD_SET_VEHICLE_VARIABLE , tc . VAR_ROUTE , vehID , 1 + 4 + sum ( map ( len , edgeList ) ) + 4 * len ( edgeList ) )
self . _connection . _packStringList ( edgeList )
self . _connection . _sendExact ( ) |
def init ( options ) :
"""Initialize some defaults""" | # Set matlplotlib ' s backend so LIVVkit can plot to files .
import matplotlib
matplotlib . use ( 'agg' )
livvkit . output_dir = os . path . abspath ( options . out_dir )
livvkit . index_dir = livvkit . output_dir
livvkit . verify = True if options . verify is not None else False
livvkit . validate = True if options . ... |
def get_components_for_species ( alignment , species ) :
"""Return the component for each species in the list ` species ` or None""" | # If the number of components in the alignment is less that the requested number
# of species we can immediately fail
if len ( alignment . components ) < len ( species ) :
return None
# Otherwise , build an index of components by species , then lookup
index = dict ( [ ( c . src . split ( '.' ) [ 0 ] , c ) for c in ... |
def draw_path_collection ( self , paths , path_coordinates , path_transforms , offsets , offset_coordinates , offset_order , styles , mplobj = None ) :
"""Draw a collection of paths . The paths , offsets , and styles are all
iterables , and the number of paths is max ( len ( paths ) , len ( offsets ) ) .
By def... | if offset_order == "before" :
raise NotImplementedError ( "offset before transform" )
for tup in self . _iter_path_collection ( paths , path_transforms , offsets , styles ) :
( path , path_transform , offset , ec , lw , fc ) = tup
vertices , pathcodes = path
path_transform = transforms . Affine2D ( path... |
def _create_initial_state ( self , ip , jumpkind ) :
"""Obtain a SimState object for a specific address
Fastpath means the CFG generation will work in an IDA - like way , in which it will not try to execute every
single statement in the emulator , but will just do the decoding job . This is much faster than the... | jumpkind = "Ijk_Boring" if jumpkind is None else jumpkind
if self . _initial_state is None :
state = self . project . factory . blank_state ( addr = ip , mode = "fastpath" , add_options = self . _state_add_options , remove_options = self . _state_remove_options , )
self . _initial_state = state
else : # FIXME :... |
def agg_wt_avg ( mat , min_wt = 0.01 , corr_metric = 'spearman' ) :
'''Aggregate a set of replicate profiles into a single signature using
a weighted average .
Args :
mat ( pandas df ) : a matrix of replicate profiles , where the columns are
samples and the rows are features ; columns correspond to the
re... | assert mat . shape [ 1 ] > 0 , "mat is empty! mat: {}" . format ( mat )
if mat . shape [ 1 ] == 1 :
out_sig = mat
upper_tri_df = None
raw_weights = None
weights = None
else :
assert corr_metric in [ "spearman" , "pearson" ]
# Make correlation matrix column wise
corr_mat = mat . corr ( method... |
def _release_version ( ) :
'''Returns release version''' | with io . open ( os . path . join ( SETUP_DIRNAME , 'saltpylint' , 'version.py' ) , encoding = 'utf-8' ) as fh_ :
exec_locals = { }
exec_globals = { }
contents = fh_ . read ( )
if not isinstance ( contents , str ) :
contents = contents . encode ( 'utf-8' )
exec ( contents , exec_globals , ex... |
def _is_null_value ( self , value ) :
"""Check if a given value is ` ` null ` ` .
Criteria for this is based on values that shouldn ' t be included
in the Solr ` ` add ` ` request at all .""" | if value is None :
return True
if IS_PY3 : # Python 3 . X
if isinstance ( value , str ) and len ( value ) == 0 :
return True
else : # Python 2 . X
if isinstance ( value , basestring ) and len ( value ) == 0 : # NOQA : F821
return True
# TODO : This should probably be removed when solved in c... |
def overlay_spectra ( model , dataset ) :
"""Run a series of diagnostics on the fitted spectra
Parameters
model : model
best - fit Cannon spectral model
dataset : Dataset
original spectra""" | best_flux , best_ivar = draw_spectra ( model , dataset )
coeffs_all , covs , scatters , all_chisqs , pivots , label_vector = model . model
# Overplot original spectra with best - fit spectra
print ( "Overplotting spectra for ten random stars" )
res = dataset . test_flux - best_flux
lambdas = dataset . wl
npix = len ( l... |
def integer_merge ( number_list ) :
"""A Python function to transform a list of multiple integers into a single combined integer .
> > > integer _ merge ( [ 1 , 2 , 3 ] )
123
> > > integer _ merge ( [ 4 , 5 , 6 ] )
456
> > > integer _ merge ( [ 7 , 8 , 9 ] )
789""" | string_list = [ str ( num ) for num in number_list ]
unified_number = int ( '' . join ( string_list ) )
return unified_number |
def _set_inspection ( self , v , load = False ) :
"""Setter method for inspection , mapped from YANG variable / interface / port _ channel / ip / arp / inspection ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ inspection is considered as a private
metho... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = inspection . inspection , is_container = 'container' , presence = False , yang_name = "inspection" , rest_name = "inspection" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_pa... |
def get_canonical_correlations ( dataframe , column_types ) :
'''computes the correlation coefficient between each distinct pairing of columns
preprocessing note :
any rows with missing values ( in either paired column ) are dropped for that pairing
categorical columns are replaced with one - hot encoded colu... | def preprocess ( series ) :
if column_types [ series . name ] == 'CATEGORICAL' :
series = pd . get_dummies ( series )
array = series . values . reshape ( series . shape [ 0 ] , - 1 )
return array
if dataframe . shape [ 1 ] < 2 :
return [ ]
correlations = [ ]
skip_cols = set ( )
for col_name_i , ... |
def put ( self , destination ) :
"""Copy the referenced directory to this path
The semantics of this command are similar to unix ` ` cp ` ` : if ` ` destination ` ` already
exists , the copied directory will be put at ` ` [ destination ] / / [ basename ( localpath ) ] ` ` . If
it does not already exist , the ... | target = get_target_path ( destination , self . localpath )
shutil . copytree ( self . localpath , target ) |
def serialize ( self , message ) :
"""Serialize the given message in - place , converting inputs to outputs .
We do this in - place for performance reasons . There are more fields in
a message than there are L { Field } objects because of the timestamp ,
task _ level and task _ uuid fields . By only iterating... | for key , field in self . fields . items ( ) :
message [ key ] = field . serialize ( message [ key ] ) |
def unregister_signals_oaiset ( self ) :
"""Unregister signals oaiset .""" | from . models import OAISet
from . receivers import after_insert_oai_set , after_update_oai_set , after_delete_oai_set
if contains ( OAISet , 'after_insert' , after_insert_oai_set ) :
remove ( OAISet , 'after_insert' , after_insert_oai_set )
remove ( OAISet , 'after_update' , after_update_oai_set )
remove (... |
def decode_tx_packet ( packet : str ) -> dict :
"""Break packet down into primitives , and do basic interpretation .
> > > decode _ packet ( ' 10 ; Kaku ; ID = 41 ; SWITCH = 1 ; CMD = ON ; ' ) = = {
. . . ' node ' : ' gateway ' ,
. . . ' protocol ' : ' kaku ' ,
. . . ' id ' : ' 000041 ' ,
. . . ' switch '... | node_id , protocol , attrs = packet . split ( DELIM , 2 )
data = cast ( Dict [ str , Any ] , { 'node' : PacketHeader ( node_id ) . name , } )
data [ 'protocol' ] = protocol . lower ( )
for i , attr in enumerate ( filter ( None , attrs . strip ( DELIM ) . split ( DELIM ) ) ) :
if i == 0 :
data [ 'id' ] = att... |
def modify_number_pattern ( number_pattern , ** kwargs ) :
"""Modifies a number pattern by specified keyword arguments .""" | params = [ 'pattern' , 'prefix' , 'suffix' , 'grouping' , 'int_prec' , 'frac_prec' , 'exp_prec' , 'exp_plus' ]
for param in params :
if param in kwargs :
continue
kwargs [ param ] = getattr ( number_pattern , param )
return NumberPattern ( ** kwargs ) |
def evaluate_strings ( self , groups ) :
"""Evaluate strings .""" | if self . strings :
encoding = self . current_encoding
if self . generic_mode : # Generic assumes no escapes rules .
self . quoted_strings . append ( [ groups [ 'strings' ] [ 1 : - 1 ] , self . line_num , encoding ] )
else :
value = groups [ 'strings' ]
stype = set ( )
if val... |
def tokenize_sentences ( self , untokenized_string : str ) :
"""Tokenize sentences by reading trained tokenizer and invoking
` ` PunktSentenceTokenizer ( ) ` ` .
: type untokenized _ string : str
: param untokenized _ string : A string containing one of more sentences .
: rtype : list of strings""" | # load tokenizer
assert isinstance ( untokenized_string , str ) , 'Incoming argument must be a string.'
if self . language == 'latin' :
self . models_path = self . _get_models_path ( self . language )
try :
self . model = open_pickle ( os . path . expanduser ( os . path . join ( self . models_path , 'la... |
def form ( ** kwargs : Question ) :
"""Create a form with multiple questions .
The parameter name of a question will be the key for the answer in
the returned dict .""" | return Form ( * ( FormField ( k , q ) for k , q in kwargs . items ( ) ) ) |
def _condition_to_tag_check ( self , sample , base_sc_name , mapping , scraper_config , tags = None ) :
"""Metrics from kube - state - metrics have changed
For example :
kube _ node _ status _ condition { condition = " Ready " , node = " ip - 172-33-39-189 . eu - west - 1 . compute " , status = " true " } 1
k... | if bool ( sample [ self . SAMPLE_VALUE ] ) is False :
return
# Ignore if gauge is not 1 and we are not processing the pod phase check
label_value , condition_map = self . _get_metric_condition_map ( base_sc_name , sample [ self . SAMPLE_LABELS ] )
service_check_name = condition_map [ 'service_check_name' ]
mapping ... |
def get_authorization ( self , request ) :
"""This function extracts the authorization JWT string . It first
looks for specified key in header and then looks
for the same in body part .
Parameters
request : HttpRequest
This is the raw request that user has sent .
Returns
auth : str
Return request ' ... | from django . utils . six import text_type
from rest_framework import HTTP_HEADER_ENCODING
auth = request . data . get ( self . key , b'' ) or request . META . get ( self . header_key , b'' )
if isinstance ( auth , text_type ) : # Work around django test client oddness
auth = auth . encode ( HTTP_HEADER_ENCODING )
... |
def get_input ( problem ) :
"""" Returns the specified problem answer in the form
problem : problem id
Returns string , or bytes if a file is loaded""" | input_data = load_input ( )
pbsplit = problem . split ( ":" )
problem_input = input_data [ 'input' ] [ pbsplit [ 0 ] ]
if isinstance ( problem_input , dict ) and "filename" in problem_input and "value" in problem_input :
if len ( pbsplit ) > 1 and pbsplit [ 1 ] == 'filename' :
return problem_input [ "filena... |
def _call ( self , coeffs ) :
"""Return the inverse wavelet transform of ` ` coeffs ` ` .""" | if self . impl == 'pywt' :
coeffs = pywt . unravel_coeffs ( coeffs , coeff_slices = self . _coeff_slices , coeff_shapes = self . _coeff_shapes , output_format = 'wavedecn' )
recon = pywt . waverecn ( coeffs , wavelet = self . pywt_wavelet , mode = self . pywt_pad_mode , axes = self . axes )
recon_shape = se... |
def _ResolveRelativeImport ( name , package ) :
"""Resolves a relative import into an absolute path .
This is mostly an adapted version of the logic found in the backported
version of import _ module in Python 2.7.
https : / / github . com / python / cpython / blob / 2.7 / Lib / importlib / _ _ init _ _ . py ... | level = sum ( 1 for c in itertools . takewhile ( lambda c : c == '.' , name ) )
if level == 1 :
return package + name
else :
parts = package . split ( '.' ) [ : - ( level - 1 ) ]
if not parts :
return None
parts . append ( name [ level : ] )
return '.' . join ( parts ) |
def setup_and_run_analysis ( self ) :
"""Execute analysis after the tab is displayed .
Please check the code in dock . py accept ( ) . It should follow
approximately the same code .""" | self . show_busy ( )
# Read user ' s settings
self . read_settings ( )
# Prepare impact function from wizard dialog user input
self . impact_function = self . prepare_impact_function ( )
# Prepare impact function
status , message = self . impact_function . prepare ( )
message = basestring_to_message ( message )
# Check... |
def cumstd ( expr , sort = None , ascending = True , unique = False , preceding = None , following = None ) :
"""Calculate cumulative standard deviation of a sequence expression .
: param expr : expression for calculation
: param sort : name of the sort column
: param ascending : whether to sort in ascending ... | data_type = _stats_type ( expr )
return _cumulative_op ( expr , CumStd , sort = sort , ascending = ascending , unique = unique , preceding = preceding , following = following , data_type = data_type ) |
def list_pkgs ( versions_as_list = False , ** kwargs ) :
'''List the packages currently installed in a dict : :
{ ' < package _ name > ' : ' < version > ' }
CLI Example :
. . code - block : : bash
salt ' * ' pkg . list _ pkgs''' | versions_as_list = salt . utils . data . is_true ( versions_as_list )
# not yet implemented or not applicable
if any ( [ salt . utils . data . is_true ( kwargs . get ( x ) ) for x in ( 'removed' , 'purge_desired' ) ] ) :
return { }
if 'pkg.list_pkgs' in __context__ :
if versions_as_list :
return __conte... |
def stack_outputs ( self , name ) :
"""Given a name , describes CloudFront stacks and returns dict of the stack Outputs
, else returns an empty dict .""" | try :
stack = self . cf_client . describe_stacks ( StackName = name ) [ 'Stacks' ] [ 0 ]
return { x [ 'OutputKey' ] : x [ 'OutputValue' ] for x in stack [ 'Outputs' ] }
except botocore . client . ClientError :
return { } |
def initialize ( self , * args , ** kwargs ) :
"""Call self . _ initialize with ` self ` made available to Zipline API
functions .""" | with ZiplineAPI ( self ) :
self . _initialize ( self , * args , ** kwargs ) |
def settle ( self ) :
"""收盘后的结算事件""" | self . volume_long_his += self . volume_long_today
self . volume_long_today = 0
self . volume_long_frozen_today = 0
self . volume_short_his += self . volume_short_today
self . volume_short_today = 0
self . volume_short_frozen_today = 0 |
def from_interval ( self , startnote , shorthand , up = True ) :
"""Shortcut to from _ interval _ shorthand .""" | return self . from_interval_shorthand ( startnote , shorthand , up ) |
def show ( self ) :
"""This could use some love , it ' s currently here as reference""" | for entry in self . _entries :
print "{'%s': %s, 'records': %s}" % ( entry . _record_type , entry . host , entry . records )
print |
def delete ( self , cascade_delete = None , access_key = None , secret_key = None , verbose = None , debug = None , retries = None , headers = None ) :
"""Delete a file from the Archive . Note : Some files - - such as
< itemname > _ meta . xml - - cannot be deleted .
: type cascade _ delete : bool
: param cas... | cascade_delete = '0' if not cascade_delete else '1'
access_key = self . item . session . access_key if not access_key else access_key
secret_key = self . item . session . secret_key if not secret_key else secret_key
debug = False if not debug else debug
verbose = False if not verbose else verbose
max_retries = 2 if ret... |
def lhoodplot ( self , trsig = None , fig = None , piechart = True , figsize = None , logscale = True , constraints = 'all' , suptitle = None , Ltot = None , maxdur = None , maxslope = None , inverse = False , colordict = None , cachefile = None , nbins = 20 , dur_range = None , slope_range = None , depth_range = None ... | setfig ( fig , figsize = figsize )
if trsig is not None :
dep , ddep = trsig . logdepthfit
dur , ddur = trsig . durfit
slope , dslope = trsig . slopefit
ddep = ddep . reshape ( ( 2 , 1 ) )
ddur = ddur . reshape ( ( 2 , 1 ) )
dslope = dslope . reshape ( ( 2 , 1 ) )
if dur_range is None :
... |
def __addNode ( self , name , cls ) :
'''Add a node to the topology''' | if name in self . nodes :
raise Exception ( "A node by the name {} already exists. Can't add a duplicate." . format ( name ) )
self . __nxgraph . add_node ( name )
self . __nxgraph . node [ name ] [ 'label' ] = name
self . __nxgraph . node [ name ] [ 'nodeobj' ] = cls ( )
self . __nxgraph . node [ name ] [ 'type' ... |
def add_group ( group_name , system_group = False , gid = None ) :
"""Add a group to the system
Will log but otherwise succeed if the group already exists .
: param str group _ name : group to create
: param bool system _ group : Create system group
: param int gid : GID for user being created
: returns :... | try :
group_info = grp . getgrnam ( group_name )
log ( 'group {0} already exists!' . format ( group_name ) )
if gid :
group_info = grp . getgrgid ( gid )
log ( 'group with gid {0} already exists!' . format ( gid ) )
except KeyError :
log ( 'creating group {0}' . format ( group_name ) )
... |
def postprocess ( self ) :
"""Postprocessing includes renaming and gzipping where necessary .
Also copies the magmom to the incar if necessary""" | for f in VASP_OUTPUT_FILES + [ self . output_file ] :
if os . path . exists ( f ) :
if self . final and self . suffix != "" :
shutil . move ( f , "{}{}" . format ( f , self . suffix ) )
elif self . suffix != "" :
shutil . copy ( f , "{}{}" . format ( f , self . suffix ) )
if ... |
def skew ( self ) :
"skewness" | n , a , b = self . n , self . a , self . b
t1 = ( a + b + 2 * n ) * ( b - a ) / ( a + b + 2 )
t2 = sqrt ( ( 1 + a + b ) / ( n * a * b * ( n + a + b ) ) )
return t1 * t2 |
def typos ( self ) :
"""letter combinations one typo away from word""" | return ( self . _deletes ( ) | self . _transposes ( ) | self . _replaces ( ) | self . _inserts ( ) ) |
def get_contract ( self , contract_name : str ) -> Dict :
"""Return ABI , BIN of the given contract .""" | assert self . contracts , 'ContractManager should have contracts compiled'
return self . contracts [ contract_name ] |
def parse_statement ( self , stream ) :
"""Statement : : = AggrGroup
| AggrObject
| AssignmentStmt""" | if self . has_group ( stream ) :
return self . parse_group ( stream )
if self . has_object ( stream ) :
return self . parse_object ( stream )
if self . has_assignment ( stream ) :
return self . parse_assignment ( stream )
if self . has_assignment_symbol ( stream ) :
return self . broken_assignment ( str... |
def all_combinations ( items ) :
"""Generate all combinations of a given list of items .""" | return ( set ( compress ( items , mask ) ) for mask in product ( * [ [ 0 , 1 ] ] * len ( items ) ) ) |
def list_all_available ( self , id_vlan ) :
"""List all environment vips availables
: return : Following dictionary :
{ ' environment _ vip ' : [ { ' id ' : < id > ,
' finalidade _ txt ' : < finalidade _ txt > ,
' cliente _ txt ' : < cliente _ txt > ,
' ambiente _ p44 _ txt ' : < ambiente _ p44 _ txt > } ... | url = 'environmentvip/search/' + str ( id_vlan )
code , xml = self . submit ( None , 'GET' , url )
key = 'environment_vip'
return get_list_map ( self . response ( code , xml , [ key ] ) , key ) |
def headalongline ( self , x , y , layers = None ) :
"""Head along line or curve
Parameters
x : array
x values of line
y : array
y values of line
layers : integer , list or array , optional
layers for which grid is returned
Returns
h : array size ` nlayers , nx `""" | xg , yg = np . atleast_1d ( x ) , np . atleast_1d ( y )
if layers is None :
Nlayers = self . aq . find_aquifer_data ( xg [ 0 ] , yg [ 0 ] ) . naq
else :
Nlayers = len ( np . atleast_1d ( layers ) )
nx = len ( xg )
if len ( yg ) == 1 :
yg = yg * np . ones ( nx )
h = np . zeros ( ( Nlayers , nx ) )
for i in r... |
def create_param_info ( task_params , parameter_map ) :
"""Builds the code block for the GPTool GetParameterInfo method based on the input task _ params .
: param task _ params : A list of task parameters to map to GPTool parameters .
: return : A string representing the code block to the GPTool GetParameterInf... | gp_params = [ ]
gp_param_list = [ ]
gp_param_idx_list = [ ]
gp_param_idx = 0
for task_param in task_params : # Setup to gp _ param dictionary used to substitute against the parameter info template .
gp_param = { }
# Convert DataType
data_type = task_param [ 'type' ] . upper ( )
if 'dimensions' in task_p... |
def to_userdata ( self ) :
"""Return a Userdata dictionary .""" | userdata = Userdata ( { 'd3' : self . memhi , 'd4' : self . memlo , 'd6' : self . control_flags , 'd7' : self . group , 'd8' : self . address . bytes [ 2 ] , 'd9' : self . address . bytes [ 1 ] , 'd10' : self . address . bytes [ 0 ] , 'd11' : self . data1 , 'd12' : self . data2 , 'd13' : self . data3 } )
return userdat... |
def get_imported_data ( csv_file , ** kwargs ) :
"""Reads the content of the Polarion exported csv file and returns imported data .""" | open_args = [ ]
open_kwargs = { }
try : # pylint : disable = pointless - statement
unicode
open_args . append ( "rb" )
except NameError :
open_kwargs [ "encoding" ] = "utf-8"
with open ( os . path . expanduser ( csv_file ) , * open_args , ** open_kwargs ) as input_file :
reader = _get_csv_reader ( input... |
def do_load ( self , filename ) :
"""Load disk image for analysis""" | try :
self . __session . load ( filename )
except IOError as e :
self . logger . error ( e . strerror ) |
def example_write_file_to_disk_if_changed ( ) :
"""Try to remove all comments from a file , and save it if changes were made .""" | my_file = FileAsObj ( '/tmp/example_file.txt' )
my_file . rm ( my_file . egrep ( '^#' ) )
if my_file . changed :
my_file . save ( ) |
def _item_to_bucket ( iterator , item ) :
"""Convert a JSON bucket to the native object .
: type iterator : : class : ` ~ google . api _ core . page _ iterator . Iterator `
: param iterator : The iterator that has retrieved the item .
: type item : dict
: param item : An item to be converted to a bucket .
... | name = item . get ( "name" )
bucket = Bucket ( iterator . client , name )
bucket . _set_properties ( item )
return bucket |
def str_fmthdr ( self , goid , goobj ) :
"""Return hdr line seen inside a GO Term box .""" | # Shorten : Ex : GO : 0007608 - > G0007608
go_txt = goid . replace ( "GO:" , "G" )
if 'mark_alt_id' in self . present and goid != goobj . id :
go_txt += 'a'
return go_txt |
def save_ical ( self , ical_location ) : # type : ( str ) - > None
"""Save the calendar instance to a file""" | data = self . cal . to_ical ( )
with open ( ical_location , 'w' ) as ical_file :
ical_file . write ( data . decode ( 'utf-8' ) ) |
def merge_diff ( initial_config = None , initial_path = None , merge_config = None , merge_path = None , saltenv = 'base' ) :
'''Return the merge diff , as text , after merging the merge config into the
initial config .
initial _ config
The initial configuration sent as text . This argument is ignored when
... | if initial_path :
initial_config = __salt__ [ 'cp.get_file_str' ] ( initial_path , saltenv = saltenv )
candidate_config = merge_text ( initial_config = initial_config , merge_config = merge_config , merge_path = merge_path , saltenv = saltenv )
clean_running_dict = tree ( config = initial_config )
clean_running = _... |
def create_init ( self , path ) : # type : ( str ) - > None
"""Create a minimal _ _ init _ _ file with enough boiler plate to not add to lint messages
: param path :
: return :""" | source = """# coding=utf-8
\"\"\"
Version
\"\"\"
__version__ = \"0.0.0\"
"""
with io . open ( path , "w" , encoding = "utf-8" ) as outfile :
outfile . write ( source ) |
def count_range ( self , txn , from_key , to_key ) :
"""Counter number of records in the perstistent map with keys
within the given range .
: param txn : The transaction in which to run .
: type txn : : class : ` zlmdb . Transaction `
: param from _ key : Count records starting and including from this key .... | key_from = struct . pack ( '>H' , self . _slot ) + self . _serialize_key ( from_key )
to_key = struct . pack ( '>H' , self . _slot ) + self . _serialize_key ( to_key )
cnt = 0
cursor = txn . _txn . cursor ( )
has_more = cursor . set_range ( key_from )
while has_more :
if cursor . key ( ) >= to_key :
break
... |
def change_background ( color ) :
"""Setup the background color to * color * .
Example : :
change _ background ( ' black ' )
change _ background ( ' white ' )
change _ background ( ' # fffff ' )
You can call this function interactively by using : :
change _ color . interactive ( )
A new dialog will po... | viewer . widget . background_color = colors . any_to_rgb ( color )
viewer . update ( ) |
def encode_hdr ( self , boundary ) :
"""Returns the header of the encoding of this parameter""" | boundary = encode_and_quote ( boundary )
headers = [ "--%s" % boundary ]
if self . filename :
disposition = 'form-data; name="%s"; filename="%s"' % ( self . name , self . filename )
else :
disposition = 'form-data; name="%s"' % self . name
headers . append ( "Content-Disposition: %s" % disposition )
if self . f... |
def get_all_resource_data ( scenario_id , include_metadata = 'N' , page_start = None , page_end = None , ** kwargs ) :
"""A function which returns the data for all resources in a network .""" | rs_qry = db . DBSession . query ( ResourceAttr . attr_id , Attr . name . label ( 'attr_name' ) , ResourceAttr . id . label ( 'resource_attr_id' ) , ResourceAttr . ref_key , ResourceAttr . network_id , ResourceAttr . node_id , ResourceAttr . link_id , ResourceAttr . group_id , ResourceAttr . project_id , ResourceAttr . ... |
def dump ( self , path ) :
"""dump DictTree data to json files .""" | try :
with open ( path , "wb" ) as f :
f . write ( self . __str__ ( ) . encode ( "utf-8" ) )
except :
pass
with open ( path , "wb" ) as f :
pickle . dump ( self . __data__ , f ) |
def lens_model_plot ( ax , lensModel , kwargs_lens , numPix = 500 , deltaPix = 0.01 , sourcePos_x = 0 , sourcePos_y = 0 , point_source = False , with_caustics = False ) :
"""plots a lens model ( convergence ) and the critical curves and caustics
: param ax :
: param kwargs _ lens :
: param numPix :
: param ... | kwargs_data = sim_util . data_configure_simple ( numPix , deltaPix )
data = Data ( kwargs_data )
_frame_size = numPix * deltaPix
_coords = data . _coords
x_grid , y_grid = data . coordinates
lensModelExt = LensModelExtensions ( lensModel )
# ra _ crit _ list , dec _ crit _ list , ra _ caustic _ list , dec _ caustic _ l... |
def slice_naive ( self , key ) :
"""Slice a data object based on its index , either by value ( . loc ) or
position ( . iloc ) .
Args :
key : Single index value , slice , tuple , or list of indices / positionals
Returns :
data : Slice of self""" | cls = self . __class__
key = check_key ( self , key )
return cls ( self . loc [ key ] ) |
def is_union ( etype ) -> bool :
"""Determine whether etype is a Union""" | return getattr ( etype , '__origin__' , None ) is not None and getattr ( etype . __origin__ , '_name' , None ) and etype . __origin__ . _name == 'Union' |
def get_end_time ( self ) :
"""Get observation end time from file metadata .""" | mda_dict = self . filehandle . attributes ( )
core_mda = mda_dict [ 'coremetadata' ]
end_time_str = self . parse_metadata_string ( core_mda )
self . _end_time = datetime . strptime ( end_time_str , "%Y-%m-%dT%H:%M:%SZ" ) |
def _encode_payload ( data , headers = None ) :
"Wrap data in an SCGI request ." | prolog = "CONTENT_LENGTH\0%d\0SCGI\x001\0" % len ( data )
if headers :
prolog += _encode_headers ( headers )
return _encode_netstring ( prolog ) + data |
def searchable_object_types ( self ) :
"""List of ( object _ types , friendly name ) present in the index .""" | try :
idx = self . index ( )
except KeyError : # index does not exists : service never started , may happens during
# tests
return [ ]
with idx . reader ( ) as r :
indexed = sorted ( set ( r . field_terms ( "object_type" ) ) )
app_indexed = self . app_state . indexed_fqcn
return [ ( name , friendly_fqcn ( n... |
def normalize_path ( path ) : # type : ( AnyStr ) - > AnyStr
"""Return a case - normalized absolute variable - expanded path .
: param str path : The non - normalized path
: return : A normalized , expanded , case - normalized path
: rtype : str""" | return os . path . normpath ( os . path . normcase ( os . path . abspath ( os . path . expandvars ( os . path . expanduser ( str ( path ) ) ) ) ) ) |
def CreateStorageReaderForFile ( cls , path ) :
"""Creates a storage reader based on the file .
Args :
path ( str ) : path to the storage file .
Returns :
StorageReader : a storage reader or None if the storage file cannot be
opened or the storage format is not supported .""" | if sqlite_file . SQLiteStorageFile . CheckSupportedFormat ( path , check_readable_only = True ) :
return sqlite_reader . SQLiteStorageFileReader ( path )
return None |
def interactive ( ) :
"""Create an interactive command line tool .
Wrapper for an interactive session for manual commands to be entered .""" | parser = argparse . ArgumentParser ( description = __doc__ )
parser . add_argument ( '--device' , default = '/dev/ttyUSB0' , help = 'Path to PLM device' )
parser . add_argument ( '-v' , '--verbose' , action = 'count' , help = 'Set logging level to verbose' )
parser . add_argument ( '-l' , '--logfile' , default = '' , h... |
def get_user ( uid ) :
"""Get an user by the UID .
: param str uid : UID to find
: return : the user
: rtype : User object
: raises ValueError : uid is not an integer
: raises KeyError : if user does not exist""" | if db is not None :
try :
uid = uid . decode ( 'utf-8' )
except AttributeError :
pass
d = db . hgetall ( 'user:{0}' . format ( uid ) )
if d :
nd = { }
# strings everywhere
for k in d :
try :
nd [ k . decode ( 'utf-8' ) ] = d [ k ] . dec... |
def listClients ( self , * args , ** kwargs ) :
"""List Clients
Get a list of all clients . With ` prefix ` , only clients for which
it is a prefix of the clientId are returned .
By default this end - point will try to return up to 1000 clients in one
request . But it * * may return less , even none * * .
... | return self . _makeApiCall ( self . funcinfo [ "listClients" ] , * args , ** kwargs ) |
def getLabel ( self ) :
"""Retrieve metadata about the text
: rtype : Metadata
: returns : Dictionary with label informations""" | response = xmlparser ( self . retriever . getLabel ( urn = str ( self . urn ) ) )
self . _parse_request ( response . xpath ( "//ti:reply/ti:label" , namespaces = XPATH_NAMESPACES ) [ 0 ] )
return self . metadata |
def auth_url ( self , scope ) :
"""Gets the url a user needs to access to give up a user token""" | params = { 'response_type' : 'code' , 'client_id' : self . __client_id , 'redirect_uri' : self . __redirect_uri , 'scope' : scope }
if self . __state is not None :
params [ 'state' ] = self . __state
return settings . AUTH_ENDPOINT + '/authorize?' + urllib . urlencode ( params ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.