signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def format_name ( text ) :
"""Format a comic name .""" | name = unescape ( text )
name = asciify ( name . replace ( u'&' , u'And' ) . replace ( u'@' , u'At' ) )
name = capfirst ( name )
return name |
def validate ( self , value ) :
"""Ensures that the password follows the following criteria :
: param value : < str >
: return : True""" | if not isinstance ( value , ( str , unicode ) ) :
raise orb . errors . ColumnValidationError ( self , 'Invalid password.' )
elif not self . __allowUnicode and value != projex . text . toAscii ( value ) :
raise orb . errors . ColumnValidationError ( self , 'Only ASCII characters are allowed for your password.' )... |
def queryset ( self , request , queryset ) :
"""Returns the filtered queryset based on the value
provided in the query string and retrievable via
` self . value ( ) ` .""" | if self . value ( ) is not None :
return queryset . filter ( information__type__pk = self . value ( ) )
else :
return queryset |
def get_settings ( profile , section , store = 'local' ) :
'''Get the firewall property from the specified profile in the specified store
as returned by ` ` netsh advfirewall ` ` .
Args :
profile ( str ) :
The firewall profile to query . Valid options are :
- domain
- public
- private
section ( str ... | # validate input
if profile . lower ( ) not in ( 'domain' , 'public' , 'private' ) :
raise ValueError ( 'Incorrect profile: {0}' . format ( profile ) )
if section . lower ( ) not in ( 'state' , 'firewallpolicy' , 'settings' , 'logging' ) :
raise ValueError ( 'Incorrect section: {0}' . format ( section ) )
if st... |
def assert_await_any_transforms_exist ( cli , transform_paths , does_exist = DEFAULT_TRANSFORM_EXISTS , timeout_seconds = DEFAULT_TIMEOUT_SECONDS ) :
"""Asserts that we successfully awaited for any transforms to exist based on does _ exist . If the timeout passes
or the expression is _ registered ! = actual state... | result = commands . await_any_transforms_exist ( cli , transform_paths , does_exist , timeout_seconds )
assert result is True
return result |
def parse_html_list ( dictionary , prefix = '' ) :
"""Used to suport list values in HTML forms .
Supports lists of primitives and / or dictionaries .
* List of primitives .
' [ 0 ] ' : ' abc ' ,
' [ 1 ] ' : ' def ' ,
' [ 2 ] ' : ' hij '
' abc ' ,
' def ' ,
' hij '
* List of dictionaries .
' [ 0 ... | ret = { }
regex = re . compile ( r'^%s\[([0-9]+)\](.*)$' % re . escape ( prefix ) )
for field , value in dictionary . items ( ) :
match = regex . match ( field )
if not match :
continue
index , key = match . groups ( )
index = int ( index )
if not key :
ret [ index ] = value
elif... |
def authenticator ( function , challenges = ( ) ) :
"""Wraps authentication logic , verify _ user through to the authentication function .
The verify _ user function passed in should accept an API key and return a user object to
store in the request context if authentication succeeded .""" | challenges = challenges or ( '{} realm="simple"' . format ( function . __name__ ) , )
def wrapper ( verify_user ) :
def authenticate ( request , response , ** kwargs ) :
result = function ( request , response , verify_user , ** kwargs )
def authenticator_name ( ) :
try :
... |
def password_args ( subparsers ) :
"""Add command line options for the set _ password operation""" | password_parser = subparsers . add_parser ( 'set_password' )
password_parser . add_argument ( 'vault_path' , help = 'Path which contains password' 'secret to be udpated' )
base_args ( password_parser ) |
def temp_connect ( self , hardware : hc . API ) :
"""Connect temporarily to the specified hardware controller .
This should be used as a context manager :
. . code - block : : python
with ctx . temp _ connect ( hw ) :
# do some tasks
ctx . home ( )
# after the with block , the context is connected to th... | old_hw = self . _hw_manager . hardware
try :
self . _hw_manager . set_hw ( hardware )
yield self
finally :
self . _hw_manager . set_hw ( old_hw ) |
def _internal_request ( self , request_obj , url , method , ** kwargs ) :
"""Internal handling of requests . Handles Exceptions .
: param request _ obj : a requests session .
: param str url : url to send request to
: param str method : type of request ( get / put / post / patch / delete )
: param kwargs : ... | method = method . lower ( )
if method not in self . _allowed_methods :
raise ValueError ( 'Method must be one of the allowed ones' )
if method == 'get' :
kwargs . setdefault ( 'allow_redirects' , True )
elif method in [ 'post' , 'put' , 'patch' ] :
if 'headers' not in kwargs :
kwargs [ 'headers' ] =... |
def get_client_sock ( addr ) :
"Get a client socket" | s = _socket . create_connection ( addr )
s . setsockopt ( _socket . SOL_SOCKET , _socket . SO_REUSEADDR , True )
s . setblocking ( False )
return s |
def show_cimreferences ( server_name , server , org_vm ) :
"""Show info about the CIM _ ReferencedProfile instances .
Goal . Clearly show what the various refs look like by using profile
names for the antecedent and dependent rather than instances .""" | try :
ref_insts = server . conn . EnumerateInstances ( "CIM_ReferencedProfile" , namespace = server . interop_ns )
prof_insts = server . conn . EnumerateInstances ( "CIM_RegisteredProfile" , namespace = server . interop_ns )
except pywbem . Error as er :
print ( 'CIM_ReferencedProfile failed for conn=%s\nex... |
def quick_search ( self , name , platform = None , sort_by = None , desc = True ) :
"""Quick search method that allows you to search for a game using only the
title and the platform
: param name : string
: param platform : int
: param sort _ by : string
: param desc : bool
: return : pybomb . clients . ... | if platform is None :
query_filter = "name:{0}" . format ( name )
else :
query_filter = "name:{0},platforms:{1}" . format ( name , platform )
search_params = { "filter" : query_filter }
if sort_by is not None :
self . _validate_sort_field ( sort_by )
if desc :
direction = self . SORT_ORDER_DESCE... |
def _to_number ( cls , string ) :
"""Convert string to int or float .""" | try :
if float ( string ) - int ( string ) == 0 :
return int ( string )
return float ( string )
except ValueError :
try :
return float ( string )
except ValueError :
return string |
def match_type_by_name ( expected_type , actual_type ) :
"""Matches expected type to an actual type .
: param expected _ type : an expected type name to match .
: param actual _ type : an actual type to match defined by type code .
: return : true if types are matching and false if they don ' t .""" | if expected_type == None :
return True
if actual_type == None :
raise Exception ( "Actual type cannot be null" )
expected_type = expected_type . lower ( )
if actual_type . __name__ . lower ( ) == expected_type :
return True
elif expected_type == "object" :
return True
elif expected_type == "int" or expe... |
def do_thing ( ) :
"""Execute command line cryptorito actions""" | if len ( sys . argv ) == 5 and sys . argv [ 1 ] == "encrypt_file" :
encrypt_file ( sys . argv [ 2 ] , sys . argv [ 3 ] , sys . argv [ 4 ] )
elif len ( sys . argv ) == 4 and sys . argv [ 1 ] == "decrypt_file" :
decrypt_file ( sys . argv [ 2 ] , sys . argv [ 3 ] )
elif len ( sys . argv ) == 3 and sys . argv [ 1 ]... |
def _raise_missing_antenna_errors ( ant_uvw , max_err ) :
"""Raises an informative error for missing antenna""" | # Find antenna uvw coordinates where any UVW component was nan
# nan + real = = nan
problems = np . nonzero ( np . add . reduce ( np . isnan ( ant_uvw ) , axis = 2 ) )
problem_str = [ ]
for c , a in zip ( * problems ) :
problem_str . append ( "[chunk %d antenna %d]" % ( c , a ) )
# Exit early
if len ( probl... |
def get_w_rel ( ns_run , simulate = False ) :
"""Get the relative posterior weights of the samples , normalised so
the maximum sample weight is 1 . This is calculated from get _ logw with
protection against numerical overflows .
Parameters
ns _ run : dict
Nested sampling run dict ( see data _ processing m... | logw = get_logw ( ns_run , simulate = simulate )
return np . exp ( logw - logw . max ( ) ) |
def _get_s16 ( self , msb , lsb ) :
"""Convert 2 bytes into a signed int .""" | buf = struct . pack ( '>bB' , self . _get_s8 ( msb ) , self . _get_u8 ( lsb ) )
return int ( struct . unpack ( '>h' , buf ) [ 0 ] ) |
def delete_record ( self , domain , record ) :
"""Deletes an existing record for a domain .""" | uri = "/domains/%s/records/%s" % ( utils . get_id ( domain ) , utils . get_id ( record ) )
resp , resp_body = self . _async_call ( uri , method = "DELETE" , error_class = exc . DomainRecordDeletionFailed , has_response = False )
return resp_body |
def add_log_listener ( self , callback ) :
"""Add a listener for Postgres log messages .
It will be called when asyncronous NoticeResponse is received
from the connection . Possible message types are : WARNING , NOTICE ,
DEBUG , INFO , or LOG .
: param callable callback :
A callable receiving the followin... | if self . is_closed ( ) :
raise exceptions . InterfaceError ( 'connection is closed' )
self . _log_listeners . add ( callback ) |
def admin_docker_list_view ( context , request ) :
"""Show list of docker images .""" | return { 'paginator' : Page ( context . all , url_maker = lambda p : request . path_url + "?page=%s" % p , page = int ( request . params . get ( 'page' , 1 ) ) , items_per_page = 6 ) } |
def validate ( token ) :
"""Validate token and return auth context .""" | token_url = TOKEN_URL_FMT . format ( token = token )
headers = { 'x-auth-token' : token , 'accept' : 'application/json' , }
resp = requests . get ( token_url , headers = headers )
if not resp . status_code == 200 :
raise HTTPError ( status = 401 )
return resp . json ( ) |
def all_neighbour_nodes ( chain_state : ChainState ) -> Set [ Address ] :
"""Return the identifiers for all nodes accross all payment networks which
have a channel open with this one .""" | addresses = set ( )
for payment_network in chain_state . identifiers_to_paymentnetworks . values ( ) :
for token_network in payment_network . tokenidentifiers_to_tokennetworks . values ( ) :
channel_states = token_network . channelidentifiers_to_channels . values ( )
for channel_state in channel_sta... |
def get_flops ( ) :
"""# DOESNT WORK""" | from sys import stdout
from re import compile
filename = "linpack.out"
fpnum = r'\d+\.\d+E[+-]\d\d'
fpnum_1 = fpnum + r' +'
pattern = compile ( r'^ *' + fpnum_1 + fpnum_1 + fpnum_1 + r'(' + fpnum + r') +' + fpnum_1 + fpnum + r' *\n$' )
speeds = [ 0.0 , 1.0e75 , 0.0 ]
file = open ( filename )
count = 0
while file :
... |
def referer_url ( self , value ) :
"""sets the referer url""" | if self . _referer_url != value :
self . _token = None
self . _referer_url = value |
def _get_anchors ( self ) :
"""Subclasses may override this method .""" | return tuple ( [ self . _getitem__anchors ( i ) for i in range ( self . _len__anchors ( ) ) ] ) |
def cache_distribution ( cls , zf , source , target_dir ) :
"""Possibly cache an egg from within a zipfile into target _ cache .
Given a zipfile handle and a filename corresponding to an egg distribution within
that zip , maybe write to the target cache and return a Distribution .""" | dependency_basename = os . path . basename ( source )
if not os . path . exists ( target_dir ) :
target_dir_tmp = target_dir + '.' + uuid . uuid4 ( ) . hex
for name in zf . namelist ( ) :
if name . startswith ( source ) and not name . endswith ( '/' ) :
zf . extract ( name , target_dir_tmp )... |
def propose_unif ( self ) :
"""Propose a new live point by sampling * uniformly *
within the unit cube .""" | u = self . unitcube . sample ( rstate = self . rstate )
ax = np . identity ( self . npdim )
return u , ax |
def _as_json_dumps ( self , indent : str = ' ' , ** kwargs ) -> str :
"""Convert to a stringified json object .
This is the same as _ as _ json with the exception that it isn ' t
a property , meaning that we can actually pass arguments . . .
: param indent : indent argument to dumps
: param kwargs : other... | return json . dumps ( self , default = self . _default , indent = indent , ** kwargs ) |
def wants ( cls , * service_names ) :
"""A class decorator to indicate that an XBlock class wants particular services .""" | def _decorator ( cls_ ) : # pylint : disable = missing - docstring
for service_name in service_names :
cls_ . _services_requested [ service_name ] = "want"
# pylint : disable = protected - access
return cls_
return _decorator |
def patch_stdout_context ( self , raw = False , patch_stdout = True , patch_stderr = True ) :
"""Return a context manager that will replace ` ` sys . stdout ` ` with a proxy
that makes sure that all printed text will appear above the prompt , and
that it doesn ' t destroy the output from the renderer .
: para... | return _PatchStdoutContext ( self . stdout_proxy ( raw = raw ) , patch_stdout = patch_stdout , patch_stderr = patch_stderr ) |
def restore_session_from_runtime_config ( ) :
"""Restore stored tabs from runtime config
The method checks if the last status of a state machine is in the backup or in tis original path and loads it
from there . The original path of these state machines are also insert into the recently opened state machines
... | # TODO add a dirty lock for a crashed rafcon instance also into backup session feature
# TODO in case a dialog is needed to give the user control
# TODO combine this and auto - backup in one structure / controller / observer
from rafcon . gui . singleton import state_machine_manager_model , global_runtime_config , glob... |
def handle_validate_token ( self , req ) :
"""Handles the GET v2 / . token / < token > call for validating a token , usually
called by a service like Swift .
On a successful validation , X - Auth - TTL will be set for how much longer
this token is valid and X - Auth - Groups will contain a comma separated
l... | token = req . path_info_pop ( )
if req . path_info or not token . startswith ( self . reseller_prefix ) :
return HTTPBadRequest ( request = req )
expires = groups = None
memcache_client = cache_from_env ( req . environ )
if memcache_client :
memcache_key = '%s/auth/%s' % ( self . reseller_prefix , token )
c... |
def get_table_csv ( cur , tablename , exclude_columns = [ ] ) :
"""Conveinience : Converts a tablename to csv format
Args :
tablename ( str ) :
exclude _ columns ( list ) :
Returns :
str : csv _ table
CommandLine :
python - m ibeis . control . SQLDatabaseControl - - test - get _ table _ csv
Example ... | import utool as ut
colnames_ = ut . get_table_columnname_list ( cur , tablename )
colnames = tuple ( [ colname for colname in colnames_ if colname not in exclude_columns ] )
row_list = ut . get_table_rows ( cur , tablename , colnames , unpack = False )
column_list = zip ( * row_list )
# = None , column _ list = [ ] , h... |
def next_sequence_id ( session , sequence_ids , parent_vid , table_class , force_query = False ) :
"""Return the next sequence id for a object , identified by the vid of the parent object , and the database prefix
for the child object . On the first call , will load the max sequence number
from the database , b... | from sqlalchemy import text
seq_col = table_class . sequence_id . property . columns [ 0 ] . name
try :
parent_col = table_class . _parent_col
except AttributeError :
parent_col = table_class . d_vid . property . columns [ 0 ] . name
assert bool ( parent_vid )
key = ( parent_vid , table_class . __name__ )
numbe... |
def drawInspectorContents ( self , reason , origin = None ) :
"""Draws all contents of this window ' s inspector .
The reason and origin parameters are passed on to the inspector ' s updateContents method .
: param reason : string describing the reason for the redraw .
Should preferably be one of the UpdateRe... | logger . debug ( "" )
logger . debug ( "-------- Drawing inspector of window: {} --------" . format ( self . windowTitle ( ) ) )
if self . inspector :
self . inspector . updateContents ( reason = reason , initiator = origin )
else :
logger . debug ( "No inspector selected" )
logger . debug ( "Finished draw insp... |
def _merge_wheres_to_has ( self , has_query , relation ) :
"""Merge the " wheres " from the relation query to a has query .
: param has _ query : The has query
: type has _ query : Builder
: param relation : The relation to count
: type relation : eloquent . orm . relations . Relation""" | relation_query = relation . get_base_query ( )
has_query . merge_wheres ( relation_query . wheres , relation_query . get_bindings ( ) )
self . _query . merge_bindings ( has_query . get_query ( ) ) |
def arg_name ( self ) -> T . Optional [ str ] :
"""Return argument name associated with given param .""" | if len ( self . args ) > 2 :
return self . args [ 2 ]
elif len ( self . args ) > 1 :
return self . args [ 1 ]
return None |
def add_paths ( self , paths ) :
"""Adds entries to the Python path .
The given paths are normalized before being added to the left of the
list
: param paths : New paths to add""" | if paths : # Use new paths in priority
self . _paths = list ( paths ) + self . _paths |
def load_shiller ( ) :
"""Load market & macroeconomic data from Robert Shiller ' s website .
Returns
iedata : pd . DataFrame
Time series of S & P 500 and interest rate variables .
Example
> > > from pyfinance import datasets
> > > shiller = datasets . load _ shiller ( )
> > > shiller . iloc [ : 7 , : ... | xls = "http://www.econ.yale.edu/~shiller/data/ie_data.xls"
cols = [ "date" , "sp50p" , "sp50d" , "sp50e" , "cpi" , "frac" , "real_rate" , "real_sp50p" , "real_sp50d" , "real_sp50e" , "cape" , ]
iedata = pd . read_excel ( xls , sheet_name = "Data" , skiprows = 7 , skip_footer = 1 , names = cols ) . drop ( "frac" , axis ... |
def solve ( self ) :
"""Solve the entire F2L . ( Generator )""" | for i in range ( 4 ) :
for slot in [ "FR" , "RB" , "BL" , "LF" ] :
solver = F2LPairSolver ( self . cube , slot )
if not solver . is_solved ( ) :
yield tuple ( [ self . cube [ slot [ i ] ] . colour for i in range ( 2 ) ] ) , solver . solve ( )
break |
def questions_slug_poll_responses_raw_tsv_get ( self , slug , ** kwargs ) :
"""One row per PollQuestion + Subpopulation + Response concerning the given Question ( Large )
Raw data from which we derived ` poll - responses - clean . tsv ` . Each row represents a single PollQuestion + Subpopulation + Response . See ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'callback' ) :
return self . questions_slug_poll_responses_raw_tsv_get_with_http_info ( slug , ** kwargs )
else :
( data ) = self . questions_slug_poll_responses_raw_tsv_get_with_http_info ( slug , ** kwargs )
return data |
def get_last_status_in_session ( self , session ) :
"""Last status in session .
Helper function to be called by resources properties .""" | try :
return self . _last_status_in_session [ session ]
except KeyError :
raise errors . Error ( 'The session %r does not seem to be valid as it does not have any last status' % session ) |
def _set_tm ( self , v , load = False ) :
"""Setter method for tm , mapped from YANG variable / system _ monitor / tm ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ tm is considered as a private
method . Backends looking to populate this variable should... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = tm . tm , is_container = 'container' , presence = True , yang_name = "tm" , rest_name = "tm" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extensions = { u'tai... |
def to_kana ( text ) :
"""Use MeCab to turn any text into its phonetic spelling , as katakana
separated by spaces .""" | records = MECAB . analyze ( text )
kana = [ ]
for record in records :
if record . pronunciation :
kana . append ( record . pronunciation )
elif record . reading :
kana . append ( record . reading )
else :
kana . append ( record . surface )
return ' ' . join ( k for k in kana if k ) |
def getPermissionBit ( self , t , m ) :
'''returns a permission bit of the string permission value for the specified object type''' | try :
if isinstance ( m , string_types ) :
return self . rights [ t ] [ m ] [ 'BITS' ]
else :
return m
except KeyError :
raise CommandExecutionError ( ( 'No right "{0}". It should be one of the following: {1}' ) . format ( m , ', ' . join ( self . rights [ t ] ) ) ) |
def from_jd ( jd ) :
'''Calculate Persian date from Julian day''' | jd = trunc ( jd ) + 0.5
depoch = jd - to_jd ( 475 , 1 , 1 )
cycle = trunc ( depoch / 1029983 )
cyear = ( depoch % 1029983 )
if cyear == 1029982 :
ycycle = 2820
else :
aux1 = trunc ( cyear / 366 )
aux2 = cyear % 366
ycycle = trunc ( ( ( 2134 * aux1 ) + ( 2816 * aux2 ) + 2815 ) / 1028522 ) + aux1 + 1
year... |
def set_attributes ( self , priority , address , rtr ) :
""": return : None""" | assert isinstance ( priority , int )
assert isinstance ( address , int )
assert isinstance ( rtr , bool )
assert priority == velbus . HIGH_PRIORITY or priority == velbus . LOW_PRIORITY
assert address >= velbus . LOW_ADDRESS and address <= velbus . HIGH_ADDRESS
self . priority = priority
self . address = address
self . ... |
def run ( self ) :
"""Sends extracted metadata in json format to stdout if stdout
option is specified , assigns metadata dictionary to class _ metadata
variable otherwise .""" | if self . stdout :
sys . stdout . write ( "extracted json data:\n" + json . dumps ( self . metadata , default = to_str ) + "\n" )
else :
extract_dist . class_metadata = self . metadata |
def map_neurons ( fun , neurites , neurite_type ) :
'''Map ` fun ` to all the neurites in a single or collection of neurons''' | nrns = _neuronfunc . neuron_population ( neurites )
return [ fun ( n , neurite_type = neurite_type ) for n in nrns ] |
def pluck ( col , key , default = None ) :
"""Extracts a list of values from a collection of dictionaries
> > > stooges = [ { " name " : " moe " , " age " : 40 } ,
. . . { " name " : " larry " , " age " : 50 } ,
. . . { " name " : " curly " , " age " : 60 } ]
> > > pluck ( stooges , " name " )
[ ' moe ' ,... | if not ( is_list ( col ) or is_tuple ( col ) ) :
fail ( "First argument must be a list or tuple" )
def _block ( dct ) :
if not is_dict ( dct ) :
return [ ]
return dct . get ( key , default )
return map ( _block , col ) |
def easeOutBounce ( n ) :
"""A bouncing tween function that hits the destination and then bounces to rest .
Args :
n ( float ) : The time progress , starting at 0.0 and ending at 1.0.
Returns :
( float ) The line progress , starting at 0.0 and ending at 1.0 . Suitable for passing to getPointOnLine ( ) .""" | _checkRange ( n )
if n < ( 1 / 2.75 ) :
return 7.5625 * n * n
elif n < ( 2 / 2.75 ) :
n -= ( 1.5 / 2.75 )
return 7.5625 * n * n + 0.75
elif n < ( 2.5 / 2.75 ) :
n -= ( 2.25 / 2.75 )
return 7.5625 * n * n + 0.9375
else :
n -= ( 2.65 / 2.75 )
return 7.5625 * n * n + 0.984375 |
def add_zone ( self , spatial_unit , container_id , name = '' , description = '' , visible = True , reuse = 0 , drop_behavior_type = None ) :
"""container _ id is a targetId that the zone belongs to""" | if not isinstance ( spatial_unit , abc_mapping_primitives . SpatialUnit ) :
raise InvalidArgument ( 'zone is not a SpatialUnit' )
# if not isinstance ( name , DisplayText ) :
# raise InvalidArgument ( ' name is not a DisplayText object ' )
if not isinstance ( reuse , int ) :
raise InvalidArgument ( 'reuse must ... |
def saveSettings ( self , settings ) :
"""Saves the data for this tree to the inputed xml entry .
: param xml | < xml . etree . ElementTree . Element >
: return < bool > success""" | # save order data
settings . setValue ( 'headerState' , wrapVariant ( str ( self . header ( ) . saveState ( ) . toBase64 ( ) ) ) )
settings . setValue ( 'sortColumn' , wrapVariant ( str ( self . sortColumn ( ) ) ) )
settings . setValue ( 'sortOrder' , wrapVariant ( str ( int ( self . sortOrder ( ) ) ) ) )
settings . se... |
def open_only ( func ) :
"""Decorator for ` . Channel ` methods which performs an openness check .
: raises :
` . SSHException ` - - If the wrapped method is called on an unopened
` . Channel ` .""" | @ wraps ( func )
def _check ( self , * args , ** kwds ) :
if ( self . closed or self . eof_received or self . eof_sent or not self . active ) :
raise SSHException ( "Channel is not open" )
return func ( self , * args , ** kwds )
return _check |
def to_list ( self , ** kwargs ) :
"""Convert the : class : ` ParameterSet ` to a list of : class : ` Parameter ` s
: return : list of class : ` Parameter ` objects""" | if kwargs :
return self . filter ( ** kwargs ) . to_list ( )
return self . _params |
def toxml ( self ) :
"""Exports this object into a LEMS XML object""" | return '<DerivedVariable name="{0}"' . format ( self . name ) + ( ' dimension="{0}"' . format ( self . dimension ) if self . dimension else '' ) + ( ' exposure="{0}"' . format ( self . exposure ) if self . exposure else '' ) + ( ' select="{0}"' . format ( self . select ) if self . select else '' ) + ( ' value="{0}"' . ... |
def blockgen ( bytes , block_size = 16 ) :
'''a block generator for pprp''' | for i in range ( 0 , len ( bytes ) , block_size ) :
block = bytes [ i : i + block_size ]
block_len = len ( block )
if block_len > 0 :
yield block
if block_len < block_size :
break |
def get_swstat_bits ( frame_filenames , swstat_channel_name , start_time , end_time ) :
'''This function just checks the first time in the SWSTAT channel
to see if the filter was on , it doesn ' t check times beyond that .
This is just for a first test on a small chunck of data .
To read the SWSTAT bits , ref... | # read frames
swstat = frame . read_frame ( frame_filenames , swstat_channel_name , start_time = start_time , end_time = end_time )
# convert number in channel to binary
bits = bin ( int ( swstat [ 0 ] ) )
# check if filterbank input or output was off
filterbank_off = False
if len ( bits ) < 14 or int ( bits [ - 13 ] )... |
def _json_to_term_model ( term_data ) :
"""Returns a term model created from the passed json data .
param : term _ data loaded json data""" | strptime = datetime . strptime
day_format = "%Y-%m-%d"
datetime_format = "%Y-%m-%dT%H:%M:%S"
term = TermModel ( )
term . year = term_data [ "Year" ]
term . quarter = term_data [ "Quarter" ]
term . last_day_add = parse_sws_date ( term_data [ "LastAddDay" ] )
term . first_day_quarter = parse_sws_date ( term_data [ "First... |
def write ( self , msg , level = logging . INFO ) :
"""method implements stream write interface , allowing to redirect stdout to logger""" | if msg is not None and len ( msg . strip ( ) ) > 0 :
self . logger . log ( level , msg ) |
def get_default_repo ( self ) :
"""Go through all the repositories defined in the config file and search
for a truthy value for the ` ` default ` ` key . If there isn ' t any return
None .""" | for repo in self . get_repos ( ) :
if self . get_safe ( repo , 'default' ) and self . getboolean ( repo , 'default' ) :
return repo
return False |
def pl2nvp ( plane ) :
"""Return a unit normal vector and point that define a specified plane .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / pl2nvp _ c . html
: param plane : A SPICE plane .
: type plane : supporttypes . Plane
: return : A unit normal vector and point that... | assert ( isinstance ( plane , stypes . Plane ) )
normal = stypes . emptyDoubleVector ( 3 )
point = stypes . emptyDoubleVector ( 3 )
libspice . pl2nvp_c ( ctypes . byref ( plane ) , normal , point )
return stypes . cVectorToPython ( normal ) , stypes . cVectorToPython ( point ) |
def finish_rel_branch ( relver ) :
"""Finish release branch""" | print ( 'finish release branch' , relver )
run ( 'git flow release finish --keepremote -F -p -m "version {ver}" {ver}' . format ( ver = relver ) , hide = True ) |
def plot_band ( plt_in , band_name , rsr_obj , ** kwargs ) :
"""Do the plotting of one band""" | if 'platform_name_in_legend' in kwargs :
platform_name_in_legend = kwargs [ 'platform_name_in_legend' ]
else :
platform_name_in_legend = False
detectors = rsr_obj . rsr [ band_name ] . keys ( )
# for det in detectors :
det = sorted ( detectors ) [ 0 ]
resp = rsr_obj . rsr [ band_name ] [ det ] [ 'response' ]
wv... |
def register_route ( self , src , dst , gateway ) :
"""Adds a routing rule to the tuntap router .
: param str | unicode src : Source / mask .
: param str | unicode dst : Destination / mask .
: param str | unicode gateway : Gateway address .""" | self . _set_aliased ( 'router-route' , ' ' . join ( ( src , dst , gateway ) ) , multi = True )
return self |
def help ( opts , bot , _ ) :
"""Usage : help [ < command > ]
With no arguments , print the form of all supported commands .
With an argument , print a detailed explanation of a command .""" | command = opts [ '<command>' ]
if command is None :
return bot . help_text ( )
if command not in bot . commands :
return "%r is not a known command" % command
return bot . commands [ command ] . __doc__ |
def hash ( hash_type , input_text ) :
'''Hash input _ text with the algorithm choice''' | hash_funcs = { 'MD5' : hashlib . md5 , 'SHA1' : hashlib . sha1 , 'SHA224' : hashlib . sha224 , 'SHA256' : hashlib . sha256 , 'SHA384' : hashlib . sha384 , 'SHA512' : hashlib . sha512 }
if hash_type == 'All' :
hash_type = [ 'MD5' , 'SHA1' , 'SHA224' , 'SHA256' , 'SHA384' , 'SHA512' ]
else :
hash_type = [ hash_ty... |
def _create_filters ( col_params , extractors ) :
"""Creates filters for the given col _ params .
Args :
col _ params : List of ListSessionGroupsRequest . ColParam protobufs .
extractors : list of extractor functions of the same length as col _ params .
Each element should extract the column described by th... | result = [ ]
for col_param , extractor in zip ( col_params , extractors ) :
a_filter = _create_filter ( col_param , extractor )
if a_filter :
result . append ( a_filter )
return result |
def check_file_for_tabs ( cls , filename , verbose = True ) :
"""identifies if the file contains tabs and returns True if it
does . It also prints the location of the lines and columns . If
verbose is set to False , the location is not printed .
: param verbose : if true prints issues
: param filename : the... | filename = path_expand ( filename )
file_contains_tabs = False
with open ( filename , 'r' ) as f :
lines = f . read ( ) . split ( "\n" )
line_no = 1
for line in lines :
if "\t" in line :
file_contains_tabs = True
location = [ i for i in range ( len ( line ) ) if line . startswith ( '\t' , i ) ]
... |
def _render_having ( having_conditions ) :
"""Render the having part of a query .
Parameters
having _ conditions : list
A ` ` list ` ` of ` ` dict ` ` s to filter the rows
Returns
str
A string that represents the " having " part of a query .
See Also
render _ query : Further clarification of ` condi... | if not having_conditions :
return ""
rendered_conditions = [ ]
for condition in having_conditions :
field = condition . get ( 'field' )
field_type = condition . get ( 'type' )
comparators = condition . get ( 'comparators' )
if None in ( field , field_type , comparators ) or not comparators :
... |
def inject ( cls , span , obj ) :
"""Injects the span context into a ` carrier ` object .
: param opentracing . span . SpanContext span : the SpanContext instance
: param Any obj : Object to use as context""" | obj . metadata [ '__parent-span__' ] = dict ( )
cls . inject_span ( span , obj . metadata [ '__parent-span__' ] ) |
def hermann_adjustment_factors ( bval , min_mag , mag_inc ) :
'''Returns the adjustment factors ( fval , fival ) proposed by Hermann ( 1978)
: param float bval :
Gutenberg & Richter ( 1944 ) b - value
: param np . ndarray min _ mag :
Minimum magnitude of completeness table
: param non - negative float mag... | fval = 10. ** ( bval * min_mag )
fival = 10. ** ( bval * ( mag_inc / 2. ) ) - 10. ** ( - bval * ( mag_inc / 2. ) )
return fval , fival |
def create ( self ) :
"""Create empty scene for power spectrum .""" | self . idx_chan = QComboBox ( )
self . idx_chan . activated . connect ( self . display_window )
self . idx_fig = QGraphicsView ( self )
self . idx_fig . scale ( 1 , - 1 )
layout = QVBoxLayout ( )
layout . addWidget ( self . idx_chan )
layout . addWidget ( self . idx_fig )
self . setLayout ( layout )
self . resizeEvent ... |
def receptive_field ( self , X , identities , max_len = 10 , threshold = 0.9 , batch_size = 1 ) :
"""Calculate the receptive field of the SOM on some data .
The receptive field is the common ending of all sequences which
lead to the activation of a given BMU . If a SOM is well - tuned to
specific sequences , ... | receptive_fields = defaultdict ( list )
predictions = self . predict ( X , batch_size )
if len ( predictions ) != len ( identities ) :
raise ValueError ( "X and identities are not the same length: " "{0} and {1}" . format ( len ( X ) , len ( identities ) ) )
for idx , p in enumerate ( predictions . tolist ( ) ) :
... |
def format_query_date ( in_date ) :
"""Format a date , datetime or a YYYYMMDD string input as YYYY - MM - DDThh : mm : ssZ
or validate a date string as suitable for the full text search interface and return it .
` None ` will be converted to ' \ * ' , meaning an unlimited date bound in date ranges .
Parameter... | if in_date is None :
return '*'
if isinstance ( in_date , ( datetime , date ) ) :
return in_date . strftime ( '%Y-%m-%dT%H:%M:%SZ' )
elif not isinstance ( in_date , string_types ) :
raise ValueError ( 'Expected a string or a datetime object. Received {}.' . format ( in_date ) )
in_date = in_date . strip ( )... |
def outdict ( self , ndigits = 3 ) :
"""Return dictionary structure rounded to a given precision .""" | outdict = { }
for i in range ( EMIR_NBARS ) :
ibar = i + 1
cbar = 'slitlet' + str ( ibar ) . zfill ( 2 )
outdict [ cbar ] = { }
outdict [ cbar ] [ '_csu_bar_left' ] = round ( self . _csu_bar_left [ i ] , ndigits )
outdict [ cbar ] [ '_csu_bar_right' ] = round ( self . _csu_bar_right [ i ] , ndigits ... |
def time_from_number ( self , value ) :
"""Converts a float value to corresponding time instance .""" | if not isinstance ( value , numbers . Real ) :
return None
delta = datetime . timedelta ( days = value )
minutes , second = divmod ( delta . seconds , 60 )
hour , minute = divmod ( minutes , 60 )
return datetime . time ( hour , minute , second ) |
def unquote ( str ) :
"""Remove quotes from a string .""" | if len ( str ) > 1 :
if str . startswith ( '"' ) and str . endswith ( '"' ) :
return str [ 1 : - 1 ] . replace ( '\\\\' , '\\' ) . replace ( '\\"' , '"' )
if str . startswith ( '<' ) and str . endswith ( '>' ) :
return str [ 1 : - 1 ]
return str |
def load_plugin ( module_name : str ) -> bool :
"""Load a module as a plugin .
: param module _ name : name of module to import
: return : successful or not""" | try :
module = importlib . import_module ( module_name )
name = getattr ( module , '__plugin_name__' , None )
usage = getattr ( module , '__plugin_usage__' , None )
_plugins . add ( Plugin ( module , name , usage ) )
logger . info ( f'Succeeded to import "{module_name}"' )
return True
except Exc... |
def get_assessment_parts_by_query ( self , assessment_part_query ) :
"""Gets a list of ` ` AssessmentParts ` ` matching the given assessment part query .
arg : assessment _ part _ query
( osid . assessment . authoring . AssessmentPartQuery ) : the
assessment part query
return : ( osid . assessment . authori... | # Implemented from template for
# osid . resource . ResourceQuerySession . get _ resources _ by _ query
and_list = list ( )
or_list = list ( )
for term in assessment_part_query . _query_terms :
if '$in' in assessment_part_query . _query_terms [ term ] and '$nin' in assessment_part_query . _query_terms [ term ] :
... |
def group_issues_by_fingerprint ( issues ) :
"""Groups issues by fingerprint . Grouping is done by issue code in addition .
IMPORTANT : It is assumed that all issues come from the SAME analyzer .""" | issues_by_fingerprint = defaultdict ( list )
for issue in issues :
if not 'fingerprint' in issue :
raise AttributeError ( "No fingerprint defined for issue with analyzer %s and code %s!" % ( issue . get ( 'analyzer' , '(undefined)' ) , issue [ 'code' ] ) )
fp_code = "%s:%s" % ( issue [ 'fingerprint' ] ,... |
def to_perioddelta ( self , freq ) :
"""Calculate TimedeltaArray of difference between index
values and index converted to PeriodArray at specified
freq . Used for vectorized offsets
Parameters
freq : Period frequency
Returns
TimedeltaArray / Index""" | # TODO : consider privatizing ( discussion in GH # 23113)
from pandas . core . arrays . timedeltas import TimedeltaArray
i8delta = self . asi8 - self . to_period ( freq ) . to_timestamp ( ) . asi8
m8delta = i8delta . view ( 'm8[ns]' )
return TimedeltaArray ( m8delta ) |
def apply_flow ( self , flowrate ) :
r"""Convert the invaded sequence into an invaded time for a given flow rate
considering the volume of invaded pores and throats .
Parameters
flowrate : float
The flow rate of the injected fluid
Returns
Creates a throat array called ' invasion _ time ' in the Algorith... | net = self . project . network
P12 = net [ 'throat.conns' ]
aa = self [ 'throat.invasion_sequence' ]
bb = sp . argsort ( self [ 'throat.invasion_sequence' ] )
P12_inv = self [ 'pore.invasion_sequence' ] [ P12 ]
# Find if the connected pores were invaded with or before each throat
P1_inv = P12_inv [ : , 0 ] <= aa
P2_inv... |
def awscli_defaults ( os_type = None ) :
"""Summary :
Parse , update local awscli config credentials
Args :
: user ( str ) : USERNAME , only required when run on windows os
Returns :
TYPE : dict object containing key , value pairs describing
os information""" | try :
if os_type is None :
os_type = platform . system ( )
if os_type == 'Linux' :
HOME = os . environ [ 'HOME' ]
awscli_credentials = HOME + '/.aws/credentials'
awscli_config = HOME + '/.aws/config'
elif os_type == 'Windows' :
username = os . getenv ( 'username' )
... |
def set_value ( self , value , status = NOMINAL , timestamp = None , major = DEFAULT_KATCP_MAJOR ) :
"""Check and then set the value of the sensor .
Parameters
value : object
Value of the appropriate type for the sensor .
status : Sensor status constant
Whether the value represents an error condition or n... | self . _kattype . check ( value , major )
if timestamp is None :
timestamp = time . time ( )
self . set ( timestamp , status , value ) |
def line ( darray , * args , ** kwargs ) :
"""Line plot of DataArray index against values
Wraps : func : ` matplotlib : matplotlib . pyplot . plot `
Parameters
darray : DataArray
Must be 1 dimensional
figsize : tuple , optional
A tuple ( width , height ) of the figure in inches .
Mutually exclusive wi... | # Handle facetgrids first
row = kwargs . pop ( 'row' , None )
col = kwargs . pop ( 'col' , None )
if row or col :
allargs = locals ( ) . copy ( )
allargs . update ( allargs . pop ( 'kwargs' ) )
allargs . pop ( 'darray' )
return _easy_facetgrid ( darray , line , kind = 'line' , ** allargs )
ndims = len (... |
def is_empty ( self ) :
'''Return ` True ` if form is valid and contains an empty lookup .''' | return ( self . is_valid ( ) and not self . simple_lookups and not self . complex_conditions and not self . extra_conditions ) |
def has_alpha_band ( src_dst ) :
"""Check for alpha band or mask in source .""" | if ( any ( [ MaskFlags . alpha in flags for flags in src_dst . mask_flag_enums ] ) or ColorInterp . alpha in src_dst . colorinterp ) :
return True
return False |
def write_file ( self , target_path , html ) :
"""Writes out the provided HTML to the provided path .""" | logger . debug ( "Building to {}{}" . format ( self . fs_name , target_path ) )
with self . fs . open ( smart_text ( target_path ) , 'wb' ) as outfile :
outfile . write ( six . binary_type ( html ) )
outfile . close ( ) |
def delete ( self ) :
"""Deletes the resource on the server .""" | if 'delete' in self . _URL :
extra = { 'resource' : self . __class__ . __name__ , 'query' : { 'id' : self . id } }
logger . info ( "Deleting {} resource." . format ( self ) , extra = extra )
self . _api . delete ( url = self . _URL [ 'delete' ] . format ( id = self . id ) )
else :
raise SbgError ( 'Reso... |
def go_to_preset ( self , action = None , channel = 0 , preset_point_number = 1 ) :
"""Params :
action - start or stop
channel - channel number
preset _ point _ number - preset point number""" | ret = self . command ( 'ptz.cgi?action={0}&channel={1}&code=GotoPreset&arg1=0' '&arg2={2}&arg3=0' . format ( action , channel , preset_point_number ) )
return ret . content . decode ( 'utf-8' ) |
def _schedule_shards ( cls , spec , readers , queue_name , base_path , mr_state ) :
"""Prepares shard states and schedules their execution .
Even though this method does not schedule shard task and save shard state
transactionally , it ' s safe for taskqueue to retry this logic because
the initial shard _ sta... | # Create shard states .
shard_states = [ ]
for shard_number , input_reader in enumerate ( readers ) :
shard_state = model . ShardState . create_new ( spec . mapreduce_id , shard_number )
shard_state . shard_description = str ( input_reader )
shard_states . append ( shard_state )
# Retrieves already existing... |
def dump_conndata ( self ) :
"""Developer tool for debugging forensics .""" | attrs = vars ( self )
return ', ' . join ( "%s: %s" % item for item in attrs . items ( ) ) |
def avatar_url_from_email ( email , size = 64 , default = 'retro' , dns = False ) :
"""Our own implementation since fas doesn ' t support this nicely yet .""" | if dns : # This makes an extra DNS SRV query , which can slow down our webapps .
# It is necessary for libravatar federation , though .
import libravatar
return libravatar . libravatar_url ( email = email , size = size , default = default , )
else :
params = _ordered_query_params ( [ ( 's' , size ) , ( 'd' ... |
def stop ( self ) :
"""stop the container""" | logger . info ( 'is being stopped' , extra = { 'formatter' : 'container' , 'container' : self . name } )
response = self . client . stop ( self . id )
while self . state ( ) [ 'running' ] :
time . sleep ( 1 )
return response |
def read_from_buffer ( cls , buf , identifier_str = None ) :
"""Load the context from a buffer .""" | try :
return cls . _read_from_buffer ( buf , identifier_str )
except Exception as e :
cls . _load_error ( e , identifier_str ) |
def _to_string ( self ) :
"""Implemented a function for _ _ str _ _ and _ _ repr _ _ to use , but
which prevents infinite recursion when migrating to Python 3""" | if self . sections :
start = "/" if self . bound_start else "**/"
sections = "/**/" . join ( str ( section ) for section in self . sections )
end = "" if self . bound_end else "/**"
else :
start = ""
sections = ""
end = "" if self . bound_end else "**"
return "{0}{1}{2}/{3}" . format ( start , s... |
def _create_temp_requirements ( self ) :
"""Create a temporary requirements . txt .
This allows testing again a git branch instead of pulling from pypi .""" | self . use_temp_requirements_file = True
# Replace tcex version with develop branch of tcex
with open ( self . requirements_file , 'r' ) as fh :
current_requirements = fh . read ( ) . strip ( ) . split ( '\n' )
self . requirements_file = 'temp-{}' . format ( self . requirements_file )
with open ( self . requirement... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.