signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def in_subnet ( cidr , addr = None ) :
'''Returns True if host or ( any of ) addrs is within specified subnet , otherwise False''' | try :
cidr = ipaddress . ip_network ( cidr )
except ValueError :
log . error ( 'Invalid CIDR \'%s\'' , cidr )
return False
if addr is None :
addr = ip_addrs ( )
addr . extend ( ip_addrs6 ( ) )
elif not isinstance ( addr , ( list , tuple ) ) :
addr = ( addr , )
return any ( ipaddress . ip_address... |
def make_file_url ( self , share_name , directory_name , file_name , protocol = None , sas_token = None ) :
'''Creates the url to access a file .
: param str share _ name :
Name of share .
: param str directory _ name :
The path to the directory .
: param str file _ name :
Name of file .
: param str p... | if directory_name is None :
url = '{}://{}/{}/{}' . format ( protocol or self . protocol , self . primary_endpoint , share_name , file_name , )
else :
url = '{}://{}/{}/{}/{}' . format ( protocol or self . protocol , self . primary_endpoint , share_name , directory_name , file_name , )
if sas_token :
url +=... |
def uploadfile ( baseurl , filename , format_ , token , nonce , cert , method = requests . post ) :
"""Uploads file ( given by ` filename ` ) to server at ` baseurl ` .
` sesson _ key ` and ` nonce ` are string values that get passed as POST
parameters .""" | filehash = sha1sum ( filename )
files = { 'filedata' : open ( filename , 'rb' ) }
payload = { 'sha1' : filehash , 'filename' : os . path . basename ( filename ) , 'token' : token , 'nonce' : nonce , }
return method ( "%s/sign/%s" % ( baseurl , format_ ) , files = files , data = payload , verify = cert ) |
def focusedWindow ( cls ) :
"""Returns a Region corresponding to whatever window is in the foreground""" | x , y , w , h = PlatformManager . getWindowRect ( PlatformManager . getForegroundWindow ( ) )
return Region ( x , y , w , h ) |
def _encode_uuid ( name , value , dummy , opts ) :
"""Encode uuid . UUID .""" | uuid_representation = opts . uuid_representation
# Python Legacy Common Case
if uuid_representation == OLD_UUID_SUBTYPE :
return b"\x05" + name + b'\x10\x00\x00\x00\x03' + value . bytes
# Java Legacy
elif uuid_representation == JAVA_LEGACY :
from_uuid = value . bytes
data = from_uuid [ 0 : 8 ] [ : : - 1 ] +... |
def depthwise_convolution ( inp , kernel , pad = None , stride = None , dilation = None , multiplier = 1 , w_init = None , b_init = None , base_axis = 1 , fix_parameters = False , rng = None , with_bias = True ) :
"""N - D Depthwise Convolution with a bias term .
Reference :
- F . Chollet : Chollet , Francois .... | if w_init is None :
w_init = UniformInitializer ( calc_uniform_lim_glorot ( inp . shape [ base_axis ] * multiplier , inp . shape [ base_axis ] , tuple ( kernel ) ) , rng = rng )
if with_bias and b_init is None :
b_init = ConstantInitializer ( )
w = get_parameter_or_create ( "W" , ( inp . shape [ base_axis ] * m... |
def update ( self , response_headers ) :
"""Update the state of the rate limiter based on the response headers .
This method should only be called following a HTTP request to reddit .
Response headers that do not contain x - ratelimit fields will be treated
as a single request . This behavior is to error on t... | if "x-ratelimit-remaining" not in response_headers :
if self . remaining is not None :
self . remaining -= 1
self . used += 1
return
now = time . time ( )
prev_remaining = self . remaining
seconds_to_reset = int ( response_headers [ "x-ratelimit-reset" ] )
self . remaining = float ( response_hea... |
def sort_items ( self , items , args = False ) :
"""Sort the ` self ` ' s contents , as contained in the list ` items ` as
specified in ` self ` ' s meta - data .""" | if self . settings [ 'sort' ] . lower ( ) == 'src' :
return
def alpha ( i ) :
return i . name
def permission ( i ) :
if args :
if i . intent == 'in' :
return 'b'
if i . intent == 'inout' :
return 'c'
if i . intent == 'out' :
return 'd'
if i... |
def _surfdens ( self , R , z , phi = 0. , t = 0. ) :
"""NAME :
_ surfdens
PURPOSE :
evaluate the surface density for this potential
INPUT :
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT :
the surface density
HISTORY :
2018-08-19 - Written - Bovy ( Uo... | r = numpy . sqrt ( R ** 2. + z ** 2. )
x = r / self . a
Rpa = numpy . sqrt ( R ** 2. + self . a ** 2. )
Rma = numpy . sqrt ( R ** 2. - self . a ** 2. + 0j )
if Rma == 0 :
za = z / self . a
return self . a ** 2. / 2. * ( ( 2. - 2. * numpy . sqrt ( za ** 2. + 1 ) + numpy . sqrt ( 2. ) * za * numpy . arctan ( za /... |
def hex_repr ( d ) :
"""> > > hex _ repr ( { " A " : 0x1 , " B " : 0xabc } )
' A = $ 01 B = $ 0abc '""" | txt = [ ]
for k , v in sorted ( d . items ( ) ) :
if isinstance ( v , int ) :
txt . append ( "%s=%s" % ( k , nice_hex ( v ) ) )
else :
txt . append ( "%s=%s" % ( k , v ) )
return " " . join ( txt ) |
def resource_spec ( opts ) :
"""Return the spec ( URL , package spec , file , etc ) for a named resource .""" | resources = _load ( opts . resources , opts . output_dir )
if opts . resource_name not in resources :
sys . stderr . write ( 'Invalid resource name: {}\n' . format ( opts . resource_name ) )
return 1
print ( resources [ opts . resource_name ] . spec ) |
def setup_container_system_config ( basedir , mountdir = None ) :
"""Create a minimal system configuration for use in a container .
@ param basedir : The directory where the configuration files should be placed as bytes .
@ param mountdir : If present , bind mounts to the configuration files will be added below... | etc = os . path . join ( basedir , b"etc" )
if not os . path . exists ( etc ) :
os . mkdir ( etc )
for file , content in CONTAINER_ETC_FILE_OVERRIDE . items ( ) : # Create " basedir / etc / file "
util . write_file ( content , etc , file )
if mountdir : # Create bind mount to " mountdir / etc / file "
... |
def check_smart_storage_config_ids ( self ) :
"""Check SmartStorageConfig controllers is there in hardware .
: raises : IloError , on an error from iLO .""" | if self . smart_storage_config_identities is None :
msg = ( 'The Redfish controller failed to get the ' 'SmartStorageConfig controller configurations.' )
LOG . debug ( msg )
raise exception . IloError ( msg ) |
def add_argument ( self , parser , bootstrap = False ) :
"""Add boolean item as an argument to the given parser .
An exclusive group is created on the parser , which will add
a boolean - style command line argument to the parser .
Examples :
A non - nested boolean value with the name ' debug ' will result
... | tmp_default = self . default
exclusive_grp = parser . add_mutually_exclusive_group ( )
self . default = True
args = self . _get_argparse_names ( parser . prefix_chars )
kwargs = self . _get_argparse_kwargs ( bootstrap )
exclusive_grp . add_argument ( * args , ** kwargs )
self . default = False
args = self . _get_argpar... |
def get_setting ( name , default ) :
"""A little helper for fetching global settings with a common prefix .""" | parent_name = "CMSPLUGIN_NEWS_{0}" . format ( name )
return getattr ( django_settings , parent_name , default ) |
def gabc ( elem , doc ) :
"""Handle gabc file inclusion and gabc code block .""" | if type ( elem ) == Code and "gabc" in elem . classes :
if doc . format == "latex" :
if elem . identifier == "" :
label = ""
else :
label = '\\label{' + elem . identifier + '}'
return latex ( "\n\\smallskip\n{%\n" + latexsnippet ( '\\gregorioscore{' + elem . text + '}... |
def ball_and_sticks ( self , ball_radius = 0.05 , stick_radius = 0.02 , colorlist = None , opacity = 1.0 ) :
"""Display the system using a ball and stick representation .""" | # Add the spheres
if colorlist is None :
colorlist = [ get_atom_color ( t ) for t in self . topology [ 'atom_types' ] ]
sizes = [ ball_radius ] * len ( self . topology [ 'atom_types' ] )
spheres = self . add_representation ( 'spheres' , { 'coordinates' : self . coordinates . astype ( 'float32' ) , 'colors' : colorl... |
def parse_PISCES_output ( pisces_output , path = False ) :
"""Takes the output list of a PISCES cull and returns in a usable dictionary .
Notes
Designed for outputs of protein sequence redundancy culls conducted using the PISCES server .
http : / / dunbrack . fccc . edu / PISCES . php
G . Wang and R . L . D... | pisces_dict = { }
if path :
pisces_path = Path ( pisces_output )
pisces_content = pisces_path . read_text ( ) . splitlines ( ) [ 1 : ]
else :
pisces_content = pisces_output . splitlines ( ) [ 1 : ]
for line in pisces_content :
pdb = line . split ( ) [ 0 ] [ : 4 ] . lower ( )
chain = line . split ( )... |
def align_lines ( line_list , character = '=' , replchar = None , pos = 0 ) :
r"""Left justifies text on the left side of character
align _ lines
TODO :
clean up and move to ubelt ?
Args :
line _ list ( list of strs ) :
character ( str ) :
pos ( int or list or None ) : does one alignment for all chars... | # FIXME : continue to fix ansi
if pos is None : # Align all occurences
num_pos = max ( [ line . count ( character ) for line in line_list ] )
pos = list ( range ( num_pos ) )
# Allow multiple alignments
if isinstance ( pos , list ) :
pos_list = pos
# recursive calls
new_lines = line_list
for pos... |
def SampleMemoryUsage ( self , parser_name ) :
"""Takes a sample of the memory usage for profiling .
Args :
parser _ name ( str ) : name of the parser .""" | if self . _memory_profiler :
used_memory = self . _process_information . GetUsedMemory ( ) or 0
self . _memory_profiler . Sample ( parser_name , used_memory ) |
def can_create_bin_with_record_types ( self , bin_record_types ) :
"""Tests if this user can create a single ` ` Bin ` ` using the desired record types .
While ` ` ResourceManager . getBinRecordTypes ( ) ` ` can be used to
examine which records are supported , this method tests which
record ( s ) are required... | # Implemented from template for
# osid . resource . BinAdminSession . can _ create _ bin _ with _ record _ types
# NOTE : It is expected that real authentication hints will be
# handled in a service adapter above the pay grade of this impl .
if self . _catalog_session is not None :
return self . _catalog_session . ... |
def from_csv ( cls , path : PathOrStr , folder : PathOrStr = None , label_delim : str = None , csv_labels : PathOrStr = 'labels.csv' , valid_pct : float = 0.2 , fn_col : int = 0 , label_col : int = 1 , suffix : str = '' , delimiter : str = None , header : Optional [ Union [ int , str ] ] = 'infer' , ** kwargs : Any ) -... | path = Path ( path )
df = pd . read_csv ( path / csv_labels , header = header , delimiter = delimiter )
return cls . from_df ( path , df , folder = folder , label_delim = label_delim , valid_pct = valid_pct , fn_col = fn_col , label_col = label_col , suffix = suffix , ** kwargs ) |
def rollback ( self , number = 0 ) :
"""Will rollback the configuration to a previous state .
Can be called also when
: param number : How many steps back in the configuration history must look back .
: raise pyPluribus . exceptions . RollbackError : In case the configuration cannot be rolled back .""" | if number < 0 :
raise pyPluribus . exceptions . RollbackError ( "Please provide a positive number to rollback to!" )
available_configs = len ( self . _config_history )
max_rollbacks = available_configs - 2
if max_rollbacks < 0 :
raise pyPluribus . exceptions . RollbackError ( "Cannot rollback: \
... |
def get_results ( ) :
"""Parse all search result pages .""" | base = "http://www.smackjeeves.com/search.php?submit=Search+for+Webcomics&search_mode=webcomics&comic_title=&special=all&last_update=3&style_all=on&genre_all=on&format_all=on&sort_by=2&start=%d"
session = requests . Session ( )
# store info in a dictionary { name - > url , number of comics , adult flag , bounce flag }
... |
def from_dict ( data , ctx ) :
"""Instantiate a new Transaction from a dict ( generally from loading a
JSON response ) . The data used to instantiate the Transaction is a
shallow copy of the dict passed in , with any complex child types
instantiated appropriately .""" | type = data . get ( "type" )
if type == "MARKET_ORDER" :
return MarketOrderTransaction . from_dict ( data , ctx )
if type == "ORDER_FILL" :
return OrderFillTransaction . from_dict ( data , ctx )
if type == "ORDER_CANCEL" :
return OrderCancelTransaction . from_dict ( data , ctx )
if type == "MARKET_ORDER_REJ... |
def doubleClick ( x = None , y = None , interval = 0.0 , button = 'left' , duration = 0.0 , tween = linear , pause = None , _pause = True ) :
"""Performs a double click .
This is a wrapper function for click ( ' left ' , x , y , 2 , interval ) .
The x and y parameters detail where the mouse event happens . If N... | _failSafeCheck ( )
# Multiple clicks work different in OSX
if sys . platform == 'darwin' :
x , y = _unpackXY ( x , y )
_mouseMoveDrag ( 'move' , x , y , 0 , 0 , duration = 0 , tween = None )
x , y = platformModule . _position ( )
platformModule . _multiClick ( x , y , button , 2 )
else :
click ( x ,... |
def set_codes ( self , codes ) :
'''Set the country code map for the data .
Codes given in a list .
i . e . DE - Germany
AT - Austria
US - United States''' | codemap = ''
for cc in codes :
cc = cc . upper ( )
if cc in self . __ccodes :
codemap += cc
else :
raise UnknownCountryCodeException ( cc )
self . codes = codemap |
def run ( self ) :
"""Load all artists into the database""" | df = ArtistsInputData ( ) . load ( )
# rename columns
df . rename ( columns = { 'artistLabel' : 'name' , 'genderLabel' : 'gender' } , inplace = True )
# attribute columns that exist in the data model
attribute_columns = [ 'name' , 'wiki_id' ]
# the extended model also stores the date of birth and gender
if config . EXT... |
def _register_info ( self , server ) :
"""Write a TensorBoardInfo file and arrange for its cleanup .
Args :
server : The result of ` self . _ make _ server ( ) ` .""" | server_url = urllib . parse . urlparse ( server . get_url ( ) )
info = manager . TensorBoardInfo ( version = version . VERSION , start_time = int ( time . time ( ) ) , port = server_url . port , pid = os . getpid ( ) , path_prefix = self . flags . path_prefix , logdir = self . flags . logdir , db = self . flags . db , ... |
def cmd ( send , msg , args ) :
"""Ping something .
Syntax : { command } < target >""" | if not msg :
send ( "Ping what?" )
return
channel = args [ 'target' ] if args [ 'target' ] != 'private' else args [ 'nick' ]
# CTCP PING
if "." not in msg and ":" not in msg :
targets = set ( msg . split ( ) )
if len ( targets ) > 3 :
send ( "Please specify three or fewer people to ping." )
... |
def load ( self , response ) :
"""Parse the GET response for the collection .
This operates as a lazy - loader , meaning that the data are only downloaded
from the server if there are not already loaded .
Collection items are loaded sequentially .
In some rare cases , a collection can have an asynchronous r... | self . _models = [ ]
if isinstance ( response , dict ) :
for key in response . keys ( ) :
model = self . model_class ( self , href = '' )
model . load ( response [ key ] )
self . _models . append ( model )
else :
for item in response :
model = self . model_class ( self , href = i... |
def _log ( self , x ) :
"""Modified version of np . log that manually sets values < = 0 to - inf
Parameters
x : ndarray of floats
Input to the log function
Returns
log _ ma : ndarray of floats
log of x , with x < = 0 values replaced with - inf""" | xshape = x . shape
_x = x . flatten ( )
y = utils . masked_log ( _x )
return y . reshape ( xshape ) |
def add_url_rule ( self , path : str , endpoint : Optional [ str ] = None , view_func : Optional [ Callable ] = None , methods : Optional [ Iterable [ str ] ] = None , defaults : Optional [ dict ] = None , host : Optional [ str ] = None , subdomain : Optional [ str ] = None , * , provide_automatic_options : Optional [ ... | endpoint = endpoint or _endpoint_from_view_func ( view_func )
handler = ensure_coroutine ( view_func )
if methods is None :
methods = getattr ( view_func , 'methods' , [ 'GET' ] )
methods = cast ( Set [ str ] , set ( methods ) )
required_methods = set ( getattr ( view_func , 'required_methods' , set ( ) ) )
if prov... |
def request ( self , arg = None ) :
'''Deal with requests''' | if not self . status :
return '{"result": "No message"}'
try :
status_dict = json . loads ( mpstatus_to_json ( self . status ) )
except Exception as e :
print ( e )
return
# If no key , send the entire json
if not arg :
return json . dumps ( status_dict )
# Get item from path
new_dict = status_dict
... |
def _ondemand ( f ) :
"""Decorator to only request information if not in cache already .""" | name = f . __name__
def func ( self , * args , ** kwargs ) :
if not args and not kwargs :
if hasattr ( self , '_%s' % name ) :
return getattr ( self , '_%s' % name )
a = f ( self , * args , ** kwargs )
setattr ( self , '_%s' % name , a )
return a
else :
return... |
def get_render_configurations ( self , request , ** kwargs ) :
"""Render image interface""" | data = self . process_form_data ( self . _get_form_defaults ( ) , kwargs )
variable_set = self . get_variable_set ( self . service . variable_set . order_by ( 'index' ) , data )
base_config = ImageConfiguration ( extent = data [ 'bbox' ] , size = data [ 'size' ] , image_format = data [ 'image_format' ] , background_col... |
def clear_cache ( self , items = None , topic = EVENT_TOPIC ) :
"""expects event object to be in the format of a session - stop or
session - expire event , whose results attribute is a
namedtuple ( identifiers , session _ key )""" | try :
for realm in self . realms :
identifier = items . identifiers . from_source ( realm . name )
if identifier :
realm . clear_cached_authc_info ( identifier )
except AttributeError :
msg = ( 'Could not clear authc_info from cache after event. ' 'items: ' + str ( items ) )
logg... |
def _invalidate_entry ( self , key ) :
"If exists : Invalidate old entry and return it ." | old_entry = self . access_lookup . get ( key )
if old_entry :
old_entry . is_valid = False
return old_entry |
async def select ( self , db ) :
"""Changes db index for all free connections .
All previously acquired connections will be closed when released .""" | res = True
async with self . _cond :
for i in range ( self . freesize ) :
res = res and ( await self . _pool [ i ] . select ( db ) )
else :
self . _db = db
return res |
def _ir_calibrate ( self , data , channel_name , cal_type ) :
"""Calibrate to brightness temperature .""" | if cal_type == 1 : # spectral radiances
return self . _srads2bt ( data , channel_name )
elif cal_type == 2 : # effective radiances
return self . _erads2bt ( data , channel_name )
else :
raise NotImplementedError ( 'Unknown calibration type' ) |
def findAllMatches ( self , needle , similarity ) :
"""Finds all matches above ` ` similarity ` ` using a search pyramid to improve efficiency
Pyramid implementation unashamedly stolen from https : / / github . com / stb - tester / stb - tester""" | positions = [ ]
# Use findBestMatch to get the best match
while True :
best_match = self . findBestMatch ( needle , similarity )
if best_match is None : # No more matches
break
# Found a match . Add it to our list
positions . append ( best_match )
# ( position , confidence )
# Erase the ... |
def get_webapp_settings ( name , site , settings ) :
r'''. . versionadded : : 2017.7.0
Get the value of the setting for the IIS web application .
. . note : :
Params are case sensitive
: param str name : The name of the IIS web application .
: param str site : The site name contains the web application . ... | ret = dict ( )
pscmd = list ( )
availableSettings = ( 'physicalPath' , 'applicationPool' , 'userName' , 'password' )
if not settings :
log . warning ( 'No settings provided' )
return ret
pscmd . append ( r'$Settings = @{};' )
# Verify setting is ine predefined settings and append relevant query command per sett... |
def _set_parse_data ( self ) :
"""set attributes derived from MediaWiki ( action = parse )""" | pdata = self . _load_response ( 'parse' ) [ 'parse' ]
self . data [ 'iwlinks' ] = utils . get_links ( pdata . get ( 'iwlinks' ) )
self . data [ 'pageid' ] = pdata . get ( 'pageid' )
self . data [ 'wikitext' ] = pdata . get ( 'wikitext' )
parsetree = pdata . get ( 'parsetree' )
self . data [ 'parsetree' ] = parsetree
bo... |
def check_git_unchanged ( filename , yes = False ) :
"""Check git to avoid overwriting user changes .""" | if check_staged ( filename ) :
s = 'There are staged changes in {}, overwrite? [y/n] ' . format ( filename )
if yes or input ( s ) in ( 'y' , 'yes' ) :
return
else :
raise RuntimeError ( 'There are staged changes in ' '{}, aborting.' . format ( filename ) )
if check_unstaged ( filename ) :
... |
def rst_to_docs_rst ( infile , outfile ) :
"""Convert an rst file to a sphinx docs rst file .""" | # Read infile into a list of lines
with open ( infile , 'r' ) as fin :
rst = fin . readlines ( )
# Inspect outfile path components to determine whether outfile
# is in the root of the examples directory or in a subdirectory
# thererof
ps = pathsplit ( outfile ) [ - 3 : ]
if ps [ - 2 ] == 'examples' :
ps = ps [ ... |
def fit_first_and_second_harmonics ( phi , intensities ) :
"""Fit the first and second harmonic function values to a set of
( angle , intensity ) pairs .
This function is used to compute corrections for ellipse fitting :
. . math : :
f ( phi ) = y0 + a1* \\ sin ( phi ) + b1* \\ cos ( phi ) + a2* \\ sin ( 2 ... | a1 = b1 = a2 = b2 = 1.
def optimize_func ( x ) :
return first_and_second_harmonic_function ( phi , np . array ( [ x [ 0 ] , x [ 1 ] , x [ 2 ] , x [ 3 ] , x [ 4 ] ] ) ) - intensities
return _least_squares_fit ( optimize_func , [ np . mean ( intensities ) , a1 , b1 , a2 , b2 ] ) |
def progressbar ( iterable = None , length = None , label = None , show_eta = True , show_percent = None , show_pos = False , item_show_func = None , fill_char = '#' , empty_char = '-' , bar_template = '%(label)s [%(bar)s] %(info)s' , info_sep = ' ' , width = 36 , file = None , color = None ) :
"""Create a progress... | try :
return IPyBackend ( iterable , length , label = label , show_eta = show_eta , show_percent = show_percent , show_pos = show_pos , item_show_func = item_show_func , info_sep = info_sep )
except ( ImportError , RuntimeError ) : # fall back if ipython is not installed or no notebook is running
return click .... |
def isseq ( obj ) :
'''Returns True if ` obj ` is a sequence - like object ( but not a string or
dict ) ; i . e . a tuple , list , subclass thereof , or having an interface
that supports iteration .''' | return not isstr ( obj ) and not isdict ( obj ) and ( isinstance ( obj , ( list , tuple ) ) or callable ( getattr ( obj , '__iter__' , None ) ) ) |
def reset_sum_fluxes ( self ) :
"""Set the sum of the fluxes calculated so far to zero .
> > > from hydpy . models . test _ v1 import *
> > > parameterstep ( )
> > > fluxes . fastaccess . _ q _ sum = 5.
> > > model . reset _ sum _ fluxes ( )
> > > fluxes . fastaccess . _ q _ sum
0.0""" | fluxes = self . sequences . fluxes
for flux in fluxes . numerics :
if flux . NDIM == 0 :
setattr ( fluxes . fastaccess , '_%s_sum' % flux . name , 0. )
else :
getattr ( fluxes . fastaccess , '_%s_sum' % flux . name ) [ : ] = 0. |
def _append ( self , menu ) :
'''append this menu item to a menu''' | from wx_loader import wx
menu . AppendMenu ( - 1 , self . name , self . wx_menu ( ) ) |
def makeMrkvHist ( self ) :
'''Makes a history of macroeconomic Markov states , stored in the attribute
MrkvNow _ hist . This version ensures that each state is reached a sufficient
number of times to have a valid sample for calcDynamics to produce a good
dynamic rule . It will sometimes cause act _ T to be i... | if hasattr ( self , 'loops_max' ) :
loops_max = self . loops_max
else : # Maximum number of loops ; final act _ T never exceeds act _ T * loops _ max
loops_max = 10
state_T_min = 50
# Choose minimum number of periods in each state for a valid Markov sequence
logit_scale = 0.2
# Scaling factor on logit choice sh... |
def get_belns_handle ( client , username = None , password = None ) :
"""Get BEL namespace arango db handle""" | ( username , password ) = get_user_creds ( username , password )
sys_db = client . db ( "_system" , username = username , password = password )
# Create a new database named " belns "
try :
if username and password :
belns_db = sys_db . create_database ( name = belns_db_name , users = [ { "username" : usern... |
def package_info ( self ) :
"""Collect built libraries names and solve flatc path .""" | self . cpp_info . libs = tools . collect_libs ( self )
self . user_info . flatc = os . path . join ( self . package_folder , "bin" , "flatc" ) |
def register_jinja_loaders ( self , * loaders ) :
"""Register one or many ` jinja2 . Loader ` instances for templates lookup .
During application initialization plugins can register a loader so that
their templates are available to jinja2 renderer .
Order of registration matters : last registered is first loo... | if not hasattr ( self , "_jinja_loaders" ) :
raise ValueError ( "Cannot register new jinja loaders after first template rendered" )
self . _jinja_loaders . extend ( loaders ) |
def __get_min_reads ( current_provisioning , min_provisioned_reads , log_tag ) :
"""Get the minimum number of reads to current _ provisioning
: type current _ provisioning : int
: param current _ provisioning : Current provisioned reads
: type min _ provisioned _ reads : int
: param min _ provisioned _ read... | # Fallback value to ensure that we always have at least 1 read
reads = 1
if min_provisioned_reads :
reads = int ( min_provisioned_reads )
if reads > int ( current_provisioning * 2 ) :
reads = int ( current_provisioning * 2 )
logger . debug ( '{0} - ' 'Cannot reach min-provisioned-reads as max sc... |
def _full_to_yearly_ts ( self , arr , dt ) :
"""Average the full timeseries within each year .""" | time_defined = self . def_time and not ( 'av' in self . dtype_in_time )
if time_defined :
arr = utils . times . yearly_average ( arr , dt )
return arr |
def search_satellite_imagery ( self , polygon_id , acquired_from , acquired_to , img_type = None , preset = None , min_resolution = None , max_resolution = None , acquired_by = None , min_cloud_coverage = None , max_cloud_coverage = None , min_valid_data_coverage = None , max_valid_data_coverage = None ) :
"""Searc... | assert polygon_id is not None
assert acquired_from is not None
assert acquired_to is not None
assert acquired_from <= acquired_to , 'Start timestamp of acquisition window must come before its end'
if min_resolution is not None :
assert min_resolution > 0 , 'Minimum resolution must be positive'
if max_resolution is ... |
def lines_from_string ( string , as_interned = False ) :
"""Create a list of file lines from a given string .
Args :
string ( str ) : File string
as _ interned ( bool ) : List of " interned " strings ( default False )
Returns :
strings ( list ) : File line list""" | if as_interned :
return [ sys . intern ( line ) for line in string . splitlines ( ) ]
return string . splitlines ( ) |
def check_grid_coordinates ( self , ds ) :
"""5.6 When the coordinate variables for a horizontal grid are not
longitude and latitude , it is required that the true latitude and
longitude coordinates be supplied via the coordinates attribute .
: param netCDF4 . Dataset ds : An open netCDF dataset
: rtype : l... | ret_val = [ ]
latitudes = cfutil . get_true_latitude_variables ( ds )
longitudes = cfutil . get_true_longitude_variables ( ds )
check_featues = [ '2d-regular-grid' , '2d-static-grid' , '3d-regular-grid' , '3d-static-grid' , 'mapped-grid' , 'reduced-grid' ]
# This one is tricky because there ' s a very subtle difference... |
def _determine_spec ( self , index ) :
"""Determine how a value for a field should be constructed
: param index :
The field number
: return :
A tuple containing the following elements :
- unicode string of the field name
- Asn1Value class of the field spec
- Asn1Value class of the value spec
- None ... | name , field_spec , field_params = self . _fields [ index ]
value_spec = field_spec
spec_override = None
if self . _spec_callbacks is not None and name in self . _spec_callbacks :
callback = self . _spec_callbacks [ name ]
spec_override = callback ( self )
if spec_override : # Allow a spec callback to speci... |
def count_nulls ( self , field ) :
"""Count the number of null values in a column""" | try :
n = self . df [ field ] . isnull ( ) . sum ( )
except KeyError :
self . warning ( "Can not find column" , field )
return
except Exception as e :
self . err ( e , "Can not count nulls" )
return
self . ok ( "Found" , n , "nulls in column" , field ) |
def get_mac_address_table_input_request_type_get_next_request_mac_address_type ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_mac_address_table = ET . Element ( "get_mac_address_table" )
config = get_mac_address_table
input = ET . SubElement ( get_mac_address_table , "input" )
request_type = ET . SubElement ( input , "request-type" )
get_next_request = ET . SubElement ( request_type , "get-next-request" ... |
def ChiSquared ( k , tag = None ) :
"""A Chi - Squared random variate
Parameters
k : int
The degrees of freedom of the distribution ( must be greater than one )""" | assert int ( k ) == k and k >= 1 , 'Chi-Squared "k" must be an integer greater than 0'
return uv ( ss . chi2 ( k ) , tag = tag ) |
def load_images ( image_paths : Iterable [ Union [ str , Path ] ] ) -> Iterable [ SpatialImage ] :
"""Load images from paths .
For efficiency , returns an iterator , not a sequence , so the results cannot
be accessed by indexing .
For every new iteration through the images , load _ images must be called
aga... | for image_path in image_paths :
if isinstance ( image_path , Path ) :
string_path = str ( image_path )
else :
string_path = image_path
logger . debug ( 'Starting to read file %s' , string_path )
yield nib . load ( string_path ) |
def rest_verbs ( http_method_names = None ) :
"""Decorator that converts a function - based view into an RestView subclass .
Takes a list of allowed methods for the view as an argument .""" | http_method_names = [ 'GET' ] if ( http_method_names is None ) else http_method_names
def decorator ( func ) :
WrappedRestView = type ( six . PY3 and 'WrappedRestView' or b'WrappedRestView' , ( RestView , ) , { '__doc__' : func . __doc__ } )
# Note , the above allows us to set the docstring .
# It is the eq... |
def collapse ( self , id_user ) :
"""Collapse comment beloging to user .""" | c = CmtCOLLAPSED ( id_bibrec = self . id_bibrec , id_cmtRECORDCOMMENT = self . id , id_user = id_user )
db . session . add ( c )
db . session . commit ( ) |
def get_adapter_path ( obj , to_cls ) :
"""Returns the adapter path that would be used to adapt ` obj ` to ` to _ cls ` .""" | from_cls = type ( obj )
key = ( from_cls , to_cls )
if key not in __mro__ :
__mro__ [ key ] = list ( itertools . product ( inspect . getmro ( from_cls ) , inspect . getmro ( to_cls ) ) )
return __mro__ [ key ] |
def map_id ( self , id , prefix , closure_list ) :
"""Map identifiers based on an equivalence closure list .""" | prefixc = prefix + ':'
ids = [ eid for eid in closure_list if eid . startswith ( prefixc ) ]
# TODO : add option to fail if no mapping , or if > 1 mapping
if len ( ids ) == 0 : # default to input
return id
return ids [ 0 ] |
def bar3d ( h2 : Histogram2D , ax : Axes3D , ** kwargs ) :
"""Plot of 2D histograms as 3D boxes .""" | density = kwargs . pop ( "density" , False )
data = get_data ( h2 , cumulative = False , flatten = True , density = density )
if "cmap" in kwargs :
cmap = _get_cmap ( kwargs )
_ , cmap_data = _get_cmap_data ( data , kwargs )
colors = cmap ( cmap_data )
else :
colors = kwargs . pop ( "color" , "blue" )
x... |
def getrolesurl ( idrole = '' , * args , ** kwargs ) :
"""Request Roles URL .
If idrole is set , you ' ll get a response adequate for a MambuRole
object . If not set , you ' ll get a response adequate for a MambuRoles
object too . See mamburoles module and pydoc for further
information .
See Mambu officia... | url = getmambuurl ( * args , ** kwargs ) + "userroles" + ( ( "/" + idrole ) if idrole else "" )
return url |
def tree ( s , token = [ WORD , POS , CHUNK , PNP , REL , LEMMA ] ) :
"""Returns a parsed Text from the given parsed string .""" | return Text ( s , token ) |
def os_release ( package , base = 'essex' , reset_cache = False ) :
'''Returns OpenStack release codename from a cached global .
If reset _ cache then unset the cached os _ release version and return the
freshly determined version .
If the codename can not be determined from either an installed package or
t... | global _os_rel
if reset_cache :
reset_os_release ( )
if _os_rel :
return _os_rel
_os_rel = ( get_os_codename_package ( package , fatal = False ) or get_os_codename_install_source ( config ( 'openstack-origin' ) ) or base )
return _os_rel |
def signout ( request , next_page = accounts_settings . ACCOUNTS_REDIRECT_ON_SIGNOUT , template_name = 'accounts/signout.html' , * args , ** kwargs ) :
"""Signs out the user and adds a success message ` ` You have been signed
out . ` ` If next _ page is defined you will be redirected to the URI . If
not the tem... | if request . user . is_authenticated ( ) and accounts_settings . ACCOUNTS_USE_MESSAGES : # pragma : no cover
messages . success ( request , _ ( 'You have been signed out.' ) , fail_silently = True )
return Signout ( request , next_page , template_name , * args , ** kwargs ) |
def configure_integration ( path ) :
"""Configure and enable an integration .""" | integration = register_integration ( path )
integration_args = { }
try :
with open ( os . path . join ( path , ARGS_JSON ) ) as f :
integration_args = json . loads ( f . read ( ) )
except Exception as exc :
logger . debug ( str ( exc ) , exc_info = True )
raise click . ClickException ( "Cannot load ... |
def randomDecimalField ( self , model_class , field_name ) :
"""Validate if the field has a ` max _ digits ` and ` decimal _ places `
And generating the unique decimal number .""" | decimal_field = model_class . _meta . get_field ( field_name )
max_digits = None
decimal_places = None
if decimal_field . max_digits is not None :
max_digits = decimal_field . max_digits
if decimal_field . decimal_places is not None :
decimal_places = decimal_field . decimal_places
digits = random . choice ( ra... |
def jaccard_sims ( feature_list ) :
"""Compute Jaccard similarities between all the observations in the feature list .
Args :
feature _ list : a list of dictionaries , each having structure as
{ ' md5 ' : String , ' features ' : list of Strings }
Returns :
list of dictionaries with structure as
{ ' sour... | sim_info_list = [ ]
for feature_info in feature_list :
md5_source = feature_info [ 'md5' ]
features_source = feature_info [ 'features' ]
for feature_info in feature_list :
md5_target = feature_info [ 'md5' ]
features_target = feature_info [ 'features' ]
if md5_source == md5_target :
... |
def _pcdata_nodes ( pcdata ) :
"""Return a list of minidom nodes with the properly escaped ` ` pcdata ` `
inside .
The following special XML characters are escaped :
* left angle bracket ( < )
* Right angle bracket ( > )
* Ampersand ( & )
By default , XML - based escaping is used for these characters . ... | nodelist = [ ]
if _CDATA_ESCAPING and isinstance ( pcdata , six . string_types ) and ( pcdata . find ( "<" ) >= 0 or pcdata . find ( ">" ) >= 0 or pcdata . find ( "&" ) >= 0 ) : # noqa : E129
# In order to support nesting of CDATA sections , we represent pcdata
# that already contains CDATA sections by multiple new CDA... |
def BSR_Row_WriteScalar ( A , i , x ) :
"""Write a scalar at each nonzero location in row i of BSR matrix A .
Parameters
A : bsr _ matrix
Input matrix
i : int
Row number
x : float
Scalar to overwrite nonzeros of row i in A
Returns
A : bsr _ matrix
All nonzeros in row i of A have been overwritten... | blocksize = A . blocksize [ 0 ]
BlockIndx = int ( i / blocksize )
rowstart = A . indptr [ BlockIndx ]
rowend = A . indptr [ BlockIndx + 1 ]
localRowIndx = i % blocksize
# for j in range ( rowstart , rowend ) :
# indys = A . data [ j , localRowIndx , : ] . nonzero ( ) [ 0]
# increment = indys . shape [ 0]
# A . data [ j... |
def set_discrimination_value ( self , discrimination ) :
"""stub""" | if not isinstance ( discrimination , float ) :
raise InvalidArgument ( 'discrimination value must be a decimal' )
self . add_decimal_value ( discrimination , 'discrimination' ) |
def setup_handler ( self , io_loop ) :
""": meth : ` . WIOLoopServiceHandler . setup _ handler ` implementation . When this object is in
' non - server mode ' ( client mode ) , then beacon message is sent""" | WNativeSocketHandler . setup_handler ( self , io_loop )
if self . server_mode ( ) is False :
self . io_handler ( ) . transport_socket ( ) . sendto ( self . io_handler ( ) . messenger ( ) . request ( self . config ( ) ) , self . transport ( ) . target_socket ( self . config ( ) ) . pair ( ) ) |
def __convert ( root , tag , values , func ) :
"""Converts the tag type found in the root and converts them using the func
and appends them to the values .""" | elements = root . getElementsByTagName ( tag )
for element in elements :
converted = func ( element )
# Append to the list
__append_list ( values , converted ) |
async def SetMeterStatus ( self , statues ) :
'''statues : typing . Sequence [ ~ MeterStatusParam ]
Returns - > typing . Sequence [ ~ ErrorResult ]''' | # map input types to rpc msg
_params = dict ( )
msg = dict ( type = 'MetricsDebug' , request = 'SetMeterStatus' , version = 2 , params = _params )
_params [ 'statues' ] = statues
reply = await self . rpc ( msg )
return reply |
def parse_passage ( obj : dict ) -> BioCPassage :
"""Deserialize a dict obj to a BioCPassage object""" | passage = BioCPassage ( )
passage . offset = obj [ 'offset' ]
passage . infons = obj [ 'infons' ]
if 'text' in obj :
passage . text = obj [ 'text' ]
for sentence in obj [ 'sentences' ] :
passage . add_sentence ( parse_sentence ( sentence ) )
for annotation in obj [ 'annotations' ] :
passage . add_annotation... |
def remove_output_data_port ( self , data_port_id , force = False , destroy = True ) :
"""Overwrites the remove _ output _ data _ port method of the State class . Prevents user from removing a
output data port from the library state .
For further documentation , look at the State class .
: param bool force : ... | if force :
return State . remove_output_data_port ( self , data_port_id , force , destroy )
else :
raise NotImplementedError ( "Remove output data port is not implemented for library state {}" . format ( self ) ) |
def make_quantile_df ( data , draw_quantiles ) :
"""Return a dataframe with info needed to draw quantile segments""" | dens = data [ 'density' ] . cumsum ( ) / data [ 'density' ] . sum ( )
ecdf = interp1d ( dens , data [ 'y' ] , assume_sorted = True )
ys = ecdf ( draw_quantiles )
# Get the violin bounds for the requested quantiles
violin_xminvs = interp1d ( data [ 'y' ] , data [ 'xminv' ] ) ( ys )
violin_xmaxvs = interp1d ( data [ 'y' ... |
def fn_name ( fn ) :
'''Gets a funtion fully quaified name .
Args :
fn : The function .
Returns : The name of the function .''' | expression = '(\S+) (?:of|at)'
# Checks if the function is a mehtod and should have the self argument passed
is_method = inspect . ismethod ( fn )
# Builds the name of the method , module . class . method or module . method
name = '{}.{}' . format ( fn . __module__ , re . compile ( expression ) . findall ( str ( fn ) )... |
def night_light ( self ) :
"""Build command for turning the led to night light mode .
: return : The command .""" | return self . _build_command ( self . NIGHT_BYTES [ self . _group_number - 1 ] , select = True , select_command = self . off ( ) ) |
def _increment_prop ( self , prop , path = None , ** kwargs ) :
"""increments the property path count
args :
prop : the key for the prop
path : the path to the prop
kwargs :
current : dictionary count for the current dictionay""" | new_path = self . make_path ( prop , path )
if self . method == 'simple' :
counter = kwargs [ 'current' ]
else :
counter = self . counts
try :
counter [ new_path ] += 1
except KeyError :
counter [ new_path ] = 1
return counter |
def disposition ( self , value ) :
"""The content - disposition of the attachment , specifying display style .
Specifies how you would like the attachment to be displayed .
- " inline " results in the attached file being displayed automatically
within the message .
- " attachment " results in the attached f... | if isinstance ( value , Disposition ) :
self . _disposition = value
else :
self . _disposition = Disposition ( value ) |
def get_metadata ( feature_name , etextno ) :
"""Looks up the value of a meta - data feature for a given text .
Arguments :
feature _ name ( str ) : The name of the meta - data to look up .
etextno ( int ) : The identifier of the Gutenberg text for which to look
up the meta - data .
Returns :
frozenset ... | metadata_values = MetadataExtractor . get ( feature_name ) . get_metadata ( etextno )
return frozenset ( metadata_values ) |
def send_messages ( self , messages ) :
"""Send messages .
: param list messages : List of SmsMessage instances .
: returns : number of messages sended successful .
: rtype : int""" | counter = 0
for message in messages :
res , _ = self . _send ( message )
if res :
counter += 1
return counter |
def ReadList ( self , * branches , ** kwargs ) :
"""Same as ` phi . dsl . Expression . List ` but any string argument ` x ` is translated to ` Read ( x ) ` .""" | branches = map ( lambda x : E . Read ( x ) if isinstance ( x , str ) else x , branches )
return self . List ( * branches , ** kwargs ) |
def delete ( self ) :
"""Destructor .""" | if self . glucose :
pysolvers . glucose3_del ( self . glucose )
self . glucose = None
if self . prfile :
self . prfile . close ( ) |
def get_xy_array ( x_segment , y_segment ) :
"""input : x _ segment , y _ segment
output : xy _ segment , ( format : [ ( x [ 0 ] , y [ 0 ] ) , ( x [ 1 ] , y [ 1 ] ) ]""" | xy_array = [ ]
for num , x in enumerate ( x_segment ) :
xy_array . append ( ( x , y_segment [ num ] ) )
return xy_array |
def xml_marshal_complete_multipart_upload ( uploaded_parts ) :
"""Marshal ' s complete multipart upload request based on * uploaded _ parts * .
: param uploaded _ parts : List of all uploaded parts , ordered by part number .
: return : Marshalled XML data .""" | root = s3_xml . Element ( 'CompleteMultipartUpload' , { 'xmlns' : _S3_NAMESPACE } )
for uploaded_part in uploaded_parts :
part_number = uploaded_part . part_number
part = s3_xml . SubElement ( root , 'Part' )
part_num = s3_xml . SubElement ( part , 'PartNumber' )
part_num . text = str ( part_number )
... |
def from_record ( cls , record ) :
"""Factory methods to create Record from pymarc . Record object .""" | if not isinstance ( record , pymarc . Record ) :
raise TypeError ( 'record must be of type pymarc.Record' )
record . __class__ = Record
return record |
def euler_options ( fn ) :
"""Decorator to link CLI options with their appropriate functions""" | euler_functions = cheat , generate , preview , skip , verify , verify_all
# Reverse functions to print help page options in alphabetical order
for option in reversed ( euler_functions ) :
name , docstring = option . __name__ , option . __doc__
kwargs = { 'flag_value' : option , 'help' : docstring }
# Apply ... |
def generate_basic ( self ) :
"""RFC 2617.""" | from base64 import b64encode
if not self . basic_auth :
creds = self . username + ':' + self . password
self . basic_auth = 'Basic '
self . basic_auth += b64encode ( creds . encode ( 'UTF-8' ) ) . decode ( 'UTF-8' )
return self . basic_auth |
def extract_version ( ) :
"""Extract the version from the package .""" | with open ( 'pdftools/__init__.py' , 'r' ) as f :
content = f . read ( )
version_match = _version_re . search ( content )
version = str ( ast . literal_eval ( version_match . group ( 1 ) ) )
return version |
def _Open ( self , path_spec , mode = 'rb' ) :
"""Opens the file system object defined by path specification .
Args :
path _ spec ( PathSpec ) : path specification of the file system .
mode ( Optional [ str ] ) : file access mode . The default is ' rb ' which
represents read - only binary .
Raises :
Acc... | if not path_spec . HasParent ( ) :
raise errors . PathSpecError ( 'Unsupported path specification without parent.' )
file_object = resolver . Resolver . OpenFileObject ( path_spec . parent , resolver_context = self . _resolver_context )
try :
zip_file = zipfile . ZipFile ( file_object , 'r' )
except :
file_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.