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
catalyst-team__catalyst
catalyst/contrib/losses/focal.py
{ "start": 103, "end": 1625 }
class ____(_Loss): """Compute focal loss for binary classification problem. It has been proposed in `Focal Loss for Dense Object Detection`_ paper. .. _Focal Loss for Dense Object Detection: https://arxiv.org/abs/1708.02002 """ def __init__( self, ignore: int = None, reduc...
FocalLossBinary
python
getsentry__sentry
tests/sentry/api/endpoints/test_accept_project_transfer.py
{ "start": 840, "end": 7519 }
class ____(APITestCase): def setUp(self) -> None: super().setUp() self.owner = self.create_user(email="example@example.com", is_superuser=False) self.from_organization = self.create_organization(owner=self.owner) self.to_organization = self.create_organization(owner=self.owner) ...
AcceptTransferProjectTest
python
keras-team__keras
keras/src/backend/tensorflow/name_scope_test.py
{ "start": 123, "end": 1624 }
class ____(TestCase): def test_stacking(self): self.assertEqual(tf.Variable(0, name="x").name, "x:0") with name_scope("outer") as outer: self.assertEqual(outer.name, "outer") self.assertEqual(tf.Variable(0, name="x").name, "outer/x:0") with name_scope("middle") as...
TFNameScopeTest
python
pydantic__pydantic
pydantic/v1/env_settings.py
{ "start": 11232, "end": 14105 }
class ____: __slots__ = ('secrets_dir',) def __init__(self, secrets_dir: Optional[StrPath]): self.secrets_dir: Optional[StrPath] = secrets_dir def __call__(self, settings: BaseSettings) -> Dict[str, Any]: """ Build fields from "secrets" files. """ secrets: Dict[str,...
SecretsSettingsSource
python
neetcode-gh__leetcode
python/0217-contains-duplicate.py
{ "start": 0, "end": 227 }
class ____: def containsDuplicate(self, nums: List[int]) -> bool: hashset = set() for n in nums: if n in hashset: return True hashset.add(n) return False
Solution
python
huggingface__transformers
src/transformers/models/aria/modular_aria.py
{ "start": 54104, "end": 54583 }
class ____(LlamaPreTrainedModel): config: AriaConfig base_model_prefix = "model" _can_compile_fullgraph = False # MoE models don't work with torch.compile (dynamic slicing) _supports_attention_backend = True @torch.no_grad() def _init_weights(self, module): PreTrainedModel._init_weight...
AriaPreTrainedModel
python
pyca__cryptography
src/cryptography/hazmat/primitives/hashes.py
{ "start": 3787, "end": 4263 }
class ____(HashAlgorithm, ExtendableOutputFunction): name = "shake256" block_size = None def __init__(self, digest_size: int): if not isinstance(digest_size, int): raise TypeError("digest_size must be an integer") if digest_size < 1: raise ValueError("digest_size mu...
SHAKE256
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/batchtospace_op_test.py
{ "start": 1315, "end": 1454 }
class ____(object): @staticmethod def batch_to_space(*args, **kwargs): return array_ops.batch_to_space(*args, **kwargs)
PythonOpImpl
python
getsentry__sentry
src/sentry/sentry_metrics/indexer/limiters/writes.py
{ "start": 2319, "end": 3039 }
class ____: _writes_limiter: WritesLimiter _namespace: str _requests: Sequence[RequestedQuota] _grants: Sequence[GrantedQuota] _timestamp: Timestamp accepted_keys: UseCaseKeyCollection dropped_strings: Sequence[DroppedString] def __enter__(self) -> RateLimitState: return self ...
RateLimitState
python
getsentry__sentry
tests/sentry/tasks/test_process_buffer.py
{ "start": 258, "end": 960 }
class ____(TestCase): def test_constraints_model_name(self) -> None: with pytest.raises(AssertionError) as err: process_incr(model_name="group", columns={"times_seen": 1}, filters={"pk": 1}) assert "model_name must be in form" in str(err) @mock.patch("sentry.buffer.backend.process")...
ProcessIncrTest
python
great-expectations__great_expectations
great_expectations/expectations/metrics/column_map_metrics/column_values_match_like_pattern.py
{ "start": 440, "end": 1081 }
class ____(ColumnMapMetricProvider): condition_metric_name = "column_values.match_like_pattern" condition_value_keys = ("like_pattern",) @column_condition_partial(engine=SqlAlchemyExecutionEngine) def _sqlalchemy(cls, column, like_pattern, _dialect, **kwargs): like_pattern_expression = get_dial...
ColumnValuesMatchLikePattern
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_datasync.py
{ "start": 35121, "end": 39275 }
class ____(DataSyncTestCaseBase): def set_up_operator(self, task_id="test_datasync_delete_task_operator", task_arn="self"): if task_arn == "self": task_arn = self.task_arn # Create operator self.datasync = DataSyncOperator( task_id=task_id, dag=self.dag, ...
TestDataSyncOperatorDelete
python
tensorflow__tensorflow
tensorflow/python/framework/type_spec_test.py
{ "start": 3237, "end": 3742 }
class ____(TwoTensorsSpec): def _serialize(self): if self.color == "smaller_tuple": return (self.x_shape, self.x_dtype, self.y_shape, self.y_dtype) elif self.color == "different_order": return (self.y_shape, self.x_shape, self.y_dtype, self.color, self.x_dtype) return (self.x_s...
TwoTensorsSpecVariableSerialize
python
viewflow__viewflow
viewflow/workflow/fields.py
{ "start": 3806, "end": 4698 }
class ____(models.CharField): def __init__(self, *args, **kwargs): kwargs.setdefault("max_length", 255) super(TaskReferenceField, self).__init__(*args, **kwargs) def to_python(self, value): if value: return import_task_by_ref(value) # TODO Raise ValidationError ret...
TaskReferenceField
python
getsentry__sentry
tests/sentry/db/postgres/schema/safe_migrations/integration/test_migrations.py
{ "start": 7000, "end": 7250 }
class ____(BaseSafeMigrationTest): app = "good_flow_safe_run_sql_with_run_sql_disabled_app" migrate_from = "0001_initial" migrate_to = "0001_initial" def test(self) -> None: self.run_migration()
SafeRunSqlWithRunSqlDisabledTest
python
huggingface__transformers
src/transformers/models/reformer/modeling_reformer.py
{ "start": 48346, "end": 57829 }
class ____(nn.Module, EfficientAttentionMixin): def __init__(self, config, layer_idx=None): super().__init__() self.num_attention_heads = config.num_attention_heads self.chunk_length = config.local_attn_chunk_length self.num_chunks_before = config.local_num_chunks_before sel...
LocalSelfAttention
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_execute_pipeline.py
{ "start": 1858, "end": 28745 }
class ____(ExecutingGraphQLContextTestMatrix): def test_start_pipeline_execution(self, graphql_context: WorkspaceRequestContext): selector = infer_job_selector(graphql_context, "csv_hello_world") result = execute_dagster_graphql( graphql_context, LAUNCH_PIPELINE_EXECUTION_MUT...
TestExecutePipeline
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_relationship.py
{ "start": 1889, "end": 5001 }
class ____(fixtures.MappedTest): run_setup_mappers = "once" @classmethod def define_tables(cls, metadata): Table( "people", metadata, Column( "person_id", Integer, primary_key=True, test_needs_autoin...
SelfReferentialTestJoinedToBase
python
pandas-dev__pandas
pandas/tests/frame/indexing/test_indexing.py
{ "start": 52559, "end": 54702 }
class ____: def test_setitem(self): df = DataFrame( {"A": np.arange(3), "B": [2**63, 2**63 + 5, 2**63 + 10]}, dtype=np.uint64, ) idx = df["A"].rename("foo") # setitem assert "C" not in df.columns df["C"] = idx tm.assert_series_equal(df...
TestDataFrameIndexingUInt64
python
openai__openai-python
src/openai/types/conversations/item_create_params.py
{ "start": 378, "end": 874 }
class ____(TypedDict, total=False): items: Required[Iterable[ResponseInputItemParam]] """The items to add to the conversation. You may add up to 20 items at a time.""" include: List[ResponseIncludable] """Additional fields to include in the response. See the `include` parameter for [listing Co...
ItemCreateParams
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pycodestyle/E30.py
{ "start": 3291, "end": 3489 }
class ____: def method(self): if True: def function(): pass # end # no error @decorator async def function(data: None) -> None: ... # end # no error
Class
python
tornadoweb__tornado
tornado/web.py
{ "start": 126074, "end": 126784 }
class ____: """A transform modifies the result of an HTTP request (e.g., GZip encoding) Applications are not expected to create their own OutputTransforms or interact with them directly; the framework chooses which transforms (if any) to apply. """ def __init__(self, request: httputil.HTTPServ...
OutputTransform
python
numba__numba
numba/cuda/cudamath.py
{ "start": 3249, "end": 3512 }
class ____(ConcreteTemplate): cases = [ signature(types.float32, types.float32, types.int32), signature(types.float64, types.float64, types.int32), ] @infer_global(math.isinf) @infer_global(math.isnan) @infer_global(math.isfinite)
Math_ldexp
python
kamyu104__LeetCode-Solutions
Python/string-compression-ii.py
{ "start": 39, "end": 985 }
class ____(object): def getLengthOfOptimalCompression(self, s, k): """ :type s: str :type k: int :rtype: int """ def length(cnt): l = 2 if cnt >= 2 else 1 while cnt >= 10: l += 1 cnt //= 10 return l ...
Solution
python
tiangolo__fastapi
fastapi/background.py
{ "start": 214, "end": 1793 }
class ____(StarletteBackgroundTasks): """ A collection of background tasks that will be called after a response has been sent to the client. Read more about it in the [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/). ## Example ```python fro...
BackgroundTasks
python
keras-team__keras
keras/src/ops/math.py
{ "start": 9104, "end": 11293 }
class ____(Operation): def __init__(self, sequence_length, sequence_stride, *, name=None): super().__init__(name=name) self.sequence_length = sequence_length self.sequence_stride = sequence_stride def compute_output_spec(self, x): if len(x.shape) < 1: raise ValueErro...
ExtractSequences
python
PyCQA__pylint
pylint/pyreverse/inspector.py
{ "start": 1280, "end": 1719 }
class ____: """Mixin adding the ability to generate integer uid.""" def __init__(self, start_value: int = 0) -> None: self.id_count = start_value def init_counter(self, start_value: int = 0) -> None: """Init the id counter.""" self.id_count = start_value def generate_id(self) ...
IdGeneratorMixIn
python
pandas-dev__pandas
asv_bench/benchmarks/series_methods.py
{ "start": 5502, "end": 5782 }
class ____: params = [10**3, 10**4, 10**5] param_names = ["N"] def setup(self, N): self.s = Series(np.random.randint(0, N, size=10 * N)).astype("object") def time_value_counts(self, N): self.s.value_counts(dropna=False)
ValueCountsObjectDropNAFalse
python
dask__distributed
distributed/shuffle/_exceptions.py
{ "start": 200, "end": 294 }
class ____(Exception): """Raised when data is not available in the buffer"""
DataUnavailable
python
scipy__scipy
scipy/stats/_discrete_distns.py
{ "start": 3548, "end": 5167 }
class ____(binom_gen): r"""A Bernoulli discrete random variable. %(before_notes)s Notes ----- The probability mass function for `bernoulli` is: .. math:: f(k) = \begin{cases}1-p &\text{if } k = 0\\ p &\text{if } k = 1\end{cases} for :math:`k` in :ma...
bernoulli_gen
python
pypa__setuptools
setuptools/_vendor/typeguard/_importhook.py
{ "start": 4575, "end": 6387 }
class ____: """ A handle that can be used to uninstall the Typeguard import hook. """ def __init__(self, hook: MetaPathFinder): self.hook = hook def __enter__(self) -> None: pass def __exit__( self, exc_type: type[BaseException], exc_val: BaseException,...
ImportHookManager
python
pypa__warehouse
tests/unit/email/ses/test_views.py
{ "start": 2422, "end": 4004 }
class ____: def test_raises_when_invalid_type(self): request = pretend.stub(json_body={"Type": "Notification"}) with pytest.raises(HTTPBadRequest): views.confirm_subscription(request) def test_confirms(self, monkeypatch): data = { "Type": "SubscriptionConfirmati...
TestConfirmSubscription
python
huggingface__transformers
src/transformers/models/clvp/modeling_clvp.py
{ "start": 43764, "end": 50549 }
class ____(ClvpPreTrainedModel): """ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`ClvpDecoderLayer`] """ def __init__(self, config): super().__init__(config) self.config = config self.input_embeds_layer = nn.Embedding(self.config.vocab...
ClvpDecoder
python
python-openxml__python-docx
src/docx/oxml/shape.py
{ "start": 1327, "end": 1570 }
class ____(BaseOxmlElement): """``<a:graphic>`` element, container for a DrawingML object.""" graphicData: CT_GraphicalObjectData = OneAndOnlyOne( # pyright: ignore[reportAssignmentType] "a:graphicData" )
CT_GraphicalObject
python
huggingface__transformers
src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
{ "start": 20140, "end": 22739 }
class ____(GradientCheckpointingLayer): """Conformer block based on https://huggingface.co/papers/2005.08100.""" # Copied from transformers.models.wav2vec2_conformer.modeling_wav2vec2_conformer.Wav2Vec2ConformerEncoderLayer.__init__ with Wav2Vec2->SeamlessM4Tv2, attention_dropout->speech_encoder_dropout, torch...
SeamlessM4Tv2ConformerEncoderLayer
python
django__django
django/db/backends/mysql/operations.py
{ "start": 420, "end": 17396 }
class ____(BaseDatabaseOperations): compiler_module = "django.db.backends.mysql.compiler" # MySQL stores positive fields as UNSIGNED ints. integer_field_ranges = { **BaseDatabaseOperations.integer_field_ranges, "PositiveSmallIntegerField": (0, 65535), "PositiveIntegerField": (0, 429...
DatabaseOperations
python
gevent__gevent
src/gevent/tests/test__pywsgi.py
{ "start": 6582, "end": 11643 }
class ____(greentest.TestCase): server = None validator = staticmethod(validator) application = None # Bind to default address, which should give us ipv6 (when available) # and ipv4. (see self.connect()) listen_addr = greentest.DEFAULT_BIND_ADDR # connect on ipv4, even though we bound to ip...
TestCase
python
vyperlang__vyper
vyper/venom/basicblock.py
{ "start": 3979, "end": 5447 }
class ____(IROperand): """ operand representing an offset into an alloca'ed memory segment which has not be concretized (allocated) yet. """ _id: int # size of the memory segment size: int # offset inside of a memory segment offset: int _curr_id: ClassVar[int] = 0 FREE_VA...
IRAbstractMemLoc
python
kamyu104__LeetCode-Solutions
Python/count-prefix-and-suffix-pairs-i.py
{ "start": 61, "end": 631 }
class ____(object): def countPrefixSuffixPairs(self, words): """ :type words: List[str] :rtype: int """ _trie = lambda: collections.defaultdict(_trie) trie = _trie() result = 0 for w in words: curr = trie for i in xrange(len(w))...
Solution
python
pexpect__pexpect
tests/test_pickling.py
{ "start": 91, "end": 338 }
class ____(unittest.TestCase): def test_picking(self): e = ExceptionPexpect('Oh noes!') clone = pickle.loads(pickle.dumps(e)) self.assertEqual(e.value, clone.value) if __name__ == '__main__': unittest.main()
PickleTest
python
scrapy__scrapy
tests/mockserver/http_resources.py
{ "start": 7881, "end": 8190 }
class ____(resource.Resource): """ A testing resource which renders itself as the value of request body without content-type header in response. """ def render(self, request): request.setHeader("content-type", "") return request.content.read()
EmptyContentTypeHeaderResource
python
ray-project__ray
python/ray/autoscaler/v2/tests/util.py
{ "start": 4101, "end": 4516 }
class ____(Check): def __init__(self, count: int): self.count = count def check(self, status: ClusterStatus): healthy_nodes = len(status.active_nodes) + len(status.idle_nodes) if healthy_nodes != self.count: raise CheckFailure(f"Expected {self.count} nodes, got {healthy_node...
NodeCountCheck
python
mlflow__mlflow
mlflow/pyfunc/loaders/chat_agent.py
{ "start": 671, "end": 4436 }
class ____: """ Wrapper class that converts dict inputs to pydantic objects accepted by :class:`~ChatAgent`. """ def __init__(self, chat_agent): """ Args: chat_agent: An instance of a subclass of :class:`~ChatAgent`. """ self.chat_agent = chat_agent def ...
_ChatAgentPyfuncWrapper
python
matplotlib__matplotlib
lib/matplotlib/testing/compare.py
{ "start": 4558, "end": 8399 }
class ____(_Converter): def __call__(self, orig, dest): old_inkscape = mpl._get_executable_info("inkscape").version.major < 1 terminator = b"\n>" if old_inkscape else b"> " if not hasattr(self, "_tmpdir"): self._tmpdir = TemporaryDirectory() # On Windows, we must make...
_SVGConverter
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/triggers/cloud_composer.py
{ "start": 1332, "end": 3392 }
class ____(BaseTrigger): """The trigger handles the async communication with the Google Cloud Composer.""" def __init__( self, project_id: str, region: str, operation_name: str, gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] |...
CloudComposerExecutionTrigger
python
sqlalchemy__sqlalchemy
examples/sharding/asyncio.py
{ "start": 1876, "end": 3190 }
class ____(DeclarativeBase): pass # we need a way to create identifiers which are unique across all databases. # one easy way would be to just use a composite primary key, where one value # is the shard id. but here, we'll show something more "generic", an id # generation function. we'll use a simplistic "id t...
Base
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/check_ops_test.py
{ "start": 24380, "end": 27355 }
class ____(test.TestCase): @test_util.run_in_graph_and_eager_modes def test_doesnt_raise_when_equal(self): small = constant_op.constant([1, 2], name="small") with ops.control_dependencies( [check_ops.assert_less_equal(small, small)]): out = array_ops.identity(small) self.evaluate(out) ...
AssertLessEqualTest
python
has2k1__plotnine
plotnine/themes/theme_matplotlib.py
{ "start": 188, "end": 4248 }
class ____(theme): """ The default matplotlib look and feel. The theme can be used (and has the same parameter to customize) like a [](`matplotlib.rc_context`) manager. Parameters ---------- rc : dict rcParams which should be applied on top of mathplotlib default. fname : str ...
theme_matplotlib
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/overloadOverlap1.py
{ "start": 5471, "end": 6555 }
class ____(Protocol): def __radd__(self: _T1, other: Any, /) -> _T1: ... @overload def func19(a: Any, b: DProto2) -> DProto2: ... @overload def func19(a: Any, b: DProto1) -> Any: ... def func19(a: Any, b: Any) -> Any: return a + b AllStr = bytes | str @overload def func20(choices: AnyStr) -> AnyStr: ....
DProto2
python
realpython__materials
hangman-pysimplegui/source_code_final/hangman.py
{ "start": 112, "end": 8029 }
class ____: def __init__(self): layout = [ [ self._build_canvas_frame(), self._build_letters_frame(), ], [ self._build_guessed_word_frame(), ], [ self._build_action_buttons_frame(), ...
Hangman
python
getsentry__sentry
tests/sentry/releases/endpoints/test_organization_release_file_details.py
{ "start": 5580, "end": 6846 }
class ____(APITestCase): def test_simple(self) -> None: self.login_as(user=self.user) project = self.create_project(name="foo") release = Release.objects.create(organization_id=project.organization_id, version="1") release.add_project(project) assert release.count_artifact...
ReleaseFileDeleteTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclass17.py
{ "start": 168, "end": 586 }
class ____: a: Final[int] b: Final[str] = "" c: ClassVar[Final[int]] = 0 d: ClassVar[Final] = 0 e: Final[ClassVar[int]] = 0 a = A(1) # This should generate an error. a.a = 0 # This should generate an error. a.b = "" # This should generate an error. a.c = 0 # This should generate an error. A.c ...
A
python
PyCQA__pylint
doc/data/messages/l/lost-exception/good.py
{ "start": 0, "end": 346 }
class ____(ZeroDivisionError): def __init__(self): super().__init__("You can't go faster than the speed of light !") def calculate_speed(distance: float, time: float) -> float: try: return distance / time except ZeroDivisionError as e: raise FasterThanTheSpeedOfLightError() from e
FasterThanTheSpeedOfLightError
python
sqlalchemy__sqlalchemy
test/typing/plain_files/ext/asyncio/async_sessionmaker.py
{ "start": 894, "end": 2649 }
class ____(Base): __tablename__ = "b" id: Mapped[int] = mapped_column(primary_key=True) a_id = mapped_column(ForeignKey("a.id")) data: Mapped[str] def work_with_a_session_one(sess: Session) -> Any: pass def work_with_a_session_two(sess: Session, param: Optional[str] = None) -> Any: pass de...
B
python
getsentry__sentry
src/sentry/api/serializers/rest_framework/environment.py
{ "start": 139, "end": 637 }
class ____(serializers.Field): def to_representation(self, value): return value def to_internal_value(self, data): if data is None: return None try: environment = Environment.objects.get( organization_id=self.context["organization"].id, name=data ...
EnvironmentField
python
sphinx-doc__sphinx
doc/usage/extensions/example_numpy.py
{ "start": 4941, "end": 5806 }
class ____(Exception): """Exceptions are documented in the same way as classes. The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself. Either form is acceptable, but the two should not be mixed. Choose one convention to document ...
ExampleError
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 489547, "end": 490189 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field( sgqlc.types.list_of("PackageVersionEdge"), graphql_name="edges" ) nodes = sgql...
PackageVersionConnection
python
modin-project__modin
modin/config/envvars.py
{ "start": 38962, "end": 39167 }
class ____(EnvironmentVariable, type=str): """Set to AWS_ACCESS_KEY_ID when running mock S3 tests for Modin in GitHub CI.""" varname = "AWS_ACCESS_KEY_ID" default = "foobar_key"
CIAWSAccessKeyID
python
automl__auto-sklearn
test/test_pipeline/test_classification.py
{ "start": 2724, "end": 3548 }
class ____(AutoSklearnPreprocessingAlgorithm): def __init__(*args, **kwargs): pass @staticmethod def get_properties(dataset_properties=None): return { "shortname": "AB", "name": "AdaBoost Classifier", "handles_regression": False, "handles_clas...
CrashPreprocessor
python
instagram__MonkeyType
demo/models.py
{ "start": 1980, "end": 2290 }
class ____(InboxEvent): type = EventType.FOLLOWED def __init__( self, id: InboxEventId, user_id: UserId, published: datetime, follower_id: UserId, ) -> None: super().__init__(id, user_id, published) self.follower_id = follower_id
FollowedEvent
python
airbytehq__airbyte
airbyte-integrations/connectors/source-salesforce/source_salesforce/streams.py
{ "start": 2875, "end": 7097 }
class ____(HttpStream, ABC): state_converter = IsoMillisConcurrentStreamStateConverter(is_sequential_state=False) page_size = 2000 transformer = TypeTransformer(TransformConfig.DefaultSchemaNormalization) encoding = DEFAULT_ENCODING def __init__( self, sf_api: Salesforce, pk...
SalesforceStream
python
doocs__leetcode
solution/1200-1299/1208.Get Equal Substrings Within Budget/Solution2.py
{ "start": 0, "end": 368 }
class ____: def equalSubstring(self, s: str, t: str, maxCost: int) -> int: n = len(s) ans = cost = l = 0 for r in range(n): cost += abs(ord(s[r]) - ord(t[r])) while cost > maxCost: cost -= abs(ord(s[l]) - ord(t[l])) l += 1 a...
Solution
python
PrefectHQ__prefect
tests/blocks/test_abstract.py
{ "start": 3875, "end": 7592 }
class ____: def test_database_block_is_abstract(self): with pytest.raises( TypeError, match="Can't instantiate abstract class DatabaseBlock" ): DatabaseBlock() async def test_database_block_implementation(self, caplog): class ADatabaseBlock(DatabaseBlock): ...
TestDatabaseBlock
python
altair-viz__altair
altair/vegalite/v6/schema/_config.py
{ "start": 180626, "end": 201767 }
class ____(TypedDict, total=False): """ :class:`altair.OverlayMarkDef` ``TypedDict`` wrapper. Parameters ---------- align The horizontal alignment of the text or ranged marks (area, bar, image, rect, rule). One of ``"left"``, ``"right"``, ``"center"``. **Note:** Expression ...
OverlayMarkDefKwds
python
PrefectHQ__prefect
src/integrations/prefect-databricks/prefect_databricks/models/jobs.py
{ "start": 53042, "end": 54386 }
class ____(BaseModel): """ See source code for the fields' description. """ model_config = ConfigDict(extra="allow", frozen=True) jar_uri: Optional[str] = Field( None, deprecated=True, description=( "Deprecated since 04/2016\\. Provide a `jar` through the `libra...
SparkJarTask
python
django__django
django/contrib/auth/views.py
{ "start": 13699, "end": 13870 }
class ____(PasswordContextMixin, TemplateView): template_name = "registration/password_change_done.html" title = _("Password change successful")
PasswordChangeDoneView
python
sqlalchemy__sqlalchemy
test/aaa_profiling/test_resultset.py
{ "start": 5238, "end": 6181 }
class ____(fixtures.TestBase): __backend__ = True def test_minimal_connection_execute(self): # create an engine without any instrumentation. e = create_engine("sqlite://") c = e.connect() # ensure initial connect activities complete c.exec_driver_sql("select 1") ...
ExecutionTest
python
sqlalchemy__sqlalchemy
test/sql/test_operators.py
{ "start": 47394, "end": 51897 }
class ____(fixtures.TestBase, testing.AssertsCompiledSQL): """test standalone booleans being wrapped in an AsBoolean, as well as true/false compilation.""" def _dialect(self, native_boolean): d = default.DefaultDialect() d.supports_native_boolean = native_boolean return d def t...
BooleanEvalTest
python
aimacode__aima-python
mdp.py
{ "start": 9216, "end": 13120 }
class ____(MDP): """A Partially Observable Markov Decision Process, defined by a transition model P(s'|s,a), actions A(s), a reward function R(s), and a sensor model P(e|s). We also keep track of a gamma value, for use by algorithms. The transition and the sensor models are defined as matrices. We a...
POMDP
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/assets/graph/asset_graph_differ.py
{ "start": 1832, "end": 8338 }
class ____: """Given two asset graphs, base_asset_graph and branch_asset_graph, we can compute how the assets in branch_asset_graph have changed with respect to base_asset_graph. The ChangeReason enum contains the list of potential changes an asset can undergo. If the base_asset_graph is None, this indi...
AssetGraphDiffer
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/instigation.py
{ "start": 4572, "end": 4778 }
class ____(graphene.Enum): ADD_PARTITIONS = "ADD_PARTITIONS" DELETE_PARTITIONS = "DELETE_PARTITIONS" class Meta: name = "DynamicPartitionsRequestType"
GrapheneDynamicPartitionsRequestType
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 49668, "end": 50376 }
class ____(themeable): """ x-axis minor-tick length Parameters ---------- theme_element : float | complex Value in points. A negative value creates the ticks inside the plot panel. A complex value (e.g. `3j`) creates ticks that span both in and out of the panel. """ ...
axis_ticks_length_minor_x
python
django__django
tests/queries/tests.py
{ "start": 138475, "end": 138875 }
class ____(TestCase): def test_evaluated_proxy_count(self): """ Generating the query string doesn't alter the query's state in irreversible ways. Refs #18248. """ ProxyCategory.objects.create() qs = ProxyCategory.objects.all() self.assertEqual(qs.count(), 1) ...
ProxyQueryCleanupTest
python
django__django
django/contrib/postgres/fields/ranges.py
{ "start": 9835, "end": 9981 }
class ____(PostgresOperatorLookup): lookup_name = "not_lt" postgres_operator = RangeOperators.NOT_LT @RangeField.register_lookup
NotLessThan
python
ray-project__ray
python/ray/util/state/common.py
{ "start": 28011, "end": 28416 }
class ____(StateSchema): severity: str = state_column(filterable=True) time: str = state_column(filterable=False) source_type: str = state_column(filterable=True) message: str = state_column(filterable=False) event_id: str = state_column(filterable=True) custom_fields: Optional[dict] = state_col...
ClusterEventState
python
ray-project__ray
python/ray/serve/tests/unit/test_deployment_state.py
{ "start": 99003, "end": 138996 }
class ____: def scale( self, dsm: DeploymentStateManager, asm: AutoscalingStateManager, deployment_ids: List[DeploymentID], ): if not deployment_ids: return app_name = deployment_ids[0].app_name assert all(dep_id.app_name == app_name for dep_i...
TestAutoscaling
python
pytorch__pytorch
torch/_dynamo/variables/misc.py
{ "start": 71874, "end": 74656 }
class ____(VariableTracker): """self.value is a compile-time constant, but not a literal""" _error_prefix = "ConstantLikeVariable" try: from numpy import ( dtype as np_dtype, floating as np_floating, generic as np_generic, ) except ImportError: ...
ConstantLikeVariable
python
explosion__spaCy
spacy/lang/th/__init__.py
{ "start": 1090, "end": 1237 }
class ____(BaseDefaults): config = load_config_from_str(DEFAULT_CONFIG) lex_attr_getters = LEX_ATTRS stop_words = STOP_WORDS
ThaiDefaults
python
great-expectations__great_expectations
great_expectations/expectations/core/expect_column_values_to_not_match_regex_list.py
{ "start": 2193, "end": 15383 }
class ____(ColumnMapExpectation): __doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION} ExpectColumnValuesToNotMatchRegexList is a \ Column Map Expectation. Column Map Expectations are one of the most common types of Expectation. They are evaluated for a single column and ask a yes/no question for every r...
ExpectColumnValuesToNotMatchRegexList
python
pytorch__pytorch
test/distributed/test_c10d_common.py
{ "start": 11158, "end": 11398 }
class ____(nn.Module): def __init__(self) -> None: super().__init__() self.embedding = nn.EmbeddingBag(10, 10, sparse=True) def forward(self, x): return F.softmax(self.embedding(x), dim=1)
SparseGradientModule
python
huggingface__transformers
tests/models/ijepa/test_modeling_ijepa.py
{ "start": 1459, "end": 6046 }
class ____: def __init__( self, parent, batch_size=13, image_size=30, patch_size=2, num_channels=3, is_training=True, use_labels=True, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, ...
IJepaModelTester
python
encode__django-rest-framework
tests/test_fields.py
{ "start": 10790, "end": 11350 }
class ____: def setup_method(self): def initial_value(): return 123 class TestSerializer(serializers.Serializer): initial_field = serializers.IntegerField(initial=initial_value) self.serializer = TestSerializer() def test_initial_should_accept_callable(self): ...
TestInitialWithCallable
python
numba__numba
numba/core/datamodel/testing.py
{ "start": 3125, "end": 4140 }
class ____(object): """Test as_data() and from_data() """ # XXX test load_from_data_pointer() as well def test_as_data(self): fnty = ir.FunctionType(ir.VoidType(), []) function = ir.Function(self.module, fnty, name="test_as_data") builder = ir.IRBuilder() builder.positio...
SupportAsDataMixin
python
huggingface__transformers
tests/models/metaclip_2/test_modeling_metaclip_2.py
{ "start": 20536, "end": 23965 }
class ____(MetaClip2ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (MetaClip2Model,) if is_torch_available() else () pipeline_model_mapping = ( {"feature-extraction": MetaClip2Model, "image-feature-extraction": MetaClip2VisionModel} if is_torch_available() ...
MetaClip2ModelTest
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/feature_store.py
{ "start": 8903, "end": 12539 }
class ____(GoogleCloudBaseOperator, OperationHelper): """ Get Feature Online store instance. This method initiates VertexAI Feature Online Store creation request. Feature Online Store aims to serve and manage features data as a part of VertexAI MLOps. :param project_id: Required. The ID of the Goo...
GetFeatureOnlineStoreOperator
python
getsentry__sentry
tests/sentry/integrations/slack/threads/activity_notifications/test_external_issue_created_activity.py
{ "start": 926, "end": 1752 }
class ____(BaseTestCase): def test_when_link_key_is_not_in_map(self) -> None: self.activity.data = {} create_issue_activity = _ExternalIssueCreatedActivity(self.activity) ret = create_issue_activity.get_link() assert ret == "" def test_when_link_key_is_empty(self) -> None: ...
TestGetLink
python
scipy__scipy
benchmarks/benchmarks/optimize_linprog.py
{ "start": 4912, "end": 5488 }
class ____(Benchmark): params = [ methods, range(20, 100, 20), range(20, 100, 20) ] param_names = ['method', 'm', 'n'] def setup(self, meth, m, n): self.A, self.b, self.c = lpgen_2d(m, n) def time_lpgen(self, meth, m, n): method, options = meth with ...
LpGen
python
google__jax
jax/experimental/mosaic/gpu/utils.py
{ "start": 11121, "end": 13784 }
class ____: op: scf.ForOp results: tuple[Any, ...] @property def result(self): if len(self.results) != 1: raise ValueError return self.results[0] def fori(bound, carrys): unwrap = False if not isinstance(carrys, (list, tuple)): carrys = [carrys] unwrap = True flat_carrys, carry_tr...
ForResult
python
Netflix__metaflow
test/core/tests/switch_basic.py
{ "start": 63, "end": 940 }
class ____(MetaflowTest): """ Tests a basic switch with multiple branches. """ PRIORITY = 2 ONLY_GRAPHS = ["simple_switch"] @steps(0, ["start"], required=True) def step_start(self): self.condition = "case2" @steps(0, ["switch-simple"], required=True) def step_switch_simple...
BasicSwitchTest
python
dagster-io__dagster
python_modules/libraries/dagster-azure/dagster_azure/fakes/fake_adls2_resource.py
{ "start": 1342, "end": 1975 }
class ____: def __init__(self, client): self.client = client self.id = None # client needs a ref to self to check if a given lease is valid self.client._lease = self # noqa: SLF001 def acquire(self, lease_duration=-1): if self.id is None: self.id = random.r...
FakeLeaseClient
python
scipy__scipy
scipy/fft/_pocketfft/tests/test_basic.py
{ "start": 8185, "end": 8367 }
class ____(_TestIFFTBase): def setup_method(self): self.cdt = np.complex128 self.rdt = np.float64 self.rtol = 1e-10 self.atol = 1e-10
TestDoubleIFFT
python
pypa__warehouse
tests/unit/legacy/api/xmlrpc/test_cache.py
{ "start": 6536, "end": 9733 }
class ____: def test_redis_lru(self, mockredis): redis_lru = RedisLru(mockredis) expected = func_test(0, 1, kwarg0=2, kwarg1=3) assert expected == redis_lru.fetch( func_test, [0, 1], {"kwarg0": 2, "kwarg1": 3}, None, None, None ) assert expected == redis_lru.fet...
TestRedisLru
python
tiangolo__fastapi
tests/test_validate_response_recursive/app.py
{ "start": 143, "end": 233 }
class ____(BaseModel): sub_items: List["RecursiveItem"] = [] name: str
RecursiveItem
python
coleifer__peewee
tests/regressions.py
{ "start": 51165, "end": 51311 }
class ____(TestModel): id = CharField(primary_key=True) name = CharField(unique=True) def __str__(self): return self.name
CharPK
python
pandas-dev__pandas
pandas/io/parsers/readers.py
{ "start": 4025, "end": 65272 }
class ____(TypedDict): colspecs: Literal["infer"] infer_nrows: Literal[100] widths: None _fwf_defaults: _Fwf_Defaults = {"colspecs": "infer", "infer_nrows": 100, "widths": None} _c_unsupported = {"skipfooter"} _python_unsupported = {"low_memory", "float_precision"} _pyarrow_unsupported = { "skipfooter...
_Fwf_Defaults
python
ray-project__ray
python/ray/tune/search/sample.py
{ "start": 5189, "end": 5521 }
class ____(Sampler): """Dummy sampler used for grid search""" def sample( self, domain: Domain, config: Optional[Union[List[Dict], Dict]] = None, size: int = 1, random_state: "RandomState" = None, ): return RuntimeError("Do not call `sample()` on grid.") @D...
Grid
python
airbytehq__airbyte
airbyte-integrations/connectors/source-shopify/source_shopify/shopify_graphql/bulk/query.py
{ "start": 88742, "end": 95872 }
class ____(ShopifyBulkQuery): """ { products( query: "updated_at:>='2019-04-13T00:00:00+00:00' AND updated_at:<='2024-04-30T12:16:17.273363+00:00'" sortKey: UPDATED_AT ) { edges { node { __typename id ...
ProductImage
python
conda__conda
conda/activate.py
{ "start": 36473, "end": 37591 }
class ____(_Activator): pathsep_join = ";".join if on_win else ":".join sep = "/" path_conversion = staticmethod( backslash_to_forwardslash if on_win else _path_identity ) # 'scripts' really refer to de/activation scripts, not scripts in the language per se # xonsh can piggy-back activat...
XonshActivator
python
PyCQA__pylint
tests/test_check_parallel.py
{ "start": 4889, "end": 5093 }
class ____(ParallelTestChecker): """A checker that does need to consolidate data across run invocations.""" name = "extra-parallel-checker" test_data = "extra-parallel"
ExtraParallelTestChecker
python
huggingface__transformers
src/transformers/models/granitemoe/modular_granitemoe.py
{ "start": 1567, "end": 1619 }
class ____(GraniteRMSNorm): pass
GraniteMoeRMSNorm