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
numba__numba
numba/core/typed_passes.py
{ "start": 3851, "end": 7034 }
class ____(FunctionPass): _raise_errors = True def __init__(self): FunctionPass.__init__(self) def run_pass(self, state): """ Type inference and legalization """ with fallback_context(state, 'Function "%s" failed type inference' % (stat...
BaseTypeInference
python
coleifer__peewee
playhouse/apsw_ext.py
{ "start": 4909, "end": 4965 }
class ____(_DateTimeField): db_value = nh
DateTimeField
python
ZoranPandovski__al-go-rithms
search/dfs/Python/number-of-islands.py
{ "start": 0, "end": 724 }
class ____: def numIslands(self, grid): islands = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == "1": islands += 1 self.depthFirstSearch(grid, i, j) return islands ...
Solution
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF033.py
{ "start": 1557, "end": 1712 }
class ____: def __post_init__( self, bar: int = 1, # comment baz: int = 2, # comment ) -> None: pass @dataclass
Foo
python
getsentry__sentry
src/sentry/profiles/utils.py
{ "start": 721, "end": 6243 }
class ____(urllib3.Retry): """ urllib3 Retry class does not allow us to retry on read errors but to exclude read timeout. Retrying after a timeout adds useless load to Snuba. """ def increment( self, method: str | None = None, url: str | None = None, response: urllib...
RetrySkipTimeout
python
gevent__gevent
src/gevent/tests/test__hub_join_timeout.py
{ "start": 436, "end": 2814 }
class ____(TimeAssertMixin, unittest.TestCase): @repeated def test_callback(self): # exiting because the spawned greenlet finished execution (spawn (=callback) variant) x = gevent.spawn(lambda: 5) with self.runs_in_no_time(): result = gevent.wait(timeout=10) self.ass...
Test
python
ray-project__ray
doc/source/serve/doc_code/application_level_autoscaling.py
{ "start": 80, "end": 275 }
class ____: def __call__(self, input_data: str) -> str: # Simulate preprocessing work time.sleep(0.05) return f"preprocessed_{input_data}" @serve.deployment
Preprocessor
python
pypa__warehouse
tests/unit/packaging/test_views.py
{ "start": 449, "end": 4410 }
class ____: def test_normalizing_redirects(self, db_request): project = ProjectFactory.create() db_request.matchdict = {"name": project.name.swapcase()} db_request.current_route_path = pretend.call_recorder( lambda name: "/project/the-redirect/" ) resp = views.p...
TestProjectDetail
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/metadata/metadata_value.py
{ "start": 25746, "end": 26433 }
class ____(MetadataValue["DagsterJobMetadataValue"]): """Representation of a dagster run. Args: job_name (str): The job's name location_name (str): The job's code location name repository_name (Optional[str]): The job's repository name. If not provided, the job is assumed to...
DagsterJobMetadataValue
python
pytorch__pytorch
test/quantization/fx/test_model_report_fx.py
{ "start": 3370, "end": 3741 }
class ____(nn.Module): def __init__(self) -> None: super().__init__() self.block1 = ThreeOps() self.block2 = ThreeOps() def forward(self, x): x = self.block1(x) y = self.block2(x) z = x + y z = F.relu(z) return z def get_example_inputs(self):...
TwoThreeOps
python
pennersr__django-allauth
allauth/socialaccount/providers/oauth2/views.py
{ "start": 3238, "end": 3785 }
class ____: @classmethod def adapter_view(cls, adapter): @login_not_required def view(request, *args, **kwargs): self = cls() self.request = request if not isinstance(adapter, OAuth2Adapter): self.adapter = adapter(request) else: ...
OAuth2View
python
python__mypy
mypy/test/testutil.py
{ "start": 915, "end": 4233 }
class ____(TestCase): def test_junit_pass(self) -> None: serious = False messages_by_file: dict[str | None, list[str]] = {} expected = """<?xml version="1.0" encoding="utf-8"?> <testsuite errors="0" failures="0" name="mypy" skips="0" tests="1" time="1.230"> <testcase classname="mypy" file=...
TestWriteJunitXml
python
tensorflow__tensorflow
tensorflow/python/training/saving/saveable_object_util.py
{ "start": 2943, "end": 3659 }
class ____(saveable_object.SaveableObject): """SaveableObject implementation that handles reference variables.""" def __init__(self, var, slice_spec, name): spec = saveable_object.SaveSpec(var, slice_spec, name, dtype=var.dtype) super(ReferenceVariableSaveable, self).__init__(var, [spec], name) def rest...
ReferenceVariableSaveable
python
tensorflow__tensorflow
tensorflow/python/data/experimental/kernel_tests/service/distributed_save_load_test.py
{ "start": 1660, "end": 17321 }
class ____( data_service_test_base.TestBase, parameterized.TestCase): """Tests for distributed save/load with the new load algorithm.""" @combinations.generate( combinations.times( test_base.default_test_combinations(), combinations.combine( num_workers=[1, 3], ...
DistributedSaveLoadTest
python
explosion__spaCy
spacy/lang/nl/lemmatizer.py
{ "start": 97, "end": 4618 }
class ____(Lemmatizer): @classmethod def get_lookups_config(cls, mode: str) -> Tuple[List[str], List[str]]: if mode == "rule": required = ["lemma_lookup", "lemma_rules", "lemma_exc", "lemma_index"] return (required, []) else: return super().get_lookups_config(...
DutchLemmatizer
python
encode__httpx
httpx/_exceptions.py
{ "start": 7736, "end": 8490 }
class ____(StreamError): """ Attempted to access streaming request content, without having called `read()`. """ def __init__(self) -> None: message = ( "Attempted to access streaming request content," " without having called `read()`." ) super().__init__(...
RequestNotRead
python
getsentry__sentry
src/sentry/notifications/types.py
{ "start": 8068, "end": 8362 }
class ____(StrEnum): UNASSIGNED = "Unassigned" TEAM = "Team" MEMBER = "Member" ASSIGNEE_CHOICES = [ (AssigneeTargetType.UNASSIGNED.value, "Unassigned"), (AssigneeTargetType.TEAM.value, "Team"), (AssigneeTargetType.MEMBER.value, "Member"), ] @dataclass
AssigneeTargetType
python
django__django
tests/admin_inlines/models.py
{ "start": 5322, "end": 5571 }
class ____(models.Model): collection = models.ForeignKey( TitleCollection, models.SET_NULL, blank=True, null=True ) title1 = models.CharField(max_length=100) title2 = models.CharField(max_length=100) # Models for #15424
Title
python
getsentry__sentry
src/sentry/replays/lib/new_query/conditions.py
{ "start": 1226, "end": 2375 }
class ____: @staticmethod def visit_eq(expression: Expression, value: Any) -> Condition: not_supported() @staticmethod def visit_neq(expression: Expression, value: Any) -> Condition: not_supported() @staticmethod def visit_gt(expression: Expression, value: Any) -> Condition: ...
GenericBase
python
pytest-dev__pytest
src/_pytest/mark/structures.py
{ "start": 1266, "end": 2288 }
class ____(enum.Enum): token = 0 #: Can be used as a parameter set id to hide it from the test name. HIDDEN_PARAM = _HiddenParam.token def istestfunc(func) -> bool: return callable(func) and getattr(func, "__name__", "<lambda>") != "<lambda>" def get_empty_parameterset_mark( config: Config, argnames: ...
_HiddenParam
python
getsentry__sentry
src/sentry/api/endpoints/source_map_debug_blue_thunder_edition.py
{ "start": 3452, "end": 3987 }
class ____(TypedDict): dist: str | None release: str | None exceptions: list[SourceMapDebugException] has_debug_ids: bool min_debug_id_sdk_version: str | None sdk_version: str | None project_has_some_artifact_bundle: bool release_has_some_artifact: bool has_uploaded_some_artifact_wit...
SourceMapDebugResponse
python
pypa__setuptools
pkg_resources/__init__.py
{ "start": 45857, "end": 57162 }
class ____: """Manage resource extraction and packages""" extraction_path: str | None = None def __init__(self) -> None: # acts like a set self.cached_files: dict[str, Literal[True]] = {} def resource_exists( self, package_or_requirement: _PkgReqType, resource_name: str ) ...
ResourceManager
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 144453, "end": 148240 }
class ____: # In the following data, `sf` was computed with mpmath. @pytest.mark.parametrize('x, a, sf', [(0.25, 2.0, 0.9375), (0.99609375, 1/256, 1.528855235208108e-05)]) def test_sf(self, x, a, sf): assert_allclose(stats.powerlaw.sf(x, a)...
TestPowerlaw
python
falconry__falcon
tests/test_hello.py
{ "start": 500, "end": 1751 }
class ____: sample_status = '200 OK' sample_unicode = 'Hello World! \x80' + testing.rand_string(0, 0) sample_utf8 = sample_unicode.encode('utf-8') def __init__(self, mode): self.called = False self.mode = mode def on_get(self, req, resp): self.called = True self.req...
HelloResource
python
getsentry__sentry
tests/sentry/integrations/bitbucket_server/test_repository.py
{ "start": 998, "end": 10357 }
class ____(APITestCase): @cached_property def integration(self) -> Integration: with assume_test_silo_mode(SiloMode.CONTROL): integration = self.create_provider_integration( provider="bitbucket_server", name="Example Bitbucket", metadata={"veri...
BitbucketServerRepositoryProviderTest
python
numpy__numpy
numpy/f2py/tests/test_crackfortran.py
{ "start": 3848, "end": 4348 }
class ____(util.F2PyTest): # issue gh-17859: add external attribute support sources = [util.getpath("tests", "src", "crackfortran", "gh17859.f")] def test_external_as_statement(self): def incr(x): return x + 123 r = self.module.external_as_statement(incr) assert r == 12...
TestExternal
python
huggingface__transformers
src/transformers/models/switch_transformers/modeling_switch_transformers.py
{ "start": 21352, "end": 22681 }
class ____(nn.Module): def __init__(self, config, has_relative_attention_bias=False, layer_idx: Optional[int] = None): super().__init__() self.SelfAttention = SwitchTransformersAttention( config, has_relative_attention_bias=has_relative_attention_bias, layer_idx=layer_idx ) ...
SwitchTransformersLayerSelfAttention
python
streamlit__streamlit
lib/tests/streamlit/runtime/caching/cache_resource_api_test.py
{ "start": 11618, "end": 17608 }
class ____(DeltaGeneratorTestCase): def setUp(self): super().setUp() # Guard against external tests not properly cache-clearing # in their teardowns. st.cache_resource.clear() def tearDown(self): st.cache_resource.clear() @parameterized.expand(WIDGET_ELEMENTS) d...
CacheResourceMessageReplayTest
python
ray-project__ray
python/ray/tests/test_actor_state_metrics.py
{ "start": 6313, "end": 6398 }
class ____: def sleep(self): time.sleep(999) @ray.remote(num_cpus=1)
Actor1
python
getsentry__sentry
src/sentry/incidents/utils/types.py
{ "start": 665, "end": 828 }
class ____(Enum): RELEASE_CREATION = 0 DEPLOY_CREATION = 1 DATA_SOURCE_SNUBA_QUERY_SUBSCRIPTION = "snuba_query_subscription"
AlertRuleActivationConditionType
python
dask__distributed
distributed/spill.py
{ "start": 10533, "end": 10721 }
class ____(zict.File): def _safe_key(self, key: Key) -> str: # We don't need _proper_ stringification, just a unique mapping return super()._safe_key(str(key))
AnyKeyFile
python
pytorch__pytorch
torch/distributed/fsdp/_fully_shard/_fsdp_param.py
{ "start": 8758, "end": 45089 }
class ____: """ This class manages a parameter with FSDP or FSDP variants applied, implementing dim-0 per-parameter sharding. """ orig_dtype: torch.dtype param_dtype: Optional[torch.dtype] reduce_dtype: Optional[torch.dtype] _orig_size: torch.Size # ND sharded_size: torch.Size # N...
FSDPParam
python
aio-libs__aiohttp
examples/combined_middleware.py
{ "start": 4627, "end": 10619 }
class ____: """Test server with stateful endpoints for middleware testing.""" def __init__(self) -> None: self.flaky_counter = 0 self.protected_counter = 0 async def handle_protected(self, request: web.Request) -> web.Response: """Protected endpoint that requires authentication and...
TestServer
python
pytorch__pytorch
torch/_guards.py
{ "start": 15050, "end": 15780 }
class ____(GuardEnvExpr): input_source_a: Source input_source_b: Source def __post_init__(self) -> None: assert self.input_source_a != self.input_source_b """ A class representing storage overlap relations among inputs that aliases the same storage. Given that a set of tensors alias the same sto...
DuplicateInputs
python
PrefectHQ__prefect
src/prefect/events/schemas/deployment_triggers.py
{ "start": 2842, "end": 3098 }
class ____(BaseDeploymentTrigger, CompoundTrigger): """A composite trigger that requires some number of triggers to have fired within the given time period""" trigger_type: ClassVar[Type[TriggerTypes]] = CompoundTrigger
DeploymentCompoundTrigger
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 380625, "end": 381101 }
class ____(sgqlc.types.Input): """Ordering options for verifiable domain connections.""" __schema__ = github_schema __field_names__ = ("field", "direction") field = sgqlc.types.Field(sgqlc.types.non_null(VerifiableDomainOrderField), graphql_name="field") """The field to order verifiable domains by....
VerifiableDomainOrder
python
airbytehq__airbyte
airbyte-integrations/connectors/source-kyve/source_kyve/stream.py
{ "start": 1005, "end": 6843 }
class ____(HttpStream, IncrementalMixin): url_base = None cursor_field = "offset" page_size = 100 # Set this as a noop. primary_key = None name = None def __init__(self, config: Mapping[str, Any], pool_data: Mapping[str, Any], **kwargs): super().__init__(**kwargs) # Here'...
KYVEStream
python
kubernetes-client__python
kubernetes/client/models/core_v1_event.py
{ "start": 383, "end": 17942 }
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...
CoreV1Event
python
weaviate__weaviate-python-client
weaviate/collections/classes/config_vectorizers.py
{ "start": 7384, "end": 7642 }
class ____(_VectorizerConfigCreate): vectorizer: Union[Vectorizers, _EnumLikeStr] = Field( default=Vectorizers.TEXT2VEC_MODEL2VEC, frozen=True, exclude=True ) vectorizeClassName: bool inferenceUrl: Optional[str]
_Text2VecModel2VecConfig
python
huggingface__transformers
src/transformers/pipelines/image_segmentation.py
{ "start": 728, "end": 9748 }
class ____(Pipeline): """ Image segmentation pipeline using any `AutoModelForXXXSegmentation`. This pipeline predicts masks of objects and their classes. Example: ```python >>> from transformers import pipeline >>> segmenter = pipeline(model="facebook/detr-resnet-50-panoptic") >>> seg...
ImageSegmentationPipeline
python
django__django
tests/queries/models.py
{ "start": 3805, "end": 4055 }
class ____(models.Model): valid = models.CharField(max_length=10) parent = models.ManyToManyField("self") class Meta: ordering = ["valid"] # Some funky cross-linked models for testing a couple of infinite recursion # cases.
Valid
python
sqlalchemy__sqlalchemy
test/sql/test_metadata.py
{ "start": 162139, "end": 164247 }
class ____(fixtures.TestBase): def test_default_generators(self): g1, g2 = Sequence("foo_id_seq"), ColumnDefault("f5") assert Column(String, default=g1).default is g1 assert Column(String, onupdate=g1).onupdate is g1 assert Column(String, default=g2).default is g2 assert Colu...
ColumnOptionsTest
python
dagster-io__dagster
python_modules/libraries/dagster-dg-cli/dagster_dg_cli/utils/plus/gql_client.py
{ "start": 293, "end": 508 }
class ____(ABC): """Abstract base class for GraphQL clients with execute method.""" @abstractmethod def execute(self, query: str, variables: Optional[Mapping[str, Any]] = None) -> dict: ...
IGraphQLClient
python
dask__dask
dask/dataframe/dask_expr/_indexing.py
{ "start": 8850, "end": 10191 }
class ____(LocBase): def _lower(self): parts = _get_partitions(self.frame, self.iindexer) parts = sorted(parts.keys()) if len(parts) == 0: parts = [0] if self.frame.npartitions == len(parts): return return type(self)(Partitions(self.frame, parts), self...
LocList
python
wandb__wandb
wandb/automations/_filters/operators.py
{ "start": 6878, "end": 6981 }
class ____(BaseOp): val: str = Field(alias="$regex") #: The regex expression to match against.
Regex
python
pypa__pip
src/pip/_vendor/pygments/lexer.py
{ "start": 16670, "end": 23592 }
class ____(LexerMeta): """ Metaclass for RegexLexer, creates the self._tokens attribute from self.tokens on the first instantiation. """ def _process_regex(cls, regex, rflags, state): """Preprocess the regular expression component of a token definition.""" if isinstance(regex, Futur...
RegexLexerMeta
python
google__jax
tests/name_stack_test.py
{ "start": 4086, "end": 8826 }
class ____(jtu.JaxTestCase): def test_vmap_should_transform_name_stack(self): @jax.vmap def f(x): with jax.named_scope('foo'): return x + 1 jaxpr = jax.make_jaxpr(f)(jnp.ones(2)).jaxpr self.assertEqual(str(jaxpr.eqns[0].source_info.name_stack), 'vmap(foo)') def test_vmap_should_trans...
NameStackTransformationTest
python
getsentry__sentry
tests/sentry/issues/test_ingest.py
{ "start": 2566, "end": 15471 }
class ____(OccurrenceTestMixin, TestCase): def test(self) -> None: event = self.store_event(data={}, project_id=self.project.id) occurrence = self.build_occurrence(event_id=event.event_id) saved_occurrence, group_info = save_issue_occurrence(occurrence.to_dict(), event) assert group_...
SaveIssueOccurrenceTest
python
django__django
tests/model_fields/models.py
{ "start": 17634, "end": 18011 }
class ____(models.Model): name = models.CharField(max_length=10) lower_name = models.GeneratedField( expression=Lower("name"), output_field=models.CharField(db_collation=test_collation, max_length=11), db_persist=True, ) class Meta: required_db_features = {"supports_stor...
GeneratedModelOutputFieldDbCollation
python
joke2k__faker
faker/providers/address/es_ES/__init__.py
{ "start": 47, "end": 3338 }
class ____(AddressProvider): building_number_formats = ("%", "%#", "%#", "%#", "%##") street_prefixes = ( "Plaza", "Calle", "Avenida", "Via", "Vial", "Rambla", "Glorieta", "Urbanización", "Callejón", "Cañada", "Alameda", ...
Provider
python
scrapy__scrapy
tests/test_downloader_handlers_http_base.py
{ "start": 16388, "end": 23481 }
class ____(TestHttpBase): """HTTP 1.1 test case""" @deferred_f_from_coro_f async def test_download_without_maxsize_limit( self, mockserver: MockServer, download_handler: DownloadHandlerProtocol ) -> None: request = Request(mockserver.url("/text", is_secure=self.is_secure)) respo...
TestHttp11Base
python
pytorch__pytorch
test/dynamo/test_resume.py
{ "start": 315, "end": 926 }
class ____(torch._dynamo.test_case.TestCase): def test_freevars(self): fn = fn_creator() opt_fn = torch.compile(fn, backend="eager") opt_fn(torch.randn(10)) codes = [v for k, v in list(globals().items()) if k.startswith("__resume_at")] self.assertEqual(len(codes), 1) ...
ResumeFunctionTests
python
walkccc__LeetCode
solutions/3388. Count Beautiful Splits in an Array/3388.py
{ "start": 0, "end": 1084 }
class ____: def beautifulSplits(self, nums: list[int]) -> int: n = len(nums) # z[start][i] := the z array of nums[i..n) with respect to nums[start..n) z = [self._zFunction(nums, start) for start in range(n)] # nums1 | nums2 | nums3 = nums[0..i] | nums[i + 1..j] | nums[j + 1..n - 1] return...
Solution
python
google__jax
tests/scheduling_groups_test.py
{ "start": 819, "end": 4707 }
class ____(jtu.JaxTestCase): def test_basic(self): a = 1. b = 2. x = 3. y = 4. @scheduling_group(name="grp0:sub_grp0") def fn0(a, b): c = jnp.add(a, b) return c @scheduling_group(name="grp0:sub_grp1") def fn1(x, y): z = jnp.multiply(x, y) return z @sched...
SchedulingGroupsTest
python
networkx__networkx
networkx/algorithms/community/tests/test_label_propagation.py
{ "start": 3299, "end": 5073 }
class ____: def _check_communities(self, G, expected): """Checks that the communities computed from the given graph ``G`` using the :func:`~networkx.asyn_lpa_communities` function match the set of nodes given in ``expected``. ``expected`` must be a :class:`set` of :class:`frozenset`...
TestAsynLpaCommunities
python
fastai__fastai
fastai/data/transforms.py
{ "start": 3705, "end": 3963 }
class ____(ItemTransform): "Creates a proper transform that applies `itemgetter(i)` (even on a tuple)" _retain = False def __init__(self, i): self.i = i def encodes(self, x): return x[self.i] # %% ../../nbs/05_data.transforms.ipynb 28
ItemGetter
python
sphinx-doc__sphinx
sphinx/domains/cpp/_ast.py
{ "start": 69804, "end": 70750 }
class ____(ASTBase): def __init__(self, expr: ASTExpression | None) -> None: self.expr = expr def __eq__(self, other: object) -> bool: if not isinstance(other, ASTNoexceptSpec): return NotImplemented return self.expr == other.expr def __hash__(self) -> int: retu...
ASTNoexceptSpec
python
pymupdf__PyMuPDF
src/__init__.py
{ "start": 95877, "end": 97459 }
class ____: def __del__(self): if not type(self) is DisplayList: return self.thisown = False def __init__(self, *args): if len(args) == 1 and isinstance(args[0], mupdf.FzRect): self.this = mupdf.FzDisplayList(args[0]) elif len(args) == 1 and isinstance(args[0], mupdf...
DisplayList
python
numba__llvmlite
llvmlite/ir/instructions.py
{ "start": 1748, "end": 1994 }
class ____(AttributeSet): _known = frozenset(['convergent', 'noreturn', 'nounwind', 'readonly', 'readnone', 'noinline', 'alwaysinline']) TailMarkerOptions = frozenset(['tail', 'musttail', 'notail'])
CallInstrAttributes
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/sensors/test_s3.py
{ "start": 1624, "end": 17834 }
class ____: def test_bucket_name_none_and_bucket_key_as_relative_path(self): """ Test if exception is raised when bucket_name is None and bucket_key is provided as relative path rather than s3:// url. :return: """ op = S3KeySensor(task_id="s3_key_sensor", bucket_key="...
TestS3KeySensor
python
sympy__sympy
sympy/liealgebras/cartan_type.py
{ "start": 1327, "end": 1790 }
class ____(Atom): """ Concrete base class for Cartan types such as A4, etc """ def __new__(cls, series, n): obj = Basic.__new__(cls) obj.n = n obj.series = series return obj def rank(self): """ Returns the rank of the Lie algebra """ ...
Standard_Cartan
python
doocs__leetcode
solution/1900-1999/1983.Widest Pair of Indices With Equal Range Sum/Solution.py
{ "start": 0, "end": 338 }
class ____: def widestPairOfIndices(self, nums1: List[int], nums2: List[int]) -> int: d = {0: -1} ans = s = 0 for i, (a, b) in enumerate(zip(nums1, nums2)): s += a - b if s in d: ans = max(ans, i - d[s]) else: d[s] = i ...
Solution
python
django__django
tests/template_tests/test_custom.py
{ "start": 9950, "end": 25075 }
class ____(TagTestCase): def test_simple_block_tags(self): c = Context({"value": 42}) templates = [ ( "{% load custom %}{% div %}content{% enddiv %}", "<div id='test'>content</div>", ), ( "{% load custom %}{% one_pa...
SimpleBlockTagTests
python
apache__avro
lang/py/avro/schema.py
{ "start": 5639, "end": 6199 }
class ____(collections.abc.Hashable, PropertiesMixin): """A mixin that defines equality as equal if the props are equal.""" fingerprint: Callable[..., bytes] def __eq__(self, that: object) -> bool: return hasattr(that, "props") and self.props == getattr(that, "props") def __hash__(self) -> in...
EqualByPropsMixin
python
kamyu104__LeetCode-Solutions
Python/insert-delete-getrandom-o1.py
{ "start": 57, "end": 1240 }
class ____(object): def __init__(self): """ Initialize your data structure here. """ self.__set = [] self.__used = {} def insert(self, val): """ Inserts a value to the set. Returns true if the set did not already contain the specified element. :...
RandomizedSet
python
scipy__scipy
scipy/fftpack/tests/test_real_transforms.py
{ "start": 11055, "end": 11197 }
class ____(_TestIDCTBase): def setup_method(self): self.rdt = np.float64 self.dec = 10 self.type = 1
TestIDCTIDouble
python
pytorch__pytorch
torch/_export/serde/schema.py
{ "start": 8981, "end": 9049 }
class ____: arg: Annotated[Argument, 10] @dataclass
UserOutputSpec
python
huggingface__transformers
src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py
{ "start": 5525, "end": 9838 }
class ____(Qwen2AudioEncoderConfig): r""" This is the configuration class to store the configuration of a [`Qwen2_5OmniAudioEncoder`]. It is used to instantiate a Qwen2.5-Omni-Thinker audio encoder according to the specified arguments, defining the model architecture. Instantiating a configuration with ...
Qwen2_5OmniAudioEncoderConfig
python
keras-team__keras
keras/src/losses/losses.py
{ "start": 38175, "end": 44350 }
class ____(LossFunctionWrapper): """Computes the alpha balanced focal crossentropy loss. Use this crossentropy loss function when there are two or more label classes and if you want to handle class imbalance without using `class_weights`. We expect labels to be provided in a `one_hot` representatio...
CategoricalFocalCrossentropy
python
pydantic__pydantic
pydantic-core/tests/serializers/test_any.py
{ "start": 1020, "end": 1131 }
class ____: class_var: ClassVar[int] = 1 a: int b: str frog: dataclasses.InitVar[int]
MyDataclass
python
huggingface__transformers
src/transformers/trainer_utils.py
{ "start": 7645, "end": 10930 }
class ____(NamedTuple): """ The best run found by a hyperparameter search (see [`~Trainer.hyperparameter_search`]). Parameters: run_id (`str`): The id of the best run (if models were saved, the corresponding checkpoint will be in the folder ending with run-{run_id}). ...
BestRun
python
walkccc__LeetCode
solutions/3145. Find Products of Elements of Big Array/3145.py
{ "start": 0, "end": 1498 }
class ____: def findProductsOfElements(self, queries: list[list[int]]) -> list[int]: def sumBitsTill(x: int) -> int: """Returns sum(i.bit_count()), where 1 <= i <= x.""" sumBits = 0 powerOfTwo = 1 while powerOfTwo <= x: sumBits += (x // (2 * powerOfTwo)) * powerOfTwo sumBit...
Solution
python
django__django
tests/m2m_through/models.py
{ "start": 1743, "end": 1940 }
class ____(models.Model): person = models.ForeignKey(Person, models.CASCADE) group = models.ForeignKey(Group, models.CASCADE) nodefaultnonull = models.IntegerField()
TestNoDefaultsOrNulls
python
openai__openai-python
src/openai/types/conversations/conversation_item_list.py
{ "start": 269, "end": 667 }
class ____(BaseModel): data: List[ConversationItem] """A list of conversation items.""" first_id: str """The ID of the first item in the list.""" has_more: bool """Whether there are more items available.""" last_id: str """The ID of the last item in the list.""" object: Literal["...
ConversationItemList
python
kamyu104__LeetCode-Solutions
Python/rearrange-array-to-maximize-prefix-score.py
{ "start": 48, "end": 360 }
class ____(object): def maxScore(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort(reverse=True) curr = 0 for i, x in enumerate(nums): curr += x if curr <= 0: return i return len(nums)
Solution
python
PyCQA__pylint
tests/functional/u/unnecessary/unnecessary_dict_index_lookup.py
{ "start": 1406, "end": 4660 }
class ____: c_dict = {} for k, v in Foo.c_dict.items(): print(B_DICT[k]) # Should not emit warning, accessing other dictionary print(Foo.c_dict[k]) # [unnecessary-dict-index-lookup] unnecessary = 0 # pylint: disable=invalid-name unnecessary += Foo.c_dict[k] # [unnecessary-dict-index-lookup] ...
Foo
python
explosion__spaCy
spacy/util.py
{ "start": 61268, "end": 68459 }
class ____: def __call__(self, text): raise NotImplementedError def pipe(self, texts, **kwargs): for text in texts: yield self(text) # add dummy methods for to_bytes, from_bytes, to_disk and from_disk to # allow serialization (see #1557) def to_bytes(self, **kwargs): ...
DummyTokenizer
python
google__jax
tests/pallas/pallas_test.py
{ "start": 46711, "end": 71959 }
class ____(PallasBaseTest): def setUp(self): super().setUp() if self.INTERPRET: self.skipTest("Control flow not supported in interpret mode yet.") def test_loop_with_float64_carry(self): if jtu.test_device_matches(["tpu"]) and not self.INTERPRET: self.skipTest("TODO: error on TPU") # ...
PallasControlFlowTest
python
huggingface__transformers
src/transformers/models/swin2sr/modeling_swin2sr.py
{ "start": 6699, "end": 9095 }
class ____(nn.Module): """ Patch Merging Layer. Args: input_resolution (`tuple[int]`): Resolution of input feature. dim (`int`): Number of input channels. norm_layer (`nn.Module`, *optional*, defaults to `nn.LayerNorm`): Normalization layer class....
Swin2SRPatchMerging
python
lxml__lxml
src/lxml/doctestcompare.py
{ "start": 2473, "end": 13188 }
class ____(OutputChecker): empty_tags = ( 'param', 'img', 'area', 'br', 'basefont', 'input', 'base', 'meta', 'link', 'col') def get_default_parser(self): return etree.XML def check_output(self, want, got, optionflags): alt_self = getattr(self, '_temp_override_self', None) ...
LXMLOutputChecker
python
getsentry__sentry
tests/snuba/api/serializers/test_group.py
{ "start": 18886, "end": 20650 }
class ____( APITestCase, SnubaTestCase, PerformanceIssueTestCase, ): def test_perf_seen_stats(self) -> None: proj = self.create_project() first_group_fingerprint = f"{PerformanceNPlusOneGroupType.type_id}-group1" timestamp = (timezone.now() - timedelta(days=5)).replace(microseco...
PerformanceGroupSerializerSnubaTest
python
ray-project__ray
python/ray/train/tests/test_iter_torch_batches_gpu.py
{ "start": 2240, "end": 2615 }
class ____(ArrowBatchCollateFn): """Collate function that returns id and value as a dictionary of tensors.""" def __call__(self, batch: pa.Table) -> Dict[str, torch.Tensor]: """Return id and value as a dictionary of tensors.""" assert isinstance(batch, pa.Table) return arrow_batch_to_te...
DictArrowBatchCollateFn
python
encode__django-rest-framework
rest_framework/viewsets.py
{ "start": 8218, "end": 8357 }
class ____(ViewSetMixin, views.APIView): """ The base ViewSet class does not provide any actions by default. """ pass
ViewSet
python
getsentry__sentry
src/sentry/issues/grouptype.py
{ "start": 5411, "end": 6141 }
class ____: text_code_formatted: bool = True # TODO(cathy): user feedback wants it formatted as text context: list[str] = field( default_factory=lambda: [ NotificationContextField.EVENTS, NotificationContextField.USERS_AFFECTED, NotificationContextField.STATE, ...
NotificationConfig
python
facebookresearch__faiss
contrib/torch/quantization.py
{ "start": 999, "end": 1219 }
class ____(Quantizer): def __init__(self, d, k): code_size = int(math.ceil(torch.log2(k) / 8)) Quantizer.__init__(d, code_size) self.k = k def train(self, x): pass
VectorQuantizer
python
encode__django-rest-framework
rest_framework/schemas/coreapi.py
{ "start": 11688, "end": 20010 }
class ____(ViewInspector): """ Default inspector for APIView Responsible for per-view introspection and schema generation. """ def __init__(self, manual_fields=None): """ Parameters: * `manual_fields`: list of `coreapi.Field` instances that will be added to auto...
AutoSchema
python
sqlalchemy__sqlalchemy
test/dialect/mssql/test_reflection.py
{ "start": 36800, "end": 37597 }
class ____(fixtures.TestBase, AssertsCompiledSQL): def test_info_unicode_cast_no_2000(self): dialect = mssql.dialect() dialect.server_version_info = base.MS_2000_VERSION stmt = tables.c.table_name == "somename" self.assert_compile( stmt, "[INFORMATION_SCHEMA]....
InfoCoerceUnicodeTest
python
doocs__leetcode
solution/1000-1099/1063.Number of Valid Subarrays/Solution2.py
{ "start": 0, "end": 334 }
class ____: def validSubarrays(self, nums: List[int]) -> int: n = len(nums) stk = [] ans = 0 for i in range(n - 1, -1, -1): while stk and nums[stk[-1]] >= nums[i]: stk.pop() ans += (stk[-1] if stk else n) - i stk.append(i) r...
Solution
python
lxml__lxml
src/lxml/tests/test_doctestcompare.py
{ "start": 158, "end": 756 }
class ____: def __init__(self, **kw): for name, value in kw.items(): setattr(self, name, value) def indent(elem, level=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not elem.tail or not elem.tail.s...
DummyInput
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_stackdriver.py
{ "start": 4697, "end": 5210 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.stackdriver.StackdriverHook") def test_execute(self, mock_hook): operator = StackdriverDisableAlertPoliciesOperator(task_id=TEST_TASK_ID, filter_=TEST_FILTER) operator.execute(context=mock.MagicMock()) mock_hook.return_val...
TestStackdriverDisableAlertPoliciesOperator
python
django__django
tests/i18n/patterns/tests.py
{ "start": 1793, "end": 3186 }
class ____(URLTestCaseBase): """ Tests if the `i18n_patterns` is adding the prefix correctly. """ def test_not_prefixed(self): with translation.override("en"): self.assertEqual(reverse("not-prefixed"), "/not-prefixed/") self.assertEqual( reverse("not-pref...
URLPrefixTests
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/anno_test.py
{ "start": 888, "end": 2468 }
class ____(test.TestCase): def test_basic(self): node = ast.Name() self.assertEqual(anno.keys(node), set()) self.assertFalse(anno.hasanno(node, 'foo')) with self.assertRaises(AttributeError): anno.getanno(node, 'foo') anno.setanno(node, 'foo', 3) self.assertEqual(anno.keys(node), {'f...
AnnoTest
python
pandas-dev__pandas
asv_bench/benchmarks/hash_functions.py
{ "start": 1359, "end": 1857 }
class ____: params = [ (np.int64, np.uint64, np.float64), (10**4, 10**5, 5 * 10**5, 10**6, 5 * 10**6), ] param_names = ["dtype", "N"] def setup(self, dtype, N): vals = np.array(list(range(55)) + [54] + list(range(55, N - 1)), dtype=dtype) indices = pd.Index(vals) ...
NumericSeriesIndexing
python
sympy__sympy
sympy/functions/combinatorial/numbers.py
{ "start": 93635, "end": 101088 }
class ____(DefinedFunction): """ The nth Motzkin number is the number of ways of drawing non-intersecting chords between n points on a circle (not necessarily touching every point by a chord). The Motzkin numbers are named after Theodore Motzkin and have diverse applications in geometry, com...
motzkin
python
kamyu104__LeetCode-Solutions
Python/valid-number.py
{ "start": 321, "end": 1867 }
class ____(object): def isNumber(self, s): """ :type s: str :rtype: bool """ transition_table = [[-1, 0, 3, 1, 2, -1], # next states for state 0 [-1, 8, -1, 1, 4, 5], # next states for state 1 [-1, -1, -1...
Solution
python
numba__numba
numba/core/typing/builtins.py
{ "start": 21403, "end": 22050 }
class ____(AttributeTemplate): key = types.Number def resolve___class__(self, ty): return types.NumberClass(ty) def resolve_real(self, ty): return getattr(ty, "underlying_float", ty) def resolve_imag(self, ty): return getattr(ty, "underlying_float", ty) @bound_function("c...
NumberAttribute
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeParams8.py
{ "start": 114, "end": 292 }
class ____[S, T]: def task(self, input: S) -> T: ... def outer_func1[S, T](): class Child(Parent[S, T]): def task(self, input: S) -> T: ... return Child
Parent
python
doocs__leetcode
lcci/16.22.Langtons Ant/Solution.py
{ "start": 0, "end": 798 }
class ____: def printKMoves(self, K: int) -> List[str]: x1 = y1 = x2 = y2 = 0 dirs = (0, 1, 0, -1, 0) d = "RDLU" x = y = 0 p = 0 black = set() for _ in range(K): if (x, y) in black: black.remove((x, y)) p = (p + 3) %...
Solution
python
bokeh__bokeh
src/bokeh/core/property/readonly.py
{ "start": 1403, "end": 2242 }
class ____(SingleParameterizedProperty[T]): """ A property that can't be manually modified by the user. """ _readonly = True def __init__(self, type_param: TypeOrInst[Property[T]], *, default: Init[T] = Undefined, help: str | None = None) -> None: super().__init__(type_param, default=default, help...
Readonly
python
django__django
django/core/validators.py
{ "start": 16104, "end": 16551 }
class ____(BaseValidator): message = ngettext_lazy( "Ensure this value has at most %(limit_value)d character (it has " "%(show_value)d).", "Ensure this value has at most %(limit_value)d characters (it has " "%(show_value)d).", "limit_value", ) code = "max_length" ...
MaxLengthValidator