signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def clone ( self ) :
"""Return a new : py : class : ` . KalmanFilter ` instance which is a shallow
clone of this one . By " shallow " , although the lists of measurements ,
etc , are cloned , the : py : class : ` . MultivariateNormal ` instances within
them are not . Since : py : meth : ` . predict ` and : py... | new_f = KalmanFilter ( initial_state_estimate = self . _initial_state_estimate )
new_f . _defaults = self . _defaults
# pylint : disable = protected - access
new_f . state_length = self . state_length
new_f . prior_state_estimates = list ( self . prior_state_estimates )
new_f . posterior_state_estimates = list ( self .... |
def send_single_text ( self , sender , receiver , content ) :
"""发送单聊文本消息
: param sender : 发送人
: param receiver : 接收人成员 ID
: param content : 消息内容
: return : 返回的 JSON 数据包""" | return self . send_text ( sender , 'single' , receiver , content ) |
def _new_list ( self , size , name ) :
"""Defines a new list to template of ` size ` and with ` name ` .
List type must be given after this keyword by defining one field . Then
the list definition has to be closed using ` End List ` .
Special value ' * ' in size means that list will decode values as long as
... | self . _message_stack . append ( ListTemplate ( size , name , self . _current_container ) ) |
def btc_make_p2sh_p2wpkh_redeem_script ( pubkey_hex ) :
"""Make the redeem script for a p2sh - p2wpkh witness script""" | pubkey_hash = hashing . bin_hash160 ( pubkey_hex . decode ( 'hex' ) ) . encode ( 'hex' )
redeem_script = btc_script_serialize ( [ '0014' + pubkey_hash ] )
return redeem_script |
def register ( email ) :
'''Register a new user account
CLI Example :
. . code - block : : bash
salt - run venafi . register email @ example . com''' | data = __utils__ [ 'http.query' ] ( '{0}/useraccounts' . format ( _base_url ( ) ) , method = 'POST' , data = salt . utils . json . dumps ( { 'username' : email , 'userAccountType' : 'API' , } ) , status = True , decode = True , decode_type = 'json' , header_dict = { 'Content-Type' : 'application/json' , } , )
status = ... |
def match_deadline ( self , start , end , match ) :
"""Matches assessments whose end time falls between the specified range inclusive .
arg : start ( osid . calendaring . DateTime ) : start of range
arg : end ( osid . calendaring . DateTime ) : end of range
arg : match ( boolean ) : ` ` true ` ` for a positiv... | self . _match_minimum_date_time ( 'deadline' , start , match )
self . _match_maximum_date_time ( 'deadline' , end , match ) |
def format_error ( self , field_name , message , index = None ) :
"""Override - able hook to format a single error message as an Error object .
See : http : / / jsonapi . org / format / # error - objects""" | pointer = [ '/data' ]
if index is not None :
pointer . append ( str ( index ) )
relationship = isinstance ( self . declared_fields . get ( field_name ) , BaseRelationship , )
if relationship :
pointer . append ( 'relationships' )
elif field_name != 'id' : # JSONAPI identifier is a special field that exists abov... |
def set_option ( self , name , val , action = Empty , opts = Empty ) :
"""Determine which options were specified outside of the defaults""" | if action is Empty and opts is Empty :
self . specified . append ( name )
super ( SpecRegister , self ) . set_option ( name , val )
else :
super ( SpecRegister , self ) . set_option ( name , val , action , opts ) |
def map ( self , func , iterable , chunksize = None ) :
"""A parallel equivalent of the map ( ) builtin function . It
blocks till the result is ready .
This method chops the iterable into a number of chunks which
it submits to the process pool as separate tasks . The
( approximate ) size of these chunks can... | return self . map_async ( func , iterable , chunksize ) . get ( ) |
def postloop ( self ) -> None :
"""Hook method executed once when the cmdloop ( ) method is about to return .""" | code = self . exit_code if self . exit_code is not None else 0
self . poutput ( '{!r} exiting with code: {}' . format ( sys . argv [ 0 ] , code ) ) |
def get_wallet_balance ( wallet_name , api_key , omit_addresses = False , coin_symbol = 'btc' ) :
'''This is particularly useful over get _ wallet _ transactions and
get _ wallet _ addresses in cases where you have lots of addresses / transactions .
Much less data to return .''' | assert is_valid_coin_symbol ( coin_symbol )
assert api_key
assert len ( wallet_name ) <= 25 , wallet_name
assert isinstance ( omit_addresses , bool ) , omit_addresses
params = { 'token' : api_key }
if omit_addresses :
params [ 'omitWalletAddresses' ] = 'true'
url = make_url ( coin_symbol , 'addrs/{}/balance' . form... |
def next_offsets ( self ) : # type : ( Descriptor ) - > Offsets
"""Retrieve the next offsets
: param Descriptor self : this
: rtype : Offsets
: return : upload offsets""" | resume_bytes = self . _resume ( )
with self . _meta_lock :
if self . _chunk_num >= self . _total_chunks :
return None , resume_bytes
if self . _offset + self . _chunk_size > self . _ase . size :
num_bytes = self . _ase . size - self . _offset
else :
num_bytes = self . _chunk_size
... |
def predict ( model_id , image_files , resize , show_image ) :
"""Predict using a deployed ( online ) model .""" | import google . datalab . ml as ml
images = _util . load_images ( image_files , resize = resize )
parts = model_id . split ( '.' )
if len ( parts ) != 2 :
raise ValueError ( 'Invalid model name for cloud prediction. Use "model.version".' )
if len ( images ) == 0 :
raise ValueError ( 'images is empty.' )
data = ... |
def process_ubam ( bam , ** kwargs ) :
"""Extracting metrics from unaligned bam format
Extracting lengths""" | logging . info ( "Nanoget: Starting to collect statistics from ubam file {}." . format ( bam ) )
samfile = pysam . AlignmentFile ( bam , "rb" , check_sq = False )
if not samfile . has_index ( ) :
pysam . index ( bam )
# Need to reload the samfile after creating index
samfile = pysam . AlignmentFile ( bam , ... |
def _load_idp_dynamic_entity_id ( self , state ) :
"""Loads an idp server with the entity id saved in state
: type state : satosa . state . State
: rtype : saml . server . Server
: param state : The current state
: return : An idp server""" | # Change the idp entity id dynamically
idp_config_file = copy . deepcopy ( self . idp_config )
idp_config_file [ "entityid" ] = "{}/{}" . format ( self . idp_config [ "entityid" ] , state [ self . name ] [ "target_entity_id" ] )
idp_config = IdPConfig ( ) . load ( idp_config_file , metadata_construction = False )
retur... |
def try_lock ( self , key , ttl = - 1 , timeout = 0 ) :
"""Tries to acquire the lock for the specified key . When the lock is not available ,
* If timeout is not provided , the current thread doesn ' t wait and returns ` ` false ` ` immediately .
* If a timeout is provided , the current thread becomes disabled ... | check_not_none ( key , "key can't be None" )
key_data = self . _to_data ( key )
return self . _encode_invoke_on_key ( map_try_lock_codec , key_data , invocation_timeout = MAX_SIZE , key = key_data , thread_id = thread_id ( ) , lease = to_millis ( ttl ) , timeout = to_millis ( timeout ) , reference_id = self . reference... |
def pause ( info = 'Press any key to continue ...' , err = False ) :
"""This command stops execution and waits for the user to press any
key to continue . This is similar to the Windows batch " pause "
command . If the program is not run through a terminal , this command
will instead do nothing .
. . versio... | if not isatty ( sys . stdin ) or not isatty ( sys . stdout ) :
return
try :
if info :
echo ( info , nl = False , err = err )
try :
getchar ( )
except ( KeyboardInterrupt , EOFError ) :
pass
finally :
if info :
echo ( err = err ) |
def get_area_bbox ( self , crs = None ) :
"""Returns a bounding box of the entire area
: param crs : Coordinate reference system in which the bounding box should be returned . If None the CRS will
be the default CRS of the splitter .
: type crs : CRS or None
: return : A bounding box of the area defined by ... | bbox_list = [ BBox ( shape . bounds , crs = self . crs ) for shape in self . shape_list ]
area_minx = min ( [ bbox . lower_left [ 0 ] for bbox in bbox_list ] )
area_miny = min ( [ bbox . lower_left [ 1 ] for bbox in bbox_list ] )
area_maxx = max ( [ bbox . upper_right [ 0 ] for bbox in bbox_list ] )
area_maxy = max ( [... |
def save ( self , filepath = None , overwrite = False , verbose = True ) :
"""Save as root of a new file .
Parameters
filepath : Path - like object ( optional )
Filepath to write . If None , file is created using natural _ name .
overwrite : boolean ( optional )
Toggle overwrite behavior . Default is Fals... | if filepath is None :
filepath = pathlib . Path ( "." ) / self . natural_name
else :
filepath = pathlib . Path ( filepath )
filepath = filepath . with_suffix ( ".wt5" )
filepath = filepath . absolute ( ) . expanduser ( )
if filepath . exists ( ) :
if overwrite :
filepath . unlink ( )
else :
... |
def merge ( self , cluster_ids , to = None ) :
"""Merge several clusters to a new cluster .
Parameters
cluster _ ids : array - like
List of clusters to merge .
to : integer or None
The id of the new cluster . By default , this is ` new _ cluster _ id ( ) ` .
Returns
up : UpdateInfo instance""" | if not _is_array_like ( cluster_ids ) :
raise ValueError ( "The first argument should be a list or " "an array." )
cluster_ids = sorted ( cluster_ids )
if not set ( cluster_ids ) <= set ( self . cluster_ids ) :
raise ValueError ( "Some clusters do not exist." )
# Find the new cluster number .
if to is None :
... |
def phase_psd_from_qd ( self , tau0 = 1.0 ) :
"""return phase power spectral density coefficient g _ b
for noise - type defined by ( qd , b , tau0)
where tau0 is the interval between data points
Colored noise generated with ( qd , b , tau0 ) parameters will
show a phase power spectral density of
S _ x ( f... | return self . qd * 2.0 * pow ( 2.0 * np . pi , self . b ) * pow ( tau0 , self . b + 1.0 ) |
def showconfig ( name , default = False , dict_return = False ) :
'''Show the configuration options for a given port .
default : False
Show the default options for a port ( not necessarily the same as the
current configuration )
dict _ return : False
Instead of returning the output of ` ` make showconfig ... | portpath = _check_portname ( name )
if default and _options_file_exists ( name ) :
saved_config = showconfig ( name , default = False , dict_return = True )
rmconfig ( name )
if _options_file_exists ( name ) :
raise CommandExecutionError ( 'Unable to get default configuration' )
default_config =... |
def fetch_lid ( self , woeid ) :
"""Fetch a location ' s corresponding LID .
Args :
woeid : ( string ) the location ' s WOEID .
Returns :
a string containing the requested LID or None if the LID could
not be found .
Raises :
urllib . error . URLError : urllib . request could not open the URL
( Pytho... | rss = self . _fetch_xml ( LID_LOOKUP_URL . format ( woeid , "f" ) )
# We are pulling the LID from the permalink tag in the XML file
# returned by Yahoo .
try :
link = rss . find ( "channel/link" ) . text
except AttributeError :
return None
# use regex or string . split
# regex assumes the format XXXXNNNN for th... |
def set_fig_size ( self , width , height = None ) :
"""Set the figure size in inches .
Sets the figure size with a call to fig . set _ size _ inches .
Default in code is 8 inches for each .
Args :
width ( float ) : Dimensions for figure width in inches .
height ( float , optional ) : Dimensions for figure... | self . figure . figure_width = width
self . figure . figure_height = height
return |
def get_ordering_field_columns ( self ) :
"""Returns an OrderedDict of ordering field column numbers and asc / desc""" | # We must cope with more than one column having the same underlying
# sort field , so we base things on column numbers .
ordering = self . _get_default_ordering ( )
ordering_fields = OrderedDict ( )
if ORDER_VAR not in self . params : # for ordering specified on model _ admin or model Meta , we don ' t
# know the right... |
def create_search_url ( self ) :
"""Generates ( urlencoded ) query string from stored key - values tuples
: returns : A string containing all arguments in a url - encoded format""" | url = '?'
for key , value in self . arguments . items ( ) :
url += '%s=%s&' % ( quote_plus ( key ) , quote_plus ( value ) )
self . url = url [ : - 1 ]
return self . url |
def do_daemon_init_and_start ( self , set_proc_title = True ) :
"""Main daemon function .
Clean , allocates , initializes and starts all necessary resources to go in daemon mode .
The set _ proc _ title parameter is mainly useful for the Alignak unit tests .
This to avoid changing the test process name !
: ... | if set_proc_title :
self . set_proctitle ( self . name )
# Change to configured user / group account
self . change_to_user_group ( )
# Change the working directory
self . change_to_workdir ( )
# Check if I am still running
self . check_parallel_run ( )
# If we must daemonize , let ' s do it !
if self . is_daemon :
... |
def mass_2d ( self , r , rho0 , Rs ) :
"""mass enclosed projected 2d sphere of radius r
: param r :
: param rho0:
: param a :
: param s :
: return :""" | sigma0 = self . rho2sigma ( rho0 , Rs )
return self . mass_2d_lens ( r , sigma0 , Rs ) |
def lookupfile ( filename ) :
"""Returns dictionary of file content as well
as google reverse GEO data""" | logger . info ( 'Looking up %s' % ( filename ) )
# First open cache file to see if we already looked up this stuff
dirname = os . path . dirname ( filename )
basefilename = os . path . basename ( filename )
CACHE_FILE = os . path . join ( dirname , '.' + basefilename + '.gpscache' )
cache = loadCacheFile ( CACHE_FILE )... |
def verifications ( self ) :
"""Access the verifications
: returns : twilio . rest . preview . acc _ security . service . verification . VerificationList
: rtype : twilio . rest . preview . acc _ security . service . verification . VerificationList""" | if self . _verifications is None :
self . _verifications = VerificationList ( self . _version , service_sid = self . _solution [ 'sid' ] , )
return self . _verifications |
def query ( self , expression , vm = 'python' ) :
"""Evaluate expression and then use it to extract rows from the table .
Parameters
expression : string
Expression to evaluate .
vm : { ' numexpr ' , ' python ' }
Virtual machine to use .
Returns
result : structured array""" | condition = self . eval ( expression , vm = vm )
return self . compress ( condition ) |
def create ( self , path , value = '' , acl = None , ephemeral = False , sequence = False , makepath = False ) :
"""Creates a Zookeeper node .
: param : path : The zookeeper node path
: param : value : Zookeeper node value
: param : acl : ACL list
: param : ephemeral : Boolean indicating where this node is ... | _log . debug ( "ZK: Creating node " + path )
return self . zk . create ( path , value , acl , ephemeral , sequence , makepath ) |
def read_text ( self , name ) :
"""Read text string from cur _ dir / name using open _ readable ( ) .""" | with self . open_readable ( name ) as fp :
res = fp . read ( )
# StringIO or file object
# try :
# res = fp . getvalue ( ) # StringIO returned by FtpTarget
# except AttributeError :
# res = fp . read ( ) # file object returned by FsTarget
res = res . decode ( "utf-8" )
return res |
def _needs_evaluation ( self ) -> bool :
"""Returns True when :
1 . Where clause is not specified
2 . Where WHERE clause is specified and it evaluates to True
Returns false if a where clause is specified and it evaluates to False""" | return self . _schema . when is None or self . _schema . when . evaluate ( self . _evaluation_context ) |
def add_row_number ( self , column_name = 'id' , start = 0 , inplace = False ) :
"""Returns an SFrame with a new column that numbers each row
sequentially . By default the count starts at 0 , but this can be changed
to a positive or negative number . The new column will be named with
the given column name . A... | if type ( column_name ) is not str :
raise TypeError ( "Must give column_name as strs" )
if type ( start ) is not int :
raise TypeError ( "Must give start as int" )
if column_name in self . column_names ( ) :
raise RuntimeError ( "Column '" + column_name + "' already exists in the current SFrame" )
the_col ... |
def create_time_series ( self , label_values , func ) :
"""Create a derived measurement to trac ` func ` .
: type label _ values : list ( : class : ` LabelValue ` )
: param label _ values : The measurement ' s label values .
: type func : function
: param func : The function to track .
: rtype : : class :... | if label_values is None :
raise ValueError
if any ( lv is None for lv in label_values ) :
raise ValueError
if len ( label_values ) != self . _len_label_keys :
raise ValueError
if func is None :
raise ValueError
return self . _create_time_series ( label_values , func ) |
def add ( self , name , arcname = None , ** kwargs ) :
"""Add a file or directory to the context tarball .
: param name : File or directory path .
: type name : unicode | str
: param args : Additional args for : meth : ` tarfile . TarFile . add ` .
: param kwargs : Additional kwargs for : meth : ` tarfile .... | if os . path . isdir ( name ) :
exclusions = get_exclusions ( name )
if exclusions :
target_prefix = os . path . abspath ( arcname or name )
kwargs . setdefault ( 'filter' , get_filter_func ( exclusions , target_prefix ) )
self . tarfile . add ( name , arcname = arcname , ** kwargs ) |
def last_restapi_key_transformer ( key , attr_desc , value ) :
"""A key transformer that returns the last RestAPI key .
: param str key : The attribute name
: param dict attr _ desc : The attribute metadata
: param object value : The value
: returns : The last RestAPI key .""" | key , value = full_restapi_key_transformer ( key , attr_desc , value )
return ( key [ - 1 ] , value ) |
def get_variable_group ( self , project , group_id ) :
"""GetVariableGroup .
[ Preview API ] Get a variable group .
: param str project : Project ID or project name
: param int group _ id : Id of the variable group .
: rtype : : class : ` < VariableGroup > < azure . devops . v5_1 . task - agent . models . V... | route_values = { }
if project is not None :
route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' )
if group_id is not None :
route_values [ 'groupId' ] = self . _serialize . url ( 'group_id' , group_id , 'int' )
response = self . _send ( http_method = 'GET' , location_id = 'f5b09dd... |
def cluster_labels_A ( hdf5_file , c , lock , I , rows_slice ) :
"""One of the task to be performed by a pool of subprocesses , as the first
step in identifying the cluster labels and indices of the cluster centers
for Affinity Propagation clustering .""" | with Worker . hdf5_lock :
with tables . open_file ( hdf5_file , 'r+' ) as fileh :
S = fileh . root . aff_prop_group . similarities
s = S [ rows_slice , ... ]
s = np . argmax ( s [ : , I ] , axis = 1 )
with lock :
c [ rows_slice ] = s [ : ]
del s |
def video_convert ( self , remote_path , video_type , ** kwargs ) :
"""对视频文件进行转码 , 实现实时观看视频功能 .
可下载支持 HLS / M3U8 的 ` 媒体云播放器 SDK < HLSSDK _ > ` _ _ 配合使用 .
. . _ HLSSDK :
http : / / developer . baidu . com / wiki / index . php ? title = docs / cplat / media / sdk
: param remote _ path : 需要下载的视频文件路径 , 以 / 开头的绝... | params = { 'path' : remote_path , 'type' : video_type , }
return self . _request ( 'file' , 'streaming' , extra_params = params , ** kwargs ) |
def crescent_data ( model_type = 'Full' , num_inducing = 10 , seed = default_seed , kernel = None , optimize = True , plot = True ) :
"""Run a Gaussian process classification on the crescent data . The demonstration calls the basic GP classification model and uses EP to approximate the likelihood .
: param model ... | try :
import pods
except ImportError :
print ( 'pods unavailable, see https://github.com/sods/ods for example datasets' )
data = pods . datasets . crescent_data ( seed = seed )
Y = data [ 'Y' ]
Y [ Y . flatten ( ) == - 1 ] = 0
if model_type == 'Full' :
m = GPy . models . GPClassification ( data [ 'X' ] , Y ... |
def sg_one_hot ( tensor , opt ) :
r"""Converts a tensor into a one - hot tensor .
See ` tf . one _ hot ( ) ` in tensorflow .
Args :
tensor : A ` Tensor ` ( automatically given by chain )
opt :
depth : The number of classes .
name : If provided , replace current tensor ' s name .
Returns :
A ` Tensor... | assert opt . depth is not None , 'depth is mandatory.'
return tf . one_hot ( tensor , opt . depth , name = opt . name ) |
def get_incident ( self , id , ** kwargs ) :
"""" Retrieve a ( v2 ) incident by id .""" | resp = self . _get_object_by_name ( self . _INCIDENT_ENDPOINT_SUFFIX , id , ** kwargs )
return resp |
def report_to_list ( queryset , display_fields , user ) :
"""Create list from a report with all data filtering .
queryset : initial queryset to generate results
display _ fields : list of field references or DisplayField models
user : requesting user
Returns list , message in case of issues .""" | model_class = queryset . model
objects = queryset
message = ""
if not _can_change_or_view ( model_class , user ) :
return [ ] , 'Permission Denied'
# Convert list of strings to DisplayField objects .
new_display_fields = [ ]
for display_field in display_fields :
field_list = display_field . split ( '__' )
f... |
def get_labs ( format ) :
"""Gets Fab Lab data from fablabs . io .""" | fablabs_json = data_from_fablabs_io ( fablabs_io_labs_api_url_v0 )
fablabs = { }
# Load all the FabLabs
for i in fablabs_json [ "labs" ] :
current_lab = FabLab ( )
current_lab . name = i [ "name" ]
current_lab . address_1 = i [ "address_1" ]
current_lab . address_2 = i [ "address_2" ]
current_lab . ... |
def to_excess_returns ( returns , rf , nperiods = None ) :
"""Given a series of returns , it will return the excess returns over rf .
Args :
* returns ( Series , DataFrame ) : Returns
* rf ( float , Series ) : ` Risk - Free rate ( s ) < https : / / www . investopedia . com / terms / r / risk - freerate . asp ... | if type ( rf ) is float and nperiods is not None :
_rf = deannualize ( rf , nperiods )
else :
_rf = rf
return returns - _rf |
def version_sort_key ( version , digits = 6 ) :
"""Produces a canonicalized version string for standard version strings
in the dotted - numeric - label format . Function appropriate for use as
the key function of sort ( ) .
The conversion removes a possible prefix and reformats each key element
as a long st... | m = re . match ( '^(\w+[_-])(\d.*)$' , version )
if m :
prefix = m . group ( 1 )
version = m . group ( 2 )
else :
prefix = ''
key = [ ]
for elem in version . split ( '.' ) :
try :
num = int ( elem )
elem = ( '%0' + str ( digits ) + 'd' ) % num
except :
pass
key . append (... |
def filter_signal ( self , data_frame , ts = 'mag_sum_acc' ) :
"""This method filters a data frame signal as suggested in : cite : ` Kassavetis2015 ` . First step is to high pass filter the data frame using a ` Butterworth < https : / / docs . scipy . org / doc / scipy - 0.14.0 / reference / generated / scipy . sig... | b , a = signal . butter ( self . filter_order , 2 * self . cutoff_frequency / self . sampling_frequency , 'high' , analog = False )
filtered_signal = signal . lfilter ( b , a , data_frame [ ts ] . values )
data_frame [ 'filtered_signal' ] = filtered_signal
logging . debug ( "filter signal" )
return data_frame |
def section ( title , bar = OVERLINE , strm = sys . stdout ) :
"""Helper function for testing demo routines""" | width = utils . term . width
printy ( bold ( title . center ( width ) ) )
printy ( bold ( ( bar * width ) [ : width ] ) ) |
def validate_package_name ( pkg_name : str ) -> None :
"""Raise an exception if the value is not a valid package name
as defined in the EthPM - Spec .""" | if not bool ( re . match ( PACKAGE_NAME_REGEX , pkg_name ) ) :
raise ValidationError ( f"{pkg_name} is not a valid package name." ) |
def do_fontsave ( self , arg ) :
"""Saves the session variables to a file so that the same analysis can be continued later .""" | # We need to save the full paths to the staging directories for the tests that are loaded
# so far ; then when the session is restored , we can reparse the results .
from os import path
import json
fullpath = path . expanduser ( arg )
data = { "fonts" : self . curargs [ "fonts" ] , "ticks" : self . curargs [ "ticks" ] ... |
def GetAnalyzerInstance ( cls , analyzer_name ) :
"""Retrieves an instance of a specific analyzer .
Args :
analyzer _ name ( str ) : name of the analyzer to retrieve .
Returns :
BaseAnalyzer : analyzer instance .
Raises :
KeyError : if analyzer class is not set for the corresponding name .""" | analyzer_name = analyzer_name . lower ( )
if analyzer_name not in cls . _analyzer_classes :
raise KeyError ( 'analyzer class not set for name: {0:s}.' . format ( analyzer_name ) )
analyzer_class = cls . _analyzer_classes [ analyzer_name ]
return analyzer_class ( ) |
def get_host_stats ( self , hosts ) :
"""Get statistics for Hosts , resp . Host entities""" | stats = { "hosts.total" : 0 , "hosts.ok" : 0 , "hosts.down" : 0 , "hosts.unreachable" : 0 , "hosts.flapping" : 0 , "hosts.in_downtime" : 0 , "hosts.checked" : 0 , "hosts.scheduled" : 0 , "hosts.active_checks" : 0 , "hosts.passive_checks" : 0 , }
for host in list ( hosts ) :
if type ( host ) is not dict :
co... |
def check_curly_quotes ( text ) :
u"""Use curly quotes , not straight quotes .""" | err = "typography.symbols.curly_quotes"
msg = u'Use curly quotes “”, not straight quotes "".'
list = [ [ u"“ or ”" , [ '"' ] ] , ]
return preferred_forms_check ( text , list , err , msg , ignore_case = False , max_errors = 2 ) |
def set_state ( self , state ) :
"""Overriding the SimStatePlugin . set _ state ( ) method
: param state : A SimState object
: return : None""" | # Sanity check
if REGION_MAPPING not in state . options : # add REGION _ MAPPING into state . options
l . warning ( 'Option "REGION_MAPPING" must be enabled when using SimAbstractMemory as the memory model. ' 'The option is added to state options as a courtesy.' )
state . options . add ( REGION_MAPPING )
SimMem... |
def _add_apt_repository ( spec ) :
"""Add the spec using add _ apt _ repository
: param spec : the parameter to pass to add _ apt _ repository
: type spec : str""" | if '{series}' in spec :
series = get_distrib_codename ( )
spec = spec . replace ( '{series}' , series )
# software - properties package for bionic properly reacts to proxy settings
# passed as environment variables ( See lp : 1433761 ) . This is not the case
# LTS and non - LTS releases below bionic .
_run_with... |
def _AddEventData ( self , event_data ) :
"""Adds event data .
Args :
event _ data ( EventData ) : event data .""" | identifier = event_data . GetIdentifier ( )
lookup_key = identifier . CopyToString ( )
self . _storage_writer . AddEventData ( event_data )
identifier = event_data . GetIdentifier ( )
self . _event_data_identifier_mappings [ lookup_key ] = identifier |
def get_usrgos ( self , fin_goids , prt ) :
"""Return source GO IDs .""" | ret = self . get_goids ( None , fin_goids , prt )
# If there have been no GO IDs explicitly specified by the user
if not ret : # If the GO - DAG is sufficiently small , print all GO IDs
if self . max_gos is not None and len ( self . go2obj ) < self . max_gos :
main_gos = set ( o . id for go , o in self . go... |
def markup_join ( seq ) :
"""Concatenation that escapes if necessary and converts to unicode .""" | buf = [ ]
iterator = imap ( soft_unicode , seq )
for arg in iterator :
buf . append ( arg )
if hasattr ( arg , '__html__' ) :
return Markup ( u'' ) . join ( chain ( buf , iterator ) )
return concat ( buf ) |
def get_info ( self ) :
'''Get info regarding the current template state
: return : info dictionary''' | self . render ( )
info = super ( Template , self ) . get_info ( )
res = { }
res [ 'name' ] = self . get_name ( )
res [ 'mutation' ] = { 'current_index' : self . _current_index , 'total_number' : self . num_mutations ( ) }
res [ 'value' ] = { 'rendered' : { 'base64' : b64encode ( self . _current_rendered . tobytes ( ) )... |
def normalizeISBN ( isbn ) :
"""> > > normalizeISBN ( ' 978800105473-4 ' )
'978-80-01-05473-4'
> > > normalizeISBN ( ' 80978800105473-4 ' )
'80978800105473-4'
> > > normalizeISBN ( ' 988800105473-4 ' )
'988800105473-4'
> > > normalizeISBN ( ' 978-80-254-94677 ' )
'978-80-254-9467-7'""" | try :
return isbnlib . mask ( isbnlib . canonical ( isbn ) )
except isbnlib . NotValidISBNError :
return isbn |
def download ( args ) :
"""Implement the ' greg download ' command""" | session = c . Session ( args )
issues = aux . parse_for_download ( args )
if issues == [ '' ] :
sys . exit ( "You need to give a list of issues, of the form " "a, b-c, d..." "" )
dumpfilename = os . path . join ( session . data_dir , 'feeddump' )
if not os . path . isfile ( dumpfilename ) :
sys . exit ( ( "You ... |
def magphase_databoxes ( ds , xscript = 0 , yscript = 'd[1]+1j*d[2]' , eyscript = None , exscript = None , g = None , ** kwargs ) :
"""Use databoxes and scripts to generate data and plot the complex magnitude
and phase versus xdata .
Parameters
ds
List of databoxes
xscript = 0
Script for x data
yscrip... | databoxes ( ds , xscript , yscript , eyscript , exscript , plotter = magphase_data , g = g , ** kwargs ) |
def get_reader_class ( reader_name ) :
"""Get a particular reader class by name .""" | for reader_class in get_reader_classes ( ) :
if reader_class . name . lower ( ) == reader_name . lower ( ) :
return reader_class
else :
logger . error ( "No such reader: %s" % reader_name )
return None |
def new_pivot ( self , attributes = None , exists = False ) :
"""Create a new pivot model instance .""" | pivot = self . _related . new_pivot ( self . _parent , attributes , self . _table , exists )
return pivot . set_pivot_keys ( self . _foreign_key , self . _other_key ) |
def get_front_page ( self , * args , ** kwargs ) :
"""Return a get _ content generator for the front page submissions .
Corresponds to the submissions provided by ` ` https : / / www . reddit . com / ` `
for the session .
The additional parameters are passed directly into
: meth : ` . get _ content ` . Note... | return self . get_content ( self . config [ 'reddit_url' ] , * args , ** kwargs ) |
def get_new_members ( self , results ) :
"""Return the newly added members .
: param results : the results of a membership request check
: type results : : class : ` list `
: return : the successful requests , as : class : ` ~ groupy . api . memberships . Members `
: rtype : generator""" | for member in results :
guid = member . pop ( 'guid' )
yield Member ( self . manager , self . group_id , ** member )
member [ 'guid' ] = guid |
def col_iscat ( df , col_name = None ) :
"""Returns a list of columns that are of type ' category ' . If col _ name is specified , returns
whether the column in the DataFrame is of type ' category ' instead .
Parameters :
df - DataFrame
DataFrame to check
col _ name - string , default None
If specified ... | col_list = df . select_dtypes ( include = 'category' ) . columns
if col_name is None :
return col_list
else :
return col_name in col_list |
def shakemap_converter_help ( ) :
"""Help message for extent selector dialog .
. . versionadded : : 3.2.1
: returns : A message object containing helpful information .
: rtype : messaging . message . Message""" | message = m . Message ( )
message . add ( m . Brand ( ) )
message . add ( heading ( ) )
message . add ( content ( ) )
return message |
def parseBasicOptions ( parser ) :
"""Setups the standard things from things added by getBasicOptionParser .""" | options = parser . parse_args ( )
setLoggingFromOptions ( options )
# Set up the temp dir root
if options . tempDirRoot == "None" : # FIXME : Really , a string containing the word None ?
options . tempDirRoot = tempfile . gettempdir ( )
return options |
def p_if_else ( p ) :
"""statement : if _ then _ part NEWLINE program _ co else _ part""" | cond_ = p [ 1 ]
then_ = p [ 3 ]
else_ = p [ 4 ] [ 0 ]
endif = p [ 4 ] [ 1 ]
p [ 0 ] = make_sentence ( 'IF' , cond_ , then_ , make_block ( else_ , endif ) , lineno = p . lineno ( 2 ) ) |
def get_path ( self , api_info ) :
"""Get the path portion of the URL to the method ( for RESTful methods ) .
Request path can be specified in the method , and it could have a base
path prepended to it .
Args :
api _ info : API information for this API , possibly including a base path .
This is the api _ ... | path = self . __path or ''
if path and path [ 0 ] == '/' : # Absolute path , ignoring any prefixes . Just strip off the leading / .
path = path [ 1 : ]
else : # Relative path .
if api_info . path :
path = '%s%s%s' % ( api_info . path , '/' if path else '' , path )
# Verify that the path seems valid .
pa... |
def euclideanDistance ( instance1 , instance2 , considerDimensions ) :
"""Calculate Euclidean Distance between two samples
Example use :
data1 = [ 2 , 2 , 2 , ' class _ a ' ]
data2 = [ 4 , 4 , 4 , ' class _ b ' ]
distance = euclideanDistance ( data1 , data2 , 3)
: param instance1 : list of attributes
: ... | distance = 0
for x in considerDimensions :
distance += pow ( ( instance1 [ x ] - instance2 [ x ] ) , 2 )
return math . sqrt ( distance ) |
def keys_recover ( gandi , fqdn , key ) :
"""Recover deleted key for a domain .""" | result = gandi . dns . keys_recover ( fqdn , key )
gandi . echo ( 'Recover successful.' )
return result |
def joined_organisations ( doc ) :
"""View for getting organisations associated with a user""" | if doc . get ( 'type' ) == 'user' :
for org_id , state in doc . get ( 'organisations' , { } ) . items ( ) :
org = { '_id' : org_id }
yield [ doc [ '_id' ] , None ] , org
try :
yield [ doc [ '_id' ] , state [ 'state' ] ] , org
except KeyError :
pass |
def gt_corners ( gt , nx , ny ) :
"""Get corner coordinates based on input geotransform and raster dimensions""" | ul = [ gt [ 0 ] , gt [ 3 ] ]
ll = [ gt [ 0 ] , gt [ 3 ] + ( gt [ 5 ] * ny ) ]
ur = [ gt [ 0 ] + ( gt [ 1 ] * nx ) , gt [ 3 ] ]
lr = [ gt [ 0 ] + ( gt [ 1 ] * nx ) , gt [ 3 ] + ( gt [ 5 ] * ny ) ]
return ul , ll , ur , lr |
def log ( message , level = None , name = None , filename = None ) :
"""Write a message to the log file and / or print to the the console .
Parameters
message : string
the content of the message to log
level : int
one of the logger . level constants
name : string
name of the logger
filename : string... | if level is None :
level = settings . log_level
if name is None :
name = settings . log_name
if filename is None :
filename = settings . log_filename
# if logging to file is turned on
if settings . log_file : # get the current logger ( or create a new one , if none ) , then log
# message at requested level
... |
def publish ( self , object_id : str , event_type : str , event_data : dict = None ) :
"""Publish a scheduling object event .
Args :
object _ id ( str ) : ID of the scheduling object
event _ type ( str ) : Type of event .
event _ data ( dict , optional ) : Event data .""" | object_key = SchedulingObject . get_key ( self . type , object_id )
publish ( event_type = event_type , event_data = event_data , object_type = self . type , object_id = object_id , object_key = object_key , origin = None ) |
def cancel ( self , job_ids ) :
'''Cancels the jobs specified by a list of job ids
Args :
job _ ids : [ < job _ id > . . . ]
Returns :
[ True / False . . . ] : If the cancel operation fails the entire list will be False .''' | job_id_list = ' ' . join ( job_ids )
retcode , stdout , stderr = self . channel . execute_wait ( "qdel {0}" . format ( job_id_list ) , 3 )
rets = None
if retcode == 0 :
for jid in job_ids :
self . resources [ jid ] [ 'status' ] = translate_table [ 'E' ]
# Setting state to exiting
rets = [ True f... |
def run ( self , x = None ) :
r"""Builds the A and b matrices , and calls the solver specified in the
` ` settings ` ` attribute .
Parameters
x : ND - array
Initial guess of unknown variable""" | logger . info ( 'Running ReactiveTransport' )
# Create S1 & S1 for 1st Picard ' s iteration
if x is None :
x = np . zeros ( shape = [ self . Np , ] , dtype = float )
self [ self . settings [ 'quantity' ] ] = x
self . _update_physics ( )
x = self . _run_reactive ( x = x )
self [ self . settings [ 'quantity' ] ] = x |
def parse_end_date ( self , request , start_date ) :
"""Return period in days after the start date to show event occurrences ,
which is one of the following in order of priority :
- ` end _ date ` GET parameter value , if given and valid . The filtering
will be * inclusive * of the end date : until end - of -... | if request . GET . get ( 'end_date' ) :
try :
return djtz . parse ( '%s 00:00' % request . GET . get ( 'end_date' ) )
except ValueError :
pass
days_to_show = self . default_days_to_show or appsettings . DEFAULT_DAYS_TO_SHOW
if 'days_to_show' in request . GET :
try :
days_to_show = in... |
def _GetChunkForWriting ( self , chunk ) :
"""Returns the relevant chunk from the datastore .""" | try :
chunk = self . chunk_cache . Get ( chunk )
chunk . dirty = True
return chunk
except KeyError :
pass
try :
chunk = self . _ReadChunk ( chunk )
chunk . dirty = True
return chunk
except KeyError :
pass
fd = io . BytesIO ( )
fd . chunk = chunk
fd . dirty = True
self . chunk_cache . Put... |
def validate_excel_sheet_name ( sheet_name ) :
""": param str sheet _ name : Excel sheet name to validate .
: raises pathvalidate . NullNameError : If the ` ` sheet _ name ` ` is empty .
: raises pathvalidate . InvalidCharError :
If the ` ` sheet _ name ` ` includes invalid char ( s ) :
| invalid _ excel _ ... | validate_null_string ( sheet_name )
if len ( sheet_name ) > __MAX_SHEET_NAME_LEN :
raise InvalidLengthError ( "sheet name is too long: expected<={:d}, actual={:d}" . format ( __MAX_SHEET_NAME_LEN , len ( sheet_name ) ) )
unicode_sheet_name = _preprocess ( sheet_name )
match = __RE_INVALID_EXCEL_SHEET_NAME . search ... |
def get_recent_updates ( self , raw = True ) :
"""Get the most recent updates on Hacker News
Response dictionary parameters :
" items " - > A list of the most recently update items by item number .
" profiles " - > A list of most recently updated user profiles by user name .
: param raw : ( optional ) : If ... | suburl = "v0/updates.json"
try :
updates_data = self . _make_request ( suburl )
except requests . HTTPError as e :
hn_logger . exception ( 'Faulted on get max item, with status {}' . format ( e . errno ) )
raise e
return updates_data if raw else HackerNewsUpdates ( ** updates_data ) |
def delete_account_api_key ( self , account_id , api_key , ** kwargs ) : # noqa : E501
"""Delete the API key . # noqa : E501
An endpoint for deleting an API key . * * Example usage : * * ` curl - X DELETE https : / / api . us - east - 1 . mbedcloud . com / v3 / accounts / { accountID } / api - keys / { apikey } -... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'asynchronous' ) :
return self . delete_account_api_key_with_http_info ( account_id , api_key , ** kwargs )
# noqa : E501
else :
( data ) = self . delete_account_api_key_with_http_info ( account_id , api_key , ** kwargs )
# noqa : E501
ret... |
def fit_binx2 ( f , data , bins = 30 , bound = None , print_level = 0 , quiet = False , * arg , ** kwd ) :
"""perform chi ^ 2 fit
: param f :
: param data :
: param bins :
: param range :
: param printlevel :
: param quiet :
: param arg :
: param kwd :
: return :""" | uml = BinnedChi2 ( f , data , bins = bins , bound = bound )
minuit = Minuit ( uml , print_level = print_level , ** kwd )
minuit . set_strategy ( 2 )
minuit . migrad ( )
if not minuit . migrad_ok ( ) or not minuit . matrix_accurate ( ) :
if not quiet :
from matplotlib import pyplot as plt
plt . figur... |
def AddFileEntry ( self , path , file_entry_type = definitions . FILE_ENTRY_TYPE_FILE , file_data = None , link_data = None ) :
"""Adds a fake file entry .
Args :
path ( str ) : path of the file entry .
file _ entry _ type ( Optional [ str ] ) : type of the file entry object .
file _ data ( Optional [ bytes... | if path in self . _paths :
raise KeyError ( 'File entry already set for path: {0:s}.' . format ( path ) )
if file_data and file_entry_type != definitions . FILE_ENTRY_TYPE_FILE :
raise ValueError ( 'File data set for non-file file entry type.' )
if link_data and file_entry_type != definitions . FILE_ENTRY_TYPE_... |
def color_diffs ( string ) :
"""Add color ANSI codes for diff lines .
Purpose : Adds the ANSI / win32 color coding for terminal output to output
| produced from difflib .
@ param string : The string to be replacing
@ type string : str
@ returns : The new string with ANSI codes injected .
@ rtype : str""... | string = string . replace ( '--- ' , color ( '--- ' , 'red' ) )
string = string . replace ( '\n+++ ' , color ( '\n+++ ' ) )
string = string . replace ( '\n-' , color ( '\n-' , 'red' ) )
string = string . replace ( '\n+' , color ( '\n+' ) )
string = string . replace ( '\n@@ ' , color ( '\n@@ ' , 'yel' ) )
return string |
def get_rulesets ( ruledir , recurse ) :
"""List of ruleset objects extracted from the yaml directory""" | if os . path . isdir ( ruledir ) and recurse :
yaml_files = [ y for x in os . walk ( ruledir ) for y in glob ( os . path . join ( x [ 0 ] , '*.yaml' ) ) ]
elif os . path . isdir ( ruledir ) and not recurse :
yaml_files = get_files ( ruledir , 'yaml' )
elif os . path . isfile ( ruledir ) :
yaml_files = [ rul... |
def set_fan_mode ( self , mode ) :
"""Set the fan mode""" | self . set_service_value ( self . thermostat_fan_service , 'Mode' , 'NewMode' , mode )
self . set_cache_value ( 'fanmode' , mode ) |
def find_answer ( self , qu ) :
"""This takes the question ' qu ' and parses info and raw input
to try and find an answer .
It should use the skills , and where parameters are needed it
should guess them if not in there - for example weather should
default to local location unless a [ country | city ] is pa... | if 'weather' in qu :
ans = 'sunny'
elif 'where' in qu :
ans = '4km to the North'
elif 'when' in qu :
ans = 'next week'
else :
ans = 'I dont know'
return ans |
def wikidata_get ( identifier ) :
"""https : / / www . wikidata . org / wiki / Special : EntityData / P248 . json""" | url = 'https://www.wikidata.org/wiki/Special:EntityData/{}.json' . format ( identifier )
# logging . info ( url )
return json . loads ( requests . get ( url ) . content ) |
def waitForVMState ( rh , userid , desiredState , maxQueries = 90 , sleepSecs = 5 ) :
"""Wait for the virtual machine to go into the indicated state .
Input :
Request Handle
userid whose state is to be monitored
Desired state , ' on ' or ' off ' , case sensitive
Maximum attempts to wait for desired state ... | rh . printSysLog ( "Enter vmUtils.waitForVMState, userid: " + userid + " state: " + desiredState + " maxWait: " + str ( maxQueries ) + " sleepSecs: " + str ( sleepSecs ) )
results = { }
cmd = [ "sudo" , "/sbin/vmcp" , "query" , "user" , userid ]
strCmd = " " . join ( cmd )
stateFnd = False
for i in range ( 1 , maxQueri... |
def _prttex_summary_cnts ( self , prt , cnts ) :
"""Write summary of level and depth counts for active GO Terms .""" | # Count level ( shortest path to root ) and depth ( longest path to root )
# values for all unique GO Terms .
prt . write ( "\n\n% LaTeX Table for GO counts at each level and depth in the GO DAG\n" )
prt . write ( r"\begin{table}[bt]" "\n" )
prt . write ( r"\begin{tabular}{|r |r |r |r |r |r |r|}" "\n" )
title = self . ... |
def function ( self , p ) :
"""Return a sine grating pattern ( two - dimensional sine wave ) .""" | return 0.5 + 0.5 * np . sin ( p . frequency * 2 * pi * self . pattern_y + p . phase ) |
def list_nodes ( call = None ) :
'''Return a list of the VMs that are on the provider''' | if call == 'action' :
raise SaltCloudSystemExit ( 'The list_nodes function must be called with -f or --function.' )
ret = { }
items = query ( action = 've' )
for item in items :
name = item . attrib [ 'name' ]
node = show_instance ( name , call = 'action' )
ret [ name ] = { 'id' : node [ 'id' ] , 'image... |
def replace_chunk ( filename , offset , length , chunk , in_place = True , max_mem = 5 ) :
"""Replace length bytes of data with chunk , starting at offset .
Any KeyboardInterrupts arriving while replace _ chunk is runnning
are deferred until the operation is complete .
If in _ place is true , the operation wo... | with suppress_interrupt ( ) :
_replace_chunk ( filename , offset , length , chunk , in_place , max_mem ) |
def flush ( self ) :
'''Flush some of the waiting messages , returns count written''' | # When profiling , we found that while there was some efficiency to be
# gained elsewhere , the big performance hit is sending lots of small
# messages at a time . In particular , consumers send many ' FIN ' messages
# which are very small indeed and the cost of dispatching so many system
# calls is very high . Instead... |
def deploy_schema_to_db ( self , mode = 'safe' , files_deployment = None , vcs_ref = None , vcs_link = None , issue_ref = None , issue_link = None , compare_table_scripts_as_int = False , config_path = None , config_dict = None , config_object = None , source_code_path = None , auto_commit = False ) :
"""Deploys sc... | return_value = { }
if files_deployment :
return_value [ 'function_scripts_requested' ] = files_deployment
return_value [ 'type_scripts_requested' ] = [ ]
return_value [ 'view_scripts_requested' ] = [ ]
return_value [ 'trigger_scripts_requested' ] = [ ]
return_value [ 'table_scripts_requested' ] = [ ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.