Unnamed: 0 int64 0 2.93k | code stringlengths 101 62.2k | docs stringlengths 51 10.7k | doc_len int64 4 1.74k | words int64 4 4.82k | lang stringclasses 1
value | prompt stringlengths 320 71.2k |
|---|---|---|---|---|---|---|
2,400 | def xatom(self, name, *args):
name = name.upper()
#if not name in self.capabilities: # Let the server decide!
# raise self.error('unknown extension command: %s' % name)
if not name in Commands:
Commands[name] = (self.state,)
return self._simple_comman... | Allow simple extension commands
notified by server in CAPABILITY response.
Assumes command is legal in current state.
(typ, [data]) = <instance>.xatom(name, arg, ...)
Returns response appropriate to extension command `name'.
| 30 | 39 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def xatom(self, name, *args):
name = name.upper()
#if not name in self.capabilities: # Let the server decide!
# raise self.error('unknown extension c... |
2,401 | def forward(self, outputs, targets):
outputs = outputs.clip(self.epsilon, 1 - self.epsilon)
log_loss = targets * dp_log(outputs) + ((targets * -1) + 1) * dp_log((outputs * -1) + 1)
log_loss = log_loss.sum(axis=1) * -1
return log_loss.mean()
| Forward pass.
.. math:: L = -t \\log(p) - (1 - t) \\log(1 - p)
Parameters
----------
outputs : numpy.array
Predictions in (0, 1), such as sigmoidal output of a neural network.
targets : numpy.array
Targets in [0, 1], such as ground truth labels.
| 44 | 34 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def forward(self, outputs, targets):
outputs = outputs.clip(self.epsilon, 1 - self.epsilon)
log_loss = targets * dp_log(outputs) + ((targets * -1) + 1) * dp_log((out... |
2,402 | def numeric_assortativity_coefficient(G, attribute, nodes=None):
if nodes is None:
nodes = G.nodes
vals = {G.nodes[n][attribute] for n in nodes}
mapping = {d: i for i, d, in enumerate(vals)}
M = attribute_mixing_matrix(G, attribute, nodes, mapping)
return _numeric_ac(M, mapping)
| Compute assortativity for numerical node attributes.
Assortativity measures the similarity of connections
in the graph with respect to the given numeric attribute.
Parameters
----------
G : NetworkX graph
attribute : string
Node attribute key.
nodes: list or iterable (optional)
... | 129 | 36 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def numeric_assortativity_coefficient(G, attribute, nodes=None):
if nodes is None:
nodes = G.nodes
vals = {G.nodes[n][attribute] for n in nodes}
mapping = {d: i for ... |
2,403 | def write_filepath(filepath, strategy):
dirpath = os.path.dirname(filepath)
base = os.path.basename(filepath)
return os.path.join(write_dirpath(dirpath, strategy), base)
| Returns the writing file path to be used to save file distributedly.
Directory to contain `filepath` would be created if it doesn't exist.
Args:
filepath: Original filepath that would be used without distribution.
strategy: The tf.distribute strategy object currently used.
Returns:
The ... | 53 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def write_filepath(filepath, strategy):
dirpath = os.path.dirname(filepath)
base = os.path.basename(filepath)
return os.path.join(write_dirpath(dirpath, strategy), base)
... |
2,404 | def serving(self, inputs):
output = self.call(inputs)
return self.serving_output(output)
CONVNEXT_START_DOCSTRING = r
CONVNEXT_INPUTS_DOCSTRING = r
@add_start_docstrings(
"The bare ConvNext model outputting raw features without any specific head on top.",
CONVNEXT_START_DOCSTRING,
... |
Method used for serving the model.
Args:
inputs (`Dict[str, tf.Tensor]`):
The input of the saved model as a dictionary of tensors.
This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
library impleme... | 298 | 30 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def serving(self, inputs):
output = self.call(inputs)
return self.serving_output(output)
CONVNEXT_START_DOCSTRING = r
CONVNEXT_INPUTS_DOCSTRING = r
@add_start_d... |
2,405 | def getclasstree(classes, unique=False):
children = {}
roots = []
for c in classes:
if c.__bases__:
for parent in c.__bases__:
if parent not in children:
children[parent] = []
if c not in children[parent]:
child... | Arrange the given list of classes into a hierarchy of nested lists.
Where a nested list appears, it contains classes derived from the class
whose entry immediately precedes the list. Each entry is a 2-tuple
containing a class and a tuple of its base classes. If the 'unique'
argument is true, exactly ... | 78 | 71 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def getclasstree(classes, unique=False):
children = {}
roots = []
for c in classes:
if c.__bases__:
for parent in c.__bases__:
if parent ... |
2,406 | def get_revision(cls, location):
# type: (str) -> str
raise NotImplementedError
|
Return the current commit id of the files at the given location.
| 12 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_revision(cls, location):
# type: (str) -> str
raise NotImplementedError
```
###Assistant :
Return the current commit id of the files at... |
2,407 | def get_current_settings() -> Settings:
from prefect.context import ProfileContext
profile = ProfileContext.get()
if profile is not None:
return profile.settings
return get_settings_from_env()
|
Returns a settings object populated with values from the current profile or, if no
profile is active, the environment.
| 19 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_current_settings() -> Settings:
from prefect.context import ProfileContext
profile = ProfileContext.get()
if profile is not None:
return profile.settings
... |
2,408 | def test_compare_key_greater(self):
self.not_at_dest_sync_strategy.determine_should_sync.return_value = False
# Try when the sync strategy says to sync the file.
self.not_at_src_sync_strategy.determine_should_sync.return_value = True
src_files = []
dest_files = []
... |
Confirm the appropriate action is taken when the soruce compare key
is greater than the destination compare key.
| 18 | 101 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_compare_key_greater(self):
self.not_at_dest_sync_strategy.determine_should_sync.return_value = False
# Try when the sync strategy says to sync the file.
... |
2,409 | def test_custom_exact_lookup_none_rhs(self):
field = Author._meta.get_field("birthdate")
OldExactLookup = field.get_lookup("exact")
author = Author.objects.create(name="author", birthdate=None)
try:
field.register_lookup(Exactly, "exact")
self.assertEqual... |
__exact=None is transformed to __isnull=True if a custom lookup class
with lookup_name != 'exact' is registered as the `exact` lookup.
| 20 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_custom_exact_lookup_none_rhs(self):
field = Author._meta.get_field("birthdate")
OldExactLookup = field.get_lookup("exact")
author = Author.objects.c... |
2,410 | def batch_pairwise_distances(U, V):
with tf.variable_scope('pairwise_dist_block'):
# Squared norms of each row in U and V.
norm_u = tf.reduce_sum(tf.square(U), 1)
norm_v = tf.reduce_sum(tf.square(V), 1)
# norm_u as a row and norm_v as a column vectors.
norm_u = tf.resha... | Compute pairwise distances between two batches of feature vectors. | 9 | 63 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def batch_pairwise_distances(U, V):
with tf.variable_scope('pairwise_dist_block'):
# Squared norms of each row in U and V.
norm_u = tf.reduce_sum(tf.square(U), 1)
... |
2,411 | def expand_dims(self, image):
self._ensure_format_supported(image)
# Do nothing if PIL image
if isinstance(image, PIL.Image.Image):
return image
if is_torch_tensor(image):
image = image.unsqueeze(0)
else:
image = np.expand_dims(image... |
Expands 2-dimensional `image` to 3 dimensions.
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
The image to expand.
| 17 | 27 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def expand_dims(self, image):
self._ensure_format_supported(image)
# Do nothing if PIL image
if isinstance(image, PIL.Image.Image):
return image... |
2,412 | def test_find_executable_task_instances_order_execution_date(self, dag_maker):
dag_id_1 = 'SchedulerJobTest.test_find_executable_task_instances_order_execution_date-a'
dag_id_2 = 'SchedulerJobTest.test_find_executable_task_instances_order_execution_date-b'
task_id = 'task-a'
ses... |
Test that task instances follow execution_date order priority. If two dagruns with
different execution dates are scheduled, tasks with earliest dagrun execution date will first
be executed
| 27 | 68 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_find_executable_task_instances_order_execution_date(self, dag_maker):
dag_id_1 = 'SchedulerJobTest.test_find_executable_task_instances_order_execution_date-a'
... |
2,413 | def dispatch(self, request, *args, **kwargs):
self.determine_active_organization(request, kwargs.get("organization_slug", None))
if self.csrf_protect:
if hasattr(self.dispatch.__func__, "csrf_exempt"):
delattr(self.dispatch.__func__, "csrf_exempt")
resp... |
A note on the CSRF protection process.
Because the CSRF decorators don't work well with view subclasses, we
allow them to control whether a CSRF check is done by setting
self.csrf_protect. This has a couple of implications:
1. We need to mark this method as @csrf_exempt so tha... | 105 | 89 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def dispatch(self, request, *args, **kwargs):
self.determine_active_organization(request, kwargs.get("organization_slug", None))
if self.csrf_protect:
... |
2,414 | def interpolator(self) -> int:
assert self._interpolator is not None
return self._interpolator
| int: The cv2 interpolator required to transpose the mask to a full frame. | 13 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def interpolator(self) -> int:
assert self._interpolator is not None
return self._interpolator
```
###Assistant : int: The cv2 interpolator required to... |
2,415 | def test_cluster_interrupt(start_connected_cluster, tmpdir):
cluster = start_connected_cluster
dirpath = str(tmpdir)
# Needs to be in scope for pytest | Tests run_experiment on cluster shutdown with actual interrupt.
This is an end-to-end test.
| 13 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_cluster_interrupt(start_connected_cluster, tmpdir):
cluster = start_connected_cluster
dirpath = str(tmpdir)
# Needs to be in scope for pytest
```
###As... |
2,416 | def test_version(self) -> None:
for version in ("1.0", 1.0, 1):
result = self.parse_response({"version": version, "type": "link"})
# An empty Open Graph response is an error, ensure the URL is included.
self.assertIn("og:url", result.open_graph_result)
# A m... | Accept versions that are similar to 1.0 as a string or int (or missing). | 14 | 85 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_version(self) -> None:
for version in ("1.0", 1.0, 1):
result = self.parse_response({"version": version, "type": "link"})
# An empty Open Gr... |
2,417 | def test_page_allowing_subpages(self):
response = self.client.get(
reverse("wagtailadmin_userbar_frontend", args=(self.event_index.id,))
)
# page allows subpages, so the 'add page' button should show
expected_url = reverse(
"wagtailadmin_pages:add_subpage", args=... |
<a href="{expected_url}" target="_parent" role="menuitem">
<svg class="icon icon-plus wagtail-action-icon" aria-hidden="true" focusable="false">
<use href="#icon-plus"></use>
</svg>
Add a child page
</a>
| 18 | 30 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_page_allowing_subpages(self):
response = self.client.get(
reverse("wagtailadmin_userbar_frontend", args=(self.event_index.id,))
)
# page allows ... |
2,418 | def render_output_ui(self, streamlit_app, input) -> None: # type: ignore
src, result = self.__root__
streamlit_app.subheader("Synthesized Audio")
streamlit_app.audio(result.content, format="audio/wav")
fig, ax = plt.subplots()
ax.imshow(src.mel, aspect="equal"... | Custom output UI.
If this method is implmeneted, it will be used instead of the default Output UI renderer.
| 19 | 39 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def render_output_ui(self, streamlit_app, input) -> None: # type: ignore
src, result = self.__root__
streamlit_app.subheader("Synthesized Audio")
s... |
2,419 | def get_default_mesh(self):
return self._default_mesh
LayoutMap.get.__doc__ = LayoutMap.__getitem__.__doc__
@keras_export("keras.dtensor.experimental.layout_map_scope", v1=[])
@contextlib.contextmanager | Return the default `Mesh` set at instance creation.
The `Mesh` can be used to create default replicated `Layout` when there
isn't a match of the input string query.
| 28 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_default_mesh(self):
return self._default_mesh
LayoutMap.get.__doc__ = LayoutMap.__getitem__.__doc__
@keras_export("keras.dtensor.experimental.layout_map_scope", ... |
2,420 | def __setitem__(self, key, item): # pragma: no cover
raise NotImplementedError("Implemented by subclasses")
|
Assign `item` value to dataset located by `key`.
Parameters
----------
key : callable or tuple
The global row numbers to assign data to.
item : modin.pandas.DataFrame, modin.pandas.Series or scalar
Value that should be assigned to located dataset.
... | 41 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __setitem__(self, key, item): # pragma: no cover
raise NotImplementedError("Implemented by subclasses")
```
###Assistant :
Assign `item` value to ... |
2,421 | def test_bad_origin_cannot_be_parsed(self):
req = self._get_POST_request_with_token()
req.META["HTTP_HOST"] = "www.example.com"
req.META["HTTP_ORIGIN"] = "https://["
mw = CsrfViewMiddleware(post_form_view)
self._check_referer_rejects(mw, req)
self.assertIs(mw._or... |
A POST request with an origin that can't be parsed by urlparse() is
rejected.
| 14 | 42 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_bad_origin_cannot_be_parsed(self):
req = self._get_POST_request_with_token()
req.META["HTTP_HOST"] = "www.example.com"
req.META["HTTP_ORIGIN"] = "ht... |
2,422 | def move_from_center(coord, centers, deltas, axmask=(True, True, True)):
return _move_from_center(coord, centers, deltas, axmask=axmask)
|
For each coordinate where *axmask* is True, move *coord* away from
*centers* by *deltas*.
| 14 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def move_from_center(coord, centers, deltas, axmask=(True, True, True)):
return _move_from_center(coord, centers, deltas, axmask=axmask)
```
###Assistant :
For ea... |
2,423 | def get_execution_info(self, job_id, function_descriptor):
function_id = function_descriptor.function_id
# If the function has already been loaded,
# There's no need to load again
if function_id in self._function_execution_info:
return self._function_execution_info[f... | Get the FunctionExecutionInfo of a remote function.
Args:
job_id: ID of the job that the function belongs to.
function_descriptor: The FunctionDescriptor of the function to get.
Returns:
A FunctionExecutionInfo object.
| 30 | 162 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_execution_info(self, job_id, function_descriptor):
function_id = function_descriptor.function_id
# If the function has already been loaded,
# There's... |
2,424 | def exclude_all_devices(self) -> bool:
return all(idx in _EXCLUDE_DEVICES for idx in range(self._device_count))
| bool: ``True`` if all GPU devices have been explicitly disabled otherwise ``False`` | 12 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def exclude_all_devices(self) -> bool:
return all(idx in _EXCLUDE_DEVICES for idx in range(self._device_count))
```
###Assistant : bool: ``True`` if all GPU de... |
2,425 | def serialize_labels(self, resources):
labels = []
for label in resources:
if label in AlexaGlobalCatalog.__dict__.values():
label = {"@type": "asset", "value": {"assetId": label}}
else:
label = {"@type": "text", "value": {"text": label, "... | Return resource label objects for friendlyNames serialized for an API response. | 11 | 35 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def serialize_labels(self, resources):
labels = []
for label in resources:
if label in AlexaGlobalCatalog.__dict__.values():
label = {"@t... |
2,426 | def _decode_bitonal(self):
data = bytearray()
total_bytes = self.state.xsize * self.state.ysize
comment_spans = False
while len(data) != total_bytes:
block = self._read_block() # read next block
if not block:
# eof
break
... |
This is a separate method because in the plain PBM format, all data tokens are
exactly one byte, so the inter-token whitespace is optional.
| 24 | 104 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _decode_bitonal(self):
data = bytearray()
total_bytes = self.state.xsize * self.state.ysize
comment_spans = False
while len(data) != total_bytes... |
2,427 | def recast_to_symbols(eqs, symbols):
if not iterable(eqs) and iterable(symbols):
raise ValueError('Both eqs and symbols must be iterable')
orig = list(symbols)
symbols = list(ordered(symbols))
swap_sym = {}
i = 0
for j, s in enumerate(symbols):
if not isinstance(s, Symbol) a... |
Return (e, s, d) where e and s are versions of *eqs* and
*symbols* in which any non-Symbol objects in *symbols* have
been replaced with generic Dummy symbols and d is a dictionary
that can be used to restore the original expressions.
Examples
========
>>> from sympy.solvers.solvers import... | 124 | 88 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def recast_to_symbols(eqs, symbols):
if not iterable(eqs) and iterable(symbols):
raise ValueError('Both eqs and symbols must be iterable')
orig = list(symbols)
symbo... |
2,428 | def model_is_indexable(cls, model, allow_child_models=False):
if getattr(model, "wagtail_reference_index_ignore", False):
return False
# Don't check any models that have a parental key, references from these will be collected from the parent
if not allow_child_models and an... |
Returns True if the given model may have outbound references that we would be interested in recording in the index.
Args:
model (type): a Django model class
allow_child_models (boolean): Child models are not indexable on their own. If you are looking at
... | 65 | 91 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def model_is_indexable(cls, model, allow_child_models=False):
if getattr(model, "wagtail_reference_index_ignore", False):
return False
# Don't check any... |
2,429 | def get_encodings_from_content(content):
warnings.warn(
(
"In requests 3.0, get_encodings_from_content will be removed. For "
"more information, please see the discussion on issue #2266. (This"
" warning should only appear once.)"
),
DeprecationWarnin... | Returns encodings from given content string.
:param content: bytestring to extract encodings from.
| 13 | 51 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_encodings_from_content(content):
warnings.warn(
(
"In requests 3.0, get_encodings_from_content will be removed. For "
"more information, plea... |
2,430 | def _scale_axis_limits(self, scale_x, scale_y, scale_z):
# Get the axis limits and centers
minx, maxx, miny, maxy, minz, maxz = self.get_w_lims()
cx = (maxx + minx)/2
cy = (maxy + miny)/2
cz = (maxz + minz)/2
# Scale the data range
dx = (maxx - minx)*sca... |
Keeping the center of the x, y, and z data axes fixed, scale their
limits by scale factors. A scale factor > 1 zooms out and a scale
factor < 1 zooms in.
Parameters
----------
scale_x : float
Scale factor for the x data axis.
scale_y : float
... | 65 | 79 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _scale_axis_limits(self, scale_x, scale_y, scale_z):
# Get the axis limits and centers
minx, maxx, miny, maxy, minz, maxz = self.get_w_lims()
cx = (maxx ... |
2,431 | def layers(self) -> tuple[str, ...]:
for node in self.ancestors:
if not isinstance(node, Widget):
break
if node.styles.has_rule("layers"):
return node.styles.layers
return ("default",)
| Layers of from parent.
Returns:
tuple[str, ...]: Tuple of layer names.
| 11 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def layers(self) -> tuple[str, ...]:
for node in self.ancestors:
if not isinstance(node, Widget):
break
if node.styles.has_rule("laye... |
2,432 | def get_roi_head_cfg(fname):
config = _get_config_module(fname)
model = copy.deepcopy(config.model)
roi_head = model.roi_head
train_cfg = None if model.train_cfg is None else model.train_cfg.rcnn
test_cfg = None if model.test_cfg is None else model.test_cfg.rcnn
roi_head.update(dict(train_... | Grab configs necessary to create a roi_head.
These are deep copied to allow for safe modification of parameters without
influencing other tests.
| 22 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_roi_head_cfg(fname):
config = _get_config_module(fname)
model = copy.deepcopy(config.model)
roi_head = model.roi_head
train_cfg = None if model.train_cfg is Non... |
2,433 | def print_as_log(*args, **kwargs):
from prefect.context import FlowRunContext, TaskRunContext
context = TaskRunContext.get() or FlowRunContext.get()
if not context or not context.log_prints:
return print(*args, **kwargs)
logger = get_run_logger()
# Print to an in-memory buffer; so we... |
A patch for `print` to send printed messages to the Prefect run logger.
If no run is active, `print` will behave as if it were not patched.
| 27 | 56 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def print_as_log(*args, **kwargs):
from prefect.context import FlowRunContext, TaskRunContext
context = TaskRunContext.get() or FlowRunContext.get()
if not context or not c... |
2,434 | def test_image():
# Test fails for matplotlib 1.5+ because the size of the image
# generated by matplotlib has changed.
if Version(matplotlib.__version__) == Version("3.4.1"):
image_size = 432
else:
pytest.skip("Test fails for older matplotlib")
np.random.seed(0) # image size depend... |
opening figure
opening axes
draw image of size {image_size}
closing axes
closing figure
| 13 | 55 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_image():
# Test fails for matplotlib 1.5+ because the size of the image
# generated by matplotlib has changed.
if Version(matplotlib.__version__) == Version("3.4.1"):
... |
2,435 | def ignore_cidr(vm_, ip):
from ipaddress import ip_address, ip_network
cidrs = config.get_cloud_config_value(
"ignore_cidr", vm_, __opts__, default=[], search_global=False
)
if cidrs and isinstance(cidrs, str):
cidrs = [cidrs]
for cidr in cidrs or []:
if ip_address(ip) ... |
Return True if we are to ignore the specified IP.
| 10 | 48 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def ignore_cidr(vm_, ip):
from ipaddress import ip_address, ip_network
cidrs = config.get_cloud_config_value(
"ignore_cidr", vm_, __opts__, default=[], search_global=Fa... |
2,436 | def encode_nested_example(schema, obj):
# Nested structures: we allow dict, list/tuples, sequences
if isinstance(schema, dict):
return {k: encode_nested_example(sub_schema, sub_obj) for k, (sub_schema, sub_obj) in zip_dict(schema, obj)}
elif isinstance(schema, (list, tuple)):
sub_schema... | Encode a nested example.
This is used since some features (in particular ClassLabel) have some logic during encoding.
To avoid iterating over possibly long lists, it first checks (recursively) if the first element that is not None or empty (if it is a sequence) has to be encoded.
If the first element needs... | 71 | 270 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def encode_nested_example(schema, obj):
# Nested structures: we allow dict, list/tuples, sequences
if isinstance(schema, dict):
return {k: encode_nested_example(sub_sche... |
2,437 | def _configure_matplotlib(cls):
rcParams["keymap.fullscreen"] = [k for k in rcParams["keymap.fullscreen"] if k != "f"]
rcParams["keymap.save"] = [k for k in rcParams["keymap.save"] if k != "s"]
rcParams["keymap.home"] = [k for k in rcParams["keymap.home"] if k != "r"]
rcParams["... | Remove `F`, 'S' and 'R' from their default bindings and stop Matplotlib from stealing
focus | 15 | 38 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _configure_matplotlib(cls):
rcParams["keymap.fullscreen"] = [k for k in rcParams["keymap.fullscreen"] if k != "f"]
rcParams["keymap.save"] = [k for k in rcParams... |
2,438 | def set_permission_cache(user, key, value):
from django.core.cache import cache
# store this key, so we can clean it when required
cache_key = get_cache_key(user, key)
cache.set(cache_key, value,
get_cms_setting('CACHE_DURATIONS')['permissions'],
version=get_cache_permi... |
Helper method for storing values in cache. Stores used keys so
all of them can be cleaned when clean_permission_cache gets called.
| 21 | 27 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def set_permission_cache(user, key, value):
from django.core.cache import cache
# store this key, so we can clean it when required
cache_key = get_cache_key(user, key)
... |
2,439 | def cookies(self) -> multidict.MultiDictView[str, tuple[str, multidict.MultiDict[str, Optional[str]]]]:
return multidict.MultiDictView(
self._get_cookies,
self._set_cookies
)
|
The response cookies. A possibly empty `MultiDictView`, where the keys are cookie
name strings, and values are `(cookie value, attributes)` tuples. Within
attributes, unary attributes (e.g. `HTTPOnly`) are indicated by a `None` value.
Modifications to the MultiDictView update `Response.... | 64 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def cookies(self) -> multidict.MultiDictView[str, tuple[str, multidict.MultiDict[str, Optional[str]]]]:
return multidict.MultiDictView(
self._get_cookies,
... |
2,440 | def _normalize_entries(entries, separators=None):
norm_files = {}
for entry in entries:
norm_files[normalize_file(entry.path, separators=separators)] = entry
return norm_files
|
Normalizes the entry paths to use the POSIX path separator.
*entries* (:class:`~collections.abc.Iterable` of :class:`.TreeEntry`)
contains the entries to be normalized.
*separators* (:class:`~collections.abc.Collection` of :class:`str`; or
:data:`None`) optionally contains the path separators to normalize.
See... | 52 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _normalize_entries(entries, separators=None):
norm_files = {}
for entry in entries:
norm_files[normalize_file(entry.path, separators=separators)] = entry
return norm_files
... |
2,441 | def assertXMLNotEqual(self, xml1, xml2, msg=None):
try:
result = compare_xml(xml1, xml2)
except Exception as e:
standardMsg = "First or second argument is not valid XML\n%s" % e
self.fail(self._formatMessage(msg, standardMsg))
else:
if res... |
Assert that two XML snippets are not semantically equivalent.
Whitespace in most cases is ignored and attribute ordering is not
significant. The arguments must be valid XML.
| 27 | 45 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def assertXMLNotEqual(self, xml1, xml2, msg=None):
try:
result = compare_xml(xml1, xml2)
except Exception as e:
standardMsg = "First or secon... |
2,442 | def token_kwargs(bits, parser, support_legacy=False):
if not bits:
return {}
match = kwarg_re.match(bits[0])
kwarg_format = match and match[1]
if not kwarg_format:
if not support_legacy:
return {}
if len(bits) < 3 or bits[1] != "as":
return {}
kw... |
Parse token keyword arguments and return a dictionary of the arguments
retrieved from the ``bits`` token list.
`bits` is a list containing the remainder of the token (split by spaces)
that is to be checked for arguments. Valid arguments are removed from this
list.
`support_legacy` - if True, ... | 90 | 95 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def token_kwargs(bits, parser, support_legacy=False):
if not bits:
return {}
match = kwarg_re.match(bits[0])
kwarg_format = match and match[1]
if not kwarg_forma... |
2,443 | def get_cost_of_delayed_shipments(scorecard):
return get_total_cost_of_shipments(scorecard) - get_cost_of_on_time_shipments(scorecard)
| Gets the total cost of all delayed shipments in the period (based on Purchase Receipts - POs) | 17 | 6 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_cost_of_delayed_shipments(scorecard):
return get_total_cost_of_shipments(scorecard) - get_cost_of_on_time_shipments(scorecard)
```
###Assistant : Gets the total cost... |
2,444 | def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None):
# if weight is specified, apply element-wise weight
if weight is not None:
loss = loss * weight
# if avg_factor is not specified, just reduce the loss
if avg_factor is None:
loss = reduce_loss(loss, reduc... | Apply element-wise weight and reduce loss.
Args:
loss (Tensor): Element-wise loss.
weight (Tensor): Element-wise weights.
reduction (str): Same as built-in losses of PyTorch.
avg_factor (float): Average factor when computing the mean of losses.
Returns:
Tensor: Processe... | 38 | 112 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None):
# if weight is specified, apply element-wise weight
if weight is not None:
loss = loss * we... |
2,445 | def test_failure_to_run_iterations():
rnd = np.random.RandomState(0)
X = rnd.standard_normal((100, 10))
A = X @ X.T
Q = rnd.standard_normal((X.shape[0], 4))
with pytest.warns(UserWarning, match="Exited at iteration"):
eigenvalues, _ = lobpcg(A, Q, maxiter=20)
assert(np.max(eigenvalu... | Check that the code exists gracefully without breaking. Issue #10974.
| 10 | 35 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_failure_to_run_iterations():
rnd = np.random.RandomState(0)
X = rnd.standard_normal((100, 10))
A = X @ X.T
Q = rnd.standard_normal((X.shape[0], 4))
with pyt... |
2,446 | def test_predictor_tableau_header(self, mock_handler):
df = pd.DataFrame([
{'a': 1, 'b': 'one'},
{'a': 2, 'b': 'two'},
{'a': 1, 'b': 'three'},
])
self.set_handler(mock_handler, name='pg', tables={'tasks': df})
# --- use predictor ---
predicted... |
SELECT
SUM(1) AS `cnt__0B4A4E8BD11C48FFB4730D4D2C32191A_ok`,
sum(`Custom SQL Query`.`a`) AS `sum_height_ok`,
max(`Custom SQL Query`.`p`) AS `sum_length1_ok`
FROM (
SELECT res.a, res.p
FROM pg.tasks as source
... | 35 | 82 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_predictor_tableau_header(self, mock_handler):
df = pd.DataFrame([
{'a': 1, 'b': 'one'},
{'a': 2, 'b': 'two'},
{'a': 1, 'b': 'three'},
... |
2,447 | def test_conflicting_specified_basename_different_models(self):
self.router.register(r'notes', NoteViewSet)
with pytest.raises(ImproperlyConfigured):
self.router.register(r'notes_basename', BasenameViewSet, basename='routertestmodel')
|
Ensure 2 routers with different models, and a conflicting basename specified
throws an exception
| 14 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_conflicting_specified_basename_different_models(self):
self.router.register(r'notes', NoteViewSet)
with pytest.raises(ImproperlyConfigured):
sel... |
2,448 | def _get_boosted_releases(self) -> BoostedReleases:
boosted_releases = BoostedReleases()
for boosted_release_cache_key, timestamp in self.redis_client.hgetall(
self._generate_cache_key_for_boosted_releases_hash()
).items():
extracted_data = self._extract_data_fro... |
Returns all the boosted releases and parses them based on key and value data.
This method should not be called directly as the boosted releases are not extended, thus they contain only a
subset of information.
| 36 | 31 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_boosted_releases(self) -> BoostedReleases:
boosted_releases = BoostedReleases()
for boosted_release_cache_key, timestamp in self.redis_client.hgetall(
... |
2,449 | def store_stats_summary(reply):
store_summary = "--- Aggregate object store stats across all nodes ---\n"
# TODO(ekl) it would be nice if we could provide a full memory usage
# breakdown by type (e.g., pinned by worker, primary, etc.)
store_summary += (
"Plasma memory usage {} MiB, {} objec... | Returns formatted string describing object store stats in all nodes. | 10 | 194 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def store_stats_summary(reply):
store_summary = "--- Aggregate object store stats across all nodes ---\n"
# TODO(ekl) it would be nice if we could provide a full memory usage
... |
2,450 | def test_spam_checker_deny(self) -> None:
self.get_failure(self.handler.register_user(localpart="user"), SynapseError)
| A spam checker can deny registration, which results in an error. | 11 | 6 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_spam_checker_deny(self) -> None:
self.get_failure(self.handler.register_user(localpart="user"), SynapseError)
```
###Assistant : A spam checker can den... |
2,451 | def _get_pitch_yaw_roll(self) -> None:
proj_matrix = np.zeros((3, 4), dtype="float32")
proj_matrix[:3, :3] = cv2.Rodrigues(self._rotation)[0]
euler = cv2.decomposeProjectionMatrix(proj_matrix)[-1]
self._pitch_yaw_roll = cast(Tuple[float, float, float], tuple(euler.squeeze()))
... | Obtain the yaw, roll and pitch from the :attr:`_rotation` in eular angles. | 12 | 28 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_pitch_yaw_roll(self) -> None:
proj_matrix = np.zeros((3, 4), dtype="float32")
proj_matrix[:3, :3] = cv2.Rodrigues(self._rotation)[0]
euler = cv2.dec... |
2,452 | def aiohttp_notify_servers_mock() -> Iterable[Mock]:
with patch(
"homeassistant.components.dlna_dmr.data.AiohttpNotifyServer"
) as mock_constructor:
servers = []
| Construct mock AiohttpNotifyServer on demand, eliminating network use.
This fixture provides a list of the constructed servers.
| 17 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def aiohttp_notify_servers_mock() -> Iterable[Mock]:
with patch(
"homeassistant.components.dlna_dmr.data.AiohttpNotifyServer"
) as mock_constructor:
servers = []... |
2,453 | def line_collection_2d_to_3d(col, zs=0, zdir='z'):
segments3d = _paths_to_3d_segments(col.get_paths(), zs, zdir)
col.__class__ = Line3DCollection
col.set_segments(segments3d)
| Convert a `.LineCollection` to a `.Line3DCollection` object. | 7 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def line_collection_2d_to_3d(col, zs=0, zdir='z'):
segments3d = _paths_to_3d_segments(col.get_paths(), zs, zdir)
col.__class__ = Line3DCollection
col.set_segments(segments3d... |
2,454 | def execute():
frappe.reload_doc("e_commerce", "web_template", "item_card_group")
blocks = frappe.db.get_all(
"Web Page Block",
filters={"web_template": "Item Card Group"},
fields=["parent", "web_template_values", "name"]
)
fields = generate_fields_to_edit()
for block... |
Convert all Item links to Website Item link values in
exisitng 'Item Card Group' Web Page Block data.
| 18 | 69 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def execute():
frappe.reload_doc("e_commerce", "web_template", "item_card_group")
blocks = frappe.db.get_all(
"Web Page Block",
filters={"web_template": "Item C... |
2,455 | def set_pickradius(self, pickradius):
if not isinstance(pickradius, Number) or pickradius < 0:
raise ValueError("pick radius should be a distance")
self._pickradius = pickradius
pickradius = property(get_pickradius, set_pickradius)
|
Set the pick radius used for containment tests.
See `.contains` for more details.
Parameters
----------
pickradius : float
Pick radius, in points.
| 22 | 25 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def set_pickradius(self, pickradius):
if not isinstance(pickradius, Number) or pickradius < 0:
raise ValueError("pick radius should be a distance")
self.... |
2,456 | def _predict(self):
with self._lock:
self._predicted_images = []
for frame in self._input_images:
self._predictor.in_queue.put(frame)
idx = 0
while idx < self._sample_size:
logger.debug("Predicting face %s of %s", idx + 1, ... | Predict from the loaded frames.
With a threading lock (to prevent stacking), run the selected faces through the Faceswap
model predict function and add the output to :attr:`predicted`
| 28 | 57 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _predict(self):
with self._lock:
self._predicted_images = []
for frame in self._input_images:
self._predictor.in_queue.put(frame)... |
2,457 | def exclude(f):
J, new = f.rep.exclude()
gens = [gen for j, gen in enumerate(f.gens) if j not in J]
return f.per(new, gens=gens)
|
Remove unnecessary generators from ``f``.
Examples
========
>>> from sympy import Poly
>>> from sympy.abc import a, b, c, d, x
>>> Poly(a + x, a, b, c, d, x).exclude()
Poly(a + x, a, x, domain='ZZ')
| 36 | 22 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def exclude(f):
J, new = f.rep.exclude()
gens = [gen for j, gen in enumerate(f.gens) if j not in J]
return f.per(new, gens=gens)
```
###Assista... |
2,458 | def set_ticks(self, ticks, labels=None, *, minor=False, **kwargs):
result = self._set_tick_locations(ticks, minor=minor)
if labels is not None:
self.set_ticklabels(labels, minor=minor, **kwargs)
return result
|
Set this Axis' tick locations and optionally labels.
If necessary, the view limits of the Axis are expanded so that all
given ticks are visible.
Parameters
----------
ticks : list of floats
List of tick locations. The axis `.Locator` is replaced by a
... | 177 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def set_ticks(self, ticks, labels=None, *, minor=False, **kwargs):
result = self._set_tick_locations(ticks, minor=minor)
if labels is not None:
self.set_... |
2,459 | def get_all_customers(date_range, company, field, limit=None):
if field == "outstanding_amount":
filters = [["docstatus", "=", "1"], ["company", "=", company]]
if date_range:
date_range = frappe.parse_json(date_range)
filters.append(["posting_date", ">=", "between", [date_range[0], date_range[1]]])
return ... |
select so.customer as name, {0} as value
FROM `tabSales Order` as so JOIN `tabSales Order Item` as so_item
ON so.name = so_item.parent
where so.docstatus = 1 {1} and so.company = %s
group by so.customer
order by value DESC
limit %s
| 40 | 73 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_all_customers(date_range, company, field, limit=None):
if field == "outstanding_amount":
filters = [["docstatus", "=", "1"], ["company", "=", company]]
if date_range:
date_ra... |
2,460 | async def _async_create_radio_entity(self) -> FlowResult:
assert self._title is not None
assert self._radio_type is not None
assert self._device_path is not None
assert self._device_settings is not None
device_settings = self._device_settings.copy()
device_setti... | Create a config entity with the current flow state. | 9 | 45 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def _async_create_radio_entity(self) -> FlowResult:
assert self._title is not None
assert self._radio_type is not None
assert self._device_path is not ... |
2,461 | def publish_daemon(self, publish_payload, *args, **kwargs):
context = zmq.Context(1)
ioloop = salt.ext.tornado.ioloop.IOLoop()
ioloop.make_current()
# Set up the context |
Bind to the interface specified in the configuration file
| 9 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def publish_daemon(self, publish_payload, *args, **kwargs):
context = zmq.Context(1)
ioloop = salt.ext.tornado.ioloop.IOLoop()
ioloop.make_current()
... |
2,462 | def _print_Pow(self, expr, rational=False):
PREC = precedence(expr)
if expr.exp is S.Half and not rational:
return "sqrt(%s)" % self._print(expr.base)
if expr.is_commutative:
if -expr.exp is S.Half and not rational:
# Note: Don't test "expr.exp ... | Printing helper function for ``Pow``
Parameters
==========
rational : bool, optional
If ``True``, it will not attempt printing ``sqrt(x)`` or
``x**S.Half`` as ``sqrt``, and will use ``x**(1/2)``
instead.
See examples for additional details
... | 102 | 124 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _print_Pow(self, expr, rational=False):
PREC = precedence(expr)
if expr.exp is S.Half and not rational:
return "sqrt(%s)" % self._print(expr.base)
... |
2,463 | def _save_tab(self, tab, active, minimal=False):
data: _JsonType = {'history': []}
if active:
data['active'] = True
if minimal:
history = [tab.history.current_item()]
else:
history = tab.history
for idx, item in enumerate(history):
... | Get a dict with data for a single tab.
Args:
tab: The WebView to save.
active: Whether the tab is currently active.
| 22 | 70 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _save_tab(self, tab, active, minimal=False):
data: _JsonType = {'history': []}
if active:
data['active'] = True
if minimal:
hist... |
2,464 | def testBestCheckpoints(self):
keep_checkpoints_num = 4
checkpoint_manager = self.checkpoint_manager(keep_checkpoints_num)
checkpoints = [
Checkpoint(Checkpoint.PERSISTENT, i, self.mock_result(i)) for i in range(16)
]
random.shuffle(checkpoints)
for ... |
Tests that the best checkpoints are tracked and ordered correctly.
| 10 | 38 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def testBestCheckpoints(self):
keep_checkpoints_num = 4
checkpoint_manager = self.checkpoint_manager(keep_checkpoints_num)
checkpoints = [
Checkp... |
2,465 | def save(self):
s = self._read_from_storage() # type: _Settings
for k, v in self.__dict__.items():
if k[0] == '_':
continue
if hasattr(s, k):
setattr(s, k, v)
log.debug("_ConfigSQL updating storage")
self._session.merge(... | Apply all configuration values to the underlying storage. | 8 | 40 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def save(self):
s = self._read_from_storage() # type: _Settings
for k, v in self.__dict__.items():
if k[0] == '_':
continue
... |
2,466 | def test_transactions(self):
prev_hour = timezone.now() - timedelta(hours=1)
event = self.transaction_data.copy()
event.update(
{
"start_timestamp": iso_format(prev_hour - timedelta(minutes=1)),
"timestamp": iso_format(prev_hour),
"tags... |
conditions = [{"id": "sentry.rules.conditions.first_seen_event.FirstSeenEventCondition"}]
filters = [{
"id": "sentry.rules.filters.tagged_event.TaggedEventFilter",
"key": "foo",
"match": "eq",
"value": "bar",
}]
result = preview(self.proje... | 28 | 153 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_transactions(self):
prev_hour = timezone.now() - timedelta(hours=1)
event = self.transaction_data.copy()
event.update(
{
"start_t... |
2,467 | def test_follows_semver_all_releases_semver_and_missing_package_semver_release_version(self):
assert (
follows_semver_versioning_scheme(
org_id=self.org.id, project_id=self.proj_1.id, release_version="2.0.0"
)
is False
)
|
Test that ensures that even if a project is following semver, then if the release_version
supplied lacks a package, then for that specific release we opt the project out of being
considered a semver project
| 35 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_follows_semver_all_releases_semver_and_missing_package_semver_release_version(self):
assert (
follows_semver_versioning_scheme(
org_id=s... |
2,468 | def MultivariateT(syms, mu, sigma, v):
return multivariate_rv(MultivariateTDistribution, syms, mu, sigma, v)
#-------------------------------------------------------------------------------
# Multivariate Normal Gamma distribution ---------------------------------------
|
Creates a joint random variable with multivariate T-distribution.
Parameters
==========
syms : A symbol/str
For identifying the random variable.
mu : A list/matrix
Representing the location vector
sigma : The shape matrix for the distribution
Examples
========
>>... | 70 | 18 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def MultivariateT(syms, mu, sigma, v):
return multivariate_rv(MultivariateTDistribution, syms, mu, sigma, v)
#---------------------------------------------------------------------... |
2,469 | def _can_hold_identifiers_and_holds_name(self, name) -> bool:
if self.is_object() or is_string_dtype(self.dtype) or self.is_categorical():
return name in self
return False
|
Faster check for ``name in self`` when we know `name` is a Python
identifier (e.g. in NDFrame.__getattr__, which hits this to support
. key lookup). For indexes that can't hold identifiers (everything
but object & categorical) we just return False.
https://github.com/pandas-dev... | 41 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _can_hold_identifiers_and_holds_name(self, name) -> bool:
if self.is_object() or is_string_dtype(self.dtype) or self.is_categorical():
return name in self
... |
2,470 | def test_remove_other_alias(self) -> None:
# Create a second alias.
other_test_alias = "#test2:test"
other_room_alias = self._add_alias(other_test_alias)
# Set the alias as the canonical alias for this room.
self._set_canonical_alias(
{
"alia... | Removing an alias listed as in alt_aliases should remove it there too. | 12 | 63 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_remove_other_alias(self) -> None:
# Create a second alias.
other_test_alias = "#test2:test"
other_room_alias = self._add_alias(other_test_alias)
... |
2,471 | def test_get_comments_no_doc(self):
response = self.client.get(
"/api/documents/500/comments/",
format="json",
)
self.assertEqual(response.status_code, 404)
|
GIVEN:
- A request to get comments from a non-existent document
WHEN:
- API request for document comments is made
THEN:
- HTTP 404 is returned
| 26 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_get_comments_no_doc(self):
response = self.client.get(
"/api/documents/500/comments/",
format="json",
)
self.assertEqual(res... |
2,472 | def test_mapping_keypad(self, config_stub, keyparser):
config_stub.val.bindings.commands = {'normal': {'a': 'nop'}}
config_stub.val.bindings.key_mappings = {'1': 'a'}
info = keyutils.KeyInfo(Qt.Key.Key_1, Qt.KeyboardModifier.KeypadModifier)
keyparser.handle(info.to_event())
... | Make sure falling back to non-numpad keys works with mappings. | 10 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_mapping_keypad(self, config_stub, keyparser):
config_stub.val.bindings.commands = {'normal': {'a': 'nop'}}
config_stub.val.bindings.key_mappings = {'1': 'a'... |
2,473 | def verify_liked_image(browser, logger):
browser.refresh()
unlike_xpath = read_xpath(like_image.__name__, "unlike")
like_elem = browser.find_elements(By.XPATH, unlike_xpath)
if len(like_elem) == 1:
return True
else:
logger.warning("--> Image was NOT liked! You have a BLOCK on ... | Check for a ban on likes using the last liked image | 11 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def verify_liked_image(browser, logger):
browser.refresh()
unlike_xpath = read_xpath(like_image.__name__, "unlike")
like_elem = browser.find_elements(By.XPATH, unlike_xpath... |
2,474 | def get_bboxes(self, dst_type='hbb'):
from ..bbox import get_box_type
_, box_type_cls = get_box_type(dst_type)
return box_type_cls.from_instance_masks(self)
| Get the certain type boxes from masks.
Please refer to ``mmdet.structures.bbox.box_type`` for more details of
the box type.
Args:
dst_type: Destination box type.
Returns:
:obj:`BaseBoxes`: Certain type boxes.
| 28 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_bboxes(self, dst_type='hbb'):
from ..bbox import get_box_type
_, box_type_cls = get_box_type(dst_type)
return box_type_cls.from_instance_masks(self)
... |
2,475 | def deprecate_call():
sympy_deprecation_warning(
,
deprecated_since_version="1.5",
active_deprecations_target="deprecated-tensor-fun-eval",
stacklevel=4,
)
|
Calling a tensor like Tensor(*indices) is deprecated. Use
Tensor.substitute_indices() instead.
| 10 | 8 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def deprecate_call():
sympy_deprecation_warning(
,
deprecated_since_version="1.5",
active_deprecations_target="deprecated-tensor-fun-eval",
stacklevel=4,
... |
2,476 | def assign_proto(proto, name, val):
is_repeated_field = hasattr(getattr(proto, name), 'extend')
if is_repeated_field and not isinstance(val, list):
val = [val]
if isinstance(val, list):
if isinstance(val[0], dict):
for item in val:
proto_item = getattr(proto... | Assign a Python object to a protobuf message, based on the Python
type (in recursive fashion). Lists become repeated fields/messages, dicts
become messages, and other types are assigned directly. For convenience,
repeated fields whose values are not lists are converted to single-element
lists; e.g., `my... | 49 | 59 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def assign_proto(proto, name, val):
is_repeated_field = hasattr(getattr(proto, name), 'extend')
if is_repeated_field and not isinstance(val, list):
val = [val]
if i... |
2,477 | def __new__(cls, *args, **kwargs):
sympy_deprecation_warning(
,
deprecated_since_version="1.8",
active_deprecations_target='deprecated-askhandler',
)
return super().__new__(cls, *args, **kwargs)
|
The AskHandler system is deprecated. The AskHandler class should
be replaced with the multipledispatch handler of Predicate
| 17 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __new__(cls, *args, **kwargs):
sympy_deprecation_warning(
,
deprecated_since_version="1.8",
active_deprecations_target='deprecated-askhandler'... |
2,478 | def incr_mean_variance_axis(X, *, axis, last_mean, last_var, last_n, weights=None):
_raise_error_wrong_axis(axis)
if not isinstance(X, (sp.csr_matrix, sp.csc_matrix)):
_raise_typeerror(X)
if np.size(last_n) == 1:
last_n = np.full(last_mean.shape, last_n, dtype=last_mean.dtype)
if... | Compute incremental mean and variance along an axis on a CSR or CSC matrix.
last_mean, last_var are the statistics computed at the last step by this
function. Both must be initialized to 0-arrays of the proper size, i.e.
the number of features in X. last_n is the number of samples encountered
until now... | 344 | 121 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def incr_mean_variance_axis(X, *, axis, last_mean, last_var, last_n, weights=None):
_raise_error_wrong_axis(axis)
if not isinstance(X, (sp.csr_matrix, sp.csc_matrix)):
... |
2,479 | async def test_thermostat_with_no_off_after_recheck(hass, hk_driver, events):
entity_id = "climate.test"
# support_auto = True
hass.states.async_set(
entity_id,
HVACMode.COOL,
{
ATTR_SUPPORTED_FEATURES: SUPPORT_TARGET_TEMPERATURE
| SUPPORT_TARGET_TEMPERA... | Test if a thermostat that is not ready when we first see it that actually does not have off. | 19 | 118 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_thermostat_with_no_off_after_recheck(hass, hk_driver, events):
entity_id = "climate.test"
# support_auto = True
hass.states.async_set(
entity_id,
... |
2,480 | def save(self, *args, **kwargs):
is_new = self.pk is None
if is_new:
clean_name = get_field_clean_name(self.label)
self.clean_name = clean_name
super().save(*args, **kwargs)
|
When new fields are created, generate a template safe ascii name to use as the
JSON storage reference for this field. Previously created fields will be updated
to use the legacy unidecode method via checks & _migrate_legacy_clean_name.
We do not want to update the clean name on any subs... | 61 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def save(self, *args, **kwargs):
is_new = self.pk is None
if is_new:
clean_name = get_field_clean_name(self.label)
self.clean_name = clean_n... |
2,481 | def dask_task_wrapper(func, repack, key, ray_pretask_cbs, ray_posttask_cbs, *args):
if ray_pretask_cbs is not None:
pre_states = [
cb(key, args) if cb is not None else None for cb in ray_pretask_cbs
]
repacked_args, repacked_deps = repack(args)
# Recursively execute Dask-inl... |
A Ray remote function acting as a Dask task wrapper. This function will
repackage the given flat `args` into its original data structures using
`repack`, execute any Dask subtasks within the repackaged arguments
(inlined by Dask's optimization pass), and then pass the concrete task
arguments to the... | 131 | 77 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def dask_task_wrapper(func, repack, key, ray_pretask_cbs, ray_posttask_cbs, *args):
if ray_pretask_cbs is not None:
pre_states = [
cb(key, args) if cb is not Non... |
2,482 | def words(count, common=True):
word_list = list(COMMON_WORDS) if common else []
c = len(word_list)
if count > c:
count -= c
while count > 0:
c = min(count, len(WORDS))
count -= c
word_list += random.sample(WORDS, c)
else:
word_list = word_... |
Return a string of `count` lorem ipsum words separated by a single space.
If `common` is True, then the first 19 words will be the standard
'lorem ipsum' words. Otherwise, all words will be selected randomly.
| 36 | 42 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def words(count, common=True):
word_list = list(COMMON_WORDS) if common else []
c = len(word_list)
if count > c:
count -= c
while count > 0:
c = ... |
2,483 | def jumpTo(self, bytes):
try:
self._position = self.index(bytes, self.position) + len(bytes) - 1
except ValueError:
raise StopIteration
return True
| Look for the next sequence of bytes matching a given sequence. If
a match is found advance the position to the last byte of the match | 26 | 18 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def jumpTo(self, bytes):
try:
self._position = self.index(bytes, self.position) + len(bytes) - 1
except ValueError:
raise StopIteration
... |
2,484 | def available(self) -> bool:
expire_after: int | None = self._config.get(CONF_EXPIRE_AFTER)
# mypy doesn't know about fget: https://github.com/python/mypy/issues/6185
return MqttAvailability.available.fget(self) and ( # type: ignore[attr-defined]
expire_after is None or not... | Return true if the device is available and value has not expired. | 12 | 31 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def available(self) -> bool:
expire_after: int | None = self._config.get(CONF_EXPIRE_AFTER)
# mypy doesn't know about fget: https://github.com/python/mypy/issues/618... |
2,485 | def Logistic(name, mu, s):
r
return rv(name, LogisticDistribution, (mu, s))
#-------------------------------------------------------------------------------
# Log-logistic distribution --------------------------------------------------------
|
Create a continuous random variable with a logistic distribution.
Explanation
===========
The density of the logistic distribution is given by
.. math::
f(x) := \frac{e^{-(x-\mu)/s}} {s\left(1+e^{-(x-\mu)/s}\right)^2}
Parameters
==========
mu : Real number, the location (me... | 105 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def Logistic(name, mu, s):
r
return rv(name, LogisticDistribution, (mu, s))
#-------------------------------------------------------------------------------
# Log-logistic distribu... |
2,486 | def __call__(self, feat_maps, comp_attribs):
assert isinstance(feat_maps, paddle.Tensor)
assert comp_attribs.ndim == 3
assert comp_attribs.shape[2] == 8
sorted_dist_inds_batch = []
local_graph_batch = []
knn_batch = []
node_feat_batch = []
node_... | Generate local graphs as GCN input.
Args:
feat_maps (Tensor): The feature maps to extract the content
features of text components.
comp_attribs (ndarray): The text component attributes.
Returns:
local_graphs_node_feat (Tensor): The node features of g... | 61 | 146 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __call__(self, feat_maps, comp_attribs):
assert isinstance(feat_maps, paddle.Tensor)
assert comp_attribs.ndim == 3
assert comp_attribs.shape[2] == 8
... |
2,487 | def _is_zero_copy_arrow_op(cls, op) -> bool:
is_zero_copy_op = False
if isinstance(op, (FrameNode, TransformNode, UnionNode)):
# - FrameNode: already materialized PyArrow table
# - TransformNode: select certain columns of the table, implemented zero-copy (``df._arrow_sel... |
Check whether the passed node of the delayed computation tree could be executed zero-copy via PyArrow execution.
Parameters
----------
op : DFAlgNode
Returns
-------
bool
| 25 | 85 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _is_zero_copy_arrow_op(cls, op) -> bool:
is_zero_copy_op = False
if isinstance(op, (FrameNode, TransformNode, UnionNode)):
# - FrameNode: already mat... |
2,488 | def batch_p_dist(x, y, p=2):
x = x.unsqueeze(1)
diff = x - y
return paddle.norm(diff, p=p, axis=list(range(2, diff.dim())))
@register |
calculate pairwise p_dist, the first index of x and y are batch
return [x.shape[0], y.shape[0]]
| 15 | 18 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def batch_p_dist(x, y, p=2):
x = x.unsqueeze(1)
diff = x - y
return paddle.norm(diff, p=p, axis=list(range(2, diff.dim())))
@register
```
###Assistant :
c... |
2,489 | def get_employee_shift(employee, for_timestamp=None, consider_default_shift=False, next_shift_direction=None):
if for_timestamp is None:
for_timestamp = now_datetime()
shift_details = get_shift_for_timestamp(employee, for_timestamp)
# if shift assignment is not found, consider default shift
default_shift = fr... | Returns a Shift Type for the given employee on the given date. (excluding the holidays)
:param employee: Employee for which shift is required.
:param for_timestamp: DateTime on which shift is required
:param consider_default_shift: If set to true, default shift is taken when no shift assignment is found.
:param ne... | 67 | 82 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_employee_shift(employee, for_timestamp=None, consider_default_shift=False, next_shift_direction=None):
if for_timestamp is None:
for_timestamp = now_datetime()
shift_details =... |
2,490 | def get_create_form_class(self):
self.create_model = self.get_create_model()
if self.create_model:
return get_task_form_class(self.create_model)
else:
return None
|
To be called after dispatch(); returns the form class for creating a new task
| 14 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_create_form_class(self):
self.create_model = self.get_create_model()
if self.create_model:
return get_task_form_class(self.create_model)
... |
2,491 | def retrieve_image(self):
image = self.storage.open(self.image_path, "rb")
image_format = self.get_image_metadata_from_file(image)
return (Image.open(image), image_format)
| Return a PIL Image instance stored at `image_path`. | 8 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def retrieve_image(self):
image = self.storage.open(self.image_path, "rb")
image_format = self.get_image_metadata_from_file(image)
return (Image.open(image),... |
2,492 | def chebval(x, c, tensor=True):
c = np.array(c, ndmin=1, copy=True)
if c.dtype.char in '?bBhHiIlLqQpP':
c = c.astype(np.double)
if isinstance(x, (tuple, list)):
x = np.asarray(x)
if isinstance(x, np.ndarray) and tensor:
c = c.reshape(c.shape + (1,)*x.ndim)
if len(c) == ... |
Evaluate a Chebyshev series at points x.
If `c` is of length `n + 1`, this function returns the value:
.. math:: p(x) = c_0 * T_0(x) + c_1 * T_1(x) + ... + c_n * T_n(x)
The parameter `x` is converted to an array only if it is a tuple or a
list, otherwise it is treated as a scalar. In either case... | 369 | 87 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def chebval(x, c, tensor=True):
c = np.array(c, ndmin=1, copy=True)
if c.dtype.char in '?bBhHiIlLqQpP':
c = c.astype(np.double)
if isinstance(x, (tuple, list)):
... |
2,493 | def dagrun_queued(self):
dag_id = request.form.get('dag_id')
dag_run_id = request.form.get('dag_run_id')
confirmed = request.form.get('confirmed') == 'true'
origin = get_safe_url(request.form.get('origin'))
return self._mark_dagrun_state_as_queued(dag_id, dag_run_id, con... | Queue DagRun so tasks that haven't run yet can be started. | 11 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def dagrun_queued(self):
dag_id = request.form.get('dag_id')
dag_run_id = request.form.get('dag_run_id')
confirmed = request.form.get('confirmed') == 'true'
... |
2,494 | def data_to_internal(data):
internal = data.copy()
if 'extra_vars' in data:
internal['extra_vars'] = json.loads(data['extra_vars'])
if 'credentials' in data:
internal['credentials'] = set(Credential.objects.get(pk=_id) for _id in data['credentials'])
if 'inventory' in data:
... |
returns internal representation, model objects, dictionaries, etc
as opposed to integer primary keys and JSON strings
| 16 | 70 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def data_to_internal(data):
internal = data.copy()
if 'extra_vars' in data:
internal['extra_vars'] = json.loads(data['extra_vars'])
if 'credentials' in data:
... |
2,495 | def _generate_sys_info_str(*sys_info) -> str:
if sys_info:
return "<br>".join(sys_info).replace("\n", "<br>")
return ""
| Format system info into a string.
*sys_info: System info strings to be included.
Returns:
Formatted string containing system information.
| 19 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _generate_sys_info_str(*sys_info) -> str:
if sys_info:
return "<br>".join(sys_info).replace("\n", "<br>")
return ""
```
###Assistant : Format system in... |
2,496 | def default(self, obj):
if isinstance(obj, tf.TensorShape):
items = obj.as_list() if obj.rank is not None else None
return {"class_name": "TensorShape", "items": items}
return get_json_type(obj)
| Encodes objects for types that aren't handled by the default
encoder. | 11 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def default(self, obj):
if isinstance(obj, tf.TensorShape):
items = obj.as_list() if obj.rank is not None else None
return {"class_name": "TensorShap... |
2,497 | async def _pause_and_wait_for_callback(self):
self._pause_requested = True
await self.async_media_pause()
try: | Send pause and wait for the pause callback to be received. | 11 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def _pause_and_wait_for_callback(self):
self._pause_requested = True
await self.async_media_pause()
try:
```
###Assistant : Send pause and ... |
2,498 | def delete_checkpoint(self, checkpoint_path):
# Ensure TrialCheckpoints are converted
if isinstance(checkpoint_path, TrialCheckpoint):
checkpoint_path = checkpoint_path.local_path
try:
checkpoint_dir = TrainableUtil.find_checkpoint_dir(checkpoint_path)
e... | Deletes local copy of checkpoint.
Args:
checkpoint_path (str): Path to checkpoint.
| 11 | 56 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def delete_checkpoint(self, checkpoint_path):
# Ensure TrialCheckpoints are converted
if isinstance(checkpoint_path, TrialCheckpoint):
checkpoint_path = ... |
2,499 | def _resize_worker_group(self, state_dict, max_retries=10):
old_workers = self.worker_group.num_workers
self.worker_group.reset()
time.sleep(1)
for i in range(max_retries):
new_workers = self.worker_group.new_workers_size()
if new_workers:
... | Resizes the number of remote workers based on available resources.
Total number of workers will never exceed `num_workers` amount.
Args:
state_dict (dict): The state dict to load to all workers.
max_retries (int): How many times to attempt to resize workers
befor... | 42 | 119 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _resize_worker_group(self, state_dict, max_retries=10):
old_workers = self.worker_group.num_workers
self.worker_group.reset()
time.sleep(1)
for ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.