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 | numpy__numpy | benchmarks/benchmarks/bench_function_base.py | {
"start": 2991,
"end": 3571
} | class ____(Benchmark):
def setup(self):
self.d = np.arange(20000)
self.e = self.d.copy()
self.cond = [(self.d > 4), (self.d < 2)]
self.cond_large = [(self.d > 4), (self.d < 2)] * 10
def time_select(self):
np.select(self.cond, [self.d, self.e])
def time_select_larger... | Select |
python | google__pytype | pytype/abstract/abstract_utils_test.py | {
"start": 195,
"end": 2181
} | class ____(test_base.UnitTest):
def setUp(self):
super().setUp()
options = config.Options.create(python_version=self.python_version)
self._ctx = test_utils.make_context(options)
def test_basic(self):
v1 = self._ctx.program.NewVariable(
[self._ctx.convert.unsolvable], [], self._ctx.root_nod... | GetViewsTest |
python | tensorflow__tensorflow | tensorflow/python/framework/test_combinations.py | {
"start": 822,
"end": 2385
} | class ____(test.TestCase, parameterized.TestCase):
@combinations.generate(
combinations.combine(mode=["graph", "eager"],
optimizer=[AdamOptimizer(),
GradientDescentOptimizer()]))
def testOptimizer(self, optimizer):
... f(optimizer)...
This wil... | AdditionExample |
python | scrapy__scrapy | tests/test_commands.py | {
"start": 532,
"end": 704
} | class ____(ScrapyCommand):
def short_desc(self) -> str:
return ""
def run(self, args: list[str], opts: argparse.Namespace) -> None:
pass
| EmptyCommand |
python | numba__llvmlite | llvmlite/ir/instructions.py | {
"start": 20695,
"end": 21666
} | class ____(Instruction):
def __init__(self, parent, typ, name, flags=()):
super(PhiInstr, self).__init__(parent, typ, "phi", (), name=name,
flags=flags)
self.incomings = []
def descr(self, buf):
incs = ', '.join('[{0}, {1}]'.format(v.get_reference(... | PhiInstr |
python | tornadoweb__tornado | tornado/websocket.py | {
"start": 26055,
"end": 27760
} | class ____:
def __init__(
self,
persistent: bool,
max_wbits: Optional[int],
compression_options: Optional[Dict[str, Any]] = None,
) -> None:
if max_wbits is None:
max_wbits = zlib.MAX_WBITS
# There is no symbolic constant for the minimum wbits value.
... | _PerMessageDeflateCompressor |
python | getsentry__sentry | src/sentry/issues/attributes.py | {
"start": 1095,
"end": 1215
} | class ____(Enum):
CREATED = "created"
UPDATED = "updated"
DELETED = "deleted"
@dataclasses.dataclass
| Operation |
python | EpistasisLab__tpot | tpot/builtin_modules/genetic_encoders.py | {
"start": 388,
"end": 1664
} | class ____(TransformerMixin, BaseEstimator ):
"""This class contains the function definition for encoding the input features as a Dominant genetic model.
The encoding used is AA(0)->1, Aa(1)->1, aa(2)->0. """
def fit(self, X, y=None):
"""Do nothing and return the estimator unchanged.
Dummy ... | DominantEncoder |
python | scikit-learn__scikit-learn | sklearn/utils/tests/test_estimator_checks.py | {
"start": 16467,
"end": 16750
} | class ____(LogisticRegression):
def decision_function(self, X):
return super().decision_function(X) + 1
def __sklearn_tags__(self):
tags = super().__sklearn_tags__()
tags.classifier_tags.poor_score = True
return tags
| PoorScoreLogisticRegression |
python | hynek__structlog | tests/test_stdlib.py | {
"start": 12511,
"end": 14510
} | class ____:
def test_formats_tuple(self):
"""
Positional arguments as simple types are rendered.
"""
formatter = PositionalArgumentsFormatter()
event_dict = formatter(
None,
None,
{"event": "%d %d %s", "positional_args": (1, 2, "test")},
... | TestPositionalArgumentsFormatter |
python | getsentry__sentry | tests/sentry/api/bases/test_organization.py | {
"start": 23156,
"end": 24278
} | class ____(BaseOrganizationEndpointTest):
def setUp(self) -> None:
self.project = self.create_project(organization=self.org)
self.env_1 = self.create_environment(project=self.project)
self.env_2 = self.create_environment(project=self.project)
def run_test(self, expected_envs, env_names=... | GetEnvironmentsTest |
python | bokeh__bokeh | src/bokeh/io/webdriver.py | {
"start": 5397,
"end": 8059
} | class ____:
reuse: bool
kind: DriverKind | None
current: WebDriver | None
_drivers: set[WebDriver]
def __init__(self, *, kind: DriverKind | None = None, reuse: bool = True) -> None:
self.kind = kind
self.reuse = reuse
self.current = None
self._drivers = set()
... | _WebdriverState |
python | PrefectHQ__prefect | src/prefect/server/database/orm_models.py | {
"start": 32557,
"end": 32840
} | class ____(Base):
tag: Mapped[str]
concurrency_limit: Mapped[int]
active_slots: Mapped[list[str]] = mapped_column(
JSON, server_default="[]", default=list
)
__table_args__: Any = (sa.Index("uq_concurrency_limit__tag", "tag", unique=True),)
| ConcurrencyLimit |
python | astropy__astropy | astropy/utils/masked/tests/test_function_helpers.py | {
"start": 2079,
"end": 2362
} | class ____(MaskedArraySetup):
def check(self, func, *args, **kwargs):
o = func(self.ma, *args, **kwargs)
expected = func(self.a, *args, **kwargs)
assert_array_equal(o.unmasked, expected)
assert_array_equal(o.mask, self.mask_a)
| InvariantMaskTestSetup |
python | pytorch__pytorch | torch/utils/_filelock.py | {
"start": 157,
"end": 1530
} | class ____(base_FileLock):
"""
This behaves like a normal file lock.
However, it adds waitcounters for acquiring and releasing the filelock
as well as for the critical region within it.
pytorch.filelock.enter - While we're acquiring the filelock.
pytorch.filelock.region - While we're holding t... | FileLock |
python | pytorch__pytorch | test/distributed/tensor/test_init.py | {
"start": 464,
"end": 1307
} | class ____(DTensorTestBase):
def _run_init_op(self, init_op, *args, **kwargs):
device_mesh = self.build_device_mesh()
shard_spec = [Shard(0)]
input_size = (8, 4)
input_tensor = torch.randn(*input_size, device=self.device_type)
dtensor = DTensor.from_local(input_tensor, device... | DTensorInitOpsTest |
python | automl__auto-sklearn | autosklearn/metalearning/metafeatures/metafeatures.py | {
"start": 26086,
"end": 27864
} | class ____(MetaFeature):
def _calculate(self, X, y, logger, feat_type):
import sklearn.discriminant_analysis
if type(y) in ("binary", "multiclass"):
kf = sklearn.model_selection.StratifiedKFold(n_splits=5)
else:
kf = sklearn.model_selection.KFold(n_splits=5)
... | LandmarkLDA |
python | getsentry__sentry | src/sentry/services/filestore/s3.py | {
"start": 9060,
"end": 25088
} | class ____(Storage):
"""
Amazon Simple Storage Service using Boto3
This storage backend supports opening files in read or write
mode and supports streaming(buffering) data in chunks to S3
when writing.
"""
# XXX: note that this file reads entirely into memory before the first
# read ha... | S3Boto3Storage |
python | pytorch__pytorch | test/dynamo/test_repros.py | {
"start": 18422,
"end": 20397
} | class ____(torch.nn.Module):
# Highly simplified version of maml.meta.Meta.finetuning
def __init__(self) -> None:
super().__init__()
self.net = FakeMamlInner()
self.update_step_test = 10
self.update_lr = 0.4
def forward(self, x_spt, y_spt, x_qry, y_qry):
querysz = x_... | PartialMaml |
python | ansible__ansible | lib/ansible/executor/interpreter_discovery.py | {
"start": 483,
"end": 3632
} | class ____(Exception):
def __init__(self, message, interpreter_name, discovery_mode):
super(InterpreterDiscoveryRequiredError, self).__init__(message)
self.interpreter_name = interpreter_name
self.discovery_mode = discovery_mode
def discover_interpreter(action, interpreter_name, discovery_... | InterpreterDiscoveryRequiredError |
python | davidhalter__jedi | jedi/inference/value/instance.py | {
"start": 1194,
"end": 1534
} | class ____(ParamName):
def __init__(self, instance, function_value, tree_name):
super().__init__(
function_value, tree_name, arguments=None)
self._instance = instance
def infer(self):
return ValueSet([self._instance])
def matches_signature(self):
return True
| InstanceExecutedParamName |
python | pandas-dev__pandas | asv_bench/benchmarks/algos/isin.py | {
"start": 9062,
"end": 9274
} | class ____:
def setup(self):
t = tuple(range(1000))
self.series = Series([t] * 1000)
self.values = [t]
def time_isin(self):
self.series.isin(self.values)
| IsInWithLongTupples |
python | Pylons__pyramid | tests/test_testing.py | {
"start": 12026,
"end": 14880
} | class ____(unittest.TestCase):
def _callFUT(self, **kw):
from pyramid.testing import setUp
return setUp(**kw)
def tearDown(self):
from pyramid.threadlocal import manager
manager.clear()
getSiteManager.reset()
def _assertSMHook(self, hook):
result = getSite... | Test_setUp |
python | keras-team__keras | keras/src/ops/image.py | {
"start": 14544,
"end": 20209
} | class ____(Operation):
def __init__(
self,
interpolation="bilinear",
fill_mode="constant",
fill_value=0,
data_format=None,
*,
name=None,
):
super().__init__(name=name)
self.interpolation = interpolation
self.fill_mode = fill_mode
... | AffineTransform |
python | psf__requests | tests/test_utils.py | {
"start": 10512,
"end": 11643
} | class ____:
def test_none(self):
encodings = get_encodings_from_content("")
assert not len(encodings)
@pytest.mark.parametrize(
"content",
(
# HTML5 meta charset attribute
'<meta charset="UTF-8">',
# HTML4 pragma directive
'<meta h... | TestContentEncodingDetection |
python | scipy__scipy | scipy/optimize/tests/test_optimize.py | {
"start": 39648,
"end": 39754
} | class ____(CheckOptimizeParameterized):
use_wrapper = False
disp = False
| TestOptimizeNoWrapperNoDisp |
python | pallets__quart | src/quart/cli.py | {
"start": 9487,
"end": 13729
} | class ____(click.Group):
"""This works similar to a regular click :class:`~click.Group` but it
changes the behavior of the :meth:`command` decorator so that it
automatically wraps the functions in :func:`with_appcontext`.
Not to be confused with :class:`QuartGroup`.
"""
def command(self, *args... | AppGroup |
python | getsentry__sentry | tests/sentry/integrations/slack/test_unfurl.py | {
"start": 6683,
"end": 55425
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
# We're redefining project to ensure that the individual tests have unique project ids.
# Sharing project ids across tests could result in some race conditions
self.project = self.create_project()
self._integratio... | UnfurlTest |
python | PrefectHQ__prefect | src/prefect/logging/loggers.py | {
"start": 11268,
"end": 13427
} | class ____(logging.Handler):
"""A context manager that collects logs for the duration of the context
Example:
```python
import logging
from prefect.logging import LogEavesdropper
with LogEavesdropper("my_logger") as eavesdropper:
logging.getLogger("my_logger").info... | LogEavesdropper |
python | great-expectations__great_expectations | tests/actions/test_core_actions.py | {
"start": 23535,
"end": 32243
} | class ____:
@pytest.mark.unit
def test_equality(self):
"""I kow, this one seems silly. But this was a bug."""
a = SlackNotificationAction(name="my_action", slack_webhook="test", notify_on="all")
b = SlackNotificationAction(name="my_action", slack_webhook="test", notify_on="all")
... | TestSlackNotificationAction |
python | pytorch__pytorch | test/mobile/model_test/quantization_ops.py | {
"start": 37,
"end": 1805
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.embedding = torch.ao.nn.quantized.Embedding(
num_embeddings=10, embedding_dim=12
)
self.embedding_input = torch.tensor([9, 6, 5, 7, 8, 8, 9, 2, 8])
self.func = torch.ao.nn.quantized.Q... | GeneralQuantModule |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_P.py | {
"start": 4095,
"end": 5941
} | class ____(Benchmark):
r"""
Penalty 1 objective function.
This class defines the Penalty 1 [1]_ global optimization problem. This is a
imultimodal minimization problem defined as follows:
.. math::
f_{\text{Penalty01}}(x) = \frac{\pi}{30} \left\{10 \sin^2(\pi y_1)
+ \sum_{i=1}^{n... | Penalty01 |
python | jazzband__django-model-utils | tests/test_inheritance_iterable.py | {
"start": 194,
"end": 583
} | class ____(TestCase):
def test_prefetch(self) -> None:
qs = InheritanceManagerTestChild1.objects.all().prefetch_related(
Prefetch(
'normal_field',
queryset=InheritanceManagerTestParent.objects.all(),
to_attr='normal_field_prefetched'
)
... | InheritanceIterableTest |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/transfers/sheets_to_gcs.py | {
"start": 1223,
"end": 5393
} | class ____(BaseOperator):
"""
Writes Google Sheet data into Google Cloud Storage.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:GoogleSheetsToGCSOperator`
:param spreadsheet_id: The Google Sheet ID to interact with.
:p... | GoogleSheetsToGCSOperator |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_image50.py | {
"start": 315,
"end": 907
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("image50.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workbook(... | TestCompareXLSXFiles |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/shortcuts/progress_bar/base.py | {
"start": 9954,
"end": 14402
} | class ____(Generic[_CounterItem]):
"""
An individual counter (A progress bar can have multiple counters).
"""
def __init__(
self,
progress_bar: ProgressBar,
data: Iterable[_CounterItem] | None = None,
label: AnyFormattedText = "",
remove_when_done: bool = False,
... | ProgressBarCounter |
python | PrefectHQ__prefect | src/integrations/prefect-ray/tests/test_task_runners.py | {
"start": 5045,
"end": 18158
} | class ____:
@pytest.fixture(params=task_runner_setups)
def task_runner(self, request):
fixture_name = request.param._fixture_function.__name__
yield request.getfixturevalue(fixture_name)
@pytest.fixture
def tmp_file(self, tmp_path):
file_path = tmp_path / "canary.txt"
fi... | TestRayTaskRunner |
python | django__django | django/views/decorators/csrf.py | {
"start": 537,
"end": 1030
} | class ____(CsrfViewMiddleware):
# Behave like CsrfViewMiddleware but don't reject requests or log warnings.
def _reject(self, request, reason):
return None
requires_csrf_token = decorator_from_middleware(_EnsureCsrfToken)
requires_csrf_token.__name__ = "requires_csrf_token"
requires_csrf_token.__doc__... | _EnsureCsrfToken |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/concepts/types/types.py | {
"start": 818,
"end": 1112
} | class ____:
pass
@op
def my_op() -> MyClass:
return MyClass()
# end_auto_type
# start_test_dagster_type
from dagster import Any, Dict, check_dagster_type
def test_dagster_type():
assert check_dagster_type(Dict[Any, Any], {"foo": "bar"}).success
# end_test_dagster_type
| MyClass |
python | pandas-dev__pandas | pandas/tests/indexes/test_indexing.py | {
"start": 6980,
"end": 8478
} | class ____:
def test_get_indexer_base(self, index):
if index._index_as_unique:
expected = np.arange(index.size, dtype=np.intp)
actual = index.get_indexer(index)
tm.assert_numpy_array_equal(expected, actual)
else:
msg = "Reindexing only valid with uniqu... | TestGetIndexer |
python | mlflow__mlflow | mlflow/pyfunc/dbconnect_artifact_cache.py | {
"start": 240,
"end": 5769
} | class ____:
"""
Manages Databricks Connect artifacts cache.
Note it doesn't support OSS Spark Connect.
This class can be used in the following environment:
- Databricks shared cluster python notebook REPL
- Databricks Serverless python notebook REPL
- Databricks connect client python REP... | DBConnectArtifactCache |
python | django__django | tests/generic_relations_regress/models.py | {
"start": 1247,
"end": 1414
} | class ____(models.Model):
account = models.IntegerField(primary_key=True)
name = models.CharField(max_length=128)
addresses = GenericRelation(Address)
| Person |
python | euske__pdfminer | pdfminer/layout.py | {
"start": 12617,
"end": 20735
} | class ____(LTContainer):
def __init__(self, bbox):
LTContainer.__init__(self, bbox)
self.groups = None
return
# group_objects: group text object to textlines.
def group_objects(self, laparams, objs):
obj0 = None
line = None
for obj1 in objs:
if o... | LTLayoutContainer |
python | doocs__leetcode | solution/1800-1899/1868.Product of Two Run-Length Encoded Arrays/Solution.py | {
"start": 0,
"end": 587
} | class ____:
def findRLEArray(
self, encoded1: List[List[int]], encoded2: List[List[int]]
) -> List[List[int]]:
ans = []
j = 0
for vi, fi in encoded1:
while fi:
f = min(fi, encoded2[j][1])
v = vi * encoded2[j][0]
if ans a... | Solution |
python | weaviate__weaviate-python-client | weaviate/collections/queries/hybrid/query/executor.py | {
"start": 949,
"end": 19315
} | class ____(
Generic[ConnectionType, Properties, References], _BaseExecutor[ConnectionType]
):
@overload
def hybrid(
self,
query: Optional[str],
*,
alpha: NUMBER = 0.7,
vector: Optional[HybridVectorType] = None,
query_properties: Optional[List[str]] = None,
... | _HybridQueryExecutor |
python | apache__airflow | airflow-core/tests/unit/dag_processing/test_collection.py | {
"start": 10334,
"end": 13275
} | class ____:
@staticmethod
def clean_db():
clear_db_dags()
clear_db_assets()
clear_db_triggers()
@pytest.fixture(autouse=True)
def per_test(self) -> Generator:
self.clean_db()
yield
self.clean_db()
def test_add_asset_activate(self, dag_maker, session)... | TestAssetModelOperationSyncAssetActive |
python | django__django | tests/test_runner_apps/sample/pattern_tests.py | {
"start": 32,
"end": 112
} | class ____(TestCase):
def test_sample(self):
self.assertEqual(1, 1)
| Test |
python | tornadoweb__tornado | tornado/test/websocket_test.py | {
"start": 30742,
"end": 31348
} | class ____(unittest.TestCase):
def test_ping_sleep_time(self):
from tornado.websocket import WebSocketProtocol13
now = datetime.datetime(2025, 1, 1, 12, 0, 0, tzinfo=datetime.timezone.utc)
interval = 10 # seconds
last_ping_time = datetime.datetime(
2025, 1, 1, 11, 59, 5... | PingCalculationTest |
python | qdrant__qdrant-client | tools/async_client_generator/transformers/import_transformer.py | {
"start": 41,
"end": 533
} | class ____(ast.NodeTransformer):
def __init__(self, import_replace_map: Optional[dict[str, str]] = None):
self.import_replace_map = import_replace_map if import_replace_map is not None else {}
def visit_Import(self, node: ast.Import) -> ast.AST:
for old_value, new_value in self.import_replace_m... | ImportTransformer |
python | getsentry__sentry | src/sentry/cache/redis.py | {
"start": 1557,
"end": 2034
} | class ____(CommonRedisCache):
def __init__(self, **options: object) -> None:
cluster, options = get_cluster_from_options("SENTRY_CACHE_OPTIONS", options)
client = get_cluster_routing_client(cluster, False)
# XXX: rb does not have a "raw" client -- use the default client
super().__ini... | RbCache |
python | numpy__numpy | numpy/lib/tests/test_function_base.py | {
"start": 55422,
"end": 72785
} | class ____:
def test_simple(self):
def addsubtract(a, b):
if a > b:
return a - b
else:
return a + b
f = vectorize(addsubtract)
r = f([0, 3, 6, 9], [1, 3, 5, 7])
assert_array_equal(r, [1, 6, 1, 2])
def test_scalar(self):
... | TestVectorize |
python | django__django | django/contrib/postgres/search.py | {
"start": 2026,
"end": 2150
} | class ____(CheckPostgresInstalledMixin, Field):
def db_type(self, connection):
return "tsvector"
| SearchVectorField |
python | sympy__sympy | sympy/physics/mechanics/tests/test_actuator.py | {
"start": 9741,
"end": 12685
} | class ____:
@pytest.fixture(autouse=True)
def _linear_damper_fixture(self):
self.damping = Symbol('c')
self.l = Symbol('l')
self.pA = Point('pA')
self.pB = Point('pB')
self.pathway = LinearPathway(self.pA, self.pB)
self.q = dynamicsymbols('q')
self.dq = d... | TestLinearDamper |
python | django__django | tests/postgres_tests/test_indexes.py | {
"start": 578,
"end": 1848
} | class ____:
def test_name_auto_generation(self):
index = self.index_class(fields=["field"])
index.set_name_with_model(CharFieldModel)
self.assertRegex(
index.name, r"postgres_te_field_[0-9a-f]{6}_%s" % self.index_class.suffix
)
def test_deconstruction_no_customizatio... | IndexTestMixin |
python | conda__conda | conda/common/io.py | {
"start": 12306,
"end": 13103
} | class ____(Executor):
def __init__(self):
self._shutdown = False
self._shutdownLock = Lock()
def submit(self, fn, *args, **kwargs):
with self._shutdownLock:
if self._shutdown:
raise RuntimeError("cannot schedule new futures after shutdown")
f = F... | DummyExecutor |
python | getsentry__sentry | src/sentry/explore/endpoints/explore_saved_query_detail.py | {
"start": 1266,
"end": 1930
} | class ____(OrganizationEndpoint):
owner = ApiOwner.EXPLORE
permission_classes = (ExploreSavedQueryPermission,)
def convert_args(self, request: Request, organization_id_or_slug, id, *args, **kwargs):
args, kwargs = super().convert_args(request, organization_id_or_slug, *args, **kwargs)
try:... | ExploreSavedQueryBase |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_eth_address.py | {
"start": 679,
"end": 1680
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_eth_address"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _panda... | ColumnValuesToBeValidEthAddress |
python | tensorflow__tensorflow | tensorflow/python/data/ops/dataset_ops.py | {
"start": 193554,
"end": 195794
} | class ____(tracking_base.Trackable):
"""Iterator over a dataset with elements converted to numpy."""
__slots__ = ["_iterator"]
def __init__(self, dataset):
self._iterator = iter(dataset)
self._dataset = dataset
def __repr__(self):
return f"NumpyIterator(iterator={self._iterator})"
def __iter__... | NumpyIterator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/transform.py | {
"start": 156,
"end": 4685
} | class ____:
"""
Transform class was implemented according to issue #4841
Shopify API returns price fields as a string and it should be converted to the number
Some records fields contain objects and arrays, which contain price fields.
Those price fields should be transformed too.
This solution d... | DataTypeEnforcer |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/model_query_transitive_extends.py | {
"start": 228,
"end": 318
} | class ____:
attribute = ...
def __init__(self):
self.instance = ...
| Test1_C |
python | scrapy__scrapy | tests/test_exporters.py | {
"start": 12452,
"end": 12591
} | class ____(TestCsvItemExporter):
item_class = MyDataClass
custom_field_item_class = CustomFieldDataclass
| TestCsvItemExporterDataclass |
python | joke2k__faker | faker/providers/person/tw_GH/__init__.py | {
"start": 44,
"end": 11396
} | class ____(PersonProvider):
formats = (
"{{first_name_male}} {{last_name_male}}",
"{{first_name_male}} {{last_name_male}}",
"{{first_name_male}} {{last_name_male}}",
"{{first_name_male}} {{last_name_male}}",
"{{first_name_male}} {{last_name_male}}-{{last_name_male}}",
... | Provider |
python | apache__airflow | providers/microsoft/azure/src/airflow/providers/microsoft/azure/hooks/powerbi.py | {
"start": 1514,
"end": 1648
} | class ____(AirflowException):
"""An exception that indicates a dataset refresh failed to complete."""
| PowerBIDatasetRefreshException |
python | facebookresearch__faiss | faiss/gpu/test/test_gpu_basics.py | {
"start": 18131,
"end": 18260
} | class ____(unittest.TestCase):
def test_gpu_flag(self):
assert "GPU" in faiss.get_compile_options().split()
| TestGpuFlags |
python | getsentry__sentry | src/sentry/feedback/usecases/label_generation.py | {
"start": 269,
"end": 2119
} | class ____(TypedDict):
"""Corresponds to GenerateFeedbackLabelsRequest in Seer."""
organization_id: int
feedback_message: str
AI_LABEL_TAG_PREFIX = "ai_categorization"
# If Seer generates more labels, we truncate it to this many labels
MAX_AI_LABELS = 15
# Max length of the serialized list of labels, whi... | LabelRequest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/decorator3.py | {
"start": 190,
"end": 632
} | class ____:
# This should generate an error if version < 3.9.
@my_decorators[0]
def my_static_method():
return 3
# This should generate an error if version < 3.9.
@my_decorators[1]
def my_class_method(cls):
return 3
# This should generate an error if version < 3.9.
@my_... | Foo |
python | huggingface__transformers | src/transformers/models/audioflamingo3/modeling_audioflamingo3.py | {
"start": 11412,
"end": 11906
} | class ____(PreTrainedModel):
config: AudioFlamingo3Config
base_model_prefix = "model"
input_modalities = ("audio", "text")
supports_gradient_checkpointing = True
_no_split_modules = ["AudioFlamingo3Attention"]
_skip_keys_device_placement = "past_key_values"
_supports_flash_attn = True
_s... | AudioFlamingo3PreTrainedModel |
python | pytorch__pytorch | torch/distributed/fsdp/_fsdp_extensions.py | {
"start": 447,
"end": 5033
} | class ____(ABC):
"""
This enables some customizable hooks to enable composability with tensor
parallelism. To activate these hooks, use :func:`_set_fsdp_extensions` to
set a custom :class:`FSDPExtensions` that implements the hooks.
"""
@abstractmethod
def pre_flatten_transform(
self... | FSDPExtensions |
python | PyCQA__pylint | tests/functional/ext/overlapping_exceptions/overlapping_exceptions.py | {
"start": 96,
"end": 1112
} | class ____(SomeException):
pass
AliasException = SomeException
try:
pass
except (SomeException, SomeException): # [overlapping-except]
pass
try:
pass
except (SomeException, SubclassException): # [overlapping-except]
pass
try:
pass
except (SomeException, AliasException): # [overlapping-ex... | SubclassException |
python | PyCQA__pylint | tests/functional/i/inner_classes.py | {
"start": 361,
"end": 407
} | class ____(Aaa):
"""docstring"""
pass
| Bbb |
python | scrapy__scrapy | tests/test_spidermiddleware_output_chain.py | {
"start": 5396,
"end": 5894
} | class ____(_BaseSpiderMiddleware):
def process_spider_output(self, response, result):
for r in result:
r["processed"].append(f"{self.__class__.__name__}.process_spider_output")
yield r
def process_spider_exception(self, response, exception):
method = f"{self.__class__.__... | _GeneratorDoNothingMiddleware |
python | getsentry__sentry | src/sentry/seer/autofix/utils.py | {
"start": 2035,
"end": 2130
} | class ____(StrEnum):
ROOT_CAUSE = "root_cause"
SOLUTION = "solution"
| AutofixTriggerSource |
python | python-pillow__Pillow | docs/example/DdsImagePlugin.py | {
"start": 7932,
"end": 8627
} | class ____(ImageFile.PyDecoder):
_pulls_fd = True
def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]:
assert self.fd is not None
try:
self.set_as_raw(_dxt5(self.fd, self.state.xsize, self.state.ysize))
except struct.error as e:
msg ... | DXT5Decoder |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-of-tasks-you-can-assign.py | {
"start": 3985,
"end": 5232
} | class ____(object):
def maxTaskAssign(self, tasks, workers, pills, strength):
"""
:type tasks: List[int]
:type workers: List[int]
:type pills: int
:type strength: int
:rtype: int
"""
def check(tasks, workers, pills, strength, x):
w = worker... | Solution4 |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/base.py | {
"start": 106106,
"end": 107691
} | class ____(compiler.IdentifierPreparer):
reserved_words = RESERVED_WORDS
def _unquote_identifier(self, value):
if value[0] == self.initial_quote:
value = value[1:-1].replace(
self.escape_to_quote, self.escape_quote
)
return value
def format_type(self... | PGIdentifierPreparer |
python | apache__airflow | airflow-core/src/airflow/utils/sqlalchemy.py | {
"start": 4414,
"end": 8455
} | class ____(TypeDecorator):
"""
A version of the JSON column that uses the Airflow extended JSON serialization.
See airflow.serialization.
"""
impl = Text
cache_ok = True
should_evaluate_none = True
def load_dialect_impl(self, dialect) -> TypeEngine:
if dialect.name == "postg... | ExtendedJSON |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/tool_selection.py | {
"start": 2512,
"end": 11797
} | class ____(AgentMiddleware):
"""Uses an LLM to select relevant tools before calling the main model.
When an agent has many tools available, this middleware filters them down
to only the most relevant ones for the user's query. This reduces token usage
and helps the main model focus on the right tools.
... | LLMToolSelectorMiddleware |
python | pytorch__pytorch | tools/test/test_vulkan_codegen.py | {
"start": 2419,
"end": 3749
} | class ____(unittest.TestCase):
def setUp(self) -> None:
self.tmpdir = tempfile.TemporaryDirectory()
with open(f"{self.tmpdir.name}/test_shader.glsl,", "w") as f:
f.write(test_shader)
with open(f"{self.tmpdir.name}/test_params.yaml", "w") as f:
f.write(test_params_ya... | TestVulkanSPVCodegen |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/ragged_rank_op_test.py | {
"start": 1025,
"end": 2610
} | class ____(test_util.TensorFlowTestCase,
parameterized.TestCase):
@parameterized.parameters([
# Rank 0
dict(
test_input=1,
expected_rank=0,
),
# Rank 1
dict(
test_input=[1],
expected_rank=1,
),
dict(
te... | RaggedRankOpTest |
python | aimacode__aima-python | agents4e.py | {
"start": 2011,
"end": 8951
} | class ____(Thing):
"""An Agent is a subclass of Thing with one required slot,
.program, which should hold a function that takes one argument, the
percept, and returns an action. (What counts as a percept or action
will depend on the specific environment in which the agent exists.)
Note that 'program... | Agent |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 368979,
"end": 369310
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("MarketplaceListing", graphql_name="node")
| MarketplaceListingEdge |
python | boto__boto3 | tests/unit/dynamodb/test_types.py | {
"start": 1733,
"end": 5017
} | class ____(unittest.TestCase):
def setUp(self):
self.serializer = TypeSerializer()
def test_serialize_unsupported_type(self):
with pytest.raises(TypeError, match=r'Unsupported type'):
self.serializer.serialize(object())
def test_serialize_null(self):
assert self.seriali... | TestSerializer |
python | kamyu104__LeetCode-Solutions | Python/find-polygon-with-the-largest-perimeter.py | {
"start": 60,
"end": 411
} | class ____(object):
def largestPerimeter(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
prefix = sum(nums)
for i in reversed(xrange(2, len(nums))):
prefix -= nums[i]
if prefix > nums[i]:
return prefix... | Solution |
python | pola-rs__polars | py-polars/src/polars/datatypes/classes.py | {
"start": 8832,
"end": 8911
} | class ____(NumericType):
"""Base class for integer data types."""
| IntegerType |
python | realpython__materials | django-vue-graphql/source_code_final/back_end/blog/admin.py | {
"start": 103,
"end": 184
} | class ____(admin.ModelAdmin):
model = Profile
@admin.register(Tag)
| ProfileAdmin |
python | jazzband__django-model-utils | model_utils/models.py | {
"start": 1303,
"end": 1635
} | class ____(models.Model):
"""
An abstract base class model that provides ``start``
and ``end`` fields to record a timeframe.
"""
start = models.DateTimeField(_('start'), null=True, blank=True)
end = models.DateTimeField(_('end'), null=True, blank=True)
class Meta:
abstract = True
... | TimeFramedModel |
python | lxml__lxml | doc/s5/ep2008/atom.py | {
"start": 13435,
"end": 13579
} | class ____(_EntryElement):
"""
For elements that contain a date in their text content.
"""
date = _date_text_property()
| DateElement |
python | great-expectations__great_expectations | tasks.py | {
"start": 26469,
"end": 41447
} | class ____(NamedTuple):
requirement_files: tuple[str, ...]
services: tuple[str, ...] = tuple()
extra_pytest_args: tuple[ # TODO: remove this once remove the custom flagging system
str, ...
] = tuple()
MARKER_DEPENDENCY_MAP: Final[Mapping[str, TestDependencies]] = {
"athena": TestDependenc... | TestDependencies |
python | kubernetes-client__python | kubernetes/client/models/v1_pod_spec.py | {
"start": 383,
"end": 58308
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1PodSpec |
python | google__jax | tests/jaxpr_effects_test.py | {
"start": 1796,
"end": 3690
} | class ____(effects.JaxprInputEffect): pass
foo_effect = OrderedEffect("foo")
foo2_effect = OrderedEffect("foo2")
bar_effect = BasicEffect("bar")
baz_effect = UnlowerableEffect()
while_effect = WhileEffect()
while1_effect = WhileEffect()
while2_effect = WhileEffect()
log_effect = OrderedEffect("log")
unordered_log_effe... | InputEffect |
python | getsentry__sentry | src/sentry/replays/lib/new_query/conditions.py | {
"start": 2731,
"end": 3931
} | class ____(GenericBase):
"""Integer scalar condition class."""
@staticmethod
def visit_eq(expression: Expression, value: int) -> Condition:
return Condition(expression, Op.EQ, value)
@staticmethod
def visit_neq(expression: Expression, value: int) -> Condition:
return Condition(expr... | IntegerScalar |
python | tiangolo__fastapi | tests/test_response_model_data_filter_no_inheritance.py | {
"start": 209,
"end": 276
} | class ____(BaseModel):
email: str
hashed_password: str
| UserDB |
python | huggingface__transformers | src/transformers/models/nemotron/modeling_nemotron.py | {
"start": 3329,
"end": 8564
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: NemotronConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
sel... | NemotronRotaryEmbedding |
python | openai__openai-python | examples/responses/streaming.py | {
"start": 159,
"end": 526
} | class ____(BaseModel):
steps: List[Step]
final_answer: str
client = OpenAI()
with client.responses.stream(
input="solve 8x + 31 = 2",
model="gpt-4o-2024-08-06",
text_format=MathResponse,
) as stream:
for event in stream:
if "output_text" in event.type:
rich.print(event)
r... | MathResponse |
python | yaml__pyyaml | tests/legacy_tests/conftest.py | {
"start": 463,
"end": 1425
} | class ____(pytest.Item):
def __init__(self, parent=None, config=None, session=None, nodeid=None, function=None, filenames=None, **kwargs):
self._function = function
self._fargs = filenames or []
super().__init__(os.path.basename(filenames[0]) if filenames else parent.name, parent, config, s... | PyYAMLItem |
python | pytorch__pytorch | torch/distributions/transforms.py | {
"start": 33614,
"end": 34288
} | class ____(Transform):
"""
Transform from unconstrained matrices to lower-triangular matrices with
nonnegative diagonal entries.
This is useful for parameterizing positive definite matrices in terms of
their Cholesky factorization.
"""
domain = constraints.independent(constraints.real, 2)
... | LowerCholeskyTransform |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-surrealdb/destination_surrealdb/destination.py | {
"start": 2765,
"end": 12503
} | class ____(Destination):
"""
Destination connector for SurrealDB.
"""
def write(
self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]
) -> Iterable[AirbyteMessage]:
"""
Reads the input stream of messages, con... | DestinationSurrealDB |
python | weaviate__weaviate-python-client | weaviate/exceptions.py | {
"start": 13599,
"end": 13955
} | class ____(Exception):
def __init__(self, pb: version.Version, grpc: version.Version) -> None:
super().__init__(
f"gRPC incompatibility detected. Protobuf: {pb.base_version}, gRPC: {grpc.base_version}. Ensure that your protobuf and grpcio versions are compatible or runtime errors may occur."
... | WeaviateProtobufIncompatibility |
python | doocs__leetcode | solution/2400-2499/2484.Count Palindromic Subsequences/Solution.py | {
"start": 0,
"end": 1063
} | class ____:
def countPalindromes(self, s: str) -> int:
mod = 10**9 + 7
n = len(s)
pre = [[[0] * 10 for _ in range(10)] for _ in range(n + 2)]
suf = [[[0] * 10 for _ in range(10)] for _ in range(n + 2)]
t = list(map(int, s))
c = [0] * 10
for i, v in enumerate(t... | Solution |
python | doocs__leetcode | solution/2600-2699/2605.Form Smallest Number From Two Digit Arrays/Solution3.py | {
"start": 0,
"end": 446
} | class ____:
def minNumber(self, nums1: List[int], nums2: List[int]) -> int:
mask1 = mask2 = 0
for x in nums1:
mask1 |= 1 << x
for x in nums2:
mask2 |= 1 << x
mask = mask1 & mask2
if mask:
return (mask & -mask).bit_length() - 1
a = (... | Solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.