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,100 | def get_mapped_key_strings_to_ints(self) -> MutableMapping[str, int]:
cache_key_results: MutableMapping[str, int] = {}
for org_id, result_dict in self.results.items():
for string, id in result_dict.items():
key = f"{org_id}:{string}"
if id is not None... |
Return the results, but formatted as the following:
{
"1:a": 10,
"1:b": 11,
"1:c", 12,
"2:e": 13
}
This is for when we use indexer_cache.set_many()
| 25 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_mapped_key_strings_to_ints(self) -> MutableMapping[str, int]:
cache_key_results: MutableMapping[str, int] = {}
for org_id, result_dict in self.results.items(... |
1,101 | def get_atext(value):
m = _non_atom_end_matcher(value)
if not m:
raise errors.HeaderParseError(
"expected atext but found '{}'".format(value))
atext = m.group()
value = value[len(atext):]
atext = ValueTerminal(atext, 'atext')
_validate_xtext(atext)
return atext, valu... | atext = <matches _atext_matcher>
We allow any non-ATOM_ENDS in atext, but add an InvalidATextDefect to
the token's defects list if we find non-atext characters.
| 24 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_atext(value):
m = _non_atom_end_matcher(value)
if not m:
raise errors.HeaderParseError(
"expected atext but found '{}'".format(value))
atext = m.... |
1,102 | def _get_linenumber_pos(self, lineno):
return (self.image_pad, self._get_line_y(lineno))
|
Get the actual position for the start of a line number.
| 11 | 6 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_linenumber_pos(self, lineno):
return (self.image_pad, self._get_line_y(lineno))
```
###Assistant :
Get the actual position for the start of a ... |
1,103 | def test_image_inside_paragraph(self):
# In Draftail's data model, images are block-level elements and therefore
# split up preceding / following text into their own paragraphs
converter = ContentstateConverter(features=["image"])
result = json.loads(
converter.from_database_... |
<p>before <embed embedtype="image" alt="an image" id="1" format="left" /> after</p>
| 9 | 111 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_image_inside_paragraph(self):
# In Draftail's data model, images are block-level elements and therefore
# split up preceding / following text into their own paragrap... |
1,104 | def l1_min_c(X, y, *, loss="squared_hinge", fit_intercept=True, intercept_scaling=1.0):
if loss not in ("squared_hinge", "log"):
raise ValueError('loss type not in ("squared_hinge", "log")')
X = check_array(X, accept_sparse="csc")
check_consistent_length(X, y)
Y = LabelBinarizer(neg_label... | Return the lowest bound for C.
The lower bound for C is computed such that for C in (l1_min_C, infinity)
the model is guaranteed not to be empty. This applies to l1 penalized
classifiers, such as LinearSVC with penalty='l1' and
linear_model.LogisticRegression with penalty='l1'.
This value is valid... | 190 | 93 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def l1_min_c(X, y, *, loss="squared_hinge", fit_intercept=True, intercept_scaling=1.0):
if loss not in ("squared_hinge", "log"):
raise ValueError('loss type not in ("squared... |
1,105 | def _mysql_tables_where_indexes_already_present(conn):
to_check = [
('xcom', 'idx_xcom_task_instance'),
('task_reschedule', 'idx_task_reschedule_dag_run'),
('task_fail', 'idx_task_fail_task_instance'),
]
tables = set()
for tbl, idx in to_check:
if conn.execute(f"show... |
If user downgraded and is upgrading again, we have to check for existing
indexes on mysql because we can't (and don't) drop them as part of the
downgrade.
| 28 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _mysql_tables_where_indexes_already_present(conn):
to_check = [
('xcom', 'idx_xcom_task_instance'),
('task_reschedule', 'idx_task_reschedule_dag_run'),
(... |
1,106 | def test_webclient_resolves_with_client_resource(self):
for resource_name_order_list in [
["webclient", "client"],
["client", "webclient"],
]:
# Create a dictionary from path regex -> resource
resource_dict: Dict[str, Resource] = {}
f... |
Tests that both client and webclient resources can be accessed simultaneously.
This is a regression test created in response to https://github.com/matrix-org/synapse/issues/11763.
| 21 | 103 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_webclient_resolves_with_client_resource(self):
for resource_name_order_list in [
["webclient", "client"],
["client", "webclient"],
]... |
1,107 | def unregister_pickle_by_value(module):
if not isinstance(module, types.ModuleType):
raise ValueError(f"Input should be a module object, got {str(module)} instead")
if module.__name__ not in _PICKLE_BY_VALUE_MODULES:
raise ValueError(f"{module} is not registered for pickle by value")
el... | Unregister that the input module should be pickled by value. | 10 | 32 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def unregister_pickle_by_value(module):
if not isinstance(module, types.ModuleType):
raise ValueError(f"Input should be a module object, got {str(module)} instead")
if m... |
1,108 | def test_get_bad_permissions(self):
# Remove privileges from user
self.user.is_superuser = False
self.user.user_permissions.add(
Permission.objects.get(
content_type__app_label="wagtailadmin", codename="access_admin"
)
)
self.user.... |
This tests that the view returns a "permission denied" redirect if a user without correct
permissions attempts to access it
| 20 | 30 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_get_bad_permissions(self):
# Remove privileges from user
self.user.is_superuser = False
self.user.user_permissions.add(
Permission.objec... |
1,109 | def get_archive_formats():
formats = [(name, registry[2]) for name, registry in
_ARCHIVE_FORMATS.items()]
formats.sort()
return formats
| Returns a list of supported formats for archiving and unarchiving.
Each element of the returned sequence is a tuple (name, description)
| 21 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_archive_formats():
formats = [(name, registry[2]) for name, registry in
_ARCHIVE_FORMATS.items()]
formats.sort()
return formats
```
###As... |
1,110 | def _handle_transforms(self, element, mobject):
if element.hasAttribute("x") and element.hasAttribute("y"):
x = self._attribute_to_float(element.getAttribute("x"))
# Flip y
y = -self._attribute_to_float(element.getAttribute("y"))
mobject.shift(x * RIGHT ... | Applies the SVG transform to the specified mobject. Transforms include:
``matrix``, ``translate``, and ``scale``.
Parameters
----------
element : :class:`minidom.Element`
The transform command to perform
mobject : :class:`Mobject`
The Mobject to transfor... | 31 | 245 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _handle_transforms(self, element, mobject):
if element.hasAttribute("x") and element.hasAttribute("y"):
x = self._attribute_to_float(element.getAttribute("x... |
1,111 | def pro_data_fixture():
return json.loads(load_fixture("data.json", "airvisual_pro"))
@pytest.fixture(name="pro") | Define an update coordinator data example for the Pro. | 9 | 6 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def pro_data_fixture():
return json.loads(load_fixture("data.json", "airvisual_pro"))
@pytest.fixture(name="pro")
```
###Assistant : Define an update coordinator data ... |
1,112 | def fetch_species_distributions(*, data_home=None, download_if_missing=True):
data_home = get_data_home(data_home)
if not exists(data_home):
makedirs(data_home)
# Define parameters for the data files. These should not be changed
# unless the data model changes. They will be saved in the ... | Loader for species distribution dataset from Phillips et. al. (2006).
Read more in the :ref:`User Guide <datasets>`.
Parameters
----------
data_home : str, default=None
Specify another download and cache folder for the datasets. By default
all scikit-learn data is stored in '~/scikit_l... | 310 | 179 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def fetch_species_distributions(*, data_home=None, download_if_missing=True):
data_home = get_data_home(data_home)
if not exists(data_home):
makedirs(data_home)
# D... |
1,113 | def set_split_factor(factor, dev=None):
assert 0 <= factor
global split_factors
dev = ivy.default(dev, default_device())
split_factors[dev] = factor
# noinspection PyShadowingNames |
Set the global split factor for a given device, which can be used to scale batch splitting chunk sizes for the
device across the codebase.
:param factor: The factor to set the device-specific split factor to.
:type factor: float
:param dev: The device to set the split factor for. Sets the default ... | 59 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def set_split_factor(factor, dev=None):
assert 0 <= factor
global split_factors
dev = ivy.default(dev, default_device())
split_factors[dev] = factor
# noinspection PyS... |
1,114 | def run(self, test, compileflags=None, out=None, clear_globs=True):
self.test = test
# Remove ``` from the end of example, which may appear in Markdown
# files
for example in test.examples:
example.want = example.want.replace('```\n', '')
example.exc_msg... |
Run the examples in ``test``, and display the results using the
writer function ``out``.
The examples are run in the namespace ``test.globs``. If
``clear_globs`` is true (the default), then this namespace will
be cleared after the test runs, to help with garbage
collec... | 111 | 197 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def run(self, test, compileflags=None, out=None, clear_globs=True):
self.test = test
# Remove ``` from the end of example, which may appear in Markdown
# fi... |
1,115 | def _fetch_all_variants(client, variables={}, permissions=None):
query =
response = client.post_graphql(
query, variables, permissions=permissions, check_no_permissions=False
)
content = get_graphql_content(response)
return content["data"]["productVariants"]
|
query fetchAllVariants($channel: String) {
productVariants(first: 10, channel: $channel) {
totalCount
edges {
node {
id
}
}
}
}
| 19 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _fetch_all_variants(client, variables={}, permissions=None):
query =
response = client.post_graphql(
query, variables, permissions=permissions, check_no_permissions=Fals... |
1,116 | def astar_torus(grid, start_node, goal_node):
colors = ['white', 'black', 'red', 'pink', 'yellow', 'green', 'orange']
levels = [0, 1, 2, 3, 4, 5, 6, 7]
cmap, norm = from_levels_and_colors(levels, colors)
grid[start_node] = 4
grid[goal_node] = 5
parent_map = [[() for _ in range(M)] for _ i... |
Finds a path between an initial and goal joint configuration using
the A* Algorithm on a tororiadal grid.
Args:
grid: An occupancy grid (ndarray)
start_node: Initial joint configuration (tuple)
goal_node: Goal joint configuration (tuple)
Returns:
Obstacle-free route in... | 44 | 192 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def astar_torus(grid, start_node, goal_node):
colors = ['white', 'black', 'red', 'pink', 'yellow', 'green', 'orange']
levels = [0, 1, 2, 3, 4, 5, 6, 7]
cmap, norm = from_lev... |
1,117 | def root_node(self) -> Optional[str]:
if len(self.graph.nodes) < 1:
return None
return list(self.graph.nodes)[0] # List conversion is required, see networkx docs
|
Returns the root node of the pipeline's graph.
| 8 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def root_node(self) -> Optional[str]:
if len(self.graph.nodes) < 1:
return None
return list(self.graph.nodes)[0] # List conversion is required, see netw... |
1,118 | def as_coefficients_dict(self, *syms):
if not syms:
d = defaultdict(list)
for ai in self.args:
c, m = ai.as_coeff_Mul()
d[m].append(c)
for k, v in d.items():
if len(v) == 1:
d[k] = v[0]
... | Return a dictionary mapping terms to their Rational coefficient.
Since the dictionary is a defaultdict, inquiries about terms which
were not present will return a coefficient of 0. If an expression is
not an Add it is considered to have a single term.
If symbols `syms` are provided, any... | 121 | 71 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def as_coefficients_dict(self, *syms):
if not syms:
d = defaultdict(list)
for ai in self.args:
c, m = ai.as_coeff_Mul()
... |
1,119 | def verify_emoji_code_foreign_keys(self) -> None:
dct = {}
for row in RealmEmoji.objects.all():
dct[row.id] = row
if not dct:
raise AssertionError("test needs RealmEmoji rows")
count = 0
for row in Reaction.objects.filter(reaction_type=Reaction... |
DB tables that refer to RealmEmoji use int(emoji_code) as the
foreign key. Those tables tend to de-normalize emoji_name due
to our inheritance-based setup. This helper makes sure those
invariants are intact, which is particularly tricky during
the import/export process (or durin... | 46 | 73 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def verify_emoji_code_foreign_keys(self) -> None:
dct = {}
for row in RealmEmoji.objects.all():
dct[row.id] = row
if not dct:
raise... |
1,120 | def format_string_to_json(balance_info):
Working Account|KES|481000.00|481000.00|0.00|0.00
balance_dict = frappe._dict()
for account_info in balance_info.split("&"):
account_info = account_info.split("|")
balance_dict[account_info[0]] = dict(
current_balance=fmt_money(account_info[2], currency="KES"),
avai... |
Format string to json.
e.g:
=> {'Working Account': {'current_balance': '481000.00',
'available_balance': '481000.00',
'reserved_balance': '0.00',
'uncleared_balance': '0.00'}}
| 16 | 28 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def format_string_to_json(balance_info):
Working Account|KES|481000.00|481000.00|0.00|0.00
balance_dict = frappe._dict()
for account_info in balance_info.split("&"):
account_info = acco... |
1,121 | def _validate_path(self) -> list[Any]:
msg = (
"xpath does not return any nodes or attributes. "
"Be sure to specify in `xpath` the parent nodes of "
"children and attributes to parse. "
"If document uses namespaces denoted with "
"xmlns, be ... |
Notes
-----
`etree` supports limited XPath. If user attempts a more complex
expression syntax error will raise.
| 17 | 148 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _validate_path(self) -> list[Any]:
msg = (
"xpath does not return any nodes or attributes. "
"Be sure to specify in `xpath` the parent nodes of ... |
1,122 | def mask(self, row_labels, col_labels):
new_obj = super().mask(row_labels, col_labels)
if isinstance(row_labels, slice) and isinstance(
self._length_cache, ObjectIDType
):
new_obj._length_cache = compute_sliced_len.remote(
row_labels, self._length... |
Lazily create a mask that extracts the indices provided.
Parameters
----------
row_labels : list-like, slice or label
The row labels for the rows to extract.
col_labels : list-like, slice or label
The column labels for the columns to extract.
Re... | 46 | 38 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def mask(self, row_labels, col_labels):
new_obj = super().mask(row_labels, col_labels)
if isinstance(row_labels, slice) and isinstance(
self._length_cach... |
1,123 | def postprocess(data_out, label_list, top_k):
output = []
for result in data_out:
result_i = softmax(result)
output_i = {}
indexs = np.argsort(result_i)[::-1][0:top_k]
for index in indexs:
label = label_list[index].split(',')[0]
output_i[label] = floa... |
Postprocess output of network, one image at a time.
Args:
data_out (numpy.ndarray): output data of network.
label_list (list): list of label.
top_k (int): Return top k results.
| 27 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def postprocess(data_out, label_list, top_k):
output = []
for result in data_out:
result_i = softmax(result)
output_i = {}
indexs = np.argsort(result_i)[... |
1,124 | def requests(self):
if hasattr(self, '_requests'):
return self._requests
else:
if not hasattr(self, 'requests_by_class'):
self.requests_by_class = {}
if self.__class__.__name__ not in self.requests_by_class:
self.requests_by_cl... |
Get the request dictionary corresponding to this specific class
:return: Returns the requests corresponding to the specific Executor instance class
| 20 | 47 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def requests(self):
if hasattr(self, '_requests'):
return self._requests
else:
if not hasattr(self, 'requests_by_class'):
sel... |
1,125 | def __call__(self, *args, **kwargs):
r
result = super().__call__(*args, **kwargs)
if isinstance(args[0], list) and all(isinstance(el, str) for el in args[0]):
return [res[0] for res in result]
return result
|
Generate the output text(s) using text(s) given as inputs.
Args:
args (`str` or `List[str]`):
Input text for the encoder.
return_tensors (`bool`, *optional*, defaults to `False`):
Whether or not to include the tensors of predictions (as token ind... | 188 | 27 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def __call__(self, *args, **kwargs):
r
result = super().__call__(*args, **kwargs)
if isinstance(args[0], list) and all(isinstance(el, str) for el in args[0]):
... |
1,126 | def rewind_body(prepared_request):
body_seek = getattr(prepared_request.body, "seek", None)
if body_seek is not None and isinstance(
prepared_request._body_position, integer_types
):
try:
body_seek(prepared_request._body_position)
except OSError:
raise Un... | Move file pointer back to its recorded starting position
so it can be read again on redirect.
| 17 | 42 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def rewind_body(prepared_request):
body_seek = getattr(prepared_request.body, "seek", None)
if body_seek is not None and isinstance(
prepared_request._body_position, int... |
1,127 | def nested_concat(tensors, new_tensors, padding_index=-100):
assert type(tensors) == type(
new_tensors
), f"Expected `tensors` and `new_tensors` to have the same type but found {type(tensors)} and {type(new_tensors)}."
if isinstance(tensors, (list, tuple)):
return type(tensors)(nested_c... |
Concat the `new_tensors` to `tensors` on the first dim and pad them on the second if needed. Works for tensors or
nested list/tuples of tensors.
| 25 | 64 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def nested_concat(tensors, new_tensors, padding_index=-100):
assert type(tensors) == type(
new_tensors
), f"Expected `tensors` and `new_tensors` to have the same type bu... |
1,128 | def kubernetes_manifest():
template = Template(
(prefect.__module_path__ / "cli" / "templates" / "kubernetes.yaml").read_text()
)
manifest = template.substitute(
{
"image_name": get_prefect_image_name(),
}
)
print(manifest)
|
Generates a kubernetes manifest for to deploy Orion to a cluster.
Example:
$ prefect orion kubernetes-manifest | kubectl apply -f -
| 21 | 22 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def kubernetes_manifest():
template = Template(
(prefect.__module_path__ / "cli" / "templates" / "kubernetes.yaml").read_text()
)
manifest = template.substitute(
... |
1,129 | def test_queries_when_requested_project_is_head_of_trace(self, mock_query, mock_querybuilder):
# Case A: Head of trace project
self.login_as(self.user)
heart = self.create_project(
name="Heart", slug="heart", teams=[self.team], fire_project_created=True
)
moc... |
Case A: Requesting for a project (bar) that is root but is a head of distributed traces
Example of smart query response (DYNAMIC_SAMPLING_DISTRIBUTION_FETCH_PROJECT_STATS):
|---------+-------+------|
| project | count | root |
|---------+-------+------|
| bar | 100 ... | 47 | 183 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_queries_when_requested_project_is_head_of_trace(self, mock_query, mock_querybuilder):
# Case A: Head of trace project
self.login_as(self.user)
heart... |
1,130 | def validate_leave_allocation_against_leave_application(ledger):
leave_application_records = frappe.db.sql_list(
,
(ledger.employee, ledger.leave_type, ledger.from_date, ledger.to_date),
)
if leave_application_records:
frappe.throw(
_("Leave allocation {0} is linked with the Leave Application {1}").forma... | Checks that leave allocation has no leave application against it
SELECT transaction_name
FROM `tabLeave Ledger Entry`
WHERE
employee=%s
AND leave_type=%s
AND transaction_type='Leave Application'
AND from_date>=%s
AND to_date<=%s
| 27 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def validate_leave_allocation_against_leave_application(ledger):
leave_application_records = frappe.db.sql_list(
,
(ledger.employee, ledger.leave_type, ledger.from_date, ledger.to_dat... |
1,131 | def dce_rpc_endianess(pkt):
try:
endianness = pkt.underlayer.endian
except AttributeError:
# handle the case where a PNIO class is
# built without its DCE-RPC under-layer
# i.e there is no endianness indication
return "!"
if endianness == 0: # big endian
... | determine the symbol for the endianness of a the DCE/RPC | 10 | 53 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def dce_rpc_endianess(pkt):
try:
endianness = pkt.underlayer.endian
except AttributeError:
# handle the case where a PNIO class is
# built without its DC... |
1,132 | def _get_extra_hosts(self, docker_client) -> Dict[str, str]:
if sys.platform == "linux" and (
# Do not warn if the user has specified a host manually that does not use
# a local address
"PREFECT_API_URL" not in self.env
or re.search(
".*(l... |
A host.docker.internal -> host-gateway mapping is necessary for communicating
with the API on Linux machines. Docker Desktop on macOS will automatically
already have this mapping.
| 25 | 108 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _get_extra_hosts(self, docker_client) -> Dict[str, str]:
if sys.platform == "linux" and (
# Do not warn if the user has specified a host manually that does n... |
1,133 | def test_del_store():
with patch("salt.modules.win_certutil.get_cert_serial") as cert_serial_mock:
cmd_mock = MagicMock(
return_value=(
"CertInfo\r\n"
"================ Certificate 0 ================\r\n"
"Serial Number: 180720d39cd2db3244ba03... |
Test removing a certificate to a specific store
| 8 | 47 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_del_store():
with patch("salt.modules.win_certutil.get_cert_serial") as cert_serial_mock:
cmd_mock = MagicMock(
return_value=(
"CertInfo... |
1,134 | def _select_backend(config):
backend_arg = config.getoption('--qute-backend')
backend_env = os.environ.get('QUTE_TESTS_BACKEND')
backend = backend_arg or backend_env or _auto_select_backend()
# Fail early if selected backend is not available
# pylint: disable=unused-import
if backend == '... | Select the backend for running tests.
The backend is auto-selected in the following manner:
1. Use QtWebKit if available
2. Otherwise use QtWebEngine as a fallback
Auto-selection is overridden by either passing a backend via
`--qute-backend=<backend>` or setting the environment variable
`QUTE_... | 64 | 44 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _select_backend(config):
backend_arg = config.getoption('--qute-backend')
backend_env = os.environ.get('QUTE_TESTS_BACKEND')
backend = backend_arg or backend_env or _au... |
1,135 | def equals(self, other):
from sympy.logic.inference import satisfiable
from sympy.core.relational import Relational
if self.has(Relational) or other.has(Relational):
raise NotImplementedError('handling of relationals')
return self.atoms() == other.atoms() and \
... |
Returns True if the given formulas have the same truth table.
For two formulas to be equal they must have the same literals.
Examples
========
>>> from sympy.abc import A, B, C
>>> from sympy import And, Or, Not
>>> (A >> B).equals(~B >> ~A)
True
... | 58 | 28 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def equals(self, other):
from sympy.logic.inference import satisfiable
from sympy.core.relational import Relational
if self.has(Relational) or other.has(Rel... |
1,136 | def get_latest_stock_qty(item_code, warehouse=None):
values, condition = [item_code], ""
if warehouse:
lft, rgt, is_group = frappe.db.get_value("Warehouse", warehouse, ["lft", "rgt", "is_group"])
if is_group:
values.extend([lft, rgt])
condition += "and exists (\
select name from `tabWarehouse` wh where... | select sum(actual_qty) from tabBin
where item_code=%s {0} | 7 | 64 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_latest_stock_qty(item_code, warehouse=None):
values, condition = [item_code], ""
if warehouse:
lft, rgt, is_group = frappe.db.get_value("Warehouse", warehouse, ["lft", "rgt", "is... |
1,137 | def get_feature_names_out(self, input_features=None):
input_features = _check_feature_names_in(
self, input_features, generate_names=True
)
est_name = self.__class__.__name__.lower()
names_list = [f"{est_name}_{name}_sqrt" for name in input_features]
for j ... | Get output feature names for transformation.
Parameters
----------
input_features : array-like of str or None, default=None
Only used to validate feature names with the names seen in :meth:`fit`.
Returns
-------
feature_names_out : ndarray of str objects
... | 39 | 45 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_feature_names_out(self, input_features=None):
input_features = _check_feature_names_in(
self, input_features, generate_names=True
)
est_n... |
1,138 | def test_render_valid_image_as_context_variable(self):
context = {"image": self.image, "image_node": "fake value"}
node = ImageNode(Variable("image"), "original", "image_node")
rendered = node.render(context)
self.assertEqual(rendered, "")
self.assertIsInstance(context... |
Tests that an ImageNode with a valid image and a context variable name
renders an empty string and puts a rendition in the context variable
| 25 | 21 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_render_valid_image_as_context_variable(self):
context = {"image": self.image, "image_node": "fake value"}
node = ImageNode(Variable("image"), "original", "i... |
1,139 | def dup_cauchy_lower_bound(f, K):
g = dup_reverse(f)
if len(g) < 2:
raise PolynomialError('Polynomial has no non-zero roots.')
if K.is_ZZ:
K = K.get_field()
b = dup_cauchy_upper_bound(g, K)
return K.one / b
| Compute the Cauchy lower bound on the absolute value of all non-zero
roots of f, real or complex. | 18 | 29 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def dup_cauchy_lower_bound(f, K):
g = dup_reverse(f)
if len(g) < 2:
raise PolynomialError('Polynomial has no non-zero roots.')
if K.is_ZZ:
K = K.get_field()
... |
1,140 | def call_deploy(cls, fname, col_partitions, storage_options, **kwargs):
from pyarrow.parquet import ParquetFile
from modin.core.storage_formats.pandas.parsers import ParquetFileToRead
# If we don't have any columns to read, we should just return an empty
# set of references.
... |
Deploy remote tasks to the workers with passed parameters.
Parameters
----------
fname : str, path object or file-like object
Name of the file to read.
col_partitions : list
List of arrays with columns names that should be read
by each partit... | 71 | 327 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def call_deploy(cls, fname, col_partitions, storage_options, **kwargs):
from pyarrow.parquet import ParquetFile
from modin.core.storage_formats.pandas.parsers import... |
1,141 | def get_connection(self):
if self.lib == _PSYCOPG_LIB_NAME:
import psycopg2
return psycopg2.connect(*self.args, **self.kwargs)
if self.lib == _SQLALCHEMY_LIB_NAME:
from sqlalchemy import create_engine
return create_engine(*self.args, **self.kwar... |
Make the database connection and get it.
For psycopg2, pass all arguments to psycopg2.connect() and return the
result of psycopg2.connect(). For sqlalchemy, pass all arguments to
sqlalchemy.create_engine() and return the result of calling connect()
on the engine.
Retur... | 44 | 26 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_connection(self):
if self.lib == _PSYCOPG_LIB_NAME:
import psycopg2
return psycopg2.connect(*self.args, **self.kwargs)
if self.lib =... |
1,142 | def argmax(x, axis=-1):
return tf.argmax(x, axis)
@keras_export("keras.backend.argmin")
@tf.__internal__.dispatch.add_dispatch_support
@doc_controls.do_not_generate_docs | Returns the index of the maximum value along an axis.
Args:
x: Tensor or variable.
axis: axis along which to perform the reduction.
Returns:
A tensor.
| 26 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def argmax(x, axis=-1):
return tf.argmax(x, axis)
@keras_export("keras.backend.argmin")
@tf.__internal__.dispatch.add_dispatch_support
@doc_controls.do_not_generate_docs
`... |
1,143 | def print_rules(self) -> Iterator[str]:
yield from self._defined_facts_lines()
yield ''
yield ''
yield from self._full_implications_lines()
yield ''
yield ''
yield from self._prereq_lines()
yield ''
yield ''
yield from self._beta_r... | Returns a generator with lines to represent the facts and rules | 11 | 51 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def print_rules(self) -> Iterator[str]:
yield from self._defined_facts_lines()
yield ''
yield ''
yield from self._full_implications_lines()
y... |
1,144 | def ensure_string(self, option, default=None):
self._ensure_stringlike(option, "string", default)
| Ensure that 'option' is a string; if not defined, set it to
'default'.
| 13 | 7 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def ensure_string(self, option, default=None):
self._ensure_stringlike(option, "string", default)
```
###Assistant : Ensure that 'option' is a string; if not de... |
1,145 | def update_ema(target_params, source_params, rate=0.99):
for targ, src in zip(target_params, source_params):
targ.detach().mul_(rate).add_(src, alpha=1 - rate)
|
Update target parameters to be closer to those of source parameters using
an exponential moving average.
:param target_params: the target parameter sequence.
:param source_params: the source parameter sequence.
:param rate: the EMA rate (closer to 1 means slower).
| 38 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def update_ema(target_params, source_params, rate=0.99):
for targ, src in zip(target_params, source_params):
targ.detach().mul_(rate).add_(src, alpha=1 - rate)
```... |
1,146 | def _android_folder() -> str | None:
try:
# First try to get path to android app via pyjnius
from jnius import autoclass
Context = autoclass("android.content.Context") # noqa: N806
result: str | None = Context.getFilesDir().getParentFile().getAbsolutePath()
except Exceptio... | :return: base folder for the Android OS or None if cannot be found | 13 | 68 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _android_folder() -> str | None:
try:
# First try to get path to android app via pyjnius
from jnius import autoclass
Context = autoclass("android.conten... |
1,147 | def de_bruijn(charset, n, maxlen):
# type: (str, int, int) -> str
k = len(charset)
a = [0] * k * n
sequence = [] # type: List[str]
|
Generate the De Bruijn Sequence up to `maxlen` characters
for the charset `charset` and subsequences of length `n`.
Algorithm modified from wikipedia
https://en.wikipedia.org/wiki/De_Bruijn_sequence
| 23 | 27 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def de_bruijn(charset, n, maxlen):
# type: (str, int, int) -> str
k = len(charset)
a = [0] * k * n
sequence = [] # type: List[str]
```
... |
1,148 | def _add_option_refresh(self) -> None:
logger.debug("Adding refresh option")
btnrefresh = ttk.Button(self.optsframe,
image=get_images().icons["reload"],
command=lambda x="update": preview_trigger().set(x)) # type:ignore
bt... | Add refresh button to refresh preview immediately | 7 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _add_option_refresh(self) -> None:
logger.debug("Adding refresh option")
btnrefresh = ttk.Button(self.optsframe,
image=get_images... |
1,149 | def close(self):
try:
if hasattr(self, "_close__fp"):
self._close__fp()
if self.fp:
self.fp.close()
self.fp = None
except Exception as msg:
logger.debug("Error closing: %s", msg)
if getattr(self, "map", Non... |
Closes the file pointer, if possible.
This operation will destroy the image core and release its memory.
The image data will be unusable afterward.
This function is required to close images that have multiple frames or
have not had their file read and closed by the
:py... | 53 | 60 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def close(self):
try:
if hasattr(self, "_close__fp"):
self._close__fp()
if self.fp:
self.fp.close()
self.... |
1,150 | def diop_general_sum_of_squares(eq, limit=1):
r
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == GeneralSumOfSquares.name:
return set(GeneralSumOfSquares(eq).solve(limit=limit))
|
Solves the equation `x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`.
Returns at most ``limit`` number of solutions.
Usage
=====
``general_sum_of_squares(eq, limit)`` : Here ``eq`` is an expression which
is assumed to be zero. Also, ``eq`` should be in the form,
`x_{1}^2 + x_{2}^2 + . . . +... | 138 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def diop_general_sum_of_squares(eq, limit=1):
r
var, coeff, diop_type = classify_diop(eq, _dict=False)
if diop_type == GeneralSumOfSquares.name:
return set(GeneralSumOfS... |
1,151 | def resolved_combinations(self) -> Tuple[Tuple[ChallengeBody, ...], ...]:
warnings.warn(
"acme.messages.Authorization.resolved_combinations is deprecated and will be "
"removed in a future release.", DeprecationWarning)
return tuple(tuple(self.challenges[idx] for idx in ... | Combinations with challenges instead of indices.
.. deprecated: 1.30.0
| 9 | 34 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def resolved_combinations(self) -> Tuple[Tuple[ChallengeBody, ...], ...]:
warnings.warn(
"acme.messages.Authorization.resolved_combinations is deprecated and wil... |
1,152 | def test_tweedie_log_identity_consistency(p):
half_tweedie_log = HalfTweedieLoss(power=p)
half_tweedie_identity = HalfTweedieLossIdentity(power=p)
n_samples = 10
y_true, raw_prediction = random_y_true_raw_prediction(
loss=half_tweedie_log, n_samples=n_samples, seed=42
)
y_pred = hal... | Test for identical losses when only the link function is different. | 11 | 174 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_tweedie_log_identity_consistency(p):
half_tweedie_log = HalfTweedieLoss(power=p)
half_tweedie_identity = HalfTweedieLossIdentity(power=p)
n_samples = 10
y_true,... |
1,153 | def laplace_transform(f, t, s, legacy_matrix=True, **hints):
r
debug('\n***** laplace_transform(%s, %s, %s)'%(f, t, s))
if isinstance(f, MatrixBase) and hasattr(f, 'applyfunc'):
conds = not hints.get('noconds', False)
if conds and legacy_matrix:
SymPyDeprecationWarning(
... |
Compute the Laplace Transform `F(s)` of `f(t)`,
.. math :: F(s) = \int_{0^{-}}^\infty e^{-st} f(t) \mathrm{d}t.
Explanation
===========
For all sensible functions, this converges absolutely in a
half-plane
.. math :: a < \operatorname{Re}(s)
This function returns ``(F, a, cond)`` w... | 300 | 89 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def laplace_transform(f, t, s, legacy_matrix=True, **hints):
r
debug('\n***** laplace_transform(%s, %s, %s)'%(f, t, s))
if isinstance(f, MatrixBase) and hasattr(f, 'applyfunc')... |
1,154 | def reduce_annotations(anno_types, answers):
for at in set(anno_types):
assert at in ("no_answer", "short_answer")
if anno_types.count("short_answer") >= anno_types.count("no_answer"):
majority = "short_answer"
is_impossible = False
else:
majority = "no_answer"
i... |
In cases where there is annotator disagreement, this fn picks either only the short_answers or only the no_answers,
depending on which is more numerous, with a bias towards picking short_answers.
Note: By this stage, all long_answer annotations and all samples with yes/no answer have been removed.
Thi... | 52 | 71 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def reduce_annotations(anno_types, answers):
for at in set(anno_types):
assert at in ("no_answer", "short_answer")
if anno_types.count("short_answer") >= anno_types.coun... |
1,155 | async def async_open_cover(self, **kwargs):
await mqtt.async_publish(
self.hass,
self._config.get(CONF_COMMAND_TOPIC),
self._config[CONF_PAYLOAD_OPEN],
self._config[CONF_QOS],
self._config[CONF_RETAIN],
self._config[CONF_ENCODING],... | Move the cover up.
This method is a coroutine.
| 9 | 35 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def async_open_cover(self, **kwargs):
await mqtt.async_publish(
self.hass,
self._config.get(CONF_COMMAND_TOPIC),
self._config[CONF_... |
1,156 | def _parse_distro_release_content(line):
# type: (str) -> Dict[str, str]
matches = _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN.match(line.strip()[::-1])
distro_info = {}
if matches:
# regexp ensures non-None
distro_info["name"] = matches.group(3)[::-1]
... |
Parse a line from a distro release file.
Parameters:
* line: Line from the distro release file. Must be a unicode string
or a UTF-8 encoded byte string.
Returns:
A dictionary containing all information items.
| 35 | 43 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _parse_distro_release_content(line):
# type: (str) -> Dict[str, str]
matches = _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN.match(line.strip()[::-1])
distro_... |
1,157 | def load_sharded_checkpoint(model, folder, strict=True):
# Load the index
index_file = os.path.join(folder, WEIGHTS_INDEX_NAME)
if not os.path.isfile(index_file):
raise ValueError(f"Can't find a checkpoint index ({WEIGHTS_INDEX_NAME}) in {folder}.")
with open(index_file, "r", encoding="utf... |
This is the same as
[`torch.nn.Module.load_state_dict`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html?highlight=load_state_dict#torch.nn.Module.load_state_dict)
but for a sharded checkpoint.
This load is performed efficiently: each checkpoint shard is loaded one by one in RAM and dele... | 115 | 167 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def load_sharded_checkpoint(model, folder, strict=True):
# Load the index
index_file = os.path.join(folder, WEIGHTS_INDEX_NAME)
if not os.path.isfile(index_file):
ra... |
1,158 | def customer_query(doctype, txt, searchfield, start, page_len, filters):
conditions = []
cust_master_name = frappe.defaults.get_user_default("cust_master_name")
if cust_master_name == "Customer Name":
fields = ["name", "customer_group", "territory"]
else:
fields = ["name", "customer_name", "customer_group", "t... | select {fields} from `tabCustomer`
where docstatus < 2
and ({scond}) and disabled=0
{fcond} {mcond}
order by
if(locate(%(_txt)s, name), locate(%(_txt)s, name), 99999),
if(locate(%(_txt)s, customer_name), locate(%(_txt)s, customer_name), 99999),
idx desc,
name, customer_name
limit %(start)s, %(pa... | 33 | 86 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def customer_query(doctype, txt, searchfield, start, page_len, filters):
conditions = []
cust_master_name = frappe.defaults.get_user_default("cust_master_name")
if cust_master_name == "C... |
1,159 | def get_group_tag_value_count(self, group, environment_id, key):
raise NotImplementedError
|
>>> get_group_tag_value_count(group, 3, 'key1')
| 4 | 7 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_group_tag_value_count(self, group, environment_id, key):
raise NotImplementedError
```
###Assistant :
>>> get_group_tag_value_count(group, 3, '... |
1,160 | def test_enqueue_task_instances_sets_ti_state_to_None_if_dagrun_in_finish_state(self, state, dag_maker):
dag_id = 'SchedulerJobTest.test_enqueue_task_instances_with_queued_state'
task_id_1 = 'dummy'
session = settings.Session()
with dag_maker(dag_id=dag_id, start_date=DEFAULT_DA... | This tests that task instances whose dagrun is in finished state are not queued | 14 | 47 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_enqueue_task_instances_sets_ti_state_to_None_if_dagrun_in_finish_state(self, state, dag_maker):
dag_id = 'SchedulerJobTest.test_enqueue_task_instances_with_queued_s... |
1,161 | def match_hostname(cert, hostname):
if not cert:
raise ValueError("empty or no certificate, match_hostname needs a "
"SSL socket or SSL context with either "
"CERT_OPTIONAL or CERT_REQUIRED")
dnsnames = []
san = cert.... | Verify that *cert* (in decoded format as returned by
SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125
rules are followed, but IP addresses are not accepted for *hostname*.
CertificateError is raised on failure. On success, the function
returns nothing.
| 40 | 155 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def match_hostname(cert, hostname):
if not cert:
raise ValueError("empty or no certificate, match_hostname needs a "
"SSL socket or ... |
1,162 | def take(self, n) -> "IterableDataset":
ex_iterable = TakeExamplesIterable(self._ex_iterable, n)
return iterable_dataset(
ex_iterable=ex_iterable,
info=self._info.copy(),
split=self._split,
format_type=self._format_type,
shuffling=copy... |
Create a new IterableDataset with only the first ``n`` elements.
Args:
n (:obj:`int`): number of elements to take.
Example:
```py
>>> from datasets import load_dataset
>>> ds = load_dataset("rotten_tomatoes", split="train", streaming=True)
>>> smal... | 117 | 18 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def take(self, n) -> "IterableDataset":
ex_iterable = TakeExamplesIterable(self._ex_iterable, n)
return iterable_dataset(
ex_iterable=ex_iterable,
... |
1,163 | def test_category_match_group(self):
from sentry.grouping.enhancer import Enhancements
enhancement = Enhancements.from_config_string(
,
)
event = make_event(
platform="native",
exception={
"values": [
{
... |
Regression test to ensure categories are applied consistently and don't
produce hash mismatches.
function:foo category=foo_like
category:foo_like -group
| 17 | 66 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_category_match_group(self):
from sentry.grouping.enhancer import Enhancements
enhancement = Enhancements.from_config_string(
,
)
... |
1,164 | def notify(self, notification, raise_exception=False):
event = notification.event
try:
return self.notify_users(
event.group, event, triggering_rules=[r.label for r in notification.rules]
)
except (
ApiError,
HTTPError,
... |
This calls the notify_users method of the plugin.
Normally this method eats the error and logs it but if we
set raise_exception=True like we do for the test plugin button,
the exception is raised
| 34 | 48 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def notify(self, notification, raise_exception=False):
event = notification.event
try:
return self.notify_users(
event.group, event, trig... |
1,165 | def test_processors(self):
from djangocms_text_ckeditor.cms_plugins import TextPlugin
from cms.plugin_pool import plugin_pool
instance = CMSPlugin.objects.all()[0].get_plugin_instance()[0]
load_from_string = self.load_template_from_string
|
Tests that plugin processors and plugin context processors can be defined
in settings and are working and that extra plugin context processors can be
passed to PluginContext.
| 27 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_processors(self):
from djangocms_text_ckeditor.cms_plugins import TextPlugin
from cms.plugin_pool import plugin_pool
instance = CMSPlugin.objects.... |
1,166 | async def test_unique_id_ignore(hass, manager):
async_setup_entry = AsyncMock(return_value=False)
mock_integration(hass, MockModule("comp", async_setup_entry=async_setup_entry))
mock_entity_platform(hass, "config_flow.comp", None)
| Test that we can ignore flows that are in progress and have a unique ID. | 15 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_unique_id_ignore(hass, manager):
async_setup_entry = AsyncMock(return_value=False)
mock_integration(hass, MockModule("comp", async_setup_entry=async_setup_entry))... |
1,167 | def bind(self, bind_string, key, propagate=True):
if not self._is_window_created('tried Window.bind'):
return
self.TKroot.bind(bind_string, lambda evt: self._user_bind_callback(bind_string, evt, propagate))
self.user_bind_dict[bind_string] = key
|
Used to add tkinter events to a Window.
The tkinter specific data is in the Window's member variable user_bind_event
:param bind_string: The string tkinter expected in its bind function
:type bind_string: (str)
:param key: The event that will be generated when the tkint... | 70 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def bind(self, bind_string, key, propagate=True):
if not self._is_window_created('tried Window.bind'):
return
self.TKroot.bind(bind_string, lambda evt: s... |
1,168 | def forward(self, body_feats=None, rois=None, rois_num=None, inputs=None):
targets = []
if self.training:
rois, rois_num, targets = self.bbox_assigner(rois, rois_num, inputs)
targets_list = [targets]
self.assigned_rois = (rois, rois_num)
self.assi... |
body_feats (list[Tensor]): Feature maps from backbone
rois (Tensor): RoIs generated from RPN module
rois_num (Tensor): The number of RoIs in each image
inputs (dict{Tensor}): The ground-truth of image
| 28 | 167 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def forward(self, body_feats=None, rois=None, rois_num=None, inputs=None):
targets = []
if self.training:
rois, rois_num, targets = self.bbox_assigner(ro... |
1,169 | def get_fws(value):
newvalue = value.lstrip()
fws = WhiteSpaceTerminal(value[:len(value)-len(newvalue)], 'fws')
return fws, newvalue
| FWS = 1*WSP
This isn't the RFC definition. We're using fws to represent tokens where
folding can be done, but when we are parsing the *un*folding has already
been done so we don't need to watch out for CRLF.
| 39 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_fws(value):
newvalue = value.lstrip()
fws = WhiteSpaceTerminal(value[:len(value)-len(newvalue)], 'fws')
return fws, newvalue
```
###Assistant : FWS = 1*... |
1,170 | def load_data_snli(batch_size, num_steps=50):
num_workers = d2l.get_dataloader_workers()
data_dir = d2l.download_extract('SNLI')
train_data = read_snli(data_dir, True)
test_data = read_snli(data_dir, False)
train_set = SNLIDataset(train_data, num_steps)
test_set = SNLIDataset(test_data, num... | Download the SNLI dataset and return data iterators and vocabulary.
Defined in :numref:`sec_natural-language-inference-and-dataset` | 13 | 42 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def load_data_snli(batch_size, num_steps=50):
num_workers = d2l.get_dataloader_workers()
data_dir = d2l.download_extract('SNLI')
train_data = read_snli(data_dir, True)
t... |
1,171 | def plot_feature_importance(model, feature_names, pair, train_dir, count_max=50) -> None:
try:
import plotly.graph_objects as go
from plotly.subplots import make_subplots
except ImportError:
logger.exception("Module plotly not found \n Please install using `pip3 install plotly`")
... |
Plot Best and Worst Features by importance for CatBoost model.
Called once per sub-train.
Usage: plot_feature_importance(
model=model,
feature_names=dk.training_features_list,
pair=pair,
train_dir=dk.data_path)
| 20 | 84 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def plot_feature_importance(model, feature_names, pair, train_dir, count_max=50) -> None:
try:
import plotly.graph_objects as go
from plotly.subplots import make_sub... |
1,172 | def get_primary_key_column(self, cursor, table_name):
cursor.execute(
"PRAGMA table_info(%s)" % self.connection.ops.quote_name(table_name)
)
for _, name, *_, pk in cursor.fetchall():
if pk:
return name
return None
| Return the column name of the primary key for the given table. | 12 | 23 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_primary_key_column(self, cursor, table_name):
cursor.execute(
"PRAGMA table_info(%s)" % self.connection.ops.quote_name(table_name)
)
for ... |
1,173 | def validate_settings():
try:
django_backend = [x for x in settings.TEMPLATES
if x['BACKEND'] == 'django.template.backends.django.DjangoTemplates'][0]
except IndexError:
raise ImproperlyConfigured(
"django CMS requires django.template.context_processors... |
Check project settings file for required options
| 7 | 95 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def validate_settings():
try:
django_backend = [x for x in settings.TEMPLATES
if x['BACKEND'] == 'django.template.backends.django.DjangoTemplates']... |
1,174 | def get(cls):
min_partition_size = super().get()
assert min_partition_size > 0, "`min_partition_size` should be > 0"
return min_partition_size
|
Get ``MinPartitionSize`` with extra checks.
Returns
-------
int
| 8 | 16 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get(cls):
min_partition_size = super().get()
assert min_partition_size > 0, "`min_partition_size` should be > 0"
return min_partition_size
```
... |
1,175 | def pbt_function(config):
lr = config["lr"]
accuracy = 0.0 # end = 1000
start = 0
if session.get_checkpoint():
state = session.get_checkpoint().to_dict()
accuracy = state["acc"]
start = state["step"]
midpoint = 100 # lr starts decreasing after acc > midpoint
q_tol... | Toy PBT problem for benchmarking adaptive learning rate.
The goal is to optimize this trainable's accuracy. The accuracy increases
fastest at the optimal lr, which is a function of the current accuracy.
The optimal lr schedule for this problem is the triangle wave as follows.
Note that many lr schedul... | 104 | 207 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def pbt_function(config):
lr = config["lr"]
accuracy = 0.0 # end = 1000
start = 0
if session.get_checkpoint():
state = session.get_checkpoint().to_dict()
... |
1,176 | def add_hedge_option(price, implied_volatility, strike, days, side):
# Determine delta position given the option
delta = calc_delta(price, implied_volatility, strike, days, 0, side)
# Determine gamma position given the option
gamma = calc_gamma(price, implied_volatility, strike, days, 0)
# De... | Determine the delta, gamma and vega value of the portfolio and/or options.
Parameters
----------
price: int
The price.
implied_volatility: float
The implied volatility.
strike: float
The strike price.
days: float
The amount of days until expiration. Use annual no... | 67 | 53 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def add_hedge_option(price, implied_volatility, strike, days, side):
# Determine delta position given the option
delta = calc_delta(price, implied_volatility, strike, days, 0, s... |
1,177 | def header_encode(self, string):
codec = self.output_codec or 'us-ascii'
header_bytes = _encode(string, codec)
# 7bit/8bit encodings return the string unchanged (modulo conversions)
encoder_module = self._get_encoder(header_bytes)
if encoder_module is None:
r... | Header-encode a string by converting it first to bytes.
The type of encoding (base64 or quoted-printable) will be based on
this charset's `header_encoding`.
:param string: A unicode string for the header. It must be possible
to encode this string to bytes using the character set's... | 55 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def header_encode(self, string):
codec = self.output_codec or 'us-ascii'
header_bytes = _encode(string, codec)
# 7bit/8bit encodings return the string unchan... |
1,178 | def data_dict(self, records):
self.version = records[0].replace("File-Date:", "").strip()
dic = {}
dic["deprecated"] = {}
for label in [
"language",
"extlang",
"script",
"region",
"variant",
"redundant",
... | Convert the BCP-47 language subtag registry to a dictionary | 9 | 137 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def data_dict(self, records):
self.version = records[0].replace("File-Date:", "").strip()
dic = {}
dic["deprecated"] = {}
for label in [
... |
1,179 | def test_async_add_hass_job_schedule_partial_coroutinefunction(event_loop):
hass = MagicMock(loop=MagicMock(wraps=event_loop))
| Test that we schedule partial coros and add jobs to the job pool. | 13 | 5 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_async_add_hass_job_schedule_partial_coroutinefunction(event_loop):
hass = MagicMock(loop=MagicMock(wraps=event_loop))
```
###Assistant : Test that we schedule ... |
1,180 | def to_label_objs(self, answer_type="generative"):
df_labels = self.df[["id", "question", "answer_text", "answer_start", "context", "document_id"]]
record_dicts = df_labels.to_dict("records")
labels = [
Label(
query=record["question"],
answer=... | Export all labels stored in this object to haystack.Label objects | 10 | 36 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def to_label_objs(self, answer_type="generative"):
df_labels = self.df[["id", "question", "answer_text", "answer_start", "context", "document_id"]]
record_dicts = df... |
1,181 | def test_api_get_storage_path(self):
response = self.client.get("/api/storage_paths/", format="json")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data["count"], 1)
resp_storage_path = response.data["... |
GIVEN:
- API request to get all storage paths
WHEN:
- API is called
THEN:
- Existing storage paths are returned
| 21 | 19 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_api_get_storage_path(self):
response = self.client.get("/api/storage_paths/", format="json")
self.assertEqual(response.status_code, 200)
self.asser... |
1,182 | def test_normalize_metric_warning():
msg = "Normalized stress is not supported"
sim = np.array([[0, 5, 3, 4], [5, 0, 2, 2], [3, 2, 0, 1], [4, 2, 1, 0]])
with pytest.raises(ValueError, match=msg):
mds.smacof(sim, metric=True, normalized_stress=True)
|
Test that a UserWarning is emitted when using normalized stress with
metric-MDS.
| 12 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_normalize_metric_warning():
msg = "Normalized stress is not supported"
sim = np.array([[0, 5, 3, 4], [5, 0, 2, 2], [3, 2, 0, 1], [4, 2, 1, 0]])
with pytest.raises(V... |
1,183 | def delete_and_patch_duplicate_bins():
duplicate_bins = frappe.db.sql(, as_dict=1)
for duplicate_bin in duplicate_bins:
existing_bins = frappe.get_list("Bin",
filters={
"item_code": duplicate_bin.item_code,
"warehouse": duplicate_bin.warehouse
},
fields=["name"],
order_by="creation",)
... |
SELECT
item_code, warehouse, count(*) as bin_count
FROM
tabBin
GROUP BY
item_code, warehouse
HAVING
bin_count > 1
| 16 | 54 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def delete_and_patch_duplicate_bins():
duplicate_bins = frappe.db.sql(, as_dict=1)
for duplicate_bin in duplicate_bins:
existing_bins = frappe.get_list("Bin",
filters={
"item_... |
1,184 | async def test_stop_long_running_job(job_sdk_client):
agent_client, head_client = job_sdk_client
with tempfile.TemporaryDirectory() as tmp_dir:
path = Path(tmp_dir)
driver_script =
test_script_file = path / "test_script.py"
with open(test_script_file, "w+") as file:
... |
Submit a job that runs for a while and stop it in the middle.
print('Hello !')
import time
time.sleep(300) # This should never finish
raise RuntimeError('Intentionally failed.')
| 27 | 74 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
async def test_stop_long_running_job(job_sdk_client):
agent_client, head_client = job_sdk_client
with tempfile.TemporaryDirectory() as tmp_dir:
path = Path(tmp_dir)
... |
1,185 | def print_help(self):
source_txt = CRYPTO_SOURCES.get(self.source, "?") if self.source != "" else ""
help_text = f
console.print(text=help_text, menu="Stocks - Due Diligence")
| Print help[cmds]
load load a specific cryptocurrency for analysis
[param]Coin: [/param]{self.current_coin}
[param]Source: [/param]{source_txt}
[src]Glassnode[/src]
active active addresses
nonzero addresses with non-zero balances
change 30d change of supply held on exchang... | 187 | 20 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def print_help(self):
source_txt = CRYPTO_SOURCES.get(self.source, "?") if self.source != "" else ""
help_text = f
console.print(text=help_text, menu="Stocks... |
1,186 | def test_get_cached_repo_files_with_all_files(self):
responses.add(
method=responses.GET,
url=f"https://api.github.com/repos/{self.repo.name}/git/trees/master?recursive=1",
status=200,
json={
"tree": [
{"type": "blob", ... | Fetch files for repo. All files rather than just source code files | 12 | 38 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_get_cached_repo_files_with_all_files(self):
responses.add(
method=responses.GET,
url=f"https://api.github.com/repos/{self.repo.name}/git/tre... |
1,187 | def check_migrations(self):
from django.db.migrations.executor import MigrationExecutor
try:
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
except ImproperlyConfigured:
# No databases are configured (or the dummy one)
return
pla... |
Print a warning if the set of migrations on disk don't match the
migrations in the database.
| 17 | 79 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def check_migrations(self):
from django.db.migrations.executor import MigrationExecutor
try:
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])... |
1,188 | def find_induced_nodes(G, s, t, treewidth_bound=sys.maxsize):
if not is_chordal(G):
raise nx.NetworkXError("Input graph is not chordal.")
H = nx.Graph(G)
H.add_edge(s, t)
induced_nodes = set()
triplet = _find_chordality_breaker(H, s, treewidth_bound)
while triplet:
(u, v, w... | Returns the set of induced nodes in the path from s to t.
Parameters
----------
G : graph
A chordal NetworkX graph
s : node
Source node to look for induced nodes
t : node
Destination node to look for induced nodes
treewidth_bound: float
Maximum treewidth acceptable... | 239 | 82 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def find_induced_nodes(G, s, t, treewidth_bound=sys.maxsize):
if not is_chordal(G):
raise nx.NetworkXError("Input graph is not chordal.")
H = nx.Graph(G)
H.add_edge... |
1,189 | def any_skipna_inferred_dtype(request):
inferred_dtype, values = request.param
values = np.array(values, dtype=object) # object dtype to avoid casting
# correctness of inference tested in tests/dtypes/test_inference.py
return inferred_dtype, values
# --------------------------------------------... |
Fixture for all inferred dtypes from _libs.lib.infer_dtype
The covered (inferred) types are:
* 'string'
* 'empty'
* 'bytes'
* 'mixed'
* 'mixed-integer'
* 'mixed-integer-float'
* 'floating'
* 'integer'
* 'decimal'
* 'boolean'
* 'datetime64'
* 'datetime'
* 'da... | 100 | 33 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def any_skipna_inferred_dtype(request):
inferred_dtype, values = request.param
values = np.array(values, dtype=object) # object dtype to avoid casting
# correctness of inf... |
1,190 | def downsample_2d(x, k=None, factor=2, gain=1, data_format='NCHW', impl='cuda'):
r
assert isinstance(factor, int) and factor >= 1
if k is None:
k = [1] * factor
k = _setup_kernel(k) * gain
p = k.shape[0] - factor
return _simple_upfirdn_2d(x, k, down=factor, pad0=(p+1)//2, pad1=p//2, dat... | Downsample a batch of 2D images with the given filter.
Accepts a batch of 2D images of the shape `[N, C, H, W]` or `[N, H, W, C]`
and downsamples each image with the given filter. The filter is normalized so that
if the input pixels are constant, they will be scaled by the specified `gain`.
Pixels outs... | 181 | 43 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def downsample_2d(x, k=None, factor=2, gain=1, data_format='NCHW', impl='cuda'):
r
assert isinstance(factor, int) and factor >= 1
if k is None:
k = [1] * factor
k = ... |
1,191 | def _check_deprecated_resample_kwargs(kwargs, origin):
# Deprecation warning of `base` and `loffset` since v1.1.0:
# we are raising the warning here to be able to set the `stacklevel`
# properly since we need to raise the `base` and `loffset` deprecation
# warning from three different cases:
# ... |
Check for use of deprecated parameters in ``resample`` and related functions.
Raises the appropriate warnings if these parameters are detected.
Only sets an approximate ``stacklevel`` for the warnings (see #37603, #36629).
Parameters
----------
kwargs : dict
Dictionary of keyword argu... | 65 | 136 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _check_deprecated_resample_kwargs(kwargs, origin):
# Deprecation warning of `base` and `loffset` since v1.1.0:
# we are raising the warning here to be able to set the `stack... |
1,192 | def get_conn(self) -> DataCatalogClient:
if not self._client:
self._client = DataCatalogClient(credentials=self._get_credentials(), client_info=CLIENT_INFO)
return self._client
| Retrieves client library object that allow access to Cloud Data Catalog service. | 12 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_conn(self) -> DataCatalogClient:
if not self._client:
self._client = DataCatalogClient(credentials=self._get_credentials(), client_info=CLIENT_INFO)
... |
1,193 | def get_api_client(self) -> ApiClient:
try:
return new_client_from_config_dict(
config_dict=self.config, context=self.context
)
except ConfigException:
raise
|
Returns an instance of the kubernetes api client with a specific context
| 12 | 13 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def get_api_client(self) -> ApiClient:
try:
return new_client_from_config_dict(
config_dict=self.config, context=self.context
)
... |
1,194 | def cuts(self) -> list[list[int]]:
if self._cuts is not None:
return self._cuts
width = self.width
height = self.height
screen_region = Region(0, 0, width, height)
cuts_sets = [{0, width} for _ in range(height)]
if self.map is not None:
f... | Get vertical cuts.
A cut is every point on a line where a widget starts or ends.
Returns:
list[list[int]]: A list of cuts for every line.
| 26 | 75 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def cuts(self) -> list[list[int]]:
if self._cuts is not None:
return self._cuts
width = self.width
height = self.height
screen_region = R... |
1,195 | def is_subclassed(layer):
return (
layer.__module__.find("keras.engine") == -1
and layer.__module__.find("keras.layers") == -1
)
| Returns True if the object is a subclassed layer or subclassed model. | 12 | 12 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def is_subclassed(layer):
return (
layer.__module__.find("keras.engine") == -1
and layer.__module__.find("keras.layers") == -1
)
```
###Assistant :... |
1,196 | def _mat(self):
sympy_deprecation_warning(
,
deprecated_since_version="1.9",
active_deprecations_target="deprecated-private-matrix-attributes"
)
return self.flat()
|
The private _mat attribute of Matrix is deprecated. Use the
.flat() method instead.
| 13 | 9 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def _mat(self):
sympy_deprecation_warning(
,
deprecated_since_version="1.9",
active_deprecations_target="deprecated-private-matrix-attributes"
... |
1,197 | def test_missing_required_field(self):
cf3 = CustomField(type=CustomFieldTypeChoices.TYPE_TEXT, name='baz', required=True)
cf3.save()
cf3.content_types.set([ContentType.objects.get_for_model(Site)])
site = Site(name='Test Site', slug='test-site')
# Set custom field dat... |
Check that a ValidationError is raised if any required custom fields are not present.
| 14 | 34 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_missing_required_field(self):
cf3 = CustomField(type=CustomFieldTypeChoices.TYPE_TEXT, name='baz', required=True)
cf3.save()
cf3.content_types.set([... |
1,198 | def test_basic(self):
context = Context({})
template =
expected =
self.assertHTMLEqual(expected, Template(template).render(context))
|
{% load wagtailadmin_tags %}
{% fragment as my_fragment %}
<p>Hello, World</p>
{% endfragment %}
Text coming after:
{{ my_fragment }}
Text coming after:
<p>Hello, World</p>
| 25 | 11 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def test_basic(self):
context = Context({})
template =
expected =
self.assertHTMLEqual(expected, Template(template).render(context))
```
###... |
1,199 | def to_dense(self) -> Series:
from pandas import Series
return Series(
self._parent.array.to_dense(),
index=self._parent.index,
name=self._parent.name,
)
|
Convert a Series from sparse values to dense.
.. versionadded:: 0.25.0
Returns
-------
Series:
A Series with the same values, stored as a dense array.
Examples
--------
>>> series = pd.Series(pd.arrays.SparseArray([0, 1, 0]))
>>> se... | 54 | 14 | Python |
###User : Below is a Python method which does a task. Create a documentation for the below code :
```Python
def to_dense(self) -> Series:
from pandas import Series
return Series(
self._parent.array.to_dense(),
index=self._parent.index,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.