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 all_posts(self):
"""Get all_posts, reloading the site if needed.""" |
rev = self.db.get('site:rev')
if int(rev) != self.revision:
self.reload_site()
return self._all_posts |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pages(self):
"""Get pages, reloading the site if needed.""" |
rev = self.db.get('site:rev')
if int(rev) != self.revision:
self.reload_site()
return self._pages |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def options(self):
""" Dictionary of options which affect the curve fitting algorithm. Must contain the key `fit_function` which must be set to the function that... |
if not hasattr(self, '_options'):
self._options = {
'fit_function': scipy.optimize.curve_fit,
'maxfev': 1000,
}
return self._options |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def limits(self):
""" Limits to use for the independent variable whenever creating a linespace, plot, etc. Defaults to `(-x, x)` where `x` is the largest absolut... |
if not hasattr(self, '_limits'):
xmax = max(abs(self.data.array[0]))
xmin = min(self.data.array[0])
x_error = self.data.error[0]
if isinstance(x_error, numpy.ndarray):
if x_error.ndim == 0: xmax = xmax + x_error
if xmin < 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 fixed_values(self):
""" A flat tuple of all values corresponding to `scipy_data_fitting.Fit.fixed_parameters` and `scipy_data_fitting.Fit.constants` after ap... |
values = []
values.extend([ prefix_factor(param) * param['value'] for param in self.fixed_parameters ])
values.extend([ prefix_factor(const) * get_constant(const['value']) for const in self.constants ])
return tuple(values) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def function(self):
""" The function passed to the `fit_function` specified in `scipy_data_fitting.Fit.options`, and used by `scipy_data_fitting.Fit.pointspace` ... |
if not hasattr(self,'_function'):
function = self.model.lambdify(self.expression, self.all_variables, **self.lambdify_options)
self._function = lambda *x: function(*(x + self.fixed_values))
return self._function |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def curve_fit(self):
""" Fits `scipy_data_fitting.Fit.function` to the data and returns the output from the specified curve fit function. See `scipy_data_fitting... |
if not hasattr(self,'_curve_fit'):
options = self.options.copy()
fit_function = options.pop('fit_function')
independent_values = self.data.array[0]
dependent_values = self.data.array[1]
if fit_function == 'lmfit':
self._curve_fit = lm... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fitted_parameters(self):
""" A tuple of fitted values for the `scipy_data_fitting.Fit.fitting_parameters`. The values in this tuple are not scaled by the pre... |
if hasattr(self,'_fitted_parameters'): return self._fitted_parameters
if not self.fitting_parameters: return tuple()
if self.options['fit_function'] == 'lmfit':
return tuple( self.curve_fit.params[key].value for key in sorted(self.curve_fit.params) )
else:
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 fitted_function(self):
""" A function of the single independent variable after partially evaluating `scipy_data_fitting.Fit.function` at the `scipy_data_fitt... |
function = self.function
fitted_parameters = self.fitted_parameters
return lambda x: function(x, *fitted_parameters) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def computed_fitting_parameters(self):
""" A list identical to what is set with `scipy_data_fitting.Fit.fitting_parameters`, but in each dictionary, the key `val... |
fitted_parameters = []
for (i, v) in enumerate(self.fitting_parameters):
param = v.copy()
param['value'] = self.fitted_parameters[i] * prefix_factor(param)**(-1)
fitted_parameters.append(param)
return fitted_parameters |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pointspace(self, **kwargs):
""" Returns a dictionary with the keys `data` and `fit`. `data` is just `scipy_data_fitting.Data.array`. `fit` is a two row [`num... |
scale_array = numpy.array([
[prefix_factor(self.independent)**(-1)],
[prefix_factor(self.dependent)**(-1)]
])
linspace = numpy.linspace(self.limits[0], self.limits[1], **kwargs)
return {
'data': self.data.array * scale_array,
'fit': numpy.arr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_json(self, path, points=50, meta=None):
""" Write the results of the fit to a json file at `path`. `points` will define the length of the `fit` array. If ... |
pointspace = self.pointspace(num=points)
fit_points = numpy.dstack(pointspace['fit'])[0]
data_points = numpy.dstack(pointspace['data'])[0]
fit = [ [ point[0], point[1] ] for point in fit_points ]
data = [ [ point[0], point[1] ] for point in data_points ]
obj = {'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 clean_for_doc(nb):
""" Cleans the notebook to be suitable for inclusion in the docs. """ |
new_cells = []
for cell in nb.worksheets[0].cells:
# Remove the pylab inline line.
if "input" in cell and cell["input"].strip() == "%pylab inline":
continue
# Remove output resulting from the stream/trace method chaining.
if "outputs" in cell:
outputs = [... |
<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_call_back(self, func):
"""sets callback function for updating the plot. in the callback function implement the logic of reading of serial input also the ... |
self.timer.add_callback(func)
self.timer.start() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_self(self, func):
"""define your callback function with the decorator @plotter.plot_self. in the callback function set the data of lines in the plot usi... |
def func_wrapper():
func()
try:
self.manager.canvas.draw()
except ValueError as ve:
print(ve)
pass
except RuntimeError as RtE:
print(RtE)
pass
except Exception as e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter(cls, **kwargs):
""" The meat. Filtering using Django model style syntax. All kwargs are translated into attributes on the underlying objects. If the a... |
qs = cls.all()
for key in kwargs:
qs = filter(lambda i: make_compare(key, kwargs[key], i), qs)
return qs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def reconnect_redis(self):
'''Reconnect to redis.
:return: Redis client instance
:rettype: redis.Redis
'''
if self.shared_client and Storage.storage:
return Storage.storage
storage = Redis(
port=self.context.config.REDIS_RESULT_STORAGE_SERVER_PO... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_key_from_request(self):
'''Return a key for the current request url.
:return: The storage key for the current url
:rettype: string
'''
path = "result:%s" % self.context.request.url
if self.is_auto_webp():
path += '/webp'
return path |
<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_max_age(self):
'''Return the TTL of the current request.
:returns: The TTL value for the current request.
:rtype: int
'''
default_ttl = self.context.config.RESULT_STORAGE_EXPIRATION_SECONDS
if self.context.request.max_age == 0:
return self.context.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 put(self, bytes):
'''Save to redis
:param bytes: Bytes to write to the storage.
:return: Redis key for the current url
:rettype: string
'''
key = self.get_key_from_request()
result_ttl = self.get_max_age()
logger.debug(
"[REDIS_RESULT_ST... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get(self):
'''Get the item from redis.'''
key = self.get_key_from_request()
result = self.get_storage().get(key)
return result if result else None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def last_updated(self):
'''Return the last_updated time of the current request item
:return: A DateTime object
:rettype: datetetime.datetime
'''
key = self.get_key_from_request()
max_age = self.get_max_age()
if max_age == 0:
return datetime.fromtime... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_of_lists_to_dict(l):
""" Convert list of key,value lists to dict [['id', 1], ['id', 2], ['id', 3], ['foo': 4]] {'id': [1, 2, 3], 'foo': [4]} """ |
d = {}
for key, val in l:
d.setdefault(key, []).append(val)
return 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 dumps(number):
"""Dumps an integer into a base36 string. :param number: the 10-based integer. :returns: the base36 string. """ |
if not isinstance(number, integer_types):
raise TypeError('number must be an integer')
if number < 0:
return '-' + dumps(-number)
value = ''
while number != 0:
number, index = divmod(number, len(alphabet))
value = alphabet[index] + value
return value or '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 acl_middleware(callback):
"""Returns a aiohttp_auth.acl middleware factory for use by the aiohttp application object. Args: callback: This is a callable whic... |
async def _acl_middleware_factory(app, handler):
async def _middleware_handler(request):
# Save the policy in the request
request[GROUPS_KEY] = callback
# Call the next handler in the chain
return await handler(request)
return _middleware_handler
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def get_user_groups(request):
"""Returns the groups that the user in this request has access to. This function gets the user id from the auth.get_auth func... |
acl_callback = request.get(GROUPS_KEY)
if acl_callback is None:
raise RuntimeError('acl_middleware not installed')
user_id = await get_auth(request)
groups = await acl_callback(user_id)
if groups is None:
return None
user_groups = (Group.AuthenticatedUser, user_id) if user_id ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def get_permitted(request, permission, context):
"""Returns true if the one of the groups in the request has the requested permission. The function takes a... |
groups = await get_user_groups(request)
if groups is None:
return False
for action, group, permissions in context:
if group in groups:
if permission in permissions:
return action == Permission.Allow
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 molecular_weight(elements):
""" Return molecular weight of a molecule. Parameters elements : numpy.ndarray An array of all elements (type: str) in a molecule... |
return (np.array([atomic_mass[i.upper()] for i in elements]).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 dlf_notation(atom_key):
"""Return element for atom key using DL_F notation.""" |
split = list(atom_key)
element = ''
number = False
count = 0
while number is False:
element = "".join((element, split[count]))
count += 1
if is_number(split[count]) is True:
number = True
# In case of for example Material Studio output, integers can also be
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def opls_notation(atom_key):
"""Return element for OPLS forcefield atom key.""" |
# warning for Ne, He, Na types overlap
conflicts = ['ne', 'he', 'na']
if atom_key in conflicts:
raise _AtomKeyConflict((
"One of the OPLS conflicting "
"atom_keys has occured '{0}'. "
"For how to solve this issue see the manual or "
"MolecularSystem._... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decipher_atom_key(atom_key, forcefield):
""" Return element for deciphered atom key. This functions checks if the forcfield specified by user is supported an... |
load_funcs = {
'DLF': dlf_notation,
'DL_F': dlf_notation,
'OPLS': opls_notation,
'OPLSAA': opls_notation,
'OPLS2005': opls_notation,
'OPLS3': opls_notation,
}
if forcefield.upper() in load_funcs.keys():
return load_funcs[forcefield.upper()](atom_key)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shift_com(elements, coordinates, com_adjust=np.zeros(3)):
""" Return coordinates translated by some vector. Parameters elements : numpy.ndarray An array of a... |
com = center_of_mass(elements, coordinates)
com = np.array([com - com_adjust] * coordinates.shape[0])
return coordinates - com |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def max_dim(elements, coordinates):
""" Return the maximum diameter of a molecule. Parameters elements : numpy.ndarray An array of all elements (type: str) in a ... |
atom_vdw_vertical = np.matrix(
[[atomic_vdw_radius[i.upper()]] for i in elements])
atom_vdw_horizontal = np.matrix(
[atomic_vdw_radius[i.upper()] for i in elements])
dist_matrix = euclidean_distances(coordinates, coordinates)
vdw_matrix = atom_vdw_vertical + atom_vdw_horizontal
re_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 pore_diameter(elements, coordinates, com=None):
"""Return pore diameter of a molecule.""" |
if com is None:
com = center_of_mass(elements, coordinates)
atom_vdw = np.array([[atomic_vdw_radius[x.upper()]] for x in elements])
dist_matrix = euclidean_distances(coordinates, com.reshape(1, -1))
re_dist_matrix = dist_matrix - atom_vdw
index = np.argmin(re_dist_matrix)
pored = re_dis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def opt_pore_diameter(elements, coordinates, bounds=None, com=None, **kwargs):
"""Return optimised pore diameter and it's COM.""" |
args = elements, coordinates
if com is not None:
pass
else:
com = center_of_mass(elements, coordinates)
if bounds is None:
pore_r = pore_diameter(elements, coordinates, com=com)[0] / 2
bounds = (
(com[0]-pore_r, com[0]+pore_r),
(com[1]-pore_r, com... |
<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_gyration_tensor(elements, coordinates):
""" Return the gyration tensor of a molecule. The gyration tensor should be invariant to the molecule's position.... |
# First calculate COM for correction.
com = centre_of_mass(elements, coordinates)
# Correct the coordinates for the COM.
coordinates = coordinates - com
# Calculate diagonal and then other values of the matrix.
diag = np.sum(coordinates**2, axis=0)
xy = np.sum(coordinates[:, 0] * coordinate... |
<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_inertia_tensor(elements, coordinates):
""" Return the tensor of inertia a molecule. Parameters elements : numpy.ndarray The array containing the molecule... |
pow2 = coordinates**2
molecular_weight = np.array(
[[atomic_mass[e.upper()]] for e in elements])
diag_1 = np.sum(molecular_weight * (pow2[:, 1] + pow2[:, 2]))
diag_2 = np.sum(molecular_weight * (pow2[:, 0] + pow2[:, 2]))
diag_3 = np.sum(molecular_weight * (pow2[:, 0] + pow2[:, 1]))
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 normalize_vector(vector):
""" Normalize a vector. A new vector is returned, the original vector is not modified. Parameters vector : np.array The vector to b... |
v = np.divide(vector, np.linalg.norm(vector))
return np.round(v, decimals=4) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rotation_matrix_arbitrary_axis(angle, axis):
""" Return a rotation matrix of `angle` radians about `axis`. Parameters angle : int or float The size of the ro... |
axis = normalize_vector(axis)
a = np.cos(angle / 2)
b, c, d = axis * np.sin(angle / 2)
e11 = np.square(a) + np.square(b) - np.square(c) - np.square(d)
e12 = 2 * (b * c - a * d)
e13 = 2 * (b * d + a * c)
e21 = 2 * (b * c + a * d)
e22 = np.square(a) + np.square(c) - np.square(b) - np.s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unit_cell_to_lattice_array(cryst):
"""Return parallelpiped unit cell lattice matrix.""" |
a_, b_, c_, alpha, beta, gamma = cryst
# Convert angles from degrees to radians.
r_alpha = np.deg2rad(alpha)
r_beta = np.deg2rad(beta)
r_gamma = np.deg2rad(gamma)
# Calculate unit cell volume that is neccessary.
volume = a_ * b_ * c_ * (
1 - np.cos(r_alpha)**2 - np.cos(r_beta)**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 lattice_array_to_unit_cell(lattice_array):
"""Return crystallographic param. from unit cell lattice matrix.""" |
cell_lengths = np.sqrt(np.sum(lattice_array**2, axis=0))
gamma_r = np.arccos(lattice_array[0][1] / cell_lengths[1])
beta_r = np.arccos(lattice_array[0][2] / cell_lengths[2])
alpha_r = np.arccos(
lattice_array[1][2] * np.sin(gamma_r) / cell_lengths[2]
+ np.cos(beta_r) * np.cos(gamma_r)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fractional_from_cartesian(coordinate, lattice_array):
"""Return a fractional coordinate from a cartesian one.""" |
deorthogonalisation_M = np.matrix(np.linalg.inv(lattice_array))
fractional = deorthogonalisation_M * coordinate.reshape(-1, 1)
return np.array(fractional.reshape(1, -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 cartisian_from_fractional(coordinate, lattice_array):
"""Return cartesian coordinate from a fractional one.""" |
orthogonalisation_M = np.matrix(lattice_array)
orthogonal = orthogonalisation_M * coordinate.reshape(-1, 1)
return np.array(orthogonal.reshape(1, -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 cart2frac_all(coordinates, lattice_array):
"""Convert all cartesian coordinates to fractional.""" |
frac_coordinates = deepcopy(coordinates)
for coord in range(frac_coordinates.shape[0]):
frac_coordinates[coord] = fractional_from_cartesian(
frac_coordinates[coord], lattice_array)
return frac_coordinates |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def frac2cart_all(frac_coordinates, lattice_array):
"""Convert all fractional coordinates to cartesian.""" |
coordinates = deepcopy(frac_coordinates)
for coord in range(coordinates.shape[0]):
coordinates[coord] = cartisian_from_fractional(coordinates[coord],
lattice_array)
return coordinates |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def angle_between_vectors(x, y):
"""Calculate the angle between two vectors x and y.""" |
first_step = abs(x[0] * y[0] + x[1] * y[1] + x[2] * y[2]) / (
np.sqrt(x[0]**2 + x[1]**2 + x[2]**2) *
np.sqrt(y[0]**2 + y[1]**2 + y[2]**2))
second_step = np.arccos(first_step)
return (second_step) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def vector_analysis(vector, coordinates, elements_vdw, increment=1.0):
"""Analyse a sampling vector's path for window analysis purpose.""" |
# Calculate number of chunks if vector length is divided by increment.
chunks = int(np.linalg.norm(vector) // increment)
# Create a single chunk.
chunk = vector / chunks
# Calculate set of points on vector's path every increment.
vector_pathway = np.array([chunk * i for i in range(chunks + 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 optimise_xy(xy, *args):
"""Return negative pore diameter for x and y coordinates optimisation.""" |
z, elements, coordinates = args
window_com = np.array([xy[0], xy[1], z])
return -pore_diameter(elements, coordinates, com=window_com)[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 optimise_z(z, *args):
"""Return pore diameter for coordinates optimisation in z direction.""" |
x, y, elements, coordinates = args
window_com = np.array([x, y, z])
return pore_diameter(elements, coordinates, com=window_com)[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 rand(self, n=1):
""" Generate random samples from the distribution Parameters n : int, optional(default=1) The number of samples to generate Returns ------- ... |
if n == 1:
return self._rand1()
else:
out = np.empty((n, self._p, self._p))
for i in range(n):
out[i] = self._rand1()
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _c0(self):
"the logarithm of normalizing constant in pdf"
h_df = self.df / 2
p, S = self._p, self.S
return h_df * (logdet(S) + p * logtwo) + lpgamma(p, h_df) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _genA(self):
""" Generate the matrix A in the Bartlett decomposition A is a lower triangular matrix, with A(i, j) ~ sqrt of Chisq(df - i + 1) when i == j ~ N... |
p, df = self._p, self.df
A = np.zeros((p, p))
for i in range(p):
A[i, i] = sqrt(st.chi2.rvs(df - i))
for j in range(p-1):
for i in range(j+1, p):
A[i, j] = np.random.randn()
return 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 _rand1(self):
"generate a single random sample"
Z = _unwhiten_cf(self._S_cf, self._genA())
return Z.dot(Z.T) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_file(self, filepath):
""" This function opens any type of a readable file and decompose the file object into a list, for each line, of lists containing ... |
self.file_path = filepath
_, self.file_type = os.path.splitext(filepath)
_, self.file_name = os.path.split(filepath)
with open(filepath) as ffile:
self.file_content = ffile.readlines()
return (self._load_funcs[self.file_type]()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump2json(self, obj, filepath, override=False, **kwargs):
""" Dump a dictionary into a JSON dictionary. Uses the json.dump() function. Parameters obj : :clas... |
# We make sure that the object passed by the user is a dictionary.
if isinstance(obj, dict):
pass
else:
raise _NotADictionary(
"This function only accepts dictionaries as input")
# We check if the filepath has a json extenstion, if not we add it.
... |
<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, data, update=False, **kwargs):
""" Creates a new object pretreated input data. .. code-block:: python DBSession.sacrud(Users).create({'name': 'V... |
data = unjson(data)
if update is True:
obj = get_obj_by_request_data(self.session, self.table, data)
else:
obj = None
return self._add(obj, data, **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 read(self, *pk):
""" Return a list of entries in the table or single entry if there is an pk. .. code-block:: python # All users DBSession.sacrud(Users).read... |
pk = [unjson(obj) for obj in pk]
if len(pk) == 1: # like ([1,2,3,4,5], )
return get_obj(self.session, self.table, pk[0])
elif len(pk) > 1: # like (1, 2, 3, 4, 5)
return get_obj(self.session, self.table, pk)
return self.session.query(self.table) |
<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(self, obj, data, **kwargs):
""" Update the object directly. .. code-block:: python DBSession.sacrud(Users)._add(UserObj, {'name': 'Gennady'}) """ |
if isinstance(obj, sqlalchemy.orm.query.Query):
obj = obj.one()
obj = self.preprocessing(obj=obj or self.table)\
.add(self.session, data, self.table)
self.session.add(obj)
if kwargs.get('commit', self.commit) is True:
try:
self.session... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _delete(self, obj, **kwargs):
""" Delete the object directly. .. code-block:: python DBSession.sacrud(Users)._delete(UserObj) If you no needed commit session... |
if isinstance(obj, sqlalchemy.orm.query.Query):
obj = obj.one()
obj = self.preprocessing(obj=obj).delete()
self.session.delete(obj)
if kwargs.get('commit', self.commit) is True:
try:
self.session.commit()
except AssertionError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authenticated(self, user_token, **validation_context):
"""Checks if user is authenticated using token passed in argument :param user_token: string representi... |
token = self.token_storage.get(user_token)
if token and token.validate(user_token, **validation_context):
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 group_authenticated(self, user_token, group):
"""Checks if user represented by token is in group. :param user_token: string representing token :param group: ... |
if self.authenticated(user_token):
token = self.token_storage.get(user_token)
groups = self.get_groups(token.username)
if group in groups:
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_groups(self, username):
"""Returns list of groups in which user is. :param username: name of Linux user """ |
groups = []
for group in grp.getgrall():
if username in group.gr_mem:
groups.append(group.gr_name)
return groups |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def auth_required(self, view):
"""Decorator which checks if user is authenticated Decorator for Flask's view which blocks not authenticated requests :param view:... |
@functools.wraps(view)
def decorated(*args, **kwargs):
log.info("Trying to get access to protected resource: '%s'", view.__name__)
if request.method == 'POST':
token = request.form['token']
if self.development or self.authenticated(token):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def group_required(self, group):
"""Decorator which checks if user is in group Decorator for Flask's view which blocks requests from not authenticated users or i... |
def decorator(view):
@functools.wraps(view)
def decorated(*args, **kwargs):
log.info("Trying to get access to resource: %s protected by group: %s", view.__name__, group)
if request.method == 'POST':
token = request.form['token']
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pyc2py(filename):
""" Find corresponding .py name given a .pyc or .pyo """ |
if re.match(".*py[co]$", filename):
if PYTHON3:
return re.sub(r'(.*)__pycache__/(.+)\.cpython-%s.py[co]$' % PYVER,
'\\1\\2.py',
filename)
else:
return filename[:-1]
return 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 clear_file_cache(filename=None):
"""Clear the file cache. If no filename is given clear it entirely. if a filename is given, clear just that filename.""" |
global file_cache, file2file_remap, file2file_remap_lines
if filename is not None:
if filename in file_cache:
del file_cache[filename]
pass
else:
file_cache = {}
file2file_remap = {}
file2file_remap_lines = {}
pass
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 clear_file_format_cache():
"""Remove syntax-formatted lines in the cache. Use this when you change the Pygments syntax or Token formatting and want to redo h... |
for fname, cache_info in file_cache.items():
for format, lines in cache_info.lines.items():
if 'plain' == format: continue
file_cache[fname].lines[format] = None
pass
pass
pass |
<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_script(script, text, opts={}):
"""Cache script if it is not already cached.""" |
global script_cache
if script not in script_cache:
update_script_cache(script, text, opts)
pass
return script |
<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_file(filename, reload_on_change=False, opts=default_opts):
"""Cache filename if it is not already cached. Return the expanded filename for it in the ca... |
filename = pyc2py(filename)
if filename in file_cache:
if reload_on_change: checkcache(filename)
pass
else:
opts['use_linecache_lines'] = True
update_cache(filename, opts)
pass
if filename in file_cache:
return file_cache[filename].path
else: return 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 is_cached(file_or_script):
"""Return True if file_or_script is cached""" |
if isinstance(file_or_script, str):
return unmap_file(file_or_script) in file_cache
else:
return is_cached_script(file_or_script)
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 path(filename):
"""Return full filename path for filename""" |
filename = unmap_file(filename)
if filename not in file_cache:
return None
return file_cache[filename].path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remap_file_lines(from_path, to_path, line_map_list):
"""Adds line_map list to the list of association of from_file to to to_file""" |
from_path = pyc2py(from_path)
cache_file(to_path)
remap_entry = file2file_remap_lines.get(to_path)
if remap_entry:
new_list = list(remap_entry.from_to_pairs) + list(line_map_list)
else:
new_list = line_map_list
# FIXME: look for duplicates ?
file2file_remap_lines[to_path] = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sha1(filename):
"""Return SHA1 of filename.""" |
filename = unmap_file(filename)
if filename not in file_cache:
cache_file(filename)
if filename not in file_cache:
return None
pass
if file_cache[filename].sha1:
return file_cache[filename].sha1.hexdigest()
sha1 = hashlib.sha1()
for line in file_cache[fil... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def size(filename, use_cache_only=False):
"""Return the number of lines in filename. If `use_cache_only' is False, we'll try to fetch the file if it is not cache... |
filename = unmap_file(filename)
if filename not in file_cache:
if not use_cache_only: cache_file(filename)
if filename not in file_cache:
return None
pass
return len(file_cache[filename].lines['plain']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maxline(filename, use_cache_only=False):
"""Return the maximum line number filename after taking into account line remapping. If no remapping then this is th... |
if filename not in file2file_remap_lines:
return size(filename, use_cache_only)
max_lineno = -1
remap_line_entry = file2file_remap_lines.get(filename)
if not remap_line_entry:
return size(filename, use_cache_only)
for t in remap_line_entry.from_to_pairs:
max_lineno = max(max... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def remember_ticket(self, request, ticket):
"""Called to store the ticket data for a request. Ticket data is stored in the aiohttp_session object Args: req... |
session = await get_session(request)
session[self.cookie_name] = ticket |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def forget_ticket(self, request):
"""Called to forget the ticket data a request Args: request: aiohttp Request object. """ |
session = await get_session(request)
session.pop(self.cookie_name, '') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def get_ticket(self, request):
"""Called to return the ticket for a request. Args: request: aiohttp Request object. Returns: A ticket (string like) object,... |
session = await get_session(request)
return session.get(self.cookie_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 auth_middleware(policy):
"""Returns a aiohttp_auth middleware factory for use by the aiohttp application object. Args: policy: A authentication policy with a... |
assert isinstance(policy, AbstractAuthentication)
async def _auth_middleware_factory(app, handler):
async def _middleware_handler(request):
# Save the policy in the request
request[POLICY_KEY] = policy
# Call the next handler in the chain
response = aw... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def get_auth(request):
"""Returns the user_id associated with a particular request. Args: request: aiohttp Request object. Returns: The user_id associated ... |
auth_val = request.get(AUTH_KEY)
if auth_val:
return auth_val
auth_policy = request.get(POLICY_KEY)
if auth_policy is None:
raise RuntimeError('auth_middleware not installed')
request[AUTH_KEY] = await auth_policy.get(request)
return request[AUTH_KEY] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def remember(request, user_id):
"""Called to store and remember the userid for a request Args: request: aiohttp Request object. user_id: String representin... |
auth_policy = request.get(POLICY_KEY)
if auth_policy is None:
raise RuntimeError('auth_middleware not installed')
return await auth_policy.remember(request, user_id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def forget(request):
"""Called to forget the userid for a request Args: request: aiohttp Request object Raises: RuntimeError: Middleware is not installed "... |
auth_policy = request.get(POLICY_KEY)
if auth_policy is None:
raise RuntimeError('auth_middleware not installed')
return await auth_policy.forget(request) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def debounce(wait):
""" Decorator that will postpone a functions execution until after wait seconds have elapsed since the last time it was invoked. """ |
def decorator(fn):
def debounced(*args, **kwargs):
def call_it():
fn(*args, **kwargs)
try:
debounced.t.cancel()
except(AttributeError):
pass
debounced.t = threading.Timer(wait, call_it)
debounced.t.s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def process_response(self, request, response):
"""Called to perform any processing of the response required. This function stores any cookie data in the CO... |
await super().process_response(request, response)
if COOKIE_AUTH_KEY in request:
if response.started:
raise RuntimeError("Cannot save cookie into started response")
cookie = request[COOKIE_AUTH_KEY]
if cookie == '':
response.del_cooki... |
<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_args():
'''
Parse CLI args
'''
parser = argparse.ArgumentParser(description='Process args')
parser.Add_argument(
'-H', '--host',
required=True,
action='store',
help='Remote host to connect to'
)
parser.add_argument(
'-P', '--port',
type... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def remember(self, request, user_id):
"""Called to store the userid for a request. This function creates a ticket from the request and user_id, and calls t... |
ticket = self._new_ticket(request, user_id)
await self.remember_ticket(request, ticket) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def get(self, request):
"""Gets the user_id for the request. Gets the ticket for the request using the get_ticket() function, and authenticates the ticket.... |
ticket = await self.get_ticket(request)
if ticket is None:
return None
try:
# Returns a tuple of (user_id, token, userdata, validuntil)
now = time.time()
fields = self._ticket.validate(ticket, self._get_ip(request), now)
# Check if w... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def process_response(self, request, response):
"""If a reissue was requested, only reiisue if the response was a valid 2xx response """ |
if _REISSUE_KEY in request:
if (response.started or
not isinstance(response, web.Response) or
response.status < 200 or response.status > 299):
return
await self.remember_ticket(request, request[_REISSUE_KEY]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def acl_required(permission, context):
"""Returns a decorator that checks if a user has the requested permission from the passed acl context. This function const... |
def decorator(func):
@wraps(func)
async def wrapper(*args):
request = args[-1]
if callable(context):
context = context()
if await get_permitted(request, permission, context):
return await func(*args)
raise web.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 check_version_2(dataset):
"""Checks if json-stat version attribute exists and is equal or greater \ than 2.0 for a given dataset. Args: dataset (OrderedDict)... |
if float(dataset.get('version')) >= 2.0 \
if dataset.get('version') else False:
return True
else:
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 unnest_collection(collection, df_list):
"""Unnest collection structure extracting all its datasets and converting \ them to Pandas Dataframes. Args: collecti... |
for item in collection['link']['item']:
if item['class'] == 'dataset':
df_list.append(Dataset.read(item['href']).write('dataframe'))
elif item['class'] == 'collection':
nested_collection = request(item['href'])
unnest_collection(nested_collection, df_list) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_dimensions(js_dict, naming):
"""Get dimensions from input data. Args: js_dict (dict):
dictionary containing dataset data and metadata. naming (string, o... |
dimensions = []
dim_names = []
if check_version_2(js_dict):
dimension_dict = js_dict
else:
dimension_dict = js_dict['dimension']
for dim in dimension_dict['id']:
dim_name = js_dict['dimension'][dim]['label']
if not dim_name:
dim_name = dim
if nam... |
<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_label(js_dict, dim, input="dataset"):
"""Get label from a given dimension. Args: js_dict (dict):
dictionary containing dataset data and metadata. di... |
if input == 'dataset':
input = js_dict['dimension'][dim]
label_col = 'label'
elif input == 'dimension':
label_col = js_dict['label']
input = js_dict
else:
raise ValueError
try:
dim_label = input['category']['label']
except KeyError:
dim_ind... |
<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_index(js_dict, dim):
"""Get index from a given dimension. Args: js_dict (dict):
dictionary containing dataset data and metadata. dim (string):
dime... |
try:
dim_index = js_dict['dimension'][dim]['category']['index']
except KeyError:
dim_label = get_dim_label(js_dict, dim)
dim_index = pd.DataFrame(list(zip([dim_label['id'][0]], [0])),
index=[0],
columns=['id', 'index'])
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_values(js_dict, value='value'):
"""Get values from input data. Args: js_dict (dict):
dictionary containing dataset data and metadata. value (string, opt... |
values = js_dict[value]
if type(values) is list:
if type(values[0]) is not dict or tuple:
return values
# being not a list of dicts or tuples leaves us with a dict...
values = {int(key): value for (key, value) in values.items()}
if js_dict.get('size'):
max_val = np.pro... |
<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_df_row(dimensions, naming='label', i=0, record=None):
"""Generate row dimension values for a pandas dataframe. Args: dimensions (list):
list of pandas d... |
check_input(naming)
if i == 0 or record is None:
record = []
for dimension in dimensions[i][naming]:
record.append(dimension)
if len(record) == len(dimensions):
yield record
if i + 1 < len(dimensions):
for row in get_df_row(dimensions, naming, i + 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 from_json_stat(datasets, naming='label', value='value'):
"""Decode JSON-stat formatted data into pandas.DataFrame object. Args: datasets(OrderedDict, list):
... |
warnings.warn(
"Shouldn't use this function anymore! Now use read() methods of"
"Dataset, Collection or Dimension.",
DeprecationWarning
)
check_input(naming)
results = []
if type(datasets) is list:
for idx, element in enumerate(datasets):
for dataset 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 request(path):
"""Send a request to a given URL accepting JSON format and return a \ deserialized Python object. Args: path (str):
The URI to be requested. ... |
headers = {'Accept': 'application/json'}
try:
requested_object = requests.get(path, headers=headers)
requested_object.raise_for_status()
except requests.exceptions.HTTPError as exception:
LOGGER.error((inspect.stack()[0][3]) + ': HTTPError = ' +
str(exception.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 auth_required(func):
"""Utility decorator that checks if a user has been authenticated for this request. Allows views to be decorated like: @auth_required de... |
@wraps(func)
async def wrapper(*args):
if (await get_auth(args[-1])) is None:
raise web.HTTPForbidden()
return await func(*args)
return wrapper |
<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_partial(parser, token):
""" Inserts the output of a view, using fully qualified view name, or view name from urls.py. IMPORTANT: the calling template ... |
args = []
kwargs = {}
tokens = token.split_contents()
if len(tokens) < 2:
raise TemplateSyntaxError(
'%r tag requires one or more arguments' %
token.contents.split()[0]
)
tokens.pop(0) # tag name
view_name = tokens.pop(0)
for token in tokens:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.