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 set_pre_handler(self, handler):
'''set pre handler'''
with self._lock:
if self._handler_ctx is not None:
return self._handler_ctx.set_pre_handler(handler)
return RET_ERROR |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def msearch(self, m, query, fields=None, limit=None, or_=True):
'''
set limit make search faster
'''
ix = self._index(m)
if fields is None:
fields = ix.fields
group = OrGroup if or_ else AndGroup
parser = MultifieldParser(fields, ix.schema, group=group... |
<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, **kwargs):
"Update document not update index."
kw = dict(index=self.name, doc_type=self.doc_type, ignore=[404])
kw.update(**kwargs)
return self._client.update(**kw) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def diagonalize_collision_matrix(collision_matrices, i_sigma=None, i_temp=None, pinv_solver=0, log_level=0):
"""Diagonalize collision matrices. Note ---- collisi... |
start = time.time()
# Matrix size of collision matrix to be diagonalized.
# The following value is expected:
# ir-colmat: num_ir_grid_points * num_band * 3
# red-colmat: num_mesh_points * num_band
shape = collision_matrices.shape
if len(shape) == 6:
size = shape[2] * shape[3... |
<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_weights(self):
"""Returns weights used for collision matrix and |X> and |f> self._rot_grid_points : ndarray shape=(ir_grid_points, point_operations), dt... |
weights = []
n = float(self._rot_grid_points.shape[1])
for r_gps in self._rot_grid_points:
weights.append(np.sqrt(len(np.unique(r_gps)) / n))
return weights |
<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_I(self, a, b, size, plus_transpose=True):
"""Return I matrix in Chaput's PRL paper. None is returned if I is zero matrix. """ |
r_sum = np.zeros((3, 3), dtype='double', order='C')
for r in self._rotations_cartesian:
for i in range(3):
for j in range(3):
r_sum[i, j] += r[a, i] * r[b, j]
if plus_transpose:
r_sum += r_sum.T
# Return None not to consume co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_mode_kappa_Chaput(self, i_sigma, i_temp, weights):
"""Calculate mode kappa by the way in Laurent Chaput's PRL paper. This gives the different result fro... |
X = self._get_X(i_temp, weights, self._gv).ravel()
num_ir_grid_points = len(self._ir_grid_points)
num_band = self._primitive.get_number_of_atoms() * 3
size = num_ir_grid_points * num_band * 3
v = self._collision_matrix[i_sigma, i_temp].reshape(size, size)
solver = _sele... |
<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_third_order_displacements(cell, symmetry, is_plusminus='auto', is_diagonal=False):
"""Create dispalcement dataset Note ---- Atoms 1, 2, and 3 are defined... |
positions = cell.get_scaled_positions()
lattice = cell.get_cell().T
# Least displacements of first atoms (Atom 1) are searched by
# using respective site symmetries of the original crystal.
# 'is_diagonal=False' below is made intentionally to expect
# better accuracy.
disps_first = get_le... |
<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_bond_symmetry(site_symmetry, lattice, positions, atom_center, atom_disp, symprec=1e-5):
""" Bond symmetry is the symmetry operations that keep the symmet... |
bond_sym = []
pos = positions
for rot in site_symmetry:
rot_pos = (np.dot(pos[atom_disp] - pos[atom_center], rot.T) +
pos[atom_center])
diff = pos[atom_disp] - rot_pos
diff -= np.rint(diff)
dist = np.linalg.norm(np.dot(lattice, diff))
if dist < sym... |
<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_least_orbits(atom_index, cell, site_symmetry, symprec=1e-5):
"""Find least orbits for a centering atom""" |
orbits = _get_orbits(atom_index, cell, site_symmetry, symprec)
mapping = np.arange(cell.get_number_of_atoms())
for i, orb in enumerate(orbits):
for num in np.unique(orb):
if mapping[num] > mapping[i]:
mapping[num] = mapping[i]
return np.unique(mapping) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_fc3_to_hdf5(fc3, filename='fc3.hdf5', p2s_map=None, compression=None):
"""Write third-order force constants in hdf5 format. Parameters force_constants ... |
with h5py.File(filename, 'w') as w:
w.create_dataset('fc3', data=fc3, compression=compression)
if p2s_map is not None:
w.create_dataset('p2s_map', data=p2s_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 write_unitary_matrix_to_hdf5(temperature, mesh, unitary_matrix=None, sigma=None, sigma_cutoff=None, solver=None, filename=None, verbose=False):
"""Write eige... |
suffix = _get_filename_suffix(mesh,
sigma=sigma,
sigma_cutoff=sigma_cutoff,
filename=filename)
hdf5_filename = "unitary" + suffix + ".hdf5"
with h5py.File(hdf5_filename, 'w') as w:
w.create_datase... |
<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_frequency_shift( self, grid_points, temperatures=np.arange(0, 1001, 10, dtype='double'), epsilons=None, output_filename=None):
"""Frequency shift from lo... |
if self._interaction is None:
self.set_phph_interaction()
if epsilons is None:
_epsilons = [0.1]
else:
_epsilons = epsilons
self._grid_points = grid_points
get_frequency_shift(self._interaction,
self._grid_points,
... |
<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_triplets_reciprocal_mesh_at_q(fixed_grid_number, mesh, rotations, is_time_reversal=True, swappable=True):
"""Search symmetry reduced triplets fixing one... |
import phono3py._phono3py as phono3c
map_triplets = np.zeros(np.prod(mesh), dtype='uintp')
map_q = np.zeros(np.prod(mesh), dtype='uintp')
grid_address = np.zeros((np.prod(mesh), 3), dtype='intc')
phono3c.triplets_reciprocal_mesh_at_q(
map_triplets,
map_q,
grid_address,
... |
<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_averaged_interaction(self):
"""Return sum over phonon triplets of interaction strength See Eq.(21) of PRB 91, 094306 (2015) """ |
# v[triplet, band0, band, band]
v = self._interaction_strength
w = self._weights_at_q
v_sum = np.dot(w, v.sum(axis=2).sum(axis=2))
return v_sum / np.prod(v.shape[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 optimize(lattice, positions, numbers, displacements, forces, alm_options=None, p2s_map=None, p2p_map=None, log_level=0):
"""Calculate force constants lattice... |
from alm import ALM
with ALM(lattice, positions, numbers) as alm:
natom = len(numbers)
alm.set_verbosity(log_level)
nkd = len(np.unique(numbers))
if 'cutoff_distance' not in alm_options:
rcs = -np.ones((2, nkd, nkd), dtype='double')
elif type(alm_options['cu... |
<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_alm_disp_fc3(disp_dataset):
"""Create displacements of atoms for ALM input Note ---- Dipslacements of all atoms in supercells for all displacement confi... |
natom = disp_dataset['natom']
ndisp = len(disp_dataset['first_atoms'])
for disp1 in disp_dataset['first_atoms']:
ndisp += len(disp1['second_atoms'])
disp = np.zeros((ndisp, natom, 3), dtype='double', order='C')
indices = []
count = 0
for disp1 in disp_dataset['first_atoms']:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def capture_dash_in_url_name(self, node):
""" Capture dash in URL name """ |
for keyword in node.keywords:
if keyword.arg == 'name' and '-' in keyword.value.s:
return DJ04(
lineno=node.lineno,
col=node.col_offset,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def capture_url_missing_namespace(self, node):
""" Capture missing namespace in url include. """ |
for arg in node.args:
if not(isinstance(arg, ast.Call) and isinstance(arg.func, ast.Name)):
continue
if arg.func.id != 'include':
continue
for keyword in arg.keywords:
if keyword.arg == 'namespace':
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 get_call_name(self, node):
""" Return call name for the given node. """ |
if isinstance(node.func, ast.Attribute):
return node.func.attr
elif isinstance(node.func, ast.Name):
return node.func.id |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def message(self):
""" Return issue message. """ |
message = self.description.format(**self.parameters)
return '{code} {message}'.format(code=self.code, message=message) |
<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, node):
""" Captures the use of exclude in ModelForm Meta """ |
if not self.checker_applies(node):
return
issues = []
for body in node.body:
if not isinstance(body, ast.ClassDef):
continue
for element in body.body:
if not isinstance(element, ast.Assign):
continue
... |
<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_scheme_and_format(source):
"""Detect scheme and format based on source and return as a tuple. Scheme is a minimum 2 letters before `://` (will be lowe... |
# Scheme: stream
if hasattr(source, 'read'):
return ('stream', None)
# Format: inline
if not isinstance(source, six.string_types):
return (None, 'inline')
# Format: gsheet
if 'docs.google.com/spreadsheets' in source:
if 'export' not in source and 'pub' not in source:
... |
<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_encoding(sample, encoding=None):
"""Detect encoding of a byte string sample. """ |
# To reduce tabulator import time
from cchardet import detect
if encoding is not None:
return normalize_encoding(sample, encoding)
result = detect(sample)
confidence = result['confidence'] or 0
encoding = result['encoding'] or 'ascii'
encoding = normalize_encoding(sample, encoding)
... |
<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_encoding(sample, encoding):
"""Normalize encoding including 'utf-8-sig', 'utf-16-be', utf-16-le tweaks. """ |
encoding = codecs.lookup(encoding).name
# Work around 'Incorrect detection of utf-8-sig encoding'
# <https://github.com/PyYoshi/cChardet/issues/28>
if encoding == 'utf-8':
if sample.startswith(codecs.BOM_UTF8):
encoding = 'utf-8-sig'
# Use the BOM stripping name (without byte-or... |
<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_html(text):
"""Detect if text is HTML. """ |
pattern = re.compile('\\s*<(!doctype|html)', re.IGNORECASE)
return bool(pattern.match(text)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset_stream(stream):
"""Reset stream pointer to the first element. If stream is not seekable raise Exception. """ |
try:
position = stream.tell()
except Exception:
position = True
if position != 0:
try:
stream.seek(0)
except Exception:
message = 'It\'s not possible to reset this stream'
raise exceptions.TabulatorException(message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def requote_uri(uri):
"""Requote uri if it contains non-ascii chars, spaces etc. """ |
# To reduce tabulator import time
import requests.utils
if six.PY2:
def url_encode_non_ascii(bytes):
pattern = '[\x80-\xFF]'
replace = lambda c: ('%%%02x' % ord(c.group(0))).upper()
return re.sub(pattern, replace, bytes)
parts = urlparse(uri)
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 import_attribute(path):
"""Import attribute by path like `package.module.attribute` """ |
module_name, attribute_name = path.rsplit('.', 1)
module = import_module(module_name)
attribute = getattr(module, attribute_name)
return attribute |
<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_options(options, names):
"""Return options for names and remove it from given options in-place. """ |
result = {}
for name, value in copy(options).items():
if name in names:
result[name] = value
del options[name]
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stringify_value(value):
"""Convert any value to string. """ |
if value is None:
return u''
isoformat = getattr(value, 'isoformat', None)
if isoformat is not None:
value = isoformat()
return type(u'')(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 reset(self):
'''Resets the stream pointer to the beginning of the file.'''
if self.__row_number > self.__sample_size:
self.__parser.reset()
self.__extract_sample()
self.__extract_headers()
self.__row_number = 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 sample(self):
'''Returns the stream's rows used as sample.
These sample rows are used internally to infer characteristics of the
source file (e.g. encoding, headers, ...).
'''
sample = []
iterator = iter(self.__sample_extended_rows)
iterator = self.__apply_pr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def iter(self, keyed=False, extended=False):
'''Iterate over the rows.
Each row is returned in a format that depends on the arguments `keyed`
and `extended`. By default, each row is returned as list of their
values.
Args:
keyed (bool, optional): When True, each retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def save(self, target, format=None, encoding=None, **options):
'''Save stream to the local filesystem.
Args:
target (str): Path where to save the stream.
format (str, optional): The format the stream will be saved as. If
None, detects from the ``target`` path. 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 validate(source, scheme=None, format=None):
'''Check if tabulator is able to load the source.
Args:
source (Union[str, IO]): The source path or IO object.
scheme (str, optional): The source scheme. Auto-detect by default.
format (str, optional): The source file format. Auto-detect b... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def require_axis(f):
""" Check if the object of the function has axis and sel_axis members """ |
@wraps(f)
def _wrapper(self, *args, **kwargs):
if None in (self.axis, self.sel_axis):
raise ValueError('%(func_name) requires the node %(node)s '
'to have an axis and a sel_axis function' %
dict(func_name=f.__name__, node=repr(self)))
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 create(point_list=None, dimensions=None, axis=0, sel_axis=None):
""" Creates a kd-tree from a list of points All points in the list must be of the same dimen... |
if not point_list and not dimensions:
raise ValueError('either point_list or dimensions must be provided')
elif point_list:
dimensions = check_dimensionality(point_list, dimensions)
# by default cycle through the axis
sel_axis = sel_axis or (lambda prev_axis: (prev_axis+1) % dimensio... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def level_order(tree, include_all=False):
""" Returns an iterator over the tree in level-order If include_all is set to True, empty parts of the tree are filled ... |
q = deque()
q.append(tree)
while q:
node = q.popleft()
yield node
if include_all or node.left:
q.append(node.left or node.__class__())
if include_all or node.right:
q.append(node.right or node.__class__()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visualize(tree, max_level=100, node_width=10, left_padding=5):
""" Prints the tree to stdout """ |
height = min(max_level, tree.height()-1)
max_width = pow(2, height)
per_level = 1
in_level = 0
level = 0
for node in level_order(tree, include_all=True):
if in_level == 0:
print()
print()
print(' '*left_padding, end=' ')
width = 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 is_leaf(self):
""" Returns True if a Node has no subnodes True False """ |
return (not self.data) or \
(all(not bool(c) for c, p in self.children)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def children(self):
""" Returns an iterator for the non-empty children of the Node The children are returned as (Node, pos) tuples where pos is 0 for the left su... |
if self.left and self.left.data is not None:
yield self.left, 0
if self.right and self.right.data is not None:
yield self.right, 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 set_child(self, index, child):
""" Sets one of the node's children index 0 refers to the left, 1 to the right child """ |
if index == 0:
self.left = child
else:
self.right = child |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_child_pos(self, child):
""" Returns the position if the given child If the given node is the left child, 0 is returned. If its the right child, 1 is retu... |
for c, pos in self.children:
if child == c:
return pos |
<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, point):
""" Adds a point to the current node or iteratively descends to one of its children. Users should call add() only to the topmost tree. """ |
current = self
while True:
check_dimensionality([point], dimensions=current.dimensions)
# Adding has hit an empty leaf-node, add here
if current.data is None:
current.data = point
return current
# split on self.axis, rec... |
<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_subnode(self, data):
""" Creates a subnode for the current node """ |
return self.__class__(data,
axis=self.sel_axis(self.axis),
sel_axis=self.sel_axis,
dimensions=self.dimensions) |
<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_replacement(self):
""" Finds a replacement for the current node The replacement is returned as a (replacement-node, replacements-parent-node) tuple """ |
if self.right:
child, parent = self.right.extreme_child(min, self.axis)
else:
child, parent = self.left.extreme_child(max, self.axis)
return (child, parent if parent is not None else 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 remove(self, point, node=None):
""" Removes the node with the given point from the tree Returns the new root node of the (sub)tree. If there are multiple poi... |
# Recursion has reached an empty leaf node, nothing here to delete
if not self:
return
# Recursion has reached the node to be deleted
if self.should_remove(point, node):
return self._remove(point)
# Remove direct subnode
if self.left and self.l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def axis_dist(self, point, axis):
""" Squared distance at the given axis between the current Node and the given point """ |
return math.pow(self.data[axis] - point[axis], 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 dist(self, point):
""" Squared distance between the current Node and the given point """ |
r = range(self.dimensions)
return sum([self.axis_dist(point, i) for i in 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 search_knn(self, point, k, dist=None):
""" Return the k nearest neighbors of point and their distances point must be an actual point, not a node. k is the nu... |
if k < 1:
raise ValueError("k must be greater than 0.")
if dist is None:
get_dist = lambda n: n.dist(point)
else:
get_dist = lambda n: dist(n.data, point)
results = []
self._search_node(point, k, results, get_dist, itertools.count())
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_nn(self, point, dist=None):
""" Search the nearest node of the given point point must be an actual point, not a node. The nearest node to the point is... |
return next(iter(self.search_knn(point, 1, dist)), 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 search_nn_dist(self, point, distance, best=None):
""" Search the n nearest nodes of the given point which are within given distance point must be a location,... |
results = []
get_dist = lambda n: n.dist(point)
self._search_nn_dist(point, distance, results, get_dist)
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 is_valid(self):
""" Checks recursively if the tree is valid It is valid if each node splits correctly """ |
if not self:
return True
if self.left and self.data[self.axis] < self.left.data[self.axis]:
return False
if self.right and self.data[self.axis] > self.right.data[self.axis]:
return False
return all(c.is_valid() for c, _ in self.children) or self.i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extreme_child(self, sel_func, axis):
""" Returns a child of the subtree and its parent The child is selected by sel_func which is either min or max (or a dif... |
max_key = lambda child_parent: child_parent[0].data[axis]
# we don't know our parent, so we include None
me = [(self, None)] if self else []
child_max = [c.extreme_child(sel_func, axis) for c, _ in self.children]
# insert self for unknown parents
child_max = [(c, p i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump_raw(self, text, stream=None):
"""Encrypt raw data and write to stream.""" |
encrypted = self.vault.encrypt(text)
if stream:
stream.write(encrypted)
else:
return encrypted |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump(self, data, stream=None):
"""Encrypt data and print stdout or write to stream.""" |
yaml_text = yaml.dump(
data,
default_flow_style=False,
allow_unicode=True)
return self.dump_raw(yaml_text, stream=stream) |
<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_item(c, name, item):
""" add_item adds MenuItems to the menu identified by 'name' """ |
if isinstance(item, MenuItem):
if name not in c.items:
c.items[name] = []
c.items[name].append(item)
c.sorted[name] = 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 load_menus(c):
""" load_menus loops through INSTALLED_APPS and loads the menu.py files from them. """ |
# we don't need to do this more than once
if c.loaded:
return
# Fetch all installed app names
app_names = settings.INSTALLED_APPS
if apps:
app_names = [
app_config.name
for app_config in apps.get_app_configs()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sort_menus(c):
""" sort_menus goes through the items and sorts them based on their weight """ |
for name in c.items:
if not c.sorted[name]:
c.items[name].sort(key=lambda x: x.weight)
c.sorted[name] = 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 process(c, request, name=None):
""" process uses the current request to determine which menus should be visible, which are selected, etc. """ |
# make sure we're loaded & sorted
c.load_menus()
c.sort_menus()
if name is None:
# special case, process all menus
items = {}
for name in c.items:
items[name] = c.process(request, name)
return items
if name not 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 check(self, request):
""" Evaluate if we should be visible for this request """ |
if callable(self.check_func):
self.visible = self.check_func(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 process(self, request):
""" """ |
# if we're not visible we return since we don't need to do anymore processing
self.check(request)
if not self.visible:
return
# evaluate our title
if callable(self.title):
self.title = self.title(request)
# if no title is set turn it into a slug... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match_url(self, request):
""" match url determines if this is selected """ |
matched = False
if self.exact_url:
if re.match("%s$" % (self.url,), request.path):
matched = True
elif re.match("%s" % self.url, request.path):
matched = True
return matched |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure(self, proto):
""" Configures the protocol using the information gathered from the remote Mongo instance. Such information may contain the max BSON ... |
if not proto:
defer.returnValue(None)
reply = yield self.__send_ismaster(proto, timeout=self.initialDelay)
# Handle the reply from the "ismaster" query. The reply contains
# configuration information about the peer.
# Make sure we got a result document.
i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def notifyReady(self):
""" Returns a deferred that will fire when the factory has created a protocol that can be used to communicate with a Mongo server. Note th... |
if self.instance:
return defer.succeed(self.instance)
def on_cancel(d):
self.__notify_ready.remove(d)
df = defer.Deferred(on_cancel)
self.__notify_ready.append(df)
return 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 retryNextHost(self, connector=None):
""" Have this connector connect again, to the next host in the configured list of hosts. """ |
if not self.continueTrying:
msg = "TxMongo: Abandoning {0} on explicit request.".format(connector)
log.msg(msg)
return
if connector is None:
if self.connector is None:
raise ValueError("TxMongo: No additional connector to retry.")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def indexes_created(self):
"""Returns a defer on the creation of this GridFS instance's indexes """ |
d = defer.Deferred()
self.__indexes_created_defer.chainDeferred(d)
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 get_last_version(self, filename):
"""Get a file from GridFS by ``"filename"``. Returns the most recently uploaded file in GridFS with the name `filename` as ... |
def ok(doc):
if doc is None:
raise NoFile("TxMongo: no file in gridfs with filename {0}".format(repr(filename)))
return GridOut(self.__collection, doc)
return self.__files.find_one({"filename": filename},
filter = filter.sor... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authenticate(self, name, password, mechanism="DEFAULT"):
""" Send an authentication command for this database. mostly stolen from pymongo """ |
if not isinstance(name, (bytes, unicode)):
raise TypeError("TxMongo: name must be an instance of basestring.")
if not isinstance(password, (bytes, unicode)):
raise TypeError("TxMongo: password must be an instance of basestring.")
"""
Authenticating
"""
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timeout(func):
"""Decorator to add timeout to Deferred calls""" |
@wraps(func)
def _timeout(*args, **kwargs):
now = time()
deadline = kwargs.pop("deadline", None)
seconds = kwargs.pop("timeout", None)
if deadline is None and seconds is not None:
deadline = now + seconds
if deadline is not None and deadline < 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 writelines(self, sequence):
"""Write a sequence of strings to the file. Does not add separators. """ |
iterator = iter(sequence)
def iterate(_=None):
try:
return self.write(next(iterator)).addCallback(iterate)
except StopIteration:
return
return defer.maybeDeferred(iterate) |
<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_new_requests(self):
"""Retrieve all the new request that were found in this request. Returns: list(:class:`nyawc.http.Request`):
A list of request objec... |
content_type = self.__queue_item.response.headers.get('content-type')
scrapers = self.__get_all_scrapers()
new_requests = []
for scraper in scrapers:
instance = scraper(self.__options, self.__queue_item)
if self.__content_type_matches(content_type, instance.con... |
<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_request(self, url, method, data, auth, cookies, headers, proxies, timeout, verify):
"""Execute a request with the given data. Args: url (str):
The UR... |
request_by_method = getattr(requests, method)
return request_by_method(
url=url,
data=data,
auth=auth,
cookies=cookies,
headers=headers,
proxies=proxies,
timeout=timeout,
verify=verify,
allow_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 __get_all_scrapers(self):
"""Find all available scraper references. Returns: list(obj):
The scraper references. """ |
modules_strings = self.__get_all_scrapers_modules()
modules = []
for module_string in modules_strings:
module = importlib.import_module("nyawc.scrapers." + module_string)
modules.append(getattr(module, module_string))
return modules |
<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_all_scrapers_modules(self):
"""Find all available scraper modules. Returns: list(obj):
The scraper modules. """ |
modules = []
file = os.path.realpath(__file__)
folder = os.path.dirname(file)
for filename in os.listdir(folder + "/../scrapers"):
if filename.endswith("Scraper.py") and not filename.startswith("Base"):
modules.append(filename[:-3])
return modules |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __content_type_matches(self, content_type, available_content_types):
"""Check if the given content type matches one of the available content types. Args: con... |
if content_type is None:
return False
if content_type in available_content_types:
return True
for available_content_type in available_content_types:
if available_content_type in content_type:
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 increase_route_count(self, crawled_request):
"""Increase the count that determines how many times a URL of a certain route has been crawled. Args: crawled_re... |
for route in self.__routing_options.routes:
if re.compile(route).match(crawled_request.url):
count_key = str(route) + crawled_request.method
if count_key in self.__routing_count.keys():
self.__routing_count[count_key] += 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 is_treshold_reached(self, scraped_request):
"""Check if similar requests to the given requests have already been crawled X times. Where X is the minimum tres... |
for route in self.__routing_options.routes:
if re.compile(route).match(scraped_request.url):
count_key = str(route) + scraped_request.method
if count_key in self.__routing_count.keys():
return self.__routing_count[count_key] >= self.__routing_op... |
<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_request(self, request):
"""Add a request to the queue. Args: request (:class:`nyawc.http.Request`):
The request to add. Returns: :class:`nyawc.QueueItem... |
queue_item = QueueItem(request, Response(request.url))
self.add(queue_item)
return queue_item |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_request(self, request):
"""Check if the given request already exists in the queue. Args: request (:class:`nyawc.http.Request`):
The request to check. Re... |
queue_item = QueueItem(request, Response(request.url))
key = queue_item.get_hash()
for status in QueueItem.STATUSES:
if key in self.__get_var("items_" + status).keys():
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_first(self, status):
"""Get the first item in the queue that has the given status. Args: status (str):
return the first item with this status. Returns: ... |
items = self.get_all(status)
if items:
return list(items.items())[0][1]
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_for_type(input_type="text"):
"""Get a random string for the given html input type Args: input_type (str):
The input type (e.g. email). Returns: str: The... |
if input_type in RandomInputHelper.cache:
return RandomInputHelper.cache[input_type]
types = {
"text": RandomInputHelper.get_random_value,
"hidden": RandomInputHelper.get_random_value,
"search": RandomInputHelper.get_random_value,
"color": 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 get_random_value(length=10, character_sets=[string.ascii_uppercase, string.ascii_lowercase]):
"""Get a random string with the given length. Args: length (int... |
return "".join(random.choice("".join(character_sets)) for i in range(length)) |
<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_random_email(ltd="com"):
"""Get a random email address with the given ltd. Args: ltd (str):
The ltd to use (e.g. com). Returns: str: The random email. "... |
email = [
RandomInputHelper.get_random_value(6, [string.ascii_lowercase]),
"@",
RandomInputHelper.get_random_value(6, [string.ascii_lowercase]),
".",
ltd
]
return "".join(email) |
<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_random_password():
"""Get a random password that complies with most of the requirements. Note: This random password is not strong and not "really" random... |
password = []
password.append(RandomInputHelper.get_random_value(4, [string.ascii_lowercase]))
password.append(RandomInputHelper.get_random_value(2, [string.digits]))
password.append(RandomInputHelper.get_random_value(2, ["$&*@!"]))
password.append(RandomInputHelper.get_random... |
<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_random_url(ltd="com"):
"""Get a random url with the given ltd. Args: ltd (str):
The ltd to use (e.g. com). Returns: str: The random url. """ |
url = [
"https://",
RandomInputHelper.get_random_value(8, [string.ascii_lowercase]),
".",
ltd
]
return "".join(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 get_random_telephonenumber():
"""Get a random 10 digit phone number that complies with most of the requirements. Returns: str: The random telephone number. "... |
phone = [
RandomInputHelper.get_random_value(3, "123456789"),
RandomInputHelper.get_random_value(3, "12345678"),
"".join(map(str, random.sample(range(10), 4)))
]
return "-".join(phone) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def complies_with_scope(queue_item, new_request, scope):
"""Check if the new request complies with the crawling scope. Args: queue_item (:class:`nyawc.QueueItem`... |
if not URLHelper.is_parsable(queue_item.request.url):
return False
if not URLHelper.is_parsable(new_request.url):
return False
if scope.request_methods:
if not queue_item.request.method in scope.request_methods:
return False
if sco... |
<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_cookie_header(queue_item):
"""Convert a requests cookie jar to a HTTP request cookie header value. Args: queue_item (:class:`nyawc.QueueItem`):
The pare... |
header = []
path = URLHelper.get_path(queue_item.request.url)
for cookie in queue_item.request.cookies:
root_path = cookie.path == "" or cookie.path == "/"
if path.startswith(cookie.path) or root_path:
header.append(cookie.name + "=" + cookie.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 get_soup_response(self):
"""Get the response as a cached BeautifulSoup container. Returns: obj: The BeautifulSoup container. """ |
if self.response is not None:
if self.__response_soup is None:
result = BeautifulSoup(self.response.text, "lxml")
if self.decomposed:
return result
else:
self.__response_soup = BeautifulSoup(self.response.text... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_hash(self):
"""Generate and return the dict index hash of the given queue item. Note: Cookies should not be included in the hash calculation because othe... |
if self.__index_hash:
return self.__index_hash
key = self.request.method
key += URLHelper.get_protocol(self.request.url)
key += URLHelper.get_subdomain(self.request.url)
key += URLHelper.get_hostname(self.request.url)
key += URLHelper.get_tld(self.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 __get_request(self, host, soup):
"""Build a request from the given soup form. Args: host str: The URL of the current queue item. soup (obj):
The BeautifulSo... |
url = URLHelper.make_absolute(host, self.__trim_grave_accent(soup["action"])) if soup.has_attr("action") else host
method_original = soup["method"] if soup.has_attr("method") else "get"
method = "post" if method_original.lower() == "post" else "get"
data = self.__get_form_data(soup)
... |
<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_form_data(self, soup):
"""Build a form data dict from the given form. Args: soup (obj):
The BeautifulSoup form. Returns: obj: The form data (key/value... |
elements = self.__get_valid_form_data_elements(soup)
form_data = self.__get_default_form_data_input(elements)
callback = self.options.callbacks.form_before_autofill
action = callback(self.queue_item, elements, form_data)
if action == CrawlerActions.DO_AUTOFILL_FORM:
... |
<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_valid_form_data_elements(self, soup):
"""Get all valid form input elements. Note: An element is valid when the value can be updated client-side and the... |
elements = []
for element in soup.find_all(["input", "button", "textarea", "select"]):
if element.has_attr("name"):
elements.append(element)
return elements |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __autofill_form_data(self, form_data, elements):
"""Autofill empty form data with random data. Args: form_data (obj):
The {key: value} form data elements li... |
for element in elements:
if not element["name"] in form_data:
continue
if not len(form_data[element["name"]]) is 0:
continue
if element.name == "textarea":
form_data[element["name"]] = RandomInputHelper.get_for_type("textare... |
<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_default_value_from_element(self, element):
"""Get the default value of a form element Args: elements (obj):
The soup element. Returns: str: The defaul... |
if element.name == "select":
options = element.find_all("option")
is_multiple = element.has_attr("multiple")
selected_options = [
option for option in options
if option.has_attr("selected")
]
if not selected_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 append_with_data(url, data):
"""Append the given URL with the given data OrderedDict. Args: url (str):
The URL to append. data (obj):
The key value Ordered... |
if data is None:
return url
url_parts = list(urlparse(url))
query = OrderedDict(parse_qsl(url_parts[4], keep_blank_values=True))
query.update(data)
url_parts[4] = URLHelper.query_dict_to_string(query)
return urlunparse(url_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 get_subdomain(url):
"""Get the subdomain of the given URL. Args: url (str):
The URL to get the subdomain from. Returns: str: The subdomain(s) """ |
if url not in URLHelper.__cache:
URLHelper.__cache[url] = urlparse(url)
return ".".join(URLHelper.__cache[url].netloc.split(".")[:-2]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_hostname(url):
"""Get the hostname of the given URL. Args: url (str):
The URL to get the hostname from. Returns: str: The hostname """ |
if url not in URLHelper.__cache:
URLHelper.__cache[url] = urlparse(url)
parts = URLHelper.__cache[url].netloc.split(".")
if len(parts) == 1:
return parts[0]
else:
return ".".join(parts[-2:-1]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.