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
Textualize__rich
benchmarks/benchmarks.py
{ "start": 2163, "end": 2801 }
class ____: def setup(self): self.console = Console( file=StringIO(), color_system="truecolor", legacy_windows=False ) self.syntax = Syntax( code=snippets.PYTHON_SNIPPET, lexer="python", word_wrap=True ) def time_text_thin_terminal_heavy_wrapping(self): ...
SyntaxWrappingSuite
python
django__django
django/utils/log.py
{ "start": 5593, "end": 8939 }
class ____(logging.Formatter): default_time_format = "%d/%b/%Y %H:%M:%S" def __init__(self, *args, **kwargs): self.style = color_style() super().__init__(*args, **kwargs) def format(self, record): msg = record.msg status_code = getattr(record, "status_code", None) ...
ServerFormatter
python
networkx__networkx
networkx/readwrite/tests/test_gml.py
{ "start": 247, "end": 18206 }
class ____: @classmethod def setup_class(cls): cls.simple_data = """Creator "me" Version "xx" graph [ comment "This is a sample graph" directed 1 IsPlanar 1 pos [ x 0 y 1 ] node [ id 1 label "Node 1" pos [ x 1 y 1 ] ] node [ id 2 pos [ x 1 y 2 ] label "Node 2" ] node [...
TestGraph
python
psf__black
tests/data/cases/docstring.py
{ "start": 3924, "end": 7976 }
class ____: """Multiline class docstring """ def method(self): """Multiline method docstring """ pass def foo(): """This is a docstring with some lines of text here """ return def bar(): """This is another docstring with more lines of text ...
MyClass
python
huggingface__transformers
src/transformers/models/deberta/modeling_deberta.py
{ "start": 19779, "end": 20378 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.intermediate_size, config.hidden_size) self.LayerNorm = DebertaLayerNorm(config.hidden_size, config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.c...
DebertaOutput
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/methodOverride1.py
{ "start": 13352, "end": 13464 }
class ____[T](Base8[T]): # This should generate an error. def method1[U: str](self, x: U) -> U: ...
Derived8
python
spack__spack
lib/spack/spack/test/cmd/ci.py
{ "start": 14604, "end": 70981 }
class ____(NamedTuple): broken_spec_file: pathlib.Path ci_job_url: str ci_pipeline_url: str env_dir: pathlib.Path log_dir: pathlib.Path mirror_dir: pathlib.Path mirror_url: str repro_dir: pathlib.Path root_spec_dag_hash: str test_dir: pathlib.Path working_dir: pathlib.Path ...
RebuildEnv
python
kamyu104__LeetCode-Solutions
Python/minimum-distance-to-type-a-word-using-two-fingers.py
{ "start": 601, "end": 1253 }
class ____(object): def minimumDistance(self, word): """ :type word: str :rtype: int """ def distance(a, b): if -1 in [a, b]: return 0 return abs(a//6 - b//6) + abs(a%6 - b%6) dp = {(-1, -1): 0} for c in word: ...
Solution2
python
pytorch__pytorch
test/functorch/test_eager_transforms.py
{ "start": 42790, "end": 52219 }
class ____(TestCase): def test_no_vmap_staticmethod_and_no_generate_vmap_rule(self, device): class NumpyCube(torch.autograd.Function): @staticmethod def forward(input): input_np = to_numpy(input) # noqa: F821 dinput = torch.tensor(3 * input_np**2, dev...
TestAutogradFunctionVmapAPI
python
astropy__astropy
astropy/io/registry/tests/test_registries.py
{ "start": 40183, "end": 41597 }
class ____(TestUnifiedIORegistry): def setup_class(self): """Setup class. This is called 1st by pytest.""" self._cls = lambda *args: default_registry # ============================================================================= # Test compat # much of this is already tested above since EmptyData...
TestDefaultRegistry
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 15571, "end": 15793 }
class ____(FinalizeCompute, Expr): _parameters = ["frame"] def _simplify_down(self): from dask.dataframe.dask_expr._repartition import Repartition return Repartition(self.frame, 1)
FinalizeComputeDF
python
tornadoweb__tornado
tornado/test/websocket_test.py
{ "start": 26545, "end": 26752 }
class ____(MaskFunctionMixin): def mask(self, mask, data): return _websocket_mask_python(mask, data) @unittest.skipIf(speedups is None, "tornado.speedups module not present")
PythonMaskFunctionTest
python
great-expectations__great_expectations
tests/integration/conftest.py
{ "start": 9044, "end": 10614 }
class ____: base_batch: Batch comparison_data_source_name: str comparison_table_name: str @pytest.fixture def multi_source_batch( _batch_setup_for_datasource: BatchTestSetup, _cached_secondary_test_configs: dict[UUID, BatchTestSetup], ) -> Generator[MultiSourceBatch, None, None]: """Fixture th...
MultiSourceBatch
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/no_self_use.py
{ "start": 1732, "end": 2441 }
class ____: # No errors def string(self): msg = "" raise NotImplementedError(msg) def fstring(self, x): msg = f"{x}" raise NotImplementedError(msg) def docstring(self): """Lorem ipsum dolor sit amet.""" msg = "" raise NotImplementedError(msg) ...
Foo
python
numpy__numpy
numpy/_core/tests/test_numeric.py
{ "start": 77701, "end": 79166 }
class ____: def test_zero(self): assert_equal(np.binary_repr(0), '0') def test_positive(self): assert_equal(np.binary_repr(10), '1010') assert_equal(np.binary_repr(12522), '11000011101010') assert_equal(np.binary_repr(10736848), '1010001...
TestBinaryRepr
python
sympy__sympy
sympy/assumptions/predicates/sets.py
{ "start": 699, "end": 1000 }
class ____(Predicate): """ Non-integer extended real predicate. """ name = 'noninteger' handler = Dispatcher( "NonIntegerHandler", doc=("Handler for Q.noninteger.\n\n" "Test that an expression is a non-integer extended real number.") )
NonIntegerPredicate
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 68440, "end": 68724 }
class ____(BaseModel, extra="forbid"): """ Should have at least one value not matching the any given values """ except_: "AnyVariants" = Field( ..., description="Should have at least one value not matching the any given values", alias="except" )
MatchExcept
python
getsentry__sentry
src/sentry/integrations/msteams/card_builder/utils.py
{ "start": 970, "end": 1852 }
class ____: LINK_IDENTITY_BUTTON = "Link Identities" LINK_IDENTITY = "You need to link your Microsoft Teams account to your Sentry account before you can take action through Teams messages. Please click here to do so." LINK_COMMAND_MESSAGE = "Your Microsoft Teams identity will be linked to your Sentry acco...
IdentityMessages
python
huggingface__transformers
tests/models/siglip2/test_modeling_siglip2.py
{ "start": 25078, "end": 27552 }
class ____(Siglip2ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (Siglip2ForImageClassification,) if is_torch_available() else () pipeline_model_mapping = {"image-classification": Siglip2ForImageClassification} if is_torch_available() else {} additional_model_inputs = ["pixel...
Siglip2ForImageClassificationModelTest
python
dask__distributed
distributed/tests/test_worker_memory.py
{ "start": 4058, "end": 5234 }
class ____: def __init__(self, *, reported_size=0): self.reported_size = int(reported_size) def __getstate__(self): raise CustomError() def __sizeof__(self): return self.reported_size async def assert_basic_futures(c: Client) -> None: futures = c.map(inc, range(10)) resul...
FailToPickle
python
dagster-io__dagster
python_modules/dagster/dagster/_core/log_manager.py
{ "start": 3328, "end": 6380 }
class ____(TypedDict): """Internal class representing the full metadata on a log record after it has been modified by the `DagsterLogHandler`. It contains all the fields on `DagsterLogHandlerMetadata`, an optional `DagsterEvent`, and some fields concerning the individual log message. """ run_id: Op...
DagsterLogRecordMetadata
python
huggingface__transformers
tests/models/sam_hq/test_modeling_sam_hq.py
{ "start": 12476, "end": 19620 }
class ____: def __init__( self, parent, hidden_size=36, intermediate_size=72, projection_dim=62, output_channels=32, num_hidden_layers=12, num_attention_heads=4, num_channels=3, image_size=24, patch_size=2, hidden_act="g...
SamHQModelTester
python
marshmallow-code__marshmallow
src/marshmallow/validate.py
{ "start": 1049, "end": 2331 }
class ____(Validator): """Compose multiple validators and combine their error messages. Example: :: from marshmallow import validate, ValidationError def is_even(value): if value % 2 != 0: raise ValidationError("Not an even value.") validator = validate....
And
python
ray-project__ray
doc/source/serve/doc_code/monitoring/logging_config.py
{ "start": 192, "end": 496 }
class ____: def __call__(self) -> int: return "hello world" serve.run(Model.bind()) resp = requests.get("http://localhost:8000/") # __deployment_json_end__ # __serve_run_json_start__ import requests from ray import serve from ray.serve.schema import LoggingConfig @serve.deployment
Model
python
oauthlib__oauthlib
oauthlib/oauth2/rfc6749/grant_types/resource_owner_password_credentials.py
{ "start": 200, "end": 8484 }
class ____(GrantTypeBase): """`Resource Owner Password Credentials Grant`_ The resource owner password credentials grant type is suitable in cases where the resource owner has a trust relationship with the client, such as the device operating system or a highly privileged application. The authori...
ResourceOwnerPasswordCredentialsGrant
python
apache__airflow
providers/elasticsearch/src/airflow/providers/elasticsearch/hooks/elasticsearch.py
{ "start": 7140, "end": 8572 }
class ____(BaseHook): """ Interacts with Elasticsearch. This hook uses the official Elasticsearch Python Client. :param hosts: list: A list of a single or many Elasticsearch instances. Example: ["http://localhost:9200"] :param es_conn_args: dict: Additional arguments you might need to enter to connect ...
ElasticsearchPythonHook
python
pandas-dev__pandas
pandas/tests/indexes/period/test_scalar_compat.py
{ "start": 188, "end": 1383 }
class ____: def test_start_time(self): # GH#17157 index = period_range(freq="M", start="2016-01-01", end="2016-05-31") expected_index = date_range( "2016-01-01", end="2016-05-31", freq="MS", unit="ns" ) tm.assert_index_equal(index.start_time, expected_index) ...
TestPeriodIndexOps
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 152892, "end": 159446 }
class ____(str, Enum): """ Defines write ordering guarantees for collection operations * `weak` - write operations may be reordered, works faster, default * `medium` - write operations go through dynamically selected leader, may be inconsistent for a short period of time in case of leader change * `strong` -...
WriteOrdering
python
bokeh__bokeh
src/bokeh/core/property/auto.py
{ "start": 1218, "end": 2486 }
class ____(Enum): """ Accepts only the string "auto". Useful for properties that can be configured to behave "automatically". Example: This property is often most useful in conjunction with the :class:`~bokeh.core.properties.Either` property. .. code-block:: python >...
Auto
python
astropy__astropy
astropy/convolution/tests/test_convolve_fft.py
{ "start": 20220, "end": 37256 }
class ____: @pytest.mark.parametrize("boundary", BOUNDARY_OPTIONS) @pytest.mark.parametrize("nan_treatment", NANTREATMENT_OPTIONS) @pytest.mark.parametrize("normalize_kernel", NORMALIZE_OPTIONS) @pytest.mark.parametrize("dealias", [True, False]) def test_unity_1x1_none(self, boundary, nan_treatment,...
TestConvolve2D
python
mlflow__mlflow
mlflow/tracking/context/abstract_context.py
{ "start": 115, "end": 1060 }
class ____: """ Abstract base class for context provider objects specifying custom tags at run-creation time (e.g. tags specifying the git repo with which the run is associated). When a run is created via the fluent ``mlflow.start_run`` method, MLflow iterates through all registered RunContextProvi...
RunContextProvider
python
pytorch__pytorch
torch/_library/fake_impl.py
{ "start": 216, "end": 4765 }
class ____: """A holder where one can register an fake impl to.""" def __init__(self, qualname: str): self.qualname: str = qualname # kernels stores all registered fake kernels, ordered by registration # time ascendingly (newer registration after older registration). If an # ope...
FakeImplHolder
python
google__jax
jax/_src/pallas/mosaic/lowering.py
{ "start": 6784, "end": 8256 }
class ____: grid_sizes: tuple[int, ...] # Includes both user and vmap axes. grid_names: tuple[Hashable, ...] | None vmapped_dims: tuple[int, ...] # Indices of vmapped grid dimensions. user_grid_indices: Sequence[ir.Value] | None block_shapes: list[tuple[int | pallas_core.Squeezed, ...]] name_stack: source...
LoweringContext
python
coleifer__peewee
tests/db_tests.py
{ "start": 14467, "end": 15086 }
class ____(ModelTestCase): requires = [CatToy] def setUp(self): with self.database: self.execute('CREATE SCHEMA huey;') super(TestSchemaNamespace, self).setUp() def tearDown(self): super(TestSchemaNamespace, self).tearDown() with self.database: self....
TestSchemaNamespace
python
openai__openai-python
src/openai/resources/realtime/realtime.py
{ "start": 18348, "end": 22296 }
class ____: """ Context manager over a `RealtimeConnection` that is returned by `realtime.connect()` This context manager ensures that the connection will be closed when it exits. --- Note that if your application doesn't work well with the context manager approach then you can call the `.ent...
RealtimeConnectionManager
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/concepts/io_management/test_io_manager.py
{ "start": 23, "end": 965 }
class ____(dg.IOManager): def __init__(self): self.storage_dict = {} def handle_output(self, context: dg.OutputContext, obj): self.storage_dict[(context.step_key, context.name)] = obj def load_input(self, context: dg.InputContext): if context.upstream_output: return sel...
MyIOManager
python
facebook__pyre-check
tools/incremental_test/runner.py
{ "start": 759, "end": 1336 }
class ____: line: int column: int path: str description: str @staticmethod def from_json(input_json: Dict[str, Any]) -> "PyreError": try: return PyreError( line=int(input_json["line"]), column=int(input_json["column"]), path=in...
PyreError
python
Pylons__pyramid
tests/test_config/test_views.py
{ "start": 108447, "end": 109257 }
class ____(unittest.TestCase): def _callFUT(self, ob): from pyramid.config.views import isexception return isexception(ob) def test_is_exception_instance(self): class E(Exception): pass e = E() self.assertEqual(self._callFUT(e), True) def test_is_excep...
Test_isexception
python
sphinx-doc__sphinx
tests/test_util/test_util_fileutil.py
{ "start": 500, "end": 6236 }
class ____(BuiltinTemplateLoader, BaseRenderer): def __init__(self) -> None: super().__init__() builder = mock.Mock() builder.config.templates_path = [] builder._translator = None self.init(builder) def test_copy_asset_file(tmp_path: Path) -> None: renderer = DummyTempl...
DummyTemplateLoader
python
readthedocs__readthedocs.org
readthedocs/search/api/v3/tests/test_api.py
{ "start": 577, "end": 2655 }
class ____(TestCase): def setUp(self): call_command("search_index", "--delete", "-f") call_command("search_index", "--create") def tearDown(self): super().tearDown() call_command("search_index", "--delete", "-f") def get_dummy_processed_json(self, extra=None): """ ...
SearchTestBase
python
Pylons__pyramid
tests/test_router.py
{ "start": 61982, "end": 62341 }
class ____: def __init__(self): self.messages = [] def info(self, msg): self.messages.append(msg) warn = info debug = info def exc_raised(exc, func, *arg, **kw): try: func(*arg, **kw) except exc as e: return e else: raise AssertionError('%s not rai...
DummyLogger
python
google__flatbuffers
python/flatbuffers/number_types.py
{ "start": 2148, "end": 2299 }
class ____(object): bytewidth = 8 min_val = -(2**63) max_val = (2**63) - 1 py_type = int name = "int64" packer_type = packer.int64
Int64Flags
python
pytorch__pytorch
torchgen/static_runtime/generator.py
{ "start": 22591, "end": 27116 }
class ____: def out_variant(self, groups: Sequence[NativeFunctionsGroup]) -> str: if not groups: return "" generated_type_variants = [] for g in groups: with native_function_manager(g): assert is_supported(g) assert isinstance(g, Native...
GenOpTestCase
python
django__django
tests/migrations/models.py
{ "start": 893, "end": 1077 }
class ____(models.Model): """ A model that is in a migration-less app (which this app is if its migrations directory has not been repointed) """ pass
UnmigratedModel
python
pandas-dev__pandas
pandas/tests/indexes/categorical/test_indexing.py
{ "start": 4991, "end": 7337 }
class ____: def test_get_loc(self): # GH 12531 cidx1 = CategoricalIndex(list("abcde"), categories=list("edabc")) idx1 = Index(list("abcde")) assert cidx1.get_loc("a") == idx1.get_loc("a") assert cidx1.get_loc("e") == idx1.get_loc("e") for i in [cidx1, idx1]: ...
TestGetLoc
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 667401, "end": 668458 }
class ____(sgqlc.types.Type): """Represents an actor in a Git commit (ie. an author or committer).""" __schema__ = github_schema __field_names__ = ("avatar_url", "date", "email", "name", "user") avatar_url = sgqlc.types.Field( sgqlc.types.non_null(URI), graphql_name="avatarUrl", ...
GitActor
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 414406, "end": 414685 }
class ____: def get_py_mod_name(self, code): return code.get_py_string_const( self.module_name, identifier=True) def get_py_qualified_name(self, code): return code.get_py_string_const( self.qualname, identifier=True)
ModuleNameMixin
python
kamyu104__LeetCode-Solutions
Python/traffic-light-controlled-intersection.py
{ "start": 48, "end": 821 }
class ____(object): def __init__(self): self.__l = threading.Lock() self.__light = 1 def carArrived(self, carId, roadId, direction, turnGreen, crossCar): """ :type roadId: int --> // ID of the car :type carId: int --> // ID of the road the car travels on. Can be 1 (...
TrafficLight
python
dagster-io__dagster
python_modules/dagster-pipes/dagster_pipes/__init__.py
{ "start": 53076, "end": 55606 }
class ____(PipesParamsLoader): """Params loader that extracts params from widgets (base params) in a Databricks Notebook.""" def __init__(self, widgets: Any): self.widgets = widgets def is_dagster_pipes_process(self) -> bool: # use the presence of the pipes context to discern if we are in ...
PipesDatabricksNotebookWidgetsParamsLoader
python
getsentry__sentry
tests/sentry/autofix/test_utils.py
{ "start": 669, "end": 1662 }
class ____(TestCase): def test_code_mappings_empty(self) -> None: project = self.create_project() repos = get_autofix_repos_from_project_code_mappings(project) assert repos == [] def test_get_repos_from_project_code_mappings_with_data(self) -> None: project = self.create_project...
TestGetRepoFromCodeMappings
python
aio-libs__aiohttp
aiohttp/tracing.py
{ "start": 8361, "end": 8500 }
class ____: """Parameters sent by the `on_connection_queued_start` signal""" @frozen_dataclass_decorator
TraceConnectionQueuedStartParams
python
openai__openai-python
src/openai/types/fine_tuning/jobs/fine_tuning_job_checkpoint.py
{ "start": 596, "end": 1347 }
class ____(BaseModel): id: str """The checkpoint identifier, which can be referenced in the API endpoints.""" created_at: int """The Unix timestamp (in seconds) for when the checkpoint was created.""" fine_tuned_model_checkpoint: str """The name of the fine-tuned checkpoint model that is creat...
FineTuningJobCheckpoint
python
getsentry__sentry
src/sentry/issue_detection/detectors/experiments/mn_plus_one_db_span_detector.py
{ "start": 1722, "end": 5525 }
class ____(MNPlusOneState): """ The initial state for the MN+1 DB Query detector, and the state we return to whenever there is no active repeating pattern being checked. Keeps a list of recently seen spans until a repeat is found, at which point it transitions to the ContinuingMNPlusOne state. ...
SearchingForMNPlusOne
python
huggingface__transformers
tests/models/autoformer/test_modeling_autoformer.py
{ "start": 17074, "end": 20248 }
class ____(unittest.TestCase): def test_inference_no_head(self): model = AutoformerModel.from_pretrained("huggingface/autoformer-tourism-monthly").to(torch_device) batch = prepare_batch() with torch.no_grad(): output = model( past_values=batch["past_values"], ...
AutoformerModelIntegrationTests
python
apache__airflow
providers/openlineage/tests/unit/openlineage/extractors/test_base.py
{ "start": 3828, "end": 4419 }
class ____(BaseOperator): def execute(self, context) -> Any: pass def get_openlineage_facets_on_start(self) -> OperatorLineage: return OperatorLineage( inputs=INPUTS, outputs=OUTPUTS, run_facets=RUN_FACETS, job_facets=JOB_FACETS, ) de...
OperatorWithoutFailure
python
django__django
django/contrib/auth/models.py
{ "start": 1164, "end": 3061 }
class ____(models.Model): """ The permissions system provides a way to assign permissions to specific users and groups of users. The permission system is used by the Django admin site, but may also be useful in your own code. The Django admin site uses permissions as follows: - The "add" p...
Permission
python
ray-project__ray
python/ray/serve/_private/storage/kv_store_base.py
{ "start": 133, "end": 1532 }
class ____(metaclass=abc.ABCMeta): """Abstract class for KVStore defining APIs needed for ray serve use cases, currently (8/6/2021) controller state checkpointing. """ @abstractmethod def get_storage_key(self, key: str) -> str: """Get internal key for storage. Args: key...
KVStoreBase
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF053.py
{ "start": 998, "end": 1095 }
class ____[*Ts](Callable[[*_Cs], tuple[*Ts]], Generic[_Cs]): ... # TODO: Type parameter defaults
C
python
huggingface__transformers
src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py
{ "start": 48767, "end": 49749 }
class ____(nn.Module): def __init__( self, patch_size: int = 14, temporal_patch_size: int = 2, in_channels: int = 3, embed_dim: int = 1152, ) -> None: super().__init__() self.patch_size = patch_size self.temporal_patch_size = temporal_patch_size ...
Qwen2_5_VisionPatchEmbed
python
astropy__astropy
astropy/wcs/wcsapi/low_level_api.py
{ "start": 101, "end": 15926 }
class ____(metaclass=abc.ABCMeta): """ Abstract base class for the low-level WCS interface. This is described in `APE 14: A shared Python interface for World Coordinate Systems <https://doi.org/10.5281/zenodo.1188875>`_. """ @property @abc.abstractmethod def pixel_n_dim(self): ...
BaseLowLevelWCS
python
davidhalter__jedi
test/completion/classes.py
{ "start": 4574, "end": 4920 }
class ____: def __init__(self, a): self.a = a def ret(self): return self.a d = b b = ret if 1: c = b #? int() V(1).b() #? int() V(1).c() #? V(1).d() # Only keywords should be possible to complete. #? ['is', 'in', 'not', 'and', 'or', 'if'] V(1).d() # ----------------- # ...
V
python
Lightning-AI__lightning
tests/tests_pytorch/trainer/optimization/test_manual_optimization.py
{ "start": 25093, "end": 33905 }
class ____(TesManualOptimizationDDPModel): def training_step(self, batch, batch_idx): # emulate gans training opt_gen, opt_dis = self.optimizers() # Note: Be careful, don't log on the same key in self.log in both closure # as they will be aggregated together on epoch_end wo...
TestManualOptimizationDDPModelToggleModel
python
mlflow__mlflow
mlflow/types/agent.py
{ "start": 3645, "end": 5337 }
class ____(BaseModel): """ Represents the response of a ChatAgent. Args: messages: A list of :py:class:`ChatAgentMessage` that are returned from the model. finish_reason (str): The reason why generation stopped. **Optional** defaults to ``None`` custom_outputs (Dict[str, Any]): An o...
ChatAgentResponse
python
kamyu104__LeetCode-Solutions
Python/count-sorted-vowel-strings.py
{ "start": 29, "end": 459 }
class ____(object): def countVowelStrings(self, n): """ :type n: int :rtype: int """ def nCr(n, r): # Time: O(n), Space: O(1) if n-r < r: return nCr(n, n-r) c = 1 for k in xrange(1, r+1): c *= n-k+1 ...
Solution
python
getsentry__sentry-python
sentry_sdk/integrations/django/__init__.py
{ "start": 18159, "end": 26729 }
class ____(RequestExtractor): def __init__(self, request): # type: (Union[WSGIRequest, ASGIRequest]) -> None try: drf_request = request._sentry_drf_request_backref() if drf_request is not None: request = drf_request except AttributeError: p...
DjangoRequestExtractor
python
python-pillow__Pillow
src/PIL/GbrImagePlugin.py
{ "start": 1003, "end": 2979 }
class ____(ImageFile.ImageFile): format = "GBR" format_description = "GIMP brush file" def _open(self) -> None: header_size = i32(self.fp.read(4)) if header_size < 20: msg = "not a GIMP brush" raise SyntaxError(msg) version = i32(self.fp.read(4)) if v...
GbrImageFile
python
python-pillow__Pillow
Tests/test_image_resample.py
{ "start": 15841, "end": 16998 }
class ____: def test_reduce(self) -> None: test_color = 254 for size in range(400000, 400010, 2): i = Image.new("L", (size, 1), 0) draw = ImageDraw.Draw(i) draw.rectangle((0, 0, i.size[0] // 2 - 1, 0), test_color) px = i.resize((5, i.size[1]), Image....
TestCoreResampleCoefficients
python
mlflow__mlflow
mlflow/types/responses_helpers.py
{ "start": 12255, "end": 12392 }
class ____(BaseModel): code: str | None = None message: str param: str | None = None type: str = "error"
ResponseErrorEvent
python
huggingface__transformers
src/transformers/models/idefics2/image_processing_idefics2_fast.py
{ "start": 3271, "end": 11693 }
class ____(BaseImageProcessorFast): resample = PILImageResampling.BILINEAR image_mean = IMAGENET_STANDARD_MEAN image_std = IMAGENET_STANDARD_STD do_resize = True do_rescale = True do_normalize = True do_pad = True do_convert_rgb = True do_image_splitting = False size = {"shortest...
Idefics2ImageProcessorFast
python
getsentry__sentry
src/sentry/workflow_engine/handlers/condition/assigned_to_handler.py
{ "start": 529, "end": 2443 }
class ____(DataConditionHandler[WorkflowEventData]): group = DataConditionHandler.Group.ACTION_FILTER subgroup = DataConditionHandler.Subgroup.ISSUE_ATTRIBUTES comparison_json_schema = { "type": "object", "properties": { "target_type": {"type": "string", "enum": [*AssigneeTarget...
AssignedToConditionHandler
python
pytorch__pytorch
test/test_cuda_trace.py
{ "start": 572, "end": 4232 }
class ____(TestCase): def setUp(self): super().setUp() torch._C._activate_gpu_trace() self.mock = unittest.mock.MagicMock() def test_event_creation_callback(self): gpu_trace.register_callback_for_event_creation(self.mock) event = torch.cuda.Event() event.record(...
TestCudaTrace
python
python__mypy
mypy/plugin.py
{ "start": 9479, "end": 10654 }
class ____: """Interface for accessing type checker functionality in plugins. Methods docstrings contain only basic info. Look for corresponding implementation docstrings in checker.py for more details. """ msg: MessageBuilder options: Options path: str # Type context for type inferen...
CheckerPluginInterface
python
django__django
django/contrib/postgres/operations.py
{ "start": 2681, "end": 2805 }
class ____(CreateExtension): def __init__(self, hints=None): super().__init__("bloom", hints=hints)
BloomExtension
python
django__django
tests/generic_relations_regress/models.py
{ "start": 2346, "end": 2411 }
class ____(models.Model): notes = GenericRelation(Note)
Contact
python
pytorch__pytorch
test/functorch/test_logging.py
{ "start": 304, "end": 668 }
class ____(LoggingTestCase): @make_logging_test(aot=logging.DEBUG) def test_logging(self, records): def f(x): return torch.sin(x) compiled_f = aot_function(f, fw_compiler=nop, bw_compiler=nop) compiled_f(torch.randn(3)) self.assertGreater(len(records), 0) if __name...
TestAOTLogging
python
apache__airflow
airflow-core/tests/unit/utils/test_otel_utils.py
{ "start": 1016, "end": 32345 }
class ____: # The method that extracts the spans from the output, # counts that there is no indentation on the cli, when a span starts and finishes. example_output = """ { "name": "test_dag", "context": { "trace_id": "0x01f441c9c53e793e8808c77939ddbf36", "span_id": "0x779a3a331684439...
TestUtilsUnit
python
redis__redis-py
redis/commands/search/query.py
{ "start": 11939, "end": 12234 }
class ____(Filter): METERS = "m" KILOMETERS = "km" FEET = "ft" MILES = "mi" def __init__( self, field: str, lon: float, lat: float, radius: float, unit: str = KILOMETERS ) -> None: Filter.__init__(self, "GEOFILTER", field, lon, lat, radius, unit)
GeoFilter
python
readthedocs__readthedocs.org
readthedocs/builds/tests/test_build_queryset.py
{ "start": 367, "end": 5699 }
class ____: @pytest.fixture(autouse=True) def setup_method(self, settings): settings.RTD_DEFAULT_FEATURES = dict( [RTDProductFeature(type=TYPE_CONCURRENT_BUILDS, value=4).to_item()] ) def test_concurrent_builds(self): project = fixture.get( Project, ...
TestBuildQuerySet
python
vyperlang__vyper
vyper/builtins/functions.py
{ "start": 87787, "end": 88584 }
class ____(TypenameFoldedFunctionT): def _try_fold(self, node): self._validate_arg_types(node) input_type = type_from_annotation(node.args[0]) if not isinstance(input_type, (IntegerT, DecimalT)): raise InvalidType(f"Expected numeric type but got {input_type} instead", node) ...
_MinMaxValue
python
django__django
tests/migrations/test_writer.py
{ "start": 1085, "end": 1215 }
class ____: def deconstruct(self): return ("DeconstructibleInstances", [], {}) @deconstructible
DeconstructibleInstances
python
doocs__leetcode
solution/1100-1199/1166.Design File System/Solution.py
{ "start": 0, "end": 658 }
class ____: def __init__(self, v: int = -1): self.children = {} self.v = v def insert(self, w: str, v: int) -> bool: node = self ps = w.split("/") for p in ps[1:-1]: if p not in node.children: return False node = node.children[p] ...
Trie
python
urllib3__urllib3
src/urllib3/connection.py
{ "start": 35410, "end": 42227 }
class ____(typing.NamedTuple): """ Wrapped socket and whether the connection is verified after the TLS handshake """ socket: ssl.SSLSocket | SSLTransport is_verified: bool def _ssl_wrap_socket_and_match_hostname( sock: socket.socket, *, cert_reqs: None | str | int, ssl_version...
_WrappedAndVerifiedSocket
python
PrefectHQ__prefect
src/prefect/server/concurrency/lease_storage/__init__.py
{ "start": 541, "end": 793 }
class ____(BaseModel): """Model for validating concurrency limit lease metadata.""" model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid") slots: int holder: Optional[ConcurrencyLeaseHolder] = None
ConcurrencyLimitLeaseMetadata
python
huggingface__transformers
src/transformers/models/detr/modeling_detr.py
{ "start": 24810, "end": 27886 }
class ____(nn.Module): def __init__(self, config: DetrConfig): super().__init__() self.embed_dim = config.d_model self.self_attn = DetrAttention( embed_dim=self.embed_dim, num_heads=config.encoder_attention_heads, dropout=config.attention_dropout, ...
DetrEncoderLayer
python
sqlalchemy__sqlalchemy
test/sql/test_operators.py
{ "start": 96522, "end": 97970 }
class ____(fixtures.TestBase): def _raises(self, expr): assert_raises_message( TypeError, "Boolean value of this clause is not defined", bool, expr, ) def _assert_true(self, expr): is_(bool(expr), True) def _assert_false(self, expr): ...
NonZeroTest
python
modin-project__modin
modin/core/execution/dispatching/factories/factories.py
{ "start": 23617, "end": 23958 }
class ____(BaseIO): """ I/O class for native pandas execution. This class inherits the default function implementations from the ``BaseIO`` parent class. """ _should_warn_on_default_to_pandas: bool = False query_compiler_cls = NativeQueryCompiler @doc(_doc_factory_class, execution_name="...
NativeIO
python
python-visualization__folium
folium/plugins/encoded.py
{ "start": 202, "end": 1558 }
class ____(JSCSSMixin, MacroElement, ABC): """Base Interface to create folium objects from encoded strings. Derived classes must define `_encoding_type` property which returns the string representation of the folium object to create from the encoded string. Parameters ---------- encoded: str ...
_BaseFromEncoded
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/auto_materialize_rule_impls.py
{ "start": 19076, "end": 24125 }
class ____(AutoMaterializeRule, NamedTuple("_MaterializeOnMissingRule", [])): @property def decision_type(self) -> AutoMaterializeDecisionType: return AutoMaterializeDecisionType.MATERIALIZE @property def description(self) -> str: return "materialization is missing" def get_handled...
MaterializeOnMissingRule
python
tensorflow__tensorflow
tensorflow/python/ops/ragged/ragged_tensor_bounding_shape_op_test.py
{ "start": 1074, "end": 5724 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): @parameterized.named_parameters([ # rank = 2 dict(testcase_name='docstring_example', rt=[[1, 2, 3, 4], [5], [], [6, 7, 8, 9], [10]], expected=[5, 4]), dict(testcase_name='shape_...
RaggedTensorBoundingShapeOp
python
scipy__scipy
scipy/stats/_discrete_distns.py
{ "start": 47437, "end": 51764 }
class ____(rv_discrete): r"""A Poisson Binomial discrete random variable. %(before_notes)s See Also -------- binom Notes ----- The probability mass function for `poisson_binom` is: .. math:: f(k; p_1, p_2, ..., p_n) = \sum_{A \in F_k} \prod_{i \in A} p_i \prod_{j \in A^C} 1...
poisson_binom_gen
python
pandas-dev__pandas
asv_bench/benchmarks/multiindex_object.py
{ "start": 2408, "end": 3917 }
class ____: def setup(self): self.mi_int = MultiIndex.from_product( [np.arange(1000), np.arange(1000)], names=["one", "two"] ) self.obj_index = np.array( [ (0, 10), (0, 11), (0, 12), (0, 13), ...
Integer
python
great-expectations__great_expectations
great_expectations/experimental/metric_repository/metrics.py
{ "start": 4862, "end": 5356 }
class ____(Metric, Generic[_ValueType]): @override @property def value_type(self) -> str: type_ = self.__orig_class__.__args__[0] # type: ignore[attr-defined] # __orig_class__ is used to get the generic type string_rep = str(type_) if string_rep.startswith("<class"): ret...
TableMetric
python
numpy__numpy
numpy/random/tests/test_direct.py
{ "start": 12280, "end": 13096 }
class ____(Base): @classmethod def setup_class(cls): cls.bit_generator = Philox cls.bits = 64 cls.dtype = np.uint64 cls.data1 = cls._read_csv( join(pwd, './data/philox-testset-1.csv')) cls.data2 = cls._read_csv( join(pwd, './data/philox-testset-2.c...
TestPhilox
python
astropy__astropy
astropy/io/ascii/core.py
{ "start": 25539, "end": 35823 }
class ____: """ Base table data reader. """ start_line = None """ None, int, or a function of ``lines`` that returns None or int """ end_line = None """ None, int, or a function of ``lines`` that returns None or int """ comment = None """ Regular expression for comment lines """ ...
BaseData
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/decorator5.py
{ "start": 430, "end": 687 }
class ____: @decorator1 def method1(self, var: str, kvar: str): return reveal_type(ClassA().method1, expected_text="(var: str, kvar: str) -> None") reveal_type(ClassA.method1, expected_text="(self: ClassA, var: str, kvar: str) -> None")
ClassA
python
pytorch__pytorch
torch/ao/pruning/sparsifier/weight_norm_sparsifier.py
{ "start": 349, "end": 9405 }
class ____(BaseSparsifier): r"""Weight-Norm Sparsifier This sparsifier computes the norm of every sparse block and "zeroes-out" the ones with the lowest norm. The level of sparsity defines how many of the blocks is removed. This sparsifier is controlled by three variables: 1. `sparsity_level` ...
WeightNormSparsifier
python
joke2k__faker
faker/providers/phone_number/ka_GE/__init__.py
{ "start": 49, "end": 437 }
class ____(PhoneNumberProvider): # Sourse: https://en.wikipedia.org/wiki/Telephone_numbers_in_Georgia_(country) formats = ( "+995 ### ### ###", "+995 (###) ### ###", "+995#########", "0 ### ### ###", "+995 32 ### ## ##", "+995 34# ### ###", "+995 (34#) ###...
Provider
python
django__django
tests/delete/models.py
{ "start": 6149, "end": 6368 }
class ____(models.Model): referrer = models.ForeignKey(Referrer, models.CASCADE) other_referrer = models.ForeignKey( Referrer, models.CASCADE, to_field="unique_field", related_name="+" )
SecondReferrer
python
kamyu104__LeetCode-Solutions
Python/find-minimum-diameter-after-merging-two-trees.py
{ "start": 2597, "end": 4136 }
class ____(object): def minimumDiameterAfterMerge(self, edges1, edges2): """ :type edges1: List[List[int]] :type edges2: List[List[int]] :rtype: int """ def ceil_divide(a, b): return (a+b-1)//2 def tree_diameter(edges): def bfs(): ...
Solution3
python
dask__dask
dask/context.py
{ "start": 1333, "end": 1757 }
class ____: def __init__(self, default, key, falsey=None): self._default = default self._key = key self._falsey = falsey def __get__(self, instance, owner=None): if self._key in _globals: if _globals[self._key]: return _globals[self._key] ...
GlobalMethod