language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | mlflow__mlflow | mlflow/types/responses_helpers.py | {
"start": 2187,
"end": 2272
} | class ____(BaseModel):
refusal: str
type: str = "refusal"
| ResponseOutputRefusal |
python | coleifer__peewee | peewee.py | {
"start": 154771,
"end": 155220
} | class ____(object):
def __init__(self, field):
self.field = field
self.model = field.rel_model
self.rel_model = field.model
def __get__(self, instance, instance_type=None):
if instance is not None:
dest = self.field.rel_field.name
return (self.rel_model
... | BackrefAccessor |
python | gevent__gevent | src/greentest/3.10/test_ftplib.py | {
"start": 32163,
"end": 33791
} | class ____(TestCase):
def setUp(self):
self.server = DummyFTPServer((HOSTv6, 0),
af=socket.AF_INET6,
encoding=DEFAULT_ENCODING)
self.server.start()
self.client = ftplib.FTP(timeout=TIMEOUT, encoding=DEFAULT_ENCODING)
... | TestIPv6Environment |
python | keras-team__keras | keras/src/layers/layer.py | {
"start": 71405,
"end": 77857
} | class ____:
def __init__(self, signature, call_context_args, args, kwargs):
# Strip out user-supplied call-context args that this layer’s `call()`
# does not accept (otherwise `signature.bind` would raise).
# This includes built-in args like `training`, and user-defined args.
call_ar... | CallSpec |
python | scipy__scipy | scipy/linalg/tests/test_lapack.py | {
"start": 6125,
"end": 16438
} | class ____:
def test_gels(self):
rng = np.random.default_rng(1234)
# Test fat/tall matrix argument handling - gh-issue #8329
for ind, dtype in enumerate(DTYPES):
m = 10
n = 20
nrhs = 1
a1 = rng.random((m, n)).astype(dtype)
b1 = rng... | TestLeastSquaresSolvers |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_column10.py | {
"start": 315,
"end": 1220
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_column10.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.go... | TestCompareXLSXFiles |
python | allegroai__clearml | clearml/debugging/timer.py | {
"start": 115,
"end": 1915
} | class ____(object):
"""A class implementing a simple timer, with a reset option"""
def __init__(self) -> None:
self._start_time = 0.0
self._diff = 0.0
self._total_time = 0.0
self._average_time = 0.0
self._calls = 0
self.tic()
def reset(self) -> None:
... | Timer |
python | apache__airflow | shared/secrets_masker/tests/secrets_masker/test_secrets_masker.py | {
"start": 40143,
"end": 41698
} | class ____:
"""Test that secrets masker doesn't import kubernetes unnecessarily."""
def test_no_k8s_import_when_not_needed(self):
"""Ensure kubernetes is not imported when masking non-k8s secrets."""
# Ensure kubernetes is not already imported
k8s_modules = [m for m in sys.modules if m.... | TestKubernetesImportAvoidance |
python | PyCQA__pycodestyle | tests/test_blank_lines.py | {
"start": 462,
"end": 1660
} | class ____(BlankLinesTestCase):
"""
Tests for default blank with 2 blank lines for top level and 1
blank line for methods.
"""
def test_initial_no_blank(self):
"""
It will accept no blank lines at the start of the file.
"""
result = errors_from_src("""def some_functi... | TestBlankLinesDefault |
python | getsentry__sentry | src/sentry/api/base.py | {
"start": 24566,
"end": 25150
} | class ____:
def track_set_commits_local(self, request: Request, organization_id=None, project_ids=None):
try:
analytics.record(
ReleaseSetCommitsLocalEvent(
user_id=request.user.id if request.user and request.user.id else None,
organization... | ReleaseAnalyticsMixin |
python | gevent__gevent | src/gevent/tests/test__os.py | {
"start": 2179,
"end": 5087
} | class ____(TestOS_tp):
def read(self, fd, count):
return os.nb_read(fd, count)
def write(self, fd, count):
return os.nb_write(fd, count)
def pipe(self):
r, w = super(TestOS_nb, self).pipe()
os.make_nonblocking(r)
os.make_nonblocking(w)
return r, w
def ... | TestOS_nb |
python | scipy__scipy | scipy/spatial/tests/test_kdtree.py | {
"start": 15938,
"end": 16107
} | class ____(_Test_two_random_trees_periodic):
def setup_method(self):
super().setup_method()
self.d = 2
@KDTreeTest
| _Test_two_random_trees_far_periodic |
python | scrapy__scrapy | scrapy/selector/unified.py | {
"start": 1018,
"end": 3170
} | class ____(_ParselSelector, object_ref):
"""
An instance of :class:`Selector` is a wrapper over response to select
certain parts of its content.
``response`` is an :class:`~scrapy.http.HtmlResponse` or an
:class:`~scrapy.http.XmlResponse` object that will be used for selecting
and extracting da... | Selector |
python | Netflix__metaflow | metaflow/_vendor/yaml/resolver.py | {
"start": 137,
"end": 6844
} | class ____:
DEFAULT_SCALAR_TAG = 'tag:yaml.org,2002:str'
DEFAULT_SEQUENCE_TAG = 'tag:yaml.org,2002:seq'
DEFAULT_MAPPING_TAG = 'tag:yaml.org,2002:map'
yaml_implicit_resolvers = {}
yaml_path_resolvers = {}
def __init__(self):
self.resolver_exact_paths = []
self.resolver_prefix_p... | BaseResolver |
python | langchain-ai__langchain | libs/standard-tests/tests/unit_tests/test_basic_tool.py | {
"start": 234,
"end": 513
} | class ____(BaseTool):
name: str = "ParrotMultiplyTool"
description: str = (
"Multiply two numbers like a parrot. Parrots always add eighty for their matey."
)
@override
def _run(self, a: int, b: int) -> int:
return a * b + 80
| ParrotMultiplyTool |
python | kamyu104__LeetCode-Solutions | Python/block-placement-queries.py | {
"start": 108,
"end": 1862
} | class ____(object):
def getResults(self, queries):
"""
:type queries: List[List[int]]
:rtype: List[bool]
"""
class BIT(object): # 0-indexed.
def __init__(self, n, default=0, fn=lambda x, y: x+y):
self.__bit = [default]*(n+1) # Extra one for dummy... | Solution |
python | yaml__pyyaml | lib/yaml/serializer.py | {
"start": 163,
"end": 4165
} | class ____:
ANCHOR_TEMPLATE = 'id%03d'
def __init__(self, encoding=None,
explicit_start=None, explicit_end=None, version=None, tags=None):
self.use_encoding = encoding
self.use_explicit_start = explicit_start
self.use_explicit_end = explicit_end
self.use_version = v... | Serializer |
python | gevent__gevent | src/gevent/tests/test__local.py | {
"start": 2008,
"end": 10727
} | class ____(greentest.TestCase):
# pylint:disable=attribute-defined-outside-init,blacklisted-name
def setUp(self):
del deleted_sentinels[:]
del created_sentinels[:]
tearDown = setUp
def test_create_local_subclass_init_args(self):
with self.assertRaisesRegex(TypeError,
... | TestGeventLocal |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/tryExcept1.py | {
"start": 841,
"end": 1447
} | class ____(*base_exceptions): ...
def func4():
try:
pass
except Exception1:
pass
except Exception2:
pass
def func5():
try:
return 1
# This should generate an error.
except int:
pass
# This should generate an error.
except (NotImplementedError, s... | Exception2 |
python | tensorflow__tensorflow | tensorflow/python/autograph/converters/continue_statements_test.py | {
"start": 958,
"end": 5508
} | class ____(converter_testing.TestCase):
def assertTransformedEquivalent(self, f, *inputs):
tr = self.transform(f, continue_statements)
self.assertEqual(f(*inputs), tr(*inputs))
def test_basic(self):
def f(x):
v = []
while x > 0:
x -= 1
if x % 2 == 0:
continue
... | ContinueCanonicalizationTest |
python | pypa__hatch | tests/backend/metadata/test_core.py | {
"start": 19956,
"end": 21797
} | class ____:
def test_dynamic(self, isolation):
metadata = ProjectMetadata(
str(isolation), None, {"project": {"requires-python": 9000, "dynamic": ["requires-python"]}}
)
with pytest.raises(
ValueError,
match=(
"Metadata field `requires-pyt... | TestRequiresPython |
python | optuna__optuna | optuna/pruners/_wilcoxon.py | {
"start": 528,
"end": 9623
} | class ____(BasePruner):
"""Pruner based on the `Wilcoxon signed-rank test <https://en.wikipedia.org/w/index.php?title=Wilcoxon_signed-rank_test&oldid=1195011212>`__.
This pruner performs the Wilcoxon signed-rank test between the current trial and the current best trial,
and stops whenever the pruner is sur... | WilcoxonPruner |
python | getsentry__sentry | tests/sentry/issues/test_search_issues_dataset.py | {
"start": 192,
"end": 1171
} | class ____(SnubaTestCase, TestCase):
def test_query_dataset_returns_empty(self) -> None:
# make a random query just to verify the table exists
now = datetime.now()
json_body = {
"selected_columns": ["project_id"],
"offset": 0,
"limit": 100,
"pr... | DatasetTest |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_multiarray.py | {
"start": 211161,
"end": 211840
} | class ____(TestCase):
def test_usigned_shortshort(self):
dt = np.min_scalar_type(2**8 - 1)
wanted = np.dtype("uint8")
assert_equal(wanted, dt)
# three tests below are added based on what numpy does
def test_complex(self):
dt = np.min_scalar_type(0 + 0j)
assert dt == ... | TestMinScalarType |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/scoped_css.py | {
"start": 454,
"end": 669
} | class ____(App):
def compose(self) -> ComposeResult:
yield MyWidget()
yield MyWidget()
yield Label("I should not be styled")
if __name__ == "__main__":
app = MyApp()
app.run()
| MyApp |
python | ray-project__ray | rllib/utils/replay_buffers/prioritized_episode_buffer.py | {
"start": 633,
"end": 33219
} | class ____(EpisodeReplayBuffer):
"""Prioritized Replay Buffer that stores episodes by their ID.
This replay buffer stores episode data (more specifically `SingleAgentEpisode`
objects) and implements prioritized experience replay first proposed
in the paper by Schaul et al. (2016, https://arxiv.org/abs/... | PrioritizedEpisodeReplayBuffer |
python | django__django | tests/admin_inlines/admin.py | {
"start": 5427,
"end": 5579
} | class ____(forms.ModelForm):
extra_field = forms.CharField()
class Meta:
model = ShoppingWeakness
fields = "__all__"
| WeaknessForm |
python | bokeh__bokeh | src/bokeh/models/dom.py | {
"start": 2063,
"end": 2288
} | class ____(Model, Qualified):
""" Base class for DOM nodes. """
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
| DOMNode |
python | jina-ai__jina | jina/serve/networking/instrumentation.py | {
"start": 214,
"end": 494
} | class ____:
"""
dataclass that contain the metrics used in the networking part
"""
sending_requests_time_metrics: Optional['Summary']
received_response_bytes: Optional['Summary']
send_requests_bytes_metrics: Optional['Summary']
@dataclass
| _NetworkingMetrics |
python | wandb__wandb | wandb/automations/events.py | {
"start": 8106,
"end": 8793
} | class ____(_BaseMutationEventInput):
"""A new artifact is linked to a collection.
Examples:
Define an event that triggers when an artifact is linked to the
collection "my-collection" with the alias "prod":
```python
from wandb import Api
from wandb.automations import On... | OnLinkArtifact |
python | django__django | tests/csrf_tests/tests.py | {
"start": 7325,
"end": 7653
} | class ____(HttpRequest):
"""
A version of HttpRequest that lets one track and change some things more
easily.
"""
def __init__(self):
super().__init__()
self.session = TestingSessionStore()
def is_secure(self):
return getattr(self, "_is_secure_override", False)
| TestingHttpRequest |
python | getsentry__sentry | tests/sentry/middleware/test_ratelimit_middleware.py | {
"start": 13190,
"end": 13560
} | class ____(Endpoint):
permission_classes = (AllowAny,)
enforce_rate_limit = False
rate_limits = RateLimitConfig(
limit_overrides={"GET": {RateLimitCategory.IP: RateLimit(limit=40, window=100)}}
)
def get(self, request):
return Response({"ok": True})
CONCURRENT_RATE_LIMIT = 3
CONC... | RaceConditionEndpoint |
python | pytorch__pytorch | torch/distributed/_composable/replicate.py | {
"start": 343,
"end": 5307
} | class ____(_State):
_ddp_weakref: weakref.ref
def __init__(self) -> None:
super().__init__()
self.module: nn.Module = nn.ParameterList()
self.has_initialized: bool = False
self._param_list: nn.ParameterList = nn.ParameterList()
# TODO(@fegin): this variable is originally... | _ReplicateState |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 310593,
"end": 311044
} | class ____(sgqlc.types.Input):
"""Ordering options for team member connections"""
__schema__ = github_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(sgqlc.types.non_null(TeamMemberOrderField), graphql_name="field")
"""The field to order team members by."""
direction ... | TeamMemberOrder |
python | scikit-learn__scikit-learn | sklearn/multioutput.py | {
"start": 40251,
"end": 45544
} | class ____(MetaEstimatorMixin, RegressorMixin, _BaseChain):
"""A multi-label model that arranges regressions into a chain.
Each model makes a prediction in the order specified by the chain using
all of the available features provided to the model plus the predictions
of models that are earlier in the c... | RegressorChain |
python | pypa__pip | src/pip/_vendor/rich/live.py | {
"start": 676,
"end": 1249
} | class ____(Thread):
"""A thread that calls refresh() at regular intervals."""
def __init__(self, live: "Live", refresh_per_second: float) -> None:
self.live = live
self.refresh_per_second = refresh_per_second
self.done = Event()
super().__init__(daemon=True)
def stop(self) ... | _RefreshThread |
python | huggingface__transformers | src/transformers/models/xmod/modeling_xmod.py | {
"start": 35592,
"end": 40513
} | class ____(XmodPreTrainedModel, GenerationMixin):
_tied_weights_keys = {
"lm_head.decoder.weight": "roberta.embeddings.word_embeddings.weight",
"lm_head.decoder.bias": "lm_head.bias",
}
# Copied from transformers.models.roberta.modeling_roberta.RobertaForCausalLM.__init__ with Roberta->Xmod... | XmodForCausalLM |
python | numpy__numpy | numpy/lib/tests/test_arraypad.py | {
"start": 36257,
"end": 37287
} | class ____:
"""Check how padding behaves on arrays with an empty dimension."""
@pytest.mark.parametrize(
# Keep parametrization ordered, otherwise pytest-xdist might believe
# that different tests were collected during parallelization
"mode", sorted(_all_modes.keys() - {"constant", "emp... | TestEmptyArray |
python | gevent__gevent | src/greentest/3.12/test_threading.py | {
"start": 3561,
"end": 44318
} | class ____(BaseTestCase):
maxDiff = 9999
@cpython_only
def test_name(self):
def func(): pass
thread = threading.Thread(name="myname1")
self.assertEqual(thread.name, "myname1")
# Convert int name to str
thread = threading.Thread(name=123)
self.assertEqual(th... | ThreadTests |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 265537,
"end": 265827
} | class ____(sgqlc.types.Interface):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("viewer_can_delete",)
viewer_can_delete = sgqlc.types.Field(
sgqlc.types.non_null(Boolean), graphql_name="viewerCanDelete"
)
| Deletable |
python | eventlet__eventlet | tests/db_pool_test.py | {
"start": 17474,
"end": 17586
} | class ____(Psycopg2ConnectionPool, TpoolConnectionPool, TestPsycopg2Base):
__test__ = True
| Test01Psycopg2Tpool |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-salesforce/unit_tests/integration/test_availability_strategy.py | {
"start": 422,
"end": 3389
} | class ____(TestCase):
def setUp(self) -> None:
self._strategy = SalesforceAvailabilityStrategy()
def test_handle_http_error_with_json_decode_error_then_raise_exception(self) -> None:
mock_response = Mock()
mock_response.json.side_effect = exceptions.JSONDecodeError("Expecting value", "<... | AvailabilityStrategyTest |
python | streamlit__streamlit | lib/streamlit/elements/lib/column_types.py | {
"start": 4798,
"end": 5135
} | class ____(TypedDict):
type: Literal["datetime"]
format: NotRequired[
str | Literal["localized", "distance", "calendar", "iso8601"] | None
]
min_value: NotRequired[str | None]
max_value: NotRequired[str | None]
step: NotRequired[int | float | None]
timezone: NotRequired[str | None]
... | DatetimeColumnConfig |
python | PrefectHQ__prefect | src/prefect/client/schemas/objects.py | {
"start": 2281,
"end": 2360
} | class ____(AutoEnum):
FLOW_RUN = "flow_run"
TASK_RUN = "task_run"
| RunType |
python | streamlit__streamlit | lib/tests/streamlit/web/server/app_static_file_handler_test.py | {
"start": 1178,
"end": 9786
} | class ____(tornado.testing.AsyncHTTPTestCase):
def setUp(self) -> None:
self._tmpdir = tempfile.TemporaryDirectory(dir=os.getcwd())
self._tmpfile = tempfile.NamedTemporaryFile(dir=self._tmpdir.name, delete=False)
self._tmp_js_file = tempfile.NamedTemporaryFile(
dir=self._tmpdir.n... | AppStaticFileHandlerTest |
python | tensorflow__tensorflow | tensorflow/lite/python/convert_saved_model_test.py | {
"start": 1494,
"end": 11093
} | class ____(test_util.TensorFlowTestCase):
def _createSimpleSavedModel(self, shape):
"""Create a simple SavedModel on the fly."""
saved_model_dir = os.path.join(self.get_temp_dir(), "simple_savedmodel")
with session.Session() as sess:
in_tensor = array_ops.placeholder(shape=shape, dtype=dtypes.float... | FreezeSavedModelTest |
python | google__pytype | pytype/annotation_utils.py | {
"start": 588,
"end": 27572
} | class ____(utils.ContextWeakrefMixin):
"""Utility class for inline type annotations."""
def __init__(self, ctx):
super().__init__(ctx)
# calling sub_one_annotation is costly, due to calling multiple of chained
# constructors (via annot.replace) and generating complex data structure.
# And in some c... | AnnotationUtils |
python | sqlalchemy__sqlalchemy | test/engine/test_reconnect.py | {
"start": 29223,
"end": 33901
} | class ____(fixtures.TestBase):
"""real test for issue #5648, which had to be revisited for 2.0 as the
initial version was not adequately tested and non-implementation for
mysql, postgresql was not caught
"""
__backend__ = True
__requires__ = ("graceful_disconnects",)
@testing.fixture
... | RealPrePingEventHandlerTest |
python | redis__redis-py | tests/test_pipeline.py | {
"start": 194,
"end": 14717
} | class ____:
def test_pipeline_is_true(self, r):
"Ensure pipeline instances are not false-y"
with r.pipeline() as pipe:
assert pipe
def test_pipeline(self, r):
with r.pipeline() as pipe:
(
pipe.set("a", "a1")
.get("a")
... | TestPipeline |
python | openai__openai-python | src/openai/types/completion_usage.py | {
"start": 1213,
"end": 1735
} | class ____(BaseModel):
completion_tokens: int
"""Number of tokens in the generated completion."""
prompt_tokens: int
"""Number of tokens in the prompt."""
total_tokens: int
"""Total number of tokens used in the request (prompt + completion)."""
completion_tokens_details: Optional[Completi... | CompletionUsage |
python | django__django | tests/async/tests.py | {
"start": 1035,
"end": 2064
} | class ____(SimpleTestCase):
"""
async_unsafe decorator should work correctly and returns the correct
message.
"""
@async_unsafe
def dangerous_method(self):
return True
async def test_async_unsafe(self):
# async_unsafe decorator catches bad access and returns the right
... | AsyncUnsafeTest |
python | django__django | tests/queries/models.py | {
"start": 1536,
"end": 1932
} | class ____(models.Model):
info = models.CharField(max_length=100)
note = models.ForeignKey(Note, models.CASCADE, null=True)
value = models.IntegerField(null=True)
date = models.ForeignKey(DateTimePK, models.SET_NULL, null=True)
filterable = models.BooleanField(default=True)
class Meta:
... | ExtraInfo |
python | apache__airflow | helm-tests/tests/helm_tests/webserver/test_ingress_web.py | {
"start": 914,
"end": 9669
} | class ____:
"""Tests ingress web."""
def test_should_pass_validation_with_just_ingress_enabled_v1(self):
render_chart(
values={"ingress": {"web": {"enabled": True}}, "airflowVersion": "2.10.5"},
show_only=["templates/webserver/webserver-ingress.yaml"],
) # checks that n... | TestIngressWeb |
python | mlflow__mlflow | mlflow/server/auth/entities.py | {
"start": 2883,
"end": 3856
} | class ____:
def __init__(
self,
experiment_id,
user_id,
permission,
):
self._experiment_id = experiment_id
self._user_id = user_id
self._permission = permission
@property
def experiment_id(self):
return self._experiment_id
@property
... | ExperimentPermission |
python | getsentry__sentry | tests/sentry/db/postgres/schema/safe_migrations/integration/test_migrations.py | {
"start": 11111,
"end": 11758
} | class ____(BaseSafeMigrationTest):
app = "good_flow_delete_pending_with_fk_constraints_app"
migrate_from = "0001"
migrate_to = "0003"
def test(self) -> None:
self._run_migration(self.app, "0001_initial")
assert f"{self.app}_testtable" in connection.introspection.table_names()
s... | DeletionModelGoodDeleteRemoveFKConstraints |
python | gevent__gevent | src/gevent/_config.py | {
"start": 12590,
"end": 13112
} | class ____(IntSettingMixin, Setting):
name = 'trace_malloc'
environment_key = 'PYTHONTRACEMALLOC'
default = False
desc = """\
Should FFI objects track their allocation?
This is only useful for low-level debugging.
On Python 3, this environment variable is built in to the
interpreter, ... | TraceMalloc |
python | google__pytype | pytype/tests/test_variable_annotations.py | {
"start": 119,
"end": 1175
} | class ____(test_base.BaseTest):
"""Tests for PEP526 variable annotations."""
def test_pyi_annotations(self):
with test_utils.Tempdir() as d:
d.create_file(
"foo.pyi",
"""
from typing import List
x: int
y: List[int]
class A:
a: int
b:... | VariableAnnotationsBasicTest |
python | django__django | tests/forms_tests/field_tests/test_typedchoicefield.py | {
"start": 150,
"end": 3602
} | class ____(SimpleTestCase):
def test_typedchoicefield_1(self):
f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
self.assertEqual(1, f.clean("1"))
msg = "'Select a valid choice. 2 is not one of the available choices.'"
with self.assertRaisesMessage(ValidationError, ms... | TypedChoiceFieldTest |
python | FactoryBoy__factory_boy | tests/test_using.py | {
"start": 63944,
"end": 64410
} | class ____:
def __init__(self, keys, instance):
self.keys = keys
self.instance = instance
def get_or_create(self, **kwargs):
defaults = kwargs.pop('defaults', {})
if kwargs == self.keys:
return self.instance, False
kwargs.update(defaults)
instance = F... | BetterFakeModelManager |
python | PyCQA__pylint | tests/functional/ext/docparams/return/missing_return_doc_required_Sphinx.py | {
"start": 1507,
"end": 1838
} | class ____:
"""Example of a class function trying to use `type` as return
documentation in a Sphinx style docstring
"""
def test_ignores_non_property_return_type_sphinx( # [missing-return-doc, missing-return-type-doc]
self,
):
"""docstring ...
:type: int
"""
... | Foo |
python | wandb__wandb | wandb/vendor/pygments/lexers/graph.py | {
"start": 457,
"end": 2370
} | class ____(RegexLexer):
"""
For `Cypher Query Language
<http://docs.neo4j.org/chunked/milestone/cypher-query-lang.html>`_
For the Cypher version in Neo4J 2.0
.. versionadded:: 2.0
"""
name = 'Cypher'
aliases = ['cypher']
filenames = ['*.cyp', '*.cypher']
flags = re.MULTILINE |... | CypherLexer |
python | pandas-dev__pandas | asv_bench/benchmarks/io/csv.py | {
"start": 2728,
"end": 3128
} | class ____(BaseIO):
fname = "__test__.csv"
def setup(self):
rng = date_range("2000", periods=100_000, freq="s")
self.data = DataFrame({"a": 1}, index=rng)
def time_frame_date_formatting_index(self):
self.data.to_csv(self.fname, date_format="%Y-%m-%d %H:%M:%S")
def time_frame_d... | ToCSVDatetimeIndex |
python | pytorch__pytorch | torch/_inductor/runtime/triton_heuristics.py | {
"start": 139070,
"end": 139280
} | class ____(GridExpr):
def generate(self, meta: dict[str, int]) -> None:
self.x_grid = self.ceildiv("xnumel", meta.get("XBLOCK"))
self.y_grid = self.ceildiv("ynumel", meta.get("YBLOCK"))
| Grid2D |
python | ansible__ansible | lib/ansible/galaxy/dependency_resolution/dataclasses.py | {
"start": 23712,
"end": 24738
} | class ____(
_ComputedReqKindsMixin,
CandidateNamedTuple,
):
"""A concrete collection candidate with its version resolved."""
def __new__(cls, *args: object, **kwargs: object) -> t.Self:
self = CandidateNamedTuple.__new__(cls, *args, **kwargs)
return self
def __init__(self, ... | Candidate |
python | pydata__xarray | xarray/computation/ops.py | {
"start": 8912,
"end": 9137
} | class ____:
__slots__ = ()
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
if getattr(cls, "_reduce_method", None):
inject_reduce_methods(cls)
| IncludeReduceMethods |
python | kubernetes-client__python | kubernetes/client/models/v1_container_state_waiting.py | {
"start": 383,
"end": 4375
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1ContainerStateWaiting |
python | huggingface__transformers | src/transformers/models/dia/generation_dia.py | {
"start": 1440,
"end": 22024
} | class ____(GenerationMixin):
# Indicates CFG which needs preparation to be properly handled by repeats
_uses_cfg = None
def _get_logits_processor(
self,
generation_config: GenerationConfig,
input_ids_seq_length: Optional[int] = None,
encoder_input_ids: Optional[torch.LongTen... | DiaGenerationMixin |
python | jina-ai__jina | jina/jaml/__init__.py | {
"start": 17578,
"end": 17916
} | class ____(type):
"""
Metaclass for :class:`JAMLCompatible`.
It enables any class inherit from :class:`JAMLCompatible` to auto-register itself at :class:`JAML`
"""
def __new__(cls, *args, **kwargs):
_cls = super().__new__(cls, *args, **kwargs)
JAML.register(_cls)
return _cl... | JAMLCompatibleType |
python | ray-project__ray | python/ray/tests/test_actor_retry_1.py | {
"start": 89,
"end": 400
} | class ____:
def __init__(self) -> None:
self.count = 0
def increment(self) -> int:
c = self.count
self.count += 1
return c
def get_count(self) -> int:
return self.count
# TODO: also do work for async and threaded actors
@ray.remote(max_task_retries=3)
| Counter |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/global_shuffle_test.py | {
"start": 1430,
"end": 7243
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
"""Tests for global shuffling of tf.data datasets."""
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(
dataset_range=[1, 100],
seed=[None, 42]... | GlobalShuffleTest |
python | pytorch__pytorch | torch/testing/_internal/common_subclass.py | {
"start": 282,
"end": 2230
} | class ____(torch.Tensor):
@staticmethod
def __new__(cls, *args, **kwargs):
t, kwargs = cls.get_wrapper_properties(*args, **kwargs)
if "size" not in kwargs:
size = t.size()
else:
size = kwargs["size"]
del kwargs["size"]
if "dtype" not in kwargs:... | WrapperTensor |
python | huggingface__transformers | tests/models/metaclip_2/test_modeling_metaclip_2.py | {
"start": 15600,
"end": 18378
} | class ____(MetaClip2ModelTesterMixin, unittest.TestCase):
all_model_classes = (MetaClip2TextModel, MetaClip2TextModelWithProjection) if is_torch_available() else ()
model_split_percents = [0.5, 0.8, 0.9]
def setUp(self):
self.model_tester = MetaClip2TextModelTester(self)
self.config_tester... | MetaClip2TextModelTest |
python | spyder-ide__spyder | spyder/plugins/updatemanager/plugin.py | {
"start": 586,
"end": 4869
} | class ____(SpyderPluginV2):
NAME = 'update_manager'
REQUIRES = [Plugins.Preferences]
OPTIONAL = [Plugins.Application, Plugins.MainMenu, Plugins.StatusBar]
CONTAINER_CLASS = UpdateManagerContainer
CONF_SECTION = 'update_manager'
CONF_FILE = False
CAN_BE_DISABLED = False
# ---- SpyderPlug... | UpdateManager |
python | pytest-dev__pytest-asyncio | pytest_asyncio/plugin.py | {
"start": 17277,
"end": 29857
} | class ____(PytestAsyncioFunction):
"""
Pytest item that is coroutine or an asynchronous generator decorated by
@hypothesis.given.
"""
def setup(self) -> None:
if not getattr(self.obj, "hypothesis", False) and getattr(
self.obj, "is_hypothesis_test", False
):
... | AsyncHypothesisTest |
python | kamyu104__LeetCode-Solutions | Python/split-array-into-fibonacci-sequence.py | {
"start": 32,
"end": 1193
} | class ____(object):
def splitIntoFibonacci(self, S):
"""
:type S: str
:rtype: List[int]
"""
def startswith(S, k, x):
y = 0
for i in xrange(k, len(S)):
y = 10*y + int(S[i])
if y == x:
return i-k+1
... | Solution |
python | sphinx-doc__sphinx | sphinx/directives/patches.py | {
"start": 2800,
"end": 4424
} | class ____(SphinxDirective):
"""Parse and mark up content of a code block.
This is compatible with docutils' :rst:dir:`code` directive.
"""
optional_arguments = 1
option_spec: ClassVar[OptionSpec] = {
'class': directives.class_option,
'force': directives.flag,
'name': direc... | Code |
python | pandas-dev__pandas | pandas/tests/tseries/offsets/test_business_hour.py | {
"start": 41631,
"end": 58547
} | class ____:
# opening time should be affected by sign of n, not by n's value and end
opening_time_cases = [
(
[
BusinessHour(),
BusinessHour(n=2),
BusinessHour(n=4),
BusinessHour(end="10:00"),
BusinessHour(n=2, e... | TestOpeningTimes |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 20230,
"end": 20542
} | class ____:
Alias = AliasAction
Data = DataAction
Collections = CollectionsAction
Roles = RolesAction
Cluster = ClusterAction
Nodes = NodesAction
Backups = BackupsAction
Tenants = TenantsAction
Users = UsersAction
Replicate = ReplicateAction
Groups = GroupAction
| Actions |
python | google__pytype | pytype/pytd/pytd.py | {
"start": 16822,
"end": 16918
} | class ____(_SetOfTypes):
"""A union type that contains all types in self.type_list."""
| UnionType |
python | getsentry__sentry | tests/sentry/rules/processing/test_processor.py | {
"start": 1940,
"end": 25698
} | class ____(TestCase, PerformanceIssueTestCase):
def setUp(self) -> None:
event = self.store_event(data={}, project_id=self.project.id)
self.group_event = event.for_group(cast(Group, event.group))
Rule.objects.filter(project=self.group_event.project).delete()
ProjectOwnership.objects... | RuleProcessorTest |
python | cython__cython | tests/run/py3k_super.py | {
"start": 2105,
"end": 2788
} | class ____(A):
"""
>>> obj = C()
>>> obj.method_1()
2
>>> obj.method_2()
3
>>> obj.method_3()
['__class__', 'self']
>>> obj.method_4()
['self']
>>> obj.method_5() # doctest: +ELLIPSIS
<class '...py3k_super.C'>
>>> obj.super_class() # doctest: +ELLIPSIS
<class '.... | C |
python | django__django | tests/fixtures/models.py | {
"start": 3431,
"end": 3546
} | class ____(models.Manager):
def get_by_natural_key(self, key):
return self.get(key=key)
| NaturalKeyManager |
python | spack__spack | lib/spack/spack/llnl/util/lock.py | {
"start": 5932,
"end": 6389
} | class ____:
READ = 0
WRITE = 1
@staticmethod
def to_str(tid):
ret = "READ"
if tid == LockType.WRITE:
ret = "WRITE"
return ret
@staticmethod
def to_module(tid):
lock = fcntl.LOCK_SH
if tid == LockType.WRITE:
lock = fcntl.LOCK_EX
... | LockType |
python | walkccc__LeetCode | solutions/1575. Count All Possible Routes/1575.py | {
"start": 0,
"end": 634
} | class ____:
def countRoutes(
self,
locations: list[int],
start: int,
finish: int,
fuel: int,
) -> int:
MOD = 1_000_000_007
@functools.lru_cache(None)
def dp(i: int, fuel: int) -> int:
"""
Returns the number of ways to reach the `finish` city from the i-th city
... | Solution |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_redshift_cluster.py | {
"start": 22781,
"end": 29077
} | class ____:
@mock.patch("airflow.providers.amazon.aws.hooks.redshift_cluster.RedshiftHook.cluster_status")
@mock.patch.object(RedshiftHook, "conn")
def test_delete_cluster_with_wait_for_completion(self, mock_conn, mock_cluster_status):
mock_cluster_status.return_value = "cluster_not_found"
r... | TestDeleteClusterOperator |
python | pallets__werkzeug | src/werkzeug/sansio/multipart.py | {
"start": 383,
"end": 464
} | class ____(Event):
name: str
headers: Headers
@dataclass(frozen=True)
| Field |
python | mkdocs__mkdocs | mkdocs/tests/build_tests.py | {
"start": 39434,
"end": 39936
} | class ____(markdown.preprocessors.Preprocessor):
def __init__(self, base_path: str) -> None:
self.base_path = base_path
def run(self, lines: list[str]) -> list[str]:
for i, line in enumerate(lines):
if m := re.search(r'^--8<-- "(.+)"$', line):
try:
... | _TestPreprocessor |
python | google__pytype | pytype/tools/xref/indexer.py | {
"start": 9225,
"end": 9361
} | class ____:
"""Representation of an expression function call argument."""
names: list[str]
type: Any
@dataclasses.dataclass
| ExprArg |
python | kamyu104__LeetCode-Solutions | Python/partition-array-into-disjoint-intervals.py | {
"start": 29,
"end": 408
} | class ____(object):
def partitionDisjoint(self, A):
"""
:type A: List[int]
:rtype: int
"""
B = A[:]
for i in reversed(xrange(len(A)-1)):
B[i] = min(B[i], B[i+1])
p_max = 0
for i in xrange(1, len(A)):
p_max = max(p_max, A[i-1])
... | Solution |
python | graphql-python__graphene | graphene/types/tests/test_scalar.py | {
"start": 4624,
"end": 6240
} | class ____:
def test_query(self):
"""
Test that a normal query works.
"""
result = schema.execute("{ optional { float(input: 20) } }")
assert not result.errors
assert result.data == {"optional": {"float": 20.0}}
result = schema.execute("{ optional { float(inp... | TestFloat |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/internal/conjecture/engine.py | {
"start": 6344,
"end": 6834
} | class ____(Enum):
max_examples = "settings.max_examples={s.max_examples}"
max_iterations = (
"settings.max_examples={s.max_examples}, "
"but < 10% of examples satisfied assumptions"
)
max_shrinks = f"shrunk example {MAX_SHRINKS} times"
finished = "nothing left to do"
flaky = "tes... | ExitReason |
python | python-markdown__markdown | markdown/inlinepatterns.py | {
"start": 8250,
"end": 11447
} | class ____: # pragma: no cover
"""
Base class that inline patterns subclass.
Inline patterns are handled by means of `Pattern` subclasses, one per regular expression.
Each pattern object uses a single regular expression and must support the following methods:
[`getCompiledRegExp`][markdown.inlinep... | Pattern |
python | airbytehq__airbyte | airbyte-ci/connectors/connectors_qa/src/connectors_qa/models.py | {
"start": 1530,
"end": 7506
} | class ____(ABC):
requires_metadata: bool = True
runs_on_released_connectors: bool = True
@property
@abstractmethod
def name(self) -> str:
"""The name of the QA check
Raises:
NotImplementedError: Subclasses must implement name property/attribute
Returns:
... | Check |
python | kamyu104__LeetCode-Solutions | Python/maximum-ascending-subarray-sum.py | {
"start": 29,
"end": 389
} | class ____(object):
def maxAscendingSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = curr = 0
for i in xrange(len(nums)):
if not (i and nums[i-1] < nums[i]):
curr = 0
curr += nums[i]
result = max(... | Solution |
python | astropy__astropy | astropy/utils/masked/core.py | {
"start": 14087,
"end": 14672
} | class ____:
mask_val = np.ma.masked
def __init__(self, bound=False):
super().__init__(bound)
# If bound to a data object instance then create the dict of attributes
# which stores the info attribute values.
if bound:
# Specify how to serialize this object depending ... | MaskedInfoBase |
python | python-pillow__Pillow | src/PIL/BlpImagePlugin.py | {
"start": 14293,
"end": 16533
} | class ____(ImageFile.PyEncoder):
_pushes_fd = True
def _write_palette(self) -> bytes:
data = b""
assert self.im is not None
palette = self.im.getpalette("RGBA", "RGBA")
for i in range(len(palette) // 4):
r, g, b, a = palette[i * 4 : (i + 1) * 4]
data += s... | BLPEncoder |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_assorted_poly.py | {
"start": 90656,
"end": 98843
} | class ____(fixtures.DeclarativeMappedTest):
"""test for #10006"""
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
employee_m2m = Table(
"employee_m2m",
Base.metadata,
Column(
"left", Integer, ForeignKey("employee.id"), pr... | MultiOfTypeContainsEagerTest |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_getnewargs/invalid_getnewargs_ex_returned.py | {
"start": 2049,
"end": 2257
} | class ____:
""" __getnewargs_ex__ returns tuple with wrong type for both args """
def __getnewargs_ex__(self): # [invalid-getnewargs-ex-returned]
return ({'x': 'y'}, (2,))
| FifthBadGetNewArgsEx |
python | streamlit__streamlit | lib/streamlit/runtime/caching/cache_data_api.py | {
"start": 2433,
"end": 4392
} | class ____(CachedFuncInfo[P, R]):
"""Implements the CachedFuncInfo interface for @st.cache_data."""
persist: CachePersistType
max_entries: int | None
ttl: float | timedelta | str | None
def __init__(
self,
func: Callable[P, R],
persist: CachePersistType,
max_entries... | CachedDataFuncInfo |
python | ionelmc__pytest-benchmark | tests/test_with_testcase.py | {
"start": 45,
"end": 285
} | class ____(unittest.TestCase):
@pytest.fixture(autouse=True)
def setupBenchmark(self, benchmark):
self.benchmark = benchmark
def test_foo(self):
self.benchmark(time.sleep, 0.000001)
| TerribleTerribleWayToWriteTests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.