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,200 | def _setup_room_for_insertion_backfill_tests(self) -> _BackfillSetupInfo:
room_id = "!backfill-room-test:some-host"
depth_map: Dict[str, int] = {
"1": 1,
"2": 2,
"insertion_eventA": 3,
"3": 4,
"insertion_eventB": 5,
"4": 6... |
Sets up a room with various insertion event backward extremities to test
backfill functions against.
Returns:
_BackfillSetupInfo including the `room_id` to test against and
`depth_map` of events in the room
| 30 | 27 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _setup_room_for_insertion_backfill_tests(self) -> _BackfillSetupInfo:
room_id = "!backfill-room-test:some-host"
depth_map: Dict[str, int] = {
"1": 1... |
2,201 | def postprocessing(data):
if type_to_string(type(data)) == "torch.Tensor":
try:
import torch
from torchvision import transforms
# By default Torch tensors are displayed as images. To display them as JSON,
# the user can simply convert them to numpy arra... | Add support for types that are not supported by Gradio.
Some data types like PyTorch tensors, cannot be processed and displayed through
Gradio. Thus we extend support to these data types by transforming them into a form
that Gradio can process and display.
| 43 | 59 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def postprocessing(data):
if type_to_string(type(data)) == "torch.Tensor":
try:
import torch
from torchvision import transforms
# By de... |
2,202 | def get_scrap_item_details(bom_no):
scrap_items = {}
for item in frappe.db.sql(
,
bom_no,
as_dict=1,
):
scrap_items[item.item_code] = item.stock_qty
return scrap_items
| select item_code, stock_qty from `tabBOM Scrap Item`
where parent = %s | 11 | 18 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_scrap_item_details(bom_no):
scrap_items = {}
for item in frappe.db.sql(
,
bom_no,
as_dict=1,
):
scrap_items[item.item_code] = item.stock_qty
return scrap_items
... |
2,203 | def get_is_active(self, session=NEW_SESSION) -> Optional[None]:
return session.query(DagModel.is_active).filter(DagModel.dag_id == self.dag_id).scalar()
| Returns a boolean indicating whether this DAG is active | 9 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_is_active(self, session=NEW_SESSION) -> Optional[None]:
return session.query(DagModel.is_active).filter(DagModel.dag_id == self.dag_id).scalar()
```
###... |
2,204 | def is_homepage(self) -> bool:
return self.is_top_level and self.is_index and self.file.url in ('.', './', 'index.html')
previous_page: Optional[Page]
next_page: Optional[Page]
parent: Optional[Section]
children: None = None
is_section: bool = False
... | Evaluates to `True` for the homepage of the site and `False` for all other pages.The [page][mkdocs.structure.pages.Page] object for the previous page or `None`.
The value will be `None` if the current page is the first item in the site navigation
or if the current page is not included in the navigation at all.T... | 158 | 36 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def is_homepage(self) -> bool:
return self.is_top_level and self.is_index and self.file.url in ('.', './', 'index.html')
previous_page: Optional[Page]
next_pa... |
2,205 | def _filetypes(self):
all_files = ("All files", "*.*")
filetypes = dict(
default=(all_files,),
alignments=[("Faceswap Alignments", "*.fsa"), all_files],
config_project=[("Faceswap Project files", "*.fsw"), all_files],
config_task=[("Faceswap Task ... | dict: The accepted extensions for each file type for opening/saving | 10 | 154 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _filetypes(self):
all_files = ("All files", "*.*")
filetypes = dict(
default=(all_files,),
alignments=[("Faceswap Alignments", "*.fsa"), ... |
2,206 | def result(self):
if self._state == _CANCELLED:
exc = self._make_cancelled_error()
raise exc
if self._state != _FINISHED:
raise exceptions.InvalidStateError('Result is not ready.')
self.__log_traceback = False
if self._exception is not None:
... | Return the result this future represents.
If the future has been cancelled, raises CancelledError. If the
future's result isn't yet available, raises InvalidStateError. If
the future is done and has an exception set, this exception is raised.
| 37 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def result(self):
if self._state == _CANCELLED:
exc = self._make_cancelled_error()
raise exc
if self._state != _FINISHED:
raise e... |
2,207 | def _set_fsspec_for_multiprocess() -> None:
fsspec.asyn.iothread[0] = None
fsspec.asyn.loop[0] = None
|
Clear reference to the loop and thread.
This is necessary otherwise HTTPFileSystem hangs in the ML training loop.
Only required for fsspec >= 0.9.0
See https://github.com/fsspec/gcsfs/issues/379
| 26 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _set_fsspec_for_multiprocess() -> None:
fsspec.asyn.iothread[0] = None
fsspec.asyn.loop[0] = None
```
###Assistant :
Clear reference to the loop and threa... |
2,208 | def stable_cumsum(arr, axis=None, rtol=1e-05, atol=1e-08):
out = np.cumsum(arr, axis=axis, dtype=np.float64)
expected = np.sum(arr, axis=axis, dtype=np.float64)
if not np.all(
np.isclose(
out.take(-1, axis=axis), expected, rtol=rtol, atol=atol, equal_nan=True
)
):
... | Use high precision for cumsum and check that final value matches sum.
Warns if the final cumulative sum does not match the sum (up to the chosen
tolerance).
Parameters
----------
arr : array-like
To be cumulatively summed as flat.
axis : int, default=None
Axis along which the c... | 93 | 47 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def stable_cumsum(arr, axis=None, rtol=1e-05, atol=1e-08):
out = np.cumsum(arr, axis=axis, dtype=np.float64)
expected = np.sum(arr, axis=axis, dtype=np.float64)
if not np.al... |
2,209 | def confirm(self):
args = request.args
dag_id = args.get('dag_id')
task_id = args.get('task_id')
dag_run_id = args.get('dag_run_id')
state = args.get('state')
origin = args.get('origin')
if 'map_index' not in args:
map_indexes: Optional[List[... | Show confirmation page for marking tasks as success or failed. | 10 | 208 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def confirm(self):
args = request.args
dag_id = args.get('dag_id')
task_id = args.get('task_id')
dag_run_id = args.get('dag_run_id')
state = ... |
2,210 | def resample(self) -> Dict[str, Any]:
result = {}
for module in self.nas_modules:
result.update(module.resample(memo=result))
return result
| Trigger the resample for each ``nas_module``.
Sometimes (e.g., in differentiable cases), it does nothing.
Returns
-------
dict
Sampled architecture.
| 19 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def resample(self) -> Dict[str, Any]:
result = {}
for module in self.nas_modules:
result.update(module.resample(memo=result))
return result
... |
2,211 | def test_json_to_doc_attribute_consistency(doc):
doc_json = doc.to_json()
doc_json["tokens"][1].pop("morph")
with pytest.raises(ValueError):
Doc(doc.vocab).from_json(doc_json)
| Test that Doc.from_json() raises an exception if tokens don't all have the same set of properties. | 16 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_json_to_doc_attribute_consistency(doc):
doc_json = doc.to_json()
doc_json["tokens"][1].pop("morph")
with pytest.raises(ValueError):
Doc(doc.vocab).from_json... |
2,212 | def test_index_css_classes(self):
# General index page
response = self.client.get(reverse("admin:index"))
self.assertContains(response, '<div class="app-admin_views module')
self.assertContains(response, '<tr class="model-actor">')
self.assertContains(response, '<tr clas... |
CSS class names are used for each app and model on the admin index
pages (#17050).
| 16 | 37 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_index_css_classes(self):
# General index page
response = self.client.get(reverse("admin:index"))
self.assertContains(response, '<div class="app-admi... |
2,213 | def test_action_column_class(self):
response = self.client.get(reverse("admin:admin_views_subscriber_changelist"))
self.assertIsNotNone(response.context["action_form"])
self.assertContains(response, "action-checkbox-column")
| The checkbox column class is present in the response. | 9 | 8 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_action_column_class(self):
response = self.client.get(reverse("admin:admin_views_subscriber_changelist"))
self.assertIsNotNone(response.context["action_form... |
2,214 | def hashkey(cls, *args, **kwargs):
return cachetools.keys.hashkey(f"<{cls.__name__}>", *args, **kwargs)
|
Usage of @cachetools.cached has changed to @cachetools.cachedmethod
The previous cachetools decorator called the hash function and passed in (self, key).
The new cachtools decorator calls the hash function with just (key).
Ideally, we would continue to pass self, however, the cachetools... | 116 | 8 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def hashkey(cls, *args, **kwargs):
return cachetools.keys.hashkey(f"<{cls.__name__}>", *args, **kwargs)
```
###Assistant :
Usage of @cachetools.cached... |
2,215 | def load(cls, path):
with open(path) as yaml_file:
data = yaml.safe_load(yaml_file)
if not isinstance(data, dict):
raise TypeError(f'Conent of config file {path} is not a dict/object')
utils.set_base_path(Path(path).parent)
config = cls(**data)
ut... |
Load a YAML config file from file system.
Since YAML is a superset of JSON, it can also load JSON files.
This method raises exception if:
- The file is not available
- The file content is not valid YAML
- Top level value of the YAML is not object
- The YAML co... | 89 | 31 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def load(cls, path):
with open(path) as yaml_file:
data = yaml.safe_load(yaml_file)
if not isinstance(data, dict):
raise TypeError(f'Conent o... |
2,216 | def get_leave_allocation_for_period(employee, leave_type, from_date, to_date):
leave_allocated = 0
leave_allocations = frappe.db.sql(
,
{"from_date": from_date, "to_date": to_date, "employee": employee, "leave_type": leave_type},
as_dict=1,
)
if leave_allocations:
for leave_alloc in leave_allocations:
l... |
select employee, leave_type, from_date, to_date, total_leaves_allocated
from `tabLeave Allocation`
where employee=%(employee)s and leave_type=%(leave_type)s
and docstatus=1
and (from_date between %(from_date)s and %(to_date)s
or to_date between %(from_date)s and %(to_date)s
or (from_date < %(from_d... | 35 | 34 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_leave_allocation_for_period(employee, leave_type, from_date, to_date):
leave_allocated = 0
leave_allocations = frappe.db.sql(
,
{"from_date": from_date, "to_date": to_date, "em... |
2,217 | def test_proxy_model_content_type_is_used_for_log_entries(self):
proxy_content_type = ContentType.objects.get_for_model(
ArticleProxy, for_concrete_model=False
)
post_data = {
"site": self.site.pk,
"title": "Foo",
"hist": "Bar",
... |
Log entries for proxy models should have the proxy model's contenttype
(#21084).
| 12 | 92 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_proxy_model_content_type_is_used_for_log_entries(self):
proxy_content_type = ContentType.objects.get_for_model(
ArticleProxy, for_concrete_model=False
... |
2,218 | def typename(typ, short=False) -> str:
if not isinstance(typ, type):
return typename(type(typ))
try:
if not typ.__module__ or typ.__module__ == "builtins":
return typ.__name__
else:
if short:
module, *_ = typ.__module__.split(".")
... |
Return the name of a type
Examples
--------
>>> typename(int)
'int'
>>> from dask.core import literal
>>> typename(literal)
'dask.core.literal'
>>> typename(literal, short=True)
'dask.literal'
| 23 | 42 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def typename(typ, short=False) -> str:
if not isinstance(typ, type):
return typename(type(typ))
try:
if not typ.__module__ or typ.__module__ == "builtins":
... |
2,219 | def fetch_command(self, subcommand):
# Get commands outside of try block to prevent swallowing exceptions
commands = get_commands()
try:
app_name = commands[subcommand]
except KeyError:
if os.environ.get("DJANGO_SETTINGS_MODULE"):
# If `su... |
Try to fetch the given subcommand, printing a message with the
appropriate command called from the command line (usually
"django-admin" or "manage.py") if it can't be found.
| 27 | 114 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def fetch_command(self, subcommand):
# Get commands outside of try block to prevent swallowing exceptions
commands = get_commands()
try:
app_name... |
2,220 | def url(self, name):
name = self._normalize_name(clean_name(name))
blob = self.bucket.blob(name)
blob_params = self.get_object_parameters(name)
no_signed_url = (
blob_params.get('acl', self.default_acl) == 'publicRead' or not self.querystring_auth)
if not se... |
Return public url or a signed url for the Blob.
This DOES NOT check for existance of Blob - that makes codes too slow
for many use cases.
Overridden to force the use of the IAM signBlob API.
See https://github.com/googleapis/python-storage/blob/519074112775c19742522158f612b467cf... | 42 | 63 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def url(self, name):
name = self._normalize_name(clean_name(name))
blob = self.bucket.blob(name)
blob_params = self.get_object_parameters(name)
no_si... |
2,221 | def check_is_fitted(estimator, attributes=None, *, msg=None, all_or_any=all):
if isclass(estimator):
raise TypeError("{} is a class, not an instance.".format(estimator))
if msg is None:
msg = (
"This %(name)s instance is not fitted yet. Call 'fit' with "
"appropriate... | Perform is_fitted validation for estimator.
Checks if the estimator is fitted by verifying the presence of
fitted attributes (ending with a trailing underscore) and otherwise
raises a NotFittedError with the given message.
If an estimator does not set any attributes with a trailing underscore, it
... | 213 | 104 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def check_is_fitted(estimator, attributes=None, *, msg=None, all_or_any=all):
if isclass(estimator):
raise TypeError("{} is a class, not an instance.".format(estimator))
... |
2,222 | def p_mean_variance(self, model, x, t, transformer_out, clip_denoised=True, model_kwargs=None):
if model_kwargs is None:
model_kwargs = {}
B, C = x.shape[:2]
assert t.shape == (B,)
model_output = model(x, t, transformer_out)
assert model_output.shape == (B,... |
Apply the model to get p(x_{t-1} | x_t), as well as a prediction of
the initial x, x_0.
:param model: the model, which takes a signal and a batch of timesteps
as input.
:param x: the [N x C x ...] tensor at time t.
:param t: a 1-D Tensor of timesteps.
... | 116 | 113 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def p_mean_variance(self, model, x, t, transformer_out, clip_denoised=True, model_kwargs=None):
if model_kwargs is None:
model_kwargs = {}
B, C = x.shap... |
2,223 | def test_invalid_parameters_in_stacking():
stacker = StackingClassifier(estimators=[])
html_output = estimator_html_repr(stacker)
assert html.escape(str(stacker)) in html_output
| Invalidate stacking configuration uses default repr.
Non-regression test for #24009.
| 10 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_invalid_parameters_in_stacking():
stacker = StackingClassifier(estimators=[])
html_output = estimator_html_repr(stacker)
assert html.escape(str(stacker)) in html_o... |
2,224 | def add_permissions():
for doctype in ("South Africa VAT Settings", "South Africa VAT Account"):
add_permission(doctype, "All", 0)
for role in ("Accounts Manager", "Accounts User", "System Manager"):
add_permission(doctype, role, 0)
update_permission_property(doctype, role, 0, "write", 1)
update_permiss... | Add Permissions for South Africa VAT Settings and South Africa VAT Account
and VAT Audit Report | 16 | 59 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def add_permissions():
for doctype in ("South Africa VAT Settings", "South Africa VAT Account"):
add_permission(doctype, "All", 0)
for role in ("Accounts Manager", "Accounts User", "S... |
2,225 | def has_delete_permission(self, request, obj=None):
opts = self.opts
codename = get_permission_codename("delete", opts)
return request.user.has_perm("%s.%s" % (opts.app_label, codename))
|
Return True if the given request has permission to change the given
Django model instance, the default implementation doesn't examine the
`obj` parameter.
Can be overridden by the user in subclasses. In such case it should
return True if the given request has permission to dele... | 72 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def has_delete_permission(self, request, obj=None):
opts = self.opts
codename = get_permission_codename("delete", opts)
return request.user.has_perm("%s.%s" ... |
2,226 | def set_3d_properties(self, zs=0, zdir='z'):
xs = self.get_xdata()
ys = self.get_ydata()
zs = cbook._to_unmasked_float_array(zs).ravel()
zs = np.broadcast_to(zs, len(xs))
self._verts3d = juggle_axes(xs, ys, zs, zdir)
self.stale = True
|
Set the *z* position and direction of the line.
Parameters
----------
zs : float or array of floats
The location along the *zdir* axis in 3D space to position the
line.
zdir : {'x', 'y', 'z'}
Plane to plot line orthogonal to. Default: 'z'.
... | 52 | 26 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def set_3d_properties(self, zs=0, zdir='z'):
xs = self.get_xdata()
ys = self.get_ydata()
zs = cbook._to_unmasked_float_array(zs).ravel()
zs = np.broa... |
2,227 | def clear_tasks(self):
logger.debug("Clearing stored tasks")
self._tasks = {}
| Clears all of the stored tasks.
This is required when loading a task stored in a legacy project file, and is only to be
called by :class:`Project` when a project has been loaded which is in fact a task.
| 39 | 8 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def clear_tasks(self):
logger.debug("Clearing stored tasks")
self._tasks = {}
```
###Assistant : Clears all of the stored tasks.
This is requi... |
2,228 | def add_department_leaves(events, start, end, employee, company):
department = frappe.db.get_value("Employee", employee, "department")
if not department:
return
# department leaves
department_employees = frappe.db.sql_list(
,
(department, company),
)
filter_conditions = ' and employee in ("%s")' % '", "'... | select name from tabEmployee where department=%s
and company=%s | 8 | 39 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def add_department_leaves(events, start, end, employee, company):
department = frappe.db.get_value("Employee", employee, "department")
if not department:
return
# department leaves
d... |
2,229 | def is_file(self, follow_links=None):
if follow_links is None:
follow_links = True
node_stat = self._stat if follow_links else self._lstat
return stat.S_ISREG(node_stat.st_mode)
|
Get whether the entry is a regular file.
*follow_links* (:class:`bool` or :data:`None`) is whether to follow
symbolic links. If this is :data:`True`, a symlink to a regular file
will result in :data:`True`. Default is :data:`None` for :data:`True`.
Returns whether the entry is... | 46 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def is_file(self, follow_links=None):
if follow_links is None:
follow_links = True
node_stat = self._stat if follow_links else self._lstat
retur... |
2,230 | def test_tabular_model_form_meta_readonly_field(self):
response = self.client.get(reverse("admin:admin_inlines_someparentmodel_add"))
self.assertContains(
response,
'<img src="/static/admin/img/icon-unknown.svg" '
'class="help help-tooltip" width="10" height=... |
Tabular inlines use ModelForm.Meta.help_texts and labels for read-only
fields.
| 9 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_tabular_model_form_meta_readonly_field(self):
response = self.client.get(reverse("admin:admin_inlines_someparentmodel_add"))
self.assertContains(
... |
2,231 | def test_edit_get_unlocked_no_lock_permission(self):
# Use edit permission only
self.set_permissions(["change"])
# Get the edit page
response = self.client.get(self.get_url("edit"))
html = response.content.decode()
lock_url = self.get_url("lock")
# Shou... | A user cannot lock an object without the lock permission. | 10 | 121 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_edit_get_unlocked_no_lock_permission(self):
# Use edit permission only
self.set_permissions(["change"])
# Get the edit page
response = self... |
2,232 | def increment_project_counter(project, delta=1, using="default"):
if delta <= 0:
raise ValueError("There is only one way, and that's up.")
sample_rate = options.get("store.projectcounter-modern-upsert-sample-rate")
modern_upsert = sample_rate and random.random() <= sample_rate
# To preve... | This method primarily exists so that south code can use it. | 11 | 184 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def increment_project_counter(project, delta=1, using="default"):
if delta <= 0:
raise ValueError("There is only one way, and that's up.")
sample_rate = options.get("st... |
2,233 | def test_multiple_gen_nexts_closed_in_different_order(self) -> None:
id_gen = self._create_id_generator()
| Check that we handle overlapping calls to gen_next, even when their IDs
created and persisted in different orders. | 18 | 7 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_multiple_gen_nexts_closed_in_different_order(self) -> None:
id_gen = self._create_id_generator()
```
###Assistant : Check that we handle overlapping ca... |
2,234 | def str_presenter(dumper, data):
if len(data.splitlines()) > 1: # check for multiline string
return dumper.represent_scalar("tag:yaml.org,2002:str", data, style="|")
return dumper.represent_scalar("tag:yaml.org,2002:str", data)
yaml.add_representer(str, str_presenter)
yaml.representer.SafeRepres... |
configures yaml for dumping multiline strings
Ref: https://stackoverflow.com/questions/8640959/how-can-i-control-what-scalar-form-pyyaml-uses-for-my-data
| 8 | 34 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def str_presenter(dumper, data):
if len(data.splitlines()) > 1: # check for multiline string
return dumper.represent_scalar("tag:yaml.org,2002:str", data, style="|")
re... |
2,235 | def _get_permissions(self, user_obj, obj, from_name):
if not user_obj.is_active or user_obj.is_anonymous or obj is not None:
return set()
perm_cache_name = "_effective_permissions_cache"
if not getattr(user_obj, perm_cache_name, None):
perms = getattr(self, f"_g... | Return the permissions of `user_obj` from `from_name`.
`from_name` can be either "group" or "user" to return permissions from
`_get_group_permissions` or `_get_user_permissions` respectively.
| 22 | 44 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_permissions(self, user_obj, obj, from_name):
if not user_obj.is_active or user_obj.is_anonymous or obj is not None:
return set()
perm_cache_nam... |
2,236 | def test_trainable_layers(self):
model = model = self._get_model()
# Set the last layer to *not* be trainable.
model.layers[-1].trainable = False
self._train_model(model, use_dataset=True)
loaded = self._save_and_load(model)
self._test_evaluation(model, loaded)
... | Tests that trainable status of individual layers is preserved. | 9 | 28 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_trainable_layers(self):
model = model = self._get_model()
# Set the last layer to *not* be trainable.
model.layers[-1].trainable = False
sel... |
2,237 | def _reorder_labels(self, row_positions=None, col_positions=None):
if row_positions is not None:
ordered_rows = self._partition_mgr_cls.map_axis_partitions(
0, self._partitions, lambda df: df.iloc[row_positions]
)
row_idx = self.index[row_positions]
... |
Reorder the column and or rows in this DataFrame.
Parameters
----------
row_positions : list of int, optional
The ordered list of new row orders such that each position within the list
indicates the new position.
col_positions : list of int, optional
... | 70 | 57 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _reorder_labels(self, row_positions=None, col_positions=None):
if row_positions is not None:
ordered_rows = self._partition_mgr_cls.map_axis_partitions(
... |
2,238 | def get_actual_sle_dict(name):
sles = frappe.db.sql(
,
name,
as_dict=1,
)
sle_dict = {}
for d in sles:
sle_dict[(d.item_code, d.warehouse)] = {
"actual_qty": d.actual_qty,
"stock_value_difference": d.stock_value_difference,
}
return sle_dict
|
select
item_code, warehouse,
sum(actual_qty) as actual_qty,
sum(stock_value_difference) as stock_value_difference
from `tabStock Ledger Entry`
where voucher_type = 'Asset Capitalization' and voucher_no = %s
group by item_code, warehouse
having actual_qty != 0
| 30 | 27 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_actual_sle_dict(name):
sles = frappe.db.sql(
,
name,
as_dict=1,
)
sle_dict = {}
for d in sles:
sle_dict[(d.item_code, d.warehouse)] = {
"actual_qty": d.actual_qty,
... |
2,239 | async def _async_process_on_unload(self) -> None:
if self._on_unload is not None:
while self._on_unload:
self._on_unload.pop()()
while self._pending_tasks:
pending = [task for task in self._pending_tasks if not task.done()]
self._pending_task... | Process the on_unload callbacks and wait for pending tasks. | 9 | 30 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def _async_process_on_unload(self) -> None:
if self._on_unload is not None:
while self._on_unload:
self._on_unload.pop()()
while s... |
2,240 | def apply_func(partition, func, *args, **kwargs):
result = func(partition, *args, **kwargs)
return result, get_ip()
|
Execute a function on the partition in a worker process.
Parameters
----------
partition : pandas.DataFrame
A pandas DataFrame the function needs to be executed on.
func : callable
The function to perform.
*args : list
Positional arguments to pass to ``func``.
**kwa... | 89 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def apply_func(partition, func, *args, **kwargs):
result = func(partition, *args, **kwargs)
return result, get_ip()
```
###Assistant :
Execute a function on t... |
2,241 | def _proc_function_remote(self, *, fun, low, user, tag, jid, daemonize=True):
if daemonize and not salt.utils.platform.is_windows():
# Shutdown the multiprocessing before daemonizing
salt.log.setup.shutdown_multiprocessing_logging()
salt.utils.process.daemonize()
... |
Run this method in a multiprocess target to execute the function on the
master and fire the return data on the event bus
| 23 | 53 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _proc_function_remote(self, *, fun, low, user, tag, jid, daemonize=True):
if daemonize and not salt.utils.platform.is_windows():
# Shutdown the multiprocessi... |
2,242 | def array_safe(a, like, **kwargs):
from dask.array.routines import array
return _array_like_safe(np.array, array, a, like, **kwargs)
|
If `a` is `dask.array`, return `dask.array.asarray(a, **kwargs)`,
otherwise return `np.asarray(a, like=like, **kwargs)`, dispatching
the call to the library that implements the like array. Note that
when `a` is a `dask.Array` backed by `cupy.ndarray` but `like`
isn't, this function will call `a.com... | 66 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def array_safe(a, like, **kwargs):
from dask.array.routines import array
return _array_like_safe(np.array, array, a, like, **kwargs)
```
###Assistant :
If `a... |
2,243 | def get_tables(self) -> StatusResponse:
query =
result = self.native_query(query)
df = result.data_frame
df = df.drop(['type', 'type'], axis=1)
result.data_frame = df.rename(columns={'name': 'table_name'})
return result
|
Return list of entities that will be accessible as tables.
Returns:
HandlerResponse
SHOW TABLES;
| 14 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_tables(self) -> StatusResponse:
query =
result = self.native_query(query)
df = result.data_frame
df = df.drop(['type', 'type'], axis=1)
... |
2,244 | def accuracy(self, params, X, Y, averaged=True):
Y_hat = self.apply(params, X)
Y_hat = d2l.reshape(Y_hat, (-1, Y_hat.shape[-1]))
preds = d2l.astype(d2l.argmax(Y_hat, axis=1), Y.dtype)
compare = d2l.astype(preds == d2l.reshape(Y, -1), d2l.float32)
return d2l.reduce_mean(c... | Compute the number of correct predictions.
Defined in :numref:`sec_classification` | 9 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def accuracy(self, params, X, Y, averaged=True):
Y_hat = self.apply(params, X)
Y_hat = d2l.reshape(Y_hat, (-1, Y_hat.shape[-1]))
preds = d2l.astype(d2l.argma... |
2,245 | def open_metadata(self, book, custom_columns):
if config.config_use_google_drive:
if not gdriveutils.is_gdrive_ready():
raise Exception('Google Drive is configured but not ready')
web_content_link = gdriveutils.get_metadata_backup_via_gdrive(book.path)
if not... | namespaces = {'dc': PURL_NAMESPACE, 'opf': OPF_NAMESPACE}
test = etree.parse(book_metadata_filepath)
root = test.getroot()
for i in root.iter():
self.log.info(i)
title = root.find("dc:metadata", namespaces)
pass
with open(book_metad... | 62 | 92 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def open_metadata(self, book, custom_columns):
if config.config_use_google_drive:
if not gdriveutils.is_gdrive_ready():
raise Exception('Google Drive is c... |
2,246 | def test_gevent_monkey(pyi_builder):
pyi_builder.test_source()
# The tkinter module may be available for import, but not actually importable due to missing shared libraries.
# Therefore, we need to use `can_import_module`-based skip decorator instead of `@importorskip`.
@pytest.mark.skipif(not can_import_module("... |
from gevent.monkey import patch_all
patch_all()
| 5 | 39 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_gevent_monkey(pyi_builder):
pyi_builder.test_source()
# The tkinter module may be available for import, but not actually importable due to missing shared libraries.
# Therefor... |
2,247 | def split_auth_netloc_from_url(url):
# type: (str) -> Tuple[str, str, Tuple[str, str]]
url_without_auth, (netloc, auth) = _transform_url(url, _get_netloc)
return url_without_auth, netloc, auth
|
Parse a url into separate netloc, auth, and url with no auth.
Returns: (url_without_auth, netloc, (username, password))
| 17 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def split_auth_netloc_from_url(url):
# type: (str) -> Tuple[str, str, Tuple[str, str]]
url_without_auth, (netloc, auth) = _transform_url(url, _get_netloc)
return url_without... |
2,248 | def test_non_str_color():
text = Text("test_color_inheritance", color=Color("blue"))
markup_text = MarkupText("test_color_inheritance", color=Color("blue"))
| Test that the Text and MarkupText can accept non_str color values
i.e. colour.Color(red). | 13 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_non_str_color():
text = Text("test_color_inheritance", color=Color("blue"))
markup_text = MarkupText("test_color_inheritance", color=Color("blue"))
```
##... |
2,249 | async def test_strategy_no_network_settings(pick_radio, mock_app, hass):
mock_app.load_network_info = MagicMock(side_effect=NetworkNotFormed())
result, port = await pick_radio(RadioType.ezsp)
assert (
config_flow.FORMATION_REUSE_SETTINGS
not in result["data_schema"].schema["next_step_i... | Test formation strategy when no network settings are present. | 9 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_strategy_no_network_settings(pick_radio, mock_app, hass):
mock_app.load_network_info = MagicMock(side_effect=NetworkNotFormed())
result, port = await pick_radio(... |
2,250 | def detrend(x, key=None, axis=None):
if key is None or key in ['constant', 'mean', 'default']:
return detrend(x, key=detrend_mean, axis=axis)
elif key == 'linear':
return detrend(x, key=detrend_linear, axis=axis)
elif key == 'none':
return detrend(x, key=detrend_none, axis=axis)... |
Return *x* with its trend removed.
Parameters
----------
x : array or sequence
Array or sequence containing the data.
key : {'default', 'constant', 'mean', 'linear', 'none'} or function
The detrending algorithm to use. 'default', 'mean', and 'constant' are
the same as `det... | 114 | 121 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def detrend(x, key=None, axis=None):
if key is None or key in ['constant', 'mean', 'default']:
return detrend(x, key=detrend_mean, axis=axis)
elif key == 'linear':
... |
2,251 | def has_unrendered_errors(bound_field):
return bound_field.errors and not hasattr(
bound_field.field.widget, "render_with_errors"
)
@register.filter(is_safe=True)
@stringfilter |
Return true if this field has errors that were not accounted for by render_with_errors, because
the widget does not support the render_with_errors method
| 23 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def has_unrendered_errors(bound_field):
return bound_field.errors and not hasattr(
bound_field.field.widget, "render_with_errors"
)
@register.filter(is_safe=True)
@str... |
2,252 | def test_raw_id_threshold_page_permission_inline_admin(self):
with self.settings(CMS_RAW_ID_USERS=1):
with self.assertNumQueries(1):
self.assertEqual(PagePermissionInlineAdmin.raw_id_fields, [])
# Create users to check if threshold is honored
self._get_guys(... |
Only count users when using an integer value as threshold for
CMS_RAW_ID_USERS.
| 12 | 36 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_raw_id_threshold_page_permission_inline_admin(self):
with self.settings(CMS_RAW_ID_USERS=1):
with self.assertNumQueries(1):
self.assertE... |
2,253 | def get_breaks(self, filename, lineno):
filename = self.canonic(filename)
return filename in self.breaks and \
lineno in self.breaks[filename] and \
Breakpoint.bplist[filename, lineno] or []
| Return all breakpoints for filename:lineno.
If no breakpoints are set, return an empty list.
| 14 | 22 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_breaks(self, filename, lineno):
filename = self.canonic(filename)
return filename in self.breaks and \
lineno in self.breaks[filename] and \
... |
2,254 | def test_override(self) -> None:
self.get_success(
self.store.register_user(
self.user_id,
self.pwhash,
approved=True,
)
)
user = self.get_success(self.store.get_user_by_id(self.user_id))
self.assertIsNotNo... | Tests that if we require approval for new accounts, but we explicitly say the
new user should be considered approved, they're marked as approved.
| 24 | 26 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_override(self) -> None:
self.get_success(
self.store.register_user(
self.user_id,
self.pwhash,
approved=... |
2,255 | def tokenize(lines, token='word'):
if token == 'word':
return [line.split() for line in lines]
elif token == 'char':
return [list(line) for line in lines]
else:
print('ERROR: unknown token type: ' + token)
| Split text lines into word or character tokens.
Defined in :numref:`sec_text_preprocessing` | 11 | 31 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def tokenize(lines, token='word'):
if token == 'word':
return [line.split() for line in lines]
elif token == 'char':
return [list(line) for line in lines]
el... |
2,256 | def make_purchase_order_for_default_supplier(source_name, selected_items=None, target_doc=None):
if not selected_items:
return
if isinstance(selected_items, str):
selected_items = json.loads(selected_items)
def set_missing_values(source, target):
target.supplier = supplier
target.apply_discount_on = ""
... | Creates Purchase Order for each Supplier. Returns a list of doc objects. | 12 | 252 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def make_purchase_order_for_default_supplier(source_name, selected_items=None, target_doc=None):
if not selected_items:
return
if isinstance(selected_items, str):
selected_items = j... |
2,257 | def resolve_relation(model, app_label=None, model_name=None):
if isinstance(model, str):
if model == RECURSIVE_RELATIONSHIP_CONSTANT:
if app_label is None or model_name is None:
raise TypeError(
'app_label and model_name must be provided to resolve '
... |
Turn a model class or model reference string and return a model tuple.
app_label and model_name are used to resolve the scope of recursive and
unscoped model relationship.
| 28 | 70 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def resolve_relation(model, app_label=None, model_name=None):
if isinstance(model, str):
if model == RECURSIVE_RELATIONSHIP_CONSTANT:
if app_label is None or mod... |
2,258 | def load_tf_weights(model, resolved_archive_file, ignore_mismatched_sizes=False, _prefix=None):
missing_layers = []
unexpected_layers = []
mismatched_layers = []
# Read the H5 file
with h5py.File(resolved_archive_file, "r") as sharded_checkpoint_file:
# Retrieve the name of each layer ... |
Detect missing and unexpected layers and load the TF weights from the shard file accordingly to their names and
shapes.
Args:
model (`tf.keras.models.Model`):
The model to load the weights into.
resolved_archive_file (`str`):
The location of the H5 file.
ign... | 83 | 479 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def load_tf_weights(model, resolved_archive_file, ignore_mismatched_sizes=False, _prefix=None):
missing_layers = []
unexpected_layers = []
mismatched_layers = []
# Read... |
2,259 | def css_classes(self, extra_classes=None):
if hasattr(extra_classes, "split"):
extra_classes = extra_classes.split()
extra_classes = set(extra_classes or [])
if self.errors and hasattr(self.form, "error_css_class"):
extra_classes.add(self.form.error_css_class)
... |
Return a string of space-separated CSS classes for this field.
| 10 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def css_classes(self, extra_classes=None):
if hasattr(extra_classes, "split"):
extra_classes = extra_classes.split()
extra_classes = set(extra_classes or... |
2,260 | def _get_free_vram(self) -> List[float]:
vram = [pynvml.nvmlDeviceGetMemoryInfo(handle).free / (1024 * 1024)
for handle in self._handles]
self._log("debug", f"GPU VRAM free: {vram}")
return vram
| Obtain the amount of VRAM that is available, in Megabytes, for each connected Nvidia
GPU.
Returns
-------
list
List of `float`s containing the amount of VRAM available, in Megabytes, for each
connected GPU as corresponding to the values in :attr:`_handles
... | 40 | 22 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_free_vram(self) -> List[float]:
vram = [pynvml.nvmlDeviceGetMemoryInfo(handle).free / (1024 * 1024)
for handle in self._handles]
self._log("... |
2,261 | def get_project(doctype, txt, searchfield, start, page_len, filters):
from erpnext.controllers.queries import get_match_cond
meta = frappe.get_meta(doctype)
searchfields = meta.get_search_fields()
search_columns = ", " + ", ".join(searchfields) if searchfields else ""
search_cond = " or " + " or ".join(field + " ... | select name {search_columns} from `tabProject`
where %(key)s like %(txt)s
%(mcond)s
{search_condition}
order by name
limit %(start)s, %(page_len)s | 17 | 69 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_project(doctype, txt, searchfield, start, page_len, filters):
from erpnext.controllers.queries import get_match_cond
meta = frappe.get_meta(doctype)
searchfields = meta.get_searc... |
2,262 | def build(self, var_list):
super().build(var_list)
if getattr(self, "_built", False):
return
self._built = True
self._momentums = []
self._velocities = []
self._u_product = tf.Variable(1.0, dtype=var_list[0].dtype)
# Keep a counter on how many... | Initialize optimizer variables.
Nadam optimizer has 2 types of variables: momentums and velocities.
Args:
var_list: list of model variables to build Nadam variables on.
| 24 | 59 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def build(self, var_list):
super().build(var_list)
if getattr(self, "_built", False):
return
self._built = True
self._momentums = []
... |
2,263 | def list_distinfo_files(self, absolute=False):
record_path = os.path.join(self.path, 'installed-files.txt')
if os.path.exists(record_path):
skip = True
with codecs.open(record_path, 'r', encoding='utf-8') as f:
for line in f:
line = li... |
Iterates over the ``installed-files.txt`` entries and returns paths for
each line if the path is pointing to a file located in the
``.egg-info`` directory or one of its subdirectories.
:parameter absolute: If *absolute* is ``True``, each returned path is
trans... | 60 | 49 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def list_distinfo_files(self, absolute=False):
record_path = os.path.join(self.path, 'installed-files.txt')
if os.path.exists(record_path):
skip = True
... |
2,264 | def mixin_scalable_deployment_parser(parser):
gp = mixin_base_deployment_parser(parser, title='Scalable Deployment')
gp.add_argument(
'--polling',
type=str,
default=PollingType.ANY.name,
help=,
)
gp.add_argument(
'--shards',
type=int,
defaul... | Mixing in arguments required by a scalable deployment into the given parser.
The deployment is scalable and can have shards, replicas and polling
:param parser: the parser instance to which we add arguments
The polling strategy of the Deployment and its endpoints (when `shards>1`).
Can be defined f... | 93 | 68 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def mixin_scalable_deployment_parser(parser):
gp = mixin_base_deployment_parser(parser, title='Scalable Deployment')
gp.add_argument(
'--polling',
type=str,
... |
2,265 | def test_explorer_list_private(self):
response = self.client.get(
reverse("wagtailadmin_explore", args=(self.private_page.id,))
)
# Check the response
self.assertEqual(response.status_code, 200)
# Must have one privacy icon (next to the private child page)
... |
This tests that there is a padlock displayed
next to the private child page in the private pages explorer listing
| 20 | 35 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_explorer_list_private(self):
response = self.client.get(
reverse("wagtailadmin_explore", args=(self.private_page.id,))
)
# Check the re... |
2,266 | def next(self):
self._check("ra")
if self.firstmember is not None:
m = self.firstmember
self.firstmember = None
return m
# Read the next block.
self.fileobj.seek(self.offset)
tarinfo = None
while True:
try:
... | Return the next member of the archive as a TarInfo object, when
TarFile is opened for reading. Return None if there is no more
available.
| 25 | 112 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def next(self):
self._check("ra")
if self.firstmember is not None:
m = self.firstmember
self.firstmember = None
return m
... |
2,267 | def predict_proba(self, X):
check_is_fitted(self)
ovr = self.multi_class in ["ovr", "warn"] or (
self.multi_class == "auto"
and (
self.classes_.size <= 2
or self.solver in ("liblinear", "newton-cholesky")
)
)
i... |
Probability estimates.
The returned estimates for all classes are ordered by the
label of classes.
For a multi_class problem, if multi_class is set to be "multinomial"
the softmax function is used to find the predicted probability of
each class.
Else use a one-... | 125 | 67 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def predict_proba(self, X):
check_is_fitted(self)
ovr = self.multi_class in ["ovr", "warn"] or (
self.multi_class == "auto"
and (
... |
2,268 | def selu(x):
return tf.nn.selu(x)
@keras_export("keras.activations.softplus")
@tf.__internal__.dispatch.add_dispatch_support | Scaled Exponential Linear Unit (SELU).
The Scaled Exponential Linear Unit (SELU) activation function is defined as:
- `if x > 0: return scale * x`
- `if x < 0: return scale * alpha * (exp(x) - 1)`
where `alpha` and `scale` are pre-defined constants
(`alpha=1.67326324` and `scale=1.05070098`).
... | 205 | 6 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def selu(x):
return tf.nn.selu(x)
@keras_export("keras.activations.softplus")
@tf.__internal__.dispatch.add_dispatch_support
```
###Assistant : Scaled Exponential Line... |
2,269 | def _find_safe_escape_tokens(self, text):
for i, t, v in self._filter_to(
self.lang.get_tokens_unprocessed(text),
lambda t: t in Token.Comment or t in Token.String
):
if t is None:
for i2, t2, v2 in self._find_escape_tokens(v):
... | find escape tokens that are not in strings or comments | 10 | 41 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _find_safe_escape_tokens(self, text):
for i, t, v in self._filter_to(
self.lang.get_tokens_unprocessed(text),
lambda t: t in Token.Comment or t i... |
2,270 | def set_up_fileselector(quteproc, py_proc, kind, files, output_type):
cmd, args = py_proc(r)
args += files.split(' ')
if output_type == "a temporary file":
args += ['--file={}']
fileselect_cmd = json.dumps([cmd, *args])
quteproc.set_setting('fileselect.handler', 'external')
quteproc... | Set up fileselect.xxx.command to select the file(s).
import os
import sys
tmp_file = None
for i, arg in enumerate(sys.argv):
if arg.startswith('--file='):
tmp_file = arg[len('--file='):]
sys.argv.pop(i)
break
selected_fi... | 51 | 31 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def set_up_fileselector(quteproc, py_proc, kind, files, output_type):
cmd, args = py_proc(r)
args += files.split(' ')
if output_type == "a temporary file":
args += [... |
2,271 | def task_runner(request):
if not hasattr(request.param, "_pytestfixturefunction"):
raise TypeError("Received invalid `task_runner` parameter. Expected fixture.")
yield request.getfixturevalue(request.param.__name__)
|
An indirect fixture that expects to receive a pytest fixture that yields a task
runner.
| 15 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def task_runner(request):
if not hasattr(request.param, "_pytestfixturefunction"):
raise TypeError("Received invalid `task_runner` parameter. Expected fixture.")
yield... |
2,272 | def test_get_apns_context(self) -> None:
import zerver.lib.push_notifications
zerver.lib.push_notifications.get_apns_context.cache_clear()
try:
with self.settings(APNS_CERT_FILE="/foo.pem"), mock.patch("aioapns.APNs") as mock_apns:
apns_context = get_apns_co... | This test is pretty hacky, and needs to carefully reset the state
it modifies in order to avoid leaking state that can lead to
nondeterministic results for other tests.
| 29 | 47 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_get_apns_context(self) -> None:
import zerver.lib.push_notifications
zerver.lib.push_notifications.get_apns_context.cache_clear()
try:
... |
2,273 | def _validate(self) -> None:
if (self._args.writer == "ffmpeg" and
not self._images.is_video and
self._args.reference_video is None):
raise FaceswapError("Output as video selected, but using frames as input. You must "
"provide... | Validate the Command Line Options.
Ensure that certain cli selections are valid and won't result in an error. Checks:
* If frames have been passed in with video output, ensure user supplies reference
video.
* If "on-the-fly" and a Neural Network mask is selected, warn and s... | 97 | 230 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _validate(self) -> None:
if (self._args.writer == "ffmpeg" and
not self._images.is_video and
self._args.reference_video is None):
... |
2,274 | def get_authenticators(self) -> List[BaseAuthentication]:
# TODO: Increase test coverage and get this working for monolith mode.
if SiloMode.get_current_mode() == SiloMode.MONOLITH:
return super().get_authenticators()
last_api_authenticator = ApiAuthentication([])
... |
Instantiates and returns the list of authenticators that this view can use.
Aggregates together authenticators that can be supported using HybridCloud.
| 21 | 52 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_authenticators(self) -> List[BaseAuthentication]:
# TODO: Increase test coverage and get this working for monolith mode.
if SiloMode.get_current_mode() == S... |
2,275 | def test_naive_lowest_common_ancestor2(self):
G = nx.DiGraph()
G.add_edge(0, 1)
G.add_edge(2, 0)
G.add_edge(2, 3)
G.add_edge(4, 0)
G.add_edge(5, 2)
assert naive_lca(G, 1, 3) == 2
| Test that the one-pair function works for issue #4942. | 9 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_naive_lowest_common_ancestor2(self):
G = nx.DiGraph()
G.add_edge(0, 1)
G.add_edge(2, 0)
G.add_edge(2, 3)
G.add_edge(4, 0)
G.... |
2,276 | def get_references(state, model_tuple, field_tuple=()):
for state_model_tuple, model_state in state.models.items():
for name, field in model_state.fields.items():
reference = field_references(
state_model_tuple, field, model_tuple, *field_tuple
)
if r... |
Generator of (model_state, name, field, reference) referencing
provided context.
If field_tuple is provided only references to this particular field of
model_tuple will be generated.
| 24 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_references(state, model_tuple, field_tuple=()):
for state_model_tuple, model_state in state.models.items():
for name, field in model_state.fields.items():
... |
2,277 | async def test_media_player_eq_bands_not_supported(hass):
device = (
"media_player.test_bands",
"on",
{
"friendly_name": "Test media player",
"supported_features": SUPPORT_SELECT_SOUND_MODE,
"sound_mode": "tv",
"sound_mode_list": ["movie",... | Test EqualizerController bands directive not supported. | 6 | 181 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_media_player_eq_bands_not_supported(hass):
device = (
"media_player.test_bands",
"on",
{
"friendly_name": "Test media player",
... |
2,278 | def lstsq(a, b):
q, r = qr(a)
x = solve_triangular(r, q.T.conj().dot(b))
residuals = b - a.dot(x)
residuals = abs(residuals**2).sum(axis=0, keepdims=b.ndim == 1)
token = tokenize(a, b)
# r must be a triangular with single block
# rank
rname = "lstsq-rank-" + token
rdsk = {(rn... |
Return the least-squares solution to a linear matrix equation using
QR decomposition.
Solves the equation `a x = b` by computing a vector `x` that
minimizes the Euclidean 2-norm `|| b - a x ||^2`. The equation may
be under-, well-, or over- determined (i.e., the number of
linearly independent... | 198 | 118 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def lstsq(a, b):
q, r = qr(a)
x = solve_triangular(r, q.T.conj().dot(b))
residuals = b - a.dot(x)
residuals = abs(residuals**2).sum(axis=0, keepdims=b.ndim == 1)
to... |
2,279 | def docker_environment(): # type: () -> t.Dict[str, str]
env = common_environment()
env.update(dict((key, os.environ[key]) for key in os.environ if key.startswith('DOCKER_') or key.startswith('CONTAINER_')))
return env
| Return a dictionary of docker related environment variables found in the current environment. | 13 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def docker_environment(): # type: () -> t.Dict[str, str]
env = common_environment()
env.update(dict((key, os.environ[key]) for key in os.environ if key.startswith('DOCKER_') or... |
2,280 | def test_remove_from_figure(use_gridspec):
fig, ax = plt.subplots()
sc = ax.scatter([1, 2], [3, 4])
sc.set_array(np.array([5, 6]))
pre_position = ax.get_position()
cb = fig.colorbar(sc, use_gridspec=use_gridspec)
fig.subplots_adjust()
cb.remove()
fig.subplots_adjust()
post_posit... |
Test `remove` with the specified ``use_gridspec`` setting
| 7 | 31 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_remove_from_figure(use_gridspec):
fig, ax = plt.subplots()
sc = ax.scatter([1, 2], [3, 4])
sc.set_array(np.array([5, 6]))
pre_position = ax.get_position()
c... |
2,281 | def groupby(func, seq):
d = {}
for item in seq:
key = func(item)
if key not in d:
d[key] = []
d[key].append(item)
return d
| Group a collection by a key function
>>> from sympy.multipledispatch.utils import groupby
>>> names = ['Alice', 'Bob', 'Charlie', 'Dan', 'Edith', 'Frank']
>>> groupby(len, names) # doctest: +SKIP
{3: ['Bob', 'Dan'], 5: ['Alice', 'Edith', 'Frank'], 7: ['Charlie']}
>>> iseven = lambda x: x % 2 == ... | 72 | 24 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def groupby(func, seq):
d = {}
for item in seq:
key = func(item)
if key not in d:
d[key] = []
d[key].append(item)
return d
```
... |
2,282 | def input_files(self) -> List[str]:
metadata = self._plan.execute().get_metadata()
files = set()
for m in metadata:
for f in m.input_files:
files.add(f)
return list(files)
| Return the list of input files for the dataset.
Time complexity: O(num input files)
Returns:
The list of input files used to create the dataset, or an empty
list if the input files is not known.
| 36 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def input_files(self) -> List[str]:
metadata = self._plan.execute().get_metadata()
files = set()
for m in metadata:
for f in m.input_files:
... |
2,283 | def get_nccl_reduce_op(reduce_op):
if reduce_op not in NCCL_REDUCE_OP_MAP:
raise RuntimeError("NCCL does not support reduce op: '{}'.".format(reduce_op))
return NCCL_REDUCE_OP_MAP[reduce_op]
| Map the reduce op to NCCL reduce op type.
Args:
reduce_op (ReduceOp): ReduceOp Enum (SUM/PRODUCT/MIN/MAX).
Returns:
(nccl.ncclRedOp_t): the mapped NCCL reduce op.
| 22 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_nccl_reduce_op(reduce_op):
if reduce_op not in NCCL_REDUCE_OP_MAP:
raise RuntimeError("NCCL does not support reduce op: '{}'.".format(reduce_op))
return NCCL_RED... |
2,284 | def aligned(self) -> AlignedFace:
assert self._aligned is not None
return self._aligned
| The aligned face connected to this detected face. | 8 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def aligned(self) -> AlignedFace:
assert self._aligned is not None
return self._aligned
```
###Assistant : The aligned face connected to this detected ... |
2,285 | def upgrade():
conn = op.get_bind()
if conn.dialect.name == "sqlite":
# in sqlite TEXT and STRING column types are the same
return
if conn.dialect.name == "mysql":
op.alter_column(
'connection',
'description',
existing_type=sa.String(length=50... | Apply Fix description field in ``connection`` to be ``text`` | 9 | 47 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def upgrade():
conn = op.get_bind()
if conn.dialect.name == "sqlite":
# in sqlite TEXT and STRING column types are the same
return
if conn.dialect.name == "m... |
2,286 | def test_memory(self):
params = sum(map(list, six.itervalues(self.net.params)), [])
blobs = self.net.blobs.values()
del self.net
# now sum everything (forcing all memory to be read)
total = 0
for p in params:
total += p.data.sum() + p.diff.sum()
... | Check that holding onto blob data beyond the life of a Net is OK | 14 | 43 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_memory(self):
params = sum(map(list, six.itervalues(self.net.params)), [])
blobs = self.net.blobs.values()
del self.net
# now sum everythi... |
2,287 | async def test_timeout_stops_execution_in_sync_subflows(self, tmp_path):
canary_file = tmp_path / "canary"
|
Sync flow runs can be cancelled after a timeout once a task is called
| 14 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_timeout_stops_execution_in_sync_subflows(self, tmp_path):
canary_file = tmp_path / "canary"
```
###Assistant :
Sync flow runs can be can... |
2,288 | def get_income_account(doctype, txt, searchfield, start, page_len, filters):
from erpnext.controllers.queries import get_match_cond
# income account can be any Credit account,
# but can also be a Asset account with account_type='Income Account' in special circumstances.
# Hence the first condition is an "OR"
if n... | select tabAccount.name from `tabAccount`
where (tabAccount.report_type = "Profit and Loss"
or tabAccount.account_type in ("Income Account", "Temporary"))
and tabAccount.is_group=0
and tabAccount.`{key}` LIKE %(txt)s
{condition} {match_condition}
order by idx desc, name | 29 | 77 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_income_account(doctype, txt, searchfield, start, page_len, filters):
from erpnext.controllers.queries import get_match_cond
# income account can be any Credit account,
# but can ... |
2,289 | def win_find_exe(filename, installsubdir=None, env="ProgramFiles"):
# type: (str, Optional[Any], str) -> str
fns = [filename] if filename.endswith(".exe") else [filename + ".exe", filename] # noqa: E501
for fn in fns:
try:
if installsubdir is None:
path = _where(fn)... | Find executable in current dir, system path or in the
given ProgramFiles subdir, and retuen its absolute path.
| 18 | 56 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def win_find_exe(filename, installsubdir=None, env="ProgramFiles"):
# type: (str, Optional[Any], str) -> str
fns = [filename] if filename.endswith(".exe") else [filename + ".exe... |
2,290 | def test_custom_page_queryset(self):
self.assertIs(type(CustomManagerPage.objects.all()), CustomPageQuerySet)
self.assertIs(type(CustomManagerPage.objects.about_spam()), CustomPageQuerySet)
self.assertIs(
type(CustomManagerPage.objects.all().about_spam()), CustomPageQuerySet... |
Managers that are constructed from a custom PageQuerySet
(via PageManager.from_queryset(CustomPageQuerySet)) should return
querysets of that type
| 16 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_custom_page_queryset(self):
self.assertIs(type(CustomManagerPage.objects.all()), CustomPageQuerySet)
self.assertIs(type(CustomManagerPage.objects.about_spam... |
2,291 | def distro_release_info(self):
# type: () -> Dict[str, str]
return self._distro_release_info
|
Return a dictionary containing key-value pairs for the information
items from the distro release file data source of the OS
distribution.
For details, see :func:`distro.distro_release_info`.
| 25 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def distro_release_info(self):
# type: () -> Dict[str, str]
return self._distro_release_info
```
###Assistant :
Return a dictionary containing ... |
2,292 | def user_documents_dir(self) -> str:
return os.path.normpath(get_win_folder("CSIDL_PERSONAL"))
|
:return: documents directory tied to the user e.g. ``%USERPROFILE%\\Documents``
| 9 | 6 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def user_documents_dir(self) -> str:
return os.path.normpath(get_win_folder("CSIDL_PERSONAL"))
```
###Assistant :
:return: documents directory tied to ... |
2,293 | def round_robin_reduce_idx_iterator(self):
idx = 0
round_idx = 0
while idx < self.output_num_blocks:
for merge_idx in range(self.num_merge_tasks_per_round):
if merge_idx < self._partitions_with_extra_task:
reduce_idx = merge_idx * (self.me... |
When there are multiple nodes, merge tasks are spread throughout the
cluster to improve load-balancing. Each merge task produces outputs for
a contiguous partition of reduce tasks. This method creates an iterator
that returns reduce task indices round-robin across the merge tasks.
... | 61 | 69 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def round_robin_reduce_idx_iterator(self):
idx = 0
round_idx = 0
while idx < self.output_num_blocks:
for merge_idx in range(self.num_merge_tasks_... |
2,294 | def _check_index_name(self, result):
if self._by is not None:
# pandas does not name the index for this case
result._query_compiler.set_index_name(None)
return result
|
Check the result of groupby aggregation on the need of resetting index name.
Parameters
----------
result : DataFrame
Group by aggregation result.
Returns
-------
DataFrame
| 25 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _check_index_name(self, result):
if self._by is not None:
# pandas does not name the index for this case
result._query_compiler.set_index_name(No... |
2,295 | def check_points_in_rotated_boxes(points, boxes):
# [B, N, 5] -> [B, N, 4, 2]
corners = box2corners(boxes)
# [1, L, 2] -> [1, 1, L, 2]
points = points.unsqueeze(0)
# [B, N, 4, 2] -> [B, N, 1, 2]
a, b, c, d = corners.split(4, axis=2)
ab = b - a
ad = d - a
# [B, N, L, 2]
ap = ... | Check whether point is in rotated boxes
Args:
points (tensor): (1, L, 2) anchor points
boxes (tensor): [B, N, 5] gt_bboxes
eps (float): default 1e-9
Returns:
is_in_box (tensor): (B, N, L)
| 31 | 136 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def check_points_in_rotated_boxes(points, boxes):
# [B, N, 5] -> [B, N, 4, 2]
corners = box2corners(boxes)
# [1, L, 2] -> [1, 1, L, 2]
points = points.unsqueeze(0)
#... |
2,296 | def write_ssh_wrapper(module):
try:
# make sure we have full permission to the module_dir, which
# may not be the case if we're sudo'ing to a non-root user
if os.access(module.tmpdir, os.W_OK | os.R_OK | os.X_OK):
fd, wrapper_path = tempfile.mkstemp(prefix=module.tmpdir + '/... |
This writes an shell wrapper for ssh options to be used with git
this is only relevant for older versions of gitthat cannot
handle the options themselves. Returns path to the script
#!/bin/sh
%s $GIT_SSH_OPTS
| 35 | 102 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def write_ssh_wrapper(module):
try:
# make sure we have full permission to the module_dir, which
# may not be the case if we're sudo'ing to a non-root user
i... |
2,297 | def alpha_composite(self, im, dest=(0, 0), source=(0, 0)):
if not isinstance(source, (list, tuple)):
msg = "Source must be a tuple"
raise ValueError(msg)
if not isinstance(dest, (list, tuple)):
msg = "Destination must be a tuple"
raise ValueError... | 'In-place' analog of Image.alpha_composite. Composites an image
onto this image.
:param im: image to composite over this one
:param dest: Optional 2 tuple (left, top) specifying the upper
left corner in this (destination) image.
:param source: Optional 2 (left, top) tuple for ... | 75 | 157 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def alpha_composite(self, im, dest=(0, 0), source=(0, 0)):
if not isinstance(source, (list, tuple)):
msg = "Source must be a tuple"
raise ValueError... |
2,298 | def test_form_field_clean_name_override(self):
field = ExtendedFormField.objects.create(
page=self.form_page,
sort_order=1,
label="quanti ge·là·to?",
field_type="number", # only number fields will add the ID as a prefix to the clean_name
req... |
Creating a new field should use the overridden method
See ExtendedFormField get_field_clean_name method
| 13 | 28 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_form_field_clean_name_override(self):
field = ExtendedFormField.objects.create(
page=self.form_page,
sort_order=1,
label="quant... |
2,299 | def polyder(p, m=1):
_check_arraylike("polyder", p)
m = core.concrete_or_error(operator.index, m, "'m' argument of jnp.polyder")
p, = _promote_dtypes_inexact(p)
if m < 0:
raise ValueError("Order of derivative must be positive")
if m == 0:
return p
coeff = (arange(len(p), m, -1)[np.newaxis, :] - 1 - ... | \
Setting trim_leading_zeros=True makes the output match that of numpy.
But prevents the function from being able to be used in compiled code.
| 23 | 52 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def polyder(p, m=1):
_check_arraylike("polyder", p)
m = core.concrete_or_error(operator.index, m, "'m' argument of jnp.polyder")
p, = _promote_dtypes_inexact(p)
if m < 0:
raise V... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.