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 from_samples_bqm(cls, samples_like, bqm, **kwargs):
"""Build a SampleSet from raw samples using a BinaryQuadraticModel to get energies and vartype. Args: sam... |
# more performant to do this once, here rather than again in bqm.energies
# and in cls.from_samples
samples_like = as_samples(samples_like)
energies = bqm.energies(samples_like)
return cls.from_samples(samples_like, energy=energies, vartype=bqm.vartype, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data_vectors(self):
"""The per-sample data in a vector. Returns: dict: A dict where the keys are the fields in the record and the values are the correspondin... |
return {field: self.record[field] for field in self.record.dtype.names
if field != 'sample'} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def first(self):
"""Sample with the lowest-energy. Raises: ValueError: If empty. Example: Sample(sample={'a': -1, 'b': 1}, energy=-2.0, num_occurrences=1) """ |
try:
return next(self.data(sorted_by='energy', name='Sample'))
except StopIteration:
raise ValueError('{} is empty'.format(self.__class__.__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 done(self):
"""Return True if a pending computation is done. Used when a :class:`SampleSet` is constructed with :meth:`SampleSet.from_future`. Examples: This... |
return (not hasattr(self, '_future')) or (not hasattr(self._future, 'done')) or self._future.done() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def samples(self, n=None, sorted_by='energy'):
"""Return an iterable over the samples. Args: n (int, optional, default=None):
Maximum number of samples to retur... |
if n is not None:
return self.samples(sorted_by=sorted_by)[:n]
if sorted_by is None:
samples = self.record.sample
else:
order = np.argsort(self.record[sorted_by])
samples = self.record.sample[order]
return SamplesArray(samples, self.vari... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(self):
"""Create a shallow copy.""" |
return self.__class__(self.record.copy(),
self.variables, # a new one is made in all cases
self.info.copy(),
self.vartype) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def aggregate(self):
"""Create a new SampleSet with repeated samples aggregated. Returns: :obj:`.SampleSet` Note: :attr:`.SampleSet.record.num_occurrences` are a... |
_, indices, inverse = np.unique(self.record.sample, axis=0,
return_index=True, return_inverse=True)
# unique also sorts the array which we don't want, so we undo the sort
order = np.argsort(indices)
indices = indices[order]
record = 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 append_variables(self, samples_like, sort_labels=True):
"""Create a new sampleset with the given variables with values added. Not defined for empty sample se... |
samples, labels = as_samples(samples_like)
num_samples = len(self)
# we don't handle multiple values
if samples.shape[0] == num_samples:
# we don't need to do anything, it's already the correct shape
pass
elif samples.shape[0] == 1 and num_samples:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lowest(self, rtol=1.e-5, atol=1.e-8):
"""Return a sample set containing the lowest-energy samples. A sample is included if its energy is within tolerance of ... |
if len(self) == 0:
# empty so all are lowest
return self.copy()
record = self.record
# want all the rows within tolerance of the minimal energy
close = np.isclose(record.energy,
np.min(record.energy),
rtol=... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def slice(self, *slice_args, **kwargs):
"""Create a new SampleSet with rows sliced according to standard Python slicing syntax. Args: start (int, optional, defau... |
# handle `sorted_by` kwarg with a default value in a python2-compatible way
sorted_by = kwargs.pop('sorted_by', 'energy')
if kwargs:
# be strict about allowed kwargs: throw the same error as python3 would
raise TypeError('slice got an unexpected '
... |
<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_pandas_dataframe(self, sample_column=False):
"""Convert a SampleSet to a Pandas DataFrame Returns: :obj:`pandas.DataFrame` Examples: a b c energy num_occu... |
import pandas as pd
if sample_column:
df = pd.DataFrame(self.data(sorted_by=None, sample_dict_cast=True))
else:
# work directly with the record, it's much faster
df = pd.DataFrame(self.record.sample, columns=self.variables)
for field in sorted(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def penalty_satisfaction(response, bqm):
""" Creates a penalty satisfaction list Given a sampleSet and a bqm object, will create a binary list informing whether ... |
record = response.record
label_dict = response.variables.index
if len(bqm.info['reduction']) == 0:
return np.array([1] * len(record.sample))
penalty_vector = np.prod([record.sample[:, label_dict[qi]] *
record.sample[:, label_dict[qj]]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def polymorph_response(response, poly, bqm, penalty_strength=None, keep_penalty_variables=True, discard_unsatisfied=False):
""" Transforms the sampleset for the ... |
record = response.record
penalty_vector = penalty_satisfaction(response, bqm)
original_variables = bqm.variables
if discard_unsatisfied:
samples_to_keep = list(map(bool, list(penalty_vector)))
penalty_vector = np.array([True] * np.sum(samples_to_keep))
else:
samples_to_keep... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sample_poly(self, poly, penalty_strength=1.0, keep_penalty_variables=False, discard_unsatisfied=False, **parameters):
"""Sample from the given binary polynom... |
bqm = make_quadratic(poly, penalty_strength, vartype=poly.vartype)
response = self.child.sample(bqm, **parameters)
return polymorph_response(response, poly, bqm,
penalty_strength=penalty_strength,
keep_penalty_variables=keep_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sample_poly(self, poly, scalar=None, bias_range=1, poly_range=None, ignored_terms=None, **parameters):
"""Scale and sample from the given binary polynomial. ... |
if ignored_terms is None:
ignored_terms = set()
else:
ignored_terms = {frozenset(term) for term in ignored_terms}
# scale and normalize happen in-place so we need to make a copy
original, poly = poly, poly.copy()
if scalar is not None:
poly... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sample_poly(self, poly, **kwargs):
"""Sample from the binary polynomial and truncate output. Args: poly (obj:`.BinaryPolynomial`):
A binary polynomial. **kw... |
tkw = self._truncate_kwargs
if self._aggregate:
return self.child.sample_poly(poly, **kwargs).aggregate().truncate(**tkw)
else:
return self.child.sample_poly(poly, **kwargs).truncate(**tkw) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _samples_dicts_to_array(samples_dicts, labels):
"""Convert an iterable of samples where each sample is a dict to a numpy 2d array. Also determines the labels... |
itersamples = iter(samples_dicts)
first_sample = next(itersamples)
if labels is None:
labels = list(first_sample)
num_variables = len(labels)
def _iter_samples():
yield np.fromiter((first_sample[v] for v in labels),
count=num_variables, dtype=np.int8)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data_struct_array(sample, **vectors):
# data_struct_array(sample, *, energy, **vectors):
"""Combine samples and per-sample data into a numpy structured arra... |
if not len(sample):
# if samples are empty
sample = np.zeros((0, 0), dtype=np.int8)
else:
sample = np.asarray(sample, dtype=np.int8)
if sample.ndim < 2:
sample = np.expand_dims(sample, 0)
num_samples, num_variables = sample.shape
if 'num_occurrences' not 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 from_samples(cls, samples_like, vectors, info, vartype, variable_labels=None):
"""Build a response from samples. Args: samples_like: A collection of samples.... |
# there is no np.is_array_like so we use a try-except block
try:
# trying to cast it to int8 rules out list of dictionaries. If we didn't try to cast
# then it would just create a vector of np.object
samples = np.asarray(samples_like, dtype=np.int8)
except 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 breathe_identifier(self):
""" The unique identifier for breathe directives. .. note:: This method is currently assumed to only be called for nodes that are i... |
if self.kind == "function":
# TODO: breathe bug with templates and overloads, don't know what to do...
return "{name}({parameters})".format(
name=self.name,
parameters=", ".join(self.parameters)
)
return self.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 full_signature(self):
""" The full signature of a ``"function"`` node. **Return** :class:`python:str` The full signature of the function, including template,... |
if self.kind == "function":
return "{template}{return_type} {name}({parameters})".format(
template="template <{0}> ".format(", ".join(self.template)) if self.template else "",
return_type=self.return_type,
name=self.name,
parameters=",... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def findNestedNamespaces(self, lst):
'''
Recursive helper function for finding nested namespaces. If this node is a
namespace node, it is appended to ``lst``. Each node also calls each of its
child ``findNestedNamespaces`` with the same list.
:Parameters:
``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 findNestedDirectories(self, lst):
'''
Recursive helper function for finding nested directories. If this node is a
directory node, it is appended to ``lst``. Each node also calls each of its
child ``findNestedDirectories`` with the same list.
:Parameters:
``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 findNestedClassLike(self, lst):
'''
Recursive helper function for finding nested classes and structs. If this node
is a class or struct, it is appended to ``lst``. Each node also calls each of
its child ``findNestedClassLike`` with the same list.
:Parameters:
`... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def generateDirectoryNodeDocuments(self):
'''
Generates all of the directory reStructuredText documents.
'''
all_dirs = []
for d in self.dirs:
d.findNestedDirectories(all_dirs)
for d in all_dirs:
self.generateDirectoryNodeRST(d) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def gerrymanderNodeFilenames(self):
'''
When creating nodes, the filename needs to be relative to ``conf.py``, so it
will include ``self.root_directory``. However, when generating the API, the
file we are writing to is in the same directory as the generated node files so
we need... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def generateClassView(self):
'''
Generates the class view hierarchy, writing it to ``self.class_hierarchy_file``.
'''
class_view_stream = StringIO()
for n in self.namespaces:
n.toHierarchy(True, 0, class_view_stream)
# Add everything that was not nested in a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def generateDirectoryView(self):
'''
Generates the file view hierarchy, writing it to ``self.file_hierarchy_file``.
'''
file_view_stream = StringIO()
for d in self.dirs:
d.toHierarchy(False, 0, file_view_stream)
# add potential missing files (not sure if thi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def toConsole(self):
'''
Convenience function for printing out the entire API being generated to the
console. Unused in the release, but is helpful for debugging ;)
'''
fmt_spec = {
"class": utils.AnsiColors.BOLD_MAGENTA,
"struct": utils.AnsiColors... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sanitize(name):
""" Sanitize the specified ``name`` for use with breathe directives. **Parameters** ``name`` (:class:`python:str`) The name to be sanitized. ... |
return name.replace(
"<", "<"
).replace(
">", ">"
).replace(
"&", "&"
).replace(
"< ", "<"
).replace(
" >", ">"
).replace(
" &", "&"
).replace(
"& ", "&"
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def doxygenLanguageToPygmentsLexer(location, language):
'''
Given an input location and language specification, acquire the Pygments lexer to
use for this file.
1. If :data:`configs.lexerMapping <exhale.configs.lexerMapping>` has been specified,
then :data:`configs._compiled_lexer_mapping <exhal... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def getBriefAndDetailedRST(textRoot, node):
'''
Given an input ``node``, return a tuple of strings where the first element of
the return is the ``brief`` description and the second is the ``detailed``
description.
.. todo:: actually document this
'''
node_xml_contents = utils.nodeCompoundXM... |
<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_url(self, endpoint):
""" Builds the absolute URL using the target and desired endpoint. """ |
try:
path = self.endpoints[endpoint]
except KeyError:
msg = 'Unknown endpoint `{0}`'
raise ValueError(msg.format(endpoint))
absolute_url = urljoin(self.target, path)
return absolute_url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_version(self, project, version, egg):
""" Adds a new project egg to the Scrapyd service. First class, maps to Scrapyd's add version endpoint. """ |
url = self._build_url(constants.ADD_VERSION_ENDPOINT)
data = {
'project': project,
'version': version
}
files = {
'egg': egg
}
json = self.client.post(url, data=data, files=files,
timeout=self.timeout)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cancel(self, project, job, signal=None):
""" Cancels a job from a specific project. First class, maps to Scrapyd's cancel job endpoint. """ |
url = self._build_url(constants.CANCEL_ENDPOINT)
data = {
'project': project,
'job': job,
}
if signal is not None:
data['signal'] = signal
json = self.client.post(url, data=data, timeout=self.timeout)
return json['prevstate'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_project(self, project):
""" Deletes all versions of a project. First class, maps to Scrapyd's delete project endpoint. """ |
url = self._build_url(constants.DELETE_PROJECT_ENDPOINT)
data = {
'project': project,
}
self.client.post(url, data=data, timeout=self.timeout)
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 delete_version(self, project, version):
""" Deletes a specific version of a project. First class, maps to Scrapyd's delete version endpoint. """ |
url = self._build_url(constants.DELETE_VERSION_ENDPOINT)
data = {
'project': project,
'version': version
}
self.client.post(url, data=data, timeout=self.timeout)
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 job_status(self, project, job_id):
""" Retrieves the 'status' of a specific job specified by its id. Derived, utilises Scrapyd's list jobs endpoint to provid... |
all_jobs = self.list_jobs(project)
for state in constants.JOB_STATES:
job_ids = [job['id'] for job in all_jobs[state]]
if job_id in job_ids:
return state
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 list_jobs(self, project):
""" Lists all known jobs for a project. First class, maps to Scrapyd's list jobs endpoint. """ |
url = self._build_url(constants.LIST_JOBS_ENDPOINT)
params = {'project': project}
jobs = self.client.get(url, params=params, timeout=self.timeout)
return jobs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_projects(self):
""" Lists all deployed projects. First class, maps to Scrapyd's list projects endpoint. """ |
url = self._build_url(constants.LIST_PROJECTS_ENDPOINT)
json = self.client.get(url, timeout=self.timeout)
return json['projects'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_spiders(self, project):
""" Lists all known spiders for a specific project. First class, maps to Scrapyd's list spiders endpoint. """ |
url = self._build_url(constants.LIST_SPIDERS_ENDPOINT)
params = {'project': project}
json = self.client.get(url, params=params, timeout=self.timeout)
return json['spiders'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_versions(self, project):
""" Lists all deployed versions of a specific project. First class, maps to Scrapyd's list versions endpoint. """ |
url = self._build_url(constants.LIST_VERSIONS_ENDPOINT)
params = {'project': project}
json = self.client.get(url, params=params, timeout=self.timeout)
return json['versions'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schedule(self, project, spider, settings=None, **kwargs):
""" Schedules a spider from a specific project to run. First class, maps to Scrapyd's scheduling en... |
url = self._build_url(constants.SCHEDULE_ENDPOINT)
data = {
'project': project,
'spider': spider
}
data.update(kwargs)
if settings:
setting_params = []
for setting_name, value in iteritems(settings):
setting_params... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_response(self, response):
""" Handles the response received from Scrapyd. """ |
if not response.ok:
raise ScrapydResponseError(
"Scrapyd returned a {0} error: {1}".format(
response.status_code,
response.text))
try:
json = response.json()
except ValueError:
raise ScrapydResponseErro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self):
r"""Returns all content in this node, regardless of whitespace or not. This includes all LaTeX needed to reconstruct the original source. ['\n', \... |
for child in self.expr.all:
if isinstance(child, TexExpr):
node = TexNode(child)
node.parent = self
yield node
else:
yield child |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def children(self):
r"""Immediate children of this TeX element that are valid TeX objects. This is equivalent to contents, excluding text elements and keeping on... |
for child in self.expr.children:
node = TexNode(child)
node.parent = self
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 string(self):
r"""This is valid if and only if 1. the expression is a :class:`.TexCmd` AND 2. the command has only one argument. :rtype: Union[None,str] 'Hel... |
if isinstance(self.expr, TexCmd) and len(self.expr.args) == 1:
return self.expr.args[0].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 text(self):
r"""All text in descendant nodes. This is equivalent to contents, keeping text elements and excluding Tex expressions. 'Nested\n ' """ |
for descendant in self.contents:
if isinstance(descendant, TokenWithPosition):
yield descendant
elif hasattr(descendant, 'text'):
yield from descendant.text |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count(self, name=None, **attrs):
r"""Number of descendants matching criteria. :param Union[None,str] name: name of LaTeX expression :param attrs: LaTeX expre... |
return len(list(self.find_all(name, **attrs))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
r"""Delete this node from the parse tree. Where applicable, this will remove all descendants of this node from the parse tree. \textit{}\textit... |
# TODO: needs better abstraction for supports contents
parent = self.parent
if parent.expr._supports_contents():
parent.remove(self)
return
# TODO: needs abstraction for removing from arg
for arg in parent.args:
if self.expr in arg.contents:... |
<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(self, name=None, **attrs):
r"""First descendant node matching criteria. Returns None if no descendant node found. :return: descendant node matching crit... |
try:
return next(self.find_all(name, **attrs))
except StopIteration:
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 find_all(self, name=None, **attrs):
r"""Return all descendant nodes matching criteria. :param Union[None,str] name: name of LaTeX expression :param attrs: La... |
for descendant in self.__descendants():
if hasattr(descendant, '__match__') and \
descendant.__match__(name, attrs):
yield descendant |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self):
r"""Returns all content in this expression, regardless of whitespace or not. This includes all LaTeX needed to reconstruct the original source. Tr... |
for arg in self.args:
for expr in arg:
yield expr
for content in self._contents:
yield content |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def contents(self):
r"""Returns all contents in this expression. Optionally includes whitespace if set when node was created. ['hi'] ['\n', 'hi'] """ |
for content in self.all:
is_whitespace = isinstance(content, str) and content.isspace()
if not is_whitespace or self.preserve_whitespace:
yield content |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tokens(self):
"""Further breaks down all tokens for a particular expression into words and other expressions. ['var x = 10'] """ |
for content in self.contents:
if isinstance(content, TokenWithPosition):
for word in content.split():
yield word
else:
yield content |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def insert(self, i, *exprs):
"""Insert content at specified position into expression. :param int i: Position to add content to :param Union[TexExpr,str] exprs: L... |
self._assert_supports_contents()
for j, expr in enumerate(exprs):
self._contents.insert(i + j, expr) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(self, expr):
"""Remove a provided expression from its list of contents. :param Union[TexExpr,str] expr: Content to add :return: index of the expressio... |
self._assert_supports_contents()
index = self._contents.index(expr)
self._contents.remove(expr)
return index |
<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(s):
"""Parse a string or list and return an Argument object :param Union[str,iterable] s: Either a string or a list, where the first and last elements ... |
if isinstance(s, arg_type):
return s
if isinstance(s, (list, tuple)):
for arg in arg_type:
if [s[0], s[-1]] == arg.delims():
return arg(*s[1:-1])
raise TypeError('Malformed argument. First and last elements must '
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def insert(self, i, arg):
r"""Insert whitespace, an unparsed argument string, or an argument object. :param int i: Index to insert argument into :param Arg arg: ... |
arg = self.__coerce(arg)
if isinstance(arg, Arg):
super().insert(i, arg)
if len(self) <= 1:
self.all.append(arg)
else:
if i > len(self):
i = len(self) - 1
before = self[i - 1]
index_before = self.all.index(be... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(self, item):
"""Remove either an unparsed argument string or an argument object. :param Union[str,Arg] item: Item to remove 2 OArg('arg2') """ |
item = self.__coerce(item)
self.all.remove(item)
super().remove(item) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pop(self, i):
"""Pop argument object at provided index. :param int i: Index to pop from the list OArg('arg2') 2 RArg('arg0') """ |
item = super().pop(i)
j = self.all.index(item)
return self.all.pop(j) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def forward(self, j=1):
"""Move forward by j steps. 'abc' 'bc' """ |
if j < 0:
return self.backward(-j)
self.__i += j
return self[self.__i-j: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 read(tex):
"""Read and parse all LaTeX source :param Union[str,iterable] tex: LaTeX source :return TexEnv: the global environment """ |
if isinstance(tex, str):
tex = tex
else:
tex = ''.join(itertools.chain(*tex))
buf, children = Buffer(tokenize(tex)), []
while buf.hasNext():
content = read_tex(buf)
if content is not None:
children.append(content)
return TexEnv('[tex]', children), tex |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve(tex):
"""Resolve all imports and update the parse tree. Reads from a tex file and once finished, writes to a tex file. """ |
# soupify
soup = TexSoup(tex)
# resolve subimports
for subimport in soup.find_all('subimport'):
path = subimport.args[0] + subimport.args[1]
subimport.replace_with(*resolve(open(path)).contents)
# resolve imports
for _import in soup.find_all('import'):
_import.replace... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sollen(tex, command):
r"""Measure solution length :param Union[str,buffer] tex: the LaTeX source as a string or file buffer :param str command: the command d... |
return sum(len(a.string) for a in TexSoup(tex).find_all(command)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count(tex):
"""Extract all labels, then count the number of times each is referenced in the provided file. Does not follow \includes. """ |
# soupify
soup = TexSoup(tex)
# extract all unique labels
labels = set(label.string for label in soup.find_all('label'))
# create dictionary mapping label to number of references
return dict((label, soup.find_all('\ref{%s}' % label)) for label in labels) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def next_token(text):
r"""Returns the next possible token, advancing the iterator to the next position to start processing from. :param Union[str,iterator,Buffer... |
while text.hasNext():
for name, f in tokenizers:
current_token = f(text)
if current_token is not None:
return current_token |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tokenize(text):
r"""Generator for LaTeX tokens on text, ignoring comments. :param Union[str,iterator,Buffer] text: LaTeX to process \textbf { Do play \textit... |
current_token = next_token(text)
while current_token is not None:
yield current_token
current_token = next_token(text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def token(name):
"""Marker for a token :param str name: Name of tokenizer """ |
def wrap(f):
tokenizers.append((name, f))
return f
return wrap |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tokenize_punctuation_command(text):
"""Process command that augments or modifies punctuation. This is important to the tokenization of a string, as opening o... |
if text.peek() == '\\':
for point in PUNCTUATION_COMMANDS:
if text.peek((1, len(point) + 1)) == point:
return text.forward(len(point) + 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 tokenize_line_comment(text):
r"""Process a line comment :param Buffer text: iterator over line, with current position '%hello world' '%hello' """ |
result = TokenWithPosition('', text.position)
if text.peek() == '%' and text.peek(-1) != '\\':
result += text.forward(1)
while text.peek() != '\n' and text.hasNext():
result += text.forward(1)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tokenize_argument(text):
"""Process both optional and required arguments. :param Buffer text: iterator over line, with current position """ |
for delim in ARG_TOKENS:
if text.startswith(delim):
return text.forward(len(delim)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tokenize_math(text):
r"""Prevents math from being tokenized. :param Buffer text: iterator over line, with current position '$' '$$' """ |
if text.startswith('$') and (
text.position == 0 or text.peek(-1) != '\\' or text.endswith(r'\\')):
starter = '$$' if text.startswith('$$') else '$'
return TokenWithPosition(text.forward(len(starter)), text.position) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tokenize_string(text, delimiters=None):
r"""Process a string of text :param Buffer text: iterator over line, with current position :param Union[None,iterable... |
if delimiters is None:
delimiters = ALL_TOKENS
result = TokenWithPosition('', text.position)
for c in text:
if c == '\\' and str(text.peek()) in delimiters and str(c + text.peek()) not in delimiters:
c += next(text)
elif str(c) in delimiters: # assumes all tokens are si... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_tex(src):
r"""Read next expression from buffer :param Buffer src: a buffer of tokens """ |
c = next(src)
if c.startswith('%'):
return c
elif c.startswith('$'):
name = '$$' if c.startswith('$$') else '$'
expr = TexEnv(name, [], nobegin=True)
return read_math_env(src, expr)
elif c.startswith('\[') or c.startswith("\("):
if c.startswith('\['):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_item(src):
r"""Read the item content. There can be any number of whitespace characters between \item and the first non-whitespace character. However, af... |
def stringify(s):
return TokenWithPosition.join(s.split(' '), glue=' ')
def forward_until_new(s):
"""Catch the first non-whitespace character"""
t = TokenWithPosition('', s.peek().position)
while (s.hasNext() and
any([s.peek().startswith(substr) for substr in st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_args(src, args=None):
r"""Read all arguments from buffer. Advances buffer until end of last valid arguments. There can be any number of whitespace chara... |
args = args or TexArgs()
# Unlimited whitespace before first argument
candidate_index = src.num_forward_until(lambda s: not s.isspace())
while src.peek().isspace():
args.append(read_tex(src))
# Restricted to only one line break after first argument
line_breaks = 0
while src.peek()... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_arg(src, c):
"""Read the argument from buffer. Advances buffer until right before the end of the argument. :param Buffer src: a buffer of tokens :param ... |
content = [c]
while src.hasNext():
if src.peek() in ARG_END_TOKENS:
content.append(next(src))
break
else:
content.append(read_tex(src))
return Arg.parse(content) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hub_scores(msm, waypoints=None):
""" Calculate the hub score for one or more waypoints The "hub score" is a measure of how well traveled a certain state or s... |
n_states = msm.n_states_
if isinstance(waypoints, int):
waypoints = [waypoints]
elif waypoints is None:
waypoints = xrange(n_states)
elif not (isinstance(waypoints, list) or
isinstance(waypoints, np.ndarray)):
raise ValueError("waypoints (%s) must be an int, a lis... |
<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, sequences, y=None):
"""Fit a BACE lumping model using a sequence of cluster assignments. Parameters sequences : list(np.ndarray(dtype='int')) List ... |
super(BACE, self).fit(sequences, y=y)
if self.n_macrostates is not None:
self._do_lumping()
else:
raise RuntimeError('n_macrostates must not be None to fit')
return 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 _do_lumping(self):
"""Do the BACE lumping. """ |
c = copy.deepcopy(self.countsmat_)
if self.sliding_window:
c *= self.lag_time
c, macro_map, statesKeep = self._filterFunc(c)
w = np.array(c.sum(axis=1)).flatten()
w[statesKeep] += 1
unmerged = np.zeros(w.shape[0], dtype=np.int8)
unmerged[statesKeep... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def percentage(self):
"""Returns the progress as a percentage.""" |
if self.currval >= self.maxval:
return 100.0
return self.currval * 100.0 / self.maxval |
<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_packages():
"""Find all of mdtraj's python packages. Adapted from IPython's setupbase.py. Copyright IPython contributors, licensed under the BSD license... |
packages = ['mdtraj.scripts']
for dir,subdirs,files in os.walk('MDTraj'):
package = dir.replace(os.path.sep, '.')
if '__init__.py' not in files:
# not a package
continue
packages.append(package.replace('MDTraj', 'mdtraj'))
return packages |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _detect_sse3(self):
"Does this compiler support SSE3 intrinsics?"
self._print_support_start('SSE3')
result = self.hasfunction('__m128 v; _mm_hadd_ps(v,v)',
include='<pmmintrin.h>',
extra_postargs=['-msse3'])
self._print_support_en... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _detect_sse41(self):
"Does this compiler support SSE4.1 intrinsics?"
self._print_support_start('SSE4.1')
result = self.hasfunction( '__m128 v; _mm_round_ps(v,0x00)',
include='<smmintrin.h>',
extra_postargs=['-msse4'])
self._print_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uncertainty_K(self):
"""Estimate of the element-wise asymptotic standard deviation in the rate matrix """ |
if self.information_ is None:
self._build_information()
sigma_K = _ratematrix.sigma_K(
self.information_, theta=self.theta_, n=self.n_states_)
return sigma_K |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uncertainty_pi(self):
"""Estimate of the element-wise asymptotic standard deviation in the stationary distribution. """ |
if self.information_ is None:
self._build_information()
sigma_pi = _ratematrix.sigma_pi(
self.information_, theta=self.theta_, n=self.n_states_)
return sigma_pi |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uncertainty_eigenvalues(self):
"""Estimate of the element-wise asymptotic standard deviation in the model eigenvalues """ |
if self.information_ is None:
self._build_information()
sigma_eigenvalues = _ratematrix.sigma_eigenvalues(
self.information_, theta=self.theta_, n=self.n_states_)
if self.n_timescales is None:
return sigma_eigenvalues
return np.nan_to_num(sigma_eige... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uncertainty_timescales(self):
"""Estimate of the element-wise asymptotic standard deviation in the model relaxation timescales. """ |
if self.information_ is None:
self._build_information()
sigma_timescales = _ratematrix.sigma_timescales(
self.information_, theta=self.theta_, n=self.n_states_)
if self.n_timescales is None:
return sigma_timescales
return sigma_timescales[:self.n_ti... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _initial_guess(self, countsmat):
"""Generate an initial guess for \theta. """ |
if self.theta_ is not None:
return self.theta_
if self.guess == 'log':
transmat, pi = _transmat_mle_prinz(countsmat)
K = np.real(scipy.linalg.logm(transmat)) / self.lag_time
elif self.guess == 'pseudo':
transmat, pi = _transmat_mle_prinz(counts... |
<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_information(self):
"""Build the inverse of hessian of the log likelihood at theta_ """ |
lag_time = float(self.lag_time)
# only the "active set" of variables not at the bounds of the
# feasible set.
inds = np.where(self.theta_ != 0)[0]
hessian = _ratematrix.hessian(
self.theta_, self.countsmat_, t=lag_time, inds=inds)
self.information_ = np.ze... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _log_posterior(theta, counts, alpha, beta, n):
"""Log of the posterior probability and gradient Parameters theta : ndarray, shape=(n_params,) The free parame... |
# likelihood + grad
logp1, grad = loglikelihood(theta, counts)
# exponential prior on s_{ij}
logp2 = lexponential(theta[:-n], beta, grad=grad[:-n])
# dirichlet prior on \pi
logp3 = ldirichlet_softmax(theta[-n:], alpha=alpha, grad=grad[-n:])
logp = logp1 + logp2 + logp3
return logp, grad |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def categorical(pvals, size=None, random_state=None):
"""Return random integer from a categorical distribution Parameters pvals : sequence of floats, length p Pr... |
cumsum = np.cumsum(pvals)
if size is None:
size = (1,)
axis = 0
elif isinstance(size, tuple):
size = size + (1,)
axis = len(size) - 1
else:
raise TypeError('size must be an int or tuple of ints')
random_state = check_random_state(random_state)
return np.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def metzner_mcmc_slow(Z, n_samples, n_thin=1, random_state=None):
"""Metropolis Markov chain Monte Carlo sampler for reversible transition matrices Parameters Z ... |
# Upper and lower bounds on the sum of the K matrix, to ensure proper
# proposal weights. See Eq. 17 of [1].
K_MINUS = 0.9
K_PLUS = 1.1
Z = np.asarray(Z)
n_states = Z.shape[0]
if not Z.ndim == 2 and Z.shape[1] == n_states:
raise ValueError("Z must be square. Z.shape=%s" % str(Z.sha... |
<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_layout():
"""Specify a hierarchy of our templates.""" |
tica_msm = TemplateDir(
'tica',
[
'tica/tica.py',
'tica/tica-plot.py',
'tica/tica-sample-coordinate.py',
'tica/tica-sample-coordinate-plot.py',
],
[
TemplateDir(
'cluster',
[
... |
<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(self, name, limit=None):
"""Find the named TemplateDir in the hierarchy""" |
if name == self.name:
if limit is not None:
assert limit == 1
self.subdirs = []
return self
for subdir in self.subdirs:
res = subdir.find(name, limit)
if res is not None:
return res
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 implied_timescales(sequences, lag_times, n_timescales=10, msm=None, n_jobs=1, verbose=0):
""" Calculate the implied timescales for a given MSM. Parameters se... |
if msm is None:
msm = MarkovStateModel()
param_grid = {'lag_time' : lag_times}
models = param_sweep(msm, sequences, param_grid, n_jobs=n_jobs,
verbose=verbose)
timescales = [m.timescales_ for m in models]
n_timescales = min(n_timescales, min(len(ts) for ts in time... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def experimental(name=None):
"""A simple decorator to mark functions and methods as experimental.""" |
def inner(func):
@functools.wraps(func)
def wrapper(*fargs, **kw):
fname = name
if name is None:
fname = func.__name__
warnings.warn("%s" % fname, category=ExperimentalWarning,
stacklevel=2)
return func(*fargs... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _replace_labels(doc):
"""Really hacky find-and-replace method that modifies one of the sklearn docstrings to change the semantics of labels_ for the subclass... |
lines = doc.splitlines()
labelstart, labelend = None, None
foundattributes = False
for i, line in enumerate(lines):
stripped = line.strip()
if stripped == 'Attributes':
foundattributes = True
if foundattributes and not labelstart and stripped.startswith('labels_'):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump(value, filename, compress=None, cache_size=None):
"""Save an arbitrary python object using pickle. Parameters value : any Python object The object to st... |
if compress is not None or cache_size is not None:
warnings.warn("compress and cache_size are no longer valid options")
with open(filename, 'wb') as f:
pickle.dump(value, f) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.