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 clean(func):
""" This decorator removes the temp file from disk. This is the case where you want to analyze from a payload. """ |
def wrapper(*args, **kwargs):
# tuple: output command, path given from command line,
# path of templ file when you give the payload
out, given_path, path = func(*args, **kwargs)
try:
if not given_path:
os.remove(path)
except OSError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def file_path(path=None, payload=None, objectInput=None):
""" Given a file path, payload or file object, it writes file on disk and returns the temp path. Args: ... |
f = path if path else write_payload(payload, objectInput)
if not os.path.exists(f):
msg = "File {!r} does not exist".format(f)
log.exception(msg)
raise TikaAppFilePathError(msg)
return f |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_payload(payload=None, objectInput=None):
""" This function writes a base64 payload or file object on disk. Args: payload (string):
payload in base64 o... |
temp = tempfile.mkstemp()[1]
log.debug("Write payload in temp file {!r}".format(temp))
with open(temp, 'wb') as f:
if payload:
payload = base64.b64decode(payload)
elif objectInput:
if six.PY3:
payload = objectInput.buffer.read()
elif six... |
<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_subject(self, data):
""" Try to get a unique ID from the object. By default, this will be the 'id' field of any given object, or a field specified by the... |
if not isinstance(data, Mapping):
return None
if data.get(self.subject):
return data.get(self.subject)
return uuid.uuid4().urn |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def triplify(self, data, parent=None):
""" Recursively generate statements from the data supplied. """ |
if data is None:
return
if self.is_object:
for res in self._triplify_object(data, parent):
yield res
elif self.is_array:
for item in data:
for res in self.items.triplify(item, parent):
yield res
els... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _triplify_object(self, data, parent):
""" Create bi-directional statements for object relationships. """ |
subject = self.get_subject(data)
if self.path:
yield (subject, TYPE_SCHEMA, self.path, TYPE_SCHEMA)
if parent is not None:
yield (parent, self.predicate, subject, TYPE_LINK)
if self.reverse is not None:
yield (subject, self.reverse, parent, T... |
<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_json(request, token):
"""Return matching results as JSON""" |
result = []
searchtext = request.GET['q']
if len(searchtext) >= 3:
pickled = _simple_autocomplete_queryset_cache.get(token, None)
if pickled is not None:
app_label, model_name, query = pickle.loads(pickled)
model = apps.get_model(app_label, model_name)
qu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dash_f_e_to_dict(self, info_filename, tree_filename):
""" Raxml provides an option to fit model params to a tree, selected with -f e. The output is differen... |
with open(info_filename) as fl:
models, likelihood, partition_params = self._dash_f_e_parser.parseFile(fl).asList()
with open(tree_filename) as fl:
tree = fl.read()
d = {'likelihood': likelihood, 'ml_tree': tree, 'partitions': {}}
for model, params in zip(mode... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dict(self, info_filename, tree_filename, dash_f_e=False):
""" Parse raxml output and return a dict Option dash_f_e=True will parse the output of a raxml -... |
logger.debug('info_filename: {} {}'
.format(info_filename, '(FOUND)' if os.path.exists(info_filename) else '(NOT FOUND)'))
logger.debug('tree_filename: {} {}'
.format(tree_filename, '(FOUND)' if os.path.exists(tree_filename) else '(NOT FOUND)'))
if dash... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def freader(filename, gz=False, bz=False):
""" Returns a filereader object that can handle gzipped input """ |
filecheck(filename)
if filename.endswith('.gz'):
gz = True
elif filename.endswith('.bz2'):
bz = True
if gz:
return gzip.open(filename, 'rb')
elif bz:
return bz2.BZ2File(filename, 'rb')
else:
return io.open(filename, 'rb') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fwriter(filename, gz=False, bz=False):
""" Returns a filewriter object that can write plain or gzipped output. If gzip or bzip2 compression is asked for then... |
if filename.endswith('.gz'):
gz = True
elif filename.endswith('.bz2'):
bz = True
if gz:
if not filename.endswith('.gz'):
filename += '.gz'
return gzip.open(filename, 'wb')
elif bz:
if not filename.endswith('.bz2'):
filename += '.bz2'
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def glob_by_extensions(directory, extensions):
""" Returns files matched by all extensions in the extensions list """ |
directorycheck(directory)
files = []
xt = files.extend
for ex in extensions:
xt(glob.glob('{0}/*.{1}'.format(directory, ex)))
return files |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def head(filename, n=10):
""" prints the top `n` lines of a file """ |
with freader(filename) as fr:
for _ in range(n):
print(fr.readline().strip()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channels_for_role(role):
""" Get the channels for a role """ |
chans = []
chans_names = []
# default channels
if role == "public":
if ENABLE_PUBLIC_CHANNEL is True:
chan = dict(slug=PUBLIC_CHANNEL, path=None)
chans.append(chan)
chans_names.append(PUBLIC_CHANNEL)
elif role == "users":
if ENABLE_USERS_CHANNEL 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 ils(self, node, sorting_times=None, force_topology_change=True):
""" A constrained and approximation of ILS using nearest-neighbour interchange Process -----... |
# node = '2', par = '1', gpar = '0' -- in above diagram
n_2 = node
n_1 = n_2.parent_node
if n_1 == self.tree._tree.seed_node:
logger.warn('Node 1 is the root - calling again on child')
self.ils(n_2.child_nodes())
n_0 = n_1.parent_node
a, b = node.... |
<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_inner_edges(self):
""" Returns a list of the internal edges of the tree. """ |
inner_edges = [e for e in self._tree.preorder_edge_iter() if e.is_internal()
and e.head_node and e.tail_node]
return inner_edges |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def intersection(self, other):
""" Returns the intersection of the taxon sets of two Trees """ |
taxa1 = self.labels
taxa2 = other.labels
return taxa1 & taxa2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def postorder(self, skip_seed=False):
""" Return a generator that yields the nodes of the tree in postorder. If skip_seed=True then the root node is not included... |
for node in self._tree.postorder_node_iter():
if skip_seed and node is self._tree.seed_node:
continue
yield node |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preorder(self, skip_seed=False):
""" Return a generator that yields the nodes of the tree in preorder. If skip_seed=True then the root node is not included. ... |
for node in self._tree.preorder_node_iter():
if skip_seed and node is self._tree.seed_node:
continue
yield node |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prune_to_subset(self, subset, inplace=False):
""" Prunes the Tree to just the taxon set given in `subset` """ |
if not subset.issubset(self.labels):
print('"subset" is not a subset')
return
if not inplace:
t = self.copy()
else:
t = self
t._tree.retain_taxa_with_labels(subset)
t._tree.encode_bipartitions()
t._dirty = True
retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def randomise_branch_lengths( self, i=(1, 1), l=(1, 1), distribution_func=random.gammavariate, inplace=False, ):
""" Replaces branch lengths with values drawn fr... |
if not inplace:
t = self.copy()
else:
t = self
for n in t._tree.preorder_node_iter():
if n.is_internal():
n.edge.length = max(0, distribution_func(*i))
else:
n.edge.length = max(0, distribution_func(*l))
t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def randomise_labels( self, inplace=False, ):
""" Shuffles the leaf labels, but doesn't alter the tree structure """ |
if not inplace:
t = self.copy()
else:
t = self
names = list(t.labels)
random.shuffle(names)
for l in t._tree.leaf_node_iter():
l.taxon._label = names.pop()
t._dirty = True
return t |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reversible_deroot(self):
""" Stores info required to restore rootedness to derooted Tree. Returns the edge that was originally rooted, the length of e1, and ... |
root_edge = self._tree.seed_node.edge
lengths = dict([(edge, edge.length) for edge
in self._tree.seed_node.incident_edges() if edge is not root_edge])
self._tree.deroot()
reroot_edge = (set(self._tree.seed_node.incident_edges())
& set(lengt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rlgt(self, time=None, times=1, disallow_sibling_lgts=False):
""" Uses class LGT to perform random lateral gene transfer on ultrametric tree """ |
lgt = LGT(self.copy())
for _ in range(times):
lgt.rlgt(time, disallow_sibling_lgts)
return lgt.tree |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scale(self, factor, inplace=True):
""" Multiplies all branch lengths by factor. """ |
if not inplace:
t = self.copy()
else:
t = self
t._tree.scale_edges(factor)
t._dirty = True
return t |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def strip(self, inplace=False):
""" Sets all edge lengths to None """ |
if not inplace:
t = self.copy()
else:
t = self
for e in t._tree.preorder_edge_iter():
e.length = None
t._dirty = True
return t |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _name_things(self):
""" Easy names for debugging """ |
edges = {}
nodes = {None: 'root'}
for n in self._tree.postorder_node_iter():
nodes[n] = '.'.join([str(x.taxon) for x in n.leaf_nodes()])
for e in self._tree.preorder_edge_iter():
edges[e] = ' ---> '.join([nodes[e.tail_node], nodes[e.head_node]])
r_edges ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit(self, ini_betas=None, tol=1.0e-6, max_iter=200, solve='iwls'):
""" Method that fits a model with a particular estimation routine. Parameters ini_betas : ... |
self.fit_params['ini_betas'] = ini_betas
self.fit_params['tol'] = tol
self.fit_params['max_iter'] = max_iter
self.fit_params['solve'] = solve
if solve.lower() == 'iwls':
params, predy, w, n_iter = iwls(
self.y, self.X, self.family, self.offset, self.y... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inverse(self, z):
""" Inverse of the logit transform Parameters z : array-like The value of the logit transform at `p` Returns ------- p : array Probabilitie... |
z = np.asarray(z)
t = np.exp(-z)
return 1. / (1. + t) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inverse(self, z):
""" Inverse of the power transform link function Parameters `z` : array-like Value of the transformed mean parameters at `p` Returns ------... |
p = np.power(z, 1. / self.power)
return p |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deriv(self, p):
""" Derivative of the power transform Parameters p : array-like Mean parameters Returns -------- g'(p) : array Derivative of power transform ... |
return self.power * np.power(p, self.power - 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 deriv2(self, p):
""" Second derivative of the power transform Parameters p : array-like Mean parameters Returns -------- g''(p) : array Second derivative of ... |
return self.power * (self.power - 1) * np.power(p, self.power - 2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inverse_deriv(self, z):
""" Derivative of the inverse of the power transform Parameters z : array-like `z` is usually the linear predictor for a GLM or GEE m... |
return np.power(z, (1 - self.power)/self.power) / self.power |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deriv(self, p):
""" Derivative of CDF link Parameters p : array-like mean parameters Returns ------- g'(p) : array The derivative of CDF transform at `p` Not... |
p = self._clean(p)
return 1. / self.dbn.pdf(self.dbn.ppf(p)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deriv2(self, p):
""" Second derivative of the Cauchy link function. Parameters p: array-like Probabilities Returns ------- g''(p) : array Value of the second... |
a = np.pi * (p - 0.5)
d2 = 2 * np.pi**2 * np.sin(a) / np.cos(a)**3
return d2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deriv(self, p):
""" Derivative of C-Log-Log transform link function Parameters p : array-like Mean parameters Returns ------- g'(p) : array The derivative of... |
p = self._clean(p)
return 1. / ((p - 1) * (np.log(1 - p))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deriv2(self, p):
""" Second derivative of the C-Log-Log ink function Parameters p : array-like Mean parameters Returns ------- g''(p) : array The second deri... |
p = self._clean(p)
fl = np.log(1 - p)
d2 = -1 / ((1 - p)**2 * fl)
d2 *= 1 + 1 / fl
return d2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def deriv2(self,p):
'''
Second derivative of the negative binomial link function.
Parameters
----------
p : array-like
Mean parameters
Returns
-------
g''(p) : array
The second derivative of the negative binomial transform link
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def inverse_deriv(self, z):
'''
Derivative of the inverse of the negative binomial transform
Parameters
-----------
z : array-like
Usually the linear predictor for a GLM or GEE model
Returns
-------
g^(-1)'(z) : array
The value of... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def einfo(self, db=None):
"""query the einfo endpoint :param db: string (optional) :rtype: EInfo or EInfoDB object If db is None, the reply is a list of database... |
if db is None:
return EInfoResult(self._qs.einfo()).dblist
return EInfoResult(self._qs.einfo({'db': db, 'version': '2.0'})).dbinfo |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def esearch(self, db, term):
"""query the esearch endpoint """ |
esr = ESearchResult(self._qs.esearch({'db': db, 'term': term}))
if esr.count > esr.retmax:
logger.warning("NCBI found {esr.count} results, but we truncated the reply at {esr.retmax}"
" results; see https://github.com/biocommons/eutils/issues/124/".format(esr=esr))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def efetch(self, db, id):
"""query the efetch endpoint """ |
db = db.lower()
xml = self._qs.efetch({'db': db, 'id': str(id)})
doc = le.XML(xml)
if db in ['gene']:
return EntrezgeneSet(doc)
if db in ['nuccore', 'nucest', 'protein']:
# TODO: GBSet is misnamed; it should be GBSeq and get the GBSeq XML node as root (se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw(self, surfaceObj):
"""Blit the current button's appearance to the surface object.""" |
if self._visible:
if self.buttonDown:
surfaceObj.blit(self.surfaceDown, self._rect)
elif self.mouseOverButton:
surfaceObj.blit(self.surfaceHighlight, self._rect)
else:
surfaceObj.blit(self.surfaceNormal, self._rect) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _setlink(self, link):
""" Helper method to set the link for a family. Raises a ValueError exception if the link is not available. Note that the error message... |
# TODO: change the links class attribute in the families to hold
# meaningful information instead of a list of links instances such as
# [<statsmodels.family.links.Log object at 0x9a4240c>,
# <statsmodels.family.links.Power object at 0x9a423ec>,
# <statsmodels.family.links.Pow... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def weights(self, mu):
r""" Weights for IRLS steps Parameters mu : array-like The transformed mean response variable in the exponential family Returns ------- w ... |
return 1. / (self.link.deriv(mu)**2 * self.variance(mu)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resid_dev(self, endog, mu, scale=1.):
""" Gaussian deviance residuals Parameters endog : array-like Endogenous response variable mu : array-like Fitted mean ... |
return (endog - mu) / np.sqrt(self.variance(mu)) / scale |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deviance(self, endog, mu, freq_weights=1., scale=1.):
""" Gaussian deviance function Parameters endog : array-like Endogenous response variable mu : array-li... |
return np.sum((freq_weights * (endog - mu)**2)) / scale |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loglike(self, endog, mu, freq_weights=1., scale=1.):
""" The log-likelihood in terms of the fitted mean response. Parameters endog : array-like Endogenous re... |
if isinstance(self.link, L.Power) and self.link.power == 1:
# This is just the loglikelihood for classical OLS
nobs2 = endog.shape[0] / 2.
SSR = np.sum((endog-self.fitted(mu))**2, axis=0)
llf = -np.log(SSR) * nobs2
llf -= (1+np.log(np.pi/nobs2))*nobs2... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deviance(self, endog, mu, freq_weights=1., scale=1.):
r""" Gamma deviance function Parameters endog : array-like Endogenous response variable mu : array-like... |
endog_mu = self._clean(endog/mu)
return 2*np.sum(freq_weights*((endog-mu)/mu-np.log(endog_mu))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resid_dev(self, endog, mu, scale=1.):
r""" Gamma deviance residuals Parameters endog : array-like Endogenous response variable mu : array-like Fitted mean re... |
endog_mu = self._clean(endog / mu)
return np.sign(endog - mu) * np.sqrt(-2 * (-(endog - mu)/mu +
np.log(endog_mu))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def initialize(self, endog, freq_weights):
'''
Initialize the response variable.
Parameters
----------
endog : array
Endogenous response variable
Returns
--------
If `endog` is binary, returns `endog`
If `endog` is a 2d array, then t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def deviance(self, endog, mu, freq_weights=1, scale=1., axis=None):
r'''
Deviance function for either Bernoulli or Binomial data.
Parameters
----------
endog : array-like
Endogenous response variable (already transformed to a probability
if appropriate).
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resid_dev(self, endog, mu, scale=1.):
r""" Binomial deviance residuals Parameters endog : array-like Endogenous response variable mu : array-like Fitted mean... |
mu = self.link._clean(mu)
if np.shape(self.n) == () and self.n == 1:
one = np.equal(endog, 1)
return np.sign(endog-mu)*np.sqrt(-2 *
np.log(one * mu + (1 - one) *
(1 - mu)))/scale
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def resid_anscombe(self, endog, mu):
'''
The Anscombe residuals
Parameters
----------
endog : array-like
Endogenous response variable
mu : array-like
Fitted mean response variable
Returns
-------
resid_anscombe : array
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_by_uuid(self, uuid):
"""Find an entry by uuid. :raise: EntryNotFoundError """ |
for entry in self.entries:
if entry.uuid == uuid:
return entry
raise EntryNotFoundError("Entry not found for uuid: %s" % uuid) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_by_title(self, title):
"""Find an entry by exact title. :raise: EntryNotFoundError """ |
for entry in self.entries:
if entry.title == title:
return entry
raise EntryNotFoundError("Entry not found for title: %s" % title) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fuzzy_search_by_title(self, title, ignore_groups=None):
"""Find an entry by by fuzzy match. This will check things such as: * case insensitive matching * typ... |
entries = []
# Exact matches trump
for entry in self.entries:
if entry.title == title:
entries.append(entry)
if entries:
return self._filter_entries(entries, ignore_groups)
# Case insensitive matches next.
title_lower = title.lower... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_configuration(self):
"""Parse the haproxy config file Raises: Exception: when there are unsupported section Returns: config.Configuration: haproxy conf... |
configuration = config.Configuration()
pegtree = pegnode.parse(self.filestring)
for section_node in pegtree:
if isinstance(section_node, pegnode.GlobalSection):
configuration.globall = self.build_global(section_node)
elif isinstance(section_node, pegnode.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_global(self, global_node):
"""parse `global` section, and return the config.Global Args: global_node (TreeNode):
`global` section treenode Returns: co... |
config_block_lines = self.__build_config_block(
global_node.config_block)
return config.Global(config_block=config_block_lines) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __build_config_block(self, config_block_node):
"""parse `config_block` in each section Args: config_block_node (TreeNode):
Description Returns: """ |
node_lists = []
for line_node in config_block_node:
if isinstance(line_node, pegnode.ConfigLine):
node_lists.append(self.__build_config(line_node))
elif isinstance(line_node, pegnode.OptionLine):
node_lists.append(self.__build_option(line_node))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_defaults(self, defaults_node):
"""parse `defaults` sections, and return a config.Defaults Args: defaults_node (TreeNode):
Description Returns: config.... |
proxy_name = defaults_node.defaults_header.proxy_name.text
config_block_lines = self.__build_config_block(
defaults_node.config_block)
return config.Defaults(
name=proxy_name,
config_block=config_block_lines) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_userlist(self, userlist_node):
"""parse `userlist` sections, and return a config.Userlist""" |
proxy_name = userlist_node.userlist_header.proxy_name.text
config_block_lines = self.__build_config_block(
userlist_node.config_block)
return config.Userlist(
name=proxy_name,
config_block=config_block_lines) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_listen(self, listen_node):
"""parse `listen` sections, and return a config.Listen Args: listen_node (TreeNode):
Description Returns: config.Listen: an... |
proxy_name = listen_node.listen_header.proxy_name.text
service_address_node = listen_node.listen_header.service_address
# parse the config block
config_block_lines = self.__build_config_block(
listen_node.config_block)
# parse host and port
host, port = '',... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_frontend(self, frontend_node):
"""parse `frontend` sections, and return a config.Frontend Args: frontend_node (TreeNode):
Description Raises: Exceptio... |
proxy_name = frontend_node.frontend_header.proxy_name.text
service_address_node = frontend_node.frontend_header.service_address
# parse the config block
config_block_lines = self.__build_config_block(
frontend_node.config_block)
# parse host and port
host, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_backend(self, backend_node):
"""parse `backend` sections Args: backend_node (TreeNode):
Description Returns: config.Backend: an object """ |
proxy_name = backend_node.backend_header.proxy_name.text
config_block_lines = self.__build_config_block(
backend_node.config_block)
return config.Backend(name=proxy_name, config_block=config_block_lines) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_string(self, template_code):
""" Trying to compile and return the compiled template code. :raises: TemplateSyntaxError if there's a syntax error in the ... |
try:
return self.template_class(self.engine.from_string(template_code))
except mako_exceptions.SyntaxException as exc:
raise TemplateSyntaxError(exc.args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render(self, context=None, request=None):
""" Render the template with a given context. Here we're adding some context variables that are required for all te... |
if context is None:
context = {}
context['static'] = static
context['url'] = self.get_reverse_url()
if request is not None:
# As Django doesn't have a global request object,
# it's useful to put it in the context.
context['request'] = re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conf_int(self, alpha=.05, cols=None, method='default'):
""" Returns the confidence interval of the fitted parameters. Parameters alpha : float, optional The ... |
bse = self.bse
if self.use_t:
dist = stats.t
df_resid = getattr(self, 'df_resid_inference', self.df_resid)
q = dist.ppf(1 - alpha / 2, df_resid)
else:
dist = stats.norm
q = dist.ppf(1 - alpha / 2)
if cols is 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 MD5Hash(password):
"""
Returns md5 hash of a string.
@param password (string) - String to be hashed.
@return (string) - Md5 hash of password.
""" |
md5_password = md5.new(password)
password_md5 = md5_password.hexdigest()
return password_md5 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setVerbosity(self, verbose):
"""
Set verbosity of the SenseApi object.
@param verbose (boolean) - True of False
@return (boolean) - Boolean indicatin... |
if not (verbose == True or verbose == False):
return False
else:
self.__verbose__ = verbose
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 setServer(self, server):
"""
Set server to interact with.
@param server (string) - 'live' for live server, 'dev' for test server, 'rc' for release candi... |
if server == 'live':
self.__server__ = server
self.__server_url__ = 'api.sense-os.nl'
self.setUseHTTPS()
return True
elif server == 'dev':
self.__server__ = server
self.__server_url__ = 'api.dev.sense-os.nl'
# ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getAllSensors(self):
"""
Retrieve all the user's own sensors by iterating over the SensorsGet function
@return (list) - Array of sensors
""" |
j = 0
sensors = []
parameters = {'page':0, 'per_page':1000, 'owned':1}
while True:
parameters['page'] = j
if self.SensorsGet(parameters):
s = json.loads(self.getResponse())['sensors']
sensors.extend(s)
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 findSensor(self, sensors, sensor_name, device_type = None):
"""
Find a sensor in the provided list of sensors
@param sensors (list) - List of sensors to... |
if device_type == None:
for sensor in sensors:
if sensor['name'] == sensor_name:
return sensor['id']
else:
for sensor in sensors:
if sensor['name'] == sensor_name and sensor['device_type'] == device_type:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def AuthenticateSessionId(self, username, password):
"""
Authenticate using a username and password.
The SenseApi object will store the obtained session_id i... |
self.__setAuthenticationMethod__('authenticating_session_id')
parameters = {'username':username, 'password':password}
if self.__SenseApiCall__("/login.json", "POST", parameters = parameters):
try:
response = json.loads(self.__response__)
except:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def LogoutSessionId(self):
"""
Logout the current session_id from CommonSense
@return (bool) - Boolean indicating whether LogoutSessionId was successful
""... |
if self.__SenseApiCall__('/logout.json', 'POST'):
self.__setAuthenticationMethod__('not_authenticated')
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def AuthenticateOauth (self, oauth_token_key, oauth_token_secret, oauth_consumer_key, oauth_consumer_secret):
"""
Authenticate using Oauth
@param oauth_toke... |
self.__oauth_consumer__ = oauth.OAuthConsumer(str(oauth_consumer_key), str(oauth_consumer_secret))
self.__oauth_token__ = oauth.OAuthToken(str(oauth_token_key), str(oauth_token_secret))
self.__authentication__ = 'oauth'
if self.__SenseApiCall__('/users/current.json', 'GET'):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def SensorsDelete(self, sensor_id):
"""
Delete a sensor from CommonSense.
@param sensor_id (int) - Sensor id of sensor to delete from CommonSense.
@retur... |
if self.__SenseApiCall__('/sensors/{0}.json'.format(sensor_id), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def SensorsMetatagsGet(self, parameters, namespace = None):
"""
Retrieve sensors with their metatags.
@param namespace (string) - Namespace for which to ret... |
ns = "default" if namespace is None else namespace
parameters['namespace'] = ns
if self.__SenseApiCall__('/sensors/metatags.json', 'GET', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GroupSensorsMetatagsGet(self, group_id, parameters, namespace = None):
"""
Retrieve sensors in a group with their metatags.
@param group_id (int) - Grou... |
ns = "default" if namespace is None else namespace
parameters['namespace'] = ns
if self.__SenseApiCall__('/groups/{0}/sensors/metatags.json'.format(group_id), 'GET', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def SensorMetatagsGet(self, sensor_id, namespace = None):
"""
Retrieve the metatags of a sensor.
@param sensor_id (int) - Id of the sensor to retrieve metat... |
ns = "default" if namespace is None else namespace
if self.__SenseApiCall__('/sensors/{0}/metatags.json'.format(sensor_id), 'GET', parameters = {'namespace': ns}):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def SensorMetatagsPost(self, sensor_id, metatags, namespace = None):
"""
Attach metatags to a sensor for a specific namespace
@param sensor_id (int) - Id of... |
ns = "default" if namespace is None else namespace
if self.__SenseApiCall__("/sensors/{0}/metatags.json?namespace={1}".format(sensor_id, ns), "POST", parameters = metatags):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GroupSensorsFind(self, group_id, parameters, filters, namespace = None):
"""
Find sensors in a group based on a number of filters on metatags
@param gro... |
ns = "default" if namespace is None else namespace
parameters['namespace'] = ns
if self.__SenseApiCall__("/groups/{0}/sensors/find.json?{1}".format(group_id, urllib.urlencode(parameters, True)), "POST", parameters = filters):
return True
else:
self.__error_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def MetatagDistinctValuesGet(self, metatag_name, namespace = None):
"""
Find the distinct value of a metatag name in a certain namespace
@param metatag_name... |
ns = "default" if namespace is None else namespace
if self.__SenseApiCall__("/metatag_name/{0}/distinct_values.json", "GET", parameters = {'namespace': ns}):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def SensorDataDelete(self, sensor_id, data_id):
"""
Delete a sensor datum from a specific sensor in CommonSense.
@param sensor_id (int) - Sensor id of the s... |
if self.__SenseApiCall__('/sensors/{0}/data/{1}.json'.format(sensor_id, data_id), 'DELETE'):
return True
else:
self.__error_ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def SensorsDataPost(self, parameters):
"""
Post sensor data to multiple sensors in CommonSense simultaneously.
@param parameters (dictionary) - Data to post... |
if self.__SenseApiCall__('/sensors/data.json', 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ServicesDelete (self, sensor_id, service_id):
"""
Delete a service from CommonSense.
@param sensor_id (int) - Sensor id of the sensor the service is con... |
if self.__SenseApiCall__('/sensors/{0}/services/{1}.json'.format(sensor_id, service_id), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ServicesSetUseDataTimestamp(self, sensor_id, service_id, parameters):
"""
Indicate whether a math service should use the original timestamps of the incomin... |
if self.__SenseApiCall__('/sensors/{0}/services/{1}/SetUseDataTimestamp.json'.format(sensor_id, service_id), 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def CreateUser (self, parameters):
"""
Create a user
This method creates a user and returns the user object and session
@param parameters (dictionary) - Pa... |
print "Creating user"
print parameters
if self.__SenseApiCall__('/users.json', 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def UsersUpdate (self, user_id, parameters):
"""
Update the current user.
@param user_id (int) - id of the user to be updated
@param parameters (dictionary... |
if self.__SenseApiCall__('/users/{0}.json'.format(user_id), 'PUT', parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def UsersChangePassword (self, current_password, new_password):
"""
Change the password for the current user
@param current_password (string) - md5 hash of ... |
if self.__SenseApiCall__('/change_password', "POST", {"current_password":current_password, "new_password":new_password}):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def UsersDelete (self, user_id):
"""
Delete user.
@return (bool) - Boolean indicating whether UsersDelete was successful.
""" |
if self.__SenseApiCall__('/users/{user_id}.json'.format(user_id = user_id), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def EventsNotificationsDelete(self, event_notification_id):
"""
Delete an event-notification from CommonSense.
@param event_notification_id (int) - Id of th... |
if self.__SenseApiCall__('/events/notifications/{0}.json'.format(event_notification_id), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def TriggersDelete(self, trigger_id):
"""
Delete a trigger from CommonSense.
@param trigger_id (int) - Trigger id of the trigger to delete.
@return (bool... |
if self.__SenseApiCall__('/triggers/{0}'.format(trigger_id), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def SensorsTriggersNotificationsDelete(self, sensor_id, trigger_id, notification_id):
"""
Disconnect a notification from a sensor-trigger combination.
@para... |
if self.__SenseApiCall__('/sensors/{0}/triggers/{1}/notifications/{2}.json'.format(sensor_id, trigger_id, notification_id), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def SensorsTriggersNotificationsPost(self, sensor_id, trigger_id, parameters):
"""
Connect a notification to a sensor-trigger combination.
@param sensor_id ... |
if self.__SenseApiCall__('/sensors/{0}/triggers/{1}/notifications.json'.format(sensor_id, trigger_id), 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def NotificationsDelete(self, notification_id):
"""
Delete a notification from CommonSense.
@param notification_id (int) - Notification id of the notificati... |
if self.__SenseApiCall__('/notifications/{0}.json'.format(notification_id), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def DeviceGet(self, device_id):
"""
Obtain details of a single device
@param device_id (int) - Device for which to obtain details
""" |
if self.__SenseApiCall__('/devices/{0}'.format(device_id), 'GET'):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def DeviceSensorsGet(self, device_id, parameters):
"""
Obtain a list of all sensors attached to a device.
@param device_id (int) - Device for which to retri... |
if self.__SenseApiCall__('/devices/{0}/sensors.json'.format(device_id), 'GET', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GroupsDelete(self, group_id):
"""
Delete a group from CommonSense.
@param group_id (int) - group id of group to delete from CommonSense.
@return (boo... |
if self.__SenseApiCall__('/groups/{0}.json'.format(group_id), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GroupsUsersPost(self, parameters, group_id):
"""
Add users to a group in CommonSense.
@param parameters (dictonary) - Dictionary containing the users to... |
if self.__SenseApiCall__('/groups/{group_id}/users.json'.format(group_id = group_id), 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.