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,000 | def _fix_unknown_dimension(self, input_shape, output_shape):
output_shape = list(output_shape)
msg = (
"total size of new array must be unchanged, "
"input_shape = {}, output_shape = {}".format(
input_shape, output_shape
)
)
k... | Find and replace a missing dimension in an output shape.
This is a near direct port of the internal Numpy function
`_fix_unknown_dimension` in `numpy/core/src/multiarray/shape.c`
Args:
input_shape: Shape of array being reshaped
output_shape: Desired shape of the array with ... | 91 | 105 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _fix_unknown_dimension(self, input_shape, output_shape):
output_shape = list(output_shape)
msg = (
"total size of new array must be unchanged, "
... |
2,001 | def test_converter_with_unicode_dtype():
txt = StringIO('abc,def\nrst,xyz')
conv = bytes.upper
res = np.loadtxt(
txt, dtype=np.dtype("U3"), converters=conv, delimiter=",")
expected = np.array([['ABC', 'DEF'], ['RST', 'XYZ']])
assert_equal(res, expected)
|
With the default 'bytes' encoding, tokens are encoded prior to being
passed to the converter. This means that the output of the converter may
be bytes instead of unicode as expected by `read_rows`.
This test checks that outputs from the above scenario are properly decoded
prior to parsing by `read... | 50 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_converter_with_unicode_dtype():
txt = StringIO('abc,def\nrst,xyz')
conv = bytes.upper
res = np.loadtxt(
txt, dtype=np.dtype("U3"), converters=conv, deli... |
2,002 | def alembic_stamp(revision):
# lazy import for performance
import alembic.command
alembic.command.stamp(alembic_config(), revision=revision)
|
Stamp the revision table with the given revision; don’t run any migrations
Args:
revision: The revision passed to `alembic stamp`.
| 20 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def alembic_stamp(revision):
# lazy import for performance
import alembic.command
alembic.command.stamp(alembic_config(), revision=revision)
```
###Assistant :... |
2,003 | def unflatten_superdims(assignment):
def check(cond):
if cond: return
raise NotImplementedError("Failed to convert OpSharding into a ShardingSpec. "
"Please open a bug report!")
flat_assignment = np.asarray(assignment, dtype=np.int64)
check(flat_assignment[0] == 0)
dims ... | Unflatten a list of dimension sizes and their strides that generates assignment.
If this function succeeds for a given ``assignment``, then the following property
should be satisfied::
dims_with_strides = unflatten_superdims(assignment)
base_array = np.arange(map(fst, sorted(dims_with_strides, key=snd, re... | 79 | 98 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def unflatten_superdims(assignment):
def check(cond):
if cond: return
raise NotImplementedError("Failed to convert OpSharding into a ShardingSpec. "
... |
2,004 | def test_perf_issue_no_associate_error_event(self):
self.project.update_option("sentry:performance_issue_creation_rate", 1.0)
with mock.patch("sentry_sdk.tracing.Span.containing_transaction"), self.feature(
{
"projects:performance-suspect-spans-ingestion": True,
... | Test that you can't associate an error event with a performance issue | 12 | 50 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_perf_issue_no_associate_error_event(self):
self.project.update_option("sentry:performance_issue_creation_rate", 1.0)
with mock.patch("sentry_sdk.tracing.Sp... |
2,005 | def testNodeTerminatedDuringUpdate(self):
cluster_config = copy.deepcopy(MOCK_DEFAULT_CONFIG)
cluster_config["available_node_types"]["ray.worker.default"]["min_workers"] = 2
cluster_config["worker_start_ray_commands"] = ["ray_start_cmd"]
# Don't need the extra node type or a do... |
Tests autoscaler handling a node getting terminated during an update
triggered by the node missing a heartbeat.
Extension of testRecoverUnhealthyWorkers.
In this test, two nodes miss a heartbeat.
One of them (node 0) is terminated during its recovery update.
The other ... | 65 | 134 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def testNodeTerminatedDuringUpdate(self):
cluster_config = copy.deepcopy(MOCK_DEFAULT_CONFIG)
cluster_config["available_node_types"]["ray.worker.default"]["min_worke... |
2,006 | def call_cr(self, other_args):
parser = argparse.ArgumentParser(
prog="cr",
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description=,
)
parser.add_argument(
"-t",
"--type",
d... | Process cr commandDisplays crypto {borrow,supply} interest rates for cryptocurrencies across several platforms.
You can select rate type with --type {borrow,supply}
You can display only N number of platforms with --limit parameter.Cryptocurrencies to search interest rates for separated b... | 55 | 66 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def call_cr(self, other_args):
parser = argparse.ArgumentParser(
prog="cr",
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelp... |
2,007 | def export(self):
result = {}
for name, module in self.nas_modules:
if name not in result:
result[name] = module.export()
return result
|
Export the NAS result, ideally the best choice of each nas_modules.
You may implement an ``export`` method for your customized nas_module.
Returns
--------
result : Dict[str, int]
Keys are names of nas_modules, and values are the choice indices of them.
| 40 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def export(self):
result = {}
for name, module in self.nas_modules:
if name not in result:
result[name] = module.export()
return ... |
2,008 | def clean_pipeline_string(self, individual):
dirty_string = str(individual)
# There are many parameter prefixes in the pipeline strings, used solely for
# making the terminal name unique, eg. LinearSVC__.
parameter_prefixes = [
(m.start(), m.end()) for m in re.findit... | Provide a string of the individual without the parameter prefixes.
Parameters
----------
individual: individual
Individual which should be represented by a pretty string
Returns
-------
A string like str(individual), but with parameter prefixes removed.
... | 34 | 70 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def clean_pipeline_string(self, individual):
dirty_string = str(individual)
# There are many parameter prefixes in the pipeline strings, used solely for
# ma... |
2,009 | def _lin_eq2dict(a, symset):
if a in symset:
return S.Zero, {a: S.One}
elif a.is_Add:
terms_list = defaultdict(list)
coeff_list = []
for ai in a.args:
ci, ti = _lin_eq2dict(ai, symset)
coeff_list.append(ci)
for mij, cij in ti.items():
... | Efficiently convert a linear equation to a dict of coefficients | 10 | 129 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _lin_eq2dict(a, symset):
if a in symset:
return S.Zero, {a: S.One}
elif a.is_Add:
terms_list = defaultdict(list)
coeff_list = []
for ai in a.... |
2,010 | def internal_ip(self, node_id):
ip = (
self._get_cached_node(node_id=node_id)["internal_ip"]
or self._get_node(node_id=node_id)["internal_ip"]
)
return ip
| Returns the internal ip (Ray ip) of the given node. | 10 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def internal_ip(self, node_id):
ip = (
self._get_cached_node(node_id=node_id)["internal_ip"]
or self._get_node(node_id=node_id)["internal_ip"]
... |
2,011 | def _write_file(self, source, dest, type, compress=False):
start = self.lib.tell()
length = os.stat(source).st_size
with open(source, 'rb') as f:
if compress:
buffer = bytearray(16 * 1024)
compressor = zlib.compressobj(self.LEVEL)
... |
Stream copy a large file into the archive and update the table of contents.
| 14 | 49 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _write_file(self, source, dest, type, compress=False):
start = self.lib.tell()
length = os.stat(source).st_size
with open(source, 'rb') as f:
... |
2,012 | def incidence_matrix(G, nodelist=None, edgelist=None, oriented=False, weight=None):
import scipy as sp
import scipy.sparse # call as sp.sparse
if nodelist is None:
nodelist = list(G)
if edgelist is None:
if G.is_multigraph():
edgelist = list(G.edges(keys=True))
... | Returns incidence matrix of G.
The incidence matrix assigns each row to a node and each column to an edge.
For a standard incidence matrix a 1 appears wherever a row's node is
incident on the column's edge. For an oriented incidence matrix each
edge is assigned an orientation (arbitrarily for undirect... | 272 | 164 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def incidence_matrix(G, nodelist=None, edgelist=None, oriented=False, weight=None):
import scipy as sp
import scipy.sparse # call as sp.sparse
if nodelist is None:
... |
2,013 | def call(self, features, training=None):
if not isinstance(features, dict):
raise ValueError(
"We expected a dictionary here. Instead we got: ", features
)
if training is None:
training = backend.learning_phase()
transformation_cache =... | Returns sequence input corresponding to the `feature_columns`.
Args:
features: A dict mapping keys to tensors.
training: Python boolean or None, indicating whether to the layer is
being run in training mode. This argument is passed to the call
method of any `FeatureC... | 137 | 98 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def call(self, features, training=None):
if not isinstance(features, dict):
raise ValueError(
"We expected a dictionary here. Instead we got: ", ... |
2,014 | def feed_eof(self):
self._incoming.write_eof()
ssldata, appdata = self.feed_ssldata(b'')
assert appdata == [] or appdata == [b'']
| Send a potentially "ragged" EOF.
This method will raise an SSL_ERROR_EOF exception if the EOF is
unexpected.
| 17 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def feed_eof(self):
self._incoming.write_eof()
ssldata, appdata = self.feed_ssldata(b'')
assert appdata == [] or appdata == [b'']
```
###Assista... |
2,015 | def screen(self) -> Screen:
try:
return self._screen_stack[-1]
except IndexError:
raise ScreenStackError("No screens on stack") from None
| Get the current screen.
Raises:
ScreenStackError: If there are no screens on the stack.
Returns:
Screen: The currently active screen.
| 20 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def screen(self) -> Screen:
try:
return self._screen_stack[-1]
except IndexError:
raise ScreenStackError("No screens on stack") from None
... |
2,016 | def test_empty_dunder_path_no_dunder_file(self):
with self.assertRaises(ImproperlyConfigured):
AppConfig("label", Stub(__path__=[]))
| If the __path__ attr is empty and there is no __file__, raise. | 12 | 6 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_empty_dunder_path_no_dunder_file(self):
with self.assertRaises(ImproperlyConfigured):
AppConfig("label", Stub(__path__=[]))
```
###Assistan... |
2,017 | def train_epoch_ch3(net, train_iter, loss, updater):
# Sum of training loss, sum of training accuracy, no. of examples
metric = Accumulator(3)
for X, y in train_iter:
# Compute gradients and update parameters
with tf.GradientTape() as tape:
y_hat = net(X)
# Keras... | The training loop defined in Chapter 3.
Defined in :numref:`sec_softmax_scratch` | 10 | 134 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def train_epoch_ch3(net, train_iter, loss, updater):
# Sum of training loss, sum of training accuracy, no. of examples
metric = Accumulator(3)
for X, y in train_iter:
... |
2,018 | def all_estimators(type_filter=None):
# lazy import to avoid circular imports from sklearn.base
from . import IS_PYPY
from ._testing import ignore_warnings
from ..base import (
BaseEstimator,
ClassifierMixin,
RegressorMixin,
TransformerMixin,
ClusterMixin,
... | Get a list of all estimators from `sklearn`.
This function crawls the module and gets all classes that inherit
from BaseEstimator. Classes that are defined in test-modules are not
included.
Parameters
----------
type_filter : {"classifier", "regressor", "cluster", "transformer"} \
... | 124 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def all_estimators(type_filter=None):
# lazy import to avoid circular imports from sklearn.base
from . import IS_PYPY
from ._testing import ignore_warnings
from ..base i... |
2,019 | def test_legend_auto5():
fig, axs = plt.subplots(ncols=2, figsize=(9.6, 4.8))
leg_bboxes = []
for ax, loc in zip(axs.flat, ("center", "best")):
# An Ellipse patch at the top, a U-shaped Polygon patch at the
# bottom and a ring-like Wedge patch: the correct placement of
# the le... |
Check that the automatic placement handle a rather complex
case with non rectangular patch. Related to issue #9580.
| 18 | 109 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_legend_auto5():
fig, axs = plt.subplots(ncols=2, figsize=(9.6, 4.8))
leg_bboxes = []
for ax, loc in zip(axs.flat, ("center", "best")):
# An Ellipse patch a... |
2,020 | def _toggle_cursor_visible(self):
if time.monotonic() - self._last_keypress_time > self.cursor_blink_period:
self._cursor_blink_visible = not self._cursor_blink_visible
self.refresh()
| Manages the blinking of the cursor - ensuring blinking only starts when the
user hasn't pressed a key in some time | 21 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _toggle_cursor_visible(self):
if time.monotonic() - self._last_keypress_time > self.cursor_blink_period:
self._cursor_blink_visible = not self._cursor_blink_... |
2,021 | def parse_semver(version, operator) -> Optional[SemverFilter]:
(operator, negated) = handle_operator_negation(operator)
try:
operator = OPERATOR_TO_DJANGO[operator]
except KeyError:
raise InvalidSearchQuery("Invalid operation 'IN' for semantic version filter.")
version = version if... |
Attempts to parse a release version using our semver syntax. version should be in
format `<package_name>@<version>` or `<version>`, where package_name is a string and
version is a version string matching semver format (https://semver.org/). We've
slightly extended this format to allow up to 4 integers.... | 55 | 191 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def parse_semver(version, operator) -> Optional[SemverFilter]:
(operator, negated) = handle_operator_negation(operator)
try:
operator = OPERATOR_TO_DJANGO[operator]
... |
2,022 | def test_not_logged_in_gives_403_to_ajax_requests(self):
# Get dashboard
response = self.client.get(
reverse("wagtailadmin_home"), HTTP_X_REQUESTED_WITH="XMLHttpRequest"
)
# AJAX requests should be given a 403 error instead of being redirected
self.assertEqu... |
This tests that a not logged in user is given a 403 error on AJAX requests
| 16 | 26 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_not_logged_in_gives_403_to_ajax_requests(self):
# Get dashboard
response = self.client.get(
reverse("wagtailadmin_home"), HTTP_X_REQUESTED_WITH=... |
2,023 | def bytes_to_unicode(self) -> Dict[int, str]:
bs: List[int] = (
list(range(ord("!"), ord("~") + 1))
+ list(range(ord("¡"), ord("¬") + 1))
+ list(range(ord("®"), ord("ÿ") + 1))
)
cs: List[int] = bs[:]
n = 0
for b in range(2 ** 8):
... |
Returns list of utf-8 byte and a corresponding list of unicode strings.
The reversible bpe codes work on unicode strings. This means you need a large #
of unicode characters in your vocab if you want to avoid UNKs. When you're at
something like a 10B token dataset you end up needing ar... | 93 | 62 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def bytes_to_unicode(self) -> Dict[int, str]:
bs: List[int] = (
list(range(ord("!"), ord("~") + 1))
+ list(range(ord("¡"), ord("¬") + 1))
... |
2,024 | async def test_get_events_custom_calendars(hass, calendar, get_api_events):
config = dict(CALDAV_CONFIG)
config["custom_calendars"] = [
{"name": "Private", "calendar": "Private", "search": "This is a normal event"}
]
assert await async_setup_component(hass, "calendar", {"calendar": config}... | Test that only searched events are returned on API. | 9 | 64 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_get_events_custom_calendars(hass, calendar, get_api_events):
config = dict(CALDAV_CONFIG)
config["custom_calendars"] = [
{"name": "Private", "calendar": "... |
2,025 | def leaf_symbols(self) -> Iterable[Symbol]:
for arg in self.arguments:
if isinstance(arg, SymbolicExpression):
yield from arg.leaf_symbols()
|
Return a generator of all leaf symbols.
Useful for when you want to inspect when the symbols come from.
No deduplication even if the symbols has duplicates.
| 27 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def leaf_symbols(self) -> Iterable[Symbol]:
for arg in self.arguments:
if isinstance(arg, SymbolicExpression):
yield from arg.leaf_symbols()
... |
2,026 | def append_step(self, obs, action, next_obs, reward, terminated, truncated, info):
if self._outfile:
if self._save_info:
self._current_rollout.append(
[obs, action, next_obs, reward, terminated, truncated, info]
)
else:
... | Add a step to the current rollout, if we are saving them | 12 | 35 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def append_step(self, obs, action, next_obs, reward, terminated, truncated, info):
if self._outfile:
if self._save_info:
self._current_rollout.ap... |
2,027 | def test_nested_prefetch_is_not_overwritten_by_related_object(self):
queryset = House.objects.only('name').prefetch_related(
Prefetch('rooms', queryset=Room.objects.prefetch_related(
Prefetch('house', queryset=House.objects.only('address')),
)),
)
... |
The prefetched relationship is used rather than populating the reverse
relationship from the parent, when prefetching a set of child objects
related to a set of parent objects and the child queryset itself
specifies a prefetch back to the parent.
| 40 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_nested_prefetch_is_not_overwritten_by_related_object(self):
queryset = House.objects.only('name').prefetch_related(
Prefetch('rooms', queryset=Room.obje... |
2,028 | def apply(self, i):
r
i = _sympify(i)
if i.is_integer is False:
raise NotImplementedError("{} should be an integer.".format(i))
n = self.size
if (i < 0) == True or (i >= n) == True:
raise NotImplementedError(
"{} should be an integer betwe... | Apply the permutation to an expression.
Parameters
==========
i : Expr
It should be an integer between $0$ and $n-1$ where $n$
is the size of the permutation.
If it is a symbol or a symbolic expression that can
have integer values, an ``AppliedP... | 180 | 51 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def apply(self, i):
r
i = _sympify(i)
if i.is_integer is False:
raise NotImplementedError("{} should be an integer.".format(i))
n = self.size
... |
2,029 | def _convert_mesh_to_triangles(self, coordinates):
if isinstance(coordinates, np.ma.MaskedArray):
p = coordinates.data
else:
p = coordinates
p_a = p[:-1, :-1]
p_b = p[:-1, 1:]
p_c = p[1:, 1:]
p_d = p[1:, :-1]
p_center = (p_a + p_b... |
Convert a given mesh into a sequence of triangles, each point
with its own color. The result can be used to construct a call to
`~.RendererBase.draw_gouraud_triangles`.
| 26 | 112 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _convert_mesh_to_triangles(self, coordinates):
if isinstance(coordinates, np.ma.MaskedArray):
p = coordinates.data
else:
p = coordinates
... |
2,030 | def count(self, level=None):
if level is None:
return notna(self._values).sum().astype("int64")
else:
warnings.warn(
"Using the level keyword in DataFrame and Series aggregations is "
"deprecated and will be removed in a future version. Us... |
Return number of non-NA/null observations in the Series.
Parameters
----------
level : int or level name, default None
If the axis is a MultiIndex (hierarchical), count along a
particular level, collapsing into a smaller Series.
Returns
-------
... | 74 | 126 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def count(self, level=None):
if level is None:
return notna(self._values).sum().astype("int64")
else:
warnings.warn(
"Using t... |
2,031 | def __format__(self, specifier, context=None, _localeconv=None):
# Note: PEP 3101 says that if the type is not present then
# there should be at least one digit after the decimal point.
# We take the liberty of ignoring this requirement for
# Decimal---it's presumably there to ... | Format a Decimal instance according to the given specifier.
The specifier should be a standard format specifier, with the
form described in PEP 3101. Formatting types 'e', 'E', 'f',
'F', 'g', 'G', 'n' and '%' are supported. If the formatting
type is omitted it defaults to 'g' or 'G', ... | 55 | 350 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __format__(self, specifier, context=None, _localeconv=None):
# Note: PEP 3101 says that if the type is not present then
# there should be at least one digit aft... |
2,032 | def test_feature_names_in():
pd = pytest.importorskip("pandas")
iris = datasets.load_iris()
X_np = iris.data
df = pd.DataFrame(X_np, columns=iris.feature_names)
| Check that feature_name_in are recorded by `_validate_data` | 7 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_feature_names_in():
pd = pytest.importorskip("pandas")
iris = datasets.load_iris()
X_np = iris.data
df = pd.DataFrame(X_np, columns=iris.feature_names)
... |
2,033 | def check_interactive_compatibility(self):
from pytorch_lightning.utilities import _IS_INTERACTIVE
if _IS_INTERACTIVE and self._strategy_type is not None and not self._strategy_type.is_interactive_compatible():
raise MisconfigurationException(
f"`Trainer(strategy={s... | Raises a `MisconfigurationException` if the accelerator and/or plugin is not compatible with an
interactive environment. | 15 | 67 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def check_interactive_compatibility(self):
from pytorch_lightning.utilities import _IS_INTERACTIVE
if _IS_INTERACTIVE and self._strategy_type is not None and not se... |
2,034 | def theme_global(new_theme=None):
if new_theme is not None:
if new_theme not in theme_list():
popup_error_with_traceback('Cannot use custom themes with theme_global call',
'Your request to use theme {} cannot be performed.'.format(new_theme),
... |
Sets / Gets the global PySimpleGUI Theme. If none is specified then returns the global theme from user settings.
Note the theme must be a standard, built-in PySimpleGUI theme... not a user-created theme.
:param new_theme: the new theme name to use
:type new_theme: (str)
:return: the cur... | 51 | 76 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def theme_global(new_theme=None):
if new_theme is not None:
if new_theme not in theme_list():
popup_error_with_traceback('Cannot use custom themes with theme_glo... |
2,035 | def close(self):
self._reset_retries()
self._closed = True
# Chunked-encoded posts are terminated with '0\r\n\r\n'
# For some reason, either Python or node.js seems to
# require an extra \r\n.
try:
self._conn.send("\r\n0\r\n\r\n".encode("utf-8"))
... | Close the connection to server.
If available, return a http_client.HTTPResponse object.
Closing the connection involves sending the
Transfer-Encoding terminating bytes.
| 20 | 45 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def close(self):
self._reset_retries()
self._closed = True
# Chunked-encoded posts are terminated with '0\r\n\r\n'
# For some reason, either Python ... |
2,036 | def _get_svc_path(name="*", status=None):
# This is the core routine to work with services, called by many
# other functions of this module.
#
# The name of a service is the "apparent" folder's name that contains its
# "run" script. If its "folder" is a symlink, the service is an "alias" of
... |
Return a list of paths to services with ``name`` that have the specified ``status``
name
a glob for service name. default is '*'
status
None : all services (no filter, default choice)
'DISABLED' : available service(s) that is not enabled
'ENABLED' : enabled service ... | 50 | 164 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_svc_path(name="*", status=None):
# This is the core routine to work with services, called by many
# other functions of this module.
#
# The name of a service i... |
2,037 | def test_model_torch_save_ddp_cpu(tmpdir):
model = BoringModel()
num_epochs = 1
trainer = Trainer(
default_root_dir=tmpdir, max_epochs=num_epochs, strategy="ddp_spawn", accelerator="cpu", devices=2, logger=False
)
temp_path = os.path.join(tmpdir, "temp.pt")
trainer.fit(model)
#... | Test to ensure torch save does not fail for model and trainer using cpu ddp. | 15 | 34 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_model_torch_save_ddp_cpu(tmpdir):
model = BoringModel()
num_epochs = 1
trainer = Trainer(
default_root_dir=tmpdir, max_epochs=num_epochs, strategy="ddp_spaw... |
2,038 | def default_batch_size(self) -> int:
# Using 2 avoid ONNX making assumption about single sample batch
return OnnxConfig.default_fixed_batch
|
The default batch size to use if no other indication
Returns:
Integer > 0
| 14 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def default_batch_size(self) -> int:
# Using 2 avoid ONNX making assumption about single sample batch
return OnnxConfig.default_fixed_batch
```
###Assis... |
2,039 | def addMacOSCodeSignature(filenames):
# Weak signing.
identity = getMacOSSigningIdentity()
command = [
"codesign",
"-s",
identity,
"--force",
"--deep",
"--preserve-metadata=entitlements",
]
assert type(filenames) is not str
command.extend(f... | Remove the code signature from a filename.
Args:
filenames - The files to be signed.
Returns:
None
Notes:
This is macOS specific.
| 22 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def addMacOSCodeSignature(filenames):
# Weak signing.
identity = getMacOSSigningIdentity()
command = [
"codesign",
"-s",
identity,
"--force... |
2,040 | def exception_handler(exc, context):
if isinstance(exc, Http404):
exc = exceptions.NotFound(*(exc.args))
elif isinstance(exc, PermissionDenied):
exc = exceptions.PermissionDenied(*(exc.args))
if isinstance(exc, exceptions.APIException):
headers = {}
if getattr(exc, 'aut... |
Returns the response that should be used for any given exception.
By default we handle the REST framework `APIException`, and also
Django's built-in `Http404` and `PermissionDenied` exceptions.
Any unhandled exceptions may return `None`, which will cause a 500 error
to be raised.
| 42 | 56 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def exception_handler(exc, context):
if isinstance(exc, Http404):
exc = exceptions.NotFound(*(exc.args))
elif isinstance(exc, PermissionDenied):
exc = exceptions... |
2,041 | def compute_cooccurrence_matrix(self, df):
user_item_hits = sparse.coo_matrix(
(np.repeat(1, df.shape[0]), (df[self.col_user_id], df[self.col_item_id])),
shape=(self.n_users, self.n_items),
).tocsr()
item_cooccurrence = user_item_hits.transpose().dot(user_item_... | Co-occurrence matrix.
The co-occurrence matrix is defined as :math:`C = U^T * U`
where U is the user_affinity matrix with 1's as values (instead of ratings).
Args:
df (pandas.DataFrame): DataFrame of users and items
Returns:
numpy.ndarray: Co-occurrence matrix... | 38 | 25 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def compute_cooccurrence_matrix(self, df):
user_item_hits = sparse.coo_matrix(
(np.repeat(1, df.shape[0]), (df[self.col_user_id], df[self.col_item_id])),
... |
2,042 | def _makeTags(tagStr, xml, suppress_LT=Suppress("<"), suppress_GT=Suppress(">")):
if isinstance(tagStr, str_type):
resname = tagStr
tagStr = Keyword(tagStr, caseless=not xml)
else:
resname = tagStr.name
tagAttrName = Word(alphas, alphanums + "_-:")
if xml:
tagAttrVa... | Internal helper to construct opening and closing tag expressions, given a tag name | 13 | 164 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _makeTags(tagStr, xml, suppress_LT=Suppress("<"), suppress_GT=Suppress(">")):
if isinstance(tagStr, str_type):
resname = tagStr
tagStr = Keyword(tagStr, caseless... |
2,043 | def load_data(label_mode="fine"):
if label_mode not in ["fine", "coarse"]:
raise ValueError(
'`label_mode` must be one of `"fine"`, `"coarse"`. '
f"Received: label_mode={label_mode}."
)
dirname = "cifar-100-python"
origin = "https://www.cs.toronto.edu/~kriz/cifa... | Loads the CIFAR100 dataset.
This is a dataset of 50,000 32x32 color training images and
10,000 test images, labeled over 100 fine-grained classes that are
grouped into 20 coarse-grained classes. See more info at the
[CIFAR homepage](https://www.cs.toronto.edu/~kriz/cifar.html).
Args:
label_m... | 193 | 88 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def load_data(label_mode="fine"):
if label_mode not in ["fine", "coarse"]:
raise ValueError(
'`label_mode` must be one of `"fine"`, `"coarse"`. '
f"R... |
2,044 | def find_airflow_sources_root() -> Path:
default_airflow_sources_root = Path.cwd()
# Try to find airflow sources in current working dir
airflow_sources_root = search_upwards_for_airflow_sources_root(Path.cwd())
if not airflow_sources_root:
# Or if it fails, find it in parents of the directo... |
Find the root of airflow sources. When Breeze is run from sources, it is easy, but this one also
has to handle the case when Breeze is installed via `pipx` so it searches upwards of the current
directory to find the right root of airflow directory.
If not found, current directory is returned (this han... | 71 | 114 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def find_airflow_sources_root() -> Path:
default_airflow_sources_root = Path.cwd()
# Try to find airflow sources in current working dir
airflow_sources_root = search_upwards... |
2,045 | def _parse_proxy_entry(proxy_str):
config = [c.strip() for c in proxy_str.split(' ') if c]
if not config:
raise ParseProxyError("Empty proxy entry")
if config[0] == "DIRECT":
if len(config) != 1:
raise ParseProxyError("Invalid number of parameter... | Parse one proxy string entry, as described in PAC specification. | 10 | 94 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _parse_proxy_entry(proxy_str):
config = [c.strip() for c in proxy_str.split(' ') if c]
if not config:
raise ParseProxyError("Empty proxy entry")
... |
2,046 | def test_gen_pyf(capfd, hello_world_f90, monkeypatch):
ipath = Path(hello_world_f90)
opath = Path(hello_world_f90).stem + ".pyf"
monkeypatch.setattr(sys, "argv", f'f2py -h {opath} {ipath}'.split())
with util.switchdir(ipath.parent):
f2pycli() # Generate wrappers
out, _ = capfd.rea... | Ensures that a signature file is generated via the CLI
CLI :: -h
| 13 | 37 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_gen_pyf(capfd, hello_world_f90, monkeypatch):
ipath = Path(hello_world_f90)
opath = Path(hello_world_f90).stem + ".pyf"
monkeypatch.setattr(sys, "argv", f'f2py -h {... |
2,047 | def _dictionary(self):
# type: () -> Dict[str, Any]
# NOTE: Dictionaries are not populated if not loaded. So, conditionals
# are not needed here.
retval = {}
for variant in OVERRIDE_ORDER:
retval.update(self._config[variant])
return retval
| A dictionary representing the loaded configuration.
| 6 | 34 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _dictionary(self):
# type: () -> Dict[str, Any]
# NOTE: Dictionaries are not populated if not loaded. So, conditionals
# are not needed here.
... |
2,048 | def using(self, alias):
return RawQuerySet(
self.raw_query,
model=self.model,
query=self.query.chain(using=alias),
params=self.params,
translations=self.translations,
using=alias,
)
| Select the database this RawQuerySet should execute against. | 8 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def using(self, alias):
return RawQuerySet(
self.raw_query,
model=self.model,
query=self.query.chain(using=alias),
params=sel... |
2,049 | def get_weights(self):
params = self.weights
return backend.batch_get_value(params)
# TODO(tanzheny): Maybe share this logic with base_layer. | Returns the current weights of the optimizer.
The weights of an optimizer are its state (ie, variables).
This function returns the weight values associated with this
optimizer as a list of Numpy arrays. The first value is always the
iterations count of the optimizer, followed by the opt... | 143 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_weights(self):
params = self.weights
return backend.batch_get_value(params)
# TODO(tanzheny): Maybe share this logic with base_layer.
```
##... |
2,050 | def _focal_loss_cost(self, cls_pred, gt_labels):
cls_pred = cls_pred.sigmoid()
neg_cost = -(1 - cls_pred + self.eps).log() * (
1 - self.alpha) * cls_pred.pow(self.gamma)
pos_cost = -(cls_pred + self.eps).log() * self.alpha * (
1 - cls_pred).pow(self.gamma)
... |
Args:
cls_pred (Tensor): Predicted classification logits, shape
(num_query, num_class).
gt_labels (Tensor): Label of `gt_bboxes`, shape (num_gt,).
Returns:
torch.Tensor: cls_cost value with weight
| 22 | 44 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _focal_loss_cost(self, cls_pred, gt_labels):
cls_pred = cls_pred.sigmoid()
neg_cost = -(1 - cls_pred + self.eps).log() * (
1 - self.alpha) * cls_pred... |
2,051 | def date_extract_sql(self, lookup_type, field_name):
raise NotImplementedError(
"subclasses of BaseDatabaseOperations may require a date_extract_sql() method"
)
|
Given a lookup_type of 'year', 'month', or 'day', return the SQL that
extracts a value from the given date field field_name.
| 21 | 15 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def date_extract_sql(self, lookup_type, field_name):
raise NotImplementedError(
"subclasses of BaseDatabaseOperations may require a date_extract_sql() method"
... |
2,052 | def test_threepid_invite_spamcheck(self) -> None:
# Mock a few functions to prevent the test from failing due to failing to talk to
# a remote IS. We keep the mock for make_and_store_3pid_invite around so we
# can check its call_count later on during the test.
make_invite_mock =... |
Test allowing/blocking threepid invites with a spam-check module.
In this test, we use the more recent API in which callbacks return a `Union[Codes, Literal["NOT_SPAM"]]`. | 24 | 227 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_threepid_invite_spamcheck(self) -> None:
# Mock a few functions to prevent the test from failing due to failing to talk to
# a remote IS. We keep the mock f... |
2,053 | def test_generate_invalid_param_val_all_valid(constraints):
with pytest.raises(NotImplementedError):
generate_invalid_param_val(constraints[0], constraints=constraints)
@pytest.mark.parametrize(
"constraint",
[
_ArrayLikes,
_Callables,
_InstancesOf,
_NoneConstr... | Check that the function raises NotImplementedError when there's no invalid value
for the constraint.
| 14 | 17 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_generate_invalid_param_val_all_valid(constraints):
with pytest.raises(NotImplementedError):
generate_invalid_param_val(constraints[0], constraints=constraints)
@p... |
2,054 | def load_drawer_from_disk(self):
exists = Path(self.full_path / str('pair_dictionary.json')).resolve().exists()
if exists:
with open(self.full_path / str('pair_dictionary.json'), "r") as fp:
self.pair_dict = json.load(fp)
elif not self.follow_mode:
... |
Locate and load a previously saved data drawer full of all pair model metadata in
present model folder.
:returns:
exists: bool = whether or not the drawer was located
| 29 | 47 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def load_drawer_from_disk(self):
exists = Path(self.full_path / str('pair_dictionary.json')).resolve().exists()
if exists:
with open(self.full_path / str... |
2,055 | def address_exclude(self, other):
if not self._version == other._version:
raise TypeError("%s and %s are not of the same version" % (
self, other))
if not isinstance(other, _BaseNetwork):
raise TypeError("%s is not a network object" % other)... | Remove an address from a larger block.
For example:
addr1 = ip_network('192.0.2.0/28')
addr2 = ip_network('192.0.2.1/32')
list(addr1.address_exclude(addr2)) =
[IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
IPv4Network('192.0.2.4/... | 88 | 157 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def address_exclude(self, other):
if not self._version == other._version:
raise TypeError("%s and %s are not of the same version" % (
... |
2,056 | def mutual_information(cooccurrence):
with np.errstate(invalid="ignore", divide="ignore"):
result = np.log2(cooccurrence.shape[0] * lift(cooccurrence))
return np.array(result)
| Helper method to calculate the Mutual Information of a matrix of
co-occurrences.
Mutual information is a measurement of the amount of information
explained by the i-th j-th item column vector.
Args:
cooccurrence (numpy.ndarray): The symmetric matrix of co-occurrences of items.
Returns:
... | 51 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def mutual_information(cooccurrence):
with np.errstate(invalid="ignore", divide="ignore"):
result = np.log2(cooccurrence.shape[0] * lift(cooccurrence))
return np.array... |
2,057 | def _is_dunder(name):
return len(name) > 4 and name.startswith('__') and name.endswith('__')
# Prior to Python 3.7 types did not have `copy_with`. A lot of the equality
# checks, argument expansion etc. are done on the _subs_tre. As a result we
# can't provide a get_type_hints function tha... | Returns True if name is a __dunder_variable_name__. | 7 | 49 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _is_dunder(name):
return len(name) > 4 and name.startswith('__') and name.endswith('__')
# Prior to Python 3.7 types did not have `copy_with`. A lot of the equality... |
2,058 | def fit(self, X, y=None, sample_weight=None):
algorithm = self._choose_algorithm(self.algorithm, self.metric)
if isinstance(self.bandwidth, str):
methods_supported = ("scott", "silvermann")
if self.bandwidth not in methods_supported:
raise ValueError(
... | Fit the Kernel Density model on the data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
List of n_features-dimensional data points. Each row
corresponds to a single data point.
y : None
Ignored. This parameter exists only for... | 70 | 133 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def fit(self, X, y=None, sample_weight=None):
algorithm = self._choose_algorithm(self.algorithm, self.metric)
if isinstance(self.bandwidth, str):
metho... |
2,059 | def get_on_pixels(self, image):
if image.mode != "L":
msg = "Image mode must be L"
raise ValueError(msg)
return _imagingmorph.get_on_pixels(image.im.id)
| Get a list of all turned on pixels in a binary image
Returns a list of tuples of (x,y) coordinates
of all matching pixels. See :ref:`coordinate-system`. | 26 | 18 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_on_pixels(self, image):
if image.mode != "L":
msg = "Image mode must be L"
raise ValueError(msg)
return _imagingmorph.get_on_pixels(... |
2,060 | def visit_Num(self, node):
if isinstance(node.n, int):
return fix_missing_locations(Call(func=Name('Integer', Load()),
args=[node], keywords=[]))
elif isinstance(node.n, float):
return fix_missing_locations(Call(func=Name('Float', Load()),
... | This function exists for backwards compatibility with Python 3.7.
It should be removed when SymPy removes support for Python 3.7. | 20 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def visit_Num(self, node):
if isinstance(node.n, int):
return fix_missing_locations(Call(func=Name('Integer', Load()),
args=[node], keywords=... |
2,061 | def enable(display=1, logdir=None, context=5, format="html"):
sys.excepthook = Hook(display=display, logdir=logdir,
context=context, format=format)
| Install an exception handler that formats tracebacks as HTML.
The optional argument 'display' can be set to 0 to suppress sending the
traceback to the browser, and 'logdir' can be set to a directory to cause
tracebacks to be written to files there. | 43 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def enable(display=1, logdir=None, context=5, format="html"):
sys.excepthook = Hook(display=display, logdir=logdir,
context=context, format=format)
... |
2,062 | def parse_list_header(value):
result = []
for item in _parse_list_header(value):
if item[:1] == item[-1:] == '"':
item = unquote_header_value(item[1:-1])
result.append(item)
return result
# From mitsuhiko/werkzeug (used with permission). | Parse lists as described by RFC 2068 Section 2.
In particular, parse comma-separated lists where the elements of
the list may include quoted-strings. A quoted-string could
contain a comma. A non-quoted string could have quotes in the
middle. Quotes are removed automatically after parsing.
It ba... | 99 | 27 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def parse_list_header(value):
result = []
for item in _parse_list_header(value):
if item[:1] == item[-1:] == '"':
item = unquote_header_value(item[1:-1])
... |
2,063 | def media_series_title(self) -> str | None:
if self._playing and self._is_feature_available(FeatureName.SeriesName):
return self._playing.series_name
return None
| Title of series of current playing media, TV show only. | 10 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def media_series_title(self) -> str | None:
if self._playing and self._is_feature_available(FeatureName.SeriesName):
return self._playing.series_name
ret... |
2,064 | def _build_template(name, template, files, config, nav):
# Run `pre_template` plugin events.
template = config['plugins'].run_event(
'pre_template', template, template_name=name, config=config
)
if utils.is_error_template(name):
# Force absolute URLs in the nav of error pages and ... |
Return rendered output for given template as a string.
| 9 | 116 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _build_template(name, template, files, config, nav):
# Run `pre_template` plugin events.
template = config['plugins'].run_event(
'pre_template', template, template_... |
2,065 | def matches(self, expr, repl_dict=None, old=False):
expr = sympify(expr)
if not isinstance(expr, self.__class__):
return None
if repl_dict is None:
repl_dict = {}
else:
repl_dict = repl_dict.copy()
if self == expr:
return... |
Helper method for match() that looks for a match between Wild symbols
in self and expressions in expr.
Examples
========
>>> from sympy import symbols, Wild, Basic
>>> a, b, c = symbols('a b c')
>>> x = Wild('x')
>>> Basic(a + x, x).matches(Basic(a + b,... | 66 | 88 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def matches(self, expr, repl_dict=None, old=False):
expr = sympify(expr)
if not isinstance(expr, self.__class__):
return None
if repl_dict is No... |
2,066 | def _create_placement_group(self, num_workers):
pg = get_current_placement_group()
if pg is None:
bundle = {"CPU": self._num_cpus_per_worker, "GPU": int(self._use_gpu)}
bundles = [bundle] * num_workers
pg = ray.util.placement_group(bundles, strategy="SPREAD")... | Creates a placement group for the workers.
If this worker is already in a placement group then a new one will
not be created. This is primarily for when Tune is the upstream and
will allocate resources for SGD workers.
If this worker is not in a placement group, a new one will be creat... | 77 | 85 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _create_placement_group(self, num_workers):
pg = get_current_placement_group()
if pg is None:
bundle = {"CPU": self._num_cpus_per_worker, "GPU": int(... |
2,067 | def get_warehouse_list(filters):
from frappe.core.doctype.user_permission.user_permission import get_permitted_documents
condition = ""
user_permitted_warehouse = get_permitted_documents("Warehouse")
value = ()
if user_permitted_warehouse:
condition = "and name in %s"
value = set(user_permitted_warehouse)
el... | select name
from `tabWarehouse` where is_group = 0
{condition} | 9 | 48 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_warehouse_list(filters):
from frappe.core.doctype.user_permission.user_permission import get_permitted_documents
condition = ""
user_permitted_warehouse = get_permitted_documents... |
2,068 | def unmap(self) -> "BaseOperator":
dag = self.dag
if not dag:
raise RuntimeError("Cannot unmap a task without a DAG")
dag._remove_task(self.task_id)
if isinstance(self.operator_class, str):
raise RuntimeError("Cannot unmap a deserialized operator")
... | Get the "normal" Operator after applying the current mapping. | 9 | 30 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def unmap(self) -> "BaseOperator":
dag = self.dag
if not dag:
raise RuntimeError("Cannot unmap a task without a DAG")
dag._remove_task(self.task_... |
2,069 | def require_tensorflow(test_case):
if not is_tensorflow_available():
return unittest.skip("test requires TensorFlow")(test_case)
else:
return test_case
|
Decorator marking a test that requires TensorFlow installed. These tests are skipped when TensorFlow isn't
installed
| 16 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def require_tensorflow(test_case):
if not is_tensorflow_available():
return unittest.skip("test requires TensorFlow")(test_case)
else:
return test_case
... |
2,070 | def as_completed(fs, timeout=None):
if timeout is not None:
end_time = timeout + time.monotonic()
fs = set(fs)
total_futures = len(fs)
with _AcquireFutures(fs):
finished = set(
f for f in fs
if f._state in [CANCELLED_AND_NOTIFIED, FINISHED])
... | An iterator over the given futures that yields each as it completes.
Args:
fs: The sequence of Futures (possibly created by different Executors) to
iterate over.
timeout: The maximum number of seconds to wait. If None, then there
is no limit on the wait time.
Returns:
... | 85 | 125 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def as_completed(fs, timeout=None):
if timeout is not None:
end_time = timeout + time.monotonic()
fs = set(fs)
total_futures = len(fs)
with _AcquireFutures(fs):... |
2,071 | def pack_env_dict(self) -> Dict[str, Any]:
env_info = {"window_size": self.CONV_WIDTH,
"reward_kwargs": self.reward_params,
"config": self.config,
"live": self.live}
if self.data_provider:
env_info["fee"] = self.data_provid... |
Create dictionary of environment arguments
| 5 | 27 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def pack_env_dict(self) -> Dict[str, Any]:
env_info = {"window_size": self.CONV_WIDTH,
"reward_kwargs": self.reward_params,
"config":... |
2,072 | def sample(self) -> SampleBatchType:
if self.fake_sampler and self.last_batch is not None:
return self.last_batch
elif self.input_reader is None:
raise ValueError(
"RolloutWorker has no `input_reader` object! "
"Cannot call `sample()`. Yo... | Returns a batch of experience sampled from this worker.
This method must be implemented by subclasses.
Returns:
A columnar batch of experiences (e.g., tensors).
Examples:
>>> import gym
>>> from ray.rllib.evaluation.rollout_worker import RolloutWorker
... | 67 | 184 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def sample(self) -> SampleBatchType:
if self.fake_sampler and self.last_batch is not None:
return self.last_batch
elif self.input_reader is None:
... |
2,073 | def test_no_duplicates_for_non_unique_related_object_in_list_filter(self):
parent = Parent.objects.create(name="Mary")
# Two children with the same name
Child.objects.create(parent=parent, name="Daniel")
Child.objects.create(parent=parent, name="Daniel")
m = ParentAdmin... |
Regressions tests for #15819: If a field listed in list_filters is a
non-unique related object, results shouldn't appear more than once.
| 21 | 47 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_no_duplicates_for_non_unique_related_object_in_list_filter(self):
parent = Parent.objects.create(name="Mary")
# Two children with the same name
Chil... |
2,074 | def get_current_tax_app() -> Optional[App]:
return (
App.objects.order_by("pk")
.for_event_type(WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES)
.for_event_type(WebhookEventSyncType.ORDER_CALCULATE_TAXES)
.last()
)
| Return currently used tax app or None, if there aren't any. | 11 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_current_tax_app() -> Optional[App]:
return (
App.objects.order_by("pk")
.for_event_type(WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES)
.for_event_typ... |
2,075 | def test_callbacks(self) -> None:
cache: DeferredCache[str, int] = DeferredCache("test")
callbacks = set()
# start with an entry, with a callback
cache.prefill("k1", 10, callback=lambda: callbacks.add("prefill"))
# now replace that entry with a pending result
o... | Invalidation callbacks are called at the right time | 8 | 140 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_callbacks(self) -> None:
cache: DeferredCache[str, int] = DeferredCache("test")
callbacks = set()
# start with an entry, with a callback
ca... |
2,076 | def sql_flush(style, connection, reset_sequences=True, allow_cascade=False):
tables = connection.introspection.django_table_names(
only_existing=True, include_views=False
)
return connection.ops.sql_flush(
style,
tables,
reset_sequences=reset_sequences,
allow_cas... |
Return a list of the SQL statements used to flush the database.
| 12 | 18 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def sql_flush(style, connection, reset_sequences=True, allow_cascade=False):
tables = connection.introspection.django_table_names(
only_existing=True, include_views=False
... |
2,077 | def generate(cls, size, callback, channels=3, target_mode=None):
size_1d, size_2d, size_3d = cls._check_size(size)
if channels not in (3, 4):
raise ValueError("Only 3 or 4 output channels are supported")
table = [0] * (size_1d * size_2d * size_3d * channels)
idx_out... | Generates new LUT using provided callback.
:param size: Size of the table. Passed to the constructor.
:param callback: Function with three parameters which correspond
three color channels. Will be called ``size**3``
times with values from 0.0 to 1.0 and... | 67 | 88 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def generate(cls, size, callback, channels=3, target_mode=None):
size_1d, size_2d, size_3d = cls._check_size(size)
if channels not in (3, 4):
raise Value... |
2,078 | def regex_lookup(self, lookup_type):
raise NotImplementedError(
"subclasses of BaseDatabaseOperations may require a regex_lookup() method"
)
|
Return the string to use in a query when performing regular expression
lookups (using "regex" or "iregex"). It should contain a '%s'
placeholder for the column being searched against.
If the feature is not supported (or part of it is not supported), raise
NotImplementedError.
... | 44 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def regex_lookup(self, lookup_type):
raise NotImplementedError(
"subclasses of BaseDatabaseOperations may require a regex_lookup() method"
)
```... |
2,079 | def link_existing_conversations(doc, state):
if doc.doctype != "Contact":
return
try:
numbers = [d.phone for d in doc.phone_nos]
for number in numbers:
number = strip_number(number)
if not number:
continue
logs = frappe.db.sql_list(
,
dict(phone_number="%{}".format(number), docname=doc.n... |
Called from hooks on creation of Contact or Lead to link all the existing conversations.
SELECT cl.name FROM `tabCall Log` cl
LEFT JOIN `tabDynamic Link` dl
ON cl.name = dl.parent
WHERE (cl.`from` like %(phone_number)s or cl.`to` like %(phone_number)s)
GROUP BY cl.name
HAVING SUM(
CASE
... | 58 | 55 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def link_existing_conversations(doc, state):
if doc.doctype != "Contact":
return
try:
numbers = [d.phone for d in doc.phone_nos]
for number in numbers:
number = strip_number(nu... |
2,080 | async def async_volume_up(self) -> None:
if hasattr(self, "volume_up"):
await self.hass.async_add_executor_job(self.volume_up)
return
if (
self.volume_level is not None
and self.volume_level < 1
and self.supported_features & MediaPlay... | Turn volume up for media player.
This method is a coroutine.
| 11 | 31 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def async_volume_up(self) -> None:
if hasattr(self, "volume_up"):
await self.hass.async_add_executor_job(self.volume_up)
return
if (
... |
2,081 | def infer_axes(self) -> bool:
s = self.storable
if s is None:
return False
self.get_attrs()
return True
|
infer the axes of my storer
return a boolean indicating if we have a valid storer or not
| 18 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def infer_axes(self) -> bool:
s = self.storable
if s is None:
return False
self.get_attrs()
return True
```
###Assistant :
... |
2,082 | def _validate_set_axis(self, new_labels, old_labels):
new_labels = ensure_index(new_labels)
old_len = len(old_labels)
new_len = len(new_labels)
if old_len != new_len:
raise ValueError(
f"Length mismatch: Expected axis has {old_len} elements, "
... |
Validate the possibility of replacement of old labels with the new labels.
Parameters
----------
new_labels : list-like
The labels to replace with.
old_labels : list-like
The labels to replace.
Returns
-------
list-like
... | 35 | 36 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _validate_set_axis(self, new_labels, old_labels):
new_labels = ensure_index(new_labels)
old_len = len(old_labels)
new_len = len(new_labels)
if ol... |
2,083 | def transform_data(result, translated_columns, query_builder) -> EventsResponse:
final_result: EventsResponse = {"data": result["data"], "meta": result["meta"]}
for col in final_result["meta"]:
# Translate back column names that were converted to snuba format
col["name"] = translated_column... |
Transform internal names back to the public schema ones.
When getting timeseries results via rollup, this function will
zerofill the output results.
| 22 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def transform_data(result, translated_columns, query_builder) -> EventsResponse:
final_result: EventsResponse = {"data": result["data"], "meta": result["meta"]}
for col in final... |
2,084 | def plot_contour(*args, show=True, **kwargs):
args = list(map(sympify, args))
plot_expr = check_arguments(args, 1, 2)
series = [ContourSeries(*arg) for arg in plot_expr]
plot_contours = Plot(*series, **kwargs)
if len(plot_expr[0].free_symbols) > 2:
raise ValueError('Contour Plot cannot... |
Draws contour plot of a function
Usage
=====
Single plot
``plot_contour(expr, range_x, range_y, **kwargs)``
If the ranges are not specified, then a default range of (-10, 10) is used.
Multiple plot with the same range.
``plot_contour(expr1, expr2, range_x, range_y, **kwargs)``
... | 283 | 43 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def plot_contour(*args, show=True, **kwargs):
args = list(map(sympify, args))
plot_expr = check_arguments(args, 1, 2)
series = [ContourSeries(*arg) for arg in plot_expr]
... |
2,085 | def peek(self, n=0):
self._check_can_read()
# Relies on the undocumented fact that BufferedReader.peek()
# always returns at least one byte (except at EOF), independent
# of the value of n
return self._buffer.peek(n)
| Return buffered data without advancing the file position.
Always returns at least one byte of data, unless at EOF.
The exact number of bytes returned is unspecified.
| 27 | 31 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def peek(self, n=0):
self._check_can_read()
# Relies on the undocumented fact that BufferedReader.peek()
# always returns at least one byte (except at EOF), ... |
2,086 | def cache_full(self) -> bool:
if self._cache_info["cache_full"]:
return self._cache_info["cache_full"]
with self._lock:
return self._cache_info["cache_full"]
| bool: ``True`` if the cache has been fully populated. ``False`` if there are items still
to be cached. | 18 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def cache_full(self) -> bool:
if self._cache_info["cache_full"]:
return self._cache_info["cache_full"]
with self._lock:
return self._cache_in... |
2,087 | def get_queryset(self, request):
if self.queryset is None:
raise ImproperlyConfigured(
f"{self.__class__.__name__} does not define a queryset. Set queryset on the class or "
f"override its get_queryset() method."
)
return self.queryset.all... |
Return the base queryset for the view. By default, this returns self.queryset.all().
Args:
request: The current request
| 17 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_queryset(self, request):
if self.queryset is None:
raise ImproperlyConfigured(
f"{self.__class__.__name__} does not define a queryset. Se... |
2,088 | def _preprocess(self, inputs):
inputs = self._check_input_text(inputs)
self._max_cls_len = 5
num_workers = self.kwargs[
'num_workers'] if 'num_workers' in self.kwargs else 0
lazy_load = self.kwargs[
'lazy_load'] if 'lazy_load' in self.kwargs else False
... |
Create the dataset and dataloader for the predict.
| 8 | 46 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _preprocess(self, inputs):
inputs = self._check_input_text(inputs)
self._max_cls_len = 5
num_workers = self.kwargs[
'num_workers'] if 'num_wo... |
2,089 | def session_destroy(consul_url=None, token=None, session=None, **kwargs):
ret = {}
if not consul_url:
consul_url = _get_config()
if not consul_url:
log.error("No Consul URL found.")
ret["message"] = "No Consul URL found."
ret["res"] = False
re... |
Destroy session
:param consul_url: The Consul server URL.
:param session: The ID of the session to destroy.
:param dc: By default, the datacenter of the agent is queried;
however, the dc can be provided using the "dc" parameter.
:return: Boolean & message of success or failure.
... | 55 | 86 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def session_destroy(consul_url=None, token=None, session=None, **kwargs):
ret = {}
if not consul_url:
consul_url = _get_config()
if not consul_url:
l... |
2,090 | def post_save_action(cls, info, instance, cleaned_input):
manager = load_plugin_manager(info.context)
cls.call_event(manager.collection_updated, instance)
| Override this method with `pass` to avoid triggering product webhook. | 10 | 10 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def post_save_action(cls, info, instance, cleaned_input):
manager = load_plugin_manager(info.context)
cls.call_event(manager.collection_updated, instance)
`... |
2,091 | def _deserialize_metric(metric_config):
from keras import (
metrics as metrics_module,
) # pylint:disable=g-import-not-at-top
if metric_config in ["accuracy", "acc", "crossentropy", "ce"]:
# Do not deserialize accuracy and cross-entropy strings as we have special
# case handli... | Deserialize metrics, leaving special strings untouched. | 6 | 47 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _deserialize_metric(metric_config):
from keras import (
metrics as metrics_module,
) # pylint:disable=g-import-not-at-top
if metric_config in ["accuracy", "acc... |
2,092 | def softsign(x):
return tf.math.softsign(x)
@keras_export("keras.activations.swish")
@tf.__internal__.dispatch.add_dispatch_support | Softsign activation function, `softsign(x) = x / (abs(x) + 1)`.
Example Usage:
>>> a = tf.constant([-1.0, 0.0, 1.0], dtype = tf.float32)
>>> b = tf.keras.activations.softsign(a)
>>> b.numpy()
array([-0.5, 0. , 0.5], dtype=float32)
Args:
x: Input tensor.
Returns:
The sof... | 45 | 6 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def softsign(x):
return tf.math.softsign(x)
@keras_export("keras.activations.swish")
@tf.__internal__.dispatch.add_dispatch_support
```
###Assistant : Softsign activat... |
2,093 | def compute_inlier_metric(self) -> None:
import scipy.stats as ss
nmb_previous_points = self.data['InlierMetric_nmb_points']
weibull_percentile = self.data['InlierMetric_weib_perc']
train_ft_df = self.data_dictionary['train_features']
train_ft_df_reindexed = train... |
Compute inlier metric from backwards distance distributions.
This metric defines how well features from a timepoint fit
into previous timepoints.
| 20 | 145 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def compute_inlier_metric(self) -> None:
import scipy.stats as ss
nmb_previous_points = self.data['InlierMetric_nmb_points']
weibull_percentile = self.... |
2,094 | def items_view(self, traverser, items):
if len(items) == 1:
traverser(items[0])
self.write(",")
else:
self.interleave(lambda: self.write(", "), traverser, items)
| Traverse and separate the given *items* with a comma and append it to
the buffer. If *items* is a single item sequence, a trailing comma
will be added. | 28 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def items_view(self, traverser, items):
if len(items) == 1:
traverser(items[0])
self.write(",")
else:
self.interleave(lambda: sel... |
2,095 | def refresh_stats(self) -> None:
try:
self._mallctl("epoch", read=False, write=1)
except Exception as e:
logger.warning("Failed to reload jemalloc stats: %s", e)
| Request that jemalloc updates its internal statistics. This needs to
be called before querying for stats, otherwise it will return stale
values.
| 22 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def refresh_stats(self) -> None:
try:
self._mallctl("epoch", read=False, write=1)
except Exception as e:
logger.warning("Failed to reload jem... |
2,096 | def test_to_numpy_array_multiweight_reduction(func, expected):
G = nx.MultiDiGraph()
weights = [-1, 2, 10.0]
for w in weights:
G.add_edge(0, 1, weight=w)
A = nx.to_numpy_array(G, multigraph_weight=func, dtype=float)
assert np.allclose(A, [[0, expected], [0, 0]])
# Undirected case
... | Test various functions for reducing multiedge weights. | 7 | 43 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_to_numpy_array_multiweight_reduction(func, expected):
G = nx.MultiDiGraph()
weights = [-1, 2, 10.0]
for w in weights:
G.add_edge(0, 1, weight=w)
A = nx.... |
2,097 | def test_vr_connector_causal_slice(self):
view_rq_dict = {
"state": ViewRequirement("obs"),
# shift array should be [-2, -1, 0]
"prev_states": ViewRequirement("obs", shift="-2:0"),
# shift array should be [-4, -2, 0]
"prev_strided_states_even"... | Test that the ViewRequirementConnector can handle slice shifts correctly. | 9 | 152 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_vr_connector_causal_slice(self):
view_rq_dict = {
"state": ViewRequirement("obs"),
# shift array should be [-2, -1, 0]
"prev_sta... |
2,098 | def render(self) -> RenderableType:
return Padding(
Align.right(FigletText(self.value), vertical="middle"),
(0, 1),
style="white on rgb(51,51,51)",
)
| Build a Rich renderable to render the calculator display. | 9 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def render(self) -> RenderableType:
return Padding(
Align.right(FigletText(self.value), vertical="middle"),
(0, 1),
style="white on rgb(5... |
2,099 | def in_place_subclassed_model_state_restoration(model):
assert not model._is_graph_network
# Restore layers and build attributes
if (
hasattr(model, "_original_attributes_cache")
and model._original_attributes_cache is not None
):
# Models have sticky attribute assignment, s... | Restores the original state of a model after it was "reset".
This undoes this action of `_in_place_subclassed_model_reset`, which is
called in `clone_and_build_model` if `in_place_reset` is set to True.
Args:
model: Instance of a Keras model created via subclassing, on which
`_in_place_subcl... | 44 | 101 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def in_place_subclassed_model_state_restoration(model):
assert not model._is_graph_network
# Restore layers and build attributes
if (
hasattr(model, "_original_attri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.