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 |
|---|---|---|---|---|---|---|
1,000 | def reload_markets(self) -> None:
# Check whether markets have to be reloaded
if (self._last_markets_refresh > 0) and (
self._last_markets_refresh + self.markets_refresh_interval
> arrow.utcnow().int_timestamp):
return None
logger.debug("Perfo... | Reload markets both sync and async if refresh interval has passed | 11 | 56 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def reload_markets(self) -> None:
# Check whether markets have to be reloaded
if (self._last_markets_refresh > 0) and (
self._last_markets_refresh + ... |
1,001 | def is_strongly_diagonally_dominant(self):
r
if not self.is_square:
return False
rows, cols = self.shape
| Tests if the matrix is row strongly diagonally dominant.
Explanation
===========
A $n, n$ matrix $A$ is row strongly diagonally dominant if
.. math::
\left|A_{i, i}\right| > \sum_{j = 0, j \neq i}^{n-1}
\left|A_{i, j}\right| \quad {\text{for all }}
... | 121 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def is_strongly_diagonally_dominant(self):
r
if not self.is_square:
return False
rows, cols = self.shape
```
###Assistant : Tests if the mat... |
1,002 | def create_calibration_module(self, feature) -> torch.nn.Module:
if feature.get("calibration"):
calibration_cls = calibration.get_calibration_cls(BINARY, "temperature_scaling")
return calibration_cls(binary=True)
return None
| Creates the appropriate calibration module based on the feature config.
Today, only one type of calibration ("temperature_scaling") is available, but more options may be supported in
the future.
| 28 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def create_calibration_module(self, feature) -> torch.nn.Module:
if feature.get("calibration"):
calibration_cls = calibration.get_calibration_cls(BINARY, "temper... |
1,003 | def _download(url, path, md5sum=None):
if not osp.exists(path):
os.makedirs(path)
fname = osp.split(url)[-1]
fullname = osp.join(path, fname)
retry_cnt = 0
while not (osp.exists(fullname) and _check_exist_file_md5(fullname, md5sum,
... |
Download from url, save to path.
url (str): download url
path (str): download to given path
| 16 | 143 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _download(url, path, md5sum=None):
if not osp.exists(path):
os.makedirs(path)
fname = osp.split(url)[-1]
fullname = osp.join(path, fname)
retry_cnt = 0
... |
1,004 | def related_objects(self):
all_related_fields = self._get_fields(
forward=False, reverse=True, include_hidden=True
)
return make_immutable_fields_list(
"related_objects",
(
obj
for obj in all_related_fields
... |
Return all related objects pointing to the current model. The related
objects can come from a one-to-one, one-to-many, or many-to-many field
relation type.
Private API intended only to be used by Django itself; get_fields()
combined with filtering of field properties is the pub... | 49 | 25 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def related_objects(self):
all_related_fields = self._get_fields(
forward=False, reverse=True, include_hidden=True
)
return make_immutable_fields... |
1,005 | def test_https_good_referer(self):
req = self._get_POST_request_with_token()
req._is_secure_override = True
req.META["HTTP_HOST"] = "www.example.com"
req.META["HTTP_REFERER"] = "https://www.example.com/somepage"
mw = CsrfViewMiddleware(post_form_view)
mw.process_... |
A POST HTTPS request with a good referer is accepted.
| 10 | 25 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_https_good_referer(self):
req = self._get_POST_request_with_token()
req._is_secure_override = True
req.META["HTTP_HOST"] = "www.example.com"
... |
1,006 | def test_state_policy(self) -> None:
room_id = self.helper.create_room_as(self.user_id, tok=self.token)
# Set the maximum lifetime to 35 days so that the first event gets expired but not
# the second one.
self.helper.send_state(
room_id=room_id,
event_ty... | Tests that an event gets correctly expired if there is no default retention
policy but there's a policy specific to the room.
| 22 | 40 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_state_policy(self) -> None:
room_id = self.helper.create_room_as(self.user_id, tok=self.token)
# Set the maximum lifetime to 35 days so that the first even... |
1,007 | def insertion_sort(list, n):
for i in range(0, n):
key = list[i]
j = i - 1
# Swap elements witth key iff they are
# greater than key
while j >= 0 and list[j] > key:
list[j + 1] = list[j]
j = j - 1
list[j + 1] = key
return list
|
sort list in assending order
INPUT:
list=list of values to be sorted
n=size of list that contains values to be sorted
OUTPUT:
list of sorted values in assending order
| 29 | 53 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def insertion_sort(list, n):
for i in range(0, n):
key = list[i]
j = i - 1
# Swap elements witth key iff they are
# greater than key
while j ... |
1,008 | def get_template_context(self):
return {"name": self.__class__.__name__.lower(), "label": self.label}
|
:return: a dictionary with context variables for the javascript file associated with the context
| 14 | 7 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_template_context(self):
return {"name": self.__class__.__name__.lower(), "label": self.label}
```
###Assistant :
:return: a dictionary with con... |
1,009 | def connect(self):
if self.is_connected is True:
return self.connection
connection = teradatasql.connect(
**self.connection_data
)
self.is_connected = True
self.connection = connection
return self.connection
|
Handles the connection to a Teradata database insance.
| 8 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def connect(self):
if self.is_connected is True:
return self.connection
connection = teradatasql.connect(
**self.connection_data
)
... |
1,010 | def unregister_event_manager(self, manager):
self.event_managers.remove(manager)
for type_id in manager.type_ids:
self.event_managers_dict[type_id].remove(manager)
manager.stop()
manager.window = None
| Unregister and stop an event manager previously registered with
:meth:`register_event_manager`.
.. versionadded:: 2.1.0
.. warning::
This is an experimental method and it remains so until this warning
is present as it can be changed or removed in the next versions of
... | 42 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def unregister_event_manager(self, manager):
self.event_managers.remove(manager)
for type_id in manager.type_ids:
self.event_managers_dict[type_id].remov... |
1,011 | def _c3_mro(cls, abcs=None):
for i, base in enumerate(reversed(cls.__bases__)):
if hasattr(base, '__abstractmethods__'):
boundary = len(cls.__bases__) - i
break # Bases up to the last explicit ABC are considered first.
else:
boundary = 0
abcs = list(abcs) if ab... | Computes the method resolution order using extended C3 linearization.
If no *abcs* are given, the algorithm works exactly like the built-in C3
linearization used for method resolution.
If given, *abcs* is a list of abstract base classes that should be inserted
into the resulting MRO. Unrelated ABCs ar... | 141 | 132 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _c3_mro(cls, abcs=None):
for i, base in enumerate(reversed(cls.__bases__)):
if hasattr(base, '__abstractmethods__'):
boundary = len(cls.__bases__) - i
... |
1,012 | async def async_start_charging(self) -> None:
await self.hass.async_add_executor_job(self.leaf.start_charging)
self.schedule_update()
| Request to start charging the car. Used by the button platform. | 11 | 8 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def async_start_charging(self) -> None:
await self.hass.async_add_executor_job(self.leaf.start_charging)
self.schedule_update()
```
###Assistant :... |
1,013 | def test_multiple_server_connections(tctx):
server1 = Placeholder(Server)
server2 = Placeholder(Server)
playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=False)
| Test multiple requests being rewritten to different targets. | 8 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_multiple_server_connections(tctx):
server1 = Placeholder(Server)
server2 = Placeholder(Server)
playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular), hooks=Fal... |
1,014 | def test_overlapping_output_names(self) -> None:
self._test_overlapping_names(
outputs0=['o0', 'o1'], outputs1=['o1', 'o2'])
|
Tests error checking when the name of the output overlaps
| 10 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_overlapping_output_names(self) -> None:
self._test_overlapping_names(
outputs0=['o0', 'o1'], outputs1=['o1', 'o2'])
```
###Assistant :
... |
1,015 | def test_write_profiles_does_not_include_default(self, temporary_profiles_path):
write_profiles({})
assert "profiles.default" not in temporary_profiles_path.read_text()
|
Including the default has a tendency to bake in settings the user may not want, and
can prevent them from gaining new defaults.
| 23 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_write_profiles_does_not_include_default(self, temporary_profiles_path):
write_profiles({})
assert "profiles.default" not in temporary_profiles_path.read_tex... |
1,016 | def phase_retarder(theta=0, delta=0):
R = Matrix([[cos(theta)**2 + exp(I*delta)*sin(theta)**2,
(1-exp(I*delta))*cos(theta)*sin(theta)],
[(1-exp(I*delta))*cos(theta)*sin(theta),
sin(theta)**2 + exp(I*delta)*cos(theta)**2]])
return R*exp(-I*delta/2)
| A phase retarder Jones matrix with retardance `delta` at angle `theta`.
Parameters
==========
theta : numeric type or SymPy Symbol
The angle of the fast axis relative to the horizontal plane.
delta : numeric type or SymPy Symbol
The phase difference between the fast and slow axes of th... | 153 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def phase_retarder(theta=0, delta=0):
R = Matrix([[cos(theta)**2 + exp(I*delta)*sin(theta)**2,
(1-exp(I*delta))*cos(theta)*sin(theta)],
[(1-exp(I*del... |
1,017 | def wrapCommandForDebuggerForExec(*args):
gdb_path = getExecutablePath("gdb")
# Windows extra ball, attempt the downloaded one.
if isWin32Windows() and gdb_path is None:
from nuitka.Options import assumeYesForDownloads
mingw64_gcc_path = getCachedDownloadedMinGW64(
target... | Wrap a command for system debugger to call exec
Args:
args: (list of str) args for call to be debugged
Returns:
args tuple with debugger command inserted
Notes:
Currently only gdb and lldb are supported, but adding more
debuggers would be very welcome.
| 43 | 90 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def wrapCommandForDebuggerForExec(*args):
gdb_path = getExecutablePath("gdb")
# Windows extra ball, attempt the downloaded one.
if isWin32Windows() and gdb_path is None:
... |
1,018 | def test_commands_with_invalid_settings(self):
args = ["startproject"]
out, err = self.run_django_admin(args, settings_file="bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "You must provide a project name", regex=True)
|
Commands that don't require settings succeed if the settings file
doesn't exist.
| 12 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_commands_with_invalid_settings(self):
args = ["startproject"]
out, err = self.run_django_admin(args, settings_file="bad_settings")
self.assertNoOutp... |
1,019 | def read(self, size=-1):
if self.closed:
raise ValueError("I/O operation on closed file")
if self.size_read >= self.chunksize:
return b''
if size < 0:
size = self.chunksize - self.size_read
if size > self.chunksize - self.size_read:
... | Read at most size bytes from the chunk.
If size is omitted or negative, read until the end
of the chunk.
| 21 | 67 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def read(self, size=-1):
if self.closed:
raise ValueError("I/O operation on closed file")
if self.size_read >= self.chunksize:
return b''
... |
1,020 | def slicing_plan(chunks, index):
from dask.array.utils import asarray_safe
if not is_arraylike(index):
index = np.asanyarray(index)
cum_chunks = cached_cumsum(chunks)
cum_chunks = asarray_safe(cum_chunks, like=index)
# this dispactches to the array library
chunk_locations = np.sea... | Construct a plan to slice chunks with the given index
Parameters
----------
chunks : Tuple[int]
One dimensions worth of chunking information
index : np.ndarray[int]
The index passed to slice on that dimension
Returns
-------
out : List[Tuple[int, np.ndarray]]
A list... | 48 | 99 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def slicing_plan(chunks, index):
from dask.array.utils import asarray_safe
if not is_arraylike(index):
index = np.asanyarray(index)
cum_chunks = cached_cumsum(chunk... |
1,021 | def _add_conv_branch(self) -> None:
branch_convs = ModuleList()
for i in range(self.num_convs):
branch_convs.append(
Bottleneck(
inplanes=self.conv_out_channels,
planes=self.conv_out_channels // 4,
conv_cfg=... | Add the fc branch which consists of a sequential of conv layers. | 12 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _add_conv_branch(self) -> None:
branch_convs = ModuleList()
for i in range(self.num_convs):
branch_convs.append(
Bottleneck(
... |
1,022 | def match_files(patterns, files):
all_files = files if isinstance(files, Collection) else list(files)
return_files = set()
for pattern in patterns:
if pattern.include is not None:
result_files = pattern.match(all_files)
if pattern.include:
return_files.update(result_files)
else:
return_files.dif... |
Matches the files to the patterns.
*patterns* (:class:`~collections.abc.Iterable` of :class:`~pathspec.pattern.Pattern`)
contains the patterns to use.
*files* (:class:`~collections.abc.Iterable` of :class:`str`) contains
the normalized file paths to be matched against *patterns*.
Returns the matched files (:c... | 36 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def match_files(patterns, files):
all_files = files if isinstance(files, Collection) else list(files)
return_files = set()
for pattern in patterns:
if pattern.include is not None:
... |
1,023 | def _get_offsets_buffer(self) -> Tuple[PandasBuffer, Any]:
if self.dtype[0] == DtypeKind.STRING:
# For each string, we need to manually determine the next offset
values = self._col.to_numpy()
ptr = 0
offsets = np.zeros(shape=(len(values) + 1,), dtype=np.i... |
Return the buffer containing the offset values for variable-size binary
data (e.g., variable-length strings) and the buffer's associated dtype.
Raises NoBufferPresent if the data buffer does not have an associated
offsets buffer.
| 32 | 130 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_offsets_buffer(self) -> Tuple[PandasBuffer, Any]:
if self.dtype[0] == DtypeKind.STRING:
# For each string, we need to manually determine the next offset... |
1,024 | def _unschedule_refresh(self) -> None:
if self._unsub_refresh:
self._unsub_refresh()
self._unsub_refresh = None
| Unschedule any pending refresh since there is no longer any listeners. | 11 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _unschedule_refresh(self) -> None:
if self._unsub_refresh:
self._unsub_refresh()
self._unsub_refresh = None
```
###Assistant : Unsch... |
1,025 | def test_connect_and_rollback(self):
new_connection = connection.copy()
try:
# Ensure the database default time zone is different than
# the time zone in new_connection.settings_dict. We can
# get the default time zone by reset & show.
with new_co... |
PostgreSQL shouldn't roll back SET TIME ZONE, even if the first
transaction is rolled back (#17062).
| 16 | 119 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_connect_and_rollback(self):
new_connection = connection.copy()
try:
# Ensure the database default time zone is different than
# the ... |
1,026 | def test_readback_tfrecords(ray_start_regular_shared, tmp_path):
# The dataset we will write to a .tfrecords file.
ds = ray.data.from_items(
[
# Row one.
{
"int_item": 1,
"int_list": [2, 2, 3],
"float_item": 1.0,
... |
Test reading back TFRecords written using datasets.
The dataset we read back should be the same that we wrote.
| 19 | 79 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_readback_tfrecords(ray_start_regular_shared, tmp_path):
# The dataset we will write to a .tfrecords file.
ds = ray.data.from_items(
[
# Row one.
... |
1,027 | def call(self, inputs, state):
cur_state_pos = 0
cur_inp = inputs
new_states = []
for i, cell in enumerate(self._cells):
with tf.compat.v1.variable_scope("cell_%d" % i):
if self._state_is_tuple:
if not tf.nest.is_nested(state):
... | Run this multi-layer cell on inputs, starting from state. | 9 | 79 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def call(self, inputs, state):
cur_state_pos = 0
cur_inp = inputs
new_states = []
for i, cell in enumerate(self._cells):
with tf.compat.v... |
1,028 | def test_basic(push_channel):
msgs = [
{"foo": "bar"},
{"bar": "baz"},
{"baz": "qux", "list": [1, 2, 3]},
]
for msg in msgs:
ret = push_channel.send(msg, timeout=5, tries=1)
assert ret["load"] == msg
|
Test a variety of messages, make sure we get the expected responses
| 12 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_basic(push_channel):
msgs = [
{"foo": "bar"},
{"bar": "baz"},
{"baz": "qux", "list": [1, 2, 3]},
]
for msg in msgs:
ret = push_chann... |
1,029 | def test_put_global(self) -> None:
self.get_success(
self._module_api.account_data_manager.put_global(
self.user_id, "test.data", {"wombat": True}
)
)
# Request that account data from the normal store; check it's as we expect.
self.asser... |
Tests that written account data using `put_global` can be read out again later.
| 13 | 36 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_put_global(self) -> None:
self.get_success(
self._module_api.account_data_manager.put_global(
self.user_id, "test.data", {"wombat": Tru... |
1,030 | def get_conda_environment_content(build_metadata):
template = environment.from_string(
.strip()
)
return template.render(build_metadata=build_metadata)
|
# DO NOT EDIT: this file is generated from the specification found in the
# following script to centralize the configuration for all Azure CI builds:
# build_tools/azure/update_environments_and_lock_files.py
channels:
- {{ build_metadata['channel'] }}
dependencies:
{% for conda_dep in build_metadata['conda_depende... | 77 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_conda_environment_content(build_metadata):
template = environment.from_string(
.strip()
)
return template.render(build_metadata=build_metadata)
```
... |
1,031 | def preprocess(self, image, image_format):
format = self.format or image_format
save_kwargs = {"format": format}
# Ensuring image is properly rotated
if hasattr(image, "_getexif"):
exif_datadict = image._getexif() # returns None if no EXIF data
if exif_... | Preprocess an image.
An API hook for image pre-processing. Calls any image format specific
pre-processors (if defined). I.E. If `image_format` is 'JPEG', this
method will look for a method named `preprocess_JPEG`, if found
`image` will be passed to it.
Arguments:
im... | 92 | 94 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def preprocess(self, image, image_format):
format = self.format or image_format
save_kwargs = {"format": format}
# Ensuring image is properly rotated
... |
1,032 | def get_package_paths(package):
pkg_paths = get_all_package_paths(package)
if not pkg_paths:
raise ValueError(f"Package '{package}' does not exist or is not a package!")
if len(pkg_paths) > 1:
logger.warning(
"get_package_paths - package %s has multiple paths (%r); returnin... |
Given a package, return the path to packages stored on this machine and also returns the path to this particular
package. For example, if pkg.subpkg lives in /abs/path/to/python/libs, then this function returns
``(/abs/path/to/python/libs, /abs/path/to/python/libs/pkg/subpkg)``.
NOTE: due to backwards... | 84 | 49 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_package_paths(package):
pkg_paths = get_all_package_paths(package)
if not pkg_paths:
raise ValueError(f"Package '{package}' does not exist or is not a package!")... |
1,033 | def get_address_territory(address_name):
territory = None
if address_name:
address_fields = frappe.db.get_value("Address", address_name, ["city", "state", "country"])
for value in address_fields:
territory = frappe.db.get_value("Territory", value)
if territory:
break
return territory
| Tries to match city, state and country of address to existing territory | 12 | 27 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_address_territory(address_name):
territory = None
if address_name:
address_fields = frappe.db.get_value("Address", address_name, ["city", "state", "country"])
for value in a... |
1,034 | def _get_device_coords(self, position, height):
x = self.legend_width + RACK_ELEVATION_BORDER_WIDTH
y = RACK_ELEVATION_BORDER_WIDTH
if self.rack.desc_units:
y += int((position - 1) * self.unit_height)
else:
y += int((self.rack.u_height - position + 1) * s... |
Return the X, Y coordinates of the top left corner for a device in the specified rack unit.
| 18 | 38 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_device_coords(self, position, height):
x = self.legend_width + RACK_ELEVATION_BORDER_WIDTH
y = RACK_ELEVATION_BORDER_WIDTH
if self.rack.desc_units:
... |
1,035 | def igcd(*args):
if len(args) < 2:
raise TypeError(
'igcd() takes at least 2 arguments (%s given)' % len(args))
args_temp = [abs(as_int(i)) for i in args]
if 1 in args_temp:
return 1
a = args_temp.pop()
if HAS_GMPY: # Using gmpy if present to speed up.
for b ... | Computes nonnegative integer greatest common divisor.
Explanation
===========
The algorithm is based on the well known Euclid's algorithm [1]_. To
improve speed, ``igcd()`` has its own caching mechanism.
Examples
========
>>> from sympy import igcd
>>> igcd(2, 4)
2
>>> igcd(5... | 49 | 71 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def igcd(*args):
if len(args) < 2:
raise TypeError(
'igcd() takes at least 2 arguments (%s given)' % len(args))
args_temp = [abs(as_int(i)) for i in args]
... |
1,036 | def _prev_next_cb(self, found, *, going_up, callback):
if found:
result = browsertab.SearchNavigationResult.found
# Check if the match count change is opposite to the search direction
if self._old_match.current > 0:
if not going_up and self._old_match... | Call the prev/next callback based on the search result. | 9 | 52 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _prev_next_cb(self, found, *, going_up, callback):
if found:
result = browsertab.SearchNavigationResult.found
# Check if the match count change i... |
1,037 | def onModuleSourceCode(self, module_name, source_code):
if module_name != "tensorflow":
return source_code
source_lines = source_code.splitlines()
found_insert = False
for i, l in enumerate(source_lines):
if l.startswith("def ") and "_running_from_pip_pa... | Neutralize some path magic in tensorflow.
Notes:
Make sure tensorflow understands, we are not running as a PIP
installed application.
| 20 | 59 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def onModuleSourceCode(self, module_name, source_code):
if module_name != "tensorflow":
return source_code
source_lines = source_code.splitlines()
... |
1,038 | def cast_scalar_indexer(val):
# assumes lib.is_scalar(val)
if lib.is_float(val) and val.is_integer():
raise IndexError(
# GH#34193
"Indexing with a float is no longer supported. Manually convert "
"to an integer key instead."
)
return val
|
Disallow indexing with a float key, even if that key is a round number.
Parameters
----------
val : scalar
Returns
-------
outval : scalar
| 24 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def cast_scalar_indexer(val):
# assumes lib.is_scalar(val)
if lib.is_float(val) and val.is_integer():
raise IndexError(
# GH#34193
"Indexing with... |
1,039 | def load_plugins(base_type, database): # type: (t.Type[C], t.Dict[str, t.Type[C]]) -> None
plugins: t.Dict[str, t.Type[C]] = dict((sc.__module__.rsplit('.', 1)[1], sc) for sc in get_subclasses(base_type))
for plugin in plugins:
database[plugin] = plugins[plugin]
|
Load plugins of the specified type and track them in the specified database.
Only plugins which have already been imported will be loaded.
| 23 | 28 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def load_plugins(base_type, database): # type: (t.Type[C], t.Dict[str, t.Type[C]]) -> None
plugins: t.Dict[str, t.Type[C]] = dict((sc.__module__.rsplit('.', 1)[1], sc) for sc in ge... |
1,040 | def _undetermined_coefficients_match(expr, x, func=None, eq_homogeneous=S.Zero):
r
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
expr = powsimp(expr, combine='exp') # exp(x)*exp(2*x + 1) => exp(3*x + 1)
retdict = {}
|
Returns a trial function match if undetermined coefficients can be applied
to ``expr``, and ``None`` otherwise.
A trial expression can be found for an expression for use with the method
of undetermined coefficients if the expression is an
additive/multiplicative combination of constants, polynomia... | 194 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _undetermined_coefficients_match(expr, x, func=None, eq_homogeneous=S.Zero):
r
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
expr = powsimp(expr, combine='exp') ... |
1,041 | def _remove_raw(self) -> None:
if "raw" in self._selections:
return
logger.debug("Removing Raw Data from output")
for key in list(self._stats.keys()):
if key.startswith("raw"):
del self._stats[key]
logger.debug("Removed Raw Data from outpu... | Remove raw values from :attr:`stats` if they are not requested. | 10 | 27 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _remove_raw(self) -> None:
if "raw" in self._selections:
return
logger.debug("Removing Raw Data from output")
for key in list(self._stats.key... |
1,042 | def get_keras_blocks(keras_weight_names):
# example: 'block1a_dwconv/depthwise_kernel:0' -> 'block1a'
keras_blocks = {x.split("_")[0] for x in keras_weight_names if "block" in x}
return sorted(keras_blocks)
| Extract the block names from list of full weight names. | 10 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_keras_blocks(keras_weight_names):
# example: 'block1a_dwconv/depthwise_kernel:0' -> 'block1a'
keras_blocks = {x.split("_")[0] for x in keras_weight_names if "block" in x... |
1,043 | def get_dashboard_info(party_type, party, loyalty_program=None):
current_fiscal_year = get_fiscal_year(nowdate(), as_dict=True)
doctype = "Sales Invoice" if party_type == "Customer" else "Purchase Invoice"
companies = frappe.get_all(
doctype, filters={"docstatus": 1, party_type.lower(): party}, distinct=1, field... |
select company, sum(debit_in_account_currency) - sum(credit_in_account_currency)
from `tabGL Entry`
where party_type = %s and party=%s
and is_cancelled = 0
group by company | 21 | 193 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_dashboard_info(party_type, party, loyalty_program=None):
current_fiscal_year = get_fiscal_year(nowdate(), as_dict=True)
doctype = "Sales Invoice" if party_type == "Customer" else ... |
1,044 | def print_help(self):
help_text =
console.print(text=help_text, menu="Portfolio - Brokers - Robinhood")
| Print help[cmds]
login login to robinhood
holdings show account holdings in stocks
history show equity history of your account
[/cmds] | 20 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def print_help(self):
help_text =
console.print(text=help_text, menu="Portfolio - Brokers - Robinhood")
```
###Assistant : Print help[cmds]
login ... |
1,045 | def test_page_with_inline_model_with_tabbed_panel_only(self):
EventPageSpeaker.settings_panels = [
FieldPanel("first_name"),
FieldPanel("last_name"),
]
warning = checks.Warning(
"EventPageSpeaker.settings_panels will have no effect on InlinePanel mo... | Test that checks will warn against setting single tabbed panel on InlinePanel modelEnsure that EventPageSpeaker uses `panels` instead of `settings_panels`.
There are no tabs on non-Page model editing within InlinePanels. | 30 | 31 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_page_with_inline_model_with_tabbed_panel_only(self):
EventPageSpeaker.settings_panels = [
FieldPanel("first_name"),
FieldPanel("last_name")... |
1,046 | def to_kwargs(self):
default_dict = self.__class__().to_dict()
this_dict = self.to_dict()
return {k: v for k, v in this_dict.items() if default_dict[k] != v}
@dataclass |
Returns a dictionary containing the attributes with values different from the default of this class.
| 15 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def to_kwargs(self):
default_dict = self.__class__().to_dict()
this_dict = self.to_dict()
return {k: v for k, v in this_dict.items() if default_dict[k] != v}... |
1,047 | def update_document_archive_file(document_id):
document = Document.objects.get(id=document_id)
mime_type = document.mime_type
parser_class: Type[DocumentParser] = get_parser_class_for_mime_type(mime_type)
if not parser_class:
logger.error(
f"No parser found for mime type {mim... |
Re-creates the archive file of a document, including new OCR content and thumbnail
| 13 | 141 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def update_document_archive_file(document_id):
document = Document.objects.get(id=document_id)
mime_type = document.mime_type
parser_class: Type[DocumentParser] = get_pars... |
1,048 | def execute():
frappe.reload_doc("Selling", "doctype", "Customer Credit Limit")
frappe.reload_doc("Selling", "doctype", "Customer")
frappe.reload_doc("Setup", "doctype", "Customer Group")
if frappe.db.a_row_exists("Customer Credit Limit"):
return
move_credit_limit_to_child_table()
| Move credit limit and bypass credit limit to the child table of customer credit limit | 15 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def execute():
frappe.reload_doc("Selling", "doctype", "Customer Credit Limit")
frappe.reload_doc("Selling", "doctype", "Customer")
frappe.reload_doc("Setup", "doctype", "Customer Group... |
1,049 | def forceexit(self, tradeid, ordertype=None, amount=None):
return self._post("forceexit", data={
"tradeid": tradeid,
"ordertype": ordertype,
"amount": amount,
})
| Force-exit a trade.
:param tradeid: Id of the trade (can be received via status command)
:param ordertype: Order type to use (must be market or limit)
:param amount: Amount to sell. Full sell if not given
:return: json object
| 39 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def forceexit(self, tradeid, ordertype=None, amount=None):
return self._post("forceexit", data={
"tradeid": tradeid,
"ordertype": ordertype,
... |
1,050 | def _abi3_applies(python_version):
# type: (PythonVersion) -> bool
return len(python_version) > 1 and tuple(python_version) >= (3, 2)
|
Determine if the Python version supports abi3.
PEP 384 was first implemented in Python 3.2.
| 15 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _abi3_applies(python_version):
# type: (PythonVersion) -> bool
return len(python_version) > 1 and tuple(python_version) >= (3, 2)
```
###Assistant :
Deter... |
1,051 | def variable(value, dtype=None, name=None, constraint=None):
if dtype is None:
dtype = floatx()
if hasattr(value, "tocoo"):
sparse_coo = value.tocoo()
indices = np.concatenate(
(
np.expand_dims(sparse_coo.row, 1),
np.expand_dims(sparse_coo... | Instantiates a variable and returns it.
Args:
value: Numpy array, initial value of the tensor.
dtype: Tensor type.
name: Optional name string for the tensor.
constraint: Optional projection function to be
applied to the variable after an optimizer update.
Returns:
... | 77 | 64 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def variable(value, dtype=None, name=None, constraint=None):
if dtype is None:
dtype = floatx()
if hasattr(value, "tocoo"):
sparse_coo = value.tocoo()
in... |
1,052 | def get_cost_to_borrow() -> pd.DataFrame:
ftp = ftplib.FTP("ftp3.interactivebrokers.com", "shortstock")
flo = BytesIO()
ftp.retrbinary("RETR usa.txt", flo.write)
flo.seek(0)
data = pd.read_csv(flo, sep="|", skiprows=1)
data = data[["#SYM", "FEERATE", "AVAILABLE"]]
data["AVAILABLE"] = ... | Get stocks with highest cost to borrow [Source: Interactive Broker]
Returns
-------
pd.DataFrame
Cost to borrow
| 16 | 51 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_cost_to_borrow() -> pd.DataFrame:
ftp = ftplib.FTP("ftp3.interactivebrokers.com", "shortstock")
flo = BytesIO()
ftp.retrbinary("RETR usa.txt", flo.write)
flo.se... |
1,053 | def _enable_task_listeners():
if get_listener_manager().has_listeners:
register_task_instance_state_events()
|
Check if we have any registered listeners, then register sqlalchemy hooks for
TI state change if we do.
| 18 | 5 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _enable_task_listeners():
if get_listener_manager().has_listeners:
register_task_instance_state_events()
```
###Assistant :
Check if we... |
1,054 | def has_computed_output(self) -> bool:
return self._snapshot_blocks is not None and not self._stages_after_snapshot
| Whether this plan has a computed snapshot for the final stage, i.e. for the
output of this plan.
| 18 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def has_computed_output(self) -> bool:
return self._snapshot_blocks is not None and not self._stages_after_snapshot
```
###Assistant : Whether this plan has a ... |
1,055 | def get_conditions(filters):
conditions = ""
accounting_dimensions = get_accounting_dimensions(as_list=False) or []
accounting_dimensions_list = [d.fieldname for d in accounting_dimensions]
if filters.get("company"):
conditions += " and company=%(company)s"
if filters.get("customer") and "customer" not in acc... | and exists(select name from `tab{table}`
where parent=`tabSales Invoice`.name
and ifnull(`tab{table}`.{field}, '') = %({field})s)
and exists(select name from `tabSales Invoice Item`
where parent=`tabSales Invoice`.name
| 23 | 150 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_conditions(filters):
conditions = ""
accounting_dimensions = get_accounting_dimensions(as_list=False) or []
accounting_dimensions_list = [d.fieldname for d in accounting_dimensio... |
1,056 | def _get_classifier_artifacts(fitted_estimator, prefix, X, y_true, sample_weight):
import sklearn
if not _is_plotting_supported():
return []
|
Draw and record various common artifacts for classifier
For all classifiers, we always log:
(1) confusion matrix:
https://scikit-learn.org/stable/modules/generated/sklearn.metrics.plot_confusion_matrix.html
For only binary classifiers, we will log:
(2) precision recall curve:
https://scik... | 117 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_classifier_artifacts(fitted_estimator, prefix, X, y_true, sample_weight):
import sklearn
if not _is_plotting_supported():
return []
```
###Assista... |
1,057 | def double_edge_swap(G, nswap=1, max_tries=100, seed=None):
if G.is_directed():
raise nx.NetworkXError(
"double_edge_swap() not defined for directed graphs. Use directed_edge_swap instead."
)
if nswap > max_tries:
raise nx.NetworkXError("Number of swaps > number of tries... | Swap two edges in the graph while keeping the node degrees fixed.
A double-edge swap removes two randomly chosen edges u-v and x-y
and creates the new edges u-x and v-y::
u--v u v
becomes | |
x--y x y
If either the edge u-x or v-y already exist no swap is p... | 135 | 228 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def double_edge_swap(G, nswap=1, max_tries=100, seed=None):
if G.is_directed():
raise nx.NetworkXError(
"double_edge_swap() not defined for directed graphs. Use ... |
1,058 | def test_dataset_shard_with_task_parallelization(self):
config = {
"input": "dataset",
"input_config": {
"format": "json",
"paths": self.dset_path,
"parallelism": 10,
},
}
NUM_WORKERS = 4
_, sha... | Tests whether the dataset_shard function works correctly with parallelism
for reading the dataset. | 13 | 44 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_dataset_shard_with_task_parallelization(self):
config = {
"input": "dataset",
"input_config": {
"format": "json",
... |
1,059 | def test_image_comparison_expect_rms(im1, im2, tol, expect_rms):
baseline_dir, result_dir = map(Path, _image_directories(lambda: "dummy"))
# Copy both "baseline" and "test" image to result_dir, so that 1)
# compare_images writes the diff to result_dir, rather than to the source
# tree and 2) the ba... |
Compare two images, expecting a particular RMS error.
im1 and im2 are filenames relative to the baseline_dir directory.
tol is the tolerance to pass to compare_images.
expect_rms is the expected RMS value, or None. If None, the test will
succeed if compare_images succeeds. Otherwise, the test wi... | 61 | 97 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_image_comparison_expect_rms(im1, im2, tol, expect_rms):
baseline_dir, result_dir = map(Path, _image_directories(lambda: "dummy"))
# Copy both "baseline" and "test" imag... |
1,060 | def test_versioned_symbols_reserialization(self):
module_v2 = torch.jit.load(pytorch_test_dir + "/jit/fixtures/_test_serialization_subcmul_v2.pt")
buffer = io.BytesIO()
torch.jit.save(module_v2, buffer)
buffer.seek(0)
module_reserialized = torch.jit.load(buffer)
... |
Tests that loading and saving serialized Torchscript with a versioned
symbol won't persist the original function and will inline the
versioned builtin.
| 22 | 27 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_versioned_symbols_reserialization(self):
module_v2 = torch.jit.load(pytorch_test_dir + "/jit/fixtures/_test_serialization_subcmul_v2.pt")
buffer = io.BytesI... |
1,061 | def test_stylesheet_apply_takes_final_rule_in_specificity_clash():
css = ".a {background: red; color: lime;} .b {background: blue;}"
stylesheet = _make_stylesheet(css)
node = DOMNode(classes="a b", id="c")
stylesheet.apply(node)
assert node.styles.color == Color(0, 255, 0) # color: lime
a... | .a and .b both contain background and have same specificity, so .b wins
since it was declared last - the background should be blue. | 24 | 39 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_stylesheet_apply_takes_final_rule_in_specificity_clash():
css = ".a {background: red; color: lime;} .b {background: blue;}"
stylesheet = _make_stylesheet(css)
node ... |
1,062 | def upgrade():
conn = op.get_bind()
if conn.dialect.name == 'sqlite':
op.execute('PRAGMA foreign_keys=OFF')
with op.batch_alter_table('ab_view_menu', schema=None) as batch_op:
batch_op.create_unique_constraint(batch_op.f('ab_view_menu_name_uq'), ['name'])
op.execute('PRA... | Apply Update migration for FAB tables to add missing constraints | 10 | 116 | 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':
op.execute('PRAGMA foreign_keys=OFF')
with op.batch_alter_table('ab_view_menu', schema=None... |
1,063 | def upgrade():
op.drop_table('ai_table')
conn = op.get_bind()
# views was created with unnamed fk. Therefore need recreate it
op.create_table(
'view_tmp',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('company_i... |
insert into view_tmp (id, name, company_id, query, integration_id)
select id, name, company_id, query, datasource_id from view;
insert into analysis (analysis) select analysis from datasource where id = :id;
select id from analysis order by id d... | 72 | 386 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def upgrade():
op.drop_table('ai_table')
conn = op.get_bind()
# views was created with unnamed fk. Therefore need recreate it
op.create_table(
'view_tmp',
s... |
1,064 | def _predict_recursive(self, X, sample_weight, cluster_node):
if cluster_node.left is None:
# This cluster has no subcluster. Labels are just the label of the cluster.
return np.full(X.shape[0], cluster_node.label, dtype=np.int32)
# Determine if data points belong to th... | Predict recursively by going down the hierarchical tree.
Parameters
----------
X : {ndarray, csr_matrix} of shape (n_samples, n_features)
The data points, currently assigned to `cluster_node`, to predict between
the subclusters of this node.
sample_weight : ndar... | 74 | 95 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _predict_recursive(self, X, sample_weight, cluster_node):
if cluster_node.left is None:
# This cluster has no subcluster. Labels are just the label of the cl... |
1,065 | def inference_voice_conversion(self, reference_wav, speaker_id=None, d_vector=None, reference_speaker_id=None, reference_d_vector=None):
# compute spectrograms
y = wav_to_spec(reference_wav, self.config.audio.fft_size, self.config.audio.hop_length, self.config.audio.win_length, center=False).tr... | Inference for voice conversion
Args:
reference_wav (Tensor): Reference wavform. Tensor of shape [B, T]
speaker_id (Tensor): speaker_id of the target speaker. Tensor of shape [B]
d_vector (Tensor): d_vector embedding of target speaker. Tensor of shape `[B, C]`
ref... | 61 | 54 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def inference_voice_conversion(self, reference_wav, speaker_id=None, d_vector=None, reference_speaker_id=None, reference_d_vector=None):
# compute spectrograms
y = w... |
1,066 | def test_nonconflicting_specified_basename(self):
self.router.register(r'notes', NoteViewSet, basename='notes')
self.router.register(r'notes_kwduplicate', KWargedNoteViewSet, basename='notes_kwduplicate')
self.router.register(r'notes_duplicate', NoteViewSet, basename='notes_duplicate')
|
Ensure 2 routers with the same model, and a distinct basename specified
on each does not throw an exception
| 19 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_nonconflicting_specified_basename(self):
self.router.register(r'notes', NoteViewSet, basename='notes')
self.router.register(r'notes_kwduplicate', KWargedNot... |
1,067 | async def test_state(hass, setup_comp):
state = hass.states.get(COVER_GROUP)
# No entity has a valid state -> group state unknown
assert state.state == STATE_UNKNOWN
assert state.attributes[ATTR_FRIENDLY_NAME] == DEFAULT_NAME
assert state.attributes[ATTR_ENTITY_ID] == [
DEMO_COVER,
... | Test handling of state.
The group state is unknown if all group members are unknown or unavailable.
Otherwise, the group state is opening if at least one group member is opening.
Otherwise, the group state is closing if at least one group member is closing.
Otherwise, the group state is open if at leas... | 65 | 389 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_state(hass, setup_comp):
state = hass.states.get(COVER_GROUP)
# No entity has a valid state -> group state unknown
assert state.state == STATE_UNKNOWN
ass... |
1,068 | def connect(self, signal, func):
if self._signals is not None:
_api.check_in_list(self._signals, signal=signal)
self._func_cid_map.setdefault(signal, {})
proxy = _weak_or_strong_ref(func, self._remove_proxy)
if proxy in self._func_cid_map[signal]:
return ... | Register *func* to be called when signal *signal* is generated. | 10 | 36 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def connect(self, signal, func):
if self._signals is not None:
_api.check_in_list(self._signals, signal=signal)
self._func_cid_map.setdefault(signal, {})... |
1,069 | def get_or_create_account(company_name, account):
default_root_type = "Liability"
root_type = account.get("root_type", default_root_type)
existing_accounts = frappe.get_all(
"Account",
filters={"company": company_name, "root_type": root_type},
or_filters={
"account_name": account.get("account_name"),
... |
Check if account already exists. If not, create it.
Return a tax account or None.
| 15 | 69 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_or_create_account(company_name, account):
default_root_type = "Liability"
root_type = account.get("root_type", default_root_type)
existing_accounts = frappe.get_all(
"Account... |
1,070 | def set_default_options(self) -> None:
default = self.cli_opts.get_option_values()
logger.debug(default)
self._gui_objects.default_options = default
self.project.set_default_options()
| Set the default options for :mod:`lib.gui.projects`
The Default GUI options are stored on Faceswap startup.
Exposed as the :attr:`_default_opts` for a project cannot be set until after the main
Command Tabs have been loaded.
| 34 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def set_default_options(self) -> None:
default = self.cli_opts.get_option_values()
logger.debug(default)
self._gui_objects.default_options = default
... |
1,071 | def _format_lines(self, tokensource):
nocls = self.noclasses
lsep = self.lineseparator
tagsfile = self.tagsfile
lspan = ''
line = []
for ttype, value in tokensource:
try:
cspan = self.span_element_openers[ttype]
except Key... |
Just format the tokens, without any wrapping tags.
Yield individual lines.
| 11 | 244 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _format_lines(self, tokensource):
nocls = self.noclasses
lsep = self.lineseparator
tagsfile = self.tagsfile
lspan = ''
line = []
... |
1,072 | def _get_remote_resource(self) -> Optional[Union[SourceRead, DestinationRead, ConnectionRead]]:
search_results = self._search().get(f"{self.resource_type}s", [])
if len(search_results) > 1:
raise DuplicateResourceError("Two or more ressources exist with the same name.")
if l... | Find the remote resource on the Airbyte instance associated with the current resource.
Raises:
DuplicateResourceError: raised if the search results return multiple resources.
Returns:
Optional[Union[SourceRead, DestinationRead, ConnectionRead]]: The remote resource found.
... | 31 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_remote_resource(self) -> Optional[Union[SourceRead, DestinationRead, ConnectionRead]]:
search_results = self._search().get(f"{self.resource_type}s", [])
if ... |
1,073 | def _get_compile_args(self, user_metrics=True):
self._assert_compile_was_called()
# pylint: disable=protected-access
saved_metrics = self.compiled_metrics._user_metrics
saved_weighted_metrics = self.compiled_metrics._user_weighted_metrics
if not user_metrics:
... | Used for saving or cloning a Model.
Args:
user_metrics: Whether to return user-supplied metrics or `Metric` objects.
Defaults to returning the user-supplied metrics.
Returns:
Dictionary of arguments that were used when compiling the model.
| 34 | 51 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_compile_args(self, user_metrics=True):
self._assert_compile_was_called()
# pylint: disable=protected-access
saved_metrics = self.compiled_metrics._... |
1,074 | def test_norestexdoc(capfd, hello_world_f90, monkeypatch):
ipath = Path(hello_world_f90)
mname = "blah"
monkeypatch.setattr(sys, "argv",
f'f2py -m {mname} {ipath} --no-rest-doc'.split())
with util.switchdir(ipath.parent):
f2pycli()
out, _ = capfd.readouterr(... | Ensures that TeX documentation is written out
CLI :: --no-rest-doc
| 10 | 34 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_norestexdoc(capfd, hello_world_f90, monkeypatch):
ipath = Path(hello_world_f90)
mname = "blah"
monkeypatch.setattr(sys, "argv",
f'f2py -m {m... |
1,075 | def set_weights(self, weights):
params = self.weights
if len(params) != len(weights):
raise ValueError(
"Length of the specified weight list ("
+ str(len(weights))
+ ") does not match the number of weights "
"of the opt... | Sets the weights of the optimizer, from Numpy arrays.
Should only be called after computing the gradients
(otherwise the optimizer has no weights).
Args:
weights: a list of Numpy arrays. The number of arrays and their shape
must match number of the dimensions of the w... | 65 | 82 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def set_weights(self, weights):
params = self.weights
if len(params) != len(weights):
raise ValueError(
"Length of the specified weight l... |
1,076 | def extract_tensors_from_dataset(dataset):
iterator = get_iterator(dataset)
inputs, targets, sample_weight = unpack_iterator_input(iterator)
return inputs, targets, sample_weight
| Extract a tuple of tensors `inputs, targets, sample_weight` from a dataset.
Args:
dataset: Dataset instance.
Returns:
Tuple of tensors `x, y, weights`. `y` and `weights` entry may be None.
| 29 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def extract_tensors_from_dataset(dataset):
iterator = get_iterator(dataset)
inputs, targets, sample_weight = unpack_iterator_input(iterator)
return inputs, targets, sample_w... |
1,077 | def _set_autocommit(self, autocommit):
raise NotImplementedError(
"subclasses of BaseDatabaseWrapper may require a _set_autocommit() method"
)
# ##### Generic transaction management methods #####
|
Backend-specific implementation to enable or disable autocommit.
| 7 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _set_autocommit(self, autocommit):
raise NotImplementedError(
"subclasses of BaseDatabaseWrapper may require a _set_autocommit() method"
)
# ###... |
1,078 | def get_edit_upload_form_context_data(self):
edit_form_class = self.get_edit_form_class()
return {
self.context_upload_name: self.upload_object,
"edit_action": reverse(
self.edit_upload_url_name, args=(self.upload_object.id,)
),
"d... |
Return the context data necessary for rendering the HTML form for supplying the
metadata to turn an upload object into a final object
| 23 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_edit_upload_form_context_data(self):
edit_form_class = self.get_edit_form_class()
return {
self.context_upload_name: self.upload_object,
... |
1,079 | def test_overriding_has_module_permission(self):
articles = Article._meta.verbose_name_plural.title()
sections = Section._meta.verbose_name_plural.title()
index_url = reverse("admin7:index")
self.client.force_login(self.superuser)
response = self.client.get(index_url)
... |
If has_module_permission() always returns False, the module shouldn't
be displayed on the admin index page for any users.
| 18 | 79 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_overriding_has_module_permission(self):
articles = Article._meta.verbose_name_plural.title()
sections = Section._meta.verbose_name_plural.title()
in... |
1,080 | def non_field_errors(self):
return self.errors.get(
NON_FIELD_ERRORS,
self.error_class(error_class="nonfield", renderer=self.renderer),
)
|
Return an ErrorList of errors that aren't associated with a particular
field -- i.e., from Form.clean(). Return an empty ErrorList if there
are none.
| 24 | 8 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def non_field_errors(self):
return self.errors.get(
NON_FIELD_ERRORS,
self.error_class(error_class="nonfield", renderer=self.renderer),
)
... |
1,081 | def _set_gradient_checkpointing(self, module, value=False):
if isinstance(module, VanModel):
module.gradient_checkpointing = value
VAN_START_DOCSTRING = r
VAN_INPUTS_DOCSTRING = r
@add_start_docstrings(
"The bare VAN model outputting raw features without any specific head on top. Note, VAN ... |
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
behavior.
Parameters:
config ([`VanConfig`]): Model configuration c... | 128 | 40 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _set_gradient_checkpointing(self, module, value=False):
if isinstance(module, VanModel):
module.gradient_checkpointing = value
VAN_START_DOCSTRING = r
VAN_INPUTS_D... |
1,082 | def update(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
raise NotImplementedError
|
Update an already-existing repo to the given ``rev_options``.
Args:
rev_options: a RevOptions object.
| 13 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def update(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
raise NotImplementedError
```
###Assistant :
Update an ... |
1,083 | def get_nested_field(value, field):
if field == '__self__':
return value
fields = field.split('__')
for fld in fields:
if isinstance(value, list):
value = [getattr(v, fld) for v in value]
else:
value = getattr(value, fld)
return value |
Get nested field from list of objects or single instance
:param value: Single instance or list to look up field
:param field: Field to lookup
:return: List or single instance of looked up field
| 34 | 34 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_nested_field(value, field):
if field == '__self__':
return value
fields = field.split('__')
for fld in fields:
if isinstance(value, list):
... |
1,084 | def test_stylesheet_many_classes_dont_overrule_id():
css = "#id {color: red;} .a.b.c.d {color: blue;}"
stylesheet = _make_stylesheet(css)
node = DOMNode(classes="a b c d", id="id")
stylesheet.apply(node)
assert node.styles.color == Color(255, 0, 0)
| #id is further to the left in the specificity tuple than class, and
a selector containing multiple classes cannot take priority over even a
single class. | 26 | 27 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_stylesheet_many_classes_dont_overrule_id():
css = "#id {color: red;} .a.b.c.d {color: blue;}"
stylesheet = _make_stylesheet(css)
node = DOMNode(classes="a b c d", i... |
1,085 | def site_data_dir(self) -> str:
return self._append_app_name_and_version("/Library/Application Support")
| :return: data directory shared by users, e.g. ``/Library/Application Support/$appname/$version`` | 9 | 7 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def site_data_dir(self) -> str:
return self._append_app_name_and_version("/Library/Application Support")
```
###Assistant : :return: data directory shared by us... |
1,086 | def test_warm_start():
tpot_obj = TPOTClassifier(
random_state=42,
population_size=1,
offspring_size=2,
generations=1,
verbosity=0,
config_dict='TPOT light',
warm_start=True)
tpot_obj.fit(pretest_X, pretest_y)
assert tpot_obj._pop is not None
... | Assert that the TPOT warm_start flag stores the pop and pareto_front from the first run. | 15 | 37 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_warm_start():
tpot_obj = TPOTClassifier(
random_state=42,
population_size=1,
offspring_size=2,
generations=1,
verbosity=0,
c... |
1,087 | def load_data_wiki(batch_size, max_len):
num_workers = d2l.get_dataloader_workers()
data_dir = d2l.download_extract('wikitext-2', 'wikitext-2')
paragraphs = _read_wiki(data_dir)
train_set = _WikiTextDataset(paragraphs, max_len)
train_iter = gluon.data.DataLoader(train_set, batch_size, shuffle=T... | Load the WikiText-2 dataset.
Defined in :numref:`subsec_prepare_mlm_data` | 7 | 26 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def load_data_wiki(batch_size, max_len):
num_workers = d2l.get_dataloader_workers()
data_dir = d2l.download_extract('wikitext-2', 'wikitext-2')
paragraphs = _read_wiki(data_... |
1,088 | def save(self, loc, **kwargs) -> Plot:
# TODO expose important keyword arguments in our signature?
with theme_context(self._theme_with_defaults()):
self._plot().save(loc, **kwargs)
return self
|
Compile the plot and write it to a buffer or file on disk.
Parameters
----------
loc : str, path, or buffer
Location on disk to save the figure, or a buffer to write into.
kwargs
Other keyword arguments are passed through to
:meth:`matplotlib... | 43 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def save(self, loc, **kwargs) -> Plot:
# TODO expose important keyword arguments in our signature?
with theme_context(self._theme_with_defaults()):
self.... |
1,089 | def test_create_realm_no_creation_key(self) -> None:
email = "user1@test.com"
with self.settings(OPEN_REALM_CREATION=False):
# Create new realm with the email, but no creation key.
result = self.client_post("/new/", {"email": email})
self.assertEqual(result.... |
Trying to create a realm without a creation_key should fail when
OPEN_REALM_CREATION is false.
| 14 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_create_realm_no_creation_key(self) -> None:
email = "user1@test.com"
with self.settings(OPEN_REALM_CREATION=False):
# Create new realm with the... |
1,090 | def _get_device_names(self) -> List[str]:
names = [pynvml.nvmlDeviceGetName(handle).decode("utf-8")
for handle in self._handles]
self._log("debug", f"GPU Devices: {names}")
return names
| Obtain the list of names of connected Nvidia GPUs as identified in :attr:`_handles`.
Returns
-------
list
The list of connected Nvidia GPU names
| 23 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_device_names(self) -> List[str]:
names = [pynvml.nvmlDeviceGetName(handle).decode("utf-8")
for handle in self._handles]
self._log("debug", ... |
1,091 | def test_delayed_message(self) -> None:
user1 = UserID.from_string(self.user_id1)
# Send a message before user2 joins
event_id1 = self.create_and_send_event(self.room_id, user1)
# Have user2 join the room
self.helper.join(self.room_id, self.user_id2, tok=self.tok2)
... | Test that a delayed message that was from before a user joined
doesn't cause a notification for the joined user.
| 20 | 71 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_delayed_message(self) -> None:
user1 = UserID.from_string(self.user_id1)
# Send a message before user2 joins
event_id1 = self.create_and_send_event... |
1,092 | def test_glm_regression_unpenalized_hstacked_X(solver, fit_intercept, glm_dataset):
model, X, y, coef, _, _, _ = glm_dataset
n_samples, n_features = X.shape
alpha = 0 # unpenalized
params = dict(
alpha=alpha,
fit_intercept=fit_intercept,
# solver=solver, # only lbfgs avail... | Test that unpenalized GLM converges for all solvers to correct solution.
We work with a simple constructed data set with known solution.
GLM fit on [X] is the same as fit on [X, X]/2.
For long X, [X, X] is a singular matrix and we check against the minimum norm
solution:
min ||w||_2 subject to ... | 61 | 314 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_glm_regression_unpenalized_hstacked_X(solver, fit_intercept, glm_dataset):
model, X, y, coef, _, _, _ = glm_dataset
n_samples, n_features = X.shape
alpha = 0 # unp... |
1,093 | def test_count_aggregation_threads(self) -> None:
user_id, token, _, other_token, room_id = self._create_users_and_room()
thread_id: str
last_event_id: str
|
This is essentially the same test as test_count_aggregation, but adds
events to the main timeline and to a thread.
| 19 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_count_aggregation_threads(self) -> None:
user_id, token, _, other_token, room_id = self._create_users_and_room()
thread_id: str
last_event_id: str... |
1,094 | def test_global_instantiated_before_config_load(self):
cache = LruCache(100)
add_resizable_cache("foo", cache_resize_callback=cache.set_cache_factor)
self.assertEqual(cache.max_size, 50)
config = {"caches": {"global_factor": 4}}
self.config.read_config(config, config_di... |
If a cache is instantiated before the config is read, it will be given
the default cache size in the interim, and then resized to the new
default cache size once the config is loaded.
| 35 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_global_instantiated_before_config_load(self):
cache = LruCache(100)
add_resizable_cache("foo", cache_resize_callback=cache.set_cache_factor)
self.as... |
1,095 | def in_top_k(predictions, targets, k):
return tf.compat.v1.math.in_top_k(predictions, targets, k)
# CONVOLUTIONS
| Returns whether the `targets` are in the top `k` `predictions`.
Args:
predictions: A tensor of shape `(batch_size, classes)` and type `float32`.
targets: A 1D tensor of length `batch_size` and type `int32` or `int64`.
k: An `int`, number of top elements to consider.
Returns:
A ... | 64 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def in_top_k(predictions, targets, k):
return tf.compat.v1.math.in_top_k(predictions, targets, k)
# CONVOLUTIONS
```
###Assistant : Returns whether the `targets` are... |
1,096 | def test_update_job(self, parent_job, grouped_jobs, api, batch):
parent_job.update_job()
# assert
for job in grouped_jobs:
job.update_job.assert_called_once_with(batch=batch)
| Checks jobs status in advance and restart if some failed. | 10 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_update_job(self, parent_job, grouped_jobs, api, batch):
parent_job.update_job()
# assert
for job in grouped_jobs:
job.update_job.assert... |
1,097 | def list_master_symlinks(saltenv=None, prefix=""):
if not saltenv:
saltenv = __opts__["saltenv"] or "base"
return _client().symlink_list(saltenv, prefix)
|
.. versionchanged:: 3005
``saltenv`` will use value from config if not explicitly set
List all of the symlinks stored on the master
CLI Example:
.. code-block:: bash
salt '*' cp.list_master_symlinks
| 30 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def list_master_symlinks(saltenv=None, prefix=""):
if not saltenv:
saltenv = __opts__["saltenv"] or "base"
return _client().symlink_list(saltenv, prefix)
```
... |
1,098 | def print_help(self):
has_screen_tickers_start = "" if self.screen_tickers else "[unvl]"
has_screen_tickers_end = "" if self.screen_tickers else "[/unvl]"
help_text = f
console.print(text=help_text, menu="Stocks - Options - Screener")
| Print help[cmds]
view view available presets (or one in particular)
set set one of the available presets
[/cmds]
[param]PRESET: [/param]{self.preset}[cmds]
scr screen data from this preset[/cmds]
{has_screen_tickers_start}
[param]Last screened tickers: [/param]{', '.join(self.... | 48 | 25 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def print_help(self):
has_screen_tickers_start = "" if self.screen_tickers else "[unvl]"
has_screen_tickers_end = "" if self.screen_tickers else "[/unvl]"
he... |
1,099 | def _find(self, tests, obj, name, module, source_lines, globs, seen):
if self._verbose:
print('Finding tests in %s' % name)
# If we've already processed this object, then ignore it.
if id(obj) in seen:
return
seen[id(obj)] = 1
# Make sure we don... |
Find tests for the given object and any contained objects, and
add them to ``tests``.
| 15 | 358 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _find(self, tests, obj, name, module, source_lines, globs, seen):
if self._verbose:
print('Finding tests in %s' % name)
# If we've already processed... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.