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 | django__django | django/contrib/gis/db/models/fields.py | {
"start": 12603,
"end": 14304
} | class ____(BaseSpatialField):
"""
Raster field for GeoDjango -- evaluates into GDALRaster objects.
"""
description = _("Raster Field")
geom_type = "RASTER"
geography = False
def _check_connection(self, connection):
# Make sure raster fields are used only on backends with raster
... | RasterField |
python | sympy__sympy | sympy/sets/fancysets.py | {
"start": 47627,
"end": 48187
} | class ____(CartesianComplexRegion, metaclass=Singleton):
"""
The :class:`Set` of all complex numbers
Examples
========
>>> from sympy import S, I
>>> S.Complexes
Complexes
>>> 1 + I in S.Complexes
True
See also
========
Reals
ComplexRegion
"""
is_empty =... | Complexes |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/self2.py | {
"start": 1165,
"end": 1518
} | class ____:
def set_scale(self: Self, scale: float) -> Self:
self.scale = scale
return self
@classmethod
def from_config(cls: type[Self], config: dict[str, float]) -> Self:
return cls()
def difference(self: Self, other: Self) -> float: ...
def apply(self: Self, f: Callable... | Shape2 |
python | scipy__scipy | scipy/signal/tests/test_ltisys.py | {
"start": 1334,
"end": 10695
} | class ____:
def _check(self, A, B, P, **kwargs):
"""
Perform the most common tests on the poles computed by place_poles
and return the Bunch object for further specific tests
"""
fsf = place_poles(A, B, P, **kwargs)
expected, _ = np.linalg.eig(A - np.dot(B, fsf.gain_... | TestPlacePoles |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/unit_tests/test_base_insight_streams.py | {
"start": 1741,
"end": 30635
} | class ____:
def test_init(self, api, some_config):
stream = AdsInsights(
api=api,
account_ids=some_config["account_ids"],
start_date=datetime(2010, 1, 1),
end_date=datetime(2011, 1, 1),
insights_lookback_window=28,
)
assert not str... | TestBaseInsightsStream |
python | pytorch__pytorch | torch/nn/modules/conv.py | {
"start": 75564,
"end": 78515
} | class ____(_LazyConvXdMixin, ConvTranspose3d): # type: ignore[misc]
r"""A :class:`torch.nn.ConvTranspose3d` module with lazy initialization of the ``in_channels`` argument.
The ``in_channels`` argument of the :class:`ConvTranspose3d` is inferred from
the ``input.size(1)``.
The attributes that will be ... | LazyConvTranspose3d |
python | getsentry__sentry | src/sentry/migrations/0951_delete_ds_waiver.py | {
"start": 240,
"end": 1492
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_webagg_core.py | {
"start": 4690,
"end": 14867
} | class ____(backend_agg.FigureCanvasAgg):
manager_class = _api.classproperty(lambda cls: FigureManagerWebAgg)
_timer_cls = TimerAsyncio
# Webagg and friends having the right methods, but still
# having bugs in practice. Do not advertise that it works until
# we can debug this.
supports_blit = Fa... | FigureCanvasWebAggCore |
python | facelessuser__soupsieve | tests/test_level4/test_open.py | {
"start": 49,
"end": 1484
} | class ____(util.TestCase):
"""Test open selectors."""
MARKUP = """
<!DOCTYPE html>
<html>
<body>
<details id="1">
<summary>This is closed.</summary<
<p>A closed details element.</p>
</details>
<details id="2" open>
<summary>This is open.</summary<
<p>An open details el... | TestOpen |
python | huggingface__transformers | src/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py | {
"start": 78669,
"end": 85055
} | class ____(Wav2Vec2ConformerPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.wav2vec2_conformer = Wav2Vec2ConformerModel(config)
num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
if config.use_weighted_layer_sum:
... | Wav2Vec2ConformerForXVector |
python | scipy__scipy | scipy/signal/tests/test_windows.py | {
"start": 42313,
"end": 55199
} | class ____:
"""Unit test for `scipy.signal.get_windows`. """
def test_WIN_FUNC_DATA_integrity(self):
"""Verify that the `_windows._WIN_FUNC_DATA` dict is consistent.
The keys of _WIN_FUNC_DATA are made of tuples of strings of allowed window
names. Its values are 2-tuples made up of... | TestGetWindow |
python | apache__airflow | airflow-core/src/airflow/jobs/triggerer_job_runner.py | {
"start": 28230,
"end": 30270
} | class ____(CommsDecoder[ToTriggerRunner, ToTriggerSupervisor]):
_async_writer: asyncio.StreamWriter = attrs.field(alias="async_writer")
_async_reader: asyncio.StreamReader = attrs.field(alias="async_reader")
body_decoder: TypeAdapter[ToTriggerRunner] = attrs.field(
factory=lambda: TypeAdapter(ToTri... | TriggerCommsDecoder |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/dataplex.py | {
"start": 4075,
"end": 4347
} | class ____(BaseGoogleLink):
"""Helper class for constructing Dataplex Catalog AspectTypes link."""
name = "Dataplex Catalog AspectTypes"
key = "dataplex_catalog_aspect_types_key"
format_str = DATAPLEX_CATALOG_ASPECT_TYPES_LINK
| DataplexCatalogAspectTypesLink |
python | pallets__itsdangerous | src/itsdangerous/serializer.py | {
"start": 1339,
"end": 15563
} | class ____(t.Generic[_TSerialized]):
"""A serializer wraps a :class:`~itsdangerous.signer.Signer` to
enable serializing and securely signing data other than bytes. It
can unsign to verify that the data hasn't been changed.
The serializer provides :meth:`dumps` and :meth:`loads`, similar to
:mod:`js... | Serializer |
python | django-mptt__django-mptt | tests/myapp/models.py | {
"start": 9619,
"end": 9833
} | class ____(MPTTModel):
parent = TreeForeignKey(
"self", null=True, blank=True, related_name="children", on_delete=models.CASCADE
)
not_concrete_field = FakeNotConcreteField()
| NotConcreteFieldModel |
python | spack__spack | lib/spack/spack/builder.py | {
"start": 15972,
"end": 19430
} | class ____(metaclass=BuilderMeta):
"""An interface for builders, without any phases defined. This class is exposed in the package
API, so that packagers can create a single class to define :meth:`setup_build_environment` and
:func:`spack.phase_callbacks.run_before` and :func:`spack.phase_callbacks.run_after... | BaseBuilder |
python | huggingface__transformers | src/transformers/models/vjepa2/modeling_vjepa2.py | {
"start": 35160,
"end": 36007
} | class ____(nn.Module):
"""Attentive Pooler"""
def __init__(self, config: VJEPA2Config):
super().__init__()
self.query_tokens = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
self.cross_attention_layer = VJEPA2PoolerCrossAttentionLayer(config)
self.self_attention_layers = nn... | VJEPA2AttentivePooler |
python | huggingface__transformers | src/transformers/models/vits/modeling_vits.py | {
"start": 24415,
"end": 25743
} | class ____(nn.Module):
def __init__(self, config: VitsConfig):
super().__init__()
self.half_channels = config.flow_size // 2
self.conv_pre = nn.Conv1d(self.half_channels, config.hidden_size, 1)
self.wavenet = VitsWaveNet(config, num_layers=config.prior_encoder_num_wavenet_layers)
... | VitsResidualCouplingLayer |
python | huggingface__transformers | src/transformers/pipelines/question_answering.py | {
"start": 9134,
"end": 30192
} | class ____(ChunkPipeline):
"""
Question Answering pipeline using any `ModelForQuestionAnswering`. See the [question answering
examples](../task_summary#question-answering) for more information.
Example:
```python
>>> from transformers import pipeline
>>> oracle = pipeline(model="deepset/r... | QuestionAnsweringPipeline |
python | uqfoundation__dill | dill/tests/test_classdef.py | {
"start": 5577,
"end": 8600
} | class ____(object):
__slots__ = 'y'
def __init__(self, y):
self.y = y
def test_slots():
assert dill.pickles(Y)
assert dill.pickles(y)
assert dill.pickles(Y.y)
assert dill.copy(y).y == value
assert dill.copy(Y2(value)).y == value
def test_origbases():
assert dill.copy(customIntList).__o... | Y2 |
python | streamlit__streamlit | lib/streamlit/runtime/runtime.py | {
"start": 2821,
"end": 2955
} | class ____(Exception):
"""Raised by operations on a Runtime instance that is stopped."""
@dataclass(frozen=True)
| RuntimeStoppedError |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/deprecated7.py | {
"start": 261,
"end": 498
} | class ____: ...
# This should generate an error if reportDeprecated is enabled.
ClassA()
@todo
def func1() -> None:
pass
# This should generate an error if reportDeprecated is enabled.
func1()
def func2() -> None:
pass
| ClassA |
python | doocs__leetcode | solution/0900-0999/0984.String Without AAA or BBB/Solution.py | {
"start": 0,
"end": 502
} | class ____:
def strWithout3a3b(self, a: int, b: int) -> str:
ans = []
while a and b:
if a > b:
ans.append('aab')
a, b = a - 2, b - 1
elif a < b:
ans.append('bba')
a, b = a - 1, b - 2
else:
... | Solution |
python | fastapi__sqlmodel | docs_src/tutorial/fastapi/update/tutorial002_py39.py | {
"start": 513,
"end": 2857
} | class ____(SQLModel):
name: Optional[str] = None
secret_name: Optional[str] = None
age: Optional[int] = None
password: Optional[str] = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
connect_args = {"check_same_thread": False}
engine = create_engine(sqlite_url, echo... | HeroUpdate |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol38.py | {
"start": 138,
"end": 342
} | class ____(Protocol):
def __neg__(self) -> "Negatable": ...
def func1(x: Negatable) -> None: ...
func1(0)
def func2(val: Literal[0, 1]):
func1(val)
T = TypeVar("T", covariant=True)
| Negatable |
python | donnemartin__system-design-primer | solutions/system_design/mint/mint_mapreduce.py | {
"start": 55,
"end": 1475
} | class ____(MRJob):
def __init__(self, categorizer):
self.categorizer = categorizer
...
def current_year_month(self):
"""Return the current year and month."""
...
def extract_year_month(self, timestamp):
"""Return the year and month portions of the timestamp."""
... | SpendingByCategory |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 264103,
"end": 264613
} | class ____(sgqlc.types.Input):
"""Ways in which lists of projects can be ordered upon return."""
__schema__ = github_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(sgqlc.types.non_null(ProjectV2OrderField), graphql_name="field")
"""The field in which to order projects by.... | ProjectV2Order |
python | hynek__structlog | tests/processors/test_renderers.py | {
"start": 15347,
"end": 18368
} | class ____:
def test_custom_formatter(self):
"""
The exception formatter can be changed.
"""
formatter = ExceptionRenderer(lambda _: "There is no exception!")
try:
raise CustomError("test")
except CustomError as e:
exc = e
assert form... | TestFormatExcInfo |
python | pytorch__pytorch | test/test_torch.py | {
"start": 290822,
"end": 473833
} | class ____(TestCase):
exact_dtype = True
def test_dir(self):
dir(torch)
def test_wildcard_import(self):
exec('from torch import *')
def test_newaxis_numpy_comparison(self):
def run_test(tensor, *idx):
npt = tensor.numpy()
self.assertEqual(tensor[idx], n... | TestTorch |
python | mlflow__mlflow | mlflow/types/llm.py | {
"start": 13250,
"end": 13802
} | class ____(_BaseDataclass):
"""
Definition for tools that can be called by the model.
Args:
function (:py:class:`FunctionToolDefinition`): The definition of a function tool.
type (str): The type of the tool. Currently only "function" is supported.
"""
function: FunctionToolDefiniti... | ToolDefinition |
python | dagster-io__dagster | python_modules/libraries/dagster-sling/dagster_sling_tests/test_sling_replication_collection_component.py | {
"start": 7798,
"end": 11968
} | class ____(TestTranslation):
def test_translation(
self,
attributes: Mapping[str, Any],
assertion: Callable[[AssetSpec], bool],
key_modifier: Optional[Callable[[AssetKey], AssetKey]],
) -> None:
defs = build_component_defs_for_test(
SlingReplicationCollectionC... | TestSlingTranslation |
python | getsentry__sentry | src/sentry/pipeline/types.py | {
"start": 472,
"end": 612
} | class ____:
"""Attributes to describe a pipeline in analytics records."""
event_type: str
pipeline_type: str
| PipelineAnalyticsEntry |
python | django__django | tests/postgres_tests/test_constraints.py | {
"start": 1169,
"end": 11723
} | class ____(PostgreSQLTestCase):
get_opclass_query = """
SELECT opcname, c.relname FROM pg_opclass AS oc
JOIN pg_index as i on oc.oid = ANY(i.indclass)
JOIN pg_class as c on c.oid = i.indexrelid
WHERE c.relname = %s
"""
def get_constraints(self, table):
"""Get the con... | SchemaTests |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/random_sharpness_test.py | {
"start": 177,
"end": 2143
} | class ____(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_layer(self):
self.run_layer_test(
layers.RandomSharpness,
init_kwargs={
"factor": 0.75,
"seed": 1,
},
input_shape=(8, 3, 4, 3),
suppo... | RandomSharpnessTest |
python | PyCQA__isort | isort/output.py | {
"start": 27663,
"end": 28660
} | class ____(str):
comments: list[str]
def __new__(
cls: type["_LineWithComments"], value: Any, comments: list[str]
) -> "_LineWithComments":
instance = super().__new__(cls, value)
instance.comments = comments
return instance
def _ensure_newline_before_comment(output: list[s... | _LineWithComments |
python | getsentry__sentry | src/sentry/analytics/base.py | {
"start": 218,
"end": 883
} | class ____(Service, abc.ABC):
__all__ = ("record", "validate")
event_manager = default_manager
def record(self, event: Event) -> None:
"""
Record an event. Must be an instance of a subclass of `Event`.
>>> analytics.record(
... MyEvent(
... some_id=123,... | Analytics |
python | sympy__sympy | sympy/logic/boolalg.py | {
"start": 23252,
"end": 26836
} | class ____(LatticeOp, BooleanFunction):
"""
Logical OR function
It evaluates its arguments in order, returning true immediately
when an argument is true, and false if they are all false.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy import Or
>>> x | y
x | y... | Or |
python | keon__algorithms | tests/test_strings.py | {
"start": 11049,
"end": 12502
} | class ____(unittest.TestCase):
"""[summary]
Test for the file roman_to_int.py
Arguments:
unittest {[type]} -- [description]
"""
def test_roman_to_int(self):
self.assertEqual(621, roman_to_int("DCXXI"))
self.assertEqual(1, roman_to_int("I"))
self.assertEqual(3999, ro... | TestRomanToInt |
python | neetcode-gh__leetcode | python/0136-single-number.py | {
"start": 0,
"end": 152
} | class ____:
def singleNumber(self, nums: List[int]) -> int:
res = 0
for n in nums:
res = n ^ res
return res
| Solution |
python | ray-project__ray | python/ray/llm/_internal/serve/engines/vllm/vllm_engine.py | {
"start": 4464,
"end": 20989
} | class ____(LLMEngine):
def __init__(
self,
llm_config: LLMConfig,
):
"""Create a vLLM Engine class
Args:
llm_config: The llm configuration for this engine
"""
super().__init__(llm_config)
self.llm_config = llm_config
if vllm is None:... | VLLMEngine |
python | chardet__chardet | chardet/charsetgroupprober.py | {
"start": 1248,
"end": 3849
} | class ____(CharSetProber):
def __init__(self, lang_filter: LanguageFilter = LanguageFilter.NONE) -> None:
super().__init__(lang_filter=lang_filter)
self._active_num = 0
self.probers: List[CharSetProber] = []
self._best_guess_prober: Optional[CharSetProber] = None
def reset(self)... | CharSetGroupProber |
python | scikit-learn__scikit-learn | sklearn/preprocessing/_data.py | {
"start": 69537,
"end": 76334
} | class ____(OneToOneFeatureMixin, TransformerMixin, BaseEstimator):
"""Normalize samples individually to unit norm.
Each sample (i.e. each row of the data matrix) with at least one
non zero component is rescaled independently of other samples so
that its norm (l1, l2 or inf) equals one.
This transf... | Normalizer |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/benchmarks/parameter_value_benchmark.py | {
"start": 1389,
"end": 6354
} | class ____(benchmark_base.DatasetBenchmarkBase):
"""Benchmarks to compare effect of different parameter values on the performance."""
def _benchmark_map(self, num_parallel_calls, buffer_size):
k = 1024 * 1024
dataset = dataset_ops.Dataset.from_tensors(
(np.random.rand(1, 4 * k), np.random.rand(4 * ... | ParameterValueBenchmark |
python | wandb__wandb | wandb/vendor/pygments/lexers/jvm.py | {
"start": 24936,
"end": 31868
} | class ____(RegexLexer):
"""
For `Ioke <http://ioke.org/>`_ (a strongly typed, dynamic,
prototype based programming language) source.
.. versionadded:: 1.4
"""
name = 'Ioke'
filenames = ['*.ik']
aliases = ['ioke', 'ik']
mimetypes = ['text/x-iokesrc']
tokens = {
'interpola... | IokeLexer |
python | pytorch__pytorch | test/test_expanded_weights.py | {
"start": 8829,
"end": 24911
} | class ____(TestCase):
def _compare_ew_and_for_loop_per_sample_grads(self, op, sample_input, reduction):
input = sample_input.input
args = sample_input.args
kwargs = sample_input.kwargs
batch_size = input.shape[0] if len(input.shape) > 1 else 1
# get per sample grads with Exp... | TestExpandedWeightFunctional |
python | run-llama__llama_index | llama-index-core/llama_index/core/graph_stores/simple.py | {
"start": 2071,
"end": 6148
} | class ____(GraphStore):
"""
Simple Graph Store.
In this graph store, triplets are stored within a simple, in-memory dictionary.
Args:
simple_graph_store_data_dict (Optional[dict]): data dict
containing the triplets. See SimpleGraphStoreData
for more details.
"""
... | SimpleGraphStore |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_tags.py | {
"start": 420,
"end": 17645
} | class ____(APITestCase, OccurrenceTestMixin, SnubaTestCase):
def setUp(self) -> None:
super().setUp()
self.min_ago = before_now(minutes=1).isoformat()
def test_simple(self) -> None:
user = self.create_user()
org = self.create_organization()
team = self.create_team(organi... | OrganizationTagsTest |
python | jina-ai__jina | tests/integration/deployments/test_deployment.py | {
"start": 12613,
"end": 15197
} | class ____(Executor):
@requests
def foo(self, docs, **kwargs):
docs.texts = ['foo' for _ in docs]
@requests(on='/bar')
def bar(self, docs, **kwargs):
docs.texts = ['bar' for _ in docs]
@pytest.fixture()
def exposed_port():
port = random_port()
yield port
@pytest.fixture(auto... | MyServeExec |
python | apache__airflow | providers/redis/tests/unit/redis/sensors/test_redis_key.py | {
"start": 1054,
"end": 1711
} | class ____:
def setup_method(self):
args = {"owner": "airflow", "start_date": DEFAULT_DATE}
self.dag = DAG("test_dag_id", schedule=None, default_args=args)
self.mock_context = MagicMock()
@patch("airflow.providers.redis.hooks.redis.RedisHook.get_conn")
def test_execute_operator(se... | TestRedisPublishOperator |
python | joke2k__faker | faker/providers/internet/zh_TW/__init__.py | {
"start": 90,
"end": 516
} | class ____(InternetProvider):
user_name_formats = (
"{{last_romanized_name}}.{{first_romanized_name}}",
"{{first_romanized_name}}.{{last_romanized_name}}",
"{{first_romanized_name}}##",
"?{{last_romanized_name}}",
)
tlds = ("com", "com", "com", "net", "org", "tw", "tw", "tw")... | Provider |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 549257,
"end": 549681
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("CreatedPullRequestContrib... | CreatedPullRequestContributionEdge |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/ragged_placeholder_op_test.py | {
"start": 1109,
"end": 3435
} | class ____(test_util.TensorFlowTestCase,
parameterized.TestCase):
@parameterized.parameters([
# dtype, ragged_rank, value_shape, name -> expected
(dtypes.int32, 0, [5], None,
'Tensor("Placeholder:0", shape=(5,), dtype=int32)'),
(dtypes.int32, 1, [], 'ph', 'tf.Ra... | RaggedPlaceholderOpTest |
python | astropy__astropy | astropy/modeling/tests/test_statistics.py | {
"start": 396,
"end": 1822
} | class ____:
"""Tests for leastsquare with pre-specified number of dimensions."""
@classmethod
def setup_class(cls):
cls.model1D = Identity(n_inputs=1)
cls.model2D = Identity(n_inputs=2) | Mapping((0,), n_inputs=2)
cls.model3D = Identity(n_inputs=3) | Mapping((0,), n_inputs=3)
... | TestLeastSquare_XD |
python | pydantic__pydantic | tests/mypy/modules/plugin_fail.py | {
"start": 930,
"end": 1035
} | class ____(BaseModel):
model_config = ConfigDict(extra=1) # type: ignore[typeddict-item]
| BadExtraModel |
python | pandas-dev__pandas | pandas/tests/indexes/datetimes/test_constructors.py | {
"start": 40194,
"end": 44083
} | class ____:
def test_dti_constructor_preserve_dti_freq(self):
rng = date_range("1/1/2000", "1/2/2000", freq="5min")
rng2 = DatetimeIndex(rng)
assert rng.freq == rng2.freq
def test_explicit_none_freq(self):
# Explicitly passing freq=None is respected
rng = date_range("1/... | TestTimeSeries |
python | numba__numba | numba/cuda/descriptor.py | {
"start": 207,
"end": 985
} | class ____(TargetDescriptor):
def __init__(self, name):
self.options = CUDATargetOptions
# The typing and target contexts are initialized only when needed -
# this prevents an attempt to load CUDA libraries at import time on
# systems that might not have them present.
self._t... | CUDATarget |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1185034,
"end": 1185333
} | class ____(sgqlc.types.Type, GitSignature):
"""Represents a GPG signature on a Commit or Tag."""
__schema__ = github_schema
__field_names__ = ("key_id",)
key_id = sgqlc.types.Field(String, graphql_name="keyId")
"""Hex-encoded ID of the key that signed this object."""
| GpgSignature |
python | tox-dev__tox | src/tox/config/of_type.py | {
"start": 617,
"end": 1242
} | class ____(ABC, Generic[T]): # noqa: PLW1641
"""Abstract base class for configuration definitions."""
def __init__(self, keys: Iterable[str], desc: str) -> None:
self.keys = keys
self.desc = desc
@abstractmethod
def __call__(self, conf: Config, loaders: list[Loader[T]], args: ConfigLo... | ConfigDefinition |
python | huggingface__transformers | tests/models/ovis2/test_modeling_ovis2.py | {
"start": 5026,
"end": 7444
} | class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
"""
Model tester for `Ovis2ForConditionalGeneration`.
"""
all_model_classes = (
(
Ovis2Model,
Ovis2ForConditionalGeneration,
)
if is_torch_available()
els... | Ovis2ModelTest |
python | fastai__fastai | fastai/vision/augment.py | {
"start": 43393,
"end": 43711
} | class ____(SpaceTfm):
"Apply `fs` to the logits"
order = 40
def __init__(self,
fs:Callable|MutableSequence, # Transformation functions applying in logit space,
**kwargs
):
super().__init__(fs, TensorImage.lighting, **kwargs)
# %% ../../nbs/09_vision.augment.ipynb 203
| LightingTfm |
python | great-expectations__great_expectations | contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/expectations/expect_column_values_to_be_equal_to_or_greater_than_profile_min.py | {
"start": 2735,
"end": 6900
} | class ____(ColumnMapExpectation):
"""Expect the column values to be greater than or equal to the minimum value of the respective column within the DataProfiler report.
This function builds upon the custom column map expectations of Great Expectations. This function asks a yes/no question of each row in the use... | ExpectColumnValuesToBeEqualToOrGreaterThanProfileMin |
python | Pylons__pyramid | src/pyramid/request.py | {
"start": 4881,
"end": 12087
} | class ____(
BaseRequest,
URLMethodsMixin,
CallbackMethodsMixin,
InstancePropertyMixin,
LocalizerRequestMixin,
SecurityAPIMixin,
AuthenticationAPIMixin,
ViewMethodsMixin,
):
"""
A subclass of the :term:`WebOb` Request class. An instance of
this class is created by the :term:`... | Request |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_itertools.py | {
"start": 113883,
"end": 116332
} | class ____(__TestCase):
def test_keywords_in_subclass(self):
# count is not subclassable...
testcases = [
(repeat, (1, 2), [1, 1]),
(zip, ([1, 2], 'ab'), [(1, 'a'), (2, 'b')]),
(filter, (None, [0, 1]), [1]),
(filterfalse, (None, [0, 1]), [0]),
... | SubclassWithKwargsTest |
python | apache__airflow | airflow-core/src/airflow/models/hitl.py | {
"start": 2558,
"end": 2684
} | class ____(TypedDict):
"""Typed dict for saving a Human-in-the-loop user information."""
id: str
name: str
| HITLUser |
python | doocs__leetcode | solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/Solution.py | {
"start": 0,
"end": 216
} | class ____:
def searchRange(self, nums: List[int], target: int) -> List[int]:
l = bisect_left(nums, target)
r = bisect_left(nums, target + 1)
return [-1, -1] if l == r else [l, r - 1]
| Solution |
python | numpy__numpy | numpy/testing/_private/utils.py | {
"start": 1618,
"end": 53151
} | class ____(Exception):
'''Raise this exception to mark a test as a known failing test.'''
pass
KnownFailureTest = KnownFailureException # backwards compat
verbose = 0
NUMPY_ROOT = pathlib.Path(np.__file__).parent
try:
np_dist = importlib.metadata.distribution('numpy')
except importlib.metadata.PackageN... | KnownFailureException |
python | openai__openai-python | src/openai/types/beta/realtime/input_audio_buffer_commit_event.py | {
"start": 233,
"end": 493
} | class ____(BaseModel):
type: Literal["input_audio_buffer.commit"]
"""The event type, must be `input_audio_buffer.commit`."""
event_id: Optional[str] = None
"""Optional client-generated ID used to identify this event."""
| InputAudioBufferCommitEvent |
python | huggingface__transformers | src/transformers/models/exaone4/modeling_exaone4.py | {
"start": 2239,
"end": 2966
} | class ____(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""
Exaone4RMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states):
inpu... | Exaone4RMSNorm |
python | donnemartin__interactive-coding-challenges | math_probability/sum_two/test_sum_two.py | {
"start": 18,
"end": 479
} | class ____(unittest.TestCase):
def test_sum_two(self):
solution = Solution()
self.assertRaises(TypeError, solution.sum_two, None)
self.assertEqual(solution.sum_two(5, 7), 12)
self.assertEqual(solution.sum_two(-5, -7), -12)
self.assertEqual(solution.sum_two(5, -7), -2)
... | TestSumTwo |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 55667,
"end": 56283
} | class ____(BaseModel):
"""
Request body for Clear Task Instances endpoint.
"""
model_config = ConfigDict(
extra="forbid",
)
new_state: TaskInstanceState | None = None
note: Annotated[Note | None, Field(title="Note")] = None
include_upstream: Annotated[bool | None, Field(title="I... | PatchTaskInstanceBody |
python | networkx__networkx | networkx/classes/tests/test_reportviews.py | {
"start": 36337,
"end": 36620
} | class ____(TestMultiDegreeView):
GRAPH = nx.MultiDiGraph
dview = nx.reportviews.DiMultiDegreeView
def test_repr(self):
dv = self.G.degree()
rep = "DiMultiDegreeView({0: 1, 1: 4, 2: 2, 3: 4, 4: 2, 5: 1})"
assert repr(dv) == rep
| TestDiMultiDegreeView |
python | gevent__gevent | src/greentest/3.14/test_urllib2.py | {
"start": 13002,
"end": 14231
} | class ____:
def __init__(self):
self.level = 0
self.req_headers = []
self.data = None
self.raise_on_endheaders = False
self.sock = None
self._tunnel_headers = {}
def __call__(self, host, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
self.host = host
se... | MockHTTPClass |
python | Pylons__pyramid | src/pyramid/testing.py | {
"start": 805,
"end": 1019
} | class ____:
__parent__ = None
__name__ = None
def __init__(self, request):
if 'bfg.routes.matchdict' in request:
self.__dict__.update(request['bfg.routes.matchdict'])
| DummyRootFactory |
python | doocs__leetcode | solution/3700-3799/3745.Maximize Expression of Three Elements/Solution.py | {
"start": 0,
"end": 307
} | class ____:
def maximizeExpressionOfThree(self, nums: List[int]) -> int:
a = b = -inf
c = inf
for x in nums:
if x < c:
c = x
if x >= a:
a, b = x, a
elif x > b:
b = x
return a + b - c
| Solution |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataplex.py | {
"start": 39491,
"end": 46999
} | class ____(GoogleCloudBaseOperator):
"""
Runs an on-demand execution of a DataScan.
:param project_id: Required. The ID of the Google Cloud project that the lake belongs to.
:param region: Required. The ID of the Google Cloud region that the lake belongs to.
:param data_scan_id: Required. Data Qual... | DataplexRunDataQualityScanOperator |
python | python-openxml__python-docx | src/docx/oxml/table.py | {
"start": 30780,
"end": 33094
} | class ____(BaseOxmlElement):
"""``<w:trPr>`` element, defining table row properties."""
get_or_add_trHeight: Callable[[], CT_Height]
_tag_seq = (
"w:cnfStyle",
"w:divId",
"w:gridBefore",
"w:gridAfter",
"w:wBefore",
"w:wAfter",
"w:cantSplit",
... | CT_TrPr |
python | walkccc__LeetCode | solutions/2953. Count Complete Substrings/2953.py | {
"start": 0,
"end": 1033
} | class ____:
def countCompleteSubstrings(self, word: str, k: int) -> int:
uniqueLetters = len(set(word))
return sum(self._countCompleteStrings(word, k, windowSize)
for windowSize in range(k, k * uniqueLetters + 1, k))
def _countCompleteStrings(self, word: str, k: int, windowSize: int) -> int:... | Solution |
python | pytorch__pytorch | torch/testing/_internal/opinfo/definitions/fft.py | {
"start": 925,
"end": 29445
} | class ____(SpectralFuncInfo):
"""
An OpInfo for a Python reference of an elementwise unary operation.
"""
def __init__(
self,
name, # the stringname of the callable Python reference
*,
op=None, # the function variant of the operation, populated as torch.<name> if None
... | SpectralFuncPythonRefInfo |
python | getsentry__sentry | src/sentry/utils/locking/manager.py | {
"start": 132,
"end": 568
} | class ____:
def __init__(self, backend: LockBackend) -> None:
self.backend = backend
def get(
self, key: str, duration: int, routing_key: str | None = None, name: str | None = None
) -> Lock:
"""
Retrieve a ``Lock`` instance.
"""
metrics.incr("lockmanager.get... | LockManager |
python | google__jax | jax/_src/pjit.py | {
"start": 35700,
"end": 52959
} | class ____:
def __repr__(self): return "pytree leaf"
@util.cache(max_size=4096, trace_context_in_key=False)
def _process_in_axis_resources(in_shardings_treedef, in_shardings_leaves,
in_layouts_treedef, in_layouts_leaves,
in_avals, in_tree, debug_info: co... | PytreeLeaf |
python | faif__python-patterns | patterns/creational/builder.py | {
"start": 2223,
"end": 2343
} | class ____:
def __repr__(self) -> str:
return "Floor: {0.floor} | Size: {0.size}".format(self)
| ComplexBuilding |
python | scrapy__scrapy | tests/test_pipeline_files.py | {
"start": 24834,
"end": 25865
} | class ____:
@inlineCallbacks
def test_persist(self):
data = b"TestFTPFilesStore: \xe2\x98\x83"
buf = BytesIO(data)
meta = {"foo": "bar"}
path = "full/filename"
with MockFTPServer() as ftp_server:
store = FTPFilesStore(ftp_server.url("/"))
empty_dic... | TestFTPFileStore |
python | pypa__warehouse | warehouse/macaroons/caveats/__init__.py | {
"start": 1700,
"end": 2238
} | class ____(Caveat):
normalized_names: list[StrictStr]
def verify(self, request: Request, context: Any, permission: str) -> Result:
if not isinstance(context, Project):
return Failure("project-scoped token used outside of a project context")
if context.normalized_name not in self.no... | ProjectName |
python | pypa__hatch | tests/backend/builders/test_wheel.py | {
"start": 15389,
"end": 18995
} | class ____:
def test_default(self, isolation):
builder = WheelBuilder(str(isolation))
assert builder.config.shared_scripts == builder.config.shared_scripts == {}
def test_invalid_type(self, isolation):
config = {"tool": {"hatch": {"build": {"targets": {"wheel": {"shared-scripts": 42}}}... | TestSharedScripts |
python | PrefectHQ__prefect | src/prefect/blocks/notifications.py | {
"start": 12336,
"end": 15074
} | class ____(AbstractAppriseNotificationBlock):
"""Enables sending notifications via Twilio SMS.
Find more on sending Twilio SMS messages in the [docs](https://www.twilio.com/docs/sms).
Examples:
Load a saved `TwilioSMS` block and send a message:
```python
from prefect.blocks.notifica... | TwilioSMS |
python | django-import-export__django-import-export | import_export/resources.py | {
"start": 1414,
"end": 2270
} | class ____:
def __init__(self, resource, instance, new):
self.left = Diff._read_field_values(resource, instance)
self.right = []
self.new = new
def compare_with(self, resource, instance):
self.right = Diff._read_field_values(resource, instance)
def as_html(self):
da... | Diff |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-file/llama_index/readers/file/ipynb/base.py | {
"start": 214,
"end": 1552
} | class ____(BaseReader):
"""Image parser."""
def __init__(
self,
parser_config: Optional[Dict] = None,
concatenate: bool = False,
):
"""Init params."""
self._parser_config = parser_config
self._concatenate = concatenate
def load_data(
self,
... | IPYNBReader |
python | mlflow__mlflow | mlflow/genai/label_schemas/label_schemas.py | {
"start": 1929,
"end": 2814
} | class ____(InputType):
"""A multi-select dropdown for collecting assessments from stakeholders.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to use it.
"""
options: list[str]
"""List of available options for the multi-sel... | InputCategoricalList |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/events.py | {
"start": 1466,
"end": 1874
} | class ____(NamedTuple):
"""An AssetKey with an (optional) partition key. Refers either to a non-partitioned asset or a
partition of a partitioned asset.
"""
asset_key: AssetKey
partition_key: Optional[str] = None
# This is currently used only for the asset partition wipe codepath. In the future, ... | AssetKeyPartitionKey |
python | weaviate__weaviate-python-client | weaviate/users/sync.py | {
"start": 384,
"end": 601
} | class ____(_UsersExecutor[ConnectionSync]):
def __init__(self, connection: ConnectionSync):
super().__init__(connection)
self.db = _UsersDB(connection)
self.oidc = _UsersOIDC(connection)
| _Users |
python | ray-project__ray | python/ray/llm/_internal/common/base_pydantic.py | {
"start": 136,
"end": 1162
} | class ____(BaseModel):
# NOTE(edoakes): Pydantic protects the namespace `model_` by default and prints
# warnings if you define fields with that prefix. However, we added such fields
# before this behavior existed. To avoid spamming user-facing logs, we mark the
# namespace as not protected. This means ... | BaseModelExtended |
python | PrefectHQ__prefect | src/prefect/tasks.py | {
"start": 3277,
"end": 9991
} | class ____(TypedDict, total=False):
"""
A TypedDict representing all available task configuration options.
This can be used with `Unpack` to provide type hints for **kwargs.
"""
name: Optional[str]
description: Optional[str]
tags: Optional[Iterable[str]]
version: Optional[str]
cach... | TaskOptions |
python | ray-project__ray | python/ray/serve/tests/test_config_files/sqlalchemy.py | {
"start": 42,
"end": 288
} | class ____:
def __init__(self):
import pymysql
from sqlalchemy import create_engine
pymysql.install_as_MySQLdb()
create_engine("mysql://some_wrong_url:3306").connect()
app = TestDeployment.bind()
| TestDeployment |
python | ray-project__ray | python/ray/train/tests/test_trainer_restore.py | {
"start": 1092,
"end": 1543
} | class ____(RuntimeError):
pass
def _failing_train_fn(config):
checkpoint = train.get_checkpoint()
it = 1
if checkpoint:
it = load_dict_checkpoint(checkpoint)["it"] + 1
print(f"\nLoading from checkpoint, which is at iteration {it}...\n")
with create_dict_checkpoint({"it": it}) as ch... | _TestSpecificError |
python | sanic-org__sanic | sanic/exceptions.py | {
"start": 20575,
"end": 21532
} | class ____(HTTPException):
"""403 Forbidden
Args:
message (Optional[Union[str, bytes]], optional): The message to be sent to the client. If `None`
then the HTTP status 'Bad Request' will be sent. Defaults to `None`.
quiet (Optional[bool], optional): When `True`, the error traceback ... | Forbidden |
python | scikit-learn__scikit-learn | sklearn/utils/tests/test_param_validation.py | {
"start": 1518,
"end": 24407
} | class ____(BaseEstimator):
"""An estimator to test the validation of estimator parameters."""
_parameter_constraints: dict = {"a": [Real]}
def __init__(self, a):
self.a = a
@_fit_context(prefer_skip_nested_validation=True)
def fit(self, X=None, y=None):
pass
@pytest.mark.paramet... | _Estimator |
python | docker__docker-py | tests/integration/api_image_test.py | {
"start": 3389,
"end": 4012
} | class ____(BaseAPIIntegrationTest):
def test_remove(self):
container = self.client.create_container(TEST_IMG, ['touch', '/test'])
id = container['Id']
self.client.start(id)
self.tmp_containers.append(id)
res = self.client.commit(id)
assert 'Id' in res
img_id =... | RemoveImageTest |
python | django-haystack__django-haystack | test_haystack/test_fields.py | {
"start": 18940,
"end": 19508
} | class ____(TestCase):
def test_init(self):
try:
foo = FacetCharField(model_attr="foo")
foo_exact = FacetCharField(facet_for="bar")
except:
self.fail()
self.assertEqual(foo.facet_for, None)
self.assertEqual(foo_exact.null, True)
self.assert... | FacetCharFieldTestCase |
python | getsentry__sentry | tests/sentry/workflow_engine/endpoints/test_organization_available_action_index.py | {
"start": 1117,
"end": 22846
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-available-action-index"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.registry = Registry[type[ActionHandler]](enable_reverse_lookup=False)
self.registry_patcher = patch(
"s... | OrganizationAvailableActionAPITestCase |
python | ray-project__ray | python/ray/serve/_private/logging_utils.py | {
"start": 1192,
"end": 1409
} | class ____(CoreContextFilter):
def filter(self, record: logging.LogRecord) -> bool:
if should_skip_context_filter(record):
return True
return super().filter(record)
| ServeCoreContextFilter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.