task_id int64 0 804 | implementation stringlengths 90 31.2k | test_cases_list listlengths 1 1 |
|---|---|---|
0 | def _isna_new(obj):
elif isinstance(obj, type):
return False
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)):
return _isna_ndarraylike(obj, old=False)
elif isinstance(obj, ABCDataFrame):
return obj.isna()
elif isinstance(obj, list):
return ... | [
"@pytest.mark.parametrize(\n \"values, expected\",\n [\n ([1, 2, 3], np.array([False, False, False])),\n ([1, 2, np.nan], np.array([False, False, True])),\n ([1, 2, np.inf], np.array([False, False, True])),\n ([1, 2, pd.NA], np.array([False, False, True])),\n ],\n)\ndef test_use... |
1 | def _isna_old(obj):
elif isinstance(obj, type):
return False
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)):
return _isna_ndarraylike(obj, old=True)
elif isinstance(obj, ABCDataFrame):
return obj.isna()
elif isinstance(obj, list):
return _... | [
"@pytest.mark.parametrize(\n \"values, expected\",\n [\n ([1, 2, 3], np.array([False, False, False])),\n ([1, 2, np.nan], np.array([False, False, True])),\n ([1, 2, np.inf], np.array([False, False, True])),\n ([1, 2, pd.NA], np.array([False, False, True])),\n ],\n)\ndef test_use... |
2 | def _use_inf_as_na(key):
globals()["_isna"] = _isna_new
def _isna_ndarraylike(obj, old: bool = False):
"""
Return an array indicating which values of the input array are NaN / NA.
Parameters
----------
obj: array-like
The input array whose elements are to be checked.
old: bool... | [
"@pytest.mark.parametrize(\n \"values, expected\",\n [\n ([1, 2, 3], np.array([False, False, False])),\n ([1, 2, np.nan], np.array([False, False, True])),\n ([1, 2, np.inf], np.array([False, False, True])),\n ([1, 2, pd.NA], np.array([False, False, True])),\n ],\n)\ndef test_use... |
3 | class SchemaBase(BaseModel):
not_: Optional[List[Any]] = PSchema(None, alias="not") # type: ignore
items: Optional[Any] = None
properties: Optional[Dict[str, Any]] = None
additionalProperties: Optional[Union[Dict[str, Any], bool]] = None
description: Optional[str] = None
format: Optional[str] =... | [
"from typing import Dict\n\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\nfrom starlette.testclient import TestClient\n\napp = FastAPI()\n\n\nclass Items(BaseModel):\n items: Dict[str, int]\n\n\n@app.post(\"/foo\")\ndef foo(items: Items):\n return items.items\n\n\nclient = TestClient(app)\n\n\n... |
4 | class Schema(SchemaBase):
not_: Optional[List[SchemaBase]] = PSchema(None, alias="not") # type: ignore
items: Optional[SchemaBase] = None
properties: Optional[Dict[str, SchemaBase]] = None
additionalProperties: Optional[Union[SchemaBase, bool]] = None
class Example(BaseModel): | [
"from typing import Dict\n\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\nfrom starlette.testclient import TestClient\n\napp = FastAPI()\n\n\nclass Items(BaseModel):\n items: Dict[str, int]\n\n\n@app.post(\"/foo\")\ndef foo(items: Items):\n return items.items\n\n\nclient = TestClient(app)\n\n\n... |
5 | class Operation(BaseModel):
operationId: Optional[str] = None
parameters: Optional[List[Union[Parameter, Reference]]] = None
requestBody: Optional[Union[RequestBody, Reference]] = None
responses: Union[Responses, Dict[str, Response]]
# Workaround OpenAPI recursive reference
callbacks: Optional[D... | [
"from typing import Dict\n\nfrom fastapi import FastAPI\nfrom pydantic import BaseModel\nfrom starlette.testclient import TestClient\n\napp = FastAPI()\n\n\nclass Items(BaseModel):\n items: Dict[str, int]\n\n\n@app.post(\"/foo\")\ndef foo(items: Items):\n return items.items\n\n\nclient = TestClient(app)\n\n\n... |
6 | class SeriesGroupBy(GroupBy):
res, out = np.zeros(len(ri), dtype=out.dtype), res
res[ids[idx]] = out
result = Series(res, index=ri, name=self._selection_name)
return self._reindex_output(result, fill_value=0)
@Appender(Series.describe.__doc__)
def describe(self, **kwarg... | [
"@pytest.mark.parametrize(\n \"func, zero_or_nan\",\n [\n (\"all\", np.NaN),\n (\"any\", np.NaN),\n (\"count\", 0),\n (\"first\", np.NaN),\n (\"idxmax\", np.NaN),\n (\"idxmin\", np.NaN),\n (\"last\", np.NaN),\n (\"mad\", np.NaN),\n (\"max\", np.Na... |
7 | class SeriesGroupBy(GroupBy):
minlength = ngroups or 0
out = np.bincount(ids[mask], minlength=minlength)
result = Series(
out,
index=self.grouper.result_index,
name=self._selection_name,
dtype="int64",
)
return self._reindex_output... | [
"@pytest.mark.parametrize(\n \"func, zero_or_nan\",\n [\n (\"all\", np.NaN),\n (\"any\", np.NaN),\n (\"count\", 0),\n (\"first\", np.NaN),\n (\"idxmax\", np.NaN),\n (\"idxmin\", np.NaN),\n (\"last\", np.NaN),\n (\"mad\", np.NaN),\n (\"max\", np.Na... |
8 | from pandas.core.dtypes.common import (
)
from pandas.core.dtypes.missing import isna, notna
from pandas._typing import FrameOrSeries, Scalar
from pandas.core import nanops
import pandas.core.algorithms as algorithms
from pandas.core.arrays import Categorical, try_cast_to_ea | [
"@pytest.mark.parametrize(\n \"func, zero_or_nan\",\n [\n (\"all\", np.NaN),\n (\"any\", np.NaN),\n (\"count\", 0),\n (\"first\", np.NaN),\n (\"idxmax\", np.NaN),\n (\"idxmin\", np.NaN),\n (\"last\", np.NaN),\n (\"mad\", np.NaN),\n (\"max\", np.Na... |
9 | class GroupBy(_GroupBy):
if isinstance(self.obj, Series):
result.name = self.obj.name
return self._reindex_output(result, fill_value=0)
@classmethod
def _add_numeric_operations(cls): | [
"@pytest.mark.parametrize(\n \"func, zero_or_nan\",\n [\n (\"all\", np.NaN),\n (\"any\", np.NaN),\n (\"count\", 0),\n (\"first\", np.NaN),\n (\"idxmax\", np.NaN),\n (\"idxmin\", np.NaN),\n (\"last\", np.NaN),\n (\"mad\", np.NaN),\n (\"max\", np.Na... |
10 | class GroupBy(_GroupBy):
if not self.observed and isinstance(result_index, CategoricalIndex):
out = out.reindex(result_index)
out = self._reindex_output(out)
return out.sort_index() if self.sort else out
# dropna is truthy | [
"@pytest.mark.parametrize(\n \"func, zero_or_nan\",\n [\n (\"all\", np.NaN),\n (\"any\", np.NaN),\n (\"count\", 0),\n (\"first\", np.NaN),\n (\"idxmax\", np.NaN),\n (\"idxmin\", np.NaN),\n (\"last\", np.NaN),\n (\"mad\", np.NaN),\n (\"max\", np.Na... |
11 | class GroupBy(_GroupBy):
mask = self._cumcount_array(ascending=False) < n
return self._selected_obj[mask]
def _reindex_output(
self, output: FrameOrSeries, fill_value: Scalar = np.NaN
) -> FrameOrSeries:
"""
If we have categorical groupers, then we might want to make sur... | [
"@pytest.mark.parametrize(\n \"func, zero_or_nan\",\n [\n (\"all\", np.NaN),\n (\"any\", np.NaN),\n (\"count\", 0),\n (\"first\", np.NaN),\n (\"idxmax\", np.NaN),\n (\"idxmin\", np.NaN),\n (\"last\", np.NaN),\n (\"mad\", np.NaN),\n (\"max\", np.Na... |
12 | class GroupBy(_GroupBy):
Parameters
----------
output : Series or DataFrame
Object resulting from grouping and applying an operation.
fill_value : scalar, default np.NaN
Value to use for unobserved categories if self.observed is False.
Returns
--... | [
"@pytest.mark.parametrize(\n \"func, zero_or_nan\",\n [\n (\"all\", np.NaN),\n (\"any\", np.NaN),\n (\"count\", 0),\n (\"first\", np.NaN),\n (\"idxmax\", np.NaN),\n (\"idxmin\", np.NaN),\n (\"last\", np.NaN),\n (\"mad\", np.NaN),\n (\"max\", np.Na... |
13 | class GroupBy(_GroupBy):
).sortlevel()
if self.as_index:
d = {
self.obj._get_axis_name(self.axis): index,
"copy": False,
"fill_value": fill_value,
}
return output.reindex(**d)
# GH 13204 | [
"@pytest.mark.parametrize(\n \"func, zero_or_nan\",\n [\n (\"all\", np.NaN),\n (\"any\", np.NaN),\n (\"count\", 0),\n (\"first\", np.NaN),\n (\"idxmax\", np.NaN),\n (\"idxmin\", np.NaN),\n (\"last\", np.NaN),\n (\"mad\", np.NaN),\n (\"max\", np.Na... |
14 | class GroupBy(_GroupBy):
output = output.drop(labels=list(g_names), axis=1)
# Set a temp index and reindex (possibly expanding)
output = output.set_index(self.grouper.result_index).reindex(
index, copy=False, fill_value=fill_value
)
# Reset in-axis grouper columns
... | [
"@pytest.mark.parametrize(\n \"func, zero_or_nan\",\n [\n (\"all\", np.NaN),\n (\"any\", np.NaN),\n (\"count\", 0),\n (\"first\", np.NaN),\n (\"idxmax\", np.NaN),\n (\"idxmin\", np.NaN),\n (\"last\", np.NaN),\n (\"mad\", np.NaN),\n (\"max\", np.Na... |
15 | def get_response(args, config_dir):
"""Send the request and return a `request.Response`."""
requests_session = get_requests_session()
requests_session.max_redirects = args.max_redirects
if not args.session and not args.session_read_only:
kwargs = get_requests_kwargs(args) | [
"from httpie import ExitStatus\nfrom utils import http, HTTP_OK\n\n def test_max_redirects(self, httpbin):\n r = http('--max-redirects=1', '--follow', httpbin.url + '/redirect/3',\n error_exit_ok=True)\n assert r.exit_status == ExitStatus.ERROR_TOO_MANY_REDIRECTS"
] |
16 | def main(args=sys.argv[1:], env=Environment(), error=None):
error('Too many redirects (--max-redirects=%s).', args.max_redirects)
except Exception as e:
# TODO: Better distinction between expected and unexpected errors.
if traceback:
raise
msg = str(e) | [
"from httpie import ExitStatus\nfrom utils import http, HTTP_OK\n\n def test_max_redirects(self, httpbin):\n r = http('--max-redirects=1', '--follow', httpbin.url + '/redirect/3',\n error_exit_ok=True)\n assert r.exit_status == ExitStatus.ERROR_TOO_MANY_REDIRECTS"
] |
17 | def top_k_categorical_accuracy(y_true, y_pred, k=5):
def sparse_top_k_categorical_accuracy(y_true, y_pred, k=5):
# If the shape of y_true is (num_samples, 1), flatten to (num_samples,)
return K.mean(K.in_top_k(y_pred, K.cast(K.flatten(y_true), 'int32'), k),
axis=-1)
| [
"@pytest.mark.skipif((K.backend() == 'cntk'),\n reason='CNTK backend does not support top_k yet')\n@pytest.mark.parametrize('y_pred, y_true', [\n # Test correctness if the shape of y_true is (num_samples, 1)\n (np.array([[0.3, 0.2, 0.1], [0.1, 0.2, 0.7]]), np.array([[1], [0]])),\n # Test... |
18 | def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False):
if is_object_dtype(dtype):
return tslib.ints_to_pydatetime(arr.view(np.int64))
elif dtype == np.int64:
if isna(arr).any():
raise ValueError("Cannot convert NaT values to integer")
... | [
"from pandas.core.dtypes.cast import astype_nansafe\nfrom pandas.core.dtypes.missing import isna\nimport numpy as np\nimport pytest\n@pytest.mark.parametrize(\"val\", [np.datetime64(\"NaT\"), np.timedelta64(\"NaT\")])\n@pytest.mark.parametrize(\"typ\", [np.int64])\ndef test_astype_nansafe(val, typ):\n arr = np.a... |
19 | def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False):
if is_object_dtype(dtype):
return tslibs.ints_to_pytimedelta(arr.view(np.int64))
elif dtype == np.int64:
if isna(arr).any():
raise ValueError("Cannot convert NaT values to integer")
... | [
"from pandas.core.dtypes.cast import astype_nansafe\nfrom pandas.core.dtypes.missing import isna\nimport numpy as np\nimport pytest\n@pytest.mark.parametrize(\"val\", [np.datetime64(\"NaT\"), np.timedelta64(\"NaT\")])\n@pytest.mark.parametrize(\"typ\", [np.int64])\ndef test_astype_nansafe(val, typ):\n arr = np.a... |
20 | class HiveCommandClient(HiveClient):
if partition is None:
stdout = run_hive_cmd('use {0}; show tables like "{1}";'.format(database, table))
return stdout and table.lower() in stdout
else:
stdout = run_hive_cmd("""use %s; show partitions %s partition
... | [
"@mock.patch(\"luigi.contrib.hive.run_hive_cmd\")\n def test_apacheclient_table_exists(self, run_command):\n run_command.return_value = \"OK\"\n returned = self.apacheclient.table_exists(\"mytable\")\n self.assertFalse(returned)\n\n run_command.return_value = \"OK\\n\" \\\n ... |
21 | https://support.sas.com/techsup/technote/ts140.pdf
"""
from collections import abc
from datetime import datetime
import struct
import warnings
| [
"import os\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\n\nfrom pandas.io.sas.sasreader import read_sas\n\ndef numeric_as_float(data):\n for v in data.columns:\n if data[v].dtype is np.dtype(\"int64\"):\n data[v] = data[v].astype(np.float64)\n\n d... |
22 | class XportReader(abc.Iterator):
if isinstance(filepath_or_buffer, (str, bytes)):
self.filepath_or_buffer = open(filepath_or_buffer, "rb")
else:
# Since xport files include non-text byte sequences, xport files
# should already be opened in binary mode in Python 3.
... | [
"import os\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\n\nfrom pandas.io.sas.sasreader import read_sas\n\ndef numeric_as_float(data):\n for v in data.columns:\n if data[v].dtype is np.dtype(\"int64\"):\n data[v] = data[v].astype(np.float64)\n\nclass... |
23 | class PolarAxes(Axes):
@cbook._delete_parameter("3.3", "args")
@cbook._delete_parameter("3.3", "kwargs")
def draw(self, renderer, *args, **kwargs):
self._unstale_viewLim()
thetamin, thetamax = np.rad2deg(self._realViewLim.intervalx)
if thetamin > thetamax:
thetamin, theta... | [
"@image_comparison(['polar_invertedylim_rorigin.png'], style='default')\ndef test_polar_invertedylim_rorigin():\n fig = plt.figure()\n ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)\n ax.yaxis.set_inverted(True)\n # Set the rlims to inverted (2, 0) without calling set_rlim, to check that\n # vie... |
24 | default: :rc:`scatter.edgecolors`
marker_obj.get_transform())
if not marker_obj.is_filled():
edgecolors = 'face'
if linewidths is None:
linewidths = rcParams['lines.linewidth']
elif np.iterable(linewidths):
linewidths = [
... | [
"@image_comparison(['scatter_marker.png'], remove_text=True)\ndef test_scatter_marker():\n fig, (ax0, ax1, ax2) = plt.subplots(ncols=3)\n ax0.scatter([3, 4, 2, 6], [2, 5, 2, 3],\n c=[(1, 0, 0), 'y', 'b', 'lime'],\n s=[60, 50, 40, 30],\n edgecolors=['k', 'r', 'g', '... |
25 | class Progbar(object):
info = ' - %.0fs' % (now - self.start)
if self.verbose == 1:
if (not force and (now - self.last_update) < self.interval and
(self.target is not None and current < self.target)):
return
prev_total_width = self.total_width | [
"import sys\nimport pytest\nimport numpy as np\nimport marshal\nfrom keras.utils.generic_utils import custom_object_scope\nfrom keras.utils.generic_utils import has_arg\nfrom keras.utils.generic_utils import Progbar\nfrom keras.utils.generic_utils import func_dump\nfrom keras.utils.generic_utils import func_load\nf... |
26 | import pandas.core.indexes.base as ibase
from pandas.core.indexes.base import Index, _index_shared_docs, maybe_extract_name
from pandas.core.indexes.extension import ExtensionIndex, inherit_names
import pandas.core.missing as missing
from pandas.core.ops import get_op_result_name
_index_doc_kwargs = dict(ibase._index_... | [
"@pytest.mark.parametrize(\"n_categories\", [5, 128])\ndef test_categorical_non_unique_monotonic(n_categories):\n # GH 28189\n # With n_categories as 5, we test the int8 case is hit in libjoin,\n # with n_categories as 128 we test the int16 case.\n left_index = CategoricalIndex([0] + list(range(n_catego... |
27 | class CategoricalIndex(ExtensionIndex, accessor.PandasDelegate):
return res
return CategoricalIndex(res, name=self.name)
def _wrap_joined_index(
self, joined: np.ndarray, other: "CategoricalIndex"
) -> "CategoricalIndex":
name = get_op_result_name(self, other)
return... | [
"@pytest.mark.parametrize(\"n_categories\", [5, 128])\ndef test_categorical_non_unique_monotonic(n_categories):\n # GH 28189\n # With n_categories as 5, we test the int8 case is hit in libjoin,\n # with n_categories as 128 we test the int16 case.\n left_index = CategoricalIndex([0] + list(range(n_catego... |
28 | class SparkSubmitTask(luigi.Task):
command = []
if value and isinstance(value, dict):
for prop, value in value.items():
command += [name, '{0}={1}'.format(prop, value)]
return command
def _flag_arg(self, name, value): | [
"@with_config({'spark': {'spark-submit': ss, 'master': 'spark://host:7077', 'conf': 'prop1=val1', 'jars': 'jar1.jar,jar2.jar',\n 'files': 'file1,file2', 'py-files': 'file1.py,file2.py', 'archives': 'archive1'}})\n@patch('luigi.contrib.spark.subprocess.Popen')\ndef test_defaults(self, proc... |
29 | def nonsingular(vmin, vmax, expander=0.001, tiny=1e-15, increasing=True):
vmin, vmax = vmax, vmin
swapped = True
# Expand vmin, vmax to float: if they were integer types, they can wrap
# around in abs (abs(np.int8(-128)) == -128) and vmax - vmin can overflow.
vmin, vmax = map(float, [vmin, ... | [
"import numpy as np\nimport pytest\n\nfrom matplotlib import cm\nimport matplotlib.colors as mcolors\n\nfrom matplotlib import rc_context\nfrom matplotlib.testing.decorators import image_comparison\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import (BoundaryNorm, LogNorm, PowerNorm, Normalize,\n ... |
30 | def _normalize(table, normalize, margins, margins_name="All"):
table = table.fillna(0)
elif margins is True:
# keep index and column of pivoted table
table_index = table.index
table_columns = table.columns
# check if margin name is in (for MI cases) or equal to last
... | [
"from datetime import date, datetime, timedelta\nfrom itertools import product\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n Categorical,\n DataFrame,\n Grouper,\n Index,\n MultiIndex,\n Series,\n concat,\n date_range,\n)\nimport pandas._testing as tm\nf... |
31 | def _normalize(table, normalize, margins, margins_name="All"):
column_margin = column_margin / column_margin.sum()
table = concat([table, column_margin], axis=1)
table = table.fillna(0)
table.columns = table_columns
elif normalize == "index":
index_ma... | [
"@pytest.mark.parametrize(\"method\", [True, False])\ndef test_margin_normalize(self, method):\n # GH 27500\n df = pd.DataFrame(\n {\n \"A\": [\"foo\", \"foo\", \"foo\", \"foo\", \"foo\", \"bar\", \"bar\", \"bar\", \"bar\"],\n \"B\": [\"one\", \"one\", \"one\", \"two\", \"two\", \... |
32 | def _normalize(table, normalize, margins, margins_name="All"):
table = table.append(index_margin)
table = table.fillna(0)
table.index = table_index
table.columns = table_columns
else:
raise ValueError("Not a valid normalize argument")
else:
... | [
"from datetime import date, datetime, timedelta\nfrom itertools import product\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import (\n Categorical,\n DataFrame,\n Grouper,\n Index,\n MultiIndex,\n Series,\n concat,\n date_range,\n)\nimport pandas._testing as tm\nf... |
33 | class Function(object):
# (since the outputs of fetches are never returned).
# This requires us to wrap fetches in `identity` ops.
self.fetches = [tf.identity(x) for x in self.fetches]
# self.session_kwargs is used for _legacy_call
self.session_kwargs = session_kwargs.copy()
... | [
"@pytest.mark.skipif(K.backend() != 'tensorflow',\n reason='Uses the `options` and `run_metadata` arguments.')\ndef test_function_tf_run_options_with_run_metadata(self):\n from tensorflow.core.protobuf import config_pb2\n x_placeholder = K.placeholder(shape=())\n y_placeholder = K.placeh... |
34 | class Function(object):
callable_opts.fetch.append(x.name)
# Handle updates.
callable_opts.target.append(self.updates_op.name)
# Handle run_options.
if self.run_options:
callable_opts.run_options.CopyFrom(self.run_options)
# Create callable.
callab... | [
"@pytest.mark.skipif(K.backend() != 'tensorflow',\n reason='Uses the `options` and `run_metadata` arguments.')\ndef test_function_tf_run_options_with_run_metadata(self):\n from tensorflow.core.protobuf import config_pb2\n x_placeholder = K.placeholder(shape=())\n y_placeholder = K.placeh... |
35 | class Function(object):
feed_symbols,
symbol_vals,
session)
if self.run_metadata:
fetched = self._callable_fn(*array_vals, run_metadata=self.run_metadata)
else:
fetched = self._callabl... | [
"@pytest.mark.skipif(K.backend() != 'tensorflow',\n reason='Uses the `options` and `run_metadata` arguments.')\ndef test_function_tf_run_options_with_run_metadata(self):\n from tensorflow.core.protobuf import config_pb2\n x_placeholder = K.placeholder(shape=())\n y_placeholder = K.placeh... |
36 | class Function(object):
'supported with sparse inputs.')
return self._legacy_call(inputs)
# callable generated by Session._make_callable_from_options accepts
# `run_metadata` keyword argument since TF 1.10
if (self.run_metadata and
... | [
"@pytest.mark.skipif(K.backend() != 'tensorflow',\n reason='Uses the `options` and `run_metadata` arguments.')\ndef test_function_tf_run_options_with_run_metadata(self):\n from tensorflow.core.protobuf import config_pb2\n x_placeholder = K.placeholder(shape=())\n y_placeholder = K.placeh... |
37 | from thefuck.utils import eager
@git_support
def match(command):
return ("fatal: A branch named '" in command.output
and "' already exists." in command.output)
@git_support
@eager
def get_new_command(command):
branch_name = re.findall(
r"fatal: A branch named '(.+)' already exists.", comma... | [
"@pytest.mark.parametrize('script, src_branch_name, branch_name', [\n ('git branch foo', 'foo', 'foo'),\n ('git checkout bar', 'bar', 'bar'),\n ('git checkout -b \"let\\'s-push-this\"', \"let's-push-this\", \"let\\\\'s-push-this\")])\ndef test_get_new_command(output, new_command, script, src_branch_name, b... |
38 | from .generic import Generic
class Bash(Generic):
def app_alias(self, fuck):
# It is VERY important to have the variables declared WITHIN the alias
alias = "alias {0}='TF_CMD=$(TF_ALIAS={0}" \
" PYTHONIOENCODING=utf-8" \
" TF_SHELL_ALIASES=$(alias)" \
... | [
"@pytest.mark.usefixtures('isfile', 'no_memoize', 'no_cache')\nclass TestZsh(object):\n @pytest.fixture\n def shell(self):\n return Zsh()\n\n @pytest.fixture(autouse=True)\n def shell_aliases(self):\n os.environ['TF_SHELL_ALIASES'] = (\n 'fuck=\\'eval $(thefuck $(fc -ln -1 | tai... |
39 | class Fish(Generic):
return ['cd', 'grep', 'ls', 'man', 'open']
def app_alias(self, fuck):
# It is VERY important to have the variables declared WITHIN the alias
return ('function {0} -d "Correct your previous console command"\n'
' set -l fucked_up_command $history[1]\n... | [
"@pytest.mark.usefixtures('isfile', 'no_memoize', 'no_cache')\nclass TestZsh(object):\n @pytest.fixture\n def shell(self):\n return Zsh()\n\n @pytest.fixture(autouse=True)\n def shell_aliases(self):\n os.environ['TF_SHELL_ALIASES'] = (\n 'fuck=\\'eval $(thefuck $(fc -ln -1 | tai... |
40 | from .generic import Generic
class Zsh(Generic):
def app_alias(self, alias_name):
# It is VERY important to have the variables declared WITHIN the alias
alias = "alias {0}='TF_CMD=$(TF_ALIAS={0}" \
" PYTHONIOENCODING=utf-8" \
" TF_SHELL_ALIASES=$(alias)" \
... | [
"@pytest.mark.usefixtures('isfile', 'no_memoize', 'no_cache')\nclass TestZsh(object):\n @pytest.fixture\n def shell(self):\n return Zsh()\n\n @pytest.fixture(autouse=True)\n def shell_aliases(self):\n os.environ['TF_SHELL_ALIASES'] = (\n 'fuck=\\'eval $(thefuck $(fc -ln -1 | tai... |
41 | class CorrectedCommand(object):
compatibility_call(self.side_effect, old_cmd, self.script)
# This depends on correct setting of PYTHONIOENCODING by the alias:
logs.debug(u'PYTHONIOENCODING: {}'.format(
os.environ.get('PYTHONIOENCODING', '!!not-set!!')))
print(self.script) | [
"@pytest.mark.usefixtures('isfile', 'no_memoize', 'no_cache')\nclass TestZsh(object):\n @pytest.fixture\n def shell(self):\n return Zsh()\n\n @pytest.fixture(autouse=True)\n def shell_aliases(self):\n os.environ['TF_SHELL_ALIASES'] = (\n 'fuck=\\'eval $(thefuck $(fc -ln -1 | tai... |
42 | b 2""",
# datetime64tz is handled correctly in agg_series,
# so is excluded here.
if len(result) and isinstance(result[0], dtype.type):
cls = dtype.construct_array_type()
result = try_cast_to_ea(cls, result, dtype=dtype)
... | [
"@pytest.mark.parametrize(\n \"func, expected_values\",\n [(pd.Series.nunique, [1, 1, 2]), (pd.Series.count, [1, 2, 2])],\n)\ndef test_groupby_agg_categorical_columns(func, expected_values):\n # 31256\n df = pd.DataFrame(\n {\n \"id\": [0, 1, 2, 3, 4],\n \"groups\": [0, 1, 1... |
43 | class BaseGrouper:
if mask.any():
result = result.astype("float64")
result[mask] = np.nan
elif (
how == "add"
and is_integer_dtype(orig_values.dtype)
and is_extension_array_dtype(orig_values.dtype)
):
# We need t... | [
"@pytest.mark.parametrize(\n \"func, expected_values\",\n [(pd.Series.nunique, [1, 1, 2]), (pd.Series.count, [1, 2, 2])],\n)\ndef test_groupby_agg_categorical_columns(func, expected_values):\n # 31256\n df = pd.DataFrame(\n {\n \"id\": [0, 1, 2, 3, 4],\n \"groups\": [0, 1, 1... |
44 | def test_aggregate_mixed_types():
tm.assert_frame_equal(result, expected)
@pytest.mark.xfail(reason="Not implemented.")
def test_aggregate_udf_na_extension_type():
# https://github.com/pandas-dev/pandas/pull/31359
# This is currently failing to cast back to Int64Dtype.
# The presence of the NA causes ... | [
"@pytest.mark.parametrize(\n \"func, expected_values\",\n [(pd.Series.nunique, [1, 1, 2]), (pd.Series.count, [1, 2, 2])],\n)\ndef test_groupby_agg_categorical_columns(func, expected_values):\n # 31256\n df = pd.DataFrame(\n {\n \"id\": [0, 1, 2, 3, 4],\n \"groups\": [0, 1, 1... |
45 | def test_resample_integerarray():
result = ts.resample("3T").mean()
expected = Series(
[1, 4, 7],
index=pd.date_range("1/1/2000", periods=3, freq="3T"),
dtype="float64",
)
tm.assert_series_equal(result, expected)
| [
"@pytest.mark.parametrize(\n \"func, expected_values\",\n [(pd.Series.nunique, [1, 1, 2]), (pd.Series.count, [1, 2, 2])],\n)\ndef test_groupby_agg_categorical_columns(func, expected_values):\n # 31256\n df = pd.DataFrame(\n {\n \"id\": [0, 1, 2, 3, 4],\n \"groups\": [0, 1, 1... |
46 | def test_resample_categorical_data_with_timedeltaindex():
index=pd.to_timedelta([0, 10], unit="s"),
)
expected = expected.reindex(["Group_obj", "Group"], axis=1)
expected["Group"] = expected["Group_obj"]
tm.assert_frame_equal(result, expected)
| [
"@pytest.mark.parametrize(\n \"func, expected_values\",\n [(pd.Series.nunique, [1, 1, 2]), (pd.Series.count, [1, 2, 2])],\n)\ndef test_groupby_agg_categorical_columns(func, expected_values):\n # 31256\n df = pd.DataFrame(\n {\n \"id\": [0, 1, 2, 3, 4],\n \"groups\": [0, 1, 1... |
47 | from ansible.galaxy.role import GalaxyRole
from ansible.galaxy.token import BasicAuthToken, GalaxyToken, KeycloakToken, NoTokenSentinel
from ansible.module_utils.ansible_release import __version__ as ansible_version
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.module_utils import six... | [
"def test_collection_install_with_url(collection_install):\n mock_install, dummy, output_dir = collection_install\n\n galaxy_args = ['ansible-galaxy', 'collection', 'install', 'https://foo/bar/foo-bar-v1.0.0.tar.gz',\n '--collections-path', output_dir]\n GalaxyCLI(args=galaxy_args).run()\... |
48 | class GalaxyCLI(CLI):
else:
requirements = []
for collection_input in collections:
requirement = None
if os.path.isfile(to_bytes(collection_input, errors='surrogate_or_strict')) or \
urlparse(collection_input... | [
"def test_collection_install_with_url(collection_install):\n mock_install, dummy, output_dir = collection_install\n\n galaxy_args = ['ansible-galaxy', 'collection', 'install', 'https://foo/bar/foo-bar-v1.0.0.tar.gz',\n '--collections-path', output_dir]\n GalaxyCLI(args=galaxy_args).run()\... |
49 | def _get_collection_info(dep_map, existing_collections, collection, requirement,
if os.path.isfile(to_bytes(collection, errors='surrogate_or_strict')):
display.vvvv("Collection requirement '%s' is a tar artifact" % to_text(collection))
b_tar_path = to_bytes(collection, errors='surrogate_or_strict')
... | [
"def test_collection_install_with_url(collection_install):\n mock_install, dummy, output_dir = collection_install\n\n galaxy_args = ['ansible-galaxy', 'collection', 'install', 'https://foo/bar/foo-bar-v1.0.0.tar.gz',\n '--collections-path', output_dir]\n GalaxyCLI(args=galaxy_args).run()\... |
50 | def _isna_old(obj):
raise NotImplementedError("isna is not defined for MultiIndex")
elif isinstance(obj, type):
return False
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)):
return _isna_ndarraylike_old(obj)
elif isinstance(obj, ABCGeneric):
re... | [
"Looking at the provided Python test file, I need to locate the test function named `test_count`. However, after carefully reviewing the entire file content, I can see that there is no function named `test_count` in this file. The file contains a class `TestSeriesAnalytics` with several test methods, but none of th... |
51 | default 'raise'
DatetimeIndex(['2018-03-01 09:00:00-05:00',
'2018-03-02 09:00:00-05:00',
'2018-03-03 09:00:00-05:00'],
dtype='datetime64[ns, US/Eastern]', freq=None)
With the ``tz=None``, we can remove the time zone information
... | [
"from datetime import date, datetime, time, timedelta, tzinfo\n\nimport dateutil\nfrom dateutil.tz import gettz, tzlocal\nimport numpy as np\nimport pytest\nimport pytz\n\nfrom pandas._libs.tslibs import conversion, timezones\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import (\n ... |
52 | default 'raise'
>>> tz_aware.tz_localize(None)
DatetimeIndex(['2018-03-01 09:00:00', '2018-03-02 09:00:00',
'2018-03-03 09:00:00'],
dtype='datetime64[ns]', freq=None)
Be careful with DST changes. When there is sequential data, pandas can
infe... | [
"from datetime import date, datetime, time, timedelta, tzinfo\n\nimport dateutil\nfrom dateutil.tz import gettz, tzlocal\nimport numpy as np\nimport pytest\nimport pytz\n\nfrom pandas._libs.tslibs import conversion, timezones\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import (\n ... |
53 | default 'raise'
)
new_dates = new_dates.view(DT64NS_DTYPE)
dtype = tz_to_dtype(tz)
freq = None
if timezones.is_utc(tz) or (len(self) == 1 and not isna(new_dates[0])):
# we can preserve freq
# TODO: Also for fixed-offsets
freq = self.freq
... | [
"from datetime import date, datetime, time, timedelta, tzinfo\n\nimport dateutil\nfrom dateutil.tz import gettz, tzlocal\nimport numpy as np\nimport pytest\nimport pytz\n\nfrom pandas._libs.tslibs import conversion, timezones\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import (\n ... |
54 | class TestSeriesComparison:
# datetime64tz dtype
dti = dti.tz_localize("US/Central")
dti._set_freq("infer") # freq not preserved by tz_localize
ser = Series(dti).rename(names[1])
result = op(ser, dti)
assert result.name == names[2] | [
"from datetime import date, datetime, time, timedelta, tzinfo\n\nimport dateutil\nfrom dateutil.tz import gettz, tzlocal\nimport numpy as np\nimport pytest\nimport pytz\n\nfrom pandas._libs.tslibs import conversion, timezones\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import (\n ... |
55 | class Sequential(Model):
first_layer = layer.layers[0]
while isinstance(first_layer, (Model, Sequential)):
first_layer = first_layer.layers[0]
if hasattr(first_layer, 'batch_input_shape'):
batch_shape = first_layer.batc... | [
"def test_nested_sequential_deferred_build():\n inner_model = keras.models.Sequential()\n inner_model.add(keras.layers.Dense(3))\n inner_model.add(keras.layers.Dense(3))\n\n model = keras.models.Sequential()\n model.add(inner_model)\n model.add(keras.layers.Dense(5))\n model.compile('sgd', 'mse... |
56 | def read_conllx(input_data, use_morphology=False, n=0):
continue
try:
id_ = int(id_) - 1
head = (int(head) - 1) if head not in ["0", "_"] else id_
dep = "ROOT" if dep == "root" else dep
tag = pos if tag =... | [
"from spacy.cli.converters.conllu2json import conllu2json\n\ninput_data = \"\"\"\n1\t[\t_\tPUNCT\t-LRB-\t_\t_\tpunct\t_\t_\n2\tThis\t_\tDET\tDT\t_\t_\tdet\t_\t_\n3\tkilling\t_\tNOUN\tNN\t_\t_\tnsubj\t_\t_\n4\tof\t_\tADP\tIN\t_\t_\tcase\t_\t_\n5\ta\t_\tDET\tDT\t_\t_\tdet\t_\t_\n6\trespected\t_\tADJ\tJJ\t_\t_\tamod\t... |
57 | from pandas.core.internals.construction import (
sanitize_index,
to_arrays,
)
from pandas.core.ops.missing import dispatch_fill_zeros
from pandas.core.series import Series
from pandas.io.formats import console, format as fmt | [
"def adjust_negative_zero(zero, expected):\n \"\"\"\n Helper to adjust the expected result if we are dividing by -0.0\n as opposed to 0.0\n \"\"\"\n if np.signbit(np.array(zero)).any():\n # All entries in the `zero` fixture should be either\n # all-negative or no-negative.\n ass... |
58 | class DataFrame(NDFrame):
# iterate over columns
return ops.dispatch_to_series(this, other, _arith_op)
else:
with np.errstate(all="ignore"):
result = _arith_op(this.values, other.values)
result = dispatch_fill_zeros(func, this.values, other.values,... | [
"def adjust_negative_zero(zero, expected):\n \"\"\"\n Helper to adjust the expected result if we are dividing by -0.0\n as opposed to 0.0\n \"\"\"\n if np.signbit(np.array(zero)).any():\n # All entries in the `zero` fixture should be either\n # all-negative or no-negative.\n ass... |
59 | class TimedeltaIndex(
this, other = self, other
if this._can_fast_union(other):
return this._fast_union(other, sort=sort)
else:
result = Index._union(this, other, sort=sort)
if isinstance(result, TimedeltaIndex): | [
"import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import Int64Index, TimedeltaIndex, timedelta_range\nimport pandas._testing as tm\n\nfrom pandas.tseries.offsets import Hour\n\n def test_union_sort_false(self):\n tdi = timedelta_range(\"1day\", periods=5)\n\n left = tdi[3:]\n ... |
60 | class TimedeltaIndex(
result._set_freq("infer")
return result
def _fast_union(self, other, sort=None):
if len(other) == 0:
return self.view(type(self))
| [
"import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import Int64Index, TimedeltaIndex, timedelta_range\nimport pandas._testing as tm\n\nfrom pandas.tseries.offsets import Hour\n\n def test_union_sort_false(self):\n tdi = timedelta_range(\"1day\", periods=5)\n\n left = tdi[3:]\n ... |
61 | class TimedeltaIndex(
# to make our life easier, "sort" the two ranges
if self[0] <= other[0]:
left, right = self, other
elif sort is False:
# TDIs are not in the "correct" order and we don't want
# to sort but want to remove overlaps
left, right ... | [
"import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import Int64Index, TimedeltaIndex, timedelta_range\nimport pandas._testing as tm\n\nfrom pandas.tseries.offsets import Hour\n\n def test_union_sort_false(self):\n tdi = timedelta_range(\"1day\", periods=5)\n\n left = tdi[3:]\n ... |
62 | from pandas.core.dtypes.common import (
is_dtype_equal,
is_extension_array_dtype,
is_float_dtype,
is_integer,
is_integer_dtype,
is_list_like, | [
"import datetime\n\nimport numpy as np\nimport pytest\nimport pytz\n\nimport pandas as pd\nfrom pandas import Timedelta, merge_asof, read_csv, to_datetime\nimport pandas._testing as tm\nfrom pandas.core.reshape.merge import MergeError\n\n def test_int_type_tolerance(self, any_int_dtype):\n # GH #28870\n\n... |
63 | class _AsOfMerge(_OrderedMerge):
if self.tolerance < Timedelta(0):
raise MergeError("tolerance must be positive")
elif is_integer_dtype(lt):
if not is_integer(self.tolerance):
raise MergeError(msg)
if self.tolerance < 0... | [
"import datetime\n\nimport numpy as np\nimport pytest\nimport pytz\n\nimport pandas as pd\nfrom pandas import Timedelta, merge_asof, read_csv, to_datetime\nimport pandas._testing as tm\nfrom pandas.core.reshape.merge import MergeError\n\n def test_int_type_tolerance(self, any_int_dtype):\n # GH #28870\n\n... |
64 | def weighted_masked_objective(fn):
score_array *= mask
# the loss per batch should be proportional
# to the number of unmasked samples.
score_array /= K.mean(mask) + K.epsilon()
# apply sample weighting
if weights is not None: | [
"import numpy as np\nimport pytest\n\nfrom keras.models import Sequential\nfrom keras.engine.training_utils import weighted_masked_objective\nfrom keras.layers import TimeDistributed, Masking, Dense\nfrom keras import losses\nfrom keras import backend as K\n\n\ndef test_masking_is_all_zeros():\n x = np.array([[[... |
65 | class _ScalarAccessIndexer(_NDFrameIndexerBase):
if not isinstance(key, tuple):
key = _tuplify(self.ndim, key)
key = list(self._convert_key(key, is_setter=True))
if len(key) != self.ndim:
raise ValueError("Not enough indexers for scalar access (setting)!")
self.... | [
"@pytest.mark.parametrize(\"kind\", [\"series\", \"frame\"])\ndef test_multiindex_at_set(self, kind):\n def _check(f, func, values=False):\n\n if f is not None:\n indices = self.generate_indices(f, values)\n for i in indices:\n getattr(f, func)[i] = 1\n ... |
66 | class _AtIndexer(_ScalarAccessIndexer):
Require they keys to be the same type as the index. (so we don't
fallback)
"""
# GH 26989
# For series, unpacking key needs to result in the label.
# This is already the case for len(key) == 1; e.g. (1,)
if self.ndim == 1 an... | [
"@pytest.mark.parametrize(\"kind\", [\"series\", \"frame\"])\ndef test_multiindex_at_set(self, kind):\n def _check(f, func, values=False):\n\n if f is not None:\n indices = self.generate_indices(f, values)\n for i in indices:\n getattr(f, func)[i] = 1\n ... |
67 | def _make_ghost_gridspec_slots(fig, gs):
# this gridspec slot doesn't have an axis so we
# make a "ghost".
ax = fig.add_subplot(gs[nn])
ax.set_visible(False)
def _make_layout_margins(ax, renderer, h_pad, w_pad): | [
"def test_invisible_axes():\n # invisible axes should not respond to events...\n fig, ax = plt.subplots()\n assert fig.canvas.inaxes((200, 200)) is not None\n ax.set_visible(False)\n assert fig.canvas.inaxes((200, 200)) is None"
] |
68 | class FigureCanvasBase:
def inaxes(self, xy):
"""
Return the topmost visible `~.axes.Axes` containing the point *xy*.
Parameters
---------- | [
"def test_invisible_axes():\n # invisible axes should not respond to events...\n fig, ax = plt.subplots()\n assert fig.canvas.inaxes((200, 200)) is not None\n ax.set_visible(False)\n assert fig.canvas.inaxes((200, 200)) is None"
] |
69 | class FigureCanvasBase:
Returns
-------
axes : `~matplotlib.axes.Axes` or None
The topmost visible axes containing the point, or None if no axes.
"""
axes_list = [a for a in self.figure.get_axes()
if a.patch.contains_point(xy) and a.get_visible()... | [
"def test_invisible_axes():\n # invisible axes should not respond to events...\n fig, ax = plt.subplots()\n assert fig.canvas.inaxes((200, 200)) is not None\n ax.set_visible(False)\n assert fig.canvas.inaxes((200, 200)) is None"
] |
70 | class Rolling(_Rolling_and_Expanding):
def _on(self):
if self.on is None:
if self.axis == 0:
return self.obj.index
elif self.axis == 1:
return self.obj.columns
elif isinstance(self.obj, ABCDataFrame) and self.on in self.obj.columns:
... | [
"@pytest.mark.parametrize(\"window\", [timedelta(days=3), pd.Timedelta(days=3)])\ndef test_rolling_datetime(self, axis_frame, tz_naive_fixture):\n # GH-28192\n tz = tz_naive_fixture\n df = pd.DataFrame(\n {\n i: [1] * 2\n for i in pd.date_range(\"2019-8-01\", \"2019-08-03\", fr... |
71 | class LocalFileSystem(FileSystem):
raise RuntimeError('Destination exists: %s' % new_path)
d = os.path.dirname(new_path)
if d and not os.path.exists(d):
self.mkdir(d)
os.rename(old_path, new_path)
| [
"from __future__ import print_function\n\nimport os\nimport random\nimport shutil\nfrom helpers import unittest\n\nimport luigi.format\nfrom luigi import LocalTarget\nfrom luigi.file import LocalFileSystem\n\nclass LocalTargetTest(unittest.TestCase, FileSystemTargetTestMixin):\n path = '/tmp/test.txt'\n copy ... |
72 | class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
new_index = self.index[loc]
if is_scalar(loc):
# In this case loc should be an integer
if self.ndim == 1:
# if we encounter an array-like and we only have 1 dim
# that me... | [
"import numpy as np\n\nimport pandas as pd\n\n\ndef test_xs_datetimelike_wrapping():\n # GH#31630 a case where we shouldn't wrap datetime64 in Timestamp\n arr = pd.date_range(\"2016-01-01\", periods=3)._data._data\n\n ser = pd.Series(arr, dtype=object)\n for i in range(len(ser)):\n ser.iloc[i] = ... |
73 | class SingleBlockManager(BlockManager):
fast path for getting a cross-section
return a view of the data
"""
raise NotImplementedError("Use series._values[loc] instead")
def concat(self, to_concat, new_axis) -> "SingleBlockManager":
""" | [
"import numpy as np\n\nimport pandas as pd\n\n\ndef test_xs_datetimelike_wrapping():\n # GH#31630 a case where we shouldn't wrap datetime64 in Timestamp\n arr = pd.date_range(\"2016-01-01\", periods=3)._data._data\n\n ser = pd.Series(arr, dtype=object)\n for i in range(len(ser)):\n ser.iloc[i] = ... |
74 | class RNN(Layer):
input_shape = input_shape[0]
if hasattr(self.cell.state_size, '__len__'):
state_size = self.cell.state_size
else:
state_size = [self.cell.state_size]
output_dim = state_size[0]
if self.return_sequences:
output_shape = (i... | [
"def test_stacked_rnn_compute_output_shape():\n cells = [recurrent.LSTMCell(3),\n recurrent.LSTMCell(6)]\n layer = recurrent.RNN(cells, return_state=True, return_sequences=True)\n output_shape = layer.compute_output_shape((None, timesteps, embedding_dim))\n expected_output_shape = [(None, ti... |
75 | class RNN(Layer):
output_shape = (input_shape[0], output_dim)
if self.return_state:
state_shape = [(input_shape[0], dim) for dim in state_size]
return [output_shape] + state_shape
else:
return output_shape | [
"def test_stacked_rnn_compute_output_shape():\n cells = [recurrent.LSTMCell(3),\n recurrent.LSTMCell(6)]\n layer = recurrent.RNN(cells, return_state=True, return_sequences=True)\n output_shape = layer.compute_output_shape((None, timesteps, embedding_dim))\n expected_output_shape = [(None, ti... |
76 | class Errors(object):
"details: https://spacy.io/api/lemmatizer#init")
E174 = ("Architecture '{name}' not found in registry. Available "
"names: {names}")
E175 = ("Can't remove rule for unknown match pattern ID: {key}")
@add_codes | [
"@pytest.mark.xfail\n@pytest.mark.parametrize(\n \"pattern,re_pattern\",\n [\n (pattern1, re_pattern1),\n (pattern2, re_pattern2),\n (pattern3, re_pattern3),\n (pattern4, re_pattern4),\n (pattern5, re_pattern5),\n ],\n)\ndef test_matcher_remove():\n nlp = English()\n ... |
77 | class CollectionRequirement:
requirement = req
op = operator.eq
# In the case we are checking a new requirement on a base requirement (parent != None) we can't accept
# version as '*' (unknown version) unless the requirement is also '*'.
if parent and... | [
"def test_add_collection_requirement_to_unknown_installed_version():\n req = collection.CollectionRequirement('namespace', 'name', None, 'https://galaxy.com', ['*'], '*', False,\n skip=True)\n\n expected = \"Cannot meet requirement namespace.name:1.0.0 as it is alread... |
78 | class CollectionRequirement:
manifest = info['manifest_file']['collection_info']
namespace = manifest['namespace']
name = manifest['name']
version = to_text(manifest['version'], errors='surrogate_or_strict')
if not hasattr(LooseVersion(version), 'version'):
... | [
"def test_add_collection_requirement_to_unknown_installed_version():\n req = collection.CollectionRequirement('namespace', 'name', None, 'https://galaxy.com', ['*'], '*', False,\n skip=True)\n\n expected = \"Cannot meet requirement namespace.name:1.0.0 as it is alread... |
79 | def _get_collection_info(dep_map, existing_collections, collection, requirement,
existing = [c for c in existing_collections if to_text(c) == to_text(collection_info)]
if existing and not collection_info.force:
# Test that the installed collection fits the requirement
existing[0].add_requirement... | [
"def test_add_collection_requirement_to_unknown_installed_version():\n req = collection.CollectionRequirement('namespace', 'name', None, 'https://galaxy.com', ['*'], '*', False,\n skip=True)\n\n expected = \"Cannot meet requirement namespace.name:1.0.0 as it is alread... |
80 | class DataFrame(NDFrame):
for k1, k2 in zip(key, value.columns):
self[k1] = value[k2]
else:
self.loc._ensure_listlike_indexer(key, axis=1)
indexer = self.loc._get_listlike_indexer(
key, axis=1, raise_missing=False
... | [
"@pytest.mark.parametrize(\n \"index,box,expected\",\n [\n (\n ([0, 2], [\"A\", \"B\", \"C\", \"D\"]),\n 7,\n pd.DataFrame(\n [[7, 7, 7, 7], [3, 4, np.nan, np.nan], [7, 7, 7, 7]],\n columns=[\"A\", \"B\", \"C\", \"D\"],\n ),\n ... |
81 | from pandas.errors import AbstractMethodError
from pandas.util._decorators import Appender
from pandas.core.dtypes.common import (
is_hashable,
is_integer,
is_iterator,
is_list_like, | [
"@pytest.mark.parametrize(\n \"index,box,expected\",\n [\n (\n ([0, 2], [\"A\", \"B\", \"C\", \"D\"]),\n 7,\n pd.DataFrame(\n [[7, 7, 7, 7], [3, 4, np.nan, np.nan], [7, 7, 7, 7]],\n columns=[\"A\", \"B\", \"C\", \"D\"],\n ),\n ... |
82 | class _LocationIndexer(_NDFrameIndexerBase):
"""
Convert a potentially-label-based key into a positional indexer.
"""
if self.name == "loc":
self._ensure_listlike_indexer(key)
if self.axis is not None:
return self._convert_tuple(key, is_setter=True)
| [
"@pytest.mark.parametrize(\n \"index,box,expected\",\n [\n (\n ([0, 2], [\"A\", \"B\", \"C\", \"D\"]),\n 7,\n pd.DataFrame(\n [[7, 7, 7, 7], [3, 4, np.nan, np.nan], [7, 7, 7, 7]],\n columns=[\"A\", \"B\", \"C\", \"D\"],\n ),\n ... |
83 | class _LocationIndexer(_NDFrameIndexerBase):
raise
raise IndexingError(key) from e
def _ensure_listlike_indexer(self, key, axis=None):
"""
Ensure that a list-like of column labels are all present by adding them if
they do not already exist.
Parameters
... | [
"@pytest.mark.parametrize(\n \"index,box,expected\",\n [\n (\n ([0, 2], [\"A\", \"B\", \"C\", \"D\"]),\n 7,\n pd.DataFrame(\n [[7, 7, 7, 7], [3, 4, np.nan, np.nan], [7, 7, 7, 7]],\n columns=[\"A\", \"B\", \"C\", \"D\"],\n ),\n ... |
84 | from thefuck.specific.git import git_support
@git_support
def match(command):
splited_script = command.script.split()
if len(splited_script) > 1:
return (splited_script[1] == 'stash'
and 'usage:' in command.stderr)
else:
return False
# git's output here is too complicated t... | [
"import pytest\nfrom thefuck.rules.git_fix_stash import match, get_new_command\nfrom thefuck.types import Command\n\n\ngit_stash_err = '''\nusage: git stash list [<options>]\n or: git stash show [<stash>]\n or: git stash drop [-q|--quiet] [<stash>]\n or: git stash ( pop | apply ) [--index] [-q|--quiet] [<stas... |
85 | except ImportError:
from ordereddict import OrderedDict
from luigi import six
import logging
logger = logging.getLogger('luigi-interface')
class TaskClassException(Exception): | [
"from helpers import unittest\n\nimport luigi\nimport luigi.worker\nimport luigi.date_interval\nimport luigi.notifications\n\nluigi.notifications.DEBUG = True\n\n def test_unhashable_type(self):\n # See #857\n class DummyTask(luigi.Task):\n x = luigi.Parameter()\n\n dummy = DummyT... |
86 | class StringMethods(NoNewAttributesMixin):
if isinstance(others, ABCSeries):
return [others]
elif isinstance(others, ABCIndexClass):
return [Series(others._values, index=idx)]
elif isinstance(others, ABCDataFrame):
return [others[x] for x in others]
el... | [
"@pytest.mark.parametrize(\"klass\", [tuple, list, np.array, pd.Series, pd.Index])\ndef test_cat_different_classes(klass):\n # https://github.com/pandas-dev/pandas/issues/33425\n s = pd.Series([\"a\", \"b\", \"c\"])\n result = s.str.cat(klass([\"x\", \"y\", \"z\"]))\n expected = pd.Series([\"ax\", \"by\... |
87 | import numpy as np
import time
import json
import warnings
import io
import sys
from collections import deque
from collections import OrderedDict | [
"import os\nimport multiprocessing\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_allclose\nfrom csv import reader\nfrom csv import Sniffer\nimport shutil\nfrom keras import optimizers\nfrom keras import initializers\nfrom keras import callbacks\nfrom keras.models import Sequential, Model\nf... |
88 | class CSVLogger(Callback):
self.writer = None
self.keys = None
self.append_header = True
if six.PY2:
self.file_flags = 'b'
self._open_args = {}
else:
self.file_flags = ''
self._open_args = {'newline': '\n'}
super(CSVLogger, ... | [
"import os\nimport multiprocessing\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_allclose\nfrom csv import reader\nfrom csv import Sniffer\nimport shutil\nfrom keras import optimizers\nfrom keras import initializers\nfrom keras import callbacks\nfrom keras.models import Sequential, Model\nf... |
89 | class CSVLogger(Callback):
if os.path.exists(self.filename):
with open(self.filename, 'r' + self.file_flags) as f:
self.append_header = not bool(len(f.readline()))
mode = 'a'
else:
mode = 'w'
self.csv_file = io.open(self.filename,
... | [
"import os\nimport multiprocessing\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_allclose\nfrom csv import reader\nfrom csv import Sniffer\nimport shutil\nfrom keras import optimizers\nfrom keras import initializers\nfrom keras import callbacks\nfrom keras.models import Sequential, Model\nf... |
90 | class CSVLogger(Callback):
if not self.writer:
class CustomDialect(csv.excel):
delimiter = self.sep
fieldnames = ['epoch'] + self.keys
if six.PY2:
fieldnames = [unicode(x) for x in fieldnames]
self.writer = csv.DictWriter(self.csv_f... | [
"import os\nimport multiprocessing\n\nimport numpy as np\nimport pytest\nfrom numpy.testing import assert_allclose\nfrom csv import reader\nfrom csv import Sniffer\nimport shutil\nfrom keras import optimizers\nfrom keras import initializers\nfrom keras import callbacks\nfrom keras.models import Sequential, Model\nf... |
91 | class Session(BaseConfigDict):
"""
for name, value in request_headers.items():
if value is None:
continue # Ignore explicitely unset headers
value = value.decode('utf8')
if name == 'User-Agent' and value.startswith('HTTPie/'):
conti... | [
"import os\nimport shutil\nfrom tempfile import gettempdir\n\nimport pytest\n\nfrom utils import TestEnvironment, mk_config_dir, http, HTTP_OK\nfrom fixtures import UNICODE\n\nclass SessionTestBase(object):\n\n def start_session(self, httpbin):\n \"\"\"Create and reuse a unique config dir for each test.\"... |
92 | class APIRouter(routing.Router):
include_in_schema=route.include_in_schema,
name=route.name,
)
elif isinstance(route, routing.WebSocketRoute):
self.add_websocket_route(
prefix + route.path, route.endpoint, name=route... | [
"from fastapi import APIRouter, FastAPI\nfrom starlette.testclient import TestClient\nfrom starlette.websockets import WebSocket\n\nrouter = APIRouter()\nprefix_router = APIRouter()\napp = FastAPI()\n\n@prefix_router.websocket_route(\"/\")\nasync def routerprefixindex(websocket: WebSocket):\n await websocket.acc... |
93 | from pandas.core.dtypes.cast import (
validate_numeric_casting,
)
from pandas.core.dtypes.common import (
ensure_int64,
ensure_platform_int,
infer_dtype_from_object, | [
"import warnings\n\nimport numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import DataFrame, Series, isna\nimport pandas._testing as tm\n\n\n def test_cov_nullable_integer(self, nullable_frame, using_infer_string):\n # GH 46240\n df = null... |
94 | Wild 185.0
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.astype(float, copy=False).to_numpy()
if method == "pearson":
correl = libalgos.nancorr(mat, minp=min_periods)
elif method == "spearman":
... | [
"import warnings\n\nimport numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import DataFrame, Series, isna\nimport pandas._testing as tm\n\n\n def test_cov_nullable_integer(self, nullable_int_dtype):\n # if we have a nullable integer dtype, we may... |
95 | Wild 185.0
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
mat = numeric_df.astype(float, copy=False).to_numpy()
if notna(mat).all():
if min_periods is not None and min_periods > len(mat):
base_cov = np.empty(... | [
"import warnings\n\nimport numpy as np\nimport pytest\n\nimport pandas.util._test_decorators as td\n\nimport pandas as pd\nfrom pandas import DataFrame, Series, isna\nimport pandas._testing as tm\n\n\n def test_cov_nullable_integer(self, nullable_int_dtype):\n # if we have a nullable integer dtype, we may... |
96 | class BaseMaskedArray(ExtensionArray, ExtensionOpsMixin):
def __len__(self) -> int:
return len(self._data)
def __invert__(self):
return type(self)(~self._data, self._mask)
def to_numpy(
self, dtype=None, copy=False, na_value: "Scalar" = lib.no_default,
): | [
"import operator\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core import ops\nfrom pandas.core.arrays.sparse import SparseArray, SparseDtype\n\n@pytest.mark.parametrize(\"fill_value\", [True, False])\ndef test_invert(fill_value):\n arr = np.array([True, ... |
97 | class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
# inv fails with 0 len
return self
new_data = self._data.apply(operator.invert)
result = self._constructor(new_data).__finalize__(self)
return result
def __nonzero__(self):
raise ValueError... | [
"import operator\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core import ops\nfrom pandas.core.arrays.sparse import SparseArray, SparseDtype\n\n@pytest.mark.parametrize(\"fill_value\", [True, False])\ndef test_invert(fill_value):\n arr = np.array([True, ... |
98 | def check_bool_indexer(index: Index, key) -> np.ndarray:
result = result.astype(bool)._values
else:
if is_sparse(result):
result = np.asarray(result)
result = check_bool_array_indexer(index, result)
return result | [
"import operator\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core import ops\nfrom pandas.core.arrays.sparse import SparseArray, SparseDtype\n\n@pytest.mark.parametrize(\"fill_value\", [True, False])\ndef test_invert(fill_value):\n arr = np.array([True, ... |
99 | """
This file contains a minimal set of tests for compliance with the extension
array interface test suite, and should contain no other tests.
The test suite for the full functionality of the array is located in
`pandas/tests/arrays/`.
The tests in this file are inherited from the BaseExtensionTests, and only
minimal ... | [
"import operator\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\nfrom pandas.core import ops\nfrom pandas.core.arrays.sparse import SparseArray, SparseDtype\n\n@pytest.mark.parametrize(\"fill_value\", [True, False])\ndef test_invert(fill_value):\n arr = np.array([True, ... |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 3