INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Execute show command and return result dictionary. | def _execShowCountCmd(self, showcmd):
"""Execute 'show' command and return result dictionary.
@param cmd: Command string.
@return: Result dictionary.
"""
result = None
lines = self._execCmd("show", showcmd + " count")
for line in line... |
Retrieve values for graphs. | def retrieveVals(self):
"""Retrieve values for graphs."""
if self.hasGraph('asterisk_calls') or self.hasGraph('asterisk_channels'):
stats = self._ami.getChannelStats(self._chanList)
if self.hasGraph('asterisk_calls') and stats:
self.setGraphVal('asterisk_calls',... |
Retrieve values for graphs. | def retrieveVals(self):
"""Retrieve values for graphs."""
fpminfo = PHPfpmInfo(self._host, self._port, self._user, self._password,
self._monpath, self._ssl)
stats = fpminfo.getStats()
if self.hasGraph('php_fpm_connections') and stats:
self.setGr... |
Implements Munin Plugin Auto - Configuration Option. | def autoconf(self):
"""Implements Munin Plugin Auto-Configuration Option.
@return: True if plugin can be auto-configured, False otherwise.
"""
fpminfo = PHPfpmInfo(self._host, self._port, self._user, self._password,
self._monpath,... |
Ping Redis Server and return Round - Trip - Time in seconds. | def ping(self):
"""Ping Redis Server and return Round-Trip-Time in seconds.
@return: Round-trip-time in seconds as float.
"""
start = time.time()
self._conn.ping()
return (time.time() - start) |
Makes multi - indexed dataframe of subject data | def list2pd(all_data, subjindex=None, listindex=None):
"""
Makes multi-indexed dataframe of subject data
Parameters
----------
all_data : list of lists of strings
strings are either all presented or all recalled items, in the order of presentation or recall
*should also work for pre... |
Creates egg data object from zero - indexed recall matrix | def recmat2egg(recmat, list_length=None):
"""
Creates egg data object from zero-indexed recall matrix
Parameters
----------
recmat : list of lists (subs) of lists (encoding lists) of ints or 2D numpy array
recall matrix representing serial positions of freely recalle... |
Fills in default distance metrics for fingerprint analyses | def default_dist_funcs(dist_funcs, feature_example):
"""
Fills in default distance metrics for fingerprint analyses
"""
if dist_funcs is None:
dist_funcs = dict()
for key in feature_example:
if key in dist_funcs:
pass
if key =... |
Takes a list of eggs stacks them and reindexes the subject number | def stack_eggs(eggs, meta='concatenate'):
'''
Takes a list of eggs, stacks them and reindexes the subject number
Parameters
----------
eggs : list of Egg data objects
A list of Eggs that you want to combine
meta : string
Determines how the meta data of each Egg combines. Default... |
Takes an egg and returns a subset of the subjects or lists | def crack_egg(egg, subjects=None, lists=None):
'''
Takes an egg and returns a subset of the subjects or lists
Parameters
----------
egg : Egg data object
Egg that you want to crack
subjects : list
List of subject idxs
lists : list
List of lists idxs
Returns
... |
Convert a MultiIndex df to list | def df2list(df):
"""
Convert a MultiIndex df to list
Parameters
----------
df : pandas.DataFrame
A MultiIndex DataFrame where the first level is subjects and the second
level is lists (e.g. egg.pres)
Returns
----------
lst : a list of lists of lists of values
... |
Fills in missing lists ( assumes end lists are missing ) | def fill_missing(x):
"""
Fills in missing lists (assumes end lists are missing)
"""
# find subject with max number of lists
maxlen = max([len(xi) for xi in x])
subs = []
for sub in x:
if len(sub)<maxlen:
for i in range(maxlen-len(sub)):
sub.append([])
... |
Parses an egg and returns fields | def parse_egg(egg):
"""Parses an egg and returns fields"""
pres_list = egg.get_pres_items().values[0]
rec_list = egg.get_rec_items().values[0]
feature_list = egg.get_pres_features().values[0]
dist_funcs = egg.dist_funcs
return pres_list, rec_list, feature_list, dist_funcs |
Helper function to merge pres and features to support legacy features argument | def merge_pres_feats(pres, features):
"""
Helper function to merge pres and features to support legacy features argument
"""
sub = []
for psub, fsub in zip(pres, features):
exp = []
for pexp, fexp in zip(psub, fsub):
lst = []
for p, f in zip(pexp, fexp):
... |
Function that calculates the Fisher z - transformation | def r2z(r):
"""
Function that calculates the Fisher z-transformation
Parameters
----------
r : int or ndarray
Correlation value
Returns
----------
result : int or ndarray
Fishers z transformed correlation value
"""
with np.errstate(invalid='ignore', divide='ig... |
Function that calculates the inverse Fisher z - transformation | def z2r(z):
"""
Function that calculates the inverse Fisher z-transformation
Parameters
----------
z : int or ndarray
Fishers z transformed correlation value
Returns
----------
result : int or ndarray
Correlation value
"""
with np.errstate(invalid='ignore', di... |
Shuffle an Egg s recalls | def shuffle_egg(egg):
""" Shuffle an Egg's recalls"""
from .egg import Egg
pres, rec, features, dist_funcs = parse_egg(egg)
if pres.ndim==1:
pres = pres.reshape(1, pres.shape[0])
rec = rec.reshape(1, rec.shape[0])
features = features.reshape(1, features.shape[0])
for ilist ... |
Retrieve values for graphs. | def retrieveVals(self):
"""Retrieve values for graphs."""
for iface in self._ifaceList:
stats = self._ifaceStats.get(iface)
graph_name = 'netiface_traffic_%s' % iface
if self.hasGraph(graph_name):
self.setGraphVal(graph_name, 'rx', stats.get('rxbytes')... |
Get NTP Peer Stats for localhost by querying local NTP Server. @return: Dictionary of NTP stats converted to seconds. | def getPeerStats(self):
"""Get NTP Peer Stats for localhost by querying local NTP Server.
@return: Dictionary of NTP stats converted to seconds.
"""
info_dict = {}
output = util.exec_command([ntpqCmd, '-n', '-c', 'peers'])
for line in output.splitlines():
... |
Get NTP Stats and offset of remote host relative to localhost by querying NTP Server on remote host. @param host: Remote Host IP. @return: Dictionary of NTP stats converted to seconds. | def getHostOffset(self, host):
"""Get NTP Stats and offset of remote host relative to localhost
by querying NTP Server on remote host.
@param host: Remote Host IP.
@return: Dictionary of NTP stats converted to seconds.
"""
info_dict = {}
output = uti... |
Get NTP Stats and offset of multiple remote hosts relative to localhost by querying NTP Servers on remote hosts. @param host: List of Remote Host IPs. @return: Dictionary of NTP stats converted to seconds. | def getHostOffsets(self, hosts):
"""Get NTP Stats and offset of multiple remote hosts relative to localhost
by querying NTP Servers on remote hosts.
@param host: List of Remote Host IPs.
@return: Dictionary of NTP stats converted to seconds.
"""
info_dict = ... |
Return system uptime in seconds. | def getUptime(self):
"""Return system uptime in seconds.
@return: Float that represents uptime in seconds.
"""
try:
fp = open(uptimeFile, 'r')
line = fp.readline()
fp.close()
except:
raise IOError('Failed reading s... |
Return system Load Average. | def getLoadAvg(self):
"""Return system Load Average.
@return: List of 1 min, 5 min and 15 min Load Average figures.
"""
try:
fp = open(loadavgFile, 'r')
line = fp.readline()
fp.close()
except:
raise IOError('Failed... |
Return cpu time utilization in seconds. | def getCPUuse(self):
"""Return cpu time utilization in seconds.
@return: Dictionary of stats.
"""
hz = os.sysconf('SC_CLK_TCK')
info_dict = {}
try:
fp = open(cpustatFile, 'r')
line = fp.readline()
fp.close()
ex... |
Return stats for running and blocked processes forks context switches and interrupts. | def getProcessStats(self):
"""Return stats for running and blocked processes, forks,
context switches and interrupts.
@return: Dictionary of stats.
"""
info_dict = {}
try:
fp = open(cpustatFile, 'r')
data = fp.read()
... |
Return stats for memory utilization. | def getMemoryUse(self):
"""Return stats for memory utilization.
@return: Dictionary of stats.
"""
info_dict = {}
try:
fp = open(meminfoFile, 'r')
data = fp.read()
fp.close()
except:
raise IOError('Failed re... |
Return information on swap partition and/ or files. | def getSwapStats(self):
"""Return information on swap partition and / or files.
@return: Dictionary of stats.
"""
info_dict = {}
try:
fp = open(swapsFile, 'r')
data = fp.read()
fp.close()
except:
ra... |
Return stats for Virtual Memory Subsystem. | def getVMstats(self):
"""Return stats for Virtual Memory Subsystem.
@return: Dictionary of stats.
"""
info_dict = {}
try:
fp = open(vmstatFile, 'r')
data = fp.read()
fp.close()
except:
raise IOError('Failed... |
Connect to Memcached. | def _connect(self):
"""Connect to Memcached."""
if self._socketFile is not None:
if not os.path.exists(self._socketFile):
raise Exception("Socket file (%s) for Memcached Instance not found."
% self._socketFile)
try:
if self.... |
Send stat command to Memcached Server and return response lines. | def _sendStatCmd(self, cmd):
"""Send stat command to Memcached Server and return response lines.
@param cmd: Command string.
@return: Array of strings.
"""
try:
self._conn.write("%s\r\n" % cmd)
regex = re.compile('^(END|ERROR)\r\n', r... |
Parse stats output from memcached and return dictionary of stats - | def _parseStats(self, lines, parse_slabs = False):
"""Parse stats output from memcached and return dictionary of stats-
@param lines: Array of lines of input text.
@param parse_slabs: Parse slab stats if True.
@return: Stats dictionary.
"""
... |
Retrieve values for graphs. | def retrieveVals(self):
"""Retrieve values for graphs."""
if self._stats is None:
serverInfo = MemcachedInfo(self._host, self._port, self._socket_file)
stats = serverInfo.getStats()
else:
stats = self._stats
if stats is None:
raise Excepti... |
Implements Munin Plugin Auto - Configuration Option. | def autoconf(self):
"""Implements Munin Plugin Auto-Configuration Option.
@return: True if plugin can be auto-configured, False otherwise.
"""
serverInfo = MemcachedInfo(self._host, self._port, self._socket_file)
return (serverInfo is not None) |
Returns correlation distance between a and b | def correlation(a, b):
"Returns correlation distance between a and b"
if isinstance(a, list):
a = np.array(a)
if isinstance(b, list):
b = np.array(b)
a = a.reshape(1, -1)
b = b.reshape(1, -1)
return cdist(a, b, 'correlation') |
Returns euclidean distance between a and b | def euclidean(a, b):
"Returns euclidean distance between a and b"
return np.linalg.norm(np.subtract(a, b)) |
Execute ps command with positional params args and return result as list of lines. | def execProcCmd(self, *args):
"""Execute ps command with positional params args and return result as
list of lines.
@param *args: Positional params for ps command.
@return: List of output lines
"""
out = util.exec_command([psCmd,] + list(args))
... |
Execute ps command with custom output format with columns from fields and return result as a nested list. The Standard Format Specifiers from ps man page must be used for the fields parameter. | def parseProcCmd(self, fields=('pid', 'user', 'cmd',), threads=False):
"""Execute ps command with custom output format with columns from
fields and return result as a nested list.
The Standard Format Specifiers from ps man page must be used for the
fields parameter.
... |
Execute ps command with custom output format with columns columns from fields select lines using the filters defined by kwargs and return result as a nested list. The Standard Format Specifiers from ps man page must be used for the fields parameter. | def getProcList(self, fields=('pid', 'user', 'cmd',), threads=False,
**kwargs):
"""Execute ps command with custom output format with columns columns
from fields, select lines using the filters defined by kwargs and return
result as a nested list.
The Standa... |
Execute ps command with custom output format with columns format with columns from fields and return result as a nested dictionary with the key PID or SPID. The Standard Format Specifiers from ps man page must be used for the fields parameter. | def getProcDict(self, fields=('user', 'cmd',), threads=False, **kwargs):
"""Execute ps command with custom output format with columns format with
columns from fields, and return result as a nested dictionary with
the key PID or SPID.
The Standard Format Specifiers from ps man ... |
Return process counts per status and priority. | def getProcStatStatus(self, threads=False, **kwargs):
"""Return process counts per status and priority.
@param **kwargs: Keyword variables are used for filtering the results
depending on the values of the columns. Each keyword
must correspond t... |
Retrieve values for graphs. | def retrieveVals(self):
"""Retrieve values for graphs."""
ntpinfo = NTPinfo()
stats = ntpinfo.getPeerStats()
if stats:
if self.hasGraph('ntp_peer_stratum'):
self.setGraphVal('ntp_peer_stratum', 'stratum',
stats.get('stratum'))... |
Main Block for Munin Plugins. | def muninMain(pluginClass, argv=None, env=None, debug=False):
"""Main Block for Munin Plugins.
@param pluginClass: Child class of MuninPlugin that implements plugin.
@param argv: List of command line arguments to Munin Plugin.
@param env: Dictionary of environment variables passed to... |
Truncate long graph and field labels. | def fixLabel(label, maxlen, delim=None, repl='', truncend=True):
"""Truncate long graph and field labels.
@param label: Label text.
@param maxlen: Maximum field label length in characters.
No maximum field label length is enforced by default.
@param delim: ... |
Private method for parsing through environment variables. Parses for environment variables common to all Munin Plugins: - MUNIN_STATEFILE - MUNIN_CAP_DIRTY_CONFIG - nested_graphs | def _parseEnv(self, env=None):
"""Private method for parsing through environment variables.
Parses for environment variables common to all Munin Plugins:
- MUNIN_STATEFILE
- MUNIN_CAP_DIRTY_CONFIG
- nested_graphs
@param env: Dictionary of env... |
Private method for returning graph object with name graph_name. | def _getGraph(self, graph_name, fail_noexist=False):
"""Private method for returning graph object with name graph_name.
@param graph_name: Graph Name
@param fail_noexist: If true throw exception if there is no graph with
name graph_name.
@return: ... |
Private method for returning subgraph object with name graph_name and parent graph with name parent_name. | def _getSubGraph(self, parent_name, graph_name, fail_noexist=False):
"""Private method for returning subgraph object with name graph_name
and parent graph with name parent_name.
@param parent_name: Root Graph Name
@param graph_name: Subgraph Name
@param fail_noexist... |
Private method for generating Multigraph ID from graph name and subgraph name. | def _getMultigraphID(self, graph_name, subgraph_name=None):
"""Private method for generating Multigraph ID from graph name and
subgraph name.
@param graph_name: Graph Name.
@param subgraph_name: Subgraph Name.
@return: Multigraph ID.
... |
Formats configuration directory from Munin Graph and returns multi - line value entries for the plugin config cycle. | def _formatConfig(self, conf_dict):
"""Formats configuration directory from Munin Graph and returns
multi-line value entries for the plugin config cycle.
@param conf_dict: Configuration directory.
@return: Multi-line text.
"""
confs = []
... |
Formats value list from Munin Graph and returns multi - line value entries for the plugin fetch cycle. | def _formatVals(self, val_list):
"""Formats value list from Munin Graph and returns multi-line value
entries for the plugin fetch cycle.
@param val_list: List of name-value pairs.
@return: Multi-line text.
"""
vals = []
for (name, val) i... |
Return value for environment variable or None. | def envGet(self, name, default=None, conv=None):
"""Return value for environment variable or None.
@param name: Name of environment variable.
@param default: Default value if variable is undefined.
@param conv: Function for converting value to desired type.
@retu... |
Parse the plugin environment variables to return list from variable with name list_<name >. The value of the variable must be a comma separated list of items. | def envGetList(self, name, attr_regex = '^\w+$', conv=None):
"""Parse the plugin environment variables to return list from variable
with name list_<name>. The value of the variable must be a comma
separated list of items.
@param name: Name of list.
... |
Register filter for including excluding attributes in graphs through the use of include_<name > and exclude_<name > environment variables. The value of the variables must be a comma separated list of items. | def envRegisterFilter(self, name, attr_regex = '^\w+$', default = True):
"""Register filter for including, excluding attributes in graphs through
the use of include_<name> and exclude_<name> environment variables.
The value of the variables must be a comma separated list of items.
... |
Check if a specific graph attribute is enabled or disabled through the use of a filter based on include_<name > and exclude_<name > environment variables. | def envCheckFilter(self, name, attr):
"""Check if a specific graph attribute is enabled or disabled through
the use of a filter based on include_<name> and exclude_<name>
environment variables.
@param name: Name of the Filter.
@param attr: Name of the Attribute.
... |
Check graph flag for enabling/ disabling attributes through the use of <name > environment variable. | def envCheckFlag(self, name, default = False):
"""Check graph flag for enabling / disabling attributes through
the use of <name> environment variable.
@param name: Name of flag.
(Also determines the environment variable name.)
@param default: Boolean (... |
Utility methos to save plugin state stored in stateObj to persistent storage to permit access to previous state in subsequent plugin runs. Any object that can be pickled and unpickled can be used to store the plugin state. | def saveState(self, stateObj):
"""Utility methos to save plugin state stored in stateObj to persistent
storage to permit access to previous state in subsequent plugin runs.
Any object that can be pickled and unpickled can be used to store the
plugin state.
@p... |
Utility method to restore plugin state from persistent storage to permit access to previous plugin state. | def restoreState(self):
"""Utility method to restore plugin state from persistent storage to
permit access to previous plugin state.
@return: Object that stores plugin state.
"""
if os.path.exists(self._stateFile):
try:
fp = open(sel... |
Utility method to associate Graph Object to Plugin. This utility method is for use in constructor of child classes for associating a MuninGraph instances to the plugin. @param graph_name: Graph Name @param graph: MuninGraph Instance | def appendGraph(self, graph_name, graph):
"""Utility method to associate Graph Object to Plugin.
This utility method is for use in constructor of child classes for
associating a MuninGraph instances to the plugin.
@param graph_name: Graph Name
@param graph: ... |
Utility method to associate Subgraph Instance to Root Graph Instance. | def appendSubgraph(self, parent_name, graph_name, graph):
"""Utility method to associate Subgraph Instance to Root Graph Instance.
This utility method is for use in constructor of child classes for
associating a MuninGraph Subgraph instance with a Root Graph instance.
@param ... |
Utility method to set Value for Field in Graph. The private method is for use in retrieveVals () method of child classes. @param graph_name: Graph Name @param field_name: Field Name. @param val: Value for field. | def setGraphVal(self, graph_name, field_name, val):
"""Utility method to set Value for Field in Graph.
The private method is for use in retrieveVals() method of child classes.
@param graph_name: Graph Name
@param field_name: Field Name.
@param val: Value ... |
Set Value for Field in Subgraph. | def setSubgraphVal(self, parent_name, graph_name, field_name, val):
"""Set Value for Field in Subgraph.
The private method is for use in retrieveVals() method of child
classes.
@param parent_name: Root Graph Name
@param graph_name: Subgraph Name
@param field_... |
Returns list of names of subgraphs for Root Graph with name parent_name. | def getSubgraphList(self, parent_name):
"""Returns list of names of subgraphs for Root Graph with name parent_name.
@param parent_name: Name of Root Graph.
@return: List of subgraph names.
"""
if not self.isMultigraph:
raise AttributeError... |
Return true if graph with name graph_name has field with name field_name. | def graphHasField(self, graph_name, field_name):
"""Return true if graph with name graph_name has field with
name field_name.
@param graph_name: Graph Name
@param field_name: Field Name.
@return: Boolean
"""
graph = self._graphDict.get(graph_nam... |
Return true if subgraph with name graph_name with parent graph with name parent_name has field with name field_name. | def subGraphHasField(self, parent_name, graph_name, field_name):
"""Return true if subgraph with name graph_name with parent graph with
name parent_name has field with name field_name.
@param parent_name: Root Graph Name
@param graph_name: Subgraph Name
@param field_nam... |
Returns list of names of fields for graph with name graph_name. | def getGraphFieldList(self, graph_name):
"""Returns list of names of fields for graph with name graph_name.
@param graph_name: Graph Name
@return: List of field names for graph.
"""
graph = self._getGraph(graph_name, True)
return graph.getField... |
Returns number of fields for graph with name graph_name. | def getGraphFieldCount(self, graph_name):
"""Returns number of fields for graph with name graph_name.
@param graph_name: Graph Name
@return: Number of fields for graph.
"""
graph = self._getGraph(graph_name, True)
return graph.getFieldCount() |
Returns list of names of fields for subgraph with name graph_name and parent graph with name parent_name. | def getSubgraphFieldList(self, parent_name, graph_name):
"""Returns list of names of fields for subgraph with name graph_name
and parent graph with name parent_name.
@param parent_name: Root Graph Name
@param graph_name: Subgraph Name
@return: List of field n... |
Returns number of fields for subgraph with name graph_name and parent graph with name parent_name. | def getSubgraphFieldCount(self, parent_name, graph_name):
"""Returns number of fields for subgraph with name graph_name and parent
graph with name parent_name.
@param parent_name: Root Graph Name
@param graph_name: Subgraph Name
@return: Number of fields for... |
Implements Munin Plugin Graph Configuration. Prints out configuration for graphs. | def config(self):
"""Implements Munin Plugin Graph Configuration.
Prints out configuration for graphs.
Use as is. Not required to be overwritten in child classes. The plugin
will work correctly as long as the Munin Graph objects have been
populated.
"""
... |
Implements Munin Plugin Fetch Option. | def fetch(self):
"""Implements Munin Plugin Fetch Option.
Prints out measured values.
"""
self.retrieveVals()
for parent_name in self._graphNames:
graph = self._graphDict[parent_name]
if self.isMultigraph:
print "multigraph %s" % self._ge... |
Implements main entry point for plugin execution. | def run(self):
"""Implements main entry point for plugin execution."""
if len(self._argv) > 1 and len(self._argv[1]) > 0:
oper = self._argv[1]
else:
oper = 'fetch'
if oper == 'fetch':
ret = self.fetch()
elif oper == 'config':
ret = ... |
Add field to Munin Graph | def addField(self, name, label, type=None, draw=None, info=None, #@ReservedAssignment
extinfo=None, colour=None, negative=None, graph=None,
min=None, max=None, cdef=None, line=None, #@ReservedAssignment
warning=None, critical=None):
"""Add field to Munin Grap... |
Returns true if field with field_name exists. | def hasField(self, name):
"""Returns true if field with field_name exists.
@param name: Field Name
@return: Boolean
"""
if self._autoFixNames:
name = self._fixName(name)
return self._fieldAttrDict.has_key(name) |
Returns dictionary of config entries for Munin Graph. | def getConfig(self):
"""Returns dictionary of config entries for Munin Graph.
@return: Dictionary of config entries.
"""
return {'graph': self._graphAttrDict,
'fields': [(field_name, self._fieldAttrDict.get(field_name))
for fi... |
Set value for field in graph. | def setVal(self, name, val):
"""Set value for field in graph.
@param name : Graph Name
@param value : Value for field.
"""
if self._autoFixNames:
name = self._fixName(name)
self._fieldValDict[name] = val |
Returns value list for Munin Graph | def getVals(self):
"""Returns value list for Munin Graph
@return: List of name-value pairs.
"""
return [(name, self._fieldValDict.get(name))
for name in self._fieldNameList] |
Query and parse Web Server Status Page. | def initStats(self, extras=None):
"""Query and parse Web Server Status Page.
@param extras: Include extra metrics, which can be computationally more
expensive.
"""
if extras is not None:
self._extras = extras
if self._extras:
... |
Query and parse Nginx Web Server Status Page. | def initStats(self):
"""Query and parse Nginx Web Server Status Page."""
url = "%s://%s:%d/%s" % (self._proto, self._host, self._port,
self._statuspath)
response = util.get_url(url, self._user, self._password)
self._statusDict = {}
for line in re... |
Read a file into a string | def read_file(filename):
"""Read a file into a string"""
path = os.path.abspath(os.path.dirname(__file__))
filepath = os.path.join(path, filename)
try:
return open(filepath).read()
except IOError:
return '' |
Retrieve values for graphs. | def retrieveVals(self):
"""Retrieve values for graphs."""
proc_info = ProcessInfo()
stats = {}
for (prefix, is_thread) in (('proc', False),
('thread', True)):
graph_name = '%s_status' % prefix
if self.hasGraph(graph_name):
... |
Retrieve values for graphs. | def retrieveVals(self):
"""Retrieve values for graphs."""
file_stats = self._fileInfo.getContainerStats()
for contname in self._fileContList:
stats = file_stats.get(contname)
if stats is not None:
if self.hasGraph('rackspace_cloudfiles_container_size'):
... |
General plot function that groups data by subject/ list number and performs analysis. | def plot(results, subjgroup=None, subjname='Subject Group', listgroup=None,
listname='List', subjconds=None, listconds=None, plot_type=None,
plot_style=None, title=None, legend=True, xlim=None, ylim=None,
save_path=None, show=True, ax=None, **kwargs):
"""
General plot function that gr... |
Return dictionary of Traffic Stats for Network Interfaces. | def getIfStats(self):
"""Return dictionary of Traffic Stats for Network Interfaces.
@return: Nested dictionary of statistics for each interface.
"""
info_dict = {}
try:
fp = open(ifaceStatsFile, 'r')
data = fp.read()
fp.close(... |
Return dictionary of Interface Configuration ( ifconfig ). | def getIfConfig(self):
"""Return dictionary of Interface Configuration (ifconfig).
@return: Dictionary of if configurations keyed by if name.
"""
conf = {}
try:
out = subprocess.Popen([ipCmd, "addr", "show"],
stdou... |
Get routing table. | def getRoutes(self):
"""Get routing table.
@return: List of routes.
"""
routes = []
try:
out = subprocess.Popen([routeCmd, "-n"],
stdout=subprocess.PIPE).communicate()[0]
except:
raise Exception... |
Execute ps command with positional params args and return result as list of lines. | def execNetstatCmd(self, *args):
"""Execute ps command with positional params args and return result as
list of lines.
@param *args: Positional params for netstat command.
@return: List of output lines
"""
out = util.exec_command([netstatCmd,] + li... |
Execute netstat command and return result as a nested dictionary. | def parseNetstatCmd(self, tcp=True, udp=True, ipv4=True, ipv6=True,
include_listen=True, only_listen=False,
show_users=False, show_procs=False,
resolve_hosts=False, resolve_ports=False,
resolve_users=True):
"""Exec... |
Execute netstat command and return result as a nested dictionary. | def getStats(self, tcp=True, udp=True, ipv4=True, ipv6=True,
include_listen=True, only_listen=False,
show_users=False, show_procs=False,
resolve_hosts=False, resolve_ports=False, resolve_users=True,
**kwargs):
"""Execute netstat command and ... |
Returns the number of TCP endpoints discriminated by status. | def getTCPportConnStatus(self, ipv4=True, ipv6=True, include_listen=False,
**kwargs):
"""Returns the number of TCP endpoints discriminated by status.
@param ipv4: Include IPv4 ports in output if True.
@param ipv6: Include IPv6 ports in ou... |
Returns TCP connection counts for each local port. | def getTCPportConnCount(self, ipv4=True, ipv6=True, resolve_ports=False,
**kwargs):
"""Returns TCP connection counts for each local port.
@param ipv4: Include IPv4 ports in output if True.
@param ipv6: Include IPv6 ports in output if True.
... |
Computes proportion of words recalled | def accuracy_helper(egg, match='exact', distance='euclidean',
features=None):
"""
Computes proportion of words recalled
Parameters
----------
egg : quail.Egg
Data to analyze
match : str (exact, best or smooth)
Matching approach to compute recall matrix. If ... |
Establish connection to PostgreSQL Database. | def _connect(self):
"""Establish connection to PostgreSQL Database."""
if self._connParams:
self._conn = psycopg2.connect(**self._connParams)
else:
self._conn = psycopg2.connect('')
try:
ver_str = self._conn.get_parameter_status('server_version')
... |
Utility method that returns database stats as a nested dictionary. | def _createStatsDict(self, headers, rows):
"""Utility method that returns database stats as a nested dictionary.
@param headers: List of columns in query result.
@param rows: List of rows in query result.
@return: Nested dictionary of values.
Fi... |
Utility method that returns totals for database statistics. | def _createTotalsDict(self, headers, rows):
"""Utility method that returns totals for database statistics.
@param headers: List of columns in query result.
@param rows: List of rows in query result.
@return: Dictionary of totals for each statistics column.
... |
Executes simple query which returns a single column. | def _simpleQuery(self, query):
"""Executes simple query which returns a single column.
@param query: Query string.
@return: Query result string.
"""
cur = self._conn.cursor()
cur.execute(query)
row = cur.fetchone()
return util.parse_... |
Returns value of Run - time Database Parameter key. | def getParam(self, key):
"""Returns value of Run-time Database Parameter 'key'.
@param key: Run-time parameter name.
@return: Run-time parameter value.
"""
cur = self._conn.cursor()
cur.execute("SHOW %s" % key)
row = cur.fetchone()
ret... |
Returns dictionary with number of connections for each database. | def getConnectionStats(self):
"""Returns dictionary with number of connections for each database.
@return: Dictionary of database connection statistics.
"""
cur = self._conn.cursor()
cur.execute("""SELECT datname,numbackends FROM pg_stat_database;""")
ro... |
Returns database block read transaction and tuple stats for each database. | def getDatabaseStats(self):
"""Returns database block read, transaction and tuple stats for each
database.
@return: Nested dictionary of stats.
"""
headers = ('datname', 'numbackends', 'xact_commit', 'xact_rollback',
'blks_read', 'blks_hit',... |
Returns the number of active lock discriminated by lock mode. | def getLockStatsMode(self):
"""Returns the number of active lock discriminated by lock mode.
@return: : Dictionary of stats.
"""
info_dict = {'all': dict(zip(self.lockModes, (0,) * len(self.lockModes))),
'wait': dict(zip(self.lockModes, (0,) * len(s... |
Returns the number of active lock discriminated by database. | def getLockStatsDB(self):
"""Returns the number of active lock discriminated by database.
@return: : Dictionary of stats.
"""
info_dict = {'all': {},
'wait': {}}
cur = self._conn.cursor()
cur.execute("SELECT d.datname, l.granted, COU... |
Returns Global Background Writer and Checkpoint Activity stats. | def getBgWriterStats(self):
"""Returns Global Background Writer and Checkpoint Activity stats.
@return: Nested dictionary of stats.
"""
info_dict = {}
if self.checkVersion('8.3'):
cur = self._conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.