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 make_polynomial(degree=3, n_samples=100, bias=0.0, noise=0.0, return_coefs=False, random_state=None):
""" Generate a noisy polynomial for a regression proble... |
generator = check_random_state(random_state)
# TODO: Add arguments to support other priors
coefs = generator.randn(degree + 1)
pows = np.arange(degree + 1)
poly = np.vectorize(lambda x: np.sum(coefs * x ** pows))
X, y = make_regression(poly, n_samples=n_samples, bias=bias, noise=noise,
... |
<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_data_home(data_home=None):
""" Return the path of the revrand data dir. This folder is used by some large dataset loaders to avoid downloading the data s... |
data_home_default = Path(__file__).ancestor(3).child('demos',
'_revrand_data')
if data_home is None:
data_home = os.environ.get('REVRAND_DATA', data_home_default)
if not os.path.exists(data_home):
os.makedirs(data_home)
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 fetch_gpml_sarcos_data(transpose_data=True, data_home=None):
""" Fetch the SARCOS dataset from the internet and parse appropriately into python arrays (44484... |
train_src_url = "http://www.gaussianprocess.org/gpml/data/sarcos_inv.mat"
test_src_url = ("http://www.gaussianprocess.org/gpml/data/sarcos_inv_test"
".mat")
data_home = get_data_home(data_home=data_home)
train_filename = os.path.join(data_home, 'sarcos_inv.mat')
test_filename ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_gpml_usps_resampled_data(transpose_data=True, data_home=None):
""" Fetch the USPS handwritten digits dataset from the internet and parse appropriately ... |
data_home = get_data_home(data_home=data_home)
data_filename = os.path.join(data_home,
'usps_resampled/usps_resampled.mat')
if not os.path.exists(data_filename):
r = requests.get('http://www.gaussianprocess.org/gpml/data/'
'usps_resampled.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split_state(self, state):
"""Split state string. Parameters state : `str` Returns ------- `list` of `str` """ |
if self.state_separator:
return state.split(self.state_separator)
return list(state) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def random_link(self, dataset, state, backward=False):
"""Get a random link. Parameters dataset : `object` Dataset from `self.get_dataset()`. state : `object` Li... |
links = self.get_links(dataset, state, backward)
if not links:
return None, None
x = randint(0, sum(link[0] for link in links) - 1)
for link in links:
count = link[0]
if x < count:
return link[1], self.follow_link(link, state, backward... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self, fp=None):
"""Update settings JSON data and save to file. Parameters fp : `file` or `str`, optional Output file. """ |
self.settings['storage'] = {
'state_separator': self.state_separator
}
self.do_save(fp) |
<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_color_setting(config_string):
"""Parse a DJANGO_COLORS environment variable to produce the system palette The general form of a pallete definition is: ... |
if not config_string:
return PALETTES[DEFAULT_PALETTE]
# Split the color configuration into parts
parts = config_string.lower().split(';')
palette = PALETTES[NOCOLOR_PALETTE].copy()
for part in parts:
if part in PALETTES:
# A default palette has been specified
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def couple(f, g):
r""" Compose a function thate returns two arguments. Given a pair of functions that take the same arguments, return a single function that retu... |
def coupled(*args, **kwargs):
return f(*args, **kwargs), g(*args, **kwargs)
return coupled |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decouple(fn):
""" Inverse operation of couple. Create two functions of one argument and one return from a function that takes two arguments and has two retur... |
def fst(*args, **kwargs):
return fn(*args, **kwargs)[0]
def snd(*args, **kwargs):
return fn(*args, **kwargs)[1]
return fst, snd |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nwise(iterable, n):
r""" Sliding window iterator. Iterator that acts like a sliding window of size `n`; slides over some iterable `n` items at a time. If ite... |
iters = tee(iterable, n)
for i, it in enumerate(iters):
for _ in range(i):
next(it, None)
return zip(*iters) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scalar_reshape(a, newshape, order='C'):
""" Reshape, but also return scalars or empty lists. Identical to `numpy.reshape` except in the case where `newshape`... |
if newshape == ():
return np.asscalar(a)
if newshape == (0,):
return []
return np.reshape(a, newshape, order) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flatten(arys, returns_shapes=True, hstack=np.hstack, ravel=np.ravel, shape=np.shape):
""" Flatten a potentially recursive list of multidimensional objects. .... |
if issequence(arys) and len(arys) > 0:
flat = partial(flatten,
returns_shapes=True,
hstack=hstack,
ravel=ravel,
shape=shape
)
flat_arys, shapes = zip(*map(flat, arys))
flat_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 unflatten(ary, shapes, reshape=scalar_reshape):
r""" Inverse opertation of flatten. Given a flat (1d) array, and a list of shapes (represented as tuples), re... |
if isinstance(shapes, list):
sizes = list(map(sumprod, shapes))
ends = np.cumsum(sizes)
begs = np.concatenate(([0], ends[:-1]))
struct_arys = [unflatten(ary[b:e], s, reshape=reshape)
for b, e, s in zip(begs, ends, shapes)]
return struct_arys
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 sumprod(seq):
""" Product of tuple, or sum of products of lists of tuples. Parameters seq : tuple or list Returns ------- int : the product of input tuples, ... |
if isinstance(seq, tuple):
# important to make sure dtype is int
# since prod on empty tuple is a float (1.0)
return np.prod(seq, dtype=int)
else:
return np.sum((sumprod(s) for s in seq), dtype=int) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def map_recursive(fn, iterable, output_type=None):
""" Apply a function of a potentially nested list of lists. Parameters fn : callable The function to apply to ... |
def applyormap(it):
if issequence(it):
return map_recursive(fn, it, output_type)
else:
return fn(it)
applied = map(applyormap, iterable)
return output_type(applied) if output_type else applied |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def map_indices(fn, iterable, indices):
r""" Map a function across indices of an iterable. Notes ----- Roughly equivalent to, though more efficient than:: lambda... |
index_set = set(indices)
for i, arg in enumerate(iterable):
if i in index_set:
yield fn(arg)
else:
yield arg |
<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_archiver(self, kind):
""" Returns instance of archiver class specific to given kind :param kind: archive kind """ |
archivers = {
'tar': TarArchiver,
'tbz2': Tbz2Archiver,
'tgz': TgzArchiver,
'zip': ZipArchiver,
}
return archivers[kind]() |
<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_init(func):
""" Decorator for adding partial application functionality to a basis object. This will add an "apply_ind" argument to a basis object initi... |
@wraps(func)
def new_init(self, *args, **kwargs):
apply_ind = kwargs.pop('apply_ind', None)
if np.isscalar(apply_ind):
apply_ind = [apply_ind]
func(self, *args, **kwargs)
self.apply_ind = apply_ind
return new_init |
<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_transform(func, self, X, *vargs, **kwargs):
""" Decorator for implementing partial application. This must decorate the ``transform`` and ``grad`` metho... |
X = X if self.apply_ind is None else X[:, self.apply_ind]
return func(self, X, *vargs, **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 apply_grad(fun, grad):
""" Apply a function that takes a gradient matrix to a sequence of 2 or 3 dimensional gradients. This is partucularly useful when the ... |
if issequence(grad):
fgrad = [apply_grad(fun, g) for g in grad]
return fgrad if len(fgrad) != 1 else fgrad[0]
elif len(grad) == 0:
return []
elif (grad.ndim == 1) or (grad.ndim == 2):
return fun(grad)
elif grad.ndim == 3:
return np.array([fun(grad[:, :, i]) for i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_dim(self, X):
""" Get the output dimensionality of this basis. This makes a cheap call to transform with the initial parameter values to ascertain the di... |
# Cache
if not hasattr(self, '_D'):
self._D = self.transform(X[[0]], *self.params_values()).shape[1]
return self._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 params_values(self):
""" Get a list of the ``Parameter`` values if they have a value. This does not include the basis regularizer. """ |
return [p.value for p in atleast_list(self.params) if p.has_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 transform(self, X, lenscale=None):
""" Apply the RBF to X. Parameters X: ndarray (N, d) array of observations where N is the number of samples, and d is the ... |
N, d = X.shape
lenscale = self._check_dim(d, lenscale)
den = (2 * lenscale**2)
return np.exp(- cdist(X / den, self.C / den, 'sqeuclidean')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform(self, X, lenscale=None):
r""" Apply the sigmoid basis function to X. Parameters X: ndarray (N, d) array of observations where N is the number of sa... |
N, d = X.shape
lenscale = self._check_dim(d, lenscale)
return expit(cdist(X / lenscale, self.C / lenscale, 'euclidean')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform(self, X, lenscale=None):
""" Apply the random basis to X. Parameters X: ndarray (N, d) array of observations where N is the number of samples, and ... |
N, D = X.shape
lenscale = self._check_dim(D, lenscale)[:, np.newaxis]
WX = np.dot(X, self.W / lenscale)
return np.hstack((np.cos(WX), np.sin(WX))) / np.sqrt(self.n) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def grad(self, X, lenscale=None):
r""" Get the gradients of this basis w.r.t.\ the length scales. Parameters X: ndarray (N, d) array of observations where N is t... |
N, D = X.shape
lenscale = self._check_dim(D, lenscale)[:, np.newaxis]
WX = np.dot(X, self.W / lenscale)
sinWX = - np.sin(WX)
cosWX = np.cos(WX)
dPhi = []
for i, l in enumerate(lenscale):
dWX = np.outer(X[:, i], - self.W[i, :] / l**2)
dPh... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform(self, X, lenscale=None):
""" Apply the Fast Food RBF basis to X. Parameters X: ndarray (N, d) array of observations where N is the number of sample... |
lenscale = self._check_dim(X.shape[1], lenscale)
VX = self._makeVX(X / lenscale)
Phi = np.hstack((np.cos(VX), np.sin(VX))) / np.sqrt(self.n)
return Phi |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform(self, X, mean=None, lenscale=None):
""" Apply the spectral mixture component basis to X. Parameters X: ndarray (N, d) array of observations where N... |
mean = self._check_dim(X.shape[1], mean, paramind=0)
lenscale = self._check_dim(X.shape[1], lenscale, paramind=1)
VX = self._makeVX(X / lenscale)
mX = X.dot(mean)[:, np.newaxis]
Phi = np.hstack((np.cos(VX + mX), np.sin(VX + mX),
np.cos(VX - mX), np.sin(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def grad(self, X, mean=None, lenscale=None):
r""" Get the gradients of this basis w.r.t.\ the mean and length scales. Parameters x: ndarray (n, d) array of obser... |
d = X.shape[1]
mean = self._check_dim(d, mean, paramind=0)
lenscale = self._check_dim(d, lenscale, paramind=1)
VX = self._makeVX(X / lenscale)
mX = X.dot(mean)[:, np.newaxis]
sinVXpmX = - np.sin(VX + mX)
sinVXmmX = - np.sin(VX - mX)
cosVXpmX = np.cos(VX... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform(self, X, *params):
""" Return the basis function applied to X. I.e. Phi(X, params), where params can also optionally be used and learned. Parameter... |
Phi = []
args = list(params)
for base in self.bases:
phi, args = base._transform_popargs(X, *args)
Phi.append(phi)
return np.hstack(Phi) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def grad(self, X, *params):
""" Return the gradient of the basis function for each parameter. Parameters X : ndarray (N, d) array of observations where N is the ... |
# Establish a few dimensions
N = X.shape[0]
D = self.get_dim(X)
endinds = self.__base_locations(X) # for the Padding indices
args = list(params)
# Generate structured gradients with appropriate zero padding
def make_dPhi(i, g):
# Pad the gradient w... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def params(self):
""" Return a list of all of the ``Parameter`` objects. Or a just a single ``Parameter`` is there is only one, and single empty ``Parameter`` if... |
paramlist = [b.params for b in self.bases if b.params.has_value]
if len(paramlist) == 0:
return Parameter()
else:
return paramlist if len(paramlist) > 1 else paramlist[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_udiff(filenode_old, filenode_new, show_whitespace=True):
""" Returns unified diff between given ``filenode_old`` and ``filenode_new``. """ |
try:
filenode_old_date = filenode_old.changeset.date
except NodeError:
filenode_old_date = None
try:
filenode_new_date = filenode_new.changeset.date
except NodeError:
filenode_new_date = None
for filenode in (filenode_old, filenode_new):
if not isinstance(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 get_gitdiff(filenode_old, filenode_new, ignore_whitespace=True):
""" Returns git style diff between given ``filenode_old`` and ``filenode_new``. :param ignor... |
for filenode in (filenode_old, filenode_new):
if not isinstance(filenode, FileNode):
raise VCSError("Given object should be FileNode object, not %s"
% filenode.__class__)
old_raw_id = getattr(filenode_old.changeset, 'raw_id', '0' * 40)
new_raw_id = getattr(filenode_new... |
<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_iterator(self):
""" make a fresh copy of generator, we should not iterate thru an original as it's needed for repeating operations on this instance of D... |
self.__udiff, iterator_copy = itertools.tee(self.__udiff)
return iterator_copy |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _extract_rev(self, line1, line2):
""" Extract the filename and revision hint from a line. """ |
try:
if line1.startswith('--- ') and line2.startswith('+++ '):
l1 = line1[4:].split(None, 1)
old_filename = l1[0].lstrip('a/') if len(l1) >= 1 else None
old_rev = l1[1] if len(l1) == 2 else 'old'
l2 = line2[4:].split(None, 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 _parse_udiff(self):
""" Parse the diff an return data for the template. """ |
lineiter = self.lines
files = []
try:
line = lineiter.next()
# skip first context
skipfirst = True
while 1:
# continue until we found the old file
if not line.startswith('--- '):
line = lineiter.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _safe_id(self, idstring):
"""Make a string safe for including in an id attribute. The HTML spec says that id attributes 'must begin with a letter ([A-Za-z]) ... |
# Transform all whitespace to underscore
idstring = re.sub(r'\s', "_", '%s' % idstring)
# Remove everything that is not a hyphen or a member of \w
idstring = re.sub(r'(?!-)\W', "", idstring).lower()
return idstring |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def raw_diff(self):
""" Returns raw string as udiff """ |
udiff_copy = self.copy_iterator()
if self.__format == 'gitdiff':
udiff_copy = self._parse_gitdiff(udiff_copy)
return u''.join(udiff_copy) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def cache(self, link, nav):
'''Stores a navigator in the identity map for the current
api. Can take a link or a bare uri'''
if link is None:
return # We don't cache navigators without a Link
elif hasattr(link, 'uri'):
self.id_map[link.uri] = nav
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 get_cached(self, link, default=None):
'''Retrieves a cached navigator from the id_map.
Either a Link object or a bare uri string may be passed in.'''
if hasattr(link, 'uri'):
return self.id_map.get(link.uri, default)
else:
return self.id_map.get(link, default... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def is_cached(self, link):
'''Returns whether the current navigator is cached. Intended
to be overwritten and customized by subclasses.
'''
if link is None:
return False
elif hasattr(link, 'uri'):
return link.uri in self.id_map
else:
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 expand_uri(self, **kwargs):
'''Returns the template uri expanded with the current arguments'''
kwargs = dict([(k, v if v != 0 else '0') for k, v in kwargs.items()])
return uritemplate.expand(self.link.uri, 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 expand_link(self, **kwargs):
'''Expands with the given arguments and returns a new
untemplated Link object
'''
props = self.link.props.copy()
del props['templated']
return Link(
uri=self.expand_uri(**kwargs),
properties=props,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def hal(root,
apiname=None,
default_curie=None,
auth=None,
headers=None,
session=None,
):
'''Create a HALNavigator'''
root = utils.fix_scheme(root)
halnav = HALNavigator(
link=Link(uri=root),
core... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def docsfor(self, rel): # pragma: nocover
'''Obtains the documentation for a link relation. Opens in a webbrowser
window'''
prefix, _rel = rel.split(':')
if prefix in self.curies:
doc_url = uritemplate.expand(self.curies[prefix], {'rel': _rel})
else:
doc_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _make_links_from(self, body):
'''Creates linked navigators from a HAL response body'''
ld = utils.CurieDict(self._core.default_curie, {})
for rel, link in body.get('_links', {}).items():
if rel != 'curies':
if isinstance(link, list):
ld[rel] = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _make_embedded_from(self, doc):
'''Creates embedded navigators from a HAL response doc'''
ld = utils.CurieDict(self._core.default_curie, {})
for rel, doc in doc.get('_embedded', {}).items():
if isinstance(doc, list):
ld[rel] = [self._recursively_embed(d) for d in ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _recursively_embed(self, doc, update_state=True):
'''Crafts a navigator from a hal-json embedded document'''
self_link = None
self_uri = utils.getpath(doc, '_links.self.href')
if self_uri is not None:
uri = urlparse.urljoin(self.uri, self_uri)
self_link = 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 _navigator_or_thunk(self, link):
'''Crafts a navigator or from a hal-json link dict.
If the link is relative, the returned navigator will have a
uri that relative to this navigator's uri.
If the link passed in is templated, a PartialNavigator will be
returned instead.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _can_parse(self, content_type):
'''Whether this navigator can parse the given content-type.
Checks that the content_type matches one of the types specified
in the 'Accept' header of the request, if supplied.
If not supplied, matches against the default'''
content_type, conten... |
<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_content(self, text):
'''Parses the content of a response doc into the correct
format for .state.
'''
try:
return json.loads(text)
except ValueError:
raise exc.UnexpectedlyNotJSON(
"The resource at {.uri} wasn't valid JSON", 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 _update_self_link(self, link, headers):
'''Update the self link of this navigator'''
self.self.props.update(link)
# Set the self.type to the content_type of the returned document
self.self.props['type'] = headers.get(
'Content-Type', self.DEFAULT_CONTENT_TYPE)
sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _ingest_response(self, response):
'''Takes a response object and ingests state, links, embedded
documents and updates the self link of this navigator to
correspond. This will only work if the response is valid
JSON
'''
self.response = response
if self._can_par... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _create_navigator(self, response, raise_exc=True):
'''Create the appropriate navigator from an api response'''
method = response.request.method
# TODO: refactor once hooks in place
if method in (POST, PUT, PATCH, DELETE) \
and response.status_code in (
http... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _request(self, method, body=None, raise_exc=True, headers=None, files=None):
'''Fetches HTTP response using the passed http method. Raises
HALNavigatorError if response is in the 400-500 range.'''
headers = headers or {}
if body and 'Content-Type' not in headers:
headers.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def fetch(self, raise_exc=True):
'''Performs a GET request to the uri of this navigator'''
self._request(GET, raise_exc=raise_exc) # ingests response
self.fetched = True
return self.state.copy() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def create(self, body=None, raise_exc=True, headers=None, **kwargs):
'''Performs an HTTP POST to the server, to create a
subordinate resource. Returns a new HALNavigator representing
that resource.
`body` may either be a string or a dictionary representing json
`headers` are add... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def upsert(self, body, raise_exc=True, headers=False, files=None):
'''Performs an HTTP PUT to the server. This is an idempotent
call that will create the resource this navigator is pointing
to, or will update it if it already exists.
`body` may either be a string or a dictionary represe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def patch(self, body, raise_exc=True, headers=False, files=None):
'''Performs an HTTP PATCH to the server. This is a
non-idempotent call that may update all or a portion of the
resource this navigator is pointing to. The format of the
patch body is up to implementations.
`body` ... |
<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_content(self, text):
'''Try to parse as HAL, but on failure use an empty dict'''
try:
return super(OrphanHALNavigator, self)._parse_content(text)
except exc.UnexpectedlyNotJSON:
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 logsumexp(X, axis=0):
""" Log-sum-exp trick for matrix X for summation along a specified axis. This performs the following operation in a stable fashion, .. ... |
mx = X.max(axis=axis)
if (X.ndim > 1):
mx = np.atleast_2d(mx).T if axis == 1 else np.atleast_2d(mx)
return np.log(np.exp(X - mx).sum(axis=axis)) + np.ravel(mx) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def softmax(X, axis=0):
""" Pass X through a softmax function in a numerically stable way using the log-sum-exp trick. This transformation is: .. math:: \\frac{\... |
if axis == 1:
return np.exp(X - logsumexp(X, axis=1)[:, np.newaxis])
elif axis == 0:
return np.exp(X - logsumexp(X, axis=0))
else:
raise ValueError("This only works on 2D arrays for now.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_visa(n):
"""Checks if credit card number fits the visa format.""" |
n, length = str(n), len(str(n))
if length >= 13 and length <= 16:
if n[0] == '4':
return True
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 is_visa_electron(n):
"""Checks if credit card number fits the visa electron format.""" |
n, length = str(n), len(str(n))
form = ['026', '508', '844', '913', '917']
if length == 16:
if n[0] == '4':
if ''.join(n[1:4]) in form or ''.join(n[1:6]) == '17500':
return True
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 is_mastercard(n):
"""Checks if credit card number fits the mastercard format.""" |
n, length = str(n), len(str(n))
if length >= 16 and length <= 19:
if ''.join(n[:2]) in strings_between(51, 56):
return True
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 is_amex(n):
"""Checks if credit card number fits the american express format.""" |
n, length = str(n), len(str(n))
if length == 15:
if n[0] == '3' and (n[1] == '4' or n[1] == '7'):
return True
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 is_discover(n):
"""Checks if credit card number fits the discover card format.""" |
n, length = str(n), len(str(n))
if length == 16:
if n[0] == '6':
if ''.join(n[1:4]) == '011' or n[1] == '5':
return True
elif n[1] == '4' and n[2] in strings_between(4, 10):
return True
elif ''.join(n[1:6]) in strings_between(22126, 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 get_format(n):
"""Gets a list of the formats a credit card number fits.""" |
formats = []
if is_visa(n):
formats.append('visa')
if is_visa_electron(n):
formats.append('visa electron')
if is_mastercard(n):
formats.append('mastercard')
if is_amex(n):
formats.append('amex')
if is_maestro(n):
formats.append('maestro')
if is_disco... |
<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_name(self):
"""Return full name of member""" |
if self.prefix is not None:
return '.'.join([self.prefix, self.member])
return self.member |
<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_signature(cls, signature):
"""Parse signature declartion string Uses :py:attr:`signature_pattern` to parse out pieces of constraint signatures. Pattern... |
assert cls.signature_pattern is not None
pattern = re.compile(cls.signature_pattern, re.VERBOSE)
match = pattern.match(signature)
if match:
groups = match.groupdict()
arguments = None
if 'arguments' in groups and groups['arguments'] is not None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_signature(self, sig, signode):
"""Parses out pieces from construct signatures Parses out prefix and argument list from construct definition. This is a... |
try:
sig = self.parse_signature(sig.strip())
except ValueError:
self.env.warn(self.env.docname,
'Parsing signature failed: "{}"'.format(sig),
self.lineno)
raise
prefix = self.env.ref_context.get('dn:prefix'... |
<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_target_and_index(self, name, sig, signode):
"""Add objects to the domain list of objects This uses the directive short name along with the full object na... |
full_name = name[0]
target_name = '{0}-{1}'.format(self.short_name, full_name)
if target_name not in self.state.document.ids:
signode['names'].append(target_name)
signode['ids'].append(target_name)
signode['first'] = not self.names
self.state.docu... |
<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_index_text(self, prefix, name_obj):
"""Produce index text by directive attributes""" |
(name, _) = name_obj
msg = '{name} ({obj_type})'
parts = {
'name': name,
'prefix': prefix,
'obj_type': self.long_name,
}
try:
(obj_ns, obj_name) = name.rsplit('.', 1)
parts['name'] = obj_name
parts['namespac... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
"""If element is considered hidden, drop the desc_signature node The default handling of signatures by :py:cls:`ObjectDescription` returns a list ... |
nodes = super(DotNetObjectNested, self).run()
if 'hidden' in self.options:
for node in nodes:
if isinstance(node, addnodes.desc):
for (m, child) in enumerate(node.children):
if isinstance(child, addnodes.desc_signature):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def before_content(self):
"""Build up prefix history for nested elements The following keys are used in :py:attr:`self.env.ref_context`: dn:prefixes Stores the p... |
super(DotNetObjectNested, self).before_content()
if self.names:
(_, prefix) = self.names.pop()
try:
self.env.ref_context['dn:prefixes'].append(prefix)
except (AttributeError, KeyError):
self.env.ref_context['dn:prefixes'] = [prefix]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_link(self, env, refnode, has_explicit_title, title, target):
"""This handles some special cases for reference links in .NET First, the standard Sphin... |
result = super(DotNetXRefRole, self).process_link(env, refnode,
has_explicit_title,
title, target)
(title, target) = result
if not has_explicit_title:
# If the first c... |
<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_obj(self, env, prefix, name, obj_type, searchorder=0):
"""Find object reference :param env: Build environment :param prefix: Object prefix :param name: ... |
# Skip parens
if name[-2:] == '()':
name = name[:-2]
if not name:
return []
object_types = list(self.object_types)
if obj_type is not None:
object_types = self.objtypes_for_role(obj_type)
objects = self.data['objects']
newna... |
<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_any_xref(self, env, fromdocname, builder, target, node, contnode):
"""Look for any references, without object type This always searches in "refspecif... |
prefix = node.get('dn:prefix')
results = []
match = self.find_obj(env, prefix, target, None, 1)
if match is not None:
(name, obj) = match
results.append(('dn:' + self.role_for_objtype(obj[1]),
make_refnode(builder, fromdocname, obj[0]... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, width, height):
"""Create an image of type. Parameters width: `int` Image width. height: `int` Image height. Returns ------- `PIL.Image.Image` "... |
return Image.new(self.mode, (width, height)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge(self, imgs):
"""Merge image channels. Parameters imgs : `list` of `PIL.Image.Image` Returns ------- `PIL.Image.Image` Raises ------ ValueError If image... |
if not imgs:
raise ValueError('empty channel list')
if len(imgs) == 1:
return imgs[0]
return Image.merge(self.mode, imgs) |
<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_keep_boundary(start, end, namespaces):
"""a helper to inspect a link and see if we should keep the link boundary """ |
result_start, result_end = False, False
parent_start = start.getparent()
parent_end = end.getparent()
if parent_start.tag == "{%s}p" % namespaces['text']:
# more than one child in the containing paragraph ?
# we keep the boundary
result_start = len(parent_start.getchildren()) >... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __prepare_namespaces(self):
"""create proper namespaces for our document """ |
# create needed namespaces
self.namespaces = dict(
text="urn:text",
draw="urn:draw",
table="urn:table",
office="urn:office",
xlink="urn:xlink",
svg="urn:svg",
manifest="urn:manifest",
)
# copy namespace... |
<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_user_instructions(self):
""" Public method to help report engine to find all instructions """ |
res = []
# TODO: Check if instructions can be stored in other content_trees
for e in get_instructions(self.content_trees[0], self.namespaces):
childs = e.getchildren()
if childs:
res.extend([c.text for c in childs])
else:
res.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 get_user_instructions_mapping(self):
""" Public method to get the mapping of all variables defined in the template """ |
instructions = self.get_user_instructions()
user_variables = self.get_user_variables()
# For now we just want for loops
instructions = [i for i in instructions
if i.startswith('for') or i == '/for']
# Now we call the decoder to get variable mapping from... |
<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_link(self, link, py3o_base, closing_link):
"""transform a py3o link into a proper Genshi statement rebase a py3o link at a proper place in the tree to... |
# OLD open office version
if link.text is not None and link.text.strip():
if not link.text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
# new open office version
elif len(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 get_user_variables(self):
"""a public method to help report engines to introspect a template and find what data it needs and how it will be used returns a li... |
# TODO: Check if some user fields are stored in other content_trees
return [
e.get('{%s}name' % e.nsmap.get('text'))[5:]
for e in get_user_fields(self.content_trees[0], self.namespaces)
] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __prepare_usertexts(self):
"""Replace user-type text fields that start with "py3o." with genshi instructions. """ |
field_expr = "//text:user-field-get[starts-with(@text:name, 'py3o.')]"
for content_tree in self.content_trees:
for userfield in content_tree.xpath(
field_expr,
namespaces=self.namespaces
):
parent = userfield.getparent()
... |
<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_images_to_manifest(self):
"""Add entries for py3o images into the manifest file.""" |
xpath_expr = "//manifest:manifest[1]"
for content_tree in self.content_trees:
# Find manifest:manifest tags.
manifest_e = content_tree.xpath(
xpath_expr,
namespaces=self.namespaces
)
if not manifest_e:
co... |
<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_tree(self, data):
"""prepare the flows without saving to file this method has been decoupled from render_flow to allow better unit testing """ |
# TODO: find a way to make this localization aware...
# because ATM it formats texts using French style numbers...
# best way would be to let the user inject its own vars...
# but this would not work on fusion servers...
# so we must find a way to localize this a bit... or remov... |
<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_flow(self, data):
"""render the OpenDocument with the user data @param data: the input stream of user data. This should be a dictionary mapping, keys ... |
self.render_tree(data)
# then reconstruct a new ODT document with the generated content
for status in self.__save_output():
yield status |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_image_path(self, identifier, path):
"""Set data for an image mentioned in the template. @param identifier: Identifier of the image; refer to the image in... |
f = open(path, 'rb')
self.set_image_data(identifier, f.read())
f.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __save_output(self):
"""Saves the output into a native OOo document format. """ |
out = zipfile.ZipFile(self.outputfilename, 'w')
for info_zip in self.infile.infolist():
if info_zip.filename in self.templated_files:
# Template file - we have edited these.
# get a temp file
streamout = open(get_secure_filename(), "w+b")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_create(args):
"""Create a generator. Parameters args : `argparse.Namespace` Command arguments. """ |
if args.type == SQLITE:
if args.output is not None and path.exists(args.output):
remove(args.output)
storage = SqliteStorage(db=args.output, settings=args.settings)
else:
storage = JsonStorage(settings=args.settings)
markov = MarkovText.from_storage(storage)
read(arg... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmd_update(args):
"""Update a generator. Parameters args : `argparse.Namespace` Command arguments. """ |
#args.output = None
markov = load(MarkovText, args.state, args)
read(args.input, markov, args.progress)
if args.output is None:
if args.type == SQLITE:
save(markov, None, args)
elif args.type == JSON:
name, ext = path.splitext(args.state)
tmp = 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 cmd_generate(args):
"""Generate text. Parameters args : `argparse.Namespace` Command arguments. """ |
if args.start:
if args.end or args.reply:
raise ValueError('multiple input arguments')
args.reply_to = args.start
args.reply_mode = ReplyMode.END
elif args.end:
if args.reply:
raise ValueError('multiple input arguments')
args.reply_to = args.end
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(args=None):
"""CLI main function. Parameters args : `list` of `str`, optional CLI arguments (default: `sys.argv`). """ |
parser = ArgumentParser()
parser.add_argument('-v', '--version',
action='version', version=CLI_VERSION)
parsers = parser.add_subparsers(dest='dtype')
text.create_arg_parser(parsers.add_parser('text'))
if image is not None:
image.create_arg_parser(parsers.add_parser... |
<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_check_digit(unchecked):
"""returns the check digit of the card number.""" |
digits = digits_of(unchecked)
checksum = sum(even_digits(unchecked)) + sum([
sum(digits_of(2 * d)) for d in odd_digits(unchecked)])
return 9 * checksum % 10 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_valid(number):
"""determines whether the card number is valid.""" |
n = str(number)
if not n.isdigit():
return False
return int(n[-1]) == get_check_digit(n[:-1]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.