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
pypa__warehouse
tests/unit/admin/test_services.py
{ "start": 263, "end": 1335 }
class ____: def test_verify_service(self): assert verifyClass(ISponsorLogoStorage, LocalSponsorLogoStorage) def test_basic_init(self): storage = LocalSponsorLogoStorage("/foo/bar/") assert storage.base == "/foo/bar/" def test_create_service(self): request = pretend.stub( ...
TestSponsorLogoStorage
python
django__django
tests/check_framework/test_database.py
{ "start": 188, "end": 2150 }
class ____(TestCase): databases = {"default", "other"} @mock.patch("django.db.backends.base.validation.BaseDatabaseValidation.check") def test_database_checks_called(self, mocked_check): check_database_backends() self.assertFalse(mocked_check.called) check_database_backends(database...
DatabaseCheckTests
python
doocs__leetcode
solution/1800-1899/1800.Maximum Ascending Subarray Sum/Solution.py
{ "start": 0, "end": 286 }
class ____: def maxAscendingSum(self, nums: List[int]) -> int: ans = t = 0 for i, v in enumerate(nums): if i == 0 or v > nums[i - 1]: t += v ans = max(ans, t) else: t = v return ans
Solution
python
milvus-io__pymilvus
pymilvus/exceptions.py
{ "start": 2299, "end": 2408 }
class ____(MilvusException): """Raise when cannot trasfer dataframe to schema"""
CannotInferSchemaException
python
scipy__scipy
scipy/integrate/_ode.py
{ "start": 345, "end": 792 }
class ____ --------- A generic interface class to numeric integrators. It has the following methods:: integrator = ode(f, jac=None) integrator = integrator.set_integrator(name, **params) integrator = integrator.set_initial_value(y0, t0=0.0) integrator = integrator.set_f_params(*args) integrator = ...
ode
python
huggingface__transformers
src/transformers/models/mgp_str/tokenization_mgp_str.py
{ "start": 878, "end": 3837 }
class ____(PreTrainedTokenizer): """ Construct a MGP-STR char tokenizer. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to this superclass for more information regarding those methods. Args: vocab_file (`str`): P...
MgpstrTokenizer
python
pytest-dev__pytest-xdist
src/xdist/workermanage.py
{ "start": 9702, "end": 18850 }
class ____: # Set when the worker is ready. workerinfo: WorkerInfo class RemoteHook: @pytest.hookimpl(trylast=True) def pytest_xdist_getremotemodule(self) -> Any: return xdist.remote def __init__( self, nodemanager: NodeManager, gateway: execnet.Gate...
WorkerController
python
great-expectations__great_expectations
great_expectations/core/profiler_types_mapping.py
{ "start": 37, "end": 3034 }
class ____: """Useful backend type mapping for building profilers.""" INT_TYPE_NAMES = [ "BIGINT", "BYTEINT", "ByteType()", "INT", "INT64", "INTEGER", "Int16Dtype", "Int32Dtype", "Int64Dtype", "Int8Dtype", "IntegerType", ...
ProfilerTypeMapping
python
apache__airflow
airflow-core/src/airflow/executors/base_executor.py
{ "start": 2495, "end": 3580 }
class ____: """ For keeping track of attempts to queue again when task still apparently running. We don't want to slow down the loop, so we don't block, but we allow it to be re-checked for at least MIN_SECONDS seconds. """ MIN_SECONDS = 10 total_tries: int = field(default=0, init=False) ...
RunningRetryAttemptType
python
pyinstaller__pyinstaller
PyInstaller/building/makespec.py
{ "start": 5770, "end": 6376 }
class ____: def __init__(self, *parts): self.path = os.path.join(*parts) self.variable_prefix = self.filename_suffix = None def __repr__(self): if self.filename_suffix is None: self.variable_prefix, self.filename_suffix = make_variable_path(self.path) if self.variabl...
Path
python
huggingface__transformers
tests/models/emu3/test_modeling_emu3.py
{ "start": 1546, "end": 3981 }
class ____: def __init__( self, parent, batch_size=13, seq_length=7, is_training=False, vocab_size=99, hidden_size=32, num_hidden_layers=2, num_attention_heads=2, num_key_value_heads=2, intermediate_size=37, max_position...
Emu3Text2TextModelTester
python
ionelmc__pytest-benchmark
src/pytest_benchmark/storage/elasticsearch.py
{ "start": 933, "end": 9427 }
class ____: def __init__(self, hosts, index, doctype, project_name, logger, default_machine_id=None): self._es_hosts = hosts self._es_index = index self._es_doctype = doctype self._es = elasticsearch.Elasticsearch(self._es_hosts, serializer=BenchmarkJSONSerializer()) self._pr...
ElasticsearchStorage
python
great-expectations__great_expectations
great_expectations/core/expectation_validation_result.py
{ "start": 30176, "end": 31804 }
class ____(Schema): success = fields.Bool() results = fields.List(fields.Nested(ExpectationValidationResultSchema)) suite_name = fields.String(required=True, allow_none=False) suite_parameters = fields.Dict() statistics = fields.Dict() meta = fields.Dict(allow_none=True) id = fields.UUID(req...
ExpectationSuiteValidationResultSchema
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_cloud_storage_transfer_service.py
{ "start": 31007, "end": 33275 }
class ____: @mock.patch( "airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook" ) def test_operation_cancel(self, mock_hook): op = CloudDataTransferServiceCancelOperationOperator( operation_name=OPERATION_NAME, task_id=T...
TestGcpStorageTransferOperationsCancelOperator
python
django__django
tests/fixtures_regress/models.py
{ "start": 6251, "end": 6340 }
class ____(models.Model): parent = models.ManyToManyField("self", blank=True)
M2MToSelf
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pep8_naming/N815.py
{ "start": 427, "end": 542 }
class ____(TypedDict): lower: int CONSTANT: str mixedCase: bool _mixedCase: list mixed_Case: set
D
python
tensorflow__tensorflow
tensorflow/core/function/polymorphism/function_cache_test.py
{ "start": 2302, "end": 3353 }
class ____(trace.TraceType): def __init__(self, *shape: Optional[int]): self.shape = shape def is_subtype_of(self, other: "MockShape") -> bool: if len(self.shape) != len(other.shape): return False if any(o is not None and s != o for s, o in zip(self.shape, other.shape)): return False ...
MockShape
python
pandas-dev__pandas
asv_bench/benchmarks/arithmetic.py
{ "start": 1182, "end": 1575 }
class ____: def setup(self): # GH#31300 arr = np.arange(10**6) df = DataFrame({"A": arr}) ser = df["A"] self.df = df self.ser = ser def time_frame_op_with_fill_value_no_nas(self): self.df.add(self.df, fill_value=4) def time_series_op_with_fill_value...
OpWithFillValue
python
matplotlib__matplotlib
lib/mpl_toolkits/axisartist/axis_artist.py
{ "start": 9167, "end": 13259 }
class ____(AttributeCopier, LabelBase): """ Axis label. Derived from `.Text`. The position of the text is updated in the fly, so changing text position has no effect. Otherwise, the properties can be changed as a normal `.Text`. To change the pad between tick labels and axis label, use `set_pad`. ...
AxisLabel
python
numba__llvmlite
llvmlite/tests/test_ir.py
{ "start": 109433, "end": 125244 }
class ____(TestBase): def test_integers(self): c = ir.Constant(int32, 42) self.assertEqual(str(c), 'i32 42') c = ir.Constant(int1, 1) self.assertEqual(str(c), 'i1 1') c = ir.Constant(int1, 0) self.assertEqual(str(c), 'i1 0') c = ir.Constant(int1, True) ...
TestConstant
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/auto_materialize_policy.py
{ "start": 469, "end": 1087 }
class ____(graphene.ObjectType): description = graphene.NonNull(graphene.String) decisionType = graphene.NonNull(GrapheneAutoMaterializeDecisionType) className = graphene.NonNull(graphene.String) class Meta: name = "AutoMaterializeRule" def __init__(self, description: str, decision_type: A...
GrapheneAutoMaterializeRule
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/solver24.py
{ "start": 789, "end": 1173 }
class ____(Iterator[ClassC[AnyStr]], Protocol): ... GenericPath: TypeAlias = AnyStr | PathLike[AnyStr] def func2(iter: Iterable[object]) -> bool: ... def func3(path: GenericPath[AnyStr]) -> ClassD[AnyStr]: ... def func4(val: str): func2(func3(val)) def func5(a: dict[T, U], b: list[T | U]): pass def ...
ClassD
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/nn_ops/softplus_op_test.py
{ "start": 1159, "end": 5421 }
class ____(test.TestCase): def _npSoftplus(self, np_features): np_features = np.asarray(np_features) zero = np.asarray(0).astype(np_features.dtype) return np.logaddexp(zero, np_features) def _testSoftplus(self, np_features, use_gpu=False): np_softplus = self._npSoftplus(np_features) with self....
SoftplusTest
python
pydata__xarray
xarray/core/datatree_render.py
{ "start": 361, "end": 438 }
class ____(NamedTuple): pre: str fill: str node: DataTree | str
Row
python
python-openxml__python-docx
src/docx/oxml/table.py
{ "start": 1366, "end": 4603 }
class ____(BaseOxmlElement): """``<w:tr>`` element.""" add_tc: Callable[[], CT_Tc] get_or_add_trPr: Callable[[], CT_TrPr] _add_trPr: Callable[[], CT_TrPr] tc_lst: list[CT_Tc] # -- custom inserter below -- tblPrEx: CT_TblPrEx | None = ZeroOrOne("w:tblPrEx") # pyright: ignore[reportAssignme...
CT_Row
python
matplotlib__matplotlib
lib/matplotlib/gridspec.py
{ "start": 20856, "end": 27851 }
class ____: """ The location of a subplot in a `GridSpec`. .. note:: Likely, you will never instantiate a `SubplotSpec` yourself. Instead, you will typically obtain one from a `GridSpec` using item-access. Parameters ---------- gridspec : `~matplotlib.gridspec.GridSpec` ...
SubplotSpec
python
ray-project__ray
python/ray/experimental/channel/conftest.py
{ "start": 5688, "end": 6060 }
class ____(ray_channel.shared_memory_channel.Channel): """ Patched Channel that records all write ops for testing. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ops = [] def write(self, *args, **kwargs): self.ops.append((args, kwargs)) ...
TracedChannel
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/nn_ops/losses_test.py
{ "start": 38601, "end": 41109 }
class ____(test.TestCase): def testIncompatibleShapes(self): with self.cached_session(): predictions = constant_op.constant([[-1.0], [2.1]]) labels = constant_op.constant([0.0, 1.0]) with self.assertRaises(ValueError): _ = losses.huber_loss(labels, predictions).eval() @test_util.run_...
HuberLossTest
python
getsentry__sentry
tests/sentry/deletions/test_monitor.py
{ "start": 427, "end": 1823 }
class ____(APITestCase, TransactionTestCase, HybridCloudTestMixin): def test_simple(self) -> None: project = self.create_project(name="test") env = Environment.objects.create(organization_id=project.organization_id, name="foo") monitor = Monitor.objects.create( organization_id=p...
DeleteMonitorTest
python
bokeh__bokeh
examples/server/app/server_auth/auth.py
{ "start": 795, "end": 2170 }
class ____(RequestHandler): def get(self): try: errormessage = self.get_argument("error") except Exception: errormessage = "" self.render("login.html", errormessage=errormessage) def check_permission(self, username, password): # !!! # !!! This co...
LoginHandler
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_object_position09.py
{ "start": 315, "end": 1685 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("object_position09.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self...
TestCompareXLSXFiles
python
pypa__warehouse
warehouse/accounts/forms.py
{ "start": 17506, "end": 17835 }
class ____(wtforms.Form): def __init__(self, *args, request, user_id, user_service, **kwargs): super().__init__(*args, **kwargs) self.request = request self.user_id = user_id self.user_service = user_service remember_device = wtforms.BooleanField(default=False)
_TwoFactorAuthenticationForm
python
pandas-dev__pandas
pandas/tests/libs/test_hashtable.py
{ "start": 25148, "end": 27212 }
class ____: def test_value_count(self, dtype): values = np.array([np.nan, np.nan, np.nan], dtype=dtype) keys, counts, _ = ht.value_count(values, True) assert len(keys) == 0 keys, counts, _ = ht.value_count(values, False) assert len(keys) == 1 and np.all(np.isnan(keys)) ...
TestHelpFunctionsWithNans
python
numba__numba
numba/tests/test_hashing.py
{ "start": 625, "end": 2052 }
class ____(TestCase): def test_warn_on_fnv(self): # FNV hash alg variant is not supported, check Numba warns work = """ import sys import warnings from collections import namedtuple # hash_info is a StructSequence, mock as a named tuple fields = ["width", "m...
TestHashingSetup
python
pydantic__pydantic
tests/mypy/modules/plugin_success.py
{ "start": 3861, "end": 3992 }
class ____(BaseModel, Generic[T]): data: T error: Optional[str] response = Response[Model](data=model, error=None)
Response
python
scrapy__scrapy
scrapy/commands/startproject.py
{ "start": 940, "end": 4418 }
class ____(ScrapyCommand): requires_crawler_process = False default_settings = {"LOG_ENABLED": False} def syntax(self) -> str: return "<project_name> [project_dir]" def short_desc(self) -> str: return "Create new project" def _is_valid_name(self, project_name: str) -> bool: ...
Command
python
getsentry__sentry
tests/snuba/api/endpoints/test_discover_key_transactions.py
{ "start": 516, "end": 951 }
class ____(APITestCase, SnubaTestCase): def setUp(self) -> None: super().setUp() self.login_as(user=self.user, superuser=False) self.org = self.create_organization(owner=self.user, name="foo") self.project = self.create_project(name="baz", organization=self.org) self.event_d...
TeamKeyTransactionTestBase
python
apache__airflow
providers/telegram/tests/unit/telegram/hooks/test_telegram.py
{ "start": 1304, "end": 12744 }
class ____: @pytest.fixture(autouse=True) def setup_connections(self, create_connection_without_db): create_connection_without_db( Connection( conn_id="telegram-webhook-without-token", conn_type="http", ) ) create_connection_without...
TestTelegramHook
python
spyder-ide__spyder
external-deps/python-lsp-server/test/plugins/test_definitions.py
{ "start": 312, "end": 4797 }
class ____(object): def __init__(self): self.members = dict() def add_member(self, id, name): self.members[id] = name subscripted_before_reference = {} subscripted_before_reference[0] = 0 subscripted_before_reference def my_func(): print('called') alias = my_func my_list = [1, None, al...
Directory
python
google__flatbuffers
python/flatbuffers/reflection/BaseType.py
{ "start": 95, "end": 414 }
class ____(object): None_ = 0 UType = 1 Bool = 2 Byte = 3 UByte = 4 Short = 5 UShort = 6 Int = 7 UInt = 8 Long = 9 ULong = 10 Float = 11 Double = 12 String = 13 Vector = 14 Obj = 15 Union = 16 Array = 17 Vector64 = 18 MaxBaseType = 19
BaseType
python
celery__celery
t/unit/app/test_loaders.py
{ "start": 545, "end": 3777 }
class ____: message_options = {'subject': 'Subject', 'body': 'Body', 'sender': 'x@x.com', 'to': 'y@x.com'} server_options = {'host': 'smtp.x.com', 'port': 1234, 'user': 'x', 'pa...
test_LoaderBase
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/schedules/__init__.py
{ "start": 2844, "end": 4426 }
class ____(graphene.Mutation): """Disable a schedule from launching runs for a job.""" Output = graphene.NonNull(GrapheneScheduleMutationResult) class Arguments: id = graphene.Argument(graphene.String) # Schedule / InstigationState id schedule_origin_id = graphene.Argument(graphene.String...
GrapheneStopRunningScheduleMutation
python
pytorch__pytorch
.ci/lumen_cli/cli/lib/core/vllm/vllm_build.py
{ "start": 970, "end": 4595 }
class ____: """ Parameters defining the vllm external input configurations. Combine with VllmDockerBuildArgs to define the vllm build environment """ # USE_TORCH_WHEEL: when true, use local Torch wheels; requires TORCH_WHEELS_PATH. # Otherwise docker build pull torch nightly during build # ...
VllmBuildParameters
python
mlflow__mlflow
mlflow/webhooks/types.py
{ "start": 3044, "end": 3694 }
class ____(TypedDict): """Payload sent when a tag is deleted from a model version. Example payload: .. code-block:: python { "name": "example_model", "version": "1", "key": "example_key", } """ name: str """The name of the registered model...
ModelVersionTagDeletedPayload
python
django-compressor__django-compressor
compressor/tests/test_offline.py
{ "start": 26023, "end": 27835 }
class ____(OfflineTestCaseMixin, TestCase): template_names = ["base.html", "base2.html", "test_compressor_offline.html"] templates_dir = "test_block_super_base_compressed" expected_hash_offline = ["e4e9263fa4c0", "9cecd41a505f", "d3f749e83c81"] expected_hash = ["028c3fc42232", "2e9d3f5545a6", "d3f749e83...
OfflineCompressBlockSuperBaseCompressed
python
django__django
tests/template_tests/filter_tests/test_join.py
{ "start": 162, "end": 2884 }
class ____(SimpleTestCase): @setup({"join01": '{{ a|join:", " }}'}) def test_join01(self): output = self.engine.render_to_string("join01", {"a": ["alpha", "beta & me"]}) self.assertEqual(output, "alpha, beta &amp; me") @setup({"join02": '{% autoescape off %}{{ a|join:", " }}{% endautoescape...
JoinTests
python
sympy__sympy
sympy/physics/quantum/state.py
{ "start": 12564, "end": 14222 }
class ____(State, BraBase): """A general time-independent Bra in quantum mechanics. Inherits from State and BraBase. A Bra is the dual of a Ket [1]_. This class and its subclasses will be the main classes that users will use for expressing Bras in Dirac notation. Parameters ========== arg...
Bra
python
Pylons__pyramid
src/pyramid/interfaces.py
{ "start": 23773, "end": 24093 }
class ____(Interface): """ """ def __call__(self, request): """Must return a tuple of IReqest, IResponse or raise an exception. The ``request`` argument will be an instance of an object that provides IRequest.""" IRequest.combined = IRequest # for exception view lookups
IRequestHandler
python
celery__celery
t/smoke/tests/test_consumer.py
{ "start": 4532, "end": 5703 }
class ____: @pytest.fixture def default_worker_app(self, default_worker_app: Celery) -> Celery: app = default_worker_app app.conf.worker_prefetch_multiplier = 1 app.conf.worker_enable_prefetch_count_reduction = False app.conf.worker_cancel_long_running_tasks_on_connection_loss = ...
test_worker_enable_prefetch_count_reduction_false
python
huggingface__transformers
src/transformers/quantizers/quantizer_bitnet.py
{ "start": 904, "end": 4254 }
class ____(HfQuantizer): """ 1.58-bit quantization from BitNet quantization method: Before loading: it converts the linear layers into BitLinear layers during loading. Check out the paper introducing this method: https://huggingface.co/papers/2402.17764 """ requires_parameters_quantization = F...
BitNetHfQuantizer
python
PyCQA__pylint
pylint/pyreverse/diadefslib.py
{ "start": 10295, "end": 11456 }
class ____: """Get diagram definitions from user (i.e. xml files) or generate them.""" def __init__(self, config: argparse.Namespace, args: Sequence[str]) -> None: self.config = config self.args = args def get_diadefs(self, project: Project, linker: Linker) -> list[ClassDiagram]: "...
DiadefsHandler
python
pypa__setuptools
setuptools/tests/test_build_py.py
{ "start": 9865, "end": 14201 }
class ____: PYPROJECTS = { "default_pyproject": DALS( """ [project] name = "foo" version = "1" """ ), "dont_include_package_data": DALS( """ [project] name = "foo" version = "1" ...
TestTypeInfoFiles
python
ApeWorX__ape
src/ape/contracts/base.py
{ "start": 12904, "end": 14405 }
class ____(ManagerAccessMixin): def __init__(self, abi: "MethodABI", address: "AddressType") -> None: super().__init__() self.abi: MethodABI = abi self.address: AddressType = address @log_instead_of_fail(default="<ContractTransaction>") def __repr__(self) -> str: return self...
ContractTransaction
python
jazzband__django-simple-history
simple_history/models.py
{ "start": 36955, "end": 37365 }
class ____( HistoricDescriptorMixin, ReverseOneToOneDescriptor ): """ Overrides get_queryset to provide historic query support, should the instance be historic (and therefore was generated by a timepoint query) and the other side of the relation also uses a history manager. """ def get_rela...
HistoricReverseOneToOneDescriptor
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_textbox36.py
{ "start": 346, "end": 1337 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("textbox36.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with textbox(s).""" workbook = Workb...
TestCompareXLSXFiles
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/nn_ops/conv_ops_test.py
{ "start": 9859, "end": 112791 }
class ____(parameterized.TestCase, test.TestCase): def _DtypesToTest(self, use_gpu): if test_util.IsMklEnabled(): return [dtypes.float32] if use_gpu: # It is important that float32 comes first, since we are using its # gradients as a reference for fp16 gradients. out = [dtypes.float3...
Conv2DTest
python
huggingface__transformers
src/transformers/models/perceiver/modeling_perceiver.py
{ "start": 9779, "end": 12498 }
class ____(nn.Module): """Attention module, including a dense block.""" def __init__( self, config, is_cross_attention=False, qk_channels=None, v_channels=None, num_heads=1, q_dim=None, kv_dim=None, use_query_residual=True, ): ...
PerceiverAttention
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 256323, "end": 256718 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("client_mutation_id", "migration_source") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") migration_source = sgqlc.types.Field( "Migrat...
CreateMigrationSourcePayload
python
tiangolo__fastapi
tests/test_dependency_after_yield_raise.py
{ "start": 174, "end": 1803 }
class ____(Exception): pass def catching_dep() -> Any: try: yield "s" except CustomError as err: raise HTTPException(status_code=418, detail="Session error") from err def broken_dep() -> Any: yield "s" raise ValueError("Broken after yield") app = FastAPI() @app.get("/catching...
CustomError
python
spack__spack
lib/spack/spack/database.py
{ "start": 8589, "end": 10464 }
class ____(NamedTuple): """Data class to configure locks in Database objects Args: enable: whether to enable locks or not. database_timeout: timeout for the database lock package_timeout: timeout for the package lock """ enable: bool database_timeout: Optional[int] pack...
LockConfiguration
python
getsentry__sentry
src/sentry/monitors/migrations/0009_backfill_monitor_detectors.py
{ "start": 2407, "end": 3712 }
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
walkccc__LeetCode
solutions/3532. Path Existence Queries in a Graph I/3532.py
{ "start": 514, "end": 878 }
class ____: def pathExistenceQueries( self, n: int, nums: list[int], maxDiff: int, queries: list[list[int]] ) -> list[bool]: uf = UnionFind(n) for i in range(1, n): if abs(nums[i] - nums[i - 1]) <= maxDiff: uf.unionByRank(i, i - 1) return [uf.find(u) == uf.f...
Solution
python
tensorflow__tensorflow
tensorflow/python/data/experimental/kernel_tests/matching_files_dataset_test.py
{ "start": 1204, "end": 5524 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): def setUp(self): super(MatchingFilesDatasetTest, self).setUp() self.tmp_dir = tempfile.mkdtemp() def tearDown(self): shutil.rmtree(self.tmp_dir, ignore_errors=True) super(MatchingFilesDatasetTest, self).t...
MatchingFilesDatasetTest
python
pytorch__pytorch
test/torch_np/numpy_tests/lib/test_function_base.py
{ "start": 67308, "end": 71439 }
class ____(TestCase): A = np.array( [ [0.15391142, 0.18045767, 0.14197213], [0.70461506, 0.96474128, 0.27906989], [0.9297531, 0.32296769, 0.19267156], ] ) B = np.array( [ [0.10377691, 0.5417086, 0.49807457], [0.82872117, 0.7...
TestCorrCoef
python
crytic__slither
slither/slithir/variables/tuple_ssa.py
{ "start": 231, "end": 522 }
class ____(TupleVariable): # pylint: disable=too-few-public-methods def __init__(self, t: TupleVariable) -> None: super().__init__(t.node, t.index) self._non_ssa_version = t @property def non_ssa_version(self): return self._non_ssa_version
TupleVariableSSA
python
huggingface__transformers
src/transformers/models/edgetam_video/modular_edgetam_video.py
{ "start": 40216, "end": 42155 }
class ____(nn.Module): def __init__(self, config: EdgeTamVideoConfig): super().__init__() self.cross_attention = EdgeTamVideoPerceiverAttention(config) self.mlp = EdgeTamVideoPerceiverMLP(config) self.dropout = nn.Dropout(config.perceiver_resampler_hidden_dropout) self.self...
EdgeTamVideoPerceiverEncoderLayer
python
pytest-dev__pytest
src/_pytest/terminal.py
{ "start": 11068, "end": 61369 }
class ____: def __init__(self, config: Config, file: TextIO | None = None) -> None: import _pytest.config self.config = config self._numcollected = 0 self._session: Session | None = None self._showfspath: bool | None = None self.stats: dict[str, list[Any]] = {} ...
TerminalReporter
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_line06.py
{ "start": 315, "end": 1375 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_line06.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_...
TestCompareXLSXFiles
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_asset_condition_evaluations.py
{ "start": 13375, "end": 31233 }
class ____(ExecutingGraphQLContextTestMatrix): def test_auto_materialize_sensor(self, graphql_context: WorkspaceRequestContext): sensor_origin = RemoteInstigatorOrigin( repository_origin=infer_repository(graphql_context).get_remote_origin(), instigator_name="my_auto_materialize_senso...
TestAssetConditionEvaluations
python
crytic__slither
slither/detectors/variables/var_read_using_this.py
{ "start": 292, "end": 2163 }
class ____(AbstractDetector): ARGUMENT = "var-read-using-this" HELP = "Contract reads its own variable using `this`" IMPACT = DetectorClassification.OPTIMIZATION CONFIDENCE = DetectorClassification.HIGH WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#public-variable-read-in-ex...
VarReadUsingThis
python
django__django
tests/force_insert_update/models.py
{ "start": 587, "end": 751 }
class ____(Counter): other_counter_ptr = models.OneToOneField( Counter, primary_key=True, parent_link=True, on_delete=models.CASCADE )
OtherSubCounter
python
scipy__scipy
scipy/stats/_relative_risk.py
{ "start": 428, "end": 9571 }
class ____: """ Result of `scipy.stats.contingency.relative_risk`. Attributes ---------- relative_risk : float This is:: (exposed_cases/exposed_total) / (control_cases/control_total) exposed_cases : int The number of "cases" (i.e. occurrence of disease or other eve...
RelativeRiskResult
python
langchain-ai__langchain
libs/core/langchain_core/structured_query.py
{ "start": 289, "end": 2295 }
class ____(ABC): """Defines interface for IR translation using a visitor pattern.""" allowed_comparators: Sequence[Comparator] | None = None """Allowed comparators for the visitor.""" allowed_operators: Sequence[Operator] | None = None """Allowed operators for the visitor.""" def _validate_fun...
Visitor
python
realpython__materials
python-guitar-synthesizer/source_code_final/src/digitar/pitch.py
{ "start": 130, "end": 783 }
class ____: frequency: Hertz @classmethod def from_scientific_notation(cls, notation: str) -> Self: if match := re.fullmatch(r"([A-G]#?)(-?\d+)?", notation): note = match.group(1) octave = int(match.group(2) or 0) semitones = "C C# D D# E F F# G G# A A# B".split(...
Pitch
python
plotly__plotly.py
plotly/graph_objs/_bar.py
{ "start": 215, "end": 94673 }
class ____(_BaseTraceType): _parent_path_str = "" _path_str = "bar" _valid_props = { "alignmentgroup", "base", "basesrc", "cliponaxis", "constraintext", "customdata", "customdatasrc", "dx", "dy", "error_x", "error_y", ...
Bar
python
allegroai__clearml
clearml/backend_interface/metrics/events.py
{ "start": 5236, "end": 5704 }
class ____(MetricsEventAdapter): """Scalar event adapter""" def __init__(self, metric: str, variant: str, value: float, iter: int, **kwargs: Any) -> None: self._value = self._convert_np_nan_inf(value) super(ScalarEvent, self).__init__(metric=metric, variant=variant, iter=iter, **kwargs) de...
ScalarEvent
python
xlwings__xlwings
xlwings/_xlmac.py
{ "start": 10648, "end": 13440 }
class ____(base_classes.Books): def __init__(self, app): self.app = app @property def api(self): return None @property def active(self): return Book(self.app, self.app.xl.active_workbook.name.get()) def __call__(self, name_or_index): b = Book(self.app, name_or_...
Books
python
huggingface__transformers
src/transformers/models/auto/modeling_auto.py
{ "start": 91056, "end": 91164 }
class ____(_BaseAutoModelClass): _model_mapping = MODEL_FOR_AUDIO_XVECTOR_MAPPING
AutoModelForAudioXVector
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_str.py
{ "start": 40, "end": 98 }
class ____: def __str__(self): return 3.05
Float
python
huggingface__transformers
src/transformers/models/trocr/modeling_trocr.py
{ "start": 17829, "end": 18021 }
class ____(PreTrainedModel): config: TrOCRConfig base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["TrOCRDecoderLayer"]
TrOCRPreTrainedModel
python
huggingface__transformers
tests/models/nougat/test_tokenization_nougat.py
{ "start": 3368, "end": 5178 }
class ____(unittest.TestCase): def test_equation_tag(self): input_text = "(3.2) \\[Equation Text\\]" excepted_output = "\\[Equation Text \\tag{3.2}\\]" self.assertEqual(markdown_compatible(input_text), excepted_output) def test_equation_tag_letters(self): input_text = "(18a) \\[...
MarkdownCompatibleTest
python
FactoryBoy__factory_boy
factory/declarations.py
{ "start": 15737, "end": 18278 }
class ____(BaseDeclaration): def __init__(self, decider, yes_declaration=SKIP, no_declaration=SKIP): super().__init__() if enums.get_builder_phase(decider) is None: # No builder phase => flat value decider = SelfAttribute(decider, default=None) self.decider = decide...
Maybe
python
ansible__ansible
test/integration/targets/var_precedence/ansible-var-precedence-check.py
{ "start": 2311, "end": 4454 }
class ____(object): BASESCRIPT = '''#!/usr/bin/python import json data = """{{ data }}""" data = json.loads(data) print(json.dumps(data, indent=2, sort_keys=True)) ''' BASEINV = { '_meta': { 'hostvars': { 'testhost': {} } } } def __init__(self, f...
DynamicInventory
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 332, "end": 1041 }
class ____(BaseModel): """ See source code for the fields' description. """ model_config = ConfigDict(extra="allow", frozen=True) max_workers: Optional[int] = Field( None, description=( "The maximum number of workers to which the cluster can scale up when" "...
AutoScale
python
tensorflow__tensorflow
tensorflow/python/distribute/coordinator/values.py
{ "start": 13872, "end": 14272 }
class ____(PerWorkerValues): """Distributed iterator for `ClusterCoordinator`.""" def __next__(self): return self.get_next() def get_next(self, name=None): """Returns the next input from the iterator for all replicas.""" raise NotImplementedError("Iterating over an `AsyncDistributedIterator` " ...
PerWorkerDistributedIterator
python
django__django
tests/messages_tests/urls.py
{ "start": 1730, "end": 1847 }
class ____(forms.Form): name = forms.CharField(required=True) slug = forms.SlugField(required=True)
ContactForm
python
facelessuser__soupsieve
tests/test_level1/test_list.py
{ "start": 91, "end": 1036 }
class ____(util.TestCase): """Test selector lists.""" def test_multiple_tags(self): """Test multiple selectors.""" self.assert_selector( """ <div> <p>Some text <span id="1"> in a paragraph</span>. <a id="2" href="http://google.com">Link</a> ...
TestSelectorLists
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 63755, "end": 63992 }
class ____(BaseModel, extra="forbid"): """ Select points with null payload for a specified field """ is_null: "PayloadField" = Field(..., description="Select points with null payload for a specified field")
IsNullCondition
python
jazzband__django-polymorphic
src/polymorphic/tests/models.py
{ "start": 6118, "end": 6288 }
class ____(QuerySet): def my_queryset_foo(self): # Just a method to prove the existence of the custom queryset. return self.all()
PlainMyManagerQuerySet
python
getsentry__sentry
src/sentry_plugins/github/webhooks/events/installation.py
{ "start": 147, "end": 847 }
class ____(Webhook): # https://developer.github.com/v3/activity/events/types/#installationevent def __call__(self, event, organization): action = event["action"] installation = event["installation"] # TODO(jess): handle uninstalls if action == "created": try: ...
InstallationEventWebhook
python
donnemartin__interactive-coding-challenges
graphs_trees/tree_lca/test_lca.py
{ "start": 18, "end": 1312 }
class ____(unittest.TestCase): def test_lca(self): node10 = Node(10) node5 = Node(5) node12 = Node(12) node3 = Node(3) node1 = Node(1) node8 = Node(8) node9 = Node(9) node18 = Node(18) node20 = Node(20) node40 = Node(40) node3....
TestLowestCommonAncestor
python
huggingface__transformers
src/transformers/models/data2vec/modeling_data2vec_text.py
{ "start": 34601, "end": 37757 }
class ____(Data2VecTextPreTrainedModel): _tied_weights_keys = { "lm_head.decoder.weight": "data2vec_text.embeddings.word_embeddings.weight", "lm_head.decoder.bias": "lm_head.bias", } def __init__(self, config): super().__init__(config) if config.is_decoder: logg...
Data2VecTextForMaskedLM
python
pallets__werkzeug
tests/test_datastructures.py
{ "start": 17447, "end": 19178 }
class ____: storage_class = ds.CombinedMultiDict def test_basic_interface(self): d1 = ds.MultiDict([("foo", "1")]) d2 = ds.MultiDict([("bar", "2"), ("bar", "3")]) d = self.storage_class([d1, d2]) # lookup assert d["foo"] == "1" assert d["bar"] == "2" ass...
TestCombinedMultiDict
python
PrefectHQ__prefect
tests/telemetry/instrumentation_tester.py
{ "start": 2169, "end": 3792 }
class ____: tracer_provider: TracerProvider memory_exporter: InMemorySpanExporter meter_provider: MeterProvider memory_metrics_reader: InMemoryMetricReader def __init__(self): self.tracer_provider, self.memory_exporter = create_tracer_provider() # This is done because set_tracer_pro...
InstrumentationTester
python
ansible__ansible
lib/ansible/_internal/_errors/_handler.py
{ "start": 282, "end": 724 }
class ____(enum.Enum): """Action to take when an error is encountered.""" IGNORE = enum.auto() WARNING = enum.auto() ERROR = enum.auto() @classmethod def from_config(cls, setting: str, variables: dict[str, t.Any] | None = None) -> t.Self: """Return an `ErrorAction` enum from the specif...
ErrorAction
python
getsentry__sentry
src/sentry/utils/arroyo.py
{ "start": 4359, "end": 6999 }
class ____: def __init__(self, num_processes: int, initializer: Callable[[], None] | None = None) -> None: self.__initializer = initializer if settings.KAFKA_CONSUMER_FORCE_DISABLE_MULTIPROCESSING: self.__pool = None else: self.__pool = ArroyoMultiprocessingPool( ...
MultiprocessingPool
python
Farama-Foundation__Gymnasium
gymnasium/wrappers/common.py
{ "start": 1149, "end": 6138 }
class ____( gym.Wrapper[ObsType, ActType, ObsType, ActType], gym.utils.RecordConstructorArgs ): """Limits the number of steps for an environment through truncating the environment if a maximum number of timesteps is exceeded. If a truncation is not defined inside the environment itself, this is the only pl...
TimeLimit
python
readthedocs__readthedocs.org
readthedocs/rtd_tests/storage.py
{ "start": 242, "end": 361 }
class ____(BuildMediaFileSystemStorageTest): internal_redirect_root_path = "proxito-static"
StaticFileSystemStorageTest
python
ApeWorX__ape
src/ape/types/private_mempool.py
{ "start": 1122, "end": 1888 }
class ____(str, Enum): """ Hints on what data should be shared about the bundle and its transactions. """ CALLDATA = "calldata" """ The calldata of the bundle's transactions should be shared. """ CONTRACT_ADDRESS = "contract_address" """ The address of the bundle's transactions...
PrivacyHint
python
getsentry__sentry
src/sentry/integrations/middleware/metrics.py
{ "start": 225, "end": 694 }
class ____(StrEnum): """Different types of operations that middleware can perform.""" ENSURE_CONTROL_SILO = "ensure_control_silo" GET_CONTROL_RESPONSE = "get_control_response" GET_REGION_RESPONSE = "get_region_response" GET_RESPONSE_FROM_FIRST_REGION = "get_response_from_first_region" GET_RESP...
MiddlewareOperationType