text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 bu...
response = '' oldlen = 0 newlen = 0 while True: response += fp.read(buffSize) newlen = len(response) if newlen - oldlen == 0: break else: oldlen = newlen return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exec_command(args, env=None): """Convenience function that executes command and returns result. @param args: Tuple of command and arguments. @param env: Dict...
try: cmd = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=buffSize, env=env) except OSError, e: raise Exception("Execution of command fa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def registerFilter(self, column, patterns, is_regex=False, ignore_case=False): """Register filter on a column of table. @param column: The column name. @param pa...
if isinstance(patterns, basestring): patt_list = (patterns,) elif isinstance(patterns, (tuple, list)): patt_list = list(patterns) else: raise ValueError("The patterns parameter must either be as string " "or a tuple / list of stri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def registerFilters(self, **kwargs): """Register multiple filters at once. @param **kwargs: Multiple filters are registered using keyword variables. Each keyword...
for (key, patterns) in kwargs.items(): if key.endswith('_regex'): col = key[:-len('_regex')] is_regex = True else: col = key is_regex = False if col.endswith('_ic'): col = col[:-len('_ic')] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def applyFilters(self, headers, table): """Apply filter on ps command result. @param headers: List of column headers. @param table: Nested list of rows and colum...
result = [] column_idxs = {} for column in self._filters.keys(): try: column_idxs[column] = headers.index(column) except ValueError: raise ValueError('Invalid column name %s in filter.' % column) for row in table: for (...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def function(data, maxt=None): """ Calculate the autocorrelation function for a 1D time series. Parameters data : numpy.ndarray (N,) The time series. Returns ---...
data = np.atleast_1d(data) assert len(np.shape(data)) == 1, \ "The autocorrelation function can only by computed " \ + "on a 1D time series." if maxt is None: maxt = len(data) result = np.zeros(maxt, dtype=float) _acor.function(np.array(data, dtype=float), result) return...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fingerprint_helper(egg, permute=False, n_perms=1000, match='exact', distance='euclidean', features=None): """ Computes clustering along a set of feature dime...
if features is None: features = egg.dist_funcs.keys() inds = egg.pres.index.tolist() slices = [egg.crack(subjects=[i], lists=[j]) for i, j in inds] weights = _get_weights(slices, features, distdict, permute, n_perms, match, distance) return np.nanmean(weights,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
try: # Attempt to evaluate into python literal return ast.literal_eval(os.environ.get(key.upper(), default)) except (ValueError, SyntaxError): return os.environ.get(key.upper(), default)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 `.e...
if filepath is None: filepath = os.path.join('.env') with open(filepath, 'wb') as file_handle: file_handle.writelines( '{0}={1}\n'.format(key.upper(), val) for key, val in kwargs.items() )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
if filepath and os.path.exists(filepath): pass else: if not os.path.exists('.env'): return False filepath = os.path.join('.env') for key, value in _get_line_(filepath): # set the key, value in the python environment vars dictionary # does not make modifi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = {} for line in response.splitlines(): mobj = re.match('(\S.*\S)\s*:\s*(\S...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: {k:v for k,v in x.items() if k in features} if x is not None else None)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 for k,v in x.items() if k != 'item'} if x is not None else None)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_created)) print('Meta data: ' + str(self.meta))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 eleme...
# put egg vars into a dict egg = { 'pres' : df2list(self.pres), 'rec' : df2list(self.rec), 'dist_funcs' : self.dist_funcs, 'subjgroup' : self.subjgroup, 'subjname' : self.subjname, 'listgroup' : self.listgroup, 'listna...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
egg = { 'data' : self.data, 'analysis' : self.analysis, 'list_length' : self.list_length, 'n_lists' : self.n_lists, 'n_subjects' : self.n_subjects, 'position' : self.position, 'date_created' : self.date_created, 'm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def solve(self, sys, mtx, rhs, autoTranspose=False): """ Solution of system of linear equation using the Numeric object. Parameters sys : constant one of UMFPACK...
if sys not in umfSys: raise ValueError('sys must be in' % umfSys) if autoTranspose and self.isCSR: ## # UMFPACK uses CSC internally... if self.family in umfRealTypes: ii = 0 else: ii = 1 if sys in u...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def linsolve(self, sys, mtx, rhs, autoTranspose=False): """ One-shot solution of system of linear equation. Reuses Numeric object if possible. Parameters sys : c...
if sys not in umfSys: raise ValueError('sys must be in' % umfSys) if self._numeric is None: self.numeric(mtx) else: if self.mtx is not mtx: self.numeric(mtx) sol = self.solve(sys, mtx, rhs, autoTranspose) self.free_numeric()...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, strategy) # unpack regg regg_pres, regg_rec, regg_features, regg_dist_funcs = parse_egg(regg) # # get the order ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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): distances[item1]={} # for each word in the list for i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
# increment n self.n+=1 next_weights = np.nanmean(_analyze_chunk(egg, analysis=fingerprint_helper, analysis_type='fingerprint', pass_features=True, permute=permute, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getDevMajorMinor(self, devpath): """Return major and minor device number for block device path devpath. @param devpath: Full path for block device. @return:...
fstat = os.stat(devpath) if stat.S_ISBLK(fstat.st_mode): return(os.major(fstat.st_rdev), os.minor(fstat.st_rdev)) else: raise ValueError("The file %s is not a valid block device." % devpath)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getUniqueDev(self, devpath): """Return unique device for any block device path. @param devpath: Full path for block device. @return: Unique device string wi...
realpath = os.path.realpath(devpath) mobj = re.match('\/dev\/(.*)$', realpath) if mobj: dev = mobj.group(1) if dev in self._diskStats: return dev else: try: (major, minor) = self._getDevMajorMinor(realpath) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: self._mapFSpathDev[fs] = dev
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 dev is not None: self._swapList.append(dev)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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._mapMajorDevclass is None: self._initBlockMajorMap() for dev in self._diskStats: stats = self._diskStats[dev] devclass ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: self._partList.append((disk,part)) return self._partList
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getContainerStats(self, limit=None, marker=None): """Returns Rackspace Cloud Files usage stats for containers. @param limit: Number of containers to return. ...
stats = {} for row in self._conn.list_containers_info(limit, marker): stats[row['name']] = {'count': row['count'], 'size': row['bytes']} return stats
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, False, defaultTimeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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), None, self._httpHeaders) rp = self._conn.getresponse() if rp.status == 200: data = rp.read() return data else: raise Exception("Retrieval of stats from S...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: Dictio...
info_dict = util.NestedDict() for line in data.splitlines(): mobj = re.match('^\s*([\w\.]+)\s*=\s*(\S.*)$', line) if mobj: (key, value) = mobj.groups() klist = key.split('.') info_dict.set_nested(klist, parse_value(value)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parseSections(self, data): """Parse data and separate sections. Returns dictionary that maps section name to section data. @param data: Multiline data. @ret...
section_dict = {} lines = data.splitlines() idx = 0 numlines = len(lines) section = None while idx < numlines: line = lines[idx] idx += 1 mobj = re.match('^(\w[\w\s\(\)]+[\w\)])\s*:$', line) if mobj: section...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)\s*\t\s*(\S.*\S)\s*\t\s*(\S.*\S)$', line) if mobj: info_list.append(mobj.groups()) return info_list
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 in ifStats: if re.match('^w\d+g\d+$', ifname): info_dict[ifname] = ifStats[ifname] return info_dict
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _connect(self): """Connect to FreeSWITCH ESL Interface."""
try: self._eslconn = ESL.ESLconnection(self._eslhost, str(self._eslport), self._eslpass) except: pass if not self._eslconn.connected(): raise Exception( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _execCmd(self, cmd, args): """Execute command and return result body as list of lines. @param cmd: Command string. @param args: Comand arguments string. @ret...
output = self._eslconn.api(cmd, args) if output: body = output.getBody() if body: return body.splitlines() return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list2pd(all_data, subjindex=None, listindex=None): """ Makes multi-indexed dataframe of subject data Parameters all_data : list of lists of strings strings a...
# set default index if it is not defined # max_nlists = max(map(lambda x: len(x), all_data)) listindex = [[idx for idx in range(len(sub))] for sub in all_data] if not listindex else listindex subjindex = [idx for idx,subj in enumerate(all_data)] if not subjindex else subjindex def make_multi_inde...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recmat2egg(recmat, list_length=None): """ Creates egg data object from zero-indexed recall matrix Parameters recmat : list of lists (subs) of lists (encoding...
from .egg import Egg as Egg pres = [[[str(word) for word in list(range(0,list_length))] for reclist in recsub] for recsub in recmat] rec = [[[str(word) for word in reclist if word is not None] for reclist in recsub] for recsub in recmat] return Egg(pres=pres,rec=rec)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 == 'item': pass elif isinstance(feature_example[key], (six.string_types, six.binary_type)): dist_fun...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 lev...
subjects = df.index.levels[0].values.tolist() lists = df.index.levels[1].values.tolist() idx = pd.IndexSlice df = df.loc[idx[subjects,lists],df.columns] lst = [df.loc[sub,:].values.tolist() for sub in subjects] return lst
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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): p.update(f) lst.append(p) exp.append(lst) sub.append(exp) return sub
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def r2z(r): """ Function that calculates the Fisher z-transformation Parameters r : int or ndarray Correlation value Returns result : int or ndarray Fishers z tr...
with np.errstate(invalid='ignore', divide='ignore'): return 0.5 * (np.log(1 + r) - np.log(1 - r))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def z2r(z): """ Function that calculates the inverse Fisher z-transformation Parameters z : int or ndarray Fishers z transformed correlation value Returns result...
with np.errstate(invalid='ignore', divide='ignore'): return (np.exp(2 * z) - 1) / (np.exp(2 * z) + 1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 in range(rec.shape[0]): idx = np.random.permutati...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 stats from file: %s' % uptimeFile) return float(line.split()[0])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 reading stats from file: %s' % loadavgFile) arr = line.split() if len(arr) >= 3: return [float(col) for col in arr[:3]] else...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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() except: raise IOError('Failed reading stats from file: %s' % cpustatFile) headers = ['user', 'nice', 'system', 'idle', 'i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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() fp.close() except: raise IOError('Failed reading stats from file: %s' % cpustatFile) for line in data.splitlines(): arr = line.split() if len(arr) > 1...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 reading stats from file: %s' % meminfoFile) for line in data.splitlines(): mobj = re.match('^(.+):\s*(\d+)\s*(\w+|)\s*$',...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 reading stats from file: %s' % vmstatFile) for line in data.splitlines(): cols = line.split() if len(cols) == ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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._timeout is not None: self._conn = util...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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', re.MULTILINE) (idx, mobj, text) = self._conn.expect([regex,], self._timeout) #@UnusedVariable except: raise Exception("Communication with %s failed" % self._instanceName) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parseStats(self, lines, parse_slabs = False): """Parse stats output from memcached and return dictionary of stats- @param lines: Array of lines of input tex...
info_dict = {} info_dict['slabs'] = {} for line in lines: mobj = re.match('^STAT\s(\w+)\s(\S+)$', line) if mobj: info_dict[mobj.group(1)] = util.parse_value(mobj.group(2), True) continue elif parse_slabs: mobj ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def euclidean(a, b): "Returns euclidean distance between a and b" return np.linalg.norm(np.subtract(a, b))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parseProcCmd(self, fields=('pid', 'user', 'cmd',), threads=False): """Execute ps command with custom output format with columns from fields and return result...
args = [] headers = [f.lower() for f in fields] args.append('--no-headers') args.append('-e') if threads: args.append('-T') field_ranges = [] fmt_strs = [] start = 0 for header in headers: field_width = psFieldWidth.get(hea...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getProcList(self, fields=('pid', 'user', 'cmd',), threads=False, **kwargs): """Execute ps command with custom output format with columns columns from fields,...
field_list = list(fields) for key in kwargs: col = re.sub('(_ic)?(_regex)?$', '', key) if not col in field_list: field_list.append(col) pinfo = self.parseProcCmd(field_list, threads) if pinfo: if len(kwargs) > 0: pfilte...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getProcDict(self, fields=('user', 'cmd',), threads=False, **kwargs): """Execute ps command with custom output format with columns format with columns from fi...
stats = {} field_list = list(fields) num_cols = len(field_list) if threads: key = 'spid' else: key = 'pid' try: key_idx = field_list.index(key) except ValueError: field_list.append(key) key_idx = len(fie...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getProcStatStatus(self, threads=False, **kwargs): """Return process counts per status and priority. @param **kwargs: Keyword variables are used for filtering...
procs = self.getProcList(['stat',], threads=threads, **kwargs) status = dict(zip(procStatusNames.values(), [0,] * len(procStatusNames))) prio = {'high': 0, 'low': 0, 'norm': 0, 'locked_in_mem': 0} total = 0 locked_in_mem = 0 if procs is not Non...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def muninMain(pluginClass, argv=None, env=None, debug=False): """Main Block for Munin Plugins. @param pluginClass: Child class of MuninPlugin that implements plu...
if argv is None: argv = sys.argv if env is None: env = os.environ debug = debug or env.has_key('MUNIN_DEBUG') if len(argv) > 1 and argv[1] == 'autoconf': autoconf = True else: autoconf = False try: plugin = pluginClass(argv, env, debug) ret = plug...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fixLabel(label, maxlen, delim=None, repl='', truncend=True): """Truncate long graph and field labels. @param label: Label text. @param maxlen: Maximum field ...
if len(label) <= maxlen: return label else: maxlen -= len(repl) if delim is not None: if truncend: end = label.rfind(delim, 0, maxlen) if end > 0: return label[:end+1] + repl else: start = labe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
graph = self._graphDict.get(graph_name) if fail_noexist and graph is None: raise AttributeError("Invalid graph name: %s" % graph_name) else: return graph
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getSubGraph(self, parent_name, graph_name, fail_noexist=False): """Private method for returning subgraph object with name graph_name and parent graph with n...
if not self.isMultigraph: raise AttributeError("Simple Munin Plugins cannot have subgraphs.") if self._graphDict.has_key(parent_name) is not None: subgraphs = self._subgraphDict.get(parent_name) if subgraphs is not None: subgraph = subgraphs.get(graph...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getMultigraphID(self, graph_name, subgraph_name=None): """Private method for generating Multigraph ID from graph name and subgraph name. @param graph_name: ...
if self.isMultiInstance and self._instanceName is not None: if subgraph_name is None: return "%s_%s" % (graph_name, self._instanceName) else: return "%s_%s.%s_%s" % (graph_name, self._instanceName, subgraph_name, s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _formatConfig(self, conf_dict): """Formats configuration directory from Munin Graph and returns multi-line value entries for the plugin config cycle. @param ...
confs = [] graph_dict = conf_dict['graph'] field_list = conf_dict['fields'] # Order and format Graph Attributes title = graph_dict.get('title') if title is not None: if self.isMultiInstance and self._instanceLabel is not None: if self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
vals = [] for (name, val) in val_list: if val is not None: if isinstance(val, float): vals.append("%s.value %f" % (name, val)) else: vals.append("%s.value %s" % (name, val)) else: vals.append...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def envGet(self, name, default=None, conv=None): """Return value for environment variable or None. @param name: Name of environment variable. @param default: Def...
if self._env.has_key(name): if conv is not None: return conv(self._env.get(name)) else: return self._env.get(name) else: return default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def saveState(self, stateObj): """Utility methos to save plugin state stored in stateObj to persistent storage to permit access to previous state in subsequent p...
try: fp = open(self._stateFile, 'w') pickle.dump(stateObj, fp) except: raise IOError("Failure in storing plugin state in file: %s" % self._stateFile) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restoreState(self): """Utility method to restore plugin state from persistent storage to permit access to previous plugin state. @return: Object that stores ...
if os.path.exists(self._stateFile): try: fp = open(self._stateFile, 'r') stateObj = pickle.load(fp) except: raise IOError("Failure in reading plugin state from file: %s" % self._stateFile) return...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def appendSubgraph(self, parent_name, graph_name, graph): """Utility method to associate Subgraph Instance to Root Graph Instance. This utility method is for use...
if not self.isMultigraph: raise AttributeError("Simple Munin Plugins cannot have subgraphs.") if self._graphDict.has_key(parent_name): if not self._subgraphDict.has_key(parent_name): self._subgraphDict[parent_name] = {} self._subgraphNames[parent_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
subgraph = self._getSubGraph(parent_name, graph_name, True) if subgraph.hasField(field_name): subgraph.setVal(field_name, val) else: raise AttributeError("Invalid field name %s for subgraph %s " "of parent graph %s." ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. @retu...
if not self.isMultigraph: raise AttributeError("Simple Munin Plugins cannot have subgraphs.") if self._graphDict.has_key(parent_name): return self._subgraphNames[parent_name] or [] else: raise AttributeError("Invalid parent graph name %s." ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 @para...
graph = self._graphDict.get(graph_name, True) return graph.hasField(field_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 fiel...
subgraph = self._getSubGraph(parent_name, graph_name, True) return subgraph.hasField(field_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
graph = self._getGraph(graph_name, True) return graph.getFieldList()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = self._getGraph(graph_name, True) return graph.getFieldCount()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_n...
graph = self._getSubGraph(parent_name, graph_name, True) return graph.getFieldList()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getSubgraphFieldCount(self, parent_name, graph_name): """Returns number of fields for subgraph with name graph_name and parent graph with name parent_name. @...
graph = self._getSubGraph(parent_name, graph_name, True) return graph.getFieldCount()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def config(self): """Implements Munin Plugin Graph Configuration. Prints out configuration for graphs. Use as is. Not required to be overwritten in child classes...
for parent_name in self._graphNames: graph = self._graphDict[parent_name] if self.isMultigraph: print "multigraph %s" % self._getMultigraphID(parent_name) print self._formatConfig(graph.getConfig()) print if (self.isMultigraph and self._ne...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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._getMultigraphID(parent_name) print self._formatVals(graph.getVals()) print if (self.i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = self.config() if ret and self._dirtyConfig: ret = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addField(self, name, label, type=None, draw=None, info=None, #@ReservedAssignment extinfo=None, colour=None, negative=None, graph=None, min=None, max=None, cd...
if self._autoFixNames: name = self._fixName(name) if negative is not None: negative = self._fixName(negative) self._fieldAttrDict[name] = dict(((k,v) for (k,v) in locals().iteritems() if (v is not None ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 field_name in self._fieldNameList]}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 response.splitlines(): mobj = re.match('\s*(\d+)\s+(\d+)\s+(\d+)\s*$',...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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() except: raise IOError('Failed reading interface stats from file: %s' % ifaceStatsFile) for line in data.splitlines(): mobj...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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('Execution of command %s failed.' % ipCmd) lines = out.splitlines() if len(lines) > 1: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getTCPportConnStatus(self, ipv4=True, ipv6=True, include_listen=False, **kwargs): """Returns the number of TCP endpoints discriminated by status. @param ipv4...
status_dict = {} result = self.getStats(tcp=True, udp=False, include_listen=include_listen, ipv4=ipv4, ipv6=ipv6, **kwargs) stats = result['stats'] for stat in stats: if stat is n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getTCPportConnCount(self, ipv4=True, ipv6=True, resolve_ports=False, **kwargs): """Returns TCP connection counts for each local port. @param ipv4: Include IP...
port_dict = {} result = self.getStats(tcp=True, udp=False, include_listen=False, ipv4=ipv4, ipv6=ipv6, resolve_ports=resolve_ports, **kwargs) stats = result['stats'] for stat in stats: ...