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 | ray-project__ray | python/ray/dashboard/modules/aggregator/tests/test_ray_event_publisher.py | {
"start": 1484,
"end": 5217
} | class ____:
"""Test the main RayEventsPublisher functionality."""
@pytest.mark.asyncio
async def test_publish_with_retries_failure_then_success(self, base_kwargs):
"""Test publish that fails then succeeds."""
call_count = {"count": 0}
# fail the first publish call but succeed on re... | TestRayEventPublisher |
python | pandas-dev__pandas | pandas/tests/tools/test_to_datetime.py | {
"start": 1627,
"end": 19341
} | class ____:
def test_to_datetime_readonly(self, writable):
# GH#34857
arr = np.array([], dtype=object)
arr.setflags(write=writable)
result = to_datetime(arr)
expected = to_datetime([])
tm.assert_index_equal(result, expected)
@pytest.mark.parametrize(
"for... | TestTimeConversionFormats |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 270141,
"end": 270631
} | class ____(sgqlc.types.Input):
"""Ways in which lists of git refs can be ordered upon return."""
__schema__ = github_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(sgqlc.types.non_null(RefOrderField), graphql_name="field")
"""The field in which to order refs by."""
d... | RefOrder |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/tests/test_rl_trainer.py | {
"start": 8459,
"end": 9749
} | class ____(unittest.TestCase):
def test_warning_group_reward(self):
with self.assertLogs("mlagents.trainers", level="WARN") as cm:
rl_trainer = create_rl_trainer()
# This one should warn
trajectory = mb.make_fake_trajectory(
length=10,
obse... | RLTrainerWarningTest |
python | ray-project__ray | python/ray/experimental/channel/nccl_group.py | {
"start": 612,
"end": 13562
} | class ____(Communicator):
"""
Represents an actor's NCCL communicator. This is the default NCCL communicator
to be used in Compiled Graph if a custom communicator is not provided.
This class is not thread-safe.
"""
def __init__(
self,
world_size: int,
comm_id: tuple,
... | _NcclGroup |
python | scrapy__scrapy | tests/test_scheduler.py | {
"start": 1496,
"end": 1559
} | class ____(NamedTuple):
downloader: MockDownloader
| MockEngine |
python | django__django | tests/postgres_tests/models.py | {
"start": 3788,
"end": 4367
} | class ____(PostgreSQLModel):
ints = IntegerRangeField(blank=True, null=True, db_default=(5, 10))
bigints = BigIntegerRangeField(blank=True, null=True)
decimals = DecimalRangeField(blank=True, null=True)
timestamps = DateTimeRangeField(blank=True, null=True)
timestamps_inner = DateTimeRangeField(blan... | RangesModel |
python | aio-libs__aiohttp | aiohttp/web_exceptions.py | {
"start": 7096,
"end": 7161
} | class ____(HTTPClientError):
status_code = 401
| HTTPUnauthorized |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/recursiveTypeAlias9.py | {
"start": 244,
"end": 497
} | class ____(Generic[A]):
val: A
a: JSON = {"a": "b"}
b: JSON = "a"
c: Example[JSON] = Example(a)
d: Example[JSON] = Example("a")
e: Example[JSON] = Example({})
f: Example[JSON] = Example({"a": "b"})
g: Example[JSON] = Example({"a": {"a": "b"}})
| Example |
python | numba__numba | numba/core/types/misc.py | {
"start": 4427,
"end": 4655
} | class ____(CPointer):
"""
Type class for pointers which aren't guaranteed to last long - e.g.
stack-allocated slots. The data model serializes such pointers
by copying the data pointed to.
"""
| EphemeralPointer |
python | pytorch__pytorch | torch/autograd/grad_mode.py | {
"start": 11134,
"end": 12471
} | class ____(_DecoratorContextManager):
r"""Context-manager that sets whether or not to always enable view-replay in autograd.
``set_view_replay_enabled`` will enable or disable view-replay based on its argument :attr:`mode`.
It can be used as a context-manager or as a function.
This context manager is ... | _force_original_view_tracking |
python | fsspec__filesystem_spec | fsspec/implementations/tests/memory/memory_test.py | {
"start": 426,
"end": 501
} | class ____(abstract.AbstractOpenTests, MemoryFixtures):
pass
| TestMemoryOpen |
python | huggingface__transformers | src/transformers/models/timesfm/modeling_timesfm.py | {
"start": 12147,
"end": 22120
} | class ____(TimesFmPreTrainedModel):
def __init__(self, config: TimesFmConfig):
super().__init__(config)
self.config = config
self.input_ff_layer = TimesFmResidualBlock(
input_dims=2 * config.patch_length,
output_dims=config.hidden_size,
hidden_dims=config... | TimesFmModel |
python | fastapi__sqlmodel | docs_src/tutorial/one/tutorial002.py | {
"start": 100,
"end": 1637
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_u... | Hero |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/missing_type.py | {
"start": 499,
"end": 789
} | class ____:
def source(self) -> None:
pass
unknown = source # revealed type is `unknown`
def test_unknown_source_attribute(x: UnknownSourceAttribute) -> None:
# TODO(T205677349): We don't find the flow here.
y = x.unknown()
_test_sink(y)
| UnknownSourceAttribute |
python | getsentry__sentry | tests/sentry/users/api/endpoints/test_user_ips.py | {
"start": 269,
"end": 1525
} | class ____(APITestCase):
endpoint = "sentry-api-0-user-ips"
def setUp(self) -> None:
super().setUp()
self.user = self.create_user(id=1)
self.login_as(self.user)
def test_simple(self) -> None:
UserIP.objects.create(
user=self.user,
ip_address="127.0.0... | UserIPsTest |
python | tensorflow__tensorflow | tensorflow/python/keras/optimizer_v2/gradient_descent.py | {
"start": 1036,
"end": 7006
} | class ____(optimizer_v2.OptimizerV2):
r"""Gradient descent (with momentum) optimizer.
Update rule for parameter `w` with gradient `g` when `momentum` is 0:
```python
w = w - learning_rate * g
```
Update rule when `momentum` is larger than 0:
```python
velocity = momentum * velocity - learning_rate *... | SGD |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_selection.py | {
"start": 2840,
"end": 6852
} | class ____:
"""Test basic tool selection functionality."""
def test_sync_basic_selection(self) -> None:
"""Test synchronous tool selection."""
# First call: selector picks tools
# Second call: agent uses selected tools
tool_calls = [
[
{
... | TestLLMToolSelectorBasic |
python | ray-project__ray | rllib/env/multi_agent_env_runner.py | {
"start": 2469,
"end": 45194
} | class ____(EnvRunner, Checkpointable):
"""The genetic environment runner for the multi-agent case."""
@override(EnvRunner)
def __init__(self, config: AlgorithmConfig, **kwargs):
"""Initializes a MultiAgentEnvRunner instance.
Args:
config: An `AlgorithmConfig` object containing ... | MultiAgentEnvRunner |
python | Textualize__textual | src/textual/worker.py | {
"start": 1663,
"end": 2310
} | class ____(enum.Enum):
"""A description of the worker's current state."""
PENDING = 1
"""Worker is initialized, but not running."""
RUNNING = 2
"""Worker is running."""
CANCELLED = 3
"""Worker is not running, and was cancelled."""
ERROR = 4
"""Worker is not running, and exited with ... | WorkerState |
python | apache__airflow | airflow-core/src/airflow/dag_processing/bundles/manager.py | {
"start": 1580,
"end": 1783
} | class ____(BaseModel):
"""Schema defining the user-specified configuration for a DAG bundle."""
name: str
classpath: str
kwargs: dict
team_name: str | None = None
| _ExternalBundleConfig |
python | pytorch__pytorch | tools/test/heuristics/test_heuristics.py | {
"start": 1818,
"end": 3231
} | class ____(TestTD):
@mock.patch(
HEURISTIC_CLASS + "_get_historical_test_class_correlations",
return_value=gen_historical_class_failures(),
)
@mock.patch(
HEURISTIC_CLASS + "query_changed_files",
return_value=["file1"],
)
def test_get_prediction_confidence(
se... | TestHistoricalClassFailureCorrelation |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/inconsistentConstructor1.py | {
"start": 372,
"end": 512
} | class ____(Parent2):
# This should generate an error if reportInconsistentConstructor is enabled.
def __new__(cls, b: str): ...
| Child2 |
python | sphinx-doc__sphinx | sphinx/ext/autosummary/__init__.py | {
"start": 3433,
"end": 3814
} | class ____(nodes.comment):
pass
def autosummary_toc_visit_html(self: nodes.NodeVisitor, node: autosummary_toc) -> None:
"""Hide autosummary toctree list in HTML output."""
raise nodes.SkipNode
def autosummary_noop(self: nodes.NodeVisitor, node: Node) -> None:
pass
# -- autosummary_table node -----... | autosummary_toc |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dag_warning.py | {
"start": 2405,
"end": 5107
} | class ____:
@pytest.mark.parametrize(
("query_params", "expected_total_entries", "expected_messages"),
[
({}, 3, [DAG1_MESSAGE, DAG2_MESSAGE, DAG3_MESSAGE]),
({"dag_id": DAG1_ID}, 1, [DAG1_MESSAGE]),
({"warning_type": DAG_WARNING_TYPE}, 3, [DAG1_MESSAGE, DAG2_MESS... | TestGetDagWarnings |
python | pennersr__django-allauth | allauth/socialaccount/providers/microsoft/provider.py | {
"start": 242,
"end": 372
} | class ____(ProviderAccount):
def get_avatar_url(self):
return self.account.extra_data.get("photo")
| MicrosoftGraphAccount |
python | sympy__sympy | sympy/physics/quantum/dagger.py | {
"start": 154,
"end": 2484
} | class ____(adjoint):
"""General Hermitian conjugate operation.
Explanation
===========
Take the Hermetian conjugate of an argument [1]_. For matrices this
operation is equivalent to transpose and complex conjugate [2]_.
Parameters
==========
arg : Expr
The SymPy expression th... | Dagger |
python | doocs__leetcode | solution/1100-1199/1110.Delete Nodes And Return Forest/Solution.py | {
"start": 192,
"end": 833
} | class ____:
def delNodes(
self, root: Optional[TreeNode], to_delete: List[int]
) -> List[TreeNode]:
def dfs(root: Optional[TreeNode]) -> Optional[TreeNode]:
if root is None:
return None
root.left, root.right = dfs(root.left), dfs(root.right)
if... | Solution |
python | PyCQA__pylint | tests/pyreverse/functional/class_diagrams/property_decorator/property_decorator.py | {
"start": 461,
"end": 895
} | class ____:
"""Test class for property decorators without annotated return type"""
def __init__(self):
self._x = 0
@property
def x(self):
"""This is a getter for x"""
return self._x
@x.setter
def x(self, value):
"""This is a setter for x"""
self._x = val... | NonAnnotatedPropertyTest |
python | python-openxml__python-docx | src/docx/oxml/shape.py | {
"start": 7055,
"end": 8070
} | class ____(BaseOxmlElement):
"""``<pic:spPr>`` element, specifies size and shape of picture container."""
xfrm = ZeroOrOne(
"a:xfrm",
successors=(
"a:custGeom",
"a:prstGeom",
"a:ln",
"a:effectLst",
"a:effectDag",
"a:scene3d... | CT_ShapeProperties |
python | bokeh__bokeh | src/bokeh/document/json.py | {
"start": 2796,
"end": 3033
} | class ____(TypedDict):
version: NotRequired[str]
title: NotRequired[str]
defs: NotRequired[list[ModelDef]]
config: NotRequired[ModelDef]
roots: list[ModelRep]
callbacks: NotRequired[dict[str, list[ModelRep]]]
| DocJson |
python | realpython__materials | python-use-global-variable-in-function/account_class.py | {
"start": 0,
"end": 1221
} | class ____:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"Successful deposit: +${amount:,.2f}")
def withdraw(self, amount):
if self.balance - amount > 0:
self.balance -= amount
print(f... | Account |
python | keras-team__keras | keras/src/ops/nn.py | {
"start": 93520,
"end": 95654
} | class ____(Operation):
def compute_output_spec(self, abs_, angle):
return KerasTensor(shape=abs_.shape)
def call(self, abs_, angle):
return _polar(abs_, angle)
@keras_export(["keras.ops.polar", "keras.ops.nn.polar"])
def polar(abs_, angle):
"""Constructs a complex tensor whose elements ar... | Polar |
python | getsentry__sentry | src/sentry/users/api/serializers/user.py | {
"start": 1656,
"end": 1718
} | class ____(TypedDict):
slug: str
name: str
| _Organization |
python | Textualize__textual | tests/test_binding_inheritance.py | {
"start": 18096,
"end": 18315
} | class ____(
Static, can_focus=True, inherit_bindings=False
):
"""A widget that can receive focus but has empty bindings and doesn't inherit bindings."""
BINDINGS = []
| FocusableWidgetWithEmptyBindingsNoInherit |
python | realpython__materials | tic-tac-toe-ai-python/source_code_step_3/tic-tac-toe/frontends/console/args.py | {
"start": 279,
"end": 1124
} | class ____(NamedTuple):
player1: Player
player2: Player
starting_mark: Mark
def parse_args() -> Args:
parser = argparse.ArgumentParser()
parser.add_argument(
"-X",
dest="player_x",
choices=PLAYER_CLASSES.keys(),
default="human",
)
parser.add_argument(
... | Args |
python | getsentry__sentry | src/sentry/api/serializers/models/project.py | {
"start": 25664,
"end": 25740
} | class ____(TypedDict):
version: str
dateFinished: datetime
| _DeployDict |
python | tensorflow__tensorflow | tensorflow/python/data/util/sparse_test.py | {
"start": 11777,
"end": 15567
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(
combinations.times(test_base.default_test_combinations(),
_test_any_sparse_combinations()))
def testAnySparse(self, classes_fn, expected):
classes = classes_fn()
self.assertEqual(sparse.any... | SparseTest |
python | PrefectHQ__prefect | src/prefect/concurrency/_asyncio.py | {
"start": 1079,
"end": 8424
} | class ____(TimeoutError):
"""Raised when acquiring a concurrency slot times out."""
logger: logging.Logger = get_logger("concurrency")
async def aacquire_concurrency_slots(
names: list[str],
slots: int,
mode: Literal["concurrency", "rate_limit"] = "concurrency",
timeout_seconds: Optional[float] ... | AcquireConcurrencySlotTimeoutError |
python | ray-project__ray | python/ray/_private/test_utils.py | {
"start": 36152,
"end": 36955
} | class ____(Queue):
def __init__(self, maxsize: int = 0, actor_options: Optional[Dict] = None) -> None:
actor_options = actor_options or {}
self.maxsize = maxsize
self.actor = (
ray.remote(_BatchQueueActor).options(**actor_options).remote(self.maxsize)
)
def get_batch... | BatchQueue |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/assertsql.py | {
"start": 861,
"end": 1843
} | class ____(SQLMatchRule):
def __init__(self, statement, params=None, consume_statement=True):
self.statement = statement
self.params = params
self.consume_statement = consume_statement
def process_statement(self, execute_observed):
stmt = execute_observed.statements[0]
i... | CursorSQL |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/comments.py | {
"start": 15906,
"end": 20585
} | class ____(MutableSliceableSequence, list, CommentedBase): # type: ignore
__slots__ = (Comment.attrib, '_lst')
def __init__(self, *args, **kw):
# type: (Any, Any) -> None
list.__init__(self, *args, **kw)
def __getsingleitem__(self, idx):
# type: (Any) -> Any
return list.__... | CommentedSeq |
python | joke2k__faker | faker/providers/job/zh_TW/__init__.py | {
"start": 156,
"end": 8742
} | class ____(BaseProvider):
jobs = [
"BIOS工程師",
"CAD/CAM工程師",
"CNC機台操作人員",
"CNC電腦程式編排人員",
"EMC/電子安規工程師",
"FAE工程師",
"IC佈局工程師",
"IC封裝/測試工程師",
"ISO/品保人員",
"Internet程式設計師",
"LCD製程工程師",
"LCD設備工程師",
"MES工程師",
"MI... | Provider |
python | lepture__authlib | authlib/jose/rfc7518/jws_algs.py | {
"start": 3013,
"end": 4592
} | class ____(JWSAlgorithm):
"""ECDSA using SHA algorithms for JWS. Available algorithms:
- ES256: ECDSA using P-256 and SHA-256
- ES384: ECDSA using P-384 and SHA-384
- ES512: ECDSA using P-521 and SHA-512
"""
SHA256 = hashes.SHA256
SHA384 = hashes.SHA384
SHA512 = hashes.SHA512
def ... | ECAlgorithm |
python | joke2k__faker | faker/providers/ssn/es_MX/__init__.py | {
"start": 2493,
"end": 6705
} | class ____(BaseProvider):
"""
A Faker provider for the Mexican SSN, RFC and CURP
"""
ssn_formats = ("###########",)
def ssn(self) -> str:
"""
Mexican Social Security Number, as given by IMSS.
:return: a random Mexican SSN
"""
office = self.random_int(min=1,... | Provider |
python | ansible__ansible | lib/ansible/_internal/_errors/_error_factory.py | {
"start": 116,
"end": 3548
} | class ____(_errors.EventFactory):
"""Factory for creating `Event` instances from `BaseException` instances on the controller."""
def _get_msg(self, exception: BaseException) -> str | None:
from ansible.errors import AnsibleError
if not isinstance(exception, AnsibleError):
return su... | ControllerEventFactory |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/parsers/__init__.py | {
"start": 1741,
"end": 2792
} | class ____(ControllerNamespaceParser, TypeParser):
"""Composite argument parser for the controller when delegation is supported."""
def get_stateless_parsers(self) -> dict[str, Parser]:
"""Return a dictionary of type names and type parsers."""
parsers: dict[str, Parser] = dict(
orig... | DelegatedControllerParser |
python | PrefectHQ__prefect | tests/input/test_actions.py | {
"start": 4377,
"end": 4975
} | class ____:
async def test_implicit_flow_run(self, flow_run_context):
await create_flow_run_input(key="key", value="value")
assert await read_flow_run_input(key="key") == "value"
async def test_explicit_flow_run(self, flow_run):
await create_flow_run_input(key="key", value="value", flow... | TestReadFlowRunInput |
python | pytorch__pytorch | torch/_dynamo/debug_utils.py | {
"start": 18852,
"end": 22794
} | class ____:
def __init__(self, save_dir: Optional[str] = None, *, pbar: Optional[tqdm] = None):
# If None, we will generate random data instead. It's important
# to natively support this use case as it will allow people to
# share repros without including the real data, if the problem
... | InputReader |
python | davidhalter__jedi | jedi/inference/gradual/base.py | {
"start": 9150,
"end": 11251
} | class ____:
def __init__(self, class_value, lazy_base_class, generics_manager):
self._class_value = class_value
self._lazy_base_class = lazy_base_class
self._generics_manager = generics_manager
@iterator_to_value_set
def infer(self):
for base in self._lazy_base_class.infer()... | _LazyGenericBaseClass |
python | huggingface__transformers | tests/models/pvt_v2/test_modeling_pvt_v2.py | {
"start": 1740,
"end": 4960
} | class ____(ModelTesterMixin):
def __init__(
self,
parent,
batch_size=13,
image_size=None,
num_channels=3,
num_encoder_blocks=4,
depths=[2, 2, 2, 2],
sr_ratios=[8, 4, 2, 1],
hidden_sizes=[16, 32, 64, 128],
downsampling_rates=[1, 4, 8, 16... | PvtV2ModelTester |
python | protocolbuffers__protobuf | python/google/protobuf/descriptor.py | {
"start": 8073,
"end": 10261
} | class ____(DescriptorBase):
"""Common class for descriptors that can be nested."""
def __init__(
self,
options,
options_class_name,
name,
full_name,
file,
containing_type,
serialized_start=None,
serialized_end=None,
serialized_options=None,
):
"""Co... | _NestedDescriptorBase |
python | dagster-io__dagster | python_modules/dagster/dagster/_grpc/types.py | {
"start": 7878,
"end": 10952
} | class ____(
NamedTuple(
"_ExecuteStepArgs",
[
# Deprecated, only needed for back-compat since it can be pulled from the DagsterRun
("job_origin", JobPythonOrigin),
("run_id", str),
("step_keys_to_execute", Optional[Sequence[str]]),
("instan... | ExecuteStepArgs |
python | getsentry__sentry | src/sentry/analytics/events/groupowner_assignment.py | {
"start": 78,
"end": 341
} | class ____(analytics.Event):
organization_id: int
project_id: int
group_id: int
new_assignment: bool
user_id: int | None = None
group_owner_type: int
method: str | None = None
analytics.register(GroupOwnerAssignment)
| GroupOwnerAssignment |
python | wandb__wandb | wandb/util.py | {
"start": 4723,
"end": 24752
} | class ____(types.ModuleType):
def __getattribute__(self, name: str) -> Any:
state = object.__getattribute__(self, "__lazy_module_state__")
state.load()
return object.__getattribute__(self, name)
def __setattr__(self, name: str, value: Any) -> None:
state = object.__getattribute_... | LazyModule |
python | fastai__fastai | fastai/text/core.py | {
"start": 5262,
"end": 11501
} | class ____:
"A wrapper around `tok` which applies `rules`, then tokenizes, then applies `post_rules`"
def __init__(self, tok, rules=None, post_rules=None):
self.rules = L(ifnone(rules, defaults.text_proc_rules))
self.post_f = compose(*L(ifnone(post_rules, defaults.text_postproc_rules)))
... | TokenizeWithRules |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 73947,
"end": 79188
} | class ____(Request):
"""
Update existing artifacts (search by key/mode) and add new ones
:param task: Task ID
:type task: str
:param artifacts: Artifacts to add or update
:type artifacts: Sequence[Artifact]
:param force: If set to True then both new and running task artifacts can be
... | AddOrUpdateArtifactsRequest |
python | langchain-ai__langchain | libs/partners/qdrant/tests/integration_tests/common.py | {
"start": 1164,
"end": 2188
} | class ____(Embeddings):
"""Fake embeddings which remember all the texts seen so far to return consistent
vectors for the same texts.
"""
def __init__(self, dimensionality: int = 10) -> None:
self.known_texts: list[str] = []
self.dimensionality = dimensionality
def embed_documents(s... | ConsistentFakeEmbeddings |
python | pypa__warehouse | tests/unit/accounts/test_views.py | {
"start": 207594,
"end": 218775
} | class ____:
def test_already_logged_in(self, pyramid_request):
pyramid_request.user = UserFactory.create()
pyramid_request.route_path = pretend.call_recorder(lambda route: f"/{route}")
result = views.confirm_login(pyramid_request)
assert isinstance(result, HTTPSeeOther)
asser... | TestConfirmLogin |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI036.py | {
"start": 9119,
"end": 9513
} | class ____:
@overload
def __exit__(self, exc_typ: type[BaseException] | None, exc: None, tb: None) -> None: ... # PYI036
@overload
def __exit__(self, exc_typ: object, exc: Exception, tb: builtins.TracebackType) -> None: ... # PYI036
def __exit__(self, exc_typ: type[BaseException] | None, exc: Base... | UnacceptableOverload2 |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 1048748,
"end": 1049016
} | class ____(sgqlc.types.Type, HovercardContext):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("viewer",)
viewer = sgqlc.types.Field(sgqlc.types.non_null(User), graphql_name="viewer")
| ViewerHovercardContext |
python | django__django | tests/model_fields/models.py | {
"start": 3416,
"end": 3506
} | class ____(models.Model):
value = models.SmallAutoField(primary_key=True)
| SmallAutoModel |
python | pypa__hatch | tests/project/test_frontend.py | {
"start": 10792,
"end": 12056
} | class ____:
def test_default(self, temp_dir, temp_dir_data, platform, global_application):
project_dir = temp_dir / "project"
project_dir.mkdir()
(project_dir / "pyproject.toml").write_text(
"""\
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]... | TestHatchGetBuildDeps |
python | django__django | django/template/defaulttags.py | {
"start": 13060,
"end": 13517
} | class ____(Node):
def __init__(self, format_string, asvar=None):
self.format_string = format_string
self.asvar = asvar
def render(self, context):
tzinfo = timezone.get_current_timezone() if settings.USE_TZ else None
formatted = date(datetime.now(tz=tzinfo), self.format_string)
... | NowNode |
python | getsentry__sentry | src/sentry/sentry_apps/external_requests/select_requester.py | {
"start": 973,
"end": 1191
} | class ____(TypedDict, total=False):
# Each contained Sequence of strings is of length 2 i.e ["label", "value"]
choices: Sequence[Annotated[Sequence[str], 2]]
defaultValue: str
@dataclass
| SelectRequesterResult |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride4.py | {
"start": 746,
"end": 931
} | class ____(BaseA[_TSource]):
def method1(
self, mapper: Callable[[_TSource, _T3], _TResult], other: BaseA[_T3]
) -> BaseA[_TResult]:
return SubclassA2()
| SubclassA2 |
python | huggingface__transformers | src/transformers/models/audioflamingo3/modular_audioflamingo3.py | {
"start": 4970,
"end": 12741
} | class ____(VoxtralForConditionalGeneration):
_tp_plan = None
_pp_plan = None
_keep_in_fp32_modules_strict = None
def __init__(self, config):
super().__init__(config)
def get_audio_features(
self, input_features: torch.FloatTensor, input_features_mask: torch.Tensor
) -> torch.Fl... | AudioFlamingo3ForConditionalGeneration |
python | lepture__authlib | authlib/jose/rfc7517/base_key.py | {
"start": 285,
"end": 3358
} | class ____:
"""This is the base class for a JSON Web Key."""
kty = "_"
ALLOWED_PARAMS = ["use", "key_ops", "alg", "kid", "x5u", "x5c", "x5t", "x5t#S256"]
PRIVATE_KEY_OPS = [
"sign",
"decrypt",
"unwrapKey",
]
PUBLIC_KEY_OPS = [
"verify",
"encrypt",
... | Key |
python | streamlit__streamlit | lib/tests/streamlit/logger_test.py | {
"start": 909,
"end": 2959
} | class ____(unittest.TestCase):
"""Logger Unittest class."""
def test_set_log_level_by_constant(self):
"""Test streamlit.logger.set_log_level."""
data = [
logging.CRITICAL,
logging.ERROR,
logging.WARNING,
logging.INFO,
logging.DEBUG,
... | LoggerTest |
python | django__django | tests/servers/tests.py | {
"start": 6206,
"end": 6437
} | class ____(LiveServerThread):
def _create_server(self, connections_override=None):
return WSGIServer(
(self.host, self.port), QuietWSGIRequestHandler, allow_reuse_address=False
)
| LiveServerSingleThread |
python | scikit-learn__scikit-learn | sklearn/preprocessing/_encoders.py | {
"start": 18882,
"end": 51166
} | class ____(_BaseEncoder):
"""
Encode categorical features as a one-hot numeric array.
The input to this transformer should be an array-like of integers or
strings, denoting the values taken on by categorical (discrete) features.
The features are encoded using a one-hot (aka 'one-of-K' or 'dummy')
... | OneHotEncoder |
python | google__jax | jax/_src/pallas/mosaic_gpu/lowering.py | {
"start": 3295,
"end": 3674
} | class ____:
axis_names: _AxisNames
lowering_semantics: mgpu.LoweringSemantics
@property
def arrival_multiplier(self) -> int:
return (
WARPGROUP_SIZE
if self.lowering_semantics == mgpu.LoweringSemantics.Lane
else 1
)
AnyBarrier = mgpu.Barrier | mgpu.ClusterBarrier
@dataclasse... | ResourceEstimatorContext |
python | jazzband__django-simple-history | simple_history/registry_tests/tests.py | {
"start": 3500,
"end": 6544
} | class ____(TestCase):
def test_tracked_abstract_base(self):
self.assertEqual(
sorted(
f.attname for f in TrackedWithAbstractBase.history.model._meta.fields
),
sorted(
[
"id",
"history_id",
... | TestTrackingInheritance |
python | realpython__materials | bulk-file-rename-tool-python/source_code_step_2/rprename/views.py | {
"start": 153,
"end": 314
} | class ____(QWidget, Ui_Window):
def __init__(self):
super().__init__()
self._setupUI()
def _setupUI(self):
self.setupUi(self)
| Window |
python | apache__airflow | airflow-core/tests/unit/serialization/test_dag_serialization.py | {
"start": 158620,
"end": 160311
} | class ____:
"""Test schema defaults functionality."""
def test_get_schema_defaults_operator(self):
"""Test getting schema defaults for operator type."""
schema_defaults = SerializedBaseOperator.get_schema_defaults("operator")
assert isinstance(schema_defaults, dict)
# Should c... | TestSchemaDefaults |
python | huggingface__transformers | src/transformers/models/sam3/configuration_sam3.py | {
"start": 15456,
"end": 20328
} | class ____(PreTrainedConfig):
r"""
Configuration class to store the configuration of a [`Sam3Model`].
Instantiating a configuration defaults will yield a similar configuration to that of SAM 3
[facebook/sam3](https://huggingface.co/facebook/sam3) architecture.
This is the main configuration class ... | Sam3Config |
python | google__jax | jax/_src/pjit.py | {
"start": 52959,
"end": 66270
} | class ____:
val: Any
def __hash__(self):
return hash(self.__class__)
def __eq__(self, other):
return isinstance(other, IgnoreKey) # ignore self.val!
def pjit_check_aval_sharding(
shardings, flat_avals, names: Sequence[str],
what_aval: str, allow_uneven_sharding: bool,
allow_partial_manual: ... | IgnoreKey |
python | kamyu104__LeetCode-Solutions | Python/search-in-a-sorted-array-of-unknown-size.py | {
"start": 32,
"end": 531
} | class ____(object):
def search(self, reader, target):
"""
:type reader: ArrayReader
:type target: int
:rtype: int
"""
left, right = 0, 19999
while left <= right:
mid = left + (right-left)//2
response = reader.get(mid)
if res... | Solution |
python | pytorch__pytorch | test/test_mps.py | {
"start": 15550,
"end": 16968
} | class ____(TestCaseMPS):
def test_mps_memory_leak_detection(self):
l = []
@self.wrap_with_mps_memory_check
def no_leak():
pass
# Trigger an intentional memory leak
@self.wrap_with_mps_memory_check
def leak_gpu0():
# increasing to 8MB to force... | TestMemoryLeak |
python | tensorflow__tensorflow | tensorflow/python/autograph/operators/control_flow.py | {
"start": 27025,
"end": 46556
} | class ____(object):
"""Verifies Python loops for TF-specific limits."""
__slots__ = (
'iterations',
'check_inefficient_unroll',
'check_op_count_after_iteration',
'ops_before_iteration',
)
def __init__(self):
self.iterations = 1
self.check_inefficient_unroll = WARN_INEFFICIE... | _PythonLoopChecker |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 294199,
"end": 294847
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("EnterpriseOutsideCollaboratorEdge"), graphql_name="edges"
)
... | EnterpriseOutsideCollaboratorConnection |
python | walkccc__LeetCode | solutions/3556. Sum of Largest Prime Substrings/3556.py | {
"start": 0,
"end": 441
} | class ____:
def sumOfLargestPrimes(self, s: str) -> int:
primes = set()
n = len(s)
for i in range(n):
for j in range(i + 1, n + 1):
num = int(s[i:j])
if num not in primes and self._isPrime(num):
primes.add(num)
top3 = sorted(primes, reverse=True)[:3]
return sum(to... | Solution |
python | astral-sh__uv | scripts/benchmark/src/benchmark/__init__.py | {
"start": 286,
"end": 1931
} | class ____(typing.NamedTuple):
name: str
"""The benchmark to run."""
commands: list[Command]
"""The commands to benchmark."""
warmup: int | None
"""The number of warmup runs to perform."""
min_runs: int | None
"""The minimum number of runs to perform."""
runs: int | None
"""T... | Hyperfine |
python | getsentry__sentry | src/sentry/api/endpoints/chunk.py | {
"start": 1863,
"end": 2068
} | class ____(BytesIO):
def __init__(self, file):
data = GzipFile(fileobj=file, mode="rb").read()
self.size = len(data)
self.name = file.name
super().__init__(data)
| GzipChunk |
python | kamyu104__LeetCode-Solutions | Python/time-needed-to-inform-all-employees.py | {
"start": 76,
"end": 895
} | class ____(object):
def numOfMinutes(self, n, headID, manager, informTime):
"""
:type n: int
:type headID: int
:type manager: List[int]
:type informTime: List[int]
:rtype: int
"""
children = collections.defaultdict(list)
for child, parent in en... | Solution |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_unary_operand_type.py | {
"start": 215,
"end": 1595
} | class ____:
def __invert__(self):
return 42
def __pos__(self):
return 42
def __neg__(self):
return 42
def these_are_good():
negative = -1
negative1 = -1.0
positive = +1
positive2 = +1.0
inverted = ~1
not_int = not 1
not_float = not 2.0
not_string = n... | Implemented |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_index.py | {
"start": 1102,
"end": 1209
} | class ____:
def __index__(self):
print("raise some error")
raise NotImplementedError
| Index6 |
python | ApeWorX__ape | tests/functional/test_exceptions.py | {
"start": 5694,
"end": 7474
} | class ____:
def test_close_match(self):
net = "sepolai"
error = NetworkNotFoundError(net, ecosystem="ethereum", options=("sepolia",))
actual = str(error)
expected = f"No network in 'ethereum' named '{net}'. Did you mean 'sepolia'?"
assert actual == expected
def test_no_c... | TestNetworkNotFoundError |
python | fluentpython__example-code | attic/descriptors/doc_descriptor.py | {
"start": 813,
"end": 1378
} | class ____:
"""A documented descriptor"""
def __init__(self, documentation):
self.__doc__ = documentation
cls_name = self.__class__.__name__
self.storage_name = '_{}_{:x}'.format(cls_name, id(self))
def __get__(self, instance, owner):
"""The __get__ method"""
if ins... | DocDescriptor |
python | great-expectations__great_expectations | tests/integration/metrics/column/test_distinct_values.py | {
"start": 683,
"end": 2030
} | class ____:
@parameterize_batch_for_data_sources(
data_source_configs=get_pandas_data_sources(),
data=DATA_FRAME,
)
def test_distinct_values_pandas(self, batch_for_datasource: Batch) -> None:
metric = ColumnDistinctValues(column=COLUMN_NAME)
metric_result = batch_for_datasour... | TestColumnDistinctValues |
python | pytorch__pytorch | test/test_overrides.py | {
"start": 46009,
"end": 46254
} | class ____(TestCase):
""" Regression test for gh-47069 """
def test_newones(self):
t = torch.tensor([1, 2]).as_subclass(SubTensor2)
n = t.new_ones((1, 2))
self.assertEqual(type(n), SubTensor2)
| TestGradNewOnesOverride |
python | neetcode-gh__leetcode | python/0560-subarray-sum-equals-k.py | {
"start": 0,
"end": 508
} | class ____:
def subarraySum(self, nums: List[int], k: int) -> int:
count = 0
sum = 0
dic = {}
dic[0] = 1
for i in range(len(nums)):
sum += nums[i]
if sum-k in dic:
count += dic[sum-k]
dic[sum] = dic.get(sum, 0)+1
ret... | Solution |
python | getsentry__sentry | tests/sentry/rules/conditions/test_level_event.py | {
"start": 229,
"end": 2871
} | class ____(RuleTestCase):
rule_cls = LevelCondition
def test_render_label(self) -> None:
rule = self.get_rule(data={"match": MatchType.EQUAL, "level": "30"})
assert rule.render_label() == "The event's level is equal to warning"
def test_equals(self) -> None:
event = self.store_even... | LevelConditionTest |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 244287,
"end": 244597
} | class ____(_PrintableStructure):
_fields_ = [
('version', c_uint),
('numMetrics', c_uint),
('sample1', c_nvmlGpmSample_t),
('sample2', c_nvmlGpmSample_t),
('metrics', c_nvmlGpmMetric_t * NVML_GPM_METRIC_MAX)
]
NVML_GPM_METRICS_GET_VERSION = 1
| c_nvmlGpmMetricsGet_t |
python | numba__numba | docs/source/conf.py | {
"start": 10763,
"end": 11554
} | class ____(SphinxDirective):
def run(self):
# Generate a warning admonition to contain the deprecation notice
warning = nodes.admonition(classes=["warning"])
warning += nodes.title(text="CUDA Built-in Target deprecation notice")
# Parse CUDA deprecation text so that the link and ref... | CudaDeprecated |
python | Textualize__textual | docs/examples/styles/scrollbars2.py | {
"start": 385,
"end": 569
} | class ____(App):
CSS_PATH = "scrollbars2.tcss"
def compose(self):
yield Label(TEXT * 10)
if __name__ == "__main__":
app = Scrollbar2App()
app.run()
| Scrollbar2App |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/pipes/clients/emr_containers.py | {
"start": 1318,
"end": 11182
} | class ____(PipesClient, TreatAsResourceParam):
"""A pipes client for running workloads on AWS EMR Containers.
Args:
client (Optional[boto3.client]): The boto3 AWS EMR containers client used to interact with AWS EMR Containers.
context_injector (Optional[PipesContextInjector]): A context injecto... | PipesEMRContainersClient |
python | pennersr__django-allauth | allauth/headless/mfa/response.py | {
"start": 2088,
"end": 2315
} | class ____(APIResponse):
def __init__(self, request, authenticators):
data = [_authenticator_data(authenticator) for authenticator in authenticators]
super().__init__(request, data=data)
| AuthenticatorsResponse |
python | scipy__scipy | scipy/io/matlab/_mio5.py | {
"start": 5201,
"end": 15942
} | class ____(MatFileReader):
''' Reader for Mat 5 mat files
Adds the following attribute to base class
uint16_codec - char codec to use for uint16 char arrays
(defaults to system default codec)
Uses variable reader that has the following standard interface (see
abstract class in ``miobase``:... | MatFile5Reader |
python | wandb__wandb | wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/read_directory_changes.py | {
"start": 4931,
"end": 5262
} | class ____(BaseObserver):
"""
Observer thread that schedules watching directories and dispatches
calls to event handlers.
"""
def __init__(self, timeout=DEFAULT_OBSERVER_TIMEOUT):
BaseObserver.__init__(self, emitter_class=WindowsApiEmitter,
timeout=timeout)
| WindowsApiObserver |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.