INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Get enriched JASPAR motifs in a FASTA file. | def _run_program(self, bin, fastafile, params=None):
"""
Get enriched JASPAR motifs in a FASTA file.
Parameters
----------
bin : str
Command used to run the tool.
fastafile : str
Name of the FASTA input file.
params : dict, optio... |
Run MEME and predict motifs from a FASTA file. | def _run_program(self, bin, fastafile, params=None):
"""
Run MEME and predict motifs from a FASTA file.
Parameters
----------
bin : str
Command used to run the tool.
fastafile : str
Name of the FASTA input file.
params : dict, op... |
Convert MEME output to motifs Parameters ---------- fo: file - like File object containing MEME output. | def parse(self, fo):
"""
Convert MEME output to motifs
Parameters
----------
fo : file-like
File object containing MEME output.
Returns
-------
motifs : list
List of Motif instances.
"""
motifs = []
... |
Scan regions in input table with motifs. | def scan_to_table(input_table, genome, scoring, pwmfile=None, ncpus=None):
"""Scan regions in input table with motifs.
Parameters
----------
input_table : str
Filename of input table. Can be either a text-separated tab file or a
feather file.
genome : str
Genome name. C... |
Run maelstrom on an input table. Parameters ---------- infile: str Filename of input table. Can be either a text - separated tab file or a feather file. genome: str Genome name. Can be either the name of a FASTA - formatted file or a genomepy genome name. outdir: str Output directory for all results. | def run_maelstrom(infile, genome, outdir, pwmfile=None, plot=True, cluster=False,
score_table=None, count_table=None, methods=None, ncpus=None):
"""Run maelstrom on an input table.
Parameters
----------
infile : str
Filename of input table. Can be either a text-separated tab file o... |
Plot clustered heatmap of predicted motif activity. Parameters ---------- kind: str optional Which data type to use for plotting. Default is final which will plot the result of the rang aggregation. Other options are freq for the motif frequencies or any of the individual activities such as rf. score. min_freq: float o... | def plot_heatmap(self, kind="final", min_freq=0.01, threshold=2, name=True, max_len=50, aspect=1, **kwargs):
"""Plot clustered heatmap of predicted motif activity.
Parameters
----------
kind : str, optional
Which data type to use for plotting. Default is 'final', whi... |
Create motif scores boxplot of different clusters. Motifs can be specified as either motif or factor names. The motif scores will be scaled and plotted as z - scores. Parameters ---------- motifs: iterable or str List of motif or factor names. name: bool optional Use factor names instead of motif names for plotting. ma... | def plot_scores(self, motifs, name=True, max_len=50):
"""Create motif scores boxplot of different clusters.
Motifs can be specified as either motif or factor names.
The motif scores will be scaled and plotted as z-scores.
Parameters
----------
motifs : iterable o... |
Return version of package on pypi. python. org using json. Adapted from https:// stackoverflow. com/ a/ 34366589 | def get_version(package, url_pattern=URL_PATTERN):
"""Return version of package on pypi.python.org using json. Adapted from https://stackoverflow.com/a/34366589"""
req = requests.get(url_pattern.format(package=package))
version = parse('0')
if req.status_code == requests.codes.ok:
# j = json.loa... |
Converts arguments extracted from a parser to a dict and will dismiss arguments which default to NOT_SET. | def get_args(parser):
"""
Converts arguments extracted from a parser to a dict,
and will dismiss arguments which default to NOT_SET.
:param parser: an ``argparse.ArgumentParser`` instance.
:type parser: argparse.ArgumentParser
:return: Dictionary with the configs found in the parsed CLI argumen... |
Parse input string and return int float or str depending on format. | def parse_value(val, parsebool=False):
"""Parse input string and return int, float or str depending on format.
@param val: Input string.
@param parsebool: If True parse yes / no, on / off as boolean.
@return: Value of type int, float or str.
"""
try:
return i... |
Buffered read from socket. Reads all data available from socket. | def socket_read(fp):
"""Buffered read from socket. Reads all data available from socket.
@fp: File pointer for socket.
@return: String of characters read from buffer.
"""
response = ''
oldlen = 0
newlen = 0
while True:
response += fp.read(buffSize)
newlen = ... |
Convenience function that executes command and returns result. | def exec_command(args, env=None):
"""Convenience function that executes command and returns result.
@param args: Tuple of command and arguments.
@param env: Dictionary of environment variables.
(Environment is not modified if None.)
@return: Command output.
"""
t... |
D. set_nested (( k1 k2 k3... ) v ) - > D [ k1 ] [ k2 ] [ k3 ]... = v | def set_nested(self, klist, value):
"""D.set_nested((k1, k2,k3, ...), v) -> D[k1][k2][k3] ... = v"""
keys = list(klist)
if len(keys) > 0:
curr_dict = self
last_key = keys.pop()
for key in keys:
if not curr_dict.has_key(key) or not isinstance(cu... |
Register filter on a column of table. | def registerFilter(self, column, patterns, is_regex=False,
ignore_case=False):
"""Register filter on a column of table.
@param column: The column name.
@param patterns: A single pattern or a list of patterns used for
matching ... |
Unregister filter on a column of the table. | def unregisterFilter(self, column):
"""Unregister filter on a column of the table.
@param column: The column header.
"""
if self._filters.has_key(column):
del self._filters[column] |
Register multiple filters at once. | def registerFilters(self, **kwargs):
"""Register multiple filters at once.
@param **kwargs: Multiple filters are registered using keyword
variables. Each keyword must correspond to a field name
with an optional suffix:
... |
Apply filter on ps command result. | def applyFilters(self, headers, table):
"""Apply filter on ps command result.
@param headers: List of column headers.
@param table: Nested list of rows and columns.
@return: Nested list of rows and columns filtered using
registered filters.
... |
Connect to a host. | def open(self, host=None, port=0, socket_file=None,
timeout=socket.getdefaulttimeout()):
"""Connect to a host.
With a host argument, it connects the instance using TCP; port number
and timeout are optional, socket_file must be None. The port number
defaults to the standar... |
General analysis function that groups data by subject/ list number and performs analysis. | def analyze(egg, subjgroup=None, listgroup=None, subjname='Subject',
listname='List', analysis=None, position=0, permute=False,
n_perms=1000, parallel=False, match='exact',
distance='euclidean', features=None, ts=None):
"""
General analysis function that groups data by subjec... |
Private function that groups data by subject/ list number and performs analysis for a chunk of data. | def _analyze_chunk(data, subjgroup=None, subjname='Subject', listgroup=None,
listname='List', analysis=None, analysis_type=None,
pass_features=False, features=None, parallel=False,
**kwargs):
"""
Private function that groups data by subject/list number an... |
Retrieve values for graphs. | def retrieveVals(self):
"""Retrieve values for graphs."""
if self.hasGraph('tomcat_memory'):
stats = self._tomcatInfo.getMemoryStats()
self.setGraphVal('tomcat_memory', 'used',
stats['total'] - stats['free'])
self.setGraphVal('tomcat_memo... |
Calculate the autocorrelation function for a 1D time series. | def function(data, maxt=None):
"""
Calculate the autocorrelation function for a 1D time series.
Parameters
----------
data : numpy.ndarray (N,)
The time series.
Returns
-------
rho : numpy.ndarray (N,)
An autocorrelation function.
"""
data = np.atleast_1d(data)... |
Retrieve values for graphs. | def retrieveVals(self):
"""Retrieve values for graphs."""
nginxInfo = NginxInfo(self._host, self._port,
self._user, self._password,
self._statuspath, self._ssl)
stats = nginxInfo.getServerStats()
if stats:
if... |
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.
"""
nginxInfo = NginxInfo(self._host, self._port,
self._user, self._password,
... |
Query and parse Web Server Status Page. | def getStats(self):
"""Query and parse Web Server Status Page.
"""
url = "%s://%s:%d/%s" % (self._proto, self._host, self._port,
self._monpath)
response = util.get_url(url, self._user, self._password)
stats = {}
for line in respo... |
Retrieve values for graphs. | def retrieveVals(self):
"""Retrieve values for graphs."""
apcinfo = APCinfo(self._host, self._port, self._user, self._password,
self._monpath, self._ssl, self._extras)
stats = apcinfo.getAllStats()
if self.hasGraph('php_apc_memory') and stats:
... |
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.
"""
apcinfo = APCinfo(self._host, self._port, self._user, self._password,
self._monpath, self.... |
Runs varnishstats command to get stats from Varnish Cache. @return: Dictionary of stats. | def getStats(self):
"""Runs varnishstats command to get stats from Varnish Cache.
@return: Dictionary of stats.
"""
info_dict = {}
args = [varnishstatCmd, '-1']
if self._instance is not None:
args.extend(['-n', self._instance])
output = util.... |
Returns description for stat entry. | def getDesc(self, entry):
"""Returns description for stat entry.
@param entry: Entry name.
@return: Description for entry.
"""
if len(self._descDict) == 0:
self.getStats()
return self._descDict.get(entry) |
Retrieve values for graphs. | def retrieveVals(self):
"""Retrieve values for graphs."""
opcinfo = OPCinfo(self._host, self._port, self._user, self._password,
self._monpath, self._ssl)
stats = opcinfo.getAllStats()
if self.hasGraph('php_opc_memory') and stats:
mem = stat... |
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.
"""
opcinfo = OPCinfo(self._host, self._port, self._user, self._password,
self._monpath, self.... |
Computes clustering along a set of feature dimensions | def fingerprint_helper(egg, permute=False, n_perms=1000,
match='exact', distance='euclidean', features=None):
"""
Computes clustering along a set of feature dimensions
Parameters
----------
egg : quail.Egg
Data to analyze
dist_funcs : dict
Dictionary of d... |
Compute clustering scores along a set of feature dimensions | def compute_feature_weights(pres_list, rec_list, feature_list, distances):
"""
Compute clustering scores along a set of feature dimensions
Parameters
----------
pres_list : list
list of presented words
rec_list : list
list of recalled words
feature_list : list
list... |
Computes probabilities for each transition distance ( probability that a word recalled will be a given distance -- in presentation order -- from the previous recalled word ). | def lagcrp_helper(egg, match='exact', distance='euclidean',
ts=None, features=None):
"""
Computes probabilities for each transition distance (probability that a word
recalled will be a given distance--in presentation order--from the previous
recalled word).
Parameters
--------... |
Retrieve values for graphs. | def retrieveVals(self):
"""Retrieve values for graphs."""
if self._diskList:
self._fetchDevAll('disk', self._diskList,
self._info.getDiskStats)
if self._mdList:
self._fetchDevAll('md', self._mdList,
self._info.... |
Generate configuration for I/ O Request stats. | def _configDevRequests(self, namestr, titlestr, devlist):
"""Generate configuration for I/O Request stats.
@param namestr: Field name component indicating device type.
@param titlestr: Title component indicating device type.
@param devlist: List of devices.
""... |
Generate configuration for I/ O Queue Length. | def _configDevActive(self, namestr, titlestr, devlist):
"""Generate configuration for I/O Queue Length.
@param namestr: Field name component indicating device type.
@param titlestr: Title component indicating device type.
@param devlist: List of devices.
"""
... |
Initialize I/ O stats for devices. | def _fetchDevAll(self, namestr, devlist, statsfunc):
"""Initialize I/O stats for devices.
@param namestr: Field name component indicating device type.
@param devlist: List of devices.
@param statsfunc: Function for retrieving stats for device.
"""
fo... |
Retrieve values for graphs. | def retrieveVals(self):
"""Retrieve values for graphs."""
for graph_name in self.getGraphList():
for field_name in self.getGraphFieldList(graph_name):
self.setGraphVal(graph_name, field_name, self._stats.get(field_name)) |
Retrieve values for graphs. | def retrieveVals(self):
"""Retrieve values for graphs."""
if self.hasGraph('sys_loadavg'):
self._loadstats = self._sysinfo.getLoadAvg()
if self._loadstats:
self.setGraphVal('sys_loadavg', 'load15min', self._loadstats[2])
self.setGraphVal('sys_loada... |
Searches os. environ. If a key is found try evaluating its type else ; return the string. | def get(key, default=None):
"""
Searches os.environ. If a key is found try evaluating its type else;
return the string.
returns: k->value (type as defined by ast.literal_eval)
"""
try:
# Attempt to evaluate into python literal
return ast.literal_eval(os.environ.get(k... |
Saves a list of keyword arguments as environment variables to a file. If no filepath given will default to the default. env file. | def save(filepath=None, **kwargs):
"""
Saves a list of keyword arguments as environment variables to a file.
If no filepath given will default to the default `.env` file.
"""
if filepath is None:
filepath = os.path.join('.env')
with open(filepath, 'wb') as file_handle:
f... |
Reads a. env file into os. environ. | def load(filepath=None):
"""
Reads a .env file into os.environ.
For a set filepath, open the file and read contents into os.environ.
If filepath is not set then look in current dir for a .env file.
"""
if filepath and os.path.exists(filepath):
pass
else:
if not o... |
Gets each line from the file and parse the data. Attempt to translate the value into a python type is possible ( falls back to string ). | def _get_line_(filepath):
"""
Gets each line from the file and parse the data.
Attempt to translate the value into a python type is possible
(falls back to string).
"""
for line in open(filepath):
line = line.strip()
# allows for comments in the file
if line.startswith('#... |
Query and parse Apache Web Server Status Page. | def initStats(self):
"""Query and parse Apache Web Server Status Page."""
url = "%s://%s:%d/%s?auto" % (self._proto, self._host, self._port,
self._statuspath)
response = util.get_url(url, self._user, self._password)
self._statusDict = {}
f... |
Returns a df of features for presented items | def get_pres_features(self, features=None):
"""
Returns a df of features for presented items
"""
if features is None:
features = self.dist_funcs.keys()
elif not isinstance(features, list):
features = [features]
return self.pres.applymap(lambda x: {... |
Returns a df of features for recalled items | def get_rec_features(self, features=None):
"""
Returns a df of features for recalled items
"""
if features is None:
features = self.dist_funcs.keys()
elif not isinstance(features, list):
features = [features]
return self.rec.applymap(lambda x: {k:v... |
Print info about the data egg | def info(self):
"""
Print info about the data egg
"""
print('Number of subjects: ' + str(self.n_subjects))
print('Number of lists per subject: ' + str(self.n_lists))
print('Number of words per list: ' + str(self.list_length))
print('Date created: ' + str(self.date... |
Save method for the Egg object | def save(self, fname, compression='blosc'):
"""
Save method for the Egg object
The data will be saved as a 'egg' file, which is a dictionary containing
the elements of a Egg saved in the hd5 format using
`deepdish`.
Parameters
----------
fname : str
... |
Save method for the FriedEgg object | def save(self, fname, compression='blosc'):
"""
Save method for the FriedEgg object
The data will be saved as a 'fegg' file, which is a dictionary containing
the elements of a FriedEgg saved in the hd5 format using
`deepdish`.
Parameters
----------
fnam... |
Computes probability of a word being recalled nth ( in the appropriate recall list ) given its presentation position. Note: zero indexed | def pnr_helper(egg, position, match='exact',
distance='euclidean', features=None):
"""
Computes probability of a word being recalled nth (in the appropriate recall
list), given its presentation position. Note: zero indexed
Parameters
----------
egg : quail.Egg
Data to a... |
Retrieve values for graphs. | def retrieveVals(self):
"""Retrieve values for graphs."""
apacheInfo = ApacheInfo(self._host, self._port,
self._user, self._password,
self._statuspath, self._ssl)
stats = apacheInfo.getServerStats()
if self.hasGraph('apache... |
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.
"""
apacheInfo = ApacheInfo(self._host, self._port,
self._user, self._password,
... |
Retrieve values for graphs. | def retrieveVals(self):
"""Retrieve values for graphs."""
ntpinfo = NTPinfo()
ntpstats = ntpinfo.getHostOffsets(self._remoteHosts)
if ntpstats:
for host in self._remoteHosts:
hostkey = re.sub('\.', '_', host)
hoststats = ntpstats.get(host)
... |
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.
"""
ntpinfo = NTPinfo()
ntpstats = ntpinfo.getHostOffsets(self._remoteHosts)
return len(ntpstats) > 0 |
Retrieve values for graphs. | def retrieveVals(self):
"""Retrieve values for graphs."""
lighttpdInfo = LighttpdInfo(self._host, self._port,
self._user, self._password,
self._statuspath, self._ssl)
stats = lighttpdInfo.getServerStats()
if self.hasGraph('... |
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.
"""
lighttpdInfo = LighttpdInfo(self._host, self._port,
self._user, self._password,
... |
Retrieve values for graphs. | def retrieveVals(self):
"""Retrieve values for graphs."""
name = 'diskspace'
if self.hasGraph(name):
for fspath in self._fslist:
if self._statsSpace.has_key(fspath):
self.setGraphVal(name, fspath,
self._statsSp... |
Perform symbolic object ( symbolic LU decomposition ) computation for a given sparsity pattern. | def symbolic(self, mtx):
"""
Perform symbolic object (symbolic LU decomposition) computation for a given
sparsity pattern.
"""
self.free_symbolic()
indx = self._getIndx(mtx)
if not assumeSortedIndices:
# row/column indices cannot be assumed to be sor... |
Perform numeric object ( LU decomposition ) computation using the symbolic decomposition. The symbolic decomposition is ( re ) computed if necessary. | def numeric(self, mtx):
"""
Perform numeric object (LU decomposition) computation using the
symbolic decomposition. The symbolic decomposition is (re)computed
if necessary.
"""
self.free_numeric()
if self._symbolic is None:
self.symbolic(mtx)
... |
Free symbolic data | def free_symbolic(self):
"""Free symbolic data"""
if self._symbolic is not None:
self.funs.free_symbolic(self._symbolic)
self._symbolic = None
self.mtx = None |
Free numeric data | def free_numeric(self):
"""Free numeric data"""
if self._numeric is not None:
self.funs.free_numeric(self._numeric)
self._numeric = None
self.free_symbolic() |
Solution of system of linear equation using the Numeric object. | def solve(self, sys, mtx, rhs, autoTranspose=False):
"""
Solution of system of linear equation using the Numeric object.
Parameters
----------
sys : constant
one of UMFPACK system description constants, like
UMFPACK_A, UMFPACK_At, see umfSys list and UMFP... |
One - shot solution of system of linear equation. Reuses Numeric object if possible. | def linsolve(self, sys, mtx, rhs, autoTranspose=False):
"""
One-shot solution of system of linear equation. Reuses Numeric object
if possible.
Parameters
----------
sys : constant
one of UMFPACK system description constants, like
UMFPACK_A, UMFPAC... |
Perform LU decomposition. | def lu(self, mtx):
"""
Perform LU decomposition.
For a given matrix A, the decomposition satisfies::
LU = PRAQ when do_recip is true
LU = P(R^-1)AQ when do_recip is false
Parameters
----------
mtx : scipy.sparse.csc_matrix or sc... |
Reorders a list according to strategy | def order_stick(presenter, egg, dist_dict, strategy, fingerprint):
"""
Reorders a list according to strategy
"""
def compute_feature_stick(features, weights, alpha):
'''create a 'stick' of feature weights'''
feature_stick = []
for f, w in zip(features, weights):
fea... |
Computes weights for one reordering using stick - breaking method | def stick_perm(presenter, egg, dist_dict, strategy):
"""Computes weights for one reordering using stick-breaking method"""
# seed RNG
np.random.seed()
# unpack egg
egg_pres, egg_rec, egg_features, egg_dist_funcs = parse_egg(egg)
# reorder
regg = order_stick(presenter, egg, dist_dict, stra... |
Creates a nested dict of distances | def compute_distances_dict(egg):
""" Creates a nested dict of distances """
pres, rec, features, dist_funcs = parse_egg(egg)
pres_list = list(pres)
features_list = list(features)
# initialize dist dict
distances = {}
# for each word in the list
for idx1, item1 in enumerate(pres_list):
... |
Compute clustering scores along a set of feature dimensions | def compute_feature_weights_dict(pres_list, rec_list, feature_list, dist_dict):
"""
Compute clustering scores along a set of feature dimensions
Parameters
----------
pres_list : list
list of presented words
rec_list : list
list of recalled words
feature_list : list
l... |
In - place method that updates fingerprint with new data | def update(self, egg, permute=False, nperms=1000,
parallel=False):
"""
In-place method that updates fingerprint with new data
Parameters
----------
egg : quail.Egg
Data to update fingerprint
Returns
----------
None
"""... |
Reorders a list of stimuli to match a fingerprint | def order(self, egg, method='permute', nperms=2500, strategy=None,
distfun='correlation', fingerprint=None):
"""
Reorders a list of stimuli to match a fingerprint
Parameters
----------
egg : quail.Egg
Data to compute fingerprint
method : str
... |
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.
"""
url = "%s://%s:%d/%s" % (self._proto, self._host, self._port, self._monpath)
... |
Return major and minor device number for block device path devpath. | def _getDevMajorMinor(self, devpath):
"""Return major and minor device number for block device path devpath.
@param devpath: Full path for block device.
@return: Tuple (major, minor).
"""
fstat = os.stat(devpath)
if stat.S_ISBLK(fstat.st_mode):
... |
Return unique device for any block device path. | def _getUniqueDev(self, devpath):
"""Return unique device for any block device path.
@param devpath: Full path for block device.
@return: Unique device string without the /dev prefix.
"""
realpath = os.path.realpath(devpath)
mobj = re.match('\/dev... |
Parses/ proc/ devices to initialize device class - major number map for block devices. | def _initBlockMajorMap(self):
"""Parses /proc/devices to initialize device class - major number map
for block devices.
"""
self._mapMajorDevclass = {}
try:
fp = open(devicesFile, 'r')
data = fp.read()
fp.close()
except:
... |
Check files in/ dev/ mapper to initialize data structures for mappings between device - mapper devices minor device numbers VGs and LVs. | def _initDMinfo(self):
"""Check files in /dev/mapper to initialize data structures for
mappings between device-mapper devices, minor device numbers, VGs
and LVs.
"""
self._mapLVtuple2dm = {}
self._mapLVname2dm = {}
self._vgTree = {}
if self._dmM... |
Initialize filesystem to device mappings. | def _initFilesystemInfo(self):
"""Initialize filesystem to device mappings."""
self._mapFSpathDev = {}
fsinfo = FilesystemInfo()
for fs in fsinfo.getFSlist():
devpath = fsinfo.getFSdev(fs)
dev = self._getUniqueDev(devpath)
if dev is not None:
... |
Initialize swap partition to device mappings. | def _initSwapInfo(self):
"""Initialize swap partition to device mappings."""
self._swapList = []
sysinfo = SystemInfo()
for (swap,attrs) in sysinfo.getSwapStats().iteritems():
if attrs['type'] == 'partition':
dev = self._getUniqueDev(swap)
if d... |
Parse and initialize block device I/ O stats in/ proc/ diskstats. | def _initDiskStats(self):
"""Parse and initialize block device I/O stats in /proc/diskstats."""
self._diskStats = {}
self._mapMajorMinor2dev = {}
try:
fp = open(diskStatsFile, 'r')
data = fp.read()
fp.close()
except:
raise IOError('... |
Sort block devices into lists depending on device class and initialize device type map and partition map. | def _initDevClasses(self):
"""Sort block devices into lists depending on device class and
initialize device type map and partition map."""
self._devClassTree = {}
self._partitionTree = {}
self._mapDevType = {}
basedevs = []
otherdevs = []
if self._mapMajo... |
Returns type of device dev. | def getDevType(self, dev):
"""Returns type of device dev.
@return: Device type as string.
"""
if self._devClassTree is None:
self._initDevClasses()
return self._mapDevType.get(dev) |
Returns list of partitions. | def getPartitionList(self):
"""Returns list of partitions.
@return: List of (disk,partition) pairs.
"""
if self._partList is None:
self._partList = []
for (disk,parts) in self.getPartitionDict().iteritems():
for part in parts:
... |
Returns I/ O stats for block device. | def getDevStats(self, dev, devtype = None):
"""Returns I/O stats for block device.
@param dev: Device name
@param devtype: Device type. (Ignored if None.)
@return: Dict of stats.
"""
if devtype is not None:
if self._devClassTree is... |
Returns I/ O stats for swap partition. | def getSwapStats(self, dev):
"""Returns I/O stats for swap partition.
@param dev: Device name for swap partition.
@return: Dict of stats.
"""
if self._swapList is None:
self._initSwapInfo()
if dev in self._swapList:
return self.ge... |
Returns I/ O stats for LV. | def getLVstats(self, *args):
"""Returns I/O stats for LV.
@param args: Two calling conventions are implemented:
- Passing two parameters vg and lv.
- Passing only one parameter in 'vg-lv' format.
@return: Dict of stats.
""... |
Returns I/ O stats for filesystem. | def getFilesystemStats(self, fs):
"""Returns I/O stats for filesystem.
@param fs: Filesystem path.
@return: Dict of stats.
"""
if self._mapFSpathDev is None:
self._initFilesystemInfo()
return self._diskStats.get(self._mapFSpathDev.get(fs)) |
Retrieve values for graphs. | def retrieveVals(self):
"""Retrieve values for graphs."""
ntpinfo = NTPinfo()
stats = ntpinfo.getHostOffset(self._remoteHost)
if stats:
graph_name = 'ntp_host_stratum_%s' % self._remoteHost
if self.hasGraph(graph_name):
self.setGraphVal(graph_name,... |
Returns Rackspace Cloud Files usage stats for containers. | def getContainerStats(self, limit=None, marker=None):
"""Returns Rackspace Cloud Files usage stats for containers.
@param limit: Number of containers to return.
@param marker: Return only results whose name is greater than marker.
@return: Dictionary of container stats in... |
Decode speech for a file or folder and return results | def decode_speech(path, keypath=None, save=False, speech_context=None,
sample_rate=44100, max_alternatives=1, language_code='en-US',
enable_word_time_offsets=True, return_raw=False):
"""
Decode speech for a file or folder and return results
This function wraps the Google... |
Parse input string and return int float or str depending on format. | def parse_value(val):
"""Parse input string and return int, float or str depending on format.
@param val: Input string.
@return: Value of type int, float or str.
"""
mobj = re.match('(-{0,1}\d+)\s*(\sseconds|/\s*\w+)$', val)
if mobj:
return int(mobj.group(1))
m... |
Connect to Squid Proxy Manager interface. | def _connect(self):
"""Connect to Squid Proxy Manager interface."""
if sys.version_info[:2] < (2,6):
self._conn = httplib.HTTPConnection(self._host, self._port)
else:
self._conn = httplib.HTTPConnection(self._host, self._port,
... |
Query Squid Proxy Server Manager Interface for stats. | def _retrieve(self, map):
"""Query Squid Proxy Server Manager Interface for stats.
@param map: Statistics map name.
@return: Dictionary of query results.
"""
self._conn.request('GET', "cache_object://%s/%s" % (self._host, map),
Non... |
Parse simple stats list of key value pairs. | def _parseCounters(self, data):
"""Parse simple stats list of key, value pairs.
@param data: Multiline data with one key-value pair in each line.
@return: Dictionary of stats.
"""
info_dict = util.NestedDict()
for line in data.splitlines():
... |
Parse data and separate sections. Returns dictionary that maps section name to section data. | def _parseSections(self, data):
"""Parse data and separate sections. Returns dictionary that maps
section name to section data.
@param data: Multiline data.
@return: Dictionary that maps section names to section data.
"""
section_dict = {}
l... |
Get manager interface section list from Squid Proxy Server | def getMenu(self):
"""Get manager interface section list from Squid Proxy Server
@return: List of tuples (section, description, type)
"""
data = self._retrieve('')
info_list = []
for line in data.splitlines():
mobj = re.match('^\s*(\S.*\S... |
Return dictionary of Traffic Stats for each Wanpipe Interface. | def getIfaceStats(self):
"""Return dictionary of Traffic Stats for each Wanpipe Interface.
@return: Nested dictionary of statistics for each interface.
"""
ifInfo = netiface.NetIfaceInfo()
ifStats = ifInfo.getIfStats()
info_dict = {}
for ifname i... |
Return RDSI Operational Stats for interface. @param iface: Interface name. ( Ex. w1g1 ) @return: Nested dictionary of statistics for interface. | def getPRIstats(self, iface):
"""Return RDSI Operational Stats for interface.
@param iface: Interface name. (Ex. w1g1)
@return: Nested dictionary of statistics for interface.
"""
info_dict = {}
output = util.exec_command([wanpipemonCmd, '-i', iface, '-c', ... |
Connect to FreeSWITCH ESL Interface. | def _connect(self):
"""Connect to FreeSWITCH ESL Interface."""
try:
self._eslconn = ESL.ESLconnection(self._eslhost,
str(self._eslport),
self._eslpass)
except:
pass
if no... |
Execute command and return result body as list of lines. | def _execCmd(self, cmd, args):
"""Execute command and return result body as list of lines.
@param cmd: Command string.
@param args: Comand arguments string.
@return: Result dictionary.
"""
output = self._eslconn.api(cmd, args)
... |
Execute show command and return result dictionary. | def _execShowCmd(self, showcmd):
"""Execute 'show' command and return result dictionary.
@param cmd: Command string.
@return: Result dictionary.
"""
result = None
lines = self._execCmd("show", showcmd)
if lines and len(lines) >= 2 and... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.