signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def from_analysis_period ( cls , analysis_period , tau_b , tau_d , daylight_savings_indicator = 'No' ) :
"""" Initialize a RevisedClearSkyCondition from an analysis _ period""" | _check_analysis_period ( analysis_period )
return cls ( analysis_period . st_month , analysis_period . st_day , tau_b , tau_d , daylight_savings_indicator ) |
def has_transition_perm ( bound_method , user ) :
"""Returns True if model in state allows to call bound _ method and user have rights on it""" | if not hasattr ( bound_method , '_django_fsm' ) :
im_func = getattr ( bound_method , 'im_func' , getattr ( bound_method , '__func__' ) )
raise TypeError ( '%s method is not transition' % im_func . __name__ )
meta = bound_method . _django_fsm
im_self = getattr ( bound_method , 'im_self' , getattr ( bound_method ... |
def wash_line ( line ) :
"""Wash a text line of certain punctuation errors , replacing them with
more correct alternatives . E . g . : the string ' Yes , I like python . '
will be transformed into ' Yes , I like python . '
@ param line : ( string ) the line to be washed .
@ return : ( string ) the washed li... | line = re_space_comma . sub ( ',' , line )
line = re_space_semicolon . sub ( ';' , line )
line = re_space_period . sub ( '.' , line )
line = re_colon_space_colon . sub ( ':' , line )
line = re_comma_space_colon . sub ( ':' , line )
line = re_space_closing_square_bracket . sub ( ']' , line )
line = re_opening_square_bra... |
def get_category ( self , slug ) :
"""Get the category object""" | try :
return get_category_for_slug ( slug )
except ObjectDoesNotExist as e :
raise Http404 ( str ( e ) ) |
def telnet_sa_telnet_server_telnet_vrf_cont_use_vrf_use_vrf_name ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
telnet_sa = ET . SubElement ( config , "telnet-sa" , xmlns = "urn:brocade.com:mgmt:brocade-sec-services" )
telnet = ET . SubElement ( telnet_sa , "telnet" )
server = ET . SubElement ( telnet , "server" )
telnet_vrf_cont = ET . SubElement ( server , "telnet-vrf-cont" )
use_vrf = ET . S... |
def _identify_dict ( core ) :
"""Specification for a dictionary .""" | if not core :
return { } , 1 , ( ) , int
core = core . copy ( )
key = sorted ( core . keys ( ) , key = chaospy . poly . base . sort_key ) [ 0 ]
shape = numpy . array ( core [ key ] ) . shape
dtype = numpy . array ( core [ key ] ) . dtype
dim = len ( key )
return core , dim , shape , dtype |
def casting_operators ( self , name = None , function = None , return_type = None , arg_types = None , header_dir = None , header_file = None , recursive = None , allow_empty = None ) :
"""returns a set of casting operator declarations , that are matched
defined criteria""" | return ( self . _find_multiple ( self . _impl_matchers [ scopedef_t . casting_operator ] , name = name , function = function , decl_type = self . _impl_decl_types [ scopedef_t . casting_operator ] , return_type = return_type , arg_types = arg_types , header_dir = header_dir , header_file = header_file , recursive = rec... |
def raw ( self , query ) :
"""make a raw query
Args :
query ( str ) : solr query
\*\*params: solr parameters""" | clone = copy . deepcopy ( self )
clone . adapter . _pre_compiled_query = query
clone . adapter . compiled_query = query
return clone |
def slugify ( self , value ) :
"""Normalizes string , converts to lowercase , removes non - alpha characters ,
and converts spaces to hyphens .""" | value = unicodedata . normalize ( 'NFKD' , value ) . encode ( 'ascii' , 'ignore' )
value = unicode ( re . sub ( '[^\w\s-]' , '' , value ) . strip ( ) . lower ( ) )
return re . sub ( '[-\s]+' , '-' , value ) |
def check_url ( self , pid , url_list ) :
'''urlCheck 返回数据
" rtn " : 0,
" taskInfo " : {
" failCode " : 0,
" name " : " . HDTVrip . 1024X576 . mkv " ,
" url " : " ed2k : / / | file | % E6 % B0 % " ,
" type " : 1,
" id " : " 0 " ,
" size " : 505005442''' | task_list = [ ]
for url in url_list :
params = { 'pid' : pid , 'url' : url , 'type' : 1 , 'v' : DEFAULT_V , 'ct' : DEFAULT_CT }
res = self . _get ( 'urlCheck' , params = params )
if res [ 'rtn' ] == 0 :
task_info = res [ 'taskInfo' ]
task_list . append ( { 'url' : task_info [ 'url' ] , 'name... |
def execute ( self ) :
"""execute Webhook
: return :""" | if bool ( self . files ) is False :
response = requests . post ( self . url , json = self . json , proxies = self . proxies )
else :
self . files [ 'payload_json' ] = ( None , json . dumps ( self . json ) )
response = requests . post ( self . url , files = self . files , proxies = self . proxies )
if respon... |
def update_lens_scaling ( self , kwargs_cosmo , kwargs_lens , inverse = False ) :
"""multiplies the scaling parameters of the profiles
: param args :
: param kwargs _ lens :
: param i :
: param inverse :
: return :""" | kwargs_lens_updated = copy . deepcopy ( kwargs_lens )
if self . _mass_scaling is False :
return kwargs_lens_updated
scale_factor_list = np . array ( kwargs_cosmo [ 'scale_factor' ] )
if inverse is True :
scale_factor_list = 1. / np . array ( kwargs_cosmo [ 'scale_factor' ] )
for i , kwargs in enumerate ( kwargs... |
def _listdir ( pth , extensions ) :
"""Non - raising listdir .""" | try :
return [ fname for fname in os . listdir ( pth ) if os . path . splitext ( fname ) [ 1 ] in extensions ]
except OSError : # pragma : nocover
pass |
def coerce ( self , other , is_positive = True ) :
"""Only copies a pointer to the new domain ' s cell""" | if hasattr ( other , 'get_domain' ) and hasattr ( other , 'lower' ) and hasattr ( other , 'upper' ) :
if self . is_domain_equal ( other ) :
return other
else :
msg = "Cannot merge partial orders with different domains!"
raise CellConstructionFailure ( msg )
if isinstance ( other , Linear... |
def _eliminate_leafs ( self , graph ) :
"""Eliminate leaf objects - that are objects not referencing any other
objects in the list ` graph ` . Returns the list of objects without the
objects identified as leafs .""" | result = [ ]
idset = set ( [ id ( x ) for x in graph ] )
for n in graph :
refset = set ( [ id ( x ) for x in get_referents ( n ) ] )
if refset . intersection ( idset ) :
result . append ( n )
return result |
def update_name ( self , name ) :
"""Updates the name of the custom type in this instance and its
parent reference .""" | if name != self . name :
self . parent . types [ name ] = self
del self . parent . types [ self . name ]
self . name = name |
def load_file_pair_list ( filename ) :
"""Load file pair list csv formatted text - file
Format is [ reference _ file ] [ delimiter ] [ estimated _ file ]
Supported delimiters : ` ` , ` ` , ` ` ; ` ` , ` ` tab ` `
Example of file - list : :
office _ snr0 _ high _ v2 . txtoffice _ snr0 _ high _ v2 _ detected ... | data = [ ]
input_file = open ( filename , 'rt' )
try :
dialect = csv . Sniffer ( ) . sniff ( input_file . readline ( ) , [ ',' , ';' , '\t' ] )
except csv . Error :
raise ValueError ( 'Unknown delimiter in file [{file}].' . format ( file = filename ) )
input_file . seek ( 0 )
for row in csv . reader ( input_fil... |
def dict_find_key ( dd , value ) :
"""Find first suitable key in dict .
: param dd :
: param value :
: return :""" | key = next ( key for key , val in dd . items ( ) if val == value )
return key |
def _offset_dt ( cls , dt , offset_str ) :
"""Return a | datetime | instance that is offset from datetime * dt * by
the timezone offset specified in * offset _ str * , a string like
` ` ' - 07:00 ' ` ` .""" | match = cls . _offset_pattern . match ( offset_str )
if match is None :
raise ValueError ( "'%s' is not a valid offset string" % offset_str )
sign , hours_str , minutes_str = match . groups ( )
sign_factor = - 1 if sign == '+' else 1
hours = int ( hours_str ) * sign_factor
minutes = int ( minutes_str ) * sign_facto... |
def onkeydown ( self , key , keycode , ctrl , shift , alt ) :
"""Called when user types and releases a key .
The widget should be able to receive the focus in order to emit the event .
Assign a ' tabindex ' attribute to make it focusable .
Args :
key ( str ) : the character value
keycode ( str ) : the num... | return ( key , keycode , ctrl , shift , alt ) |
def extract_archive ( archive , solver , put_inside = False ) :
"""Unzips / untars a previously downloaded archive file .""" | print ( 'extracting {0}' . format ( archive ) )
root = os . path . join ( 'solvers' , solver if put_inside else '' )
if archive . endswith ( '.tar.gz' ) :
if os . path . exists ( archive [ : - 7 ] ) :
shutil . rmtree ( archive [ : - 7 ] )
tfile = tarfile . open ( archive , 'r:gz' )
tfile . extractal... |
def get_data_model ( self ) :
"""Try to download the data model from Earthref .
If that fails , grab the cached data model .""" | if len ( DM ) :
self . dm = DM
self . crit_map = CRIT_MAP
return
if not set_env . OFFLINE :
dm = self . get_dm_online ( )
if dm :
print ( '-I- Using online data model' )
# self . cache _ data _ model ( dm )
return self . parse_response ( dm )
# if online is not available , ge... |
def register_view ( self , view ) :
"""Loads the text taking it from the model , then starts a
timer to scroll it .""" | self . view . set_text ( self . model . credits )
gobject . timeout_add ( 1500 , self . on_begin_scroll )
return |
def get_signature ( name , thing ) :
"""Get the signature for a function or class , formatted nicely if possible .
Parameters
name : str
Name of the thing , used as the first part of the signature
thing : class or function
Thing to get the signature of""" | if inspect . ismodule ( thing ) :
return ""
if isinstance ( thing , property ) :
func_sig = name
else :
try :
sig = inspect . signature ( thing )
except TypeError :
sig = inspect . signature ( thing . fget )
except ValueError :
return ""
func_sig = f"{name}{sig}"
try ... |
def init ( ctx , force ) :
"""Wizard to create a project - level configuration file .""" | if os . path . exists ( PROJECT_CONFIG ) and not force :
click . secho ( 'An existing configuration file was found at "{}".\n' . format ( PROJECT_CONFIG ) , fg = 'red' , bold = True )
click . secho ( 'Please remove it before in order to run the setup wizard or use\n' 'the --force flag to overwrite it.' )
ct... |
def rename_bika_setup ( ) :
"""Rename Bika Setup to just Setup to avoid naming confusions for new users""" | logger . info ( "Renaming Bika Setup..." )
bika_setup = api . get_bika_setup ( )
bika_setup . setTitle ( "Setup" )
bika_setup . reindexObject ( )
setup = api . get_portal ( ) . portal_setup
setup . runImportStepFromProfile ( 'profile-bika.lims:default' , 'controlpanel' ) |
def _log_tcex_version ( self ) :
"""Log the current TcEx version number .""" | self . log . info ( u'TcEx Version: {}' . format ( __import__ ( __name__ ) . __version__ ) ) |
def get_user_info ( self , steamID ) :
"""Request the Steam Community XML feed for a specific user .""" | url = self . create_request_url ( self . USER , steamID )
data = self . retrieve_request ( url )
return self . return_data ( data , format = 'xml' ) |
def gday_of_year ( self ) :
"""Return the number of days since January 1 of the given year .""" | return ( self . date - dt . date ( self . date . year , 1 , 1 ) ) . days |
def rebin_coord_transform ( factor , x_at_radec_0 , y_at_radec_0 , Mpix2coord , Mcoord2pix ) :
"""adopt coordinate system and transformation between angular and pixel coordinates of a re - binned image
: param bin _ size :
: param ra _ 0:
: param dec _ 0:
: param x _ 0:
: param y _ 0:
: param Matrix :
... | factor = int ( factor )
Mcoord2pix_resized = Mcoord2pix / factor
Mpix2coord_resized = Mpix2coord * factor
x_at_radec_0_resized = ( x_at_radec_0 + 0.5 ) / factor - 0.5
y_at_radec_0_resized = ( y_at_radec_0 + 0.5 ) / factor - 0.5
ra_at_xy_0_resized , dec_at_xy_0_resized = util . map_coord2pix ( - x_at_radec_0_resized , -... |
def staff_member_required ( request ) :
"Lookup decorator to require the user is a staff member ." | user = getattr ( request , 'user' , None )
if user is None or not user . is_authenticated :
return HttpResponse ( status = 401 )
# Unauthorized
elif not user . is_staff :
return HttpResponseForbidden ( ) |
def current_room_temp ( self ) :
"""Return current room temperature for in - progress session .""" | try :
rmtemps = self . intervals [ 0 ] [ 'timeseries' ] [ 'tempRoomC' ]
num_temps = len ( rmtemps )
if num_temps == 0 :
return None
rmtemp = rmtemps [ num_temps - 1 ] [ 1 ]
except KeyError :
rmtemp = None
return rmtemp |
def update_multiarray_shape_range ( spec , feature_name , shape_range ) :
"""Annotate an input or output MLMultiArray feature in a Neural Network spec
to accommodate a range of shapes
: param spec : MLModel
The MLModel spec containing the feature
: param feature _ name : str
The name of the feature for wh... | if not isinstance ( shape_range , NeuralNetworkMultiArrayShapeRange ) :
raise Exception ( 'Shape range should be of type MultiArrayShapeRange' )
shape_range . validate_array_shape_range ( )
feature = _get_feature ( spec , feature_name )
if feature . type . WhichOneof ( 'Type' ) != 'multiArrayType' :
raise Excep... |
def move_previews ( self ) :
"Move previews after a resize event" | # calculate new positions
min_y = self . _calc_preview_ypos ( )
for idx , ( key , p ) in enumerate ( self . previews . items ( ) ) :
new_dy = min_y [ idx ] - p . y
self . previews [ key ] . move_by ( 0 , new_dy )
self . _update_cregion ( )
self . show_selected ( self . _sel_id , self . _sel_widget ) |
def parse_post ( self , response ) :
'''根据 : meth : ` . ZhihuDailySpider . parse ` 中生成的具体文章地址 , 获取到文章内容 ,
并对其进行格式化处理 , 结果填充到对象属性 ` ` item _ list ` ` 中
: param Response response : 由 ` ` Scrapy ` ` 调用并传入的请求响应对象''' | content = json . loads ( response . body . decode ( ) , encoding = 'UTF-8' )
post = response . meta [ 'post' ]
post [ 'origin_url' ] = content . get ( 'share_url' , '' )
if not all ( [ post [ 'origin_url' ] ] ) :
raise ValueError ( '原文地址为空' )
post [ 'title' ] = html . escape ( content . get ( 'title' , '' ) )
if no... |
def is_jail ( name ) :
'''Return True if jail exists False if not
CLI Example :
. . code - block : : bash
salt ' * ' poudriere . is _ jail < jail name >''' | jails = list_jails ( )
for jail in jails :
if jail . split ( ) [ 0 ] == name :
return True
return False |
def dependents_of ( self , address ) :
"""Returns the addresses of the targets that depend on the target at ` address ` .
This method asserts that the address given is actually in the BuildGraph .
: API : public""" | assert address in self . _target_by_address , ( 'Cannot retrieve dependents of {address} because it is not in the BuildGraph.' . format ( address = address ) )
return self . _target_dependees_by_address [ address ] |
def _validate_value ( self , proposal ) :
"Replace all values with the actual objects in the options list" | try :
return tuple ( findvalue ( self . _options_values , i , self . equals ) for i in proposal . value )
except ValueError :
raise TraitError ( 'Invalid selection: value not found' ) |
def ref ( self ) :
'''A Bokeh protocol " reference " to this model , i . e . a dict of the
form :
. . code - block : : python
' type ' : < < view model name > >
' id ' : < < unique model id > >
Additionally there may be a ` subtype ` field if this model is a subtype .''' | if "__subtype__" in self . __class__ . __dict__ :
return { 'type' : self . __view_model__ , 'subtype' : self . __subtype__ , 'id' : self . id , }
else :
return { 'type' : self . __view_model__ , 'id' : self . id , } |
def _findlinestarts ( code ) :
"""Find the offsets in a byte code which are start of lines in the source .
Generate pairs ( offset , lineno ) as described in Python / compile . c .
Arguments :
code : code object .
Yields :
Address and line number pairs .""" | byte_increments = [ ord ( c ) for c in code . co_lnotab [ 0 : : 2 ] ]
line_increments = [ ord ( c ) for c in code . co_lnotab [ 1 : : 2 ] ]
lastlineno = None
lineno = code . co_firstlineno
addr = 0
for byte_incr , line_incr in zip ( byte_increments , line_increments ) :
if byte_incr :
if lineno != lastlinen... |
def wrann ( self , write_fs = False , write_dir = '' ) :
"""Write a WFDB annotation file from this object .
Parameters
write _ fs : bool , optional
Whether to write the ` fs ` attribute to the file .""" | for field in [ 'record_name' , 'extension' ] :
if getattr ( self , field ) is None :
raise Exception ( 'Missing required field for writing annotation file: ' , field )
present_label_fields = self . get_label_fields ( )
if not present_label_fields :
raise Exception ( 'At least one annotation label field ... |
def extract ( dump_files , extractors = ALL_EXTRACTORS ) :
"""Extracts cites from a set of ` dump _ files ` .
: Parameters :
dump _ files : str | ` file `
A set of files MediaWiki XML dump files
( expects : pages - meta - history )
extractors : ` list ` ( ` extractor ` )
A list of extractors to apply to... | # Dump processor function
def process_dump ( dump , path ) :
for page in dump :
if page . namespace != 0 :
continue
else :
for cite in extract_cite_history ( page , extractors ) :
yield cite
# Map call
return mwxml . map ( process_dump , dump_files ) |
def clean_session_table ( ) :
"""Automatically clean session table .
To enable a periodically clean of the session table , you should configure
the task as a celery periodic task .
. . code - block : : python
from datetime import timedelta
CELERYBEAT _ SCHEDULE = {
' session _ cleaner ' : {
' task ' :... | sessions = SessionActivity . query_by_expired ( ) . all ( )
for session in sessions :
delete_session ( sid_s = session . sid_s )
db . session . commit ( ) |
def _remove_previous_ned_queries ( self , coordinateList ) :
"""iterate through the transient locations to see if we have recent local NED coverage of that area already
* * Key Arguments : * *
- ` ` coordinateList ` ` - - set of coordinate to check for previous queries
* * Return : * *
- ` ` updatedCoordina... | self . log . debug ( 'starting the ``_remove_previous_ned_queries`` method' )
# 1 DEGREE QUERY RADIUS
radius = 60. * 60.
updatedCoordinateList = [ ]
keepers = [ ]
# CALCULATE THE OLDEST RESULTS LIMIT
now = datetime . now ( )
td = timedelta ( days = self . settings [ "ned stream refresh rate in days" ] )
refreshLimit = ... |
def share ( self , value , perm_type , role , notify = True , email_message = None , with_link = False ) :
"""Share the spreadsheet with other accounts .
: param value : user or group e - mail address , domain name
or None for ' default ' type .
: type value : str , None
: param perm _ type : The account ty... | self . client . insert_permission ( self . id , value = value , perm_type = perm_type , role = role , notify = notify , email_message = email_message , with_link = with_link ) |
def get_sources ( self , kind = 'all' ) :
"""Extract the sources contained in the source models by optionally
filtering and splitting them , depending on the passed parameter .""" | assert kind in ( 'all' , 'indep' , 'mutex' ) , kind
sources = [ ]
for sm in self . source_models :
for src_group in sm . src_groups :
if kind in ( 'all' , src_group . src_interdep ) :
for src in src_group :
if sm . samples > 1 :
src . samples = sm . samples
... |
def clear_host_port ( self ) :
"""Stops the adb port forwarding of the host port used by this client .""" | if self . host_port :
self . _adb . forward ( [ '--remove' , 'tcp:%d' % self . host_port ] )
self . host_port = None |
def readAlignedString ( self , align = 4 ) :
"""Reads an ASCII string aligned to the next align - bytes boundary .
@ type align : int
@ param align : ( Optional ) The value we want the ASCII string to be aligned .
@ rtype : str
@ return : A 4 - bytes aligned ( default ) ASCII string .""" | s = self . readString ( )
r = align - len ( s ) % align
while r :
s += self . data [ self . offset ]
self . offset += 1
r -= 1
return s . rstrip ( "\x00" ) |
def targetSurfacemass ( self , R , log = False ) :
"""NAME :
targetSurfacemass
PURPOSE :
evaluate the target surface mass at R
INPUT :
R - radius at which to evaluate ( can be Quantity )
log - if True , return the log ( default : False )
OUTPUT :
Sigma ( R )
HISTORY :
2010-03-28 - Written - Bovy... | return self . _surfaceSigmaProfile . surfacemass ( R , log = log ) |
def do_help ( self , line ) :
"""Get help on commands " help " or " ? " with no arguments displays a list _ objects
of commands for which help is available " help < command > " or " ?
< command > " gives help on < command >""" | command , = self . _split_args ( line , 0 , 1 )
if command is None :
return self . _print_help ( )
cmd . Cmd . do_help ( self , line ) |
def get ( self , field , value = None ) :
"""Gets user input for given field and checks if it is valid .
If input is invalid , it will ask the user to enter it again .
Defaults values to empty or : value : .
It does not check validity of parent index . It can only be tested
further down the road , so for no... | self . value = value
val = self . input ( field )
if field == 'name' :
while True :
if val != '' :
break
print ( "Name cannot be empty." )
val = self . input ( field )
elif field == 'priority' :
if val == '' : # Use default priority
return None
while True :
... |
def humanize ( number ) :
"""Return a human - readable string for number .""" | # units = ( ' bytes ' , ' KB ' , ' MB ' , ' GB ' , ' TB ' )
# base = 1000
units = ( 'bytes' , 'KiB' , 'MiB' , 'GiB' , 'TiB' )
base = 1024
if number is None :
return None
pow = int ( math . log ( number , base ) ) if number > 0 else 0
pow = min ( pow , len ( units ) - 1 )
mantissa = number / ( base ** pow )
return "... |
def available_packages ( * args , ** kwargs ) :
'''Query available plugin packages based on specified Conda channels .
Parameters
* args
Extra arguments to pass to Conda ` ` search ` ` command .
Returns
dict
. . versionchanged : : 0.24
All Conda packages beginning with ` ` microdrop . ` ` prefix from ... | # Get list of available MicroDrop plugins , i . e . , Conda packages that start
# with the prefix ` microdrop . ` .
try :
plugin_packages_info_json = ch . conda_exec ( 'search' , '--json' , '^microdrop\.' , verbose = False )
return json . loads ( plugin_packages_info_json )
except RuntimeError , exception :
... |
def compute_training_sizes ( train_perc , class_sizes , stratified = True ) :
"""Computes the maximum training size that the smallest class can provide""" | size_per_class = np . int64 ( np . around ( train_perc * class_sizes ) )
if stratified :
print ( "Different classes in training set are stratified to match smallest class!" )
# per - class
size_per_class = np . minimum ( np . min ( size_per_class ) , size_per_class )
# single number
reduced_sizes = ... |
def wrap ( self , value , timestamp = None ) :
"""Pack python value into Value""" | V = self . type ( )
S , NS = divmod ( float ( timestamp or time . time ( ) ) , 1.0 )
V . timeStamp = { 'secondsPastEpoch' : S , 'nanoseconds' : NS * 1e9 , }
if isinstance ( value , dict ) : # assume dict of index and choices list
V . value = value
self . _choices = V [ 'value.choices' ]
else : # index or string... |
def build_item ( title , key = None , synonyms = None , description = None , img_url = None , alt_text = None ) :
"""Builds an item that may be added to List or Carousel""" | item = { "info" : { "key" : key or title , "synonyms" : synonyms or [ ] } , "title" : title , "description" : description , "image" : { "imageUri" : img_url or "" , "accessibilityText" : alt_text or "{} img" . format ( title ) , } , }
return item |
def read ( self , offset ) :
""". . _ read :
Returns the value of the memory word at ` ` offset ` ` .
Might raise WriteOnlyError _ , if the device is write - only .
Might raise AddressError _ , if the offset exceeds the size of the device .""" | if ( not self . mode & 0b01 ) :
raise WriteOnlyError ( "Device is Write-Only" )
if ( offset >= self . size ) :
raise AddressError ( "Offset({}) not in address space({})" . format ( offset , self . size ) )
return self . repr_ [ offset ] . getvalue ( ) |
def settings_loader ( obj , settings_module = None , env = None , silent = True , key = None , filename = None ) :
"""Loads from defined settings module
: param obj : A dynaconf instance
: param settings _ module : A path or a list of paths e . g settings . toml
: param env : Env to look for data defaults : d... | if filename is None :
settings_module = settings_module or obj . settings_module
if not settings_module : # pragma : no cover
return
files = ensure_a_list ( settings_module )
else :
files = ensure_a_list ( filename )
files . extend ( ensure_a_list ( obj . get ( "SECRETS_FOR_DYNACONF" , None ) ) ... |
def rbdd ( * keywords ) :
"""Run story matching keywords and rewrite story if code changed .""" | settings = _personal_settings ( ) . data
settings [ "engine" ] [ "rewrite" ] = True
_storybook ( settings [ "engine" ] ) . with_params ( ** { "python version" : settings [ "params" ] [ "python version" ] } ) . only_uninherited ( ) . shortcut ( * keywords ) . play ( ) |
def make_random_gaussians_table ( n_sources , param_ranges , random_state = None ) :
"""Make a ` ~ astropy . table . Table ` containing randomly generated
parameters for 2D Gaussian sources .
Each row of the table corresponds to a Gaussian source whose
parameters are defined by the column names . The paramete... | sources = make_random_models_table ( n_sources , param_ranges , random_state = random_state )
# convert Gaussian2D flux to amplitude
if 'flux' in param_ranges and 'amplitude' not in param_ranges :
model = Gaussian2D ( x_stddev = 1 , y_stddev = 1 )
if 'x_stddev' in sources . colnames :
xstd = sources [ '... |
def _build_processor ( cls , session : AppSession ) :
'''Create the Processor
Returns :
Processor : An instance of : class : ` . processor . BaseProcessor ` .''' | web_processor = cls . _build_web_processor ( session )
ftp_processor = cls . _build_ftp_processor ( session )
delegate_processor = session . factory . new ( 'Processor' )
delegate_processor . register ( 'http' , web_processor )
delegate_processor . register ( 'https' , web_processor )
delegate_processor . register ( 'f... |
def get_ts_stats_significance ( self , x , ts , stat_ts_func , null_ts_func , B = 1000 , permute_fast = False , label_ts = '' ) :
"""Returns the statistics , pvalues and the actual number of bootstrap
samples .""" | stats_ts , pvals , nums = ts_stats_significance ( ts , stat_ts_func , null_ts_func , B = B , permute_fast = permute_fast )
return stats_ts , pvals , nums |
def value_as_datetime ( self ) :
'''Convenience property to retrieve the value tuple as a tuple of
datetime objects .''' | if self . value is None :
return None
v1 , v2 = self . value
if isinstance ( v1 , numbers . Number ) :
d1 = datetime . utcfromtimestamp ( v1 / 1000 )
else :
d1 = v1
if isinstance ( v2 , numbers . Number ) :
d2 = datetime . utcfromtimestamp ( v2 / 1000 )
else :
d2 = v2
return d1 , d2 |
def make_error ( self , error ) :
"""Create a new instance of this stanza ( this directly uses
` ` type ( self ) ` ` , so also works for subclasses without extra care ) which
has the given ` error ` value set as : attr : ` error ` .
In addition , the : attr : ` id _ ` , : attr : ` from _ ` and : attr : ` to `... | obj = type ( self ) ( from_ = self . to , to = self . from_ , # because flat is better than nested ( sarcasm )
type_ = type ( self ) . type_ . type_ . enum_class . ERROR , )
obj . id_ = self . id_
obj . error = error
return obj |
def get_domain_workgroup ( ) :
'''Get the domain or workgroup the computer belongs to .
. . versionadded : : 2015.5.7
. . versionadded : : 2015.8.2
Returns :
str : The name of the domain or workgroup
CLI Example :
. . code - block : : bash
salt ' minion - id ' system . get _ domain _ workgroup''' | with salt . utils . winapi . Com ( ) :
conn = wmi . WMI ( )
for computer in conn . Win32_ComputerSystem ( ) :
if computer . PartOfDomain :
return { 'Domain' : computer . Domain }
else :
return { 'Workgroup' : computer . Workgroup } |
def traverse_by ( self , fixers , traversal ) :
"""Traverse an AST , applying a set of fixers to each node .
This is a helper method for refactor _ tree ( ) .
Args :
fixers : a list of fixer instances .
traversal : a generator that yields AST nodes .
Returns :
None""" | if not fixers :
return
for node in traversal :
for fixer in fixers [ node . type ] :
results = fixer . match ( node )
if results :
new = fixer . transform ( node , results )
if new is not None :
node . replace ( new )
node = new |
def copy_non_reserved ( props , target ) : # type : ( Dict [ str , Any ] , Dict [ str , Any ] ) - > Dict [ str , Any ]
"""Copies all properties with non - reserved names from ` ` props ` ` to ` ` target ` `
: param props : A dictionary of properties
: param target : Another dictionary
: return : The target di... | target . update ( { key : value for key , value in props . items ( ) if not is_reserved_property ( key ) } )
return target |
def gini_coefficient ( y ) :
r"""Implements the Gini inequality index
Parameters
y : array _ like ( float )
Array of income / wealth for each individual . Ordered or unordered is fine
Returns
Gini index : float
The gini index describing the inequality of the array of income / wealth
References
https... | n = len ( y )
i_sum = np . zeros ( n )
for i in prange ( n ) :
for j in range ( n ) :
i_sum [ i ] += abs ( y [ i ] - y [ j ] )
return np . sum ( i_sum ) / ( 2 * n * np . sum ( y ) ) |
def streamserver_handle ( cls , socket , address ) :
'''Translate this class for use in a StreamServer''' | request = cls . dummy_request ( )
request . _sock = socket
server = None
cls ( request , address , server ) |
def getTextualNode ( self , textId : str , subreference : Union [ str , BaseReference ] = None , prevnext : bool = False , metadata : bool = False ) -> TextualNode :
"""Retrieve a text node from the API
: param textId : CtsTextMetadata Identifier
: type textId : str
: param subreference : CapitainsCtsPassage ... | raise NotImplementedError ( ) |
def generate_row_keys ( self ) :
"""Method for generating key features at serving time or prediction time
: param data : Pass in the data that is necessary for generating the keys
Example :
Feature : User warehouse searches and conversions
Keys will be of the form ' user _ id # warehouse _ id # searches = 2... | keys = self . key
columns = self . values
if not self . _data :
self . _data = self . get_data ( )
for column in columns :
key_prefix = self . cache_key_prefix ( ) + "#" + column
self . _data [ 'cache_key' ] = self . _data [ keys ] . apply ( lambda xdf : key_prefix + "=" + '#' . join ( xdf . astype ( str ) ... |
def _rapply ( input_layer , operation , * op_args , ** op_kwargs ) :
"""Applies the given operation to this after expanding op _ args .
Args :
input _ layer : The input layer for this op .
operation : An operation that takes a tensor and the supplied args .
* op _ args : Extra arguments for operation .
* ... | op_args = list ( op_args )
op_args . append ( input_layer . tensor )
return input_layer . with_tensor ( operation ( * op_args , ** op_kwargs ) ) |
def _GetTypeFromScope ( self , package , type_name , scope ) :
"""Finds a given type name in the current scope .
Args :
package : The package the proto should be located in .
type _ name : The name of the type to be found in the scope .
scope : Dict mapping short and full symbols to message and enum types .... | if type_name not in scope :
components = _PrefixWithDot ( package ) . split ( '.' )
while components :
possible_match = '.' . join ( components + [ type_name ] )
if possible_match in scope :
type_name = possible_match
break
else :
components . pop ( - ... |
def get_default_config ( self ) :
"""Return default config
: rtype : dict""" | config = super ( OpenLDAPCollector , self ) . get_default_config ( )
config . update ( { 'path' : 'openldap' , 'host' : 'localhost' , 'port' : 389 , 'username' : 'cn=monitor' , 'password' : 'password' , } )
return config |
def neuron ( layer_name , channel_n , x = None , y = None , batch = None ) :
"""Visualize a single neuron of a single channel .
Defaults to the center neuron . When width and height are even numbers , we
choose the neuron in the bottom right of the center 2x2 neurons .
Odd width & height : Even width & height... | def inner ( T ) :
layer = T ( layer_name )
shape = tf . shape ( layer )
x_ = shape [ 1 ] // 2 if x is None else x
y_ = shape [ 2 ] // 2 if y is None else y
if batch is None :
return layer [ : , x_ , y_ , channel_n ]
else :
return layer [ batch , x_ , y_ , channel_n ]
return inner |
def uridefrag ( uristring ) :
"""Remove an existing fragment component from a URI reference string .""" | if isinstance ( uristring , bytes ) :
parts = uristring . partition ( b'#' )
else :
parts = uristring . partition ( u'#' )
return DefragResult ( parts [ 0 ] , parts [ 2 ] if parts [ 1 ] else None ) |
def regex_findall ( regex , fname ) :
'''Return a list of all non overlapping matches in the string ( s )''' | try :
with fileobj ( fname ) as f :
return re . findall ( regex , f . read ( ) , re . MULTILINE )
except AttributeError :
return [ ] |
def inverseDict ( d ) :
"""Returns a dictionay indexed by values { value _ k : key _ k }
Parameters :
d : dictionary""" | dt = { }
for k , v in list ( d . items ( ) ) :
if type ( v ) in ( list , tuple ) :
for i in v :
dt [ i ] = k
else :
dt [ v ] = k
return dt |
def element_is_empty ( elem_to_parse , element_path = None ) :
"""Returns true if the element is None , or has no text , tail , children or attributes .
Whitespace in the element is stripped from text and tail before making the determination .""" | element = get_element ( elem_to_parse , element_path )
if element is None :
return True
is_empty = ( ( element . text is None or not element . text . strip ( ) ) and ( element . tail is None or not element . tail . strip ( ) ) and ( element . attrib is None or not len ( element . attrib ) ) and ( not len ( element ... |
def replace_deployment ( name , metadata , spec , source , template , saltenv , namespace = 'default' , ** kwargs ) :
'''Replaces an existing deployment with a new one defined by name and
namespace , having the specificed metadata and spec .''' | body = __create_object_body ( kind = 'Deployment' , obj_class = AppsV1beta1Deployment , spec_creator = __dict_to_deployment_spec , name = name , namespace = namespace , metadata = metadata , spec = spec , source = source , template = template , saltenv = saltenv )
cfg = _setup_conn ( ** kwargs )
try :
api_instance ... |
def sgraph ( N_clusters_max , file_name ) :
"""Runs METIS or hMETIS and returns the labels found by those
( hyper - ) graph partitioning algorithms .
Parameters
N _ clusters _ max : int
file _ name : string
Returns
labels : array of shape ( n _ samples , )
A vector of labels denoting the cluster to wh... | if file_name == 'DO_NOT_PROCESS' :
return [ ]
print ( '\n#' )
k = str ( N_clusters_max )
out_name = file_name + '.part.' + k
if file_name == 'wgraph_HGPA' :
print ( "INFO: Cluster_Ensembles: sgraph: " "calling shmetis for hypergraph partitioning." )
if sys . platform . startswith ( 'linux' ) :
shmet... |
def _createComboBoxes ( self , row ) :
"""Creates a combo box for each of the fullAxisNames""" | tree = self . tree
model = self . tree . model ( )
self . _setColumnCountForContents ( )
for col , _ in enumerate ( self . _axisNames , self . COL_FIRST_COMBO ) :
logger . debug ( "Adding combobox at ({}, {})" . format ( row , col ) )
comboBox = QtWidgets . QComboBox ( )
comboBox . setSizeAdjustPolicy ( QtW... |
def fetch ( self ) :
"""Perform a read request against the resource""" | start = datetime . now ( )
r = requests . get ( self . _url ( ) , auth = ( self . key , "" ) )
self . _delay_for_ratelimits ( start )
if r . status_code not in self . TRUTHY_CODES :
return self . _handle_request_exception ( r )
response = r . json ( )
if self . ENVELOPE :
self . data = response . get ( self . E... |
def run ( dest , router , args , deadline = None , econtext = None ) :
"""Run the command specified by ` args ` such that ` ` PATH ` ` searches for SSH by
the command will cause its attempt to use SSH to execute a remote program
to be redirected to use mitogen to execute that program using the context
` dest ... | if econtext is not None :
mitogen . parent . upgrade_router ( econtext )
context_id = router . allocate_id ( )
fakessh = mitogen . parent . Context ( router , context_id )
fakessh . name = u'fakessh.%d' % ( context_id , )
sock1 , sock2 = socket . socketpair ( )
stream = mitogen . core . Stream ( router , context_id... |
def _get_build_kwargs ( self , obj , pk_set = None , action = None , update_fields = None , reverse = None , ** kwargs ) :
"""Prepare arguments for rebuilding indices .""" | if action is None : # Check filter before rebuilding index .
if not self . _filter ( [ obj ] , update_fields = update_fields ) :
return
queryset = getattr ( obj , self . accessor ) . all ( )
# Special handling for relations to self .
if self . field . rel . model == self . field . rel . related_... |
def has ( self , block , name ) :
"""Return whether or not the field named ` name ` has a non - default value""" | try :
return self . _kvs . has ( self . _key ( block , name ) )
except KeyError :
return False |
def deleteLayerNode ( self , layername , nodeNum ) :
"""Removes a particular unit / node from a layer .""" | # first , construct an array of all of the weights
# that won ' t be deleted :
gene = [ ]
for layer in self . layers :
if layer . type != 'Input' :
for i in range ( layer . size ) :
if layer . name == layername and i == nodeNum :
pass
# skip it
else :
... |
def changed ( self , thresh = 0.05 , idx = True ) :
"""Changed features .
{ threshdoc }""" | ind = self . data [ self . pval_column ] <= thresh
if idx :
return ind
return self [ ind ] |
def parseMultiAttributes ( self , line ) :
"""Try parsing compound attribute string .
Return a dictionary with single attributes in ' line ' .""" | attrs = line . split ( ';' )
attrs = [ a . strip ( ) for a in attrs ]
attrs = filter ( lambda a : len ( a ) > 0 , attrs )
new_attrs = { }
for a in attrs :
k , v = a . split ( ':' )
k , v = [ s . strip ( ) for s in ( k , v ) ]
new_attrs [ k ] = v
return new_attrs |
def _filter ( self , value ) :
"""Predicate used to exclude , False , or include , True , a computed value .""" | if self . ignores and value in self . ignores :
return False
return True |
def verify_token ( self , token , ** kwargs ) :
"""Validate the token signature .""" | nonce = kwargs . get ( 'nonce' )
token = force_bytes ( token )
if self . OIDC_RP_SIGN_ALGO . startswith ( 'RS' ) :
if self . OIDC_RP_IDP_SIGN_KEY is not None :
key = self . OIDC_RP_IDP_SIGN_KEY
else :
key = self . retrieve_matching_jwk ( token )
else :
key = self . OIDC_RP_CLIENT_SECRET
payl... |
def e ( msg , * args , ** kwargs ) :
'''log a message at error level ;''' | return logging . log ( ERROR , msg , * args , ** kwargs ) |
def check_completion ( task , mark_incomplete = False , clear = False , return_stats = False ) :
"""Recursively check if a task and all its requirements are complete
Args :
task ( derived from luigi . Task ) : Task to check completion for ; check everything ' downstream '
from that task .
mark _ incomplete ... | # run recursive task checking , get stats
to_clear = dict ( )
is_complete , stats = _check_completion ( task , mark_incomplete = mark_incomplete , clear = clear , stats = { } , visited = dict ( ) , to_clear = to_clear )
# task clearing needs to happen top - down : because of foreign key constraints , a task can
# only ... |
def v1_label_direct ( request , response , visid_to_dbid , dbid_to_visid , label_store , cid , subid = None ) :
'''Return directly connected labels .
The routes for this endpoint are
` ` / dossier / v1 / label / < cid > / direct ` ` and
` ` / dossier / v1 / label / < cid > / subtopic / < subid > / direct ` ` ... | lab_to_json = partial ( label_to_json , dbid_to_visid )
ident = make_ident ( visid_to_dbid ( cid ) , subid )
labs = imap ( lab_to_json , label_store . directly_connected ( ident ) )
return list ( paginate ( request , response , labs ) ) |
def get_preferred_partition ( self , broker , sibling_distance ) :
"""The preferred partition belongs to the topic with the minimum
( also negative ) distance between destination and source .
: param broker : Destination broker
: param sibling _ distance : dict { topic : distance } negative distance should
... | # Only partitions not having replica in broker are valid
# Get best fit partition , based on avoiding partition from same topic
# and partition with least siblings in destination - broker .
eligible_partitions = self . partitions - broker . partitions
if eligible_partitions :
pref_partition = min ( eligible_partiti... |
def p_while_statement ( self , p ) :
'while _ statement : WHILE LPAREN cond RPAREN whilecontent _ statement' | p [ 0 ] = WhileStatement ( p [ 3 ] , p [ 5 ] , lineno = p . lineno ( 1 ) )
p . set_lineno ( 0 , p . lineno ( 1 ) ) |
def _EStep ( self , K , x , z_h1 , pi_h , p_h ) :
"""Description :
Internal function for computing the E - Step of the EMM algorithm .""" | # E - Step :
for i in range ( self . n ) :
for k in range ( K ) :
denom_sum = 0
for k2 in range ( K ) :
denom_sum += pi_h [ k2 ] * EMMMixPLAggregator . f ( x [ i ] , p_h [ k2 ] )
z_h1 [ i ] [ k ] = ( pi_h [ k ] * EMMMixPLAggregator . f ( x [ i ] , p_h [ k ] ) ) / denom_sum |
def is_valid ( obj : JSGValidateable , log : Optional [ Union [ TextIO , Logger ] ] = None ) -> bool :
"""Determine whether obj is valid
: param obj : Object to validate
: param log : Logger to record validation failures . If absent , no information is recorded""" | return obj . _is_valid ( log ) |
def synthetic_source ( self , value ) :
"""The synthetic _ source property .
Args :
value ( string ) . the property value .""" | if value == self . _defaults [ 'ai.operation.syntheticSource' ] and 'ai.operation.syntheticSource' in self . _values :
del self . _values [ 'ai.operation.syntheticSource' ]
else :
self . _values [ 'ai.operation.syntheticSource' ] = value |
def ConsultarTiposCarne ( self , cod_grupo_carne = 1 , sep = "||" ) :
"Obtener el código y descripción para tipos de corte de carne" | ret = self . client . consultarTiposCarne ( authRequest = { 'token' : self . Token , 'sign' : self . Sign , 'cuitRepresentada' : self . Cuit , } , codGrupoCarne = cod_grupo_carne , ) [ 'consultarTiposCarneReturn' ]
self . __analizar_errores ( ret )
array = ret . get ( 'arrayTiposCarne' , [ ] )
lista = [ it [ 'codigoDes... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.