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 problem Examples -------- """
|
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,
random_state=random_state)
if return_coefs:
return X, y, coefs
return X, y
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 several times. By default the data dir is set to a folder named 'revrand_data' in the user home folder. Alternatively, it can be set by the 'REVRAND_DATA' environment variable or programmatically by giving an explicit folder path. The '~' symbol is expanded to the user home folder. If the folder does not already exist, it is automatically created. """
|
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 data_home
|
<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, 21) (44484,) (4449, 21) (4449,) """
|
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 = os.path.join(data_home, 'sarcos_inv_test.mat')
if not os.path.exists(train_filename):
urllib.request.urlretrieve(train_src_url, train_filename)
if not os.path.exists(test_filename):
urllib.request.urlretrieve(test_src_url, test_filename)
train_data = loadmat(train_filename).get('sarcos_inv')
test_data = loadmat(test_filename).get('sarcos_inv_test')
train_bunch = Bunch(data=train_data[:, :21],
targets=train_data[:, 21])
test_bunch = Bunch(data=test_data[:, :21],
targets=test_data[:, 21])
return Bunch(train=train_bunch, test=test_bunch)
|
<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 into python arrays (4649,) (4649, 256) True True (4649,) (4649, 256) (256, 4649) """
|
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.tar.bz2')
with tarfile.open(fileobj=BytesIO(r.content)) as tar_infile:
tar_infile.extract('usps_resampled/usps_resampled.mat',
path=data_home)
matlab_dict = loadmat(data_filename)
train_data = matlab_dict['train_patterns']
test_data = matlab_dict['test_patterns']
if transpose_data:
train_data = train_data.T
test_data = test_data.T
train_targets = matlab_dict['train_labels'].T
train_targets = np.argwhere(train_targets == 1)[:, 1]
test_targets = matlab_dict['test_labels'].T
test_targets = np.argwhere(test_targets == 1)[:, 1]
train_bunch = Bunch(data=train_data,
targets=train_targets)
test_bunch = Bunch(data=test_data,
targets=test_targets)
return Bunch(train=train_bunch, test=test_bunch)
|
<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` Link source. backward : `bool`, optional Link direction. Raises ------ ValueError If link count is invalid. Returns ------- (`str` or `None`, `object` or `None`) Link value and next state. """
|
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)
x -= count
raise RuntimeError('invalid link sum')
|
<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: "palette;role=fg;role=fg/bg;role=fg,option,option;role=fg/bg,option,option" where: palette is a named palette; one of 'light', 'dark', or 'nocolor'. role is a named style used by Django fg is a background color. bg is a background color. option is a display options. Specifying a named palette is the same as manually specifying the individual definitions for each role. Any individual definitions following the pallete definition will augment the base palette definition. Valid roles: 'error', 'notice', 'sql_field', 'sql_coltype', 'sql_keyword', 'sql_table', 'http_info', 'http_success', 'http_redirect', 'http_bad_request', 'http_not_found', 'http_server_error' Valid colors: 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white' Valid options: 'bold', 'underscore', 'blink', 'reverse', 'conceal' """
|
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
palette.update(PALETTES[part])
elif '=' in part:
# Process a palette defining string
definition = {}
# Break the definition into the role,
# plus the list of specific instructions.
# The role must be in upper case
role, instructions = part.split('=')
role = role.upper()
styles = instructions.split(',')
styles.reverse()
# The first instruction can contain a slash
# to break apart fg/bg.
colors = styles.pop().split('/')
colors.reverse()
fg = colors.pop()
if fg in color_names:
definition['fg'] = fg
if colors and colors[-1] in color_names:
definition['bg'] = colors[-1]
# All remaining instructions are options
opts = tuple(s for s in styles if s in opt_dict.keys())
if opts:
definition['opts'] = opts
# The nocolor palette has all available roles.
# Use that palette as the basis for determining
# if the role is valid.
if role in PALETTES[NOCOLOR_PALETTE] and definition:
palette[role] = definition
# If there are no colors specified, return the empty palette.
if palette == PALETTES[NOCOLOR_PALETTE]:
return None
return palette
|
<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 returns a pair consisting of the return values of each function. Notes ----- Equivalent to:: lambda f, g: lambda *args, **kwargs: (f(*args, **kwargs), g(*args, **kwargs)) Examples -------- (250, 150) """
|
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 returns Examples -------- 250 150 """
|
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 iterable has `m` elements, this function will return an iterator over `m-n+1` tuples. Parameters iterable : iterable An iterable object. n : int Window size. Returns ------- iterator of tuples. Iterator of size `n` tuples Notes ----- First `n` iterators are created:: iters = tee(iterable, n) Next, iterator `i` is advanced `i` times:: for i, it in enumerate(iters):
for _ in range(i):
next(it, None) Finally, the iterators are zipped back up again:: return zip(*iters) Examples -------- [(2, 5, 7), (5, 7, 4), (7, 4, 2), (4, 2, 8), (2, 8, 6)] [(2, 5), (5, 7), (7, 4), (4, 2), (2, 8), (8, 6)] [(2,), (5,), (7,), (4,), (2,), (8,), (6,)] [(2, 5, 7, 4, 2, 8, 6)] .. todo:: [] [] A sliding window of size `n` over a list of `m` elements gives `m-n+1` windows True True True """
|
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` is the empty tuple, in which case we return a scalar instead of a 0-dimensional array. Examples -------- True 3.14 array([ 2.71]) [] """
|
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. .. note:: Not to be confused with `np.ndarray.flatten()` (a more befitting might be `chain` or `stack` or maybe something else entirely since this function is more than either `concatenate` or `np.flatten` itself. Rather, it is the composition of the former with the latter. Parameters arys : list of objects One or more input arrays of possibly heterogenous shapes and sizes. returns_shapes : bool, optional Default is `True`. If `True`, the tuple `(flattened, shapes)` is returned, otherwise only `flattened` is returned. hstack : callable, optional a function that implements horizontal stacking ravel : callable, optional a function that flattens the object shape : callable, optional a function that returns the shape of the object Returns ------- flattened,[shapes] : {1dobject, list of tuples} Return the flat (1d) object resulting from the concatenation of flattened multidimensional objects. When `returns_shapes` is `True`, return a list of tuples containing also the shapes of each array as the second element. See Also -------- revrand.utils.unflatten : its inverse Examples -------- (array([9, 4, 7, 4, 5, 2, 7, 3, 1, 2, 6, 6, 6, 5, 5, 1, 6, 9, 3, 9, 1, 9, 4, 1]), [(), (5,), (2, 3), (2, 2, 3)]) Note that scalars and 0-dimensional arrays are treated differently from 1-dimensional singleton arrays. (array([ 3.14, 2.71, 1.61]), [(), (), (1,)]) array([9, 4, 7, 4, 5, 2, 7, 3, 1, 2, 6, 6, 6, 5, 5, 1, 6, 9, 3, 9, 1, 9, 4, 1]) True True True True (array([ 3.14, 2.71, 1.61]), [(), [(), (1,)]]) """
|
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_ary = hstack(flat_arys)
shapes = list(shapes)
else:
flat_ary = ravel(arys)
shapes = shape(arys)
return (flat_ary, shapes) if returns_shapes else flat_ary
|
<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), return a list of ndarrays with the specified shapes. Parameters ary : a 1d array A flat (1d) array. shapes : list of tuples A list of ndarray shapes (tuple of array dimensions) Returns ------- list of ndarrays A list of ndarrays with the specified shapes. See Also -------- revrand.utils.flatten : its inverse Notes ----- Equivalent to:: lambda ary, shapes, order='C': \ map(partial(custom_reshape, order=order), np.hsplit(ary, np.cumsum(map(partial(np.prod, dtype=int), shapes))), shapes) Examples -------- [array([7]), array([4]), array([5, 8, 9, 1]), array([[4, 2, 5], [3, 4, 3]])] [7, array([4]), array([5, 8, 9, 1]), array([[4, 2, 5], [3, 4, 3]])] [7, array([4]), array([5, 8, 9]), array([[1, 4, 2], [5, 3, 4]])] Traceback (most recent call last):
ValueError: total size of new array must be unchanged (array([7, 4, 5, 8, 9, 1, 4, 2, 5, 3, 4, 3]), [(), (1,), (4,), (2, 3)]) [[array([7]), array([4])], array([5, 8, 9, 1]), array([[4, 2, 5], [3, 4, 3]])] (array([7, 4, 5, 8, 9, 1, 4, 2, 5, 3, 4, 3]), [(), (1,), [(4,), (2, 3)]]) """
|
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:
struct_ary = reshape(ary, shapes)
return struct_ary
|
<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, or the sum of products of lists of tuples, recursively. Examples -------- 6 10 11 """
|
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 each element (and sub elements) in iterable iterable : iterable An iterable, sequence, sequence of sequences etc. :code:`fn` will be applied to each element in each list. output_type : callable, optional if None, a map with sub-maps in the same structure as :code:`iterable` will be returned, otherwise the callable will be applied to each sequence (i.e. :code:`list` will return lists of lists etc). Returns ------- map or iterable type : if :code:`output_type` is None, a map with sub-maps in the same structure as :code:`iterable` will be returned, otherwise the callable will be applied to each sequence (i.e. :code:`list` will return lists of lists etc). Examples -------- [False, False, [False, False, [True, True]], True] (2, 4, (6, 8, (10, 12)), 14) """
|
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 fn, iterable, *indices: (fn(arg) if i in indices else arg for i, arg in enumerate(iterable)) Examples -------- [12, 6, 7, 3, 6, 24, 2] [2.1972245773362196, array([ 5., 6., 2.]), array([[ 1.60943791, 1.79175947, 0.69314718], [ 0.69314718, 1.09861229, 2.19722458]])] .. todo:: Floating point precision [9., array([5., 6., 2.]), array([[ 5., 6., 2.], [ 2., 3., 9.]])] """
|
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 initialiser that can be used to apply the basis function to only the dimensions specified in apply_ind. E.g., (100, 10) """
|
@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`` methods of basis objects if the ``slice_init`` decorator was used. """
|
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 gradient of a basis concatenation object is quite complex, eg. True (3,) Parameters fun: callable the function too apply to the (2d) gradient. grad: ndarray or generator the gradient of the basis function (output of base.grad). Returns ------- scalar, ndarray or sequence: the result of applying fun(grad) for a structured grad. """
|
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 in range(grad.shape[2])])
else:
raise ValueError("Only up to 3d gradients allowed!")
|
<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 dimensionality of the output features. Parameters X : ndarray (N, d) array of observations where N is the number of samples, and d is the dimensionality of X. Returns ------- int : The dimensionality of the basis. """
|
# 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 dimensionality of X. lenscale: scalar or ndarray, optional scalar or array of shape (d,) length scales (one for each dimension of X). If not input, this uses the value of the initial length scale. Returns ------- ndarray: of shape (N, D) where D is number of RBF centres. """
|
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 samples, and d is the dimensionality of X. lenscale: float the length scale (scalar) of the RBFs to apply to X. If not input, this uses the value of the initial length scale. Returns ------- ndarray: of shape (N, D) where D is number of centres. """
|
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 d is the dimensionality of X. lenscale: scalar or ndarray, optional scalar or array of shape (d,) length scales (one for each dimension of X). If not input, this uses the value of the initial length scale. Returns ------- ndarray: of shape (N, 2*nbases) where nbases is number of random bases to use, given in the constructor. """
|
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 the number of samples, and d is the dimensionality of X. lenscale: scalar or ndarray, optional scalar or array of shape (d,) length scales (one for each dimension of X). If not input, this uses the value of the initial length scale. Returns ------- ndarray: of shape (N, 2*nbases[, d]) where d is number of lenscales (if not ARD, i.e. scalar lenscale, this is just a 2D array). This is :math:`\partial \Phi(\mathbf{X}) / \partial \mathbf{l}` """
|
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)
dPhi.append(np.hstack((dWX * sinWX, dWX * cosWX)) /
np.sqrt(self.n))
return np.dstack(dPhi) if len(lenscale) != 1 else dPhi[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 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 samples, and d is the dimensionality of X. lenscale: scalar or ndarray, optional scalar or array of shape (d,) length scales (one for each dimension of X).If not input, this uses the value of the initial length scale. Returns ------- ndarray: of shape (N, 2*nbases) where nbases is number of random bases to use, given in the constructor (to nearest larger two power). """
|
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 is the number of samples, and d is the dimensionality of X. mean: ndarray, optional array of shape (d,) frequency means (one for each dimension of X). If not input, this uses the value of the initial mean. lenscale: ndarray, optional array of shape (d,) length scales (one for each dimension of X). If not input, this uses the value of the initial length scale. Returns ------- ndarray: of shape (N, 4*nbases) where nbases is number of random bases to use, given in the constructor (to nearest larger two power). """
|
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(VX - mX))) / \
np.sqrt(2 * 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 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 observations where n is the number of samples, and d is the dimensionality of x. mean: ndarray, optional array of shape (d,) frequency means (one for each dimension of X). If not input, this uses the value of the initial mean. lenscale: ndarray, optional array of shape (d,) length scales (one for each dimension of X). If not input, this uses the value of the initial length scale. Returns ------- ndarray: shape (n, 4*nbases) where nbases is number of random rbf bases, again to the nearest larger two power. This is :math:`\partial \phi(\mathbf{x}) / \partial \boldsymbol\mu` ndarray: shape (n, 4*nbases) where nbases is number of random rbf bases, again to the nearest larger two power. This is :math:`\partial \phi(\mathbf{x}) / \partial \mathbf{l}` """
|
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 + mX)
cosVXmmX = np.cos(VX - mX)
dPhi_len = []
dPhi_mean = []
for i, l in enumerate(lenscale):
# Means
dmX = X[:, [i]]
dPhi_mean.append(np.hstack((dmX * sinVXpmX, dmX * cosVXpmX,
-dmX * sinVXmmX, -dmX * cosVXmmX)) /
np.sqrt(2 * self.n))
# Lenscales
indlen = np.zeros(d)
indlen[i] = 1. / l**2
dVX = - self._makeVX(X * indlen) # FIXME make this more efficient?
dPhi_len.append(np.hstack((dVX * sinVXpmX, dVX * cosVXpmX,
dVX * sinVXmmX, dVX * cosVXmmX)) /
np.sqrt(2 * self.n))
dPhi_mean = np.dstack(dPhi_mean) if d != 1 else dPhi_mean[0]
dPhi_len = np.dstack(dPhi_len) if d != 1 else dPhi_len[0]
return dPhi_mean, dPhi_len
|
<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. Parameters X : ndarray (N, d) array of observations where N is the number of samples, and d is the dimensionality of X. *params : optional parameter aguments, these are the parameters of the concatenated bases `in the order` they were concatenated. Returns ------- ndarray : of shape (N, D) where D is the number of basis functions. """
|
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 number of samples, and d is the dimensionality of X. *params : optional parameter aguments, these are the parameters of the concatenated bases `in the order` they were concatenated. Returns ------- list or ndarray : this will be a list of ndarrays if there are multiple parameters, or just an ndarray if there is a single parameter. The ndarrays can have more than two dimensions (i.e. tensors of rank > 2), depending on the dimensions of the basis function parameters. If there are *no* parameters, ``[]`` is returned. """
|
# 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 with respect to the total basis dimensionality
dPhi_dim = (N, D) if g.ndim < 3 else (N, D, g.shape[2])
dPhi = np.zeros(dPhi_dim)
dPhi[:, endinds[i]:endinds[i + 1]] = g
return dPhi
# Get gradients from each basis
for i, base in enumerate(self.bases):
# evaluate gradient and deal with multiple parameter gradients by
# keeping track of the basis index
g, args, sargs = base._grad_popargs(X, *args)
for gg in atleast_tuple(g):
if len(gg) == 0:
continue
yield make_dPhi(i, gg)
|
<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 there are no parameters. """
|
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(filenode, FileNode):
raise VCSError("Given object should be FileNode object, not %s"
% filenode.__class__)
if filenode_old_date and filenode_new_date:
if not filenode_old_date < filenode_new_date:
logging.debug("Generating udiff for filenodes with not increasing "
"dates")
vcs_udiff = unified_diff(filenode_old.content.splitlines(True),
filenode_new.content.splitlines(True),
filenode_old.name,
filenode_new.name,
filenode_old_date,
filenode_old_date)
return vcs_udiff
|
<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 ignore_whitespace: ignore whitespaces in diff """
|
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.changeset, 'raw_id', '0' * 40)
repo = filenode_new.changeset.repository
vcs_gitdiff = repo.get_diff(old_raw_id, new_raw_id, filenode_new.path,
ignore_whitespace)
return vcs_gitdiff
|
<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 DiffProcessor """
|
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)
new_filename = l2[0].lstrip('b/') if len(l1) >= 1 else None
new_rev = l2[1] if len(l2) == 2 else 'new'
filename = old_filename if (old_filename !=
'dev/null') else new_filename
return filename, new_rev, old_rev
except (ValueError, IndexError):
pass
return None, None, 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 _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.next()
continue
chunks = []
filename, old_rev, new_rev = \
self._extract_rev(line, lineiter.next())
files.append({
'filename': filename,
'old_revision': old_rev,
'new_revision': new_rev,
'chunks': chunks
})
line = lineiter.next()
while line:
match = self._chunk_re.match(line)
if not match:
break
lines = []
chunks.append(lines)
old_line, old_end, new_line, new_end = \
[int(x or 1) for x in match.groups()[:-1]]
old_line -= 1
new_line -= 1
context = len(match.groups()) == 5
old_end += old_line
new_end += new_line
if context:
if not skipfirst:
lines.append({
'old_lineno': '...',
'new_lineno': '...',
'action': 'context',
'line': line,
})
else:
skipfirst = False
line = lineiter.next()
while old_line < old_end or new_line < new_end:
if line:
command, line = line[0], line[1:]
else:
command = ' '
affects_old = affects_new = False
# ignore those if we don't expect them
if command in '#@':
continue
elif command == '+':
affects_new = True
action = 'add'
elif command == '-':
affects_old = True
action = 'del'
else:
affects_old = affects_new = True
action = 'unmod'
old_line += affects_old
new_line += affects_new
lines.append({
'old_lineno': affects_old and old_line or '',
'new_lineno': affects_new and new_line or '',
'action': action,
'line': line
})
line = lineiter.next()
except StopIteration:
pass
# highlight inline changes
for file in files:
for chunk in chunks:
lineiter = iter(chunk)
#first = True
try:
while 1:
line = lineiter.next()
if line['action'] != 'unmod':
nextline = lineiter.next()
if nextline['action'] == 'unmod' or \
nextline['action'] == line['action']:
continue
self.differ(line, nextline)
except StopIteration:
pass
return files
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _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]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".")'. These regexps are slightly over-zealous, in that they remove colons and periods unnecessarily. Whitespace is transformed into underscores, and then anything which is not a hyphen or a character that matches \w (alphanumerics and underscore) is removed. """
|
# 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:
self.id_map[link] = nav
|
<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:
return link in self.id_map
|
<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=APICore(
root=root,
nav_class=HALNavigator,
apiname=apiname,
default_curie=default_curie,
session=session,
)
)
if auth:
halnav.authenticate(auth)
halnav.headers.update(DEFAULT_HEADERS)
if headers is not None:
halnav.headers.update(headers)
return halnav
|
<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_url = rel
print('opening', doc_url)
webbrowser.open(doc_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 _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] = utils.LinkList(
(self._navigator_or_thunk(lnk), lnk) for lnk in link)
else:
ld[rel] = self._navigator_or_thunk(link)
return ld
|
<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 doc]
else:
ld[rel] = self._recursively_embed(doc)
return ld
|
<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(
uri=uri,
properties=utils.getpath(doc, '_links.self')
)
curies = utils.getpath(doc, '_links.curies')
state = utils.getstate(doc)
if self_link is None:
nav = OrphanHALNavigator(
link=None,
response=None,
parent=self,
core=self._core,
curies=curies,
state=state,
)
else:
nav = HALNavigator(
link=self_link,
response=None,
core=self._core,
curies=curies,
state=state,
)
if update_state:
nav.state = state
links = self._make_links_from(doc)
if links is not None:
nav._links = links
embedded = self._make_embedded_from(doc)
if embedded is not None:
nav._embedded = embedded
return nav
|
<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.
'''
# resolve relative uris against the current uri
uri = urlparse.urljoin(self.uri, link['href'])
link_obj = Link(uri=uri, properties=link)
if link.get('templated'):
# Can expand into a real HALNavigator
return PartialNavigator(link_obj, core=self._core)
else:
return HALNavigator(link_obj, core=self._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 _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, content_subtype, content_param = utils.parse_media_type(content_type)
for accepted in self.headers.get('Accept', self.DEFAULT_CONTENT_TYPE).split(','):
type, subtype, param = utils.parse_media_type(accepted)
# if either accepted_type or content_type do not
# contain a parameter section, then it will be
# optimistically ignored
matched = (type == content_type) \
and (subtype == content_subtype) \
and (param == content_param or not (param and content_param))
if matched:
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 _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)
self.self.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 _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_parse(response.headers['Content-Type']):
hal_json = self._parse_content(response.text)
else:
raise exc.HALNavigatorError(
message="Unexpected content type! Wanted {0}, got {1}"
.format(self.headers.get('Accept', self.DEFAULT_CONTENT_TYPE),
self.response.headers['content-type']),
nav=self,
status=self.response.status_code,
response=self.response,
)
self._links = self._make_links_from(hal_json)
self._embedded = self._make_embedded_from(hal_json)
# Set properties from new document's self link
self._update_self_link(
hal_json.get('_links', {}).get('self', {}),
response.headers,
)
# Set curies if available
self.curies = dict(
(curie['name'], curie['href'])
for curie in
hal_json.get('_links', {}).get('curies', []))
# Set state by removing HAL attributes
self.state = utils.getstate(hal_json)
|
<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_client.CREATED,
http_client.FOUND,
http_client.SEE_OTHER,
http_client.NO_CONTENT) \
and 'Location' in response.headers:
uri = urlparse.urljoin(self._core.root, response.headers['Location'])
nav = HALNavigator(
link=Link(uri=uri),
core=self._core
)
# We don't ingest the response because we haven't fetched
# the newly created resource yet
elif method in (POST, PUT, PATCH, DELETE):
nav = OrphanHALNavigator(
link=None,
core=self._core,
response=response,
parent=self,
)
nav._ingest_response(response)
elif method == GET:
nav = self
nav._ingest_response(response)
else: # pragma: nocover
assert False, "This shouldn't happen"
return nav
|
<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.update({'Content-Type': 'application/json'})
response = self._core.session.request(
method,
self.uri,
data=body if not isinstance(body, dict) else None,
json=body if isinstance(body, dict) else None,
files=files,
headers=headers,
allow_redirects=False,
)
nav = self._create_navigator(response, raise_exc=raise_exc)
if raise_exc and not response:
raise exc.HALNavigatorError(
message=response.text,
status=response.status_code,
nav=nav, # may be self
response=response,
)
else:
return nav
|
<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 additional headers to send in the request
'''
return self._request(POST, body, raise_exc, headers, **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 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 representing json
`headers` are additional headers to send in the request
'''
return self._request(PUT, body, raise_exc, headers, files)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def 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` may either be a string or a dictionary representing json
`headers` are additional headers to send in the request
'''
return self._request(PATCH, body, raise_exc, headers, files)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def _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, .. math:: \log \sum^K_{k=1} \exp\{x_k\} Parameters X: ndarray 2D array of shape (N, D) to apply the log-sum-exp trick. axis: int, optional Axis to apply the summation along (works the same as axis in numpy.sum). Returns ------- lseX: ndarray results of applying the log-sum-exp trick, this will be shape (D,) if :code:`axis=0` or shape (N,) if :code:`axis=1`. """
|
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{\exp\{X_k\}}{\sum^K_{j=1} \exp\{X_j\}} and is appliedx to each row/column, `k`, of X. Parameters X: ndarray 2D array of shape (N, D) to apply the log-sum-exp trick. axis: int, optional Axis to apply the summation along (works the same as axis in numpy.sum). Returns ------- smX: ndarray results of applying the log-sum-exp trick, this will be shape (N, D), and each row will sum to 1 if :code:`axis=1` or each column will sum to 1 if :code:`axis=0`. """
|
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, 22926):
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 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_discover(n):
formats.append('discover')
return formats
|
<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 should provide the following named groups: prefix Object prefix, such as a namespace member Object member name arguments Declaration arguments, if this is a callable constraint :param signature: construct signature :type signature: string """
|
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:
arguments = re.split(r'\,\s+', groups['arguments'])
return DotNetSignature(
prefix=groups.get('prefix', None),
member=groups.get('member', None),
arguments=arguments
)
raise ValueError('Could not parse signature: {0}'.format(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 handle_signature(self, sig, signode):
"""Parses out pieces from construct signatures Parses out prefix and argument list from construct definition. This is assuming that the .NET languages this will support will be in a common format, such as:: The namespace and class will be determined by the nesting of rST directives. Returns Altered :py:data:`signode` with attributes corrected for rST nesting/etc """
|
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', None)
if prefix is not None:
sig.prefix = prefix
signode['object'] = sig.member
signode['prefix'] = sig.prefix
signode['fullname'] = sig.full_name()
# Prefix modifiers
if self.display_prefix:
signode += addnodes.desc_annotation(self.display_prefix,
self.display_prefix)
for prefix in ['public', 'protected', 'static']:
if prefix in self.options:
signode += addnodes.desc_annotation(prefix + ' ',
prefix + ' ')
# Show prefix only on shorter declarations
if sig.prefix is not None and not self.has_arguments:
signode += addnodes.desc_addname(sig.prefix + '.', sig.prefix + '.')
signode += addnodes.desc_name(sig.member, sig.member)
if self.has_arguments:
if not sig.arguments:
signode += addnodes.desc_parameterlist()
else:
# TODO replace this
_pseudo_parse_arglist(signode, ', '.join(sig.arguments))
if isinstance(self, DotNetObjectNested):
return sig.full_name(), sig.full_name()
return sig.full_name(), sig.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 name to create objects and nodes that are type and name unique. """
|
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.document.note_explicit_target(signode)
# Update domain objects
objects = self.env.domaindata['dn']['objects']
try:
found_obj = objects[full_name]
(found_doc, found_type) = found_obj
self.state_machine.reporter.warning(
('duplicate object definition of {obj_type} {obj_name}'
'other instance in {path}'
.format(obj_type=found_type, obj_name=full_name,
path=self.env.doc2path(found_doc))),
line=self.lineno)
except KeyError:
pass
finally:
objects[full_name] = (self.env.docname, self.objtype)
index_text = self.get_index_text(None, name)
if index_text:
entry = ('single', index_text, full_name, '')
if SPHINX_VERSION_14:
entry = ('single', index_text, full_name, '', None)
self.indexnode['entries'].append(entry)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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['namespace'] = obj_ns
msg = '{name} ({namespace} {obj_type})'
except ValueError:
pass
return msg.format(**parts)
|
<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 of nodes with the signature nodes. We are going to remove them if this is a hidden declaration. """
|
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):
node.children.pop(m)
return nodes
|
<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 prefix history. With each nested element, we add the prefix to a list of prefixes. When we exit that object's nesting level, :py:meth:`after_content` is triggered and the prefix is removed from the end of the list. dn:prefix Current prefix. This should reflect the last element in the prefix history """
|
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]
finally:
self.env.ref_context['dn:prefix'] = 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 Sphinx reference syntax of ``:ref:`Title<Link>```, where a reference to ``Link`` is created with title ``Title``, causes problems for the generic .NET syntax of ``:dn:cls:`FooBar<T>```. So, here we assume that ``<T>`` was the generic declaration, and fix the reference. This also uses :py:cls:`AnyXRefRole` to add `ref_context` onto the refnode. Add data there that you need it on refnodes. This method also resolves special reference operators ``~`` and ``.`` """
|
result = super(DotNetXRefRole, self).process_link(env, refnode,
has_explicit_title,
title, target)
(title, target) = result
if not has_explicit_title:
# If the first character is a tilde, don't display the parent name
title = title.lstrip('.')
target = target.lstrip('~')
if title[0:1] == '~':
title = title[1:]
dot = title.rfind('.')
if dot != -1:
title = title[dot + 1:]
else:
if title != target:
target = title = '{title}<{target}>'.format(title=title,
target=target)
return title, target
|
<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: Object name :param obj_type: Object type :param searchorder: Search for exact match """
|
# 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']
newname = None
fullname = name
if prefix is not None:
fullname = '.'.join([prefix, name])
if searchorder == 1:
if prefix and fullname in objects and objects[fullname][1] in object_types:
newname = fullname
elif name in objects and objects[name][1] in object_types:
newname = name
else:
try:
matches = [obj_name for obj_name in objects
if obj_name.endswith('.' + name)]
newname = matches.pop()
except IndexError:
pass
else:
if name in objects:
newname = name
elif prefix and fullname in objects:
newname = fullname
if newname is None:
return None
return newname, objects.get(newname, (None, 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 resolve_any_xref(self, env, fromdocname, builder, target, node, contnode):
"""Look for any references, without object type This always searches in "refspecific" mode """
|
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], name, contnode,
name)))
return results
|
<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 channel list is empty. """
|
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()) > 1
if parent_end.tag == "{%s}p" % namespaces['text']:
# more than one child in the containing paragraph ?
# we keep the boundary
result_end = len(parent_end.getchildren()) > 1
return result_start, result_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 __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 namespaces from original docs
for tree_root in self.tree_roots:
self.namespaces.update(tree_root.nsmap)
# remove any "root" namespace as lxml.xpath do not support them
self.namespaces.pop(None, None)
# declare the genshi namespace
self.namespaces['py'] = GENSHI_URI
# declare our own namespace
self.namespaces['py3o'] = PY3O_URI
|
<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.append(e.text)
return res
|
<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 instructions
d = Decoder()
res = []
for_insts = {}
tmp = res
# Create a hierarchie with for loops
for i in instructions:
if i == '/for':
tmp = tmp.parent
else:
# Decode the instruction:
# inst.values() -> forloop variable
# inst.keys() -> forloop iterable
var, it = d.decode_py3o_instruction(i)
# we keep all inst in a dict
for_insts[var] = it
# get the variable defined inside the for loop
for_vars = [v for v in user_variables if v.split('.')[0] == var]
# create a new ForList for the forloop and add it to the
# children or list
new_list = ForList(it, var)
if isinstance(tmp, list):
# We have a root for loop
res.append(new_list)
tmp = res[-1]
tmp.parent = res
else:
tmp.add_child(new_list)
tmp = new_list
# Add the attributes to our new child
for v in for_vars:
tmp.add_attr(v)
# Insert global variable in a second list
user_vars = [v for v in user_variables
if not v.split('.')[0] in for_insts.keys()]
return res, user_vars
|
<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 be ready for Genshi replacement """
|
# 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):
if not link[0].text == py3o_base:
msg = "url and text do not match in '%s'" % link.text
raise TemplateException(msg)
else:
raise TemplateException("Link text not found")
# find out if the instruction is inside a table
parent = link.getparent()
keep_start_boundary = False
keep_end_boundary = False
if parent.getparent() is not None and parent.getparent().tag == (
"{%s}table-cell" % self.namespaces['table']
):
# we are in a table
opening_paragraph = parent
opening_cell = opening_paragraph.getparent()
# same for closing
closing_paragraph = closing_link.getparent()
closing_cell = closing_paragraph.getparent()
if opening_cell == closing_cell:
# block is fully in a single cell
opening_row = opening_paragraph
closing_row = closing_paragraph
else:
opening_row = opening_cell.getparent()
closing_row = closing_cell.getparent()
elif parent.tag == "{%s}p" % self.namespaces['text']:
# if we are using text we want to keep start/end nodes
keep_start_boundary, keep_end_boundary = detect_keep_boundary(
link, closing_link, self.namespaces
)
# we are in a text paragraph
opening_row = parent
closing_row = closing_link.getparent()
else:
raise NotImplementedError(
"We handle urls in tables or text paragraph only"
)
# max split is one
instruction, instruction_value = py3o_base.split("=", 1)
instruction_value = instruction_value.strip('"')
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}%s' % (GENSHI_URI, instruction)] = instruction_value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI},
)
link.getparent().remove(link)
closing_link.getparent().remove(closing_link)
try:
move_siblings(
opening_row, closing_row, genshi_node,
keep_start_boundary=keep_start_boundary,
keep_end_boundary=keep_end_boundary,
)
except ValueError as e:
log.exception(e)
raise TemplateException("Could not move siblings for '%s'" %
py3o_base)
|
<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 list of user variable names without starting 'py3o.'"""
|
# 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()
value = userfield.attrib[
'{%s}name' % self.namespaces['text']
][5:]
value_type = self.field_info[value]['value_type']
# we try to override global var type with local settings
value_type_attr = '{%s}value-type' % self.namespaces['office']
rec = 0
parent_node = parent
# special case for float which has a value info on top level
# overriding local value
found_node = False
while rec <= 5:
if parent_node is None:
break
# find an ancestor with an office:value-type attribute
# this is the case when you are inside a table
if value_type_attr in parent_node.attrib:
value_type = parent_node.attrib[value_type_attr]
found_node = True
break
rec += 1
parent_node = parent_node.getparent()
if value_type == 'float':
value_attr = '{%s}value' % self.namespaces['office']
rec = 0
if found_node:
parent_node.attrib[value_attr] = "${%s}" % value
else:
parent_node = userfield
while rec <= 7:
if parent_node is None:
break
if value_attr in parent_node.attrib:
parent_node.attrib[value_attr] = "${%s}" % value
break
rec += 1
parent_node = parent_node.getparent()
value = "format_float(%s)" % value
if value_type == 'percentage':
del parent_node.attrib[value_attr]
value = "format_percentage(%s)" % value
parent_node.attrib[value_type_attr] = "string"
attribs = dict()
attribs['{%s}strip' % GENSHI_URI] = 'True'
attribs['{%s}content' % GENSHI_URI] = value
genshi_node = lxml.etree.Element(
'span',
attrib=attribs,
nsmap={'py': GENSHI_URI}
)
if userfield.tail:
genshi_node.tail = userfield.tail
parent.replace(userfield, genshi_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 __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:
continue
for identifier in self.images.keys():
# Add a manifest:file-entry tag.
lxml.etree.SubElement(
manifest_e[0],
'{%s}file-entry' % self.namespaces['manifest'],
attrib={
'{%s}full-path' % self.namespaces['manifest']: (
PY3O_IMAGE_PREFIX + identifier
),
'{%s}media-type' % self.namespaces['manifest']: '',
}
)
|
<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 remove it and
# consider our caller must pre - render its variables to the desired
# locale...?
new_data = dict(
decimal=decimal,
format_float=(
lambda val: (
isinstance(
val, decimal.Decimal
) or isinstance(
val, float
)
) and str(val).replace('.', ',') or val
),
format_percentage=(
lambda val: ("%0.2f %%" % val).replace('.', ',')
)
)
# Soft page breaks are hints for applications for rendering a page
# break. Soft page breaks in for loops may compromise the paragraph
# formatting especially the margins. Open-/LibreOffice will regenerate
# the page breaks when displaying the document. Therefore it is save to
# remove them.
self.remove_soft_breaks()
# first we need to transform the py3o template into a valid
# Genshi template.
starting_tags, closing_tags = self.handle_instructions(
self.content_trees,
self.namespaces
)
parents = [tag[0].getparent() for tag in starting_tags]
linknum = len(parents)
parentnum = len(set(parents))
if not linknum == parentnum:
raise TemplateException(
"Every py3o link instruction should be on its own line"
)
for link, py3o_base in starting_tags:
self.handle_link(
link,
py3o_base,
closing_tags[id(link)]
)
self.__prepare_userfield_decl()
self.__prepare_usertexts()
self.__replace_image_links()
self.__add_images_to_manifest()
for fnum, content_tree in enumerate(self.content_trees):
content = lxml.etree.tostring(content_tree.getroot())
if self.ignore_undefined_variables:
template = MarkupTemplate(content, lookup='lenient')
else:
template = MarkupTemplate(content)
# then we need to render the genshi template itself by
# providing the data to genshi
template_dict = {}
template_dict.update(data.items())
template_dict.update(new_data.items())
self.output_streams.append(
(
self.templated_files[fnum],
template.generate(**template_dict)
)
)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 being the values accessible to your report. @type data: dictionary """
|
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 the template by setting "py3o.[identifier]" as the name of that image. @type identifier: string @param path: Image path on the file system @type path: string """
|
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")
fname, output_stream = self.output_streams[
self.templated_files.index(info_zip.filename)
]
transformer = get_list_transformer(self.namespaces)
remapped_stream = output_stream | transformer
# write the whole stream to it
for chunk in remapped_stream.serialize():
streamout.write(chunk.encode('utf-8'))
yield True
# close the temp file to flush all data and make sure we get
# it back when writing to the zip archive.
streamout.close()
# write the full file to archive
out.write(streamout.name, fname)
# remove temp file
os.unlink(streamout.name)
else:
# Copy other files straight from the source archive.
out.writestr(info_zip, self.infile.read(info_zip.filename))
# Save images in the "Pictures" sub-directory of the archive.
for identifier, data in self.images.items():
out.writestr(PY3O_IMAGE_PREFIX + identifier, data)
# close the zipfile before leaving
out.close()
yield 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 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(args.input, markov, args.progress)
save(markov, args.output, args)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 + '.tmp' + ext
save(markov, tmp, args)
replace(tmp, args.state)
else:
save(markov, args.output, args)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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
args.reply_mode = ReplyMode.START
elif args.reply:
args.reply_to = args.reply
args.reply_mode = ReplyMode.REPLY
else:
args.reply_to = None
args.reply_mode = ReplyMode.END
markov = load(MarkovText, args.state, args)
ss = range(args.count)
if args.progress:
title = truncate(args.output.name, BAR_DESC_SIZE - 1, False)
ss = tqdm(ss, desc=title,
bar_format=BAR_FORMAT, dynamic_ncols=True)
if not args.format:
markov.formatter = lambda x: x
for _ in ss:
data = markov(
args.words,
state_size=args.state_size,
reply_to=args.reply_to,
reply_mode=args.reply_mode
)
if data:
print(data)
|
<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('image'))
if len(sys.argv if args is None else args) <= 1:
parser.print_help()
sys.exit(1)
args = parser.parse_args(args)
dtype = globals()[args.dtype]
try:
set_args(args)
cmd = getattr(dtype, 'cmd_' + args.command)
cmd(args)
except ValueError as err:
print(str(err), file=sys.stderr)
sys.exit(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 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.