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,600 | def delete_project_summary_annotations_before_updating_annotation(sender, instance, **kwargs):
try:
old_annotation = sender.objects.get(id=instance.id)
except Annotation.DoesNotExist:
# annotation just created - do nothing
return
old_annotation.decrease_project_summary_counters(... | Before updating annotation fields - ensure previous info removed from project.summary | 11 | 67 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def delete_project_summary_annotations_before_updating_annotation(sender, instance, **kwargs):
try:
old_annotation = sender.objects.get(id=instance.id)
except Annotation... |
2,601 | def load_config(self, modelpath, use_gpu, gpu_id, use_mkldnn, cpu_threads):
# 对运行位置进行配置
if use_gpu:
try:
int(os.environ.get('CUDA_VISIBLE_DEVICES'))
except Exception:
print(
)
use_gpu = False
... |
load the model config
modelpath: inference model path
use_gpu: use gpu or not
use_mkldnn: use mkldnn or not
Error! Unable to use GPU. Please set the environment variables "CUDA_VISIBLE_DEVICES=GPU_id" to use GPU. Now switch to CPU to continue... | 38 | 151 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def load_config(self, modelpath, use_gpu, gpu_id, use_mkldnn, cpu_threads):
# 对运行位置进行配置
if use_gpu:
try:
int(os.environ.get('CUDA_VI... |
2,602 | def trim_line(line, column=0):
line = line.strip("\n")
ll = len(line)
if ll <= 150:
return line
if column > ll:
column = ll
start = max(column - 60, 0)
# Round down if it brings us close to the edge
if start < 5:
start = 0
end = min(start + 140, ll)
# Rou... |
Trims a line down to a goal of 140 characters, with a little
wiggle room to be sensible and tries to trim around the given
`column`. So it tries to extract 60 characters before and after
the provided `column` and yield a better context.
| 44 | 139 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def trim_line(line, column=0):
line = line.strip("\n")
ll = len(line)
if ll <= 150:
return line
if column > ll:
column = ll
start = max(column - 60, ... |
2,603 | def test_background_update_default_batch_set_by_config(self):
self.get_success(
self.store.db_pool.simple_insert(
"background_updates",
values={"update_name": "test_update", "progress_json": '{"my_key": 1}'},
)
)
self.update_hand... |
Test that the background update is run with the default_batch_size set by the config
| 14 | 45 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_background_update_default_batch_set_by_config(self):
self.get_success(
self.store.db_pool.simple_insert(
"background_updates",
... |
2,604 | def _expiry_date(self, session_data):
return session_data.get("_session_expiry") or (
self._last_modification()
+ datetime.timedelta(seconds=self.get_session_cookie_age())
)
|
Return the expiry time of the file storing the session's content.
| 11 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _expiry_date(self, session_data):
return session_data.get("_session_expiry") or (
self._last_modification()
+ datetime.timedelta(seconds=self.get... |
2,605 | def __call__(self, *args, **kwargs):
# For backward compatibility
if self._in_target_context_manager:
return self.current_processor(*args, **kwargs)
images = kwargs.pop("images", None)
text = kwargs.pop("text", None)
if len(args) > 0:
images = ar... |
When used in normal mode, this method forwards all its arguments to AutoFeatureExtractor's
[`~AutoFeatureExtractor.__call__`] and returns its output. If used in the context
[`~TrOCRProcessor.as_target_processor`] this method forwards all its arguments to TrOCRTokenizer's
[`~TrOCRTokeniz... | 46 | 89 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __call__(self, *args, **kwargs):
# For backward compatibility
if self._in_target_context_manager:
return self.current_processor(*args, **kwargs)
... |
2,606 | def get_report(module_name, report_name):
reports = get_reports()
module = reports.get(module_name)
if module is None:
return None
report = module.get(report_name)
if report is None:
return None
return report
|
Return a specific report from within a module.
| 8 | 26 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_report(module_name, report_name):
reports = get_reports()
module = reports.get(module_name)
if module is None:
return None
report = module.get(report_n... |
2,607 | def test_worker_duty_configs(self) -> None:
worker1_config = self._make_worker_config(
worker_app="synapse.app.generic_worker",
worker_name="worker1",
extras={
"notify_appservices_from_worker": "worker2",
"update_user_directory_from_w... |
Additional tests for the worker duties
| 6 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_worker_duty_configs(self) -> None:
worker1_config = self._make_worker_config(
worker_app="synapse.app.generic_worker",
worker_name="worker1... |
2,608 | def actor_id(self):
# only worker mode has actor_id
assert (
self.worker.mode == ray.worker.WORKER_MODE
), f"This method is only available when the process is a\
worker. Current mode: {self.worker.mode}"
actor_id = self.worker.actor_id
return... | Get the current actor ID in this worker.
ID of the actor of the current process.
This shouldn't be used in a driver process.
Returns:
The current actor id in this worker. None if there's no actor id.
| 38 | 38 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def actor_id(self):
# only worker mode has actor_id
assert (
self.worker.mode == ray.worker.WORKER_MODE
), f"This method is only available when t... |
2,609 | def test_redirect_to_current(self):
start_url = reverse("wagtailsettings:edit", args=["tests", "testsetting"])
dest_url = reverse(
"wagtailsettings:edit", args=["tests", "testsetting", self.other_site.pk]
)
response = self.client.get(
start_url, follow=Tr... |
Should redirect to the setting for the current site taken from the URL,
by default
| 15 | 28 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_redirect_to_current(self):
start_url = reverse("wagtailsettings:edit", args=["tests", "testsetting"])
dest_url = reverse(
"wagtailsettings:edit"... |
2,610 | def fit(self, X, y, sample_weight=None, fit_params=None):
if not hasattr(self.estimator, "fit"):
raise ValueError("The base estimator should implement a fit method")
y = self._validate_data(X="no_validation", y=y, multi_output=True)
if is_classifier(self):
che... | Fit the model to data, separately for each output variable.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
The input data.
y : {array-like, sparse matrix} of shape (n_samples, n_outputs)
Multi-output targets. An indicator ma... | 110 | 114 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def fit(self, X, y, sample_weight=None, fit_params=None):
if not hasattr(self.estimator, "fit"):
raise ValueError("The base estimator should implement a fit met... |
2,611 | def inner_choices(self) -> Iterable['ValueChoice']:
for arg in self.arguments:
if isinstance(arg, ValueChoiceX):
yield from arg.inner_choices()
|
Return an iterable of all leaf value choices.
Useful for composition of value choices.
No deduplication on labels. Mutators should take care.
| 22 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def inner_choices(self) -> Iterable['ValueChoice']:
for arg in self.arguments:
if isinstance(arg, ValueChoiceX):
yield from arg.inner_choices()
... |
2,612 | def get_indices(expr):
# We call ourself recursively to determine indices of sub expressions.
# break recursion
if isinstance(expr, Indexed):
c = expr.indices
inds, dummies = _remove_repeated(c)
return inds, {}
elif expr is None:
return set(), {}
elif isinstance... | Determine the outer indices of expression ``expr``
By *outer* we mean indices that are not summation indices. Returns a set
and a dict. The set contains outer indices and the dict contains
information about index symmetries.
Examples
========
>>> from sympy.tensor.index_methods import get_i... | 263 | 152 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_indices(expr):
# We call ourself recursively to determine indices of sub expressions.
# break recursion
if isinstance(expr, Indexed):
c = expr.indices
... |
2,613 | def dist_location(dist):
# type: (Distribution) -> str
egg_link = egg_link_path(dist)
if egg_link:
return normalize_path(egg_link)
return normalize_path(dist.location)
|
Get the site-packages location of this distribution. Generally
this is dist.location, except in the case of develop-installed
packages, where dist.location is the source code location, and we
want to know where the egg-link file is.
The returned location is normalized (in particular, with symlinks... | 45 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def dist_location(dist):
# type: (Distribution) -> str
egg_link = egg_link_path(dist)
if egg_link:
return normalize_path(egg_link)
return normalize_path(dist.loc... |
2,614 | def can_connect(url, error_classes=None):
if error_classes is None:
error_classes = _get_default_network_errors()
try:
with urlopen(url, timeout=20) as response:
# Timeout just in case rate-limiting is applied
if response.status != 200:
return False
... |
Try to connect to the given url. True if succeeds, False if OSError
raised
Parameters
----------
url : basestring
The URL to try to connect to
Returns
-------
connectable : bool
Return True if no OSError (unable to connect) or URLError (bad url) was
raised
| 45 | 41 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def can_connect(url, error_classes=None):
if error_classes is None:
error_classes = _get_default_network_errors()
try:
with urlopen(url, timeout=20) as response... |
2,615 | def test_valid_slack_channel_id(self):
integration = Integration.objects.create(
external_id="1",
provider="slack",
metadata={"access_token": "xoxp-xxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxx"},
)
integration.add_organization(self.organization, self.user)
... |
Test that when a valid Slack channel ID is provided, we look up the channel name and validate it against the targetIdentifier.
| 22 | 73 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_valid_slack_channel_id(self):
integration = Integration.objects.create(
external_id="1",
provider="slack",
metadata={"access_tok... |
2,616 | def get_legacy(members):
if AIX_ABI == 64:
# AIX 64-bit member is one of shr64.o, shr_64.o, or shr4_64.o
expr = r'shr4?_?64\.o'
member = get_one_match(expr, members)
if member:
return member
else:
# 32-bit legacy names - both shr.o and shr4.o exist.
... |
This routine provides historical aka legacy naming schemes started
in AIX4 shared library support for library members names.
e.g., in /usr/lib/libc.a the member name shr.o for 32-bit binary and
shr_64.o for 64-bit binary.
| 33 | 77 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_legacy(members):
if AIX_ABI == 64:
# AIX 64-bit member is one of shr64.o, shr_64.o, or shr4_64.o
expr = r'shr4?_?64\.o'
member = get_one_match(expr, ... |
2,617 | def set_policy(name, table="filter", family="ipv4", **kwargs):
ret = {"name": name, "changes": {}, "result": None, "comment": ""}
for ignore in _STATE_INTERNAL_KEYWORDS:
if ignore in kwargs:
del kwargs[ignore]
if (
__salt__["iptables.get_policy"](table, kwargs["chain"], fa... |
.. versionadded:: 2014.1.0
Sets the default policy for iptables firewall tables
table
The table that owns the chain that should be modified
family
Networking family, either ipv4 or ipv6
policy
The requested table policy
save
If set to a true value, the new i... | 62 | 176 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def set_policy(name, table="filter", family="ipv4", **kwargs):
ret = {"name": name, "changes": {}, "result": None, "comment": ""}
for ignore in _STATE_INTERNAL_KEYWORDS:
... |
2,618 | def _after_start(self):
delay = self.request.config.getoption('--qute-delay-start')
if delay:
with self.disable_capturing():
print(f"- waiting {delay}ms for quteprocess "
f"(PID: {self.proc.processId()})...")
time.sleep(delay / 1000)... | Wait before continuing if requested, e.g. for debugger attachment. | 9 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _after_start(self):
delay = self.request.config.getoption('--qute-delay-start')
if delay:
with self.disable_capturing():
print(f"- wa... |
2,619 | def list_secrets(path, default=None):
if default is None:
default = CommandExecutionError
log.debug("Listing vault secret keys for %s in %s", __grains__["id"], path)
version2 = __utils__["vault.is_v2"](path)
if version2["v2"]:
path = version2["metadata"]
try:
url = "v1/{... |
.. versionchanged:: 3001
The ``default`` argument has been added. When the path or path/key
combination is not found, an exception will be raised, unless a default
is provided.
List secret keys at the path in vault. The vault policy used must allow this.
The path should end with a ... | 60 | 66 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def list_secrets(path, default=None):
if default is None:
default = CommandExecutionError
log.debug("Listing vault secret keys for %s in %s", __grains__["id"], path)
... |
2,620 | def test_custom_kwargs_sharded(tmpdir, cls):
strategy = cls(reduce_fp16=True)
strategy.model = Mock(spec=LightningModule)
strategy.model.trainer = Mock()
class_name = "sharded" if isinstance(strategy, DDPShardedStrategy) else "sharded_spawn"
with mock.patch(f"pytorch_lightning.strategies.{clas... | Tests to ensure that if custom kwargs are passed, they are set correctly. | 13 | 49 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_custom_kwargs_sharded(tmpdir, cls):
strategy = cls(reduce_fp16=True)
strategy.model = Mock(spec=LightningModule)
strategy.model.trainer = Mock()
class_name = "s... |
2,621 | def versions_from_parentdir(parentdir_prefix, root, verbose):
rootdirs = []
for _ in range(3):
dirname = os.path.basename(root)
if dirname.startswith(parentdir_prefix):
return {"version": dirname[len(parentdir_prefix):],
"full-revisionid": None,
... | Try to determine the version from the parent directory name.
Source tarballs conventionally unpack into a directory that includes both
the project name and a version string. We will also support searching up
two directory levels for an appropriately named parent directory
# This file was generated by ... | 84 | 58 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def versions_from_parentdir(parentdir_prefix, root, verbose):
rootdirs = []
for _ in range(3):
dirname = os.path.basename(root)
if dirname.startswith(parentdir_... |
2,622 | def response_add(self, request, obj, post_url_continue=None):
opts = obj._meta
preserved_filters = self.get_preserved_filters(request)
obj_url = reverse(
"admin:%s_%s_change" % (opts.app_label, opts.model_name),
args=(quote(obj.pk),),
current_app=self... |
Determine the HttpResponse for the add_view stage.
| 7 | 248 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def response_add(self, request, obj, post_url_continue=None):
opts = obj._meta
preserved_filters = self.get_preserved_filters(request)
obj_url = reverse(
... |
2,623 | def test_tika_parse_unreachable(self):
html = '<html><head><meta http-equiv="content-type" content="text/html; charset=UTF-8"></head><body><p>Some Text</p></body></html>'
# Check if exception is raised when Tika cannot be reached.
self.parser.tika_server = ""
self.assertRaises(... |
GIVEN:
- Fresh start
WHEN:
- tika parsing is called but tika is not available
THEN:
- a ParseError Exception is thrown
| 22 | 26 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_tika_parse_unreachable(self):
html = '<html><head><meta http-equiv="content-type" content="text/html; charset=UTF-8"></head><body><p>Some Text</p></body></html>'
... |
2,624 | def test_read_config_file_2():
tpot_obj = TPOTRegressor()
assert_raises(ValueError, tpot_obj._read_config_file, "tests/test_config.py.bad")
| Assert that _read_config_file rasies ValueError with wrong dictionary format | 9 | 8 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_read_config_file_2():
tpot_obj = TPOTRegressor()
assert_raises(ValueError, tpot_obj._read_config_file, "tests/test_config.py.bad")
```
###Assistant : Asse... |
2,625 | def pre_delete_handler(self, sender, instance, **kwargs):
key = self.get_key_for_instance(instance)
object_type = instance._meta.verbose_name
# Delete an existing object
logger.debug(f"[{self.branch}] Staging deletion of {object_type} {instance} (PK: {instance.pk})")
se... |
Hooks to the pre_delete signal when a branch is active to queue delete actions.
| 14 | 28 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def pre_delete_handler(self, sender, instance, **kwargs):
key = self.get_key_for_instance(instance)
object_type = instance._meta.verbose_name
# Delete an ex... |
2,626 | def _reset_state(self):
self.cache = {}
self.resolved_nodes = 0
self.finished_last_inference = True
# maps DAGNode uuid to unique instance of a gradio block
self.node_to_block: Dict[DAGNode, Any] = {}
# maps InputAttributeNodes to unique instance of interactive ... | Resets state for each new RayServeHandle representing a new DAG. | 10 | 42 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _reset_state(self):
self.cache = {}
self.resolved_nodes = 0
self.finished_last_inference = True
# maps DAGNode uuid to unique instance of a grad... |
2,627 | def find_element(self, selector):
return self.driver.find_element(By.CSS_SELECTOR, selector)
| find_element returns the first found element by the css `selector`
shortcut to `driver.find_element(By.CSS_SELECTOR, ...)`. | 14 | 6 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def find_element(self, selector):
return self.driver.find_element(By.CSS_SELECTOR, selector)
```
###Assistant : find_element returns the first found element by ... |
2,628 | def test_bad_persist_value(self):
with self.assertRaises(StreamlitAPIException) as e:
| Throw an error if an invalid value is passed to 'persist'. | 11 | 6 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_bad_persist_value(self):
with self.assertRaises(StreamlitAPIException) as e:
```
###Assistant : Throw an error if an invalid value is passed to 'persis... |
2,629 | def _getDataFileTagsOptionHelp():
return % ", ".join(
"'%s' (%s)" % d for d in data_files_tags
)
data_file_tags_option = data_group.add_option(
"--data-file-tags",
action="append",
dest="data_file_tags",
metavar="DATA_TAGS",
default=[],
)
parser.add_option_group(data_group)
exe... | \
For included data files, special handlings can be chosen. With the
commercial plugins, e.g. files can be included directly in the
binary. The list is completed by some plugins. With the current
list of plugins, these are available: %s.
The default is empty.\
Execute immediately the created binary (or import the compi... | 1,740 | 859 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _getDataFileTagsOptionHelp():
return % ", ".join(
"'%s' (%s)" % d for d in data_files_tags
)
data_file_tags_option = data_group.add_option(
"--data-file-tags",
... |
2,630 | def test_collect_workflow_action_data_post(self):
response = self.client.post(
reverse(
"wagtailadmin_pages:collect_workflow_action_data",
args=(
self.page.id,
"approve",
self.page.current_workflow_t... |
This tests that a POST request to the collect_workflow_action_data view (for the approve action) returns a modal response with the validated data
| 22 | 34 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_collect_workflow_action_data_post(self):
response = self.client.post(
reverse(
"wagtailadmin_pages:collect_workflow_action_data",
... |
2,631 | def test_02_train_predictor(self):
query = f
response = self.handler.native_query(query)
self.assertTrue(response.type == RESPONSE_TYPE.OK)
|
CREATE PREDICTOR {self.test_model_1}
FROM {PG_HANDLER_NAME} (SELECT * FROM {self.data_table_1} limit 50)
PREDICT rental_price
| 13 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_02_train_predictor(self):
query = f
response = self.handler.native_query(query)
self.assertTrue(response.type == RESPONSE_TYPE.OK)
```
###Assist... |
2,632 | def __call__(self, results):
img = results['img']
if self.to_float32:
img = img.astype(np.float32)
results['img_path'] = None
results['img'] = img
height, width = img.shape[:2]
results['height'] = height
results['width'] = width
resu... | Call functions to add image meta information.
Args:
results (dict): Result dict with Webcam read image in
``results['img']``.
Returns:
dict: The dict contains loaded image and meta information.
| 28 | 36 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __call__(self, results):
img = results['img']
if self.to_float32:
img = img.astype(np.float32)
results['img_path'] = None
results['... |
2,633 | def test_jemalloc_env_var_propagate():
gcs_ptype = ray.ray_constants.PROCESS_TYPE_GCS_SERVER
expected = {}
actual = ray._private.services.propagate_jemalloc_env_var(
jemalloc_path="", jemalloc_conf="", jemalloc_comps=[], process_type=gcs_ptype
)
assert actual == expected
actual... | Test `propagate_jemalloc_env_var`
If the shared library path is not specified,
it should return an empty dict.
When the shared library is specified
When the malloc config is specified
| 28 | 114 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_jemalloc_env_var_propagate():
gcs_ptype = ray.ray_constants.PROCESS_TYPE_GCS_SERVER
expected = {}
actual = ray._private.services.propagate_jemalloc_env_var(
... |
2,634 | def aug_test_bboxes(self, feats, img_metas, rescale=False):
# check with_nms argument
gb_sig = signature(self.get_results)
gb_args = [p.name for p in gb_sig.parameters.values()]
gbs_sig = signature(self._get_results_single)
gbs_args = [p.name for p in gbs_sig.parameters.... | Test det bboxes with test time augmentation, can be applied in
DenseHead except for ``RPNHead`` and its variants, e.g., ``GARPNHead``,
etc.
Args:
feats (list[Tensor]): the outer list indicates test-time
augmentations and inner Tensor should have a shape NxCxHxW,
... | 131 | 171 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def aug_test_bboxes(self, feats, img_metas, rescale=False):
# check with_nms argument
gb_sig = signature(self.get_results)
gb_args = [p.name for p in gb_sig.... |
2,635 | def pauseProducing(self) -> None:
logger.info("[%s] Pause producing", self.id())
self.state = ConnectionStates.PAUSED
| This is called when both the kernel send buffer and the twisted
tcp connection send buffers have become full.
We don't actually have any control over those sizes, so we buffer some
commands ourselves before knifing the connection due to the remote
failing to keep up.
| 46 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def pauseProducing(self) -> None:
logger.info("[%s] Pause producing", self.id())
self.state = ConnectionStates.PAUSED
```
###Assistant : This is called ... |
2,636 | def throw(self, typ, val=None, tb=None):
if val is None:
if tb is None:
raise typ
val = typ()
if tb is not None:
val = val.with_traceback(tb)
raise val
| Raise an exception in the coroutine.
Return next yielded value or raise StopIteration.
| 13 | 28 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def throw(self, typ, val=None, tb=None):
if val is None:
if tb is None:
raise typ
val = typ()
if tb is not None:
... |
2,637 | def _exit_buffer(self) -> None:
self._buffer_index -= 1
self._check_buffer()
| Leave buffer context, and render content if required. | 8 | 8 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _exit_buffer(self) -> None:
self._buffer_index -= 1
self._check_buffer()
```
###Assistant : Leave buffer context, and render content if required.
... |
2,638 | def flatten_sensors_data(sensor):
if "temp" in sensor["data"]:
sensor["data"]["temperature"] = sensor["data"]["temp"]["c"]
return sensor
| Deconstruct SwitchBot library temp object C/Fº readings from dictionary. | 9 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def flatten_sensors_data(sensor):
if "temp" in sensor["data"]:
sensor["data"]["temperature"] = sensor["data"]["temp"]["c"]
return sensor
```
###Assistant ... |
2,639 | def test_shared_embedding_column_with_non_sequence_categorical(self):
with tf.Graph().as_default():
vocabulary_size = 3
sparse_input_a = tf.compat.v1.SparseTensorValue(
# example 0, ids [2]
# example 1, ids [0, 1]
indices=((0, 0), ... | Tests that error is raised for non-sequence shared embedding
column. | 10 | 115 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_shared_embedding_column_with_non_sequence_categorical(self):
with tf.Graph().as_default():
vocabulary_size = 3
sparse_input_a = tf.compat.v1... |
2,640 | def get_next_stock_market_days(last_stock_day, n_next_days) -> list:
n_days = 0
l_pred_days = []
years: list = []
holidays: list = []
if isinstance(last_stock_day, datetime):
while n_days < n_next_days:
last_stock_day += timedelta(hours=24)
year = last_stock_day.... | Gets the next stock market day. Checks against weekends and holidays | 11 | 90 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_next_stock_market_days(last_stock_day, n_next_days) -> list:
n_days = 0
l_pred_days = []
years: list = []
holidays: list = []
if isinstance(last_stock_day, d... |
2,641 | async def test_max_concurrent_in_progress_functions(extra_req_num):
max_req = 10
a = A(max_num_call=max_req)
# Run more than allowed concurrent async functions should trigger rate limiting
res_arr = await asyncio.gather(
*[a.fn1() if i % 2 == 0 else a.fn2() for i in range(max_req + extra_r... | Test rate limiting for concurrent in-progress requests on StateHead | 9 | 120 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_max_concurrent_in_progress_functions(extra_req_num):
max_req = 10
a = A(max_num_call=max_req)
# Run more than allowed concurrent async functions should trigg... |
2,642 | def transpose_qkv(X, num_heads):
# Shape of input `X`:
# (`batch_size`, no. of queries or key-value pairs, `num_hiddens`).
# Shape of output `X`:
# (`batch_size`, no. of queries or key-value pairs, `num_heads`,
# `num_hiddens` / `num_heads`)
X = X.reshape(X.shape[0], X.shape[1], num_heads, ... | Transposition for parallel computation of multiple attention heads.
Defined in :numref:`sec_multihead-attention` | 11 | 87 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def transpose_qkv(X, num_heads):
# Shape of input `X`:
# (`batch_size`, no. of queries or key-value pairs, `num_hiddens`).
# Shape of output `X`:
# (`batch_size`, no. of... |
2,643 | def current_state(self, session=NEW_SESSION) -> str:
return (
session.query(TaskInstance.state)
.filter(
TaskInstance.dag_id == self.dag_id,
TaskInstance.task_id == self.task_id,
TaskInstance.run_id == self.run_id,
)
... |
Get the very latest state from the database, if a session is passed,
we use and looking up the state becomes part of the session, otherwise
a new session is used.
:param session: SQLAlchemy ORM Session
| 36 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def current_state(self, session=NEW_SESSION) -> str:
return (
session.query(TaskInstance.state)
.filter(
TaskInstance.dag_id == self.... |
2,644 | def house_graph(create_using=None):
description = [
"adjacencylist",
"House Graph",
5,
[[2, 3], [1, 4], [1, 4, 5], [2, 3, 5], [3, 4]],
]
G = make_small_undirected_graph(description, create_using)
return G
|
Returns the House graph (square with triangle on top)
The house graph is a simple undirected graph with
5 nodes and 6 edges [1]_.
Parameters
----------
create_using : NetworkX graph constructor, optional (default=nx.Graph)
Graph type to create. If graph instance, then cleared before po... | 68 | 28 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def house_graph(create_using=None):
description = [
"adjacencylist",
"House Graph",
5,
[[2, 3], [1, 4], [1, 4, 5], [2, 3, 5], [3, 4]],
]
G = ... |
2,645 | def check_header_validity(header):
name, value = header
for part in header:
if type(part) not in HEADER_VALIDATORS:
raise InvalidHeader(
f"Header part ({part!r}) from {{{name!r}: {value!r}}} must be "
f"of type str or bytes, not {type(part)}"
... | Verifies that header parts don't contain leading whitespace
reserved characters, or return characters.
:param header: tuple, in the format (name, value).
| 21 | 40 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def check_header_validity(header):
name, value = header
for part in header:
if type(part) not in HEADER_VALIDATORS:
raise InvalidHeader(
f"H... |
2,646 | def test_orderline_query(staff_api_client, permission_manage_orders, fulfilled_order):
order = fulfilled_order
query =
line = order.lines.first()
metadata_key = "md key"
metadata_value = "md value"
line.store_value_in_private_metadata({metadata_key: metadata_value})
line.store_value_in_me... |
query OrdersQuery {
orders(first: 1) {
edges {
node {
lines {
thumbnail(size: 540) {
url
}
variant {
... | 62 | 129 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_orderline_query(staff_api_client, permission_manage_orders, fulfilled_order):
order = fulfilled_order
query =
line = order.lines.first()
metadata_key = "md key"
... |
2,647 | def in4_pseudoheader(proto, u, plen):
# type: (int, IP, int) -> bytes
if u.len is not None:
if u.ihl is None:
olen = sum(len(x) for x in u.options)
ihl = 5 + olen // 4 + (1 if olen % 4 else 0)
else:
ihl = u.ihl
ln = max(u.len - 4 * ihl, 0)
els... | IPv4 Pseudo Header as defined in RFC793 as bytes
:param proto: value of upper layer protocol
:param u: IP layer instance
:param plen: the length of the upper layer and payload
| 31 | 132 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def in4_pseudoheader(proto, u, plen):
# type: (int, IP, int) -> bytes
if u.len is not None:
if u.ihl is None:
olen = sum(len(x) for x in u.options)
... |
2,648 | def doc_resample_fillna(method, refer_to, params=None, overwrite_template_params=False):
action = f"fill missing values in each group independently using {method} method"
params_substitution = "limit : int\n"
if params:
params_substitution = (
params
if overwrite_templa... |
Build decorator which adds docstring for the resample fillna query compiler method.
Parameters
----------
method : str
Fillna method name.
refer_to : str
Method name in ``modin.pandas.resample.Resampler`` module to refer to for
more information about parameters and output f... | 189 | 91 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def doc_resample_fillna(method, refer_to, params=None, overwrite_template_params=False):
action = f"fill missing values in each group independently using {method} method"
params... |
2,649 | def delete_events(ref_type, ref_name):
events = (
frappe.db.sql_list(
,
(ref_type, ref_name),
)
or []
)
if events:
frappe.delete_doc("Event", events, for_reload=True)
| SELECT
distinct `tabEvent`.name
from
`tabEvent`, `tabEvent Participants`
where
`tabEvent`.name = `tabEvent Participants`.parent
and `tabEvent Participants`.reference_doctype = %s
and `tabEvent Participants`.reference_docname = %s
| 22 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def delete_events(ref_type, ref_name):
events = (
frappe.db.sql_list(
,
(ref_type, ref_name),
)
or []
)
if events:
frappe.delete_doc("Event", events, for_reload=True)
... |
2,650 | def check_started(self) -> ReplicaStartupStatus:
status, version = self._actor.check_ready()
if status == ReplicaStartupStatus.SUCCEEDED:
# Re-assign DeploymentVersion if start / update / recover succeeded
# by reading re-computed version in RayServeReplica
... | Check if the replica has started. If so, transition to RUNNING.
Should handle the case where the replica has already stopped.
Returns:
status: Most recent state of replica by
querying actor obj ref
| 33 | 39 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def check_started(self) -> ReplicaStartupStatus:
status, version = self._actor.check_ready()
if status == ReplicaStartupStatus.SUCCEEDED:
# Re-assign De... |
2,651 | async def test_battery_low(hass, utcnow):
helper = await setup_test_component(
hass, create_battery_level_sensor, suffix="battery"
)
state = await helper.async_update(
ServicesTypes.BATTERY_SERVICE,
{
CharacteristicsTypes.BATTERY_LEVEL: 1,
Characteristic... | Test reading the state of a HomeKit battery's low state. | 10 | 44 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_battery_low(hass, utcnow):
helper = await setup_test_component(
hass, create_battery_level_sensor, suffix="battery"
)
state = await helper.async_upda... |
2,652 | def _hyab(self, y_true, y_pred):
delta = y_true - y_pred
root = K.sqrt(K.clip(K.pow(delta[..., 0:1], 2), self._epsilon, None))
delta_norm = frobenius_norm(delta[..., 1:3])
return root + delta_norm
| Compute the HyAB distance between true and predicted images.
Parameters
----------
y_true: :class:`plaidml.tile.Value`
The ground truth batch of images in standard or Hunt-adjusted L*A*B* color space
y_pred: :class:`plaidml.tile.Value`
The predicted batch of ima... | 56 | 24 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _hyab(self, y_true, y_pred):
delta = y_true - y_pred
root = K.sqrt(K.clip(K.pow(delta[..., 0:1], 2), self._epsilon, None))
delta_norm = frobenius_norm(de... |
2,653 | def test_dry_run(self, run_cleanup_mock, dry_run_arg, expected):
args = self.parser.parse_args(
[
'db',
'clean',
'--clean-before-timestamp',
'2021-01-01',
*dry_run_arg,
]
)
db_command... |
When tz included in the string then default timezone should not be used.
| 13 | 26 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_dry_run(self, run_cleanup_mock, dry_run_arg, expected):
args = self.parser.parse_args(
[
'db',
'clean',
... |
2,654 | def async_dismiss_setup_message(hass, entry_id):
persistent_notification.async_dismiss(hass, entry_id)
| Dismiss persistent notification and remove QR code. | 7 | 5 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def async_dismiss_setup_message(hass, entry_id):
persistent_notification.async_dismiss(hass, entry_id)
```
###Assistant : Dismiss persistent notification and remove QR... |
2,655 | def get_containing_app_config(self, object_name):
self.check_apps_ready()
candidates = []
for app_config in self.app_configs.values():
if object_name.startswith(app_config.name):
subpath = object_name[len(app_config.name) :]
if subpath == "" o... |
Look for an app config containing a given object.
object_name is the dotted Python path to the object.
Return the app config for the inner application in case of nesting.
Return None if the object isn't in any registered app config.
| 41 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_containing_app_config(self, object_name):
self.check_apps_ready()
candidates = []
for app_config in self.app_configs.values():
if object_... |
2,656 | def _track_variables(self, value):
for val in tf.nest.flatten(value):
if isinstance(val, tf.Variable):
self._track_variable(val)
elif tf_utils.is_extension_type(val):
# Manually expand extension types to track resource variables.
n... | Tracks `Variable`s including `Variable`s in `CompositeTensor`s. | 6 | 28 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _track_variables(self, value):
for val in tf.nest.flatten(value):
if isinstance(val, tf.Variable):
self._track_variable(val)
elif... |
2,657 | def _create_vhost_v2(self, node):
addrs = set()
for param in node.parameters:
addr = obj.Addr.fromstring(param)
if addr:
addrs.add(addr)
is_ssl = False
# Exclusion to match the behavior in get_virtual_hosts_v2
sslengine = node.fin... | Used by get_virtual_hosts_v2 to create vhost objects using ParserNode
interfaces.
:param interfaces.BlockNode node: The BlockNode object of VirtualHost block
:returns: newly created vhost
:rtype: :class:`~certbot_apache.obj.VirtualHost`
| 25 | 111 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _create_vhost_v2(self, node):
addrs = set()
for param in node.parameters:
addr = obj.Addr.fromstring(param)
if addr:
addr... |
2,658 | def insert_on(self, path, loc=None, replace=False):
loc = loc or self.location
if not loc:
return
nloc = _normalize_cached(loc)
bdir = os.path.dirname(nloc)
npath = [(p and _normalize_cached(p) or p) for p in path]
for p, item in enumerate(npath):
... | Ensure self.location is on path
If replace=False (default):
- If location is already in path anywhere, do nothing.
- Else:
- If it's an egg and its parent directory is on path,
insert just ahead of the parent.
- Else: add to the end of path.
... | 100 | 154 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def insert_on(self, path, loc=None, replace=False):
loc = loc or self.location
if not loc:
return
nloc = _normalize_cached(loc)
bdir = ... |
2,659 | def serving_output(self, output):
pkv = tf.convert_to_tensor(output.past_key_values) if self.config.use_cache else None
hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions e... |
The XGLM Model transformer with a language modeling head on top (linear layer with weights tied to the input
embeddings).
| 20 | 47 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def serving_output(self, output):
pkv = tf.convert_to_tensor(output.past_key_values) if self.config.use_cache else None
hs = tf.convert_to_tensor(output.hidden_states) if sel... |
2,660 | def _apply_func_to_list_of_partitions(cls, func, partitions, **kwargs):
preprocessed_map_func = cls.preprocess_func(func)
key_futures = RayWrapper.materialize(
[
partition.apply(preprocessed_map_func, **kwargs)
for partition in partitions
... |
Apply `func` to a list of remote partitions from `partitions`.
Parameters
----------
func : callable
The function to apply.
partitions : np.ndarray
NumPy array with partitions.
**kwargs : dict
Additional keywords arguments to be passe... | 59 | 30 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _apply_func_to_list_of_partitions(cls, func, partitions, **kwargs):
preprocessed_map_func = cls.preprocess_func(func)
key_futures = RayWrapper.materialize(
... |
2,661 | def _execute_impl(self, *args, **kwargs) -> ObjectRef:
return self._deployment_function_handle.remote(
*self._bound_args, **self._bound_kwargs
)
| Executor of DeploymentNode getting called each time on dag.execute.
The execute implementation is recursive, that is, the method nodes will
receive whatever this method returns. We return a handle here so method
node can directly call upon.
| 37 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _execute_impl(self, *args, **kwargs) -> ObjectRef:
return self._deployment_function_handle.remote(
*self._bound_args, **self._bound_kwargs
)
... |
2,662 | def save_img(path, x, data_format=None, file_format=None, scale=True, **kwargs):
if data_format is None:
data_format = backend.image_data_format()
img = array_to_img(x, data_format=data_format, scale=scale)
if img.mode == 'RGBA' and (file_format == 'jpg' or file_format == 'jpeg'):
warnings.warn('The JP... | Saves an image stored as a Numpy array to a path or file object.
Args:
path: Path or file object.
x: Numpy array.
data_format: Image data format, either "channels_first" or
"channels_last".
file_format: Optional file format override. If omitted, the format to use
is determined... | 82 | 51 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def save_img(path, x, data_format=None, file_format=None, scale=True, **kwargs):
if data_format is None:
data_format = backend.image_data_format()
img = array_to_img(x, data_forma... |
2,663 | def log_commenting_changes(self, changes, revision):
for comment in changes["new_comments"]:
comment.log_create(page_revision=revision, user=self.request.user)
for comment in changes["edited_comments"]:
comment.log_edit(page_revision=revision, user=self.request.user)
... |
Generates log entries for any changes made to comments or replies.
| 11 | 61 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def log_commenting_changes(self, changes, revision):
for comment in changes["new_comments"]:
comment.log_create(page_revision=revision, user=self.request.user)
... |
2,664 | def __new__(cls, stylename, **kwargs):
# The "class" should have the _style_list attribute, which is a mapping
# of style names to style classes.
_list = stylename.replace(" ", "").split(",")
_name = _list[0].lower()
try:
_cls = cls._style_list[_name]
... | Return the instance of the subclass with the given style name. | 11 | 76 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __new__(cls, stylename, **kwargs):
# The "class" should have the _style_list attribute, which is a mapping
# of style names to style classes.
_list = sty... |
2,665 | def losses(self):
collected_losses = []
for layer in self._flatten_layers():
# If any eager losses are present, we assume the model to be part of
# an eager training loop (either a custom one or the one used when
# `run_eagerly=True`) and so we always return ... | List of losses added using the `add_loss()` API.
Variable regularization tensors are created when this property is
accessed, so it is eager safe: accessing `losses` under a
`tf.GradientTape` will propagate gradients back to the corresponding
variables.
Examples:
>>> cl... | 128 | 93 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def losses(self):
collected_losses = []
for layer in self._flatten_layers():
# If any eager losses are present, we assume the model to be part of
... |
2,666 | def fit(self, X, y, Xy=None):
self._validate_params()
X, y = self._validate_data(X, y, y_numeric=True, multi_output=True)
_normalize = _deprecate_normalize(
self.normalize, default=True, estimator_name=self.__class__.__name__
)
alpha = getattr(self, "alpha... | Fit the model using X, y as training data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data.
y : array-like of shape (n_samples,) or (n_samples, n_targets)
Target values.
Xy : array-like of shape (n_samples,) or (n_sam... | 70 | 71 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def fit(self, X, y, Xy=None):
self._validate_params()
X, y = self._validate_data(X, y, y_numeric=True, multi_output=True)
_normalize = _deprecate_normalize... |
2,667 | def _decode_block_string(block_string):
assert isinstance(block_string, str)
ops = block_string.split('_')
options = {}
for op in ops:
splits = re.split(r'(\d.*)', op)
if len(splits) >= 2:
key, value = splits[:2]
options[k... | Gets a block through a string notation of arguments. | 9 | 73 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _decode_block_string(block_string):
assert isinstance(block_string, str)
ops = block_string.split('_')
options = {}
for op in ops:
s... |
2,668 | def copy(a, order='K', subok=False):
return array(a, order=order, subok=subok, copy=True)
# Basic operations
|
Return an array copy of the given object.
Parameters
----------
a : array_like
Input data.
order : {'C', 'F', 'A', 'K'}, optional
Controls the memory layout of the copy. 'C' means C-order,
'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
'C' otherwise.... | 340 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def copy(a, order='K', subok=False):
return array(a, order=order, subok=subok, copy=True)
# Basic operations
```
###Assistant :
Return an array copy of the given... |
2,669 | def test_context_placement_group():
driver_code =
proc = run_string_as_driver_nonblocking(driver_code)
|
import ray
from ray.data.context import DatasetContext
from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy
from ray._private.test_utils import placement_group_assert_no_leak
ray.init(num_cpus=1)
context = DatasetContext.get_current()
# This placement group will take up all cores of the local ... | 64 | 7 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_context_placement_group():
driver_code =
proc = run_string_as_driver_nonblocking(driver_code)
```
###Assistant :
import ray
from ray.data.context import Datas... |
2,670 | def reorder_categories(self, new_categories, ordered=None):
if set(self.dtype.categories) != set(new_categories):
raise ValueError(
"items in new_categories are not the same as in old categories"
)
return self.set_categories(new_categories, ordered=ordere... |
Reorder categories as specified in new_categories.
`new_categories` need to include all old categories and no new category
items.
Parameters
----------
new_categories : Index-like
The categories in new order.
ordered : bool, optional
Wheth... | 114 | 25 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def reorder_categories(self, new_categories, ordered=None):
if set(self.dtype.categories) != set(new_categories):
raise ValueError(
"items in new... |
2,671 | def test_get_member_list_no_permission_former_member_with_at_token(self):
# create a room, invite the user and the user joins
room_id = self.helper.create_room_as("@alice:red")
self.helper.invite(room_id, "@alice:red", self.user_id)
self.helper.join(room_id, self.user_id)
... |
Tests that a former member of the room can not get the member list
(in the case that they use an at token).
| 23 | 150 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_get_member_list_no_permission_former_member_with_at_token(self):
# create a room, invite the user and the user joins
room_id = self.helper.create_room_as("@... |
2,672 | def _keep_original_ws(s, tag_s):
return ''.join(
c if tag_c == " " and c.isspace() else tag_c
for c, tag_c in zip(s, tag_s)
)
| Replace whitespace with the original whitespace characters in `s` | 9 | 22 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _keep_original_ws(s, tag_s):
return ''.join(
c if tag_c == " " and c.isspace() else tag_c
for c, tag_c in zip(s, tag_s)
)
```
###Assistant : R... |
2,673 | def unregister_cmap(name):
cmap = _colormaps.get(name, None)
_colormaps.unregister(name)
return cmap
|
Remove a colormap recognized by :func:`get_cmap`.
You may not remove built-in colormaps.
If the named colormap is not registered, returns with no error, raises
if you try to de-register a default colormap.
.. warning::
Colormap names are currently a shared namespace that may be used
... | 118 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def unregister_cmap(name):
cmap = _colormaps.get(name, None)
_colormaps.unregister(name)
return cmap
```
###Assistant :
Remove a colormap recognized by :f... |
2,674 | def _get_extraction_protocol_with_magic_number(f) -> Optional[str]:
magic_number = f.read(MAGIC_NUMBER_MAX_LENGTH)
f.seek(0)
for i in range(MAGIC_NUMBER_MAX_LENGTH):
compression = MAGIC_NUMBER_TO_COMPRESSION_PROTOCOL.get(magic_number[: MAGIC_NUMBER_MAX_LENGTH - i])
if compression is not... | read the magic number from a file-like object and return the compression protocol | 13 | 53 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_extraction_protocol_with_magic_number(f) -> Optional[str]:
magic_number = f.read(MAGIC_NUMBER_MAX_LENGTH)
f.seek(0)
for i in range(MAGIC_NUMBER_MAX_LENGTH):
... |
2,675 | def _get_veths(net_data):
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.OrderedDict()
no_names = True
for item in net_data:
if item and isinstance(item, dict):
item = list(item.it... |
Parse the nic setup inside lxc conf tuples back to a dictionary indexed by
network interface
| 16 | 118 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_veths(net_data):
if isinstance(net_data, dict):
net_data = list(net_data.items())
nics = salt.utils.odict.OrderedDict()
current_nic = salt.utils.odict.Order... |
2,676 | def start_stdout_logging() -> None:
if '_stdout_' in _handlers:
return
handler = StreamHandler(sys.stdout)
handler.setFormatter(_StdoutFormatter())
_handlers['_stdout_'] = handler
_root_logger.addHandler(handler)
|
Register the stdout handler.
This function should be invoked on importing nni.
It is safe to call it multiple times.
| 20 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def start_stdout_logging() -> None:
if '_stdout_' in _handlers:
return
handler = StreamHandler(sys.stdout)
handler.setFormatter(_StdoutFormatter())
_handlers['... |
2,677 | def get_staffing_plan_detail(designation, company, offer_date):
detail = frappe.db.sql(
,
(designation, company, offer_date),
as_dict=1,
)
return frappe._dict(detail[0]) if (detail and detail[0].parent) else None
@frappe.whitelist() |
SELECT DISTINCT spd.parent,
sp.from_date as from_date,
sp.to_date as to_date,
sp.name,
sum(spd.vacancies) as vacancies,
spd.designation
FROM `tabStaffing Plan Detail` spd, `tabStaffing Plan` sp
WHERE
sp.docstatus=1
AND spd.designation=%s
AND sp.company=%s
AND spd.parent = sp.name
AN... | 38 | 22 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_staffing_plan_detail(designation, company, offer_date):
detail = frappe.db.sql(
,
(designation, company, offer_date),
as_dict=1,
)
return frappe._dict(detail[0]) if (detail... |
2,678 | def test_display_name(self) -> None:
evaluator = self._get_evaluator({"body": "foo bar baz"})
condition = {
"kind": "contains_display_name",
}
# Blank names are skipped.
self.assertFalse(evaluator.matches(condition, "@user:test", ""))
# Check a dis... | Check for a matching display name in the body of the event. | 12 | 94 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_display_name(self) -> None:
evaluator = self._get_evaluator({"body": "foo bar baz"})
condition = {
"kind": "contains_display_name",
}
... |
2,679 | def test_readlink_not_a_link(file, source):
with pytest.raises(SaltInvocationError) as exc:
file.readlink(path=source)
assert "A valid link was not specified" in exc.value.message
|
Test readlink where the path is not a link
Should throw a SaltInvocationError
| 13 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_readlink_not_a_link(file, source):
with pytest.raises(SaltInvocationError) as exc:
file.readlink(path=source)
assert "A valid link was not specified" in exc.val... |
2,680 | def get_periodic_data(entry, filters):
periodic_data = {}
for d in entry:
period = get_period(d.posting_date, filters)
bal_qty = 0
# if period against item does not exist yet, instantiate it
# insert existing balance dict against period, and add/subtract to it
if periodic_data.get(d.item_code) and not pe... | Structured as:
Item 1
- Balance (updated and carried forward):
- Warehouse A : bal_qty/value
- Warehouse B : bal_qty/value
- Jun 2021 (sum of warehouse quantities used in report)
- Warehouse A : bal_qty/value
... | 118 | 106 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_periodic_data(entry, filters):
periodic_data = {}
for d in entry:
period = get_period(d.posting_date, filters)
bal_qty = 0
# if period against item does not exist yet, ins... |
2,681 | def shuffle(*arrays, random_state=None, n_samples=None):
return resample(
*arrays, replace=False, n_samples=n_samples, random_state=random_state
)
| Shuffle arrays or sparse matrices in a consistent way.
This is a convenience alias to ``resample(*arrays, replace=False)`` to do
random permutations of the collections.
Parameters
----------
*arrays : sequence of indexable data-structures
Indexable data-structures can be arrays, lists, dat... | 248 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def shuffle(*arrays, random_state=None, n_samples=None):
return resample(
*arrays, replace=False, n_samples=n_samples, random_state=random_state
)
```
###A... |
2,682 | def check_changes(self, args, results): # type: (SanityConfig, Results) -> None
integration_targets = list(walk_integration_targets())
module_targets = list(walk_module_targets())
integration_targets_by_name = dict((target.name, target) for target in integration_targets)
modul... | Check changes and store results in the provided result dictionary. | 10 | 118 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def check_changes(self, args, results): # type: (SanityConfig, Results) -> None
integration_targets = list(walk_integration_targets())
module_targets = list(walk_mo... |
2,683 | def test_overlap_first(business_client, setup_before_upload, show_overlap_first):
c = business_client
config = dict(
title='test_overlap_first',
is_published=True,
maximum_annotations=1,
show_overlap_first=show_overlap_first,
sampling="Uniform sampling",
label_con... |
<View>
<Text name="text" value="$text"></Text>
<Choices name="text_class" choice="single">
<Choice value="class_A"></Choice>
<Choice value="class_B"></Choice>
</Choices>
</View> | 13 | 122 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_overlap_first(business_client, setup_before_upload, show_overlap_first):
c = business_client
config = dict(
title='test_overlap_first',
is_published=True,
... |
2,684 | def svd_flip(u, v, u_based_decision=True):
if u_based_decision:
# columns of u, rows of v
max_abs_cols = np.argmax(np.abs(u), axis=0)
signs = np.sign(u[max_abs_cols, range(u.shape[1])])
u *= signs
v *= signs[:, np.newaxis]
else:
# rows of v, columns of u
... | Sign correction to ensure deterministic output from SVD.
Adjusts the columns of u and the rows of v such that the loadings in the
columns in u that are largest in absolute value are always positive.
Parameters
----------
u : ndarray
Parameters u and v are the output of `linalg.svd` or
... | 171 | 54 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def svd_flip(u, v, u_based_decision=True):
if u_based_decision:
# columns of u, rows of v
max_abs_cols = np.argmax(np.abs(u), axis=0)
signs = np.sign(u[max_a... |
2,685 | def extra_action_out_fn(self) -> Dict[str, TensorType]:
extra_fetches = {}
# Action-logp and action-prob.
if self._sampled_action_logp is not None:
extra_fetches[SampleBatch.ACTION_PROB] = self._sampled_action_prob
extra_fetches[SampleBatch.ACTION_LOGP] = self._s... | Extra values to fetch and return from compute_actions().
By default we return action probability/log-likelihood info
and action distribution inputs (if present).
Returns:
Dict[str, TensorType]: An extra fetch-dict to be passed to and
returned from the compute_actio... | 37 | 36 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def extra_action_out_fn(self) -> Dict[str, TensorType]:
extra_fetches = {}
# Action-logp and action-prob.
if self._sampled_action_logp is not None:
... |
2,686 | async def cleanup_finished_triggers(self):
for trigger_id, details in list(self.triggers.items()):
if details["task"].done():
# Check to see if it exited for good reasons
saved_exc = None
try:
result = details["task"].resul... |
Go through all trigger tasks (coroutines) and clean up entries for
ones that have exited, optionally warning users if the exit was
not normal.
| 24 | 162 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def cleanup_finished_triggers(self):
for trigger_id, details in list(self.triggers.items()):
if details["task"].done():
# Check to see if i... |
2,687 | def get_global_travel_time(self):
gtt = 0
for entity in self.tripinfo:
gtt += self.get_duration(entity, default=0.0)
for entity in self.personinfo:
gtt += self.get_duration(entity, default=0.0)
return gtt
#############################################... |
Returns the global travel time computed from SUMO tripinfo data.
The functions process_tripinfo_file() needs to be called in advance
to initialize the data structures required.
| 25 | 26 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_global_travel_time(self):
gtt = 0
for entity in self.tripinfo:
gtt += self.get_duration(entity, default=0.0)
for entity in self.personinf... |
2,688 | def post(self, url, data=None, json=None, **kwargs):
r
return self.request("POST", url, data=data, json=json, **kwargs)
| Sends a POST request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) json to send in the body o... | 55 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def post(self, url, data=None, json=None, **kwargs):
r
return self.request("POST", url, data=data, json=json, **kwargs)
```
###Assistant : Sends a POST request.... |
2,689 | def __getitem__(self, idx):
# type: (int) -> HPackHdrEntry
assert idx >= 0
if idx > type(self)._static_entries_last_idx:
idx -= type(self)._static_entries_last_idx + 1
if idx >= len(self._dynamic_table):
raise KeyError(
'EINVAL... | Gets an element from the header tables (static or dynamic indifferently)
:param int idx: the index number of the entry to retrieve. If the index
value is superior to the last index of the static entry table, then the
dynamic entry type is requested, following the procedure described in
... | 76 | 44 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __getitem__(self, idx):
# type: (int) -> HPackHdrEntry
assert idx >= 0
if idx > type(self)._static_entries_last_idx:
idx -= type(self)._stati... |
2,690 | def test_pagination(self):
parent = Parent.objects.create(name="anything")
for i in range(1, 31):
Child.objects.create(name="name %s" % i, parent=parent)
Child.objects.create(name="filtered %s" % i, parent=parent)
request = self.factory.get("/child/")
re... |
Regression tests for #12893: Pagination in admins changelist doesn't
use queryset set by modeladmin.
| 14 | 67 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_pagination(self):
parent = Parent.objects.create(name="anything")
for i in range(1, 31):
Child.objects.create(name="name %s" % i, parent=parent)... |
2,691 | def transform(self, X):
if self.solver == "lsqr":
raise NotImplementedError(
"transform not implemented for 'lsqr' solver (use 'svd' or 'eigen')."
)
check_is_fitted(self)
X = self._validate_data(X, reset=False)
if self.solver == "svd":
... | Project data to maximize class separation.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Input data.
Returns
-------
X_new : ndarray of shape (n_samples, n_components) or \
(n_samples, min(rank, n_components))
... | 46 | 47 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def transform(self, X):
if self.solver == "lsqr":
raise NotImplementedError(
"transform not implemented for 'lsqr' solver (use 'svd' or 'eigen').... |
2,692 | async def test_heater_cooler_hvac_mode_vs_hvac_action(hass, utcnow):
helper = await setup_test_component(hass, create_heater_cooler_service)
# Simulate that current temperature is above target temp
# Heating might be on, but hvac_action currently 'off'
await helper.async_update(
ServicesTy... | Check that we haven't conflated hvac_mode and hvac_action. | 8 | 101 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_heater_cooler_hvac_mode_vs_hvac_action(hass, utcnow):
helper = await setup_test_component(hass, create_heater_cooler_service)
# Simulate that current temperature... |
2,693 | def not_in_timeout(cls, last_triggered, timeout):
return (
last_triggered is None
or timeout is None
or (time.time() - last_triggered > timeout)
)
| Checks if current error lies not in timeout after last trigger (potential reset of connection). | 15 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def not_in_timeout(cls, last_triggered, timeout):
return (
last_triggered is None
or timeout is None
or (time.time() - last_triggered > t... |
2,694 | def get_rescored_finished(self, n_best=None):
# if we never actually finished, force one
if not self.finished:
self.outputs[-1][0] = self.eos
self.finished.append(
_HypothesisTail(
timestep=len(self.outputs) - 1,
hy... |
Return finished hypotheses according to adjusted scores.
Score adjustment is done according to the Google NMT paper, which
penalizes long utterances.
:param n_best:
number of finalized hypotheses to return
:return:
list of (tokens, score, token_metadat... | 86 | 201 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_rescored_finished(self, n_best=None):
# if we never actually finished, force one
if not self.finished:
self.outputs[-1][0] = self.eos
... |
2,695 | def quantile(self, q=0.5, **kwargs):
return self._downsample("quantile", q=q, **kwargs)
|
Return value at the given quantile.
Parameters
----------
q : float or array-like, default 0.5 (50% quantile)
Returns
-------
DataFrame or Series
Quantile of values within each group.
See Also
--------
Series.quantile
... | 80 | 8 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def quantile(self, q=0.5, **kwargs):
return self._downsample("quantile", q=q, **kwargs)
```
###Assistant :
Return value at the given quantile.
... |
2,696 | def current_columns(self):
return copy.deepcopy(self.custcols) #deepcopy to prevent users from changing it
|
Return the currently defined custom columns
Return the currently defined custom columns including the ones that haven't
yet been created. It is a dict of dicts defined as follows:
custcols[lookup_name] = {
'label': lookup_name,
'name': column... | 69 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def current_columns(self):
return copy.deepcopy(self.custcols) #deepcopy to prevent users from changing it
```
###Assistant :
Return the currently defi... |
2,697 | def transform_vector(self, vector):
return Vector(
(vector.x + self.offset[0]) * self.scale[0],
(vector.y + self.offset[1]) * self.scale[1],
)
|
Transforms the given vector into the coordinate space of the final image.
Use this to find out where a point on the source image would end up in the
final image after cropping/resizing has been performed.
Returns a new vector.
| 40 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def transform_vector(self, vector):
return Vector(
(vector.x + self.offset[0]) * self.scale[0],
(vector.y + self.offset[1]) * self.scale[1],
... |
2,698 | def _load_from_file(module_path):
from imp import PY_SOURCE, load_module
imported = None
if module_path:
with open(module_path, 'r') as openfile:
imported = load_module("mod", openfile, module_path, ('imported', 'r', PY_SOURCE))
return imported
|
Load a python module from its absolute filesystem path
| 9 | 27 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _load_from_file(module_path):
from imp import PY_SOURCE, load_module
imported = None
if module_path:
with open(module_path, 'r') as openfile:
import... |
2,699 | def _alter_column_type_sql(self, table, old_field, new_field, new_type):
if not hasattr(old_field, "dim") or not hasattr(new_field, "dim"):
return super()._alter_column_type_sql(table, old_field, new_field, new_type)
if old_field.dim == 2 and new_field.dim == 3:
sql_alt... |
Special case when dimension changed.
| 5 | 60 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _alter_column_type_sql(self, table, old_field, new_field, new_type):
if not hasattr(old_field, "dim") or not hasattr(new_field, "dim"):
return super()._alter... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.