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 | modin-project__modin | asv_bench/benchmarks/benchmarks.py | {
"start": 24962,
"end": 25254
} | class ____:
param_names = ["shape"]
params = [
get_benchmark_shapes("TimeDescribe"),
]
def setup(self, shape):
self.df = generate_dataframe("int", *shape, RAND_LOW, RAND_HIGH)
def time_describe(self, shape):
execute(self.df.describe())
| TimeDescribe |
python | pytorch__pytorch | test/dynamo/test_guard_serialization.py | {
"start": 2641,
"end": 2725
} | class ____(torch.nn.Module):
def forward(self, x):
return x + 2
| FlatModule |
python | huggingface__transformers | src/transformers/models/t5gemma/modular_t5gemma.py | {
"start": 2008,
"end": 9932
} | class ____(Gemma2Config):
r"""
This is the configuration class to store the configuration of a [`T5GemmaModuleModel`]. It is used to instantiate an T5GemmaModule
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a simi... | T5GemmaModuleConfig |
python | justquick__django-activity-stream | actstream/drf/serializers.py | {
"start": 249,
"end": 2274
} | class ____(serializers.RelatedField):
"""
Expands related fields to use other Serializer. Similar to the AS1 JSON spec
"""
def to_representation(self, value):
return registered_serializers[value.__class__](value).data
DEFAULT_SERIALIZER = serializers.ModelSerializer
def serializer_factory(mo... | ExpandRelatedField |
python | python__mypy | mypy/checker.py | {
"start": 403043,
"end": 403932
} | class ____(BoolTypeQuery):
"""Find type components that are not valid for an inferred type.
These include <Erased> type, and any uninhabited types resulting from failed
(ambiguous) type inference.
"""
def __init__(self) -> None:
super().__init__(ANY_STRATEGY)
def visit_uninhabited_typ... | InvalidInferredTypes |
python | great-expectations__great_expectations | contrib/experimental/great_expectations_experimental/expectations/expect_day_sum_to_be_close_to_equivalent_week_day_mean.py | {
"start": 624,
"end": 9442
} | class ____(QueryExpectation):
"""Expect the daily sums of the given column to be close to the average sums calculated 4 weeks back.
This metric expects daily sums of the given column, to be close to the average sums calculated 4 weeks back,
respective to the specific day of the week.
The expectation fa... | ExpectDaySumToBeCloseToEquivalentWeekDayMean |
python | numba__numba | numba/cuda/tests/cudapy/test_dispatcher.py | {
"start": 3652,
"end": 16983
} | class ____(CUDATestCase):
"""Most tests based on those in numba.tests.test_dispatcher."""
def test_coerce_input_types(self):
# Do not allow unsafe conversions if we can still compile other
# specializations.
c_add = cuda.jit(add_kernel)
# Using a complex128 allows us to represe... | TestDispatcher |
python | great-expectations__great_expectations | great_expectations/execution_engine/sqlalchemy_batch_data.py | {
"start": 549,
"end": 19233
} | class ____(BatchData):
"""A class which represents a SQL alchemy batch, with properties including the construction of the batch itself
and several getters used to access various properties.""" # noqa: E501 # FIXME CoP
# Instantiating SqlAlchemyBatchData with table_name and schema_name
@overload
de... | SqlAlchemyBatchData |
python | google__pytype | pytype/tests/test_pickle1.py | {
"start": 197,
"end": 7187
} | class ____(test_base.BaseTest):
"""Tests for loading and saving pickled files."""
def _verifyDeps(self, module, immediate_deps, late_deps):
if isinstance(module, bytes):
data = pickle_utils.DecodeAst(module)
self.assertCountEqual(dict(data.dependencies), immediate_deps)
self.assertCountEqual(... | PickleTest |
python | pytorch__pytorch | test/inductor/test_ordered_set.py | {
"start": 43867,
"end": 45309
} | class ____(TestCase):
case2method = {
"<=": "issubset",
">=": "issuperset",
}
reverse = {
"==": "==",
"!=": "!=",
"<": ">",
">": "<",
"<=": ">=",
">=": "<=",
}
def test_issubset(self):
if type(self) is TestSubsets:
... | TestSubsets |
python | bokeh__bokeh | src/bokeh/models/tickers.py | {
"start": 6179,
"end": 7194
} | class ____(ContinuousTicker):
''' Generate "nice" round ticks at any magnitude.
Creates ticks that are "base" multiples of a set of given
mantissas. For example, with ``base=10`` and
``mantissas=[1, 2, 5]``, the ticker will generate the sequence::
..., 0.1, 0.2, 0.5, 1, 2, 5, 10, 20, 50, 100, ... | AdaptiveTicker |
python | apache__airflow | providers/keycloak/tests/unit/keycloak/auth_manager/routes/test_token.py | {
"start": 978,
"end": 2251
} | class ____:
token = "token"
token_body_dict = {"username": "username", "password": "password"}
@conf_vars(
{
("api_auth", "jwt_expiration_time"): "10",
}
)
@patch("airflow.providers.keycloak.auth_manager.routes.token.create_token_for")
def test_create_token(self, moc... | TestTokenRouter |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-artifact-editor/tests/test_artifact_editor.py | {
"start": 603,
"end": 16483
} | class ____(BaseModel):
"""Simple model for basic testing."""
value: str
number: Optional[int] = None
optional_number: Optional[int] = None
@pytest.fixture
def editor():
return ArtifactEditorToolSpec(Person)
@pytest.fixture
def simple_editor():
return ArtifactEditorToolSpec(SimpleModel)
de... | SimpleModel |
python | mkdocstrings__mkdocstrings | src/mkdocstrings/_internal/handlers/base.py | {
"start": 19539,
"end": 27207
} | class ____:
"""A collection of handlers.
Do not instantiate this directly. [The plugin][mkdocstrings.MkdocstringsPlugin] will keep one instance of
this for the purpose of caching. Use [mkdocstrings.MkdocstringsPlugin.get_handler][] for convenient access.
"""
def __init__(
self,
*,
... | Handlers |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_dialect.py | {
"start": 35081,
"end": 56754
} | class ____(
fixtures.TestBase, AssertsExecutionResults, AssertsCompiledSQL
):
__only_on__ = "postgresql"
__backend__ = True
@testing.fails_on(["+psycopg2"])
def test_empty_sql_string(self, connection):
result = connection.exec_driver_sql("")
assert result._soft_closed
@testing... | MiscBackendTest |
python | ethereum__web3.py | web3/contract/base_contract.py | {
"start": 53629,
"end": 53911
} | class ____:
@staticmethod
def _raise_exception() -> NoReturn:
raise ABIFallbackNotFound("No fallback function was found in the contract ABI.")
def __getattr__(self, attr: Any) -> Callable[[], None]:
return self._raise_exception
| NonExistentFallbackFunction |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1149816,
"end": 1150237
} | class ____(ScaleInvalidDataShowAsxOffset):
"""
ScaleInvalidDataShowAsValuexOffset schema wrapper.
Parameters
----------
value : float
Offset for x-position.
"""
_schema = {"$ref": '#/definitions/ScaleInvalidDataShowAsValue<"xOffset">'}
def __init__(self, value: Optional[float]... | ScaleInvalidDataShowAsValuexOffset |
python | doocs__leetcode | solution/2500-2599/2565.Subsequence With the Minimum Score/Solution.py | {
"start": 0,
"end": 764
} | class ____:
def minimumScore(self, s: str, t: str) -> int:
def check(x):
for k in range(n):
i, j = k - 1, k + x
l = f[i] if i >= 0 else -1
r = g[j] if j < n else m + 1
if l < r:
return True
return Fal... | Solution |
python | pydantic__pydantic | tests/test_forward_ref.py | {
"start": 39907,
"end": 40261
} | class ____[T](BaseModel):
t: 'T'
"""
)
assert mod_1.Model[int].model_fields['t'].annotation is int
@pytest.mark.skipif(sys.version_info < (3, 12), reason='Test related to PEP 695 syntax.')
def test_pep695_generics_syntax_arbitrary_class(create_module) -> None:
mod_1 = create_module(
"... | Model |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/iterators.py | {
"start": 1231,
"end": 1459
} | class ____:
def __iter__(self) -> Iterator[str]:
return iter([_test_source()])
def test_custom_iter():
# TODO(T137627339): False negative with custom `__iter__`
_test_sink(next(iter(CustomIter())))
| CustomIter |
python | google__pytype | pytype/pytd/pytd.py | {
"start": 3963,
"end": 4092
} | class ____(Node):
"""A module imported into the current module, possibly with an alias."""
name: str
module_name: str
| Module |
python | sphinx-doc__sphinx | sphinx/errors.py | {
"start": 2882,
"end": 3131
} | class ____(Exception):
"""Pycode Python source code analyser error."""
def __str__(self) -> str:
res = self.args[0]
if len(self.args) > 1:
res += ' (exception was: %r)' % self.args[1]
return res
| PycodeError |
python | getsentry__sentry | tests/sentry/dynamic_sampling/tasks/test_common.py | {
"start": 585,
"end": 2274
} | class ____(BaseMetricsLayerTestCase, TestCase, SnubaTestCase):
def setUp(self) -> None:
# create 10 orgs each with 10 transactions
for i in range(10):
org = self.create_organization(f"org-{i}")
for i in range(10):
project = self.create_project(organization=or... | TestGetActiveOrgs |
python | patrick-kidger__equinox | equinox/nn/_pool.py | {
"start": 13679,
"end": 16239
} | class ____(Pool):
"""Three-dimensional downsample using the maximum over a sliding window."""
def __init__(
self,
kernel_size: int | Sequence[int],
stride: int | Sequence[int] = 1,
padding: int | Sequence[int] | Sequence[tuple[int, int]] = 0,
use_ceil: bool = False,
... | MaxPool3d |
python | huggingface__transformers | tests/test_tokenization_common.py | {
"start": 11335,
"end": 127070
} | class ____:
tokenizer_class = None
space_between_special_tokens = False
from_pretrained_kwargs = None
from_pretrained_filter = None
from_pretrained_id = None
from_pretrained_vocab_key = "vocab_file"
test_seq2seq = True
test_tokenizer_from_extractor = True
# set to True to test a sen... | TokenizerTesterMixin |
python | getsentry__sentry | tests/sentry/api/endpoints/test_project_transaction_names.py | {
"start": 428,
"end": 2526
} | class ____(APITestCase):
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.org = self.create_organization(owner=self.user)
self.project = self.create_project(organization=self.org)
self.url = reverse(
"sentry-api-0-organization-project... | ProjectTransactionNamesClusterTest |
python | fluentpython__example-code-2e | 10-dp-1class-func/strategy.py | {
"start": 1260,
"end": 1431
} | class ____(NamedTuple):
product: str
quantity: int
price: Decimal
def total(self):
return self.price * self.quantity
@dataclass(frozen=True)
| LineItem |
python | google__pytype | pytype/pytd/visitors.py | {
"start": 71033,
"end": 71162
} | class ____(Visitor):
"""Set .cls pointers to 'None'."""
def EnterClassType(self, node):
node.cls = None
| ClearClassPointers |
python | networkx__networkx | networkx/classes/tests/test_coreviews.py | {
"start": 54,
"end": 1640
} | class ____:
# node->data
def setup_method(self):
self.d = {0: {"color": "blue", "weight": 1.2}, 1: {}, 2: {"color": 1}}
self.av = nx.classes.coreviews.AtlasView(self.d)
def test_pickle(self):
view = self.av
pview = pickle.loads(pickle.dumps(view, -1))
assert view == ... | TestAtlasView |
python | has2k1__plotnine | plotnine/geoms/geom_abline.py | {
"start": 609,
"end": 3188
} | class ____(geom):
"""
Lines specified by slope and intercept
{usage}
Parameters
----------
{common_parameters}
"""
DEFAULT_AES = {
"color": "black",
"linetype": "solid",
"alpha": 1,
"size": 0.5,
}
DEFAULT_PARAMS = {
"stat": "identity",
... | geom_abline |
python | facebookresearch__faiss | contrib/datasets.py | {
"start": 9480,
"end": 10311
} | class ____(Dataset):
"""
get dataset from
https://github.com/stanis-morozov/ip-nsw#dataset
"""
def __init__(self):
Dataset.__init__(self)
self.d, self.nt, self.nb, self.nq = 100, 0, 10**6, 10000
self.metric = 'IP'
self.basedir = dataset_basedir + 'music-100/'
de... | DatasetMusic100 |
python | pyparsing__pyparsing | pyparsing/core.py | {
"start": 186926,
"end": 191629
} | class ____(ParserElement):
"""Abstract subclass of :class:`ParserElement`, for combining and
post-processing parsed tokens.
"""
def __init__(self, expr: Union[ParserElement, str], savelist: bool = False) -> None:
super().__init__(savelist)
if isinstance(expr, str_type):
expr... | ParseElementEnhance |
python | great-expectations__great_expectations | tests/execution_engine/test_sqlalchemy_execution_engine.py | {
"start": 45122,
"end": 45406
} | class ____:
def test_get_connection(self, sa):
execution_engine = SqlAlchemyExecutionEngine(connection_string="sqlite://")
with execution_engine.get_connection() as connection:
assert isinstance(connection, Connection)
@pytest.mark.unit
| TestGetConnection |
python | huggingface__transformers | src/transformers/models/data2vec/modeling_data2vec_vision.py | {
"start": 35574,
"end": 37954
} | class ____(Data2VecVisionPreTrainedModel):
def __init__(self, config: Data2VecVisionConfig) -> None:
super().__init__(config)
self.num_labels = config.num_labels
self.data2vec_vision = Data2VecVisionModel(config, add_pooling_layer=True)
# Classifier head
self.classifier = n... | Data2VecVisionForImageClassification |
python | python__mypy | mypyc/ir/ops.py | {
"start": 11640,
"end": 12031
} | class ____(Op):
"""Abstract base class for control flow operations."""
def targets(self) -> Sequence[BasicBlock]:
"""Get all basic block targets of the control operation."""
return ()
def set_target(self, i: int, new: BasicBlock) -> None:
"""Update a basic block target."""
... | ControlOp |
python | pytorch__pytorch | torch/distributed/fsdp/_trace_utils.py | {
"start": 254,
"end": 1354
} | class ____:
"""
This represents a symbolic tracing configuration.
Args:
tracer (torch.fx.Tracer): An instance of :class:`torch.fx.Tracer` to
use for symbolic tracing. The default value is the native
:class:`torch.fx.Tracer` constructed with default arguments.
How... | TracingConfig |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/hooks/test_neptune.py | {
"start": 1487,
"end": 2170
} | class ____:
def test_get_conn_returns_a_boto3_connection(self):
hook = NeptuneHook(aws_conn_id="aws_default")
assert hook.get_conn() is not None
def test_get_cluster_status(self, neptune_hook: NeptuneHook, neptune_cluster_id):
assert neptune_hook.get_cluster_status(neptune_cluster_id) i... | TestNeptuneHook |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-qdrant/destination_qdrant/destination.py | {
"start": 807,
"end": 2680
} | class ____(Destination):
indexer: Indexer
embedder: Embedder
def _init_indexer(self, config: ConfigModel):
self.embedder = create_from_config(config.embedding, config.processing)
self.indexer = QdrantIndexer(config.indexing, self.embedder.embedding_dimensions)
def write(
self, ... | DestinationQdrant |
python | kamyu104__LeetCode-Solutions | Python/find-numbers-with-even-number-of-digits.py | {
"start": 107,
"end": 668
} | class ____(object):
def __init__(self):
M = 10**5
self.__lookup = [0]
i = 10
while i < M:
self.__lookup.append(i)
i *= 10
self.__lookup.append(i)
def findNumbers(self, nums):
"""
:type nums: List[int]
:rtype: int
""... | Solution |
python | getsentry__sentry | tests/sentry/auth/test_access.py | {
"start": 42518,
"end": 43094
} | class ____(TestCase):
def test_no_access(self) -> None:
result = access.DEFAULT
assert result.sso_is_valid
assert not result.scopes
assert not result.has_team_access(Mock())
assert not result.has_team_scope(Mock(), "project:read")
assert not result.has_project_access(... | DefaultAccessTest |
python | davidhalter__jedi | jedi/api/exceptions.py | {
"start": 361,
"end": 503
} | class ____(_JediError):
"""
This error is reserved for the future, shouldn't really be happening at the
moment.
"""
| WrongVersion |
python | spack__spack | lib/spack/spack/vendor/attr/validators.py | {
"start": 11864,
"end": 13222
} | class ____:
key_validator = attrib(validator=is_callable())
value_validator = attrib(validator=is_callable())
mapping_validator = attrib(default=None, validator=optional(is_callable()))
def __call__(self, inst, attr, value):
"""
We use a callable class to be able to change the ``__repr_... | _DeepMapping |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/sensors/vertex_ai/feature_store.py | {
"start": 1253,
"end": 4486
} | class ____(BaseSensorOperator):
"""
Sensor to monitor the state of a Vertex AI Feature View sync operation.
:param feature_view_sync_name: The name of the feature view sync operation to monitor. (templated)
:param location: Required. The Cloud region in which to handle the request. (templated)
:par... | FeatureViewSyncSensor |
python | ray-project__ray | python/ray/data/_internal/execution/interfaces/op_runtime_metrics.py | {
"start": 4274,
"end": 5754
} | class ____(type):
def __init__(cls, name, bases, dict):
# NOTE: `Field.name` isn't set until the dataclass is created, so we can't
# create the metrics in `metric_field` directly.
super().__init__(name, bases, dict)
# Iterate over the attributes and methods of 'OpRuntimeMetrics'.
... | OpRuntimesMetricsMeta |
python | getsentry__sentry | src/sentry/uptime/types.py | {
"start": 3194,
"end": 3405
} | class ____:
"""
Represents data used for uptime summary
"""
total_checks: int
failed_checks: int
downtime_checks: int
missed_window_checks: int
avg_duration_us: float
| UptimeSummary |
python | pennersr__django-allauth | allauth/socialaccount/providers/notion/views.py | {
"start": 167,
"end": 745
} | class ____(OAuth2Adapter):
provider_id = "notion"
basic_auth = True
client_class = NotionOAuth2Client
authorize_url = "https://api.notion.com/v1/oauth/authorize"
access_token_url = "https://api.notion.com/v1/oauth/token" # nosec
def complete_login(self, request, app, token, **kwargs):
... | NotionOAuth2Adapter |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/triggers/test_comprehend.py | {
"start": 1350,
"end": 1734
} | class ____:
EXPECTED_WAITER_NAME: str | None = None
JOB_ID: str | None = None
def test_setup(self):
# Ensure that all subclasses have an expected waiter name set.
if self.__class__.__name__ != "TestBaseComprehendTrigger":
assert isinstance(self.EXPECTED_WAITER_NAME, str)
... | TestBaseComprehendTrigger |
python | sphinx-doc__sphinx | sphinx/domains/c/_ast.py | {
"start": 24931,
"end": 25818
} | class ____(ASTTrailingTypeSpec):
def __init__(self, names: list[str]) -> None:
assert len(names) != 0
self.names = names
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTTrailingTypeSpecFundamental):
return NotImplemented
return self.names == othe... | ASTTrailingTypeSpecFundamental |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 272299,
"end": 273263
} | class ____:
rng = np.random.default_rng(3417115752)
x, y = rng.random((2, 10))
@pytest.mark.parametrize('alternative', ['less', 'greater', 'two-sided'])
def test_ranksums_result_attributes(self, alternative):
# ranksums pval = mannwhitneyu pval w/out continuity or tie correction
res1 =... | TestRankSums |
python | pytest-dev__pytest-cov | src/pytest_cov/engine.py | {
"start": 476,
"end": 1345
} | class ____:
@staticmethod
def write(v):
pass
@contextlib.contextmanager
def _backup(obj, attr):
backup = getattr(obj, attr)
try:
setattr(obj, attr, copy.copy(backup))
yield
finally:
setattr(obj, attr, backup)
def _ensure_topdir(meth):
@functools.wraps(meth)
... | _NullFile |
python | huggingface__transformers | tests/models/siglip/test_modeling_siglip.py | {
"start": 16972,
"end": 20307
} | class ____(SiglipModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
additional_model_inputs = ["pixel_values"]
all_model_classes = (SiglipModel,) if is_torch_available() else ()
pipeline_model_mapping = {"feature-extraction": SiglipModel} if is_torch_available() else {}
test_resize_embeddings =... | SiglipModelTest |
python | huggingface__transformers | src/transformers/models/dbrx/modeling_dbrx.py | {
"start": 8392,
"end": 11872
} | class ____(nn.Module):
"""Modular DBRX attention component that can be reused across different model architectures."""
def __init__(
self,
config,
layer_idx: Optional[int] = None,
**kwargs,
):
super().__init__()
self.config = config
self.hidden_size =... | DbrxAttention |
python | django__django | tests/generic_relations_regress/models.py | {
"start": 4537,
"end": 4665
} | class ____(models.Model):
nodes = GenericRelation(Node)
related_obj = models.ForeignKey("Related", models.CASCADE)
| Content |
python | has2k1__plotnine | plotnine/geoms/geom_hline.py | {
"start": 584,
"end": 2481
} | class ____(geom):
"""
Horizontal line
{usage}
Parameters
----------
{common_parameters}
"""
DEFAULT_AES = {
"color": "black",
"linetype": "solid",
"size": 0.5,
"alpha": 1,
}
REQUIRED_AES = {"yintercept"}
DEFAULT_PARAMS = {
"stat": "i... | geom_hline |
python | astropy__astropy | astropy/io/votable/converters.py | {
"start": 28925,
"end": 29658
} | class ____(VarArray):
"""
Handles a variable-length array of complex numbers.
"""
def parse(self, value, config=None, pos=None):
if value.strip() == "":
return ma.array([]), True
parts = self._splitter(value, config, pos)
parse_parts = self._base.parse_parts
... | ComplexVarArray |
python | keras-team__keras | keras/src/backend/common/remat_test.py | {
"start": 351,
"end": 2966
} | class ____(testing.TestCase):
def setUp(self):
"""Reset global state before each test."""
global_state.clear_session()
def test_remat_scope_activation(self):
self.assertIsNone(
get_current_remat_mode()
) # Initially, no mode is active
with RematScope(mode="... | TestRematScope |
python | apache__airflow | dev/breeze/src/airflow_breeze/utils/provider_dependencies.py | {
"start": 7708,
"end": 17720
} | class ____(NamedTuple):
airflow_version: str
constraints_files: list[ConstraintsForPython]
def load_constraints() -> dict[str, AirflowVersionConstraints]:
get_console().print("[info]Loading constraints for all Airflow versions[/]")
all_constraints: dict[str, AirflowVersionConstraints] = {}
for fil... | AirflowVersionConstraints |
python | huggingface__transformers | tests/models/wav2vec2/test_feature_extraction_wav2vec2.py | {
"start": 1309,
"end": 3099
} | class ____:
def __init__(
self,
parent,
batch_size=7,
min_seq_length=400,
max_seq_length=2000,
feature_size=1,
padding_value=0.0,
sampling_rate=16000,
return_attention_mask=True,
do_normalize=True,
):
self.parent = parent
... | Wav2Vec2FeatureExtractionTester |
python | fluentpython__example-code-2e | 14-inheritance/diamond.py | {
"start": 1243,
"end": 1376
} | class ____(A, B): # <4>
def ping(self):
print(f'{self}.ping() in Leaf')
super().ping()
# end::DIAMOND_CLASSES[]
| Leaf |
python | fastai__fastai | fastai/text/core.py | {
"start": 11501,
"end": 14579
} | class ____(Transform):
"Provides a consistent `Transform` interface to tokenizers operating on `DataFrame`s and folders"
input_types = (str, list, L, tuple, Path)
def __init__(self, tok, rules=None, counter=None, lengths=None, mode=None, sep=' '):
if isinstance(tok,type): tok=tok()
store_att... | Tokenizer |
python | pytorch__pytorch | benchmarks/tensorexpr/benchmark.py | {
"start": 8617,
"end": 10883
} | class ____:
r"""
An Auxiliary class for dynamic shape benchmarks
Pre-computes input with random shapes and also
modifies the compute method so in each call the
fuser sees a different input tensor shape
"""
# Number of random inputs in an instance
SAMPLE_SIZE = 100
def __init__(sel... | DynamicShape |
python | spack__spack | lib/spack/spack/util/windows_registry.py | {
"start": 545,
"end": 5342
} | class ____:
"""
Class wrapping a Windows registry key
"""
def __init__(self, name, handle):
self.path = name
self.name = os.path.split(name)[-1]
self._handle = handle
self._keys = []
self._values = {}
@property
def values(self):
"""Returns all su... | RegistryKey |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/docstring_signature.py | {
"start": 33,
"end": 122
} | class ____:
"""B(foo, bar)"""
def __init__(self):
"""B(foo, bar, baz)"""
| B |
python | kamyu104__LeetCode-Solutions | Python/minimum-distance-between-three-equal-elements-i.py | {
"start": 79,
"end": 596
} | class ____(object):
def minimumDistance(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
INF = float("inf")
result = INF
lookup = collections.defaultdict(list)
for i, x in enumerate(nums):
lookup[x].append(i)
if len(lookup... | Solution |
python | pypa__warehouse | warehouse/accounts/interfaces.py | {
"start": 390,
"end": 437
} | class ____(TokenException):
pass
| TokenExpired |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_pretty.py | {
"start": 19712,
"end": 20035
} | class ____:
x: object
def test_pretty_prints_data_classes():
assert pretty.pretty(SomeDataClass(ReprDetector())) == "SomeDataClass(x=GOOD)"
def test_handles_cycles_in_dataclass():
x = SomeDataClass(x=1)
x.x = x
assert pretty.pretty(x) == "SomeDataClass(x=SomeDataClass(...))"
@dataclass
| SomeDataClass |
python | huggingface__transformers | src/transformers/models/git/modeling_git.py | {
"start": 46673,
"end": 57445
} | class ____(GitPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"output.weight": "git.embeddings.word_embeddings.weight"}
def __init__(self, config):
super().__init__(config)
self.git = GitModel(config)
self.output = nn.Linear(config.hidden_size, config.vocab_size)
# In... | GitForCausalLM |
python | django__django | tests/model_inheritance_regress/models.py | {
"start": 3552,
"end": 3657
} | class ____(BachelorParty):
pass
# Check concrete -> abstract -> concrete inheritance
| MessyBachelorParty |
python | pypa__twine | twine/exceptions.py | {
"start": 4934,
"end": 5038
} | class ____(TwineException):
"""Raised when a distribution is invalid."""
pass
| InvalidDistribution |
python | tensorflow__tensorflow | tensorflow/python/distribute/one_device_strategy.py | {
"start": 1692,
"end": 9341
} | class ____(distribute_lib.Strategy):
"""A distribution strategy for running on a single device.
Using this strategy will place any variables created in its scope on the
specified device. Input distributed through this strategy will be
prefetched to the specified device. Moreover, any functions called via
`st... | OneDeviceStrategy |
python | python__mypy | mypy/test/testmodulefinder.py | {
"start": 5627,
"end": 13957
} | class ____(Suite):
def setUp(self) -> None:
self.package_dir = os.path.relpath(
os.path.join(package_path, "modulefinder-site-packages")
)
package_paths = (
os.path.join(self.package_dir, "baz"),
os.path.join(self.package_dir, "..", "not-a-directory"),
... | ModuleFinderSitePackagesSuite |
python | numba__numba | numba/cuda/cudadecl.py | {
"start": 5671,
"end": 5857
} | class ____(ConcreteTemplate):
key = cuda.cbrt
cases = [
signature(types.float32, types.float32),
signature(types.float64, types.float64),
]
@register
| Cuda_cbrt |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_assorted_poly.py | {
"start": 10293,
"end": 15839
} | class ____(fixtures.MappedTest):
"""test self-referential relationships on polymorphic mappers"""
@classmethod
def define_tables(cls, metadata):
global people, managers, data
people = Table(
"people",
metadata,
Column(
"person_id",
... | RelationshipTest3 |
python | matplotlib__matplotlib | lib/matplotlib/legend_handler.py | {
"start": 7540,
"end": 8491
} | class ____(HandlerNpoints):
"""
A legend handler that shows *numpoints* in the legend, and allows them to
be individually offset in the y-direction.
"""
def __init__(self, numpoints=None, yoffsets=None, **kwargs):
"""
Parameters
----------
numpoints : int
... | HandlerNpointsYoffsets |
python | numpy__numpy | numpy/_core/tests/test_deprecations.py | {
"start": 17100,
"end": 17480
} | class ____(_DeprecationTestCase):
# Deprecated in Numpy 2.4, 2025-08, gh-27639
message = "Passing more than 2 positional arguments to np.maximum and np.minimum "
@pytest.mark.parametrize("ufunc", [np.minimum, np.maximum])
def test_extremem_3_args(self, ufunc):
self.assert_deprecated(ufunc, args... | TestTooManyArgsExtremum |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 930592,
"end": 930965
} | class ____(
sgqlc.types.Type,
Node,
AuditEntry,
OrganizationAuditEntryData,
RepositoryAuditEntryData,
):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("visibility",)
visibility = sgqlc.types.Field(
RepoAccessAuditEntryVisibilit... | RepoAccessAuditEntry |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 7948,
"end": 37265
} | class ____(FieldChannelMixin, core.FieldOrDatumDefWithConditionMarkPropFieldDefnumber):
r"""
Angle schema wrapper.
Parameters
----------
shorthand : str, dict, Sequence[str], :class:`RepeatRef`
shorthand for field, aggregate, and type
aggregate : dict, :class:`Aggregate`, :class:`Argmax... | Angle |
python | coleifer__peewee | tests/cockroachdb.py | {
"start": 348,
"end": 424
} | class ____(TestModel):
k = TextField(unique=True)
v = IntegerField()
| KV |
python | tensorflow__tensorflow | tensorflow/python/keras/saving/utils_v1/export_output.py | {
"start": 3358,
"end": 5989
} | class ____(ExportOutput):
"""Represents the output of a classification head.
Either classes or scores or both must be set.
The classes `Tensor` must provide string labels, not integer class IDs.
If only classes is set, it is interpreted as providing top-k results in
descending order.
If only scores is s... | ClassificationOutput |
python | walkccc__LeetCode | solutions/1093. Statistics from a Large Sample/1093.py | {
"start": 0,
"end": 749
} | class ____:
def sampleStats(self, count: list[int]) -> list[float]:
minimum = next((i for i, num in enumerate(count) if num), None)
maximum = next((i for i, num in reversed(
list(enumerate(count))) if num), None)
n = sum(count)
mean = sum(i * c / n for i, c in enumerate(count))
mode = coun... | Solution |
python | jazzband__django-oauth-toolkit | tests/test_password.py | {
"start": 2708,
"end": 3656
} | class ____(BaseTest):
def test_password_resource_access_allowed(self):
token_request_data = {
"grant_type": "password",
"username": "test_user",
"password": "123456",
}
auth_headers = get_basic_auth_header(self.application.client_id, CLEARTEXT_SECRET)
... | TestPasswordProtectedResource |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/events/__init__.py | {
"start": 10269,
"end": 14641
} | class ____(Enum):
UNEXPECTED_TERMINATION = "UNEXPECTED_TERMINATION"
RUN_EXCEPTION = "RUN_EXCEPTION"
STEP_FAILURE = "STEP_FAILURE"
JOB_INITIALIZATION_FAILURE = "JOB_INITIALIZATION_FAILURE"
START_TIMEOUT = "START_TIMEOUT"
RUN_WORKER_RESTART = "RUN_WORKER_RESTART"
UNKNOWN = "UNKNOWN"
def _ass... | RunFailureReason |
python | django__django | tests/generic_relations/models.py | {
"start": 3933,
"end": 4142
} | class ____(models.Model):
content_type = models.ForeignKey(ContentType, models.SET_NULL, null=True)
object_id = models.PositiveIntegerField(null=True)
content_object = GenericForeignKey()
| AllowsNullGFK |
python | tornadoweb__tornado | demos/tcpecho/server.py | {
"start": 307,
"end": 1118
} | class ____(TCPServer):
@gen.coroutine
def handle_stream(self, stream, address):
while True:
try:
data = yield stream.read_until(b"\n")
logger.info("Received bytes: %s", data)
if not data.endswith(b"\n"):
data = data + b"\n"
... | EchoServer |
python | ZoranPandovski__al-go-rithms | math/highest_common_factor/cpp/hcf.py | {
"start": 774,
"end": 1018
} | class ____(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testsimple(self):
a = hcf.hcf(40,16)
self.assertEqual(a,8)
if __name__ == '__main__':
unittest.main()
| TestHCFFunction |
python | imageio__imageio | imageio/plugins/tifffile_v3.py | {
"start": 2320,
"end": 14335
} | class ____(PluginV3):
"""Support for tifffile as backend.
Parameters
----------
request : iio.Request
A request object that represents the users intent. It provides a
standard interface for a plugin to access the various ImageResources.
Check the docs for details.
kwargs : A... | TifffilePlugin |
python | pytorch__pytorch | torch/nn/attention/varlen.py | {
"start": 546,
"end": 10101
} | class ____(NamedTuple):
"""
Request which auxiliary outputs to compute from varlen_attn.
Each field is a boolean indicating whether that auxiliary output should be computed.
"""
lse: bool = False
@torch.library.custom_op("torch_attn::_varlen_attn", mutates_args={})
def _varlen_attn(
query: t... | AuxRequest |
python | tensorflow__tensorflow | tensorflow/python/distribute/coordinator/get_task_states_test.py | {
"start": 1598,
"end": 6157
} | class ____(object): # pylint: disable=missing-docstring
def setUp(self, num_workers, num_ps):
super().setUp()
self._cluster = multi_worker_test_base.create_multi_process_cluster(
num_workers=num_workers, num_ps=num_ps, rpc_layer="grpc")
self._cluster_def = self._cluster.cluster_resolver.cluster... | GetTaskStatesTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/annotated1.py | {
"start": 396,
"end": 1247
} | class ____(struct2.Packed):
name: Annotated[str, struct2.ctype("<10s")]
serial_num: UnsignedShort
school: SignedChar
def ValueRange(a: int, b: int):
pass
T1 = Annotated[int, ValueRange(-10, 5)]
T2 = Annotated[T1, ValueRange(-20, 3)]
a: Annotated[Annotated[int, "hi"], "hi"] = 3
b: T2 = 5
TypeWithSt... | Student |
python | django__django | tests/user_commands/management/commands/mutually_exclusive_required_with_same_dest.py | {
"start": 54,
"end": 488
} | class ____(BaseCommand):
def add_arguments(self, parser):
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--for", dest="until", action="store")
group.add_argument("--until", action="store")
def handle(self, *args, **options):
for option, value in o... | Command |
python | getsentry__sentry | tests/sentry/utils/sdk_crashes/test_sdk_crash_detection_cocoa.py | {
"start": 24374,
"end": 28572
} | class ____(BaseSDKCrashDetectionMixin):
def test_hub_reported(self, mock_sdk_crash_reporter: MagicMock) -> None:
self.execute_test(
get_crash_event(function="-[SentryHub getScope]"), True, mock_sdk_crash_reporter
)
def test_sentrycrash_reported(self, mock_sdk_crash_reporter: MagicMo... | CococaSDKFunctionTestMixin |
python | docker__docker-py | docker/types/services.py | {
"start": 15835,
"end": 18284
} | class ____(dict):
"""
Used to specify the way container updates should be performed by a service.
Args:
parallelism (int): Maximum number of tasks to be updated in one
iteration (0 means unlimited parallelism). Default: 0.
delay (int): Amount of time between updates, in nanoseco... | UpdateConfig |
python | google__pytype | pytype/overlays/metaclass.py | {
"start": 2681,
"end": 3280
} | class ____(abstract.PyTDFunction):
"""Implements with_metaclass."""
@classmethod
def make(cls, ctx, module):
return super().make("with_metaclass", ctx, module)
def call(self, node, func, args, alias_map=None):
"""Creates an anonymous class to act as a metaclass."""
del func, alias_map # unused
... | WithMetaclass |
python | neetcode-gh__leetcode | python/0338-counting-bits.py | {
"start": 0,
"end": 282
} | class ____:
def countBits(self, n: int) -> List[int]:
dp = [0] * (n + 1)
offset = 1
for i in range(1, n + 1):
if offset * 2 == i:
offset = i
dp[i] = 1 + dp[i - offset]
return dp
# Another dp solution
| Solution |
python | walkccc__LeetCode | solutions/877. Stone Game/877.py | {
"start": 0,
"end": 468
} | class ____:
def stoneGame(self, piles: list[int]) -> bool:
n = len(piles)
# dp[i][j] := the maximum stones you can get more than your opponent in piles[i..j]
dp = [[0] * n for _ in range(n)]
for i, pile in enumerate(piles):
dp[i][i] = pile
for d in range(1, n):
for i in range(n - d):... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 31179,
"end": 35365
} | class ____(sgqlc.types.Enum):
"""The possible item types found in a timeline.
Enumeration Choices:
* `ADDED_TO_PROJECT_EVENT`: Represents a 'added_to_project' event
on a given issue or pull request.
* `ASSIGNED_EVENT`: Represents an 'assigned' event on any
assignable object.
* `CLOSED_... | IssueTimelineItemsItemType |
python | apache__airflow | providers/cncf/kubernetes/tests/unit/cncf/kubernetes/backcompat/test_backwards_compat_converters.py | {
"start": 1424,
"end": 9477
} | class ____:
def to_k8s_client_obj(self):
return "converted_object"
def test__convert_kube_model_object_normal_value():
obj = MockKubeModelObject()
new_class = type(obj)
result = _convert_kube_model_object(obj, new_class)
assert result == "converted_object"
def test__convert_kube_model_o... | MockKubeModelObject |
python | crytic__slither | slither/tools/mutator/__main__.py | {
"start": 3932,
"end": 15074
} | class ____(argparse.Action): # pylint: disable=too-few-public-methods
def __call__(
self, parser: Any, *args: Any, **kwargs: Any
) -> None: # pylint: disable=signature-differs
checks = _get_mutators(None)
output_mutators(checks)
parser.exit()
# endregion
#####################... | ListMutators |
python | doocs__leetcode | solution/1200-1299/1200.Minimum Absolute Difference/Solution.py | {
"start": 0,
"end": 221
} | class ____:
def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
arr.sort()
mi = min(b - a for a, b in pairwise(arr))
return [[a, b] for a, b in pairwise(arr) if b - a == mi]
| Solution |
python | python-poetry__poetry | src/poetry/console/commands/python/remove.py | {
"start": 633,
"end": 3446
} | class ____(Command):
name = "python remove"
arguments: ClassVar[list[Argument]] = [
argument("python", "The python version to remove.", multiple=True)
]
options: ClassVar[list[Option]] = [
option(
"free-threaded", "t", "Use free-threaded version if available.", flag=True
... | PythonRemoveCommand |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.