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
falconry__falcon
tests/test_sinks.py
{ "start": 339, "end": 650 }
class ____(Sink): async def __call__(self, req, resp, **kwargs): super().__call__(req, resp, **kwargs) def kitchen_sink(req, resp, **kwargs): resp.set_header('X-Missing-Feature', 'kitchen-sink') async def async_kitchen_sink(req, resp, **kwargs): kitchen_sink(req, resp, **kwargs)
SinkAsync
python
walkccc__LeetCode
solutions/3129. Find All Possible Stable Binary Arrays I/3129.py
{ "start": 0, "end": 988 }
class ____: # Same as 3129. Find All Possible Stable Binary Arrays I def numberOfStableArrays(self, zero: int, one: int, limit: int) -> int: MOD = 1_000_000_007 # dp[i][j][k] := the number of stable arrays, where the number of # occurrences of 0 is i and the number of occurrences of 1 is j and the last ...
Solution
python
kamyu104__LeetCode-Solutions
Python/smallest-palindromic-rearrangement-i.py
{ "start": 71, "end": 534 }
class ____(object): def smallestPalindrome(self, s): """ :type s: str :rtype: str """ cnt = [0]*26 for i in xrange(len(s)//2): cnt[ord(s[i])-ord('a')] += 1 result = [chr(ord('a')+i)*c for i, c in enumerate(cnt)] if len(s)%2: res...
Solution
python
kamyu104__LeetCode-Solutions
Python/lucky-numbers-in-a-matrix.py
{ "start": 56, "end": 474 }
class ____(object): def luckyNumbers (self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ rows = map(min, matrix) cols = map(max, itertools.izip(*matrix)) return [cell for i, row in enumerate(matrix) for j, cell in enume...
Solution
python
fluentpython__example-code
19-dyn-attr-prop/oscon/schedule2.py
{ "start": 814, "end": 1125 }
class ____: def __init__(self, **kwargs): self.__dict__.update(kwargs) def __eq__(self, other): # <3> if isinstance(other, Record): return self.__dict__ == other.__dict__ else: return NotImplemented # END SCHEDULE2_RECORD # BEGIN SCHEDULE2_DBRECORD
Record
python
jazzband__django-pipeline
tests/tests/test_collector.py
{ "start": 347, "end": 2281 }
class ____(TestCase): def tearDown(self): super().tearDown() default_collector.clear() def test_collect(self): self.assertEqual( set(default_collector.collect()), set(self._get_collectable_files()) ) def test_collect_with_files(self): self.assertEqual( ...
CollectorTest
python
sqlalchemy__sqlalchemy
test/engine/test_processors.py
{ "start": 4263, "end": 8763 }
class ____(fixtures.TestBase): def test_distill_20_none(self): eq_(self.module._distill_params_20(None), ()) def test_distill_20_empty_sequence(self): with expect_deprecated( r"Empty parameter sequence passed to execute\(\). " "This use is deprecated and will raise an ex...
_DistillArgsTest
python
huggingface__transformers
src/transformers/models/convnextv2/modeling_convnextv2.py
{ "start": 2524, "end": 3359 }
class ____(nn.Module): """GRN (Global Response Normalization) layer""" def __init__(self, dim: int): super().__init__() self.weight = nn.Parameter(torch.zeros(1, 1, 1, dim)) self.bias = nn.Parameter(torch.zeros(1, 1, 1, dim)) def forward(self, hidden_states: torch.FloatTensor) -> t...
ConvNextV2GRN
python
kubernetes-client__python
kubernetes/client/models/v1_network_policy_spec.py
{ "start": 383, "end": 9596 }
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...
V1NetworkPolicySpec
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/sensors/bedrock.py
{ "start": 12256, "end": 15905 }
class ____(BedrockBaseSensor[BedrockAgentHook]): """ Poll the ingestion job status until it reaches a terminal state; fails if creation fails. .. seealso:: For more information on how to use this sensor, take a look at the guide: :ref:`howto/sensor:BedrockIngestionJobSensor` :param kno...
BedrockIngestionJobSensor
python
django-import-export__django-import-export
tests/core/admin.py
{ "start": 2497, "end": 2579 }
class ____(ModelResource): class Meta: model = UUIDBook
UUIDBookResource
python
kamyu104__LeetCode-Solutions
Python/number-of-ways-to-split-array.py
{ "start": 42, "end": 364 }
class ____(object): def waysToSplitArray(self, nums): """ :type nums: List[int] :rtype: int """ total = sum(nums) result = curr = 0 for i in xrange(len(nums)-1): curr += nums[i] result += int(curr >= total-curr) return result
Solution
python
allegroai__clearml
clearml/automation/job.py
{ "start": 19432, "end": 27530 }
class ____(BaseJob): def __init__( self, base_task_id: str, parameter_override: Optional[Mapping[str, str]] = None, task_overrides: Optional[Mapping[str, str]] = None, configuration_overrides: Optional[Mapping[str, Union[str, Mapping]]] = None, tags: Optional[Sequence...
ClearmlJob
python
allegroai__clearml
clearml/utilities/process/mp.py
{ "start": 5714, "end": 6498 }
class ____(_ForkSafeThreadSyncObject): def __init__(self) -> None: super(ForkQueue, self).__init__(TrQueue) def get(self, *args: Any, **kwargs: Any) -> Any: self._create() return self._sync.get(*args, **kwargs) def put(self, *args: Any, **kwargs: Any) -> None: self._create(...
ForkQueue
python
apache__airflow
airflow-core/tests/unit/always/test_project_structure.py
{ "start": 22451, "end": 37720 }
class ____(ExampleCoverageTest, AssetsCoverageTest): PROVIDER = "google" CLASS_DIRS = ProjectStructureTest.CLASS_DIRS | {"operators/vertex_ai"} DEPRECATED_CLASSES = { "airflow.providers.google.cloud.operators.cloud_storage_transfer_service" ".CloudDataTransferServiceS3ToGCSOperator", ...
TestGoogleProviderProjectStructure
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP046_0.py
{ "start": 2449, "end": 2613 }
class ____[U]: def more_generic(u: U, t: T) -> tuple[U, T]: return (u, t) # default requires 3.13 V = TypeVar("V", default=Any, bound=str)
MixedGenerics
python
ray-project__ray
python/ray/experimental/channel/torch_tensor_accelerator_channel.py
{ "start": 1552, "end": 15266 }
class ____(ChannelInterface): def __init__( self, writer: ray.actor.ActorHandle, reader_and_node_list: List[Tuple["ray.actor.ActorHandle", str]], typ: "TorchTensorType", driver_actor_id: str, tensor_metadata_channel: Optional["Channel"] = None, _cpu_data_chann...
TorchTensorAcceleratorChannel
python
huggingface__transformers
src/transformers/models/instructblip/modeling_instructblip.py
{ "start": 12480, "end": 13665 }
class ____(PreTrainedModel): config: InstructBlipConfig base_model_prefix = "blip" input_modalities = ("image", "text") supports_gradient_checkpointing = True _supports_attention_backend = True _supports_flash_attn = True _supports_sdpa = True _supports_flex_attn = True _can_compile...
InstructBlipPreTrainedModel
python
bokeh__bokeh
src/bokeh/models/glyphs.py
{ "start": 29626, "end": 30439 }
class ____(Glyph, LineGlyph): ''' Render several lines. The data for the ``MultiLine`` glyph is different in that the vector of values is not a vector of scalars. Rather, it is a "list of lists". ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) ...
MultiLine
python
scrapy__scrapy
tests/test_utils_spider.py
{ "start": 214, "end": 807 }
class ____(Spider): name = "myspider2" def test_iterate_spider_output(): i = Item() r = Request("http://scrapytest.org") o = object() assert list(iterate_spider_output(i)) == [i] assert list(iterate_spider_output(r)) == [r] assert list(iterate_spider_output(o)) == [o] assert list(iter...
MySpider2
python
PrefectHQ__prefect
src/prefect/client/schemas/objects.py
{ "start": 31962, "end": 32867 }
class ____(ObjectBaseModel): """An ORM representation of a block type""" name: Name = Field(default=..., description="A block type's name") slug: str = Field(default=..., description="A block type's slug") logo_url: Optional[HttpUrl] = Field( default=None, description="Web URL for the block typ...
BlockType
python
scipy__scipy
benchmarks/benchmarks/sparse.py
{ "start": 18507, "end": 19199 }
class ____(Benchmark): param_names = ['sparse_type', 'density', 'format', 'explicit'] params = [ ['spmatrix', 'sparray'], [0.01, 0.1, 0.5], ['csr', 'csc', 'coo'], [True, False], ] def setup(self, sparse_type, density, format, explicit): n = 1000 warnings...
Argmax
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 13556, "end": 14001 }
class ____(sgqlc.types.Enum): """Properties by which discussion poll option connections can be ordered. Enumeration Choices: * `AUTHORED_ORDER`: Order poll options by the order that the poll author specified when creating the poll. * `VOTE_COUNT`: Order poll options by the number of votes it...
DiscussionPollOptionOrderField
python
run-llama__llama_index
llama-index-integrations/sparse_embeddings/llama-index-sparse-embeddings-fastembed/llama_index/sparse_embeddings/fastembed/base.py
{ "start": 360, "end": 3931 }
class ____(BaseSparseEmbedding): """ Qdrant FastEmbedding Sparse models. FastEmbed is a lightweight, fast, Python library built for embedding generation. See more documentation at: * https://github.com/qdrant/fastembed/ * https://qdrant.github.io/fastembed/. To use this class, you must inst...
FastEmbedSparseEmbedding
python
scipy__scipy
scipy/stats/tests/test_stats.py
{ "start": 283595, "end": 288089 }
class ____: @pytest.mark.filterwarnings( "ignore:divide by zero encountered in log:RuntimeWarning:dask" ) def test_0(self, xp): a = [1, 0, 2] desired = 0 check_equal_gmean(a, desired, xp=xp) def test_1d(self, xp): # Test a 1d case a = [10, 20, 30, 40, 50...
TestGMean
python
gevent__gevent
src/greentest/3.14/test_signal.py
{ "start": 43781, "end": 51424 }
class ____(unittest.TestCase): """ Stress signal delivery, especially when a signal arrives in the middle of recomputing the signal state or executing previously tripped signal handlers. """ def setsig(self, signum, handler): old_handler = signal.signal(signum, handler) self.add...
StressTest
python
anthropics__anthropic-sdk-python
src/anthropic/resources/beta/messages/batches.py
{ "start": 35507, "end": 36116 }
class ____: def __init__(self, batches: AsyncBatches) -> None: self._batches = batches self.create = async_to_streamed_response_wrapper( batches.create, ) self.retrieve = async_to_streamed_response_wrapper( batches.retrieve, ) self.list = asyn...
AsyncBatchesWithStreamingResponse
python
langchain-ai__langchain
libs/core/langchain_core/runnables/passthrough.py
{ "start": 10210, "end": 20852 }
class ____(RunnableSerializable[dict[str, Any], dict[str, Any]]): """Runnable that assigns key-value pairs to `dict[str, Any]` inputs. The `RunnableAssign` class takes input dictionaries and, through a `RunnableParallel` instance, applies transformations, then combines these with the original data, int...
RunnableAssign
python
dagster-io__dagster
examples/docs_projects/project_mini/src/project_mini/defs/dynamic_fanout/dynamic_fanout.py
{ "start": 280, "end": 9773 }
class ____(dg.Config): input_data_path: str processing_threshold: float = 0.5 # Helper functions for your domain logic def extract_processing_units(record: dict[str, Any]) -> list[dict[str, Any]]: """Extract 10-30 processing units from a single data record.""" # Replace with your actual unit extractio...
DataProcessingConfig
python
kamyu104__LeetCode-Solutions
Python/kth-largest-sum-in-a-binary-tree.py
{ "start": 158, "end": 1881 }
class ____(object): def kthLargestLevelSum(self, root, k): """ :type root: Optional[TreeNode] :type k: int :rtype: int """ def nth_element(nums, n, left=0, compare=lambda a, b: a < b): def tri_partition(nums, left, right, target, compare): ...
Solution
python
ray-project__ray
python/ray/train/tests/test_iter_torch_batches_gpu.py
{ "start": 6681, "end": 6930 }
class ____(TuplePandasBatchCollateFn): """Collate function that returns id and value as a list of tensors.""" def __call__(self, batch: pd.DataFrame) -> List[torch.Tensor]: return list(super().__call__(batch))
ListPandasBatchCollateFn
python
pytorch__pytorch
torch/distributed/pipelining/_utils.py
{ "start": 1114, "end": 4505 }
class ____(RuntimeError): """Shape mismatch between configured and runtime values.""" def validate_tensor_metadata(desc, expected, given): if not expected.shape == given.shape: raise PipeliningShapeError( f"{desc} has a shape mismatch: expected {expected.shape} actual {given.shape}" ...
PipeliningShapeError
python
django__django
tests/builtin_server/tests.py
{ "start": 1668, "end": 2263 }
class ____(ServerHandler): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.request_handler = DummyHandler() self._used_sendfile = False def sendfile(self): self._used_sendfile = True return True def wsgi_app(environ, start_response): sta...
FileWrapperHandler
python
pypa__installer
tests/test_records.py
{ "start": 6741, "end": 9568 }
class ____: def test_accepts_empty_iterable(self): list(parse_record_file([])) @pytest.mark.parametrize( "record_input", ["record_simple_list", "record_simple_iter", "record_simple_file"], indirect=True, ) def test_accepts_all_kinds_of_iterables(self, record_input): ...
TestParseRecordFile
python
facebook__pyre-check
client/coverage_data.py
{ "start": 2281, "end": 2422 }
class ____(str, Enum): UNSAFE = "UNSAFE" STRICT = "STRICT" IGNORE_ALL = "IGNORE_ALL" @dataclasses.dataclass(frozen=True)
ModuleMode
python
Textualize__rich
rich/markdown.py
{ "start": 5983, "end": 6297 }
class ____(MarkdownElement): """A horizontal rule to divide sections.""" new_line = False def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: style = console.get_style("markdown.hr", default="none") yield Rule(style=style)
HorizontalRule
python
pytorch__pytorch
torch/onnx/_internal/fx/passes/type_promotion.py
{ "start": 8954, "end": 11193 }
class ____(TypePromotionRule): def __init__( self, namespace: str, op_name: str, promotion_kind: _prims_common.REDUCTION_OUTPUT_TYPE_KIND, ) -> None: """Constructs a TypePromotionRule for reduction operators. Args: namespace: Namespace of the op. E.g....
ReductionTypePromotionRule
python
doocs__leetcode
solution/0300-0399/0307.Range Sum Query - Mutable/Solution.py
{ "start": 0, "end": 397 }
class ____: __slots__ = ["n", "c"] def __init__(self, n): self.n = n self.c = [0] * (n + 1) def update(self, x: int, delta: int): while x <= self.n: self.c[x] += delta x += x & -x def query(self, x: int) -> int: s = 0 while x > 0: ...
BinaryIndexedTree
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 311965, "end": 312732 }
class ____(sgqlc.types.Input): """Autogenerated input type of TransferEnterpriseOrganization""" __schema__ = github_schema __field_names__ = ("organization_id", "destination_enterprise_id", "client_mutation_id") organization_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="organizationId"...
TransferEnterpriseOrganizationInput
python
dagster-io__dagster
python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/core/pex_builder/deps.py
{ "start": 1728, "end": 6550 }
class ____: local_package_paths: list[str] def local_path_for(line: str, relative_to: str) -> Optional[str]: # Return the abspath for a local package, iff this line points to a local package, # otherwise return None. # This handles relative or absolute paths specified in requirements.txt, # eg ".....
LocalPackages
python
kamyu104__LeetCode-Solutions
Python/kth-smallest-path-xor-sum.py
{ "start": 1939, "end": 3185 }
class ____(object): def kthSmallest(self, par, vals, queries): """ :type par: List[int] :type vals: List[int] :type queries: List[List[int]] :rtype: List[int] """ def small_to_large_merge(sl1, sl2): # Total Time: O(n * (logn)^2) if len(sl1) < len(...
Solution2
python
django__django
tests/csrf_tests/tests.py
{ "start": 58130, "end": 58761 }
class ____(CsrfFunctionTestMixin, SimpleTestCase): def test_csrf_token_on_404_stays_constant(self): response = self.client.get("/does not exist/") # The error handler returns status code 599. self.assertEqual(response.status_code, 599) response.charset = "ascii" token1 = resp...
CsrfInErrorHandlingViewsTests
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/type1.py
{ "start": 3156, "end": 3298 }
class ____: x1: type x2: type[Any] reveal_type(Class2.x1, expected_text="type") reveal_type(Class2.x2, expected_text="type[Any]")
Class2
python
milvus-io__pymilvus
pymilvus/client/types.py
{ "start": 13034, "end": 18543 }
class ____: """enum states of bulk insert task""" ImportPending = 0 ImportFailed = 1 ImportStarted = 2 ImportPersisted = 5 ImportCompleted = 6 ImportFailedAndCleaned = 7 ImportUnknownState = 100 """pre-defined keys of bulk insert task info""" FAILED_REASON = "failed_reason" ...
BulkInsertState
python
PyCQA__pylint
pylint/checkers/symilar.py
{ "start": 27262, "end": 33937 }
class ____(BaseRawFileChecker, Symilar): """Checks for similarities and duplicated code. This computation may be memory / CPU intensive, so you should disable it if you experience some problems. """ name = "similarities" msgs = MSGS MIN_SIMILARITY_HELP = "Minimum lines number of a similari...
SimilaritiesChecker
python
run-llama__llama_index
llama-index-packs/llama-index-packs-code-hierarchy/llama_index/packs/code_hierarchy/code_hierarchy.py
{ "start": 604, "end": 1295 }
class ____(BaseModel): """ Unfortunately some languages need special options for how to make a signature. For example, html element signatures should include their closing >, there is no easy way to include this using an always-exclusive system. However, using an always-inclusive system, python de...
_SignatureCaptureType
python
dagster-io__dagster
python_modules/dagster/dagster/_daemon/run_coordinator/queued_run_coordinator_daemon.py
{ "start": 1423, "end": 20211 }
class ____(IntervalDaemon): """Used with the QueuedRunCoordinator on the instance. This process finds queued runs from the run store and launches them. """ def __init__(self, interval_seconds, page_size=PAGE_SIZE) -> None: self._exit_stack = ExitStack() self._executor: Optional[ThreadPo...
QueuedRunCoordinatorDaemon
python
matplotlib__matplotlib
lib/matplotlib/backends/_backend_tk.py
{ "start": 44284, "end": 44486 }
class ____(backend_tools.ConfigureSubplotsBase): def trigger(self, *args): NavigationToolbar2Tk.configure_subplots(self) @backend_tools._register_tool_class(FigureCanvasTk)
ConfigureSubplotsTk
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/linalg/linear_operator_full_matrix_test.py
{ "start": 1292, "end": 4930 }
class ____( linear_operator_test_util.SquareLinearOperatorDerivedClassTest): """Most tests done in the base class LinearOperatorDerivedClassTest.""" def operator_and_matrix( self, build_info, dtype, use_placeholder, ensure_self_adjoint_and_pd=False): shape = list(build_info.shape) matrix =...
SquareLinearOperatorFullMatrixTest
python
kamyu104__LeetCode-Solutions
Python/minimum-space-wasted-from-packaging.py
{ "start": 65, "end": 752 }
class ____(object): def minWastedSpace(self, packages, boxes): """ :type packages: List[int] :type boxes: List[List[int]] :rtype: int """ MOD = 10**9+7 INF = float("inf") packages.sort() result = INF for box in boxes: box.s...
Solution
python
google__jax
tests/mosaic/gpu_dialect_test.py
{ "start": 3348, "end": 38737 }
class ____(MosaicGpuTest): def test_dialect_module_is_loaded(self): self.assertTrue(_cext.globals._check_dialect_module_loaded("mosaic_gpu")) def test_initialize_barrier_op_arrival_count_must_be_strictly_positive(self): with ir.InsertionPoint(self.module.body): mgpu.dialect.initialize_barrier( ...
DialectTest
python
readthedocs__readthedocs.org
readthedocs/core/unresolver.py
{ "start": 1890, "end": 2054 }
class ____(UnresolverError): def __init__(self, project, language): self.project = project self.language = language
TranslationWithoutVersionError
python
TheAlgorithms__Python
linear_programming/simplex.py
{ "start": 493, "end": 11830 }
class ____: """Operate on simplex tableaus >>> Tableau(np.array([[-1,-1,0,0,1],[1,3,1,0,4],[3,1,0,1,4]]), 2, 2) Traceback (most recent call last): ... TypeError: Tableau must have type float64 >>> Tableau(np.array([[-1,-1,0,0,-1],[1,3,1,0,4],[3,1,0,1,4.]]), 2, 2) Traceback (most recent cal...
Tableau
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_ip_is_not_blacklisted.py
{ "start": 859, "end": 1861 }
class ____(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.ip_is_not_blacklisted" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _p...
ColumnValuesIpIsNotBlacklisted
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/partitions/utils/multi.py
{ "start": 3502, "end": 3997 }
class ____( NamedTuple("_PartitionDimensionKey", [("dimension_name", str), ("partition_key", str)]) ): """Representation of a single dimension of a multi-dimensional partition key.""" def __new__(cls, dimension_name: str, partition_key: str): return super().__new__( cls, dim...
PartitionDimensionKey
python
tensorflow__tensorflow
tensorflow/python/keras/callbacks.py
{ "start": 32875, "end": 34420 }
class ____(Callback): """Callback that accumulates epoch averages of metrics. This callback is automatically applied to every Keras model. Args: stateful_metrics: Iterable of string names of metrics that should *not* be averaged over an epoch. Metrics in this list will be logged as-is ...
BaseLogger
python
apache__airflow
providers/standard/tests/unit/standard/triggers/test_file.py
{ "start": 1009, "end": 2381 }
class ____: FILE_PATH = "/files/dags/example_async_file.py" def test_serialization(self): """Asserts that the trigger correctly serializes its arguments and classpath.""" trigger = FileTrigger(filepath=self.FILE_PATH, poll_interval=5) classpath, kwargs = trigger.serialize() asse...
TestFileTrigger
python
tensorflow__tensorflow
tensorflow/python/distribute/failure_handling/failure_handling.py
{ "start": 3219, "end": 8307 }
class ____(object): """Customization of `PreemptionCheckpointHandler` for various platforms. A `TerminationConfig` can be created and passed to a `tf.distribute.experimental.PreemptionCheckpointHandler` to provide customization based on the platform. It can deliver three pieces of information: * How to de...
TerminationConfig
python
kamyu104__LeetCode-Solutions
Python/number-of-steps-to-reduce-a-number-in-binary-representation-to-one.py
{ "start": 29, "end": 438 }
class ____(object): def numSteps(self, s): """ :type s: str :rtype: int """ result, carry = 0, 0 for i in reversed(xrange(1, len(s))): if int(s[i]) + carry == 1: carry = 1 # once it was set, it would keep carrying forever r...
Solution
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 22843, "end": 24478 }
class ____(TestCase): """Tests for intersperse()""" def test_even(self): iterable = (x for x in '01') self.assertEqual( list(mi.intersperse(None, iterable)), ['0', None, '1'] ) def test_odd(self): iterable = (x for x in '012') self.assertEqual( ...
IntersperseTest
python
getsentry__sentry
tests/sentry/integrations/msteams/webhook/test_ms_teams_webhook_endpoint.py
{ "start": 2978, "end": 3435 }
class ____(TestCase): def test_has_all_handlers(self) -> None: instance = MsTeamsWebhookEndpoint() assert len(instance._event_handlers) == 4 assert MsTeamsEvents.INSTALLATION_UPDATE in instance._event_handlers assert MsTeamsEvents.UNKNOWN in instance._event_handlers assert Ms...
TestEventHandler
python
spyder-ide__spyder
spyder/plugins/preferences/tests/conftest.py
{ "start": 843, "end": 2368 }
class ____(QMainWindow): register_shortcut = Mock() def __init__(self, parent): super().__init__(parent) self.default_style = None self.widgetlist = [] self.thirdparty_plugins = [] self.shortcut_data = [] self.prefs_dialog_instance = None self._APPLICATIO...
MainWindowMock
python
django-haystack__django-haystack
test_haystack/test_loading.py
{ "start": 8376, "end": 15245 }
class ____(TestCase): def setUp(self): super().setUp() self.ui = loading.UnifiedIndex() self.ui.build([]) def test_get_index(self): self.assertRaises(NotHandled, self.ui.get_index, MockModel) try: self.ui.get_index(MockModel) except NotHandled as e: ...
UnifiedIndexTestCase
python
huggingface__transformers
src/transformers/modeling_outputs.py
{ "start": 60574, "end": 62286 }
class ____(ModelOutput): """ Base class for outputs of models predicting if two sentences are consecutive or not. Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `next_sentence_label` is provided): Next sequence prediction (classification) loss. logits...
NextSentencePredictorOutput
python
huggingface__transformers
src/transformers/models/granite_speech/modeling_granite_speech.py
{ "start": 10543, "end": 11566 }
class ____(nn.Module): """Conformer block, consisting largely of linear layers, attention, and convolutional layers.""" def __init__(self, config: GraniteSpeechEncoderConfig): super().__init__() self.ff1 = GraniteSpeechConformerFeedForward(config) self.attn = GraniteSpeechConformerAtten...
GraniteSpeechConformerBlock
python
pandas-dev__pandas
pandas/tests/arrays/test_datetimelike.py
{ "start": 35927, "end": 46924 }
class ____(SharedTests): index_cls = PeriodIndex array_cls = PeriodArray scalar_type = Period example_dtype = PeriodIndex([], freq="W").dtype @pytest.fixture def arr1d(self, period_index): """ Fixture returning DatetimeArray from parametrized PeriodIndex objects """ ...
TestPeriodArray
python
getlogbook__logbook
tests/conftest.py
{ "start": 1401, "end": 2455 }
class ____: def __init__(self, path): self.path = path def __fspath__(self): return self.path @pytest.fixture(params=[Path, str, CustomPathLike]) def logfile(tmp_path, request): path = str(tmp_path / "logfile.log") return request.param(path) @pytest.fixture def default_handler(reque...
CustomPathLike
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 65305, "end": 65391 }
class ____(legend_key_spacing): pass @deprecated_themeable_name
legend_entry_spacing
python
scipy__scipy
benchmarks/benchmarks/test_functions.py
{ "start": 4366, "end": 5494 }
class ____: target_E = -19.2085 solution = [8.05502, 9.66459] xmin = np.array([-10, -10]) xmax = np.array([10, 10]) stepsize = 2. temperature = 2. def fun(self, x): return - abs(sin(x[0]) * cos(x[1]) * exp(abs(1. - sqrt(x[0]**2 + x[1]**2) / pi))) def dabs(s...
HolderTable
python
pypa__setuptools
setuptools/_vendor/more_itertools/more.py
{ "start": 128554, "end": 148370 }
class ____: """Wrap *iterable* and keep a count of how many items have been consumed. The ``items_seen`` attribute starts at ``0`` and increments as the iterable is consumed: >>> iterable = map(str, range(10)) >>> it = countable(iterable) >>> it.items_seen 0 >>> nex...
countable
python
pydata__xarray
xarray/core/utils.py
{ "start": 17388, "end": 18617 }
class ____(Mapping[K, V]): """Implements the Mapping interface. Uses the wrapped mapping for item lookup and a separate wrapped keys collection for iteration. Can be used to construct a mapping object from another dict-like object without eagerly accessing its items or when a mapping object is expected...
FilteredMapping
python
redis__redis-py
redis/commands/json/__init__.py
{ "start": 4757, "end": 4845 }
class ____(JSONCommands, redis.client.Pipeline): """Pipeline for the module."""
Pipeline
python
scrapy__scrapy
tests/test_utils_curl.py
{ "start": 178, "end": 10182 }
class ____: @staticmethod def _test_command(curl_command: str, expected_result: dict[str, Any]) -> None: result = curl_to_request_kwargs(curl_command) assert result == expected_result try: Request(**result) except TypeError as e: pytest.fail(f"Request kwar...
TestCurlToRequestKwargs
python
django__django
tests/admin_views/models.py
{ "start": 17308, "end": 17430 }
class ____(models.Model): datum = models.DateField() employee = models.ForeignKey(Employee, models.CASCADE)
WorkHour
python
openai__openai-python
src/openai/types/responses/response_input_item.py
{ "start": 2877, "end": 3779 }
class ____(BaseModel): call_id: str """The ID of the computer tool call that produced the output.""" output: ResponseComputerToolCallOutputScreenshot """A computer screenshot image used with the computer use tool.""" type: Literal["computer_call_output"] """The type of the computer tool call o...
ComputerCallOutput
python
PrefectHQ__prefect
tests/server/utilities/test_text_search_parser.py
{ "start": 18206, "end": 19364 }
class ____: """Test the TextSearchQuery dataclass itself""" def test_dataclass_creation(self): query = TextSearchQuery( include=["term1", "term2"], exclude=["excluded"], required=["required"] ) assert query.include == ["term1", "term2"] assert query.exclude == ["excl...
TestDataclassStructure
python
cython__cython
Cython/Debugger/libpython.py
{ "start": 83748, "end": 83883 }
class ____(ExecutionControlCommandBase): "Run the program." invoke = dont_suppress_errors(ExecutionControlCommandBase.run)
PyRun
python
pytorch__pytorch
test/quantization/fx/test_numeric_suite_fx.py
{ "start": 30867, "end": 32474 }
class ____(QuantizationTestCase): @skipIfTorchDynamo("too slow") @skipIfNoFBGEMM @skip_if_no_torchvision def test_mobilenet_v2(self): # verify that mobilenetv2 graph is able to be matched import torchvision m = torchvision.models.__dict__['mobilenet_v2'](pretrained=False).eval()...
TestFXGraphMatcherModels
python
pytorch__pytorch
torch/testing/_internal/distributed/common_state_dict.py
{ "start": 457, "end": 4665 }
class ____: def _compare_tensor(self, orig_tensor, dist_tensor, offload_to_cpu=False): if isinstance(dist_tensor, (DTensor, ShardedTensor)): dist_tensor = _gather_state_dict({"mykey": dist_tensor}).pop("mykey") if offload_to_cpu: orig_tensor = orig_tensor.cpu() d...
VerifyStateDictMixin
python
pypa__setuptools
setuptools/_vendor/typing_extensions.py
{ "start": 2602, "end": 4660 }
class ____: def __repr__(self): return "<sentinel>" _marker = _Sentinel() if sys.version_info >= (3, 10): def _should_collect_from_parameters(t): return isinstance( t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType) ) elif sys.version_info >= (3, 9): def...
_Sentinel
python
pandas-dev__pandas
asv_bench/benchmarks/frame_methods.py
{ "start": 13510, "end": 13915 }
class ____: params = ["float64", "Float64", "float64[pyarrow]"] param_names = ["dtype"] def setup(self, dtype): data = np.random.randn(10000, 1000) # all-na columns data[:, 600:800] = np.nan # partial-na columns data[800:1000, 4000:5000] = np.nan self.df = Da...
Isna
python
EpistasisLab__tpot
tpot/search_spaces/base.py
{ "start": 3640, "end": 6634 }
class ____(): def __init__(self,): pass def generate(self, rng=None) -> SklearnIndividual: pass def flatten_graphpipeline(est): flattened_full_graph = est.graph.copy() #put ests into the node label from the attributes flattened_full_graph = nx.relabel_nodes(flattened_full_graph,...
SearchSpace
python
huggingface__transformers
src/transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py
{ "start": 1964, "end": 3552 }
class ____(nn.Module): """ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a Transformer. """ def __init__(self, config): super()._...
Dinov2WithRegistersPatchEmbeddings
python
sympy__sympy
sympy/assumptions/predicates/ntheory.py
{ "start": 1999, "end": 2546 }
class ____(Predicate): """ Odd number predicate. Explanation =========== ``ask(Q.odd(x))`` is true iff ``x`` belongs to the set of odd numbers. Examples ======== >>> from sympy import Q, ask, pi >>> ask(Q.odd(0)) False >>> ask(Q.odd(2)) False >>> ask(Q.odd(3)) ...
OddPredicate
python
redis__redis-py
tests/test_asyncio/test_pubsub.py
{ "start": 22777, "end": 24411 }
class ____: @pytest.mark.onlynoncluster @skip_if_server_version_lt("2.8.0") async def test_pubsub_channels(self, r: redis.Redis, pubsub): p = pubsub await p.subscribe("foo", "bar", "baz", "quux") for i in range(4): assert (await wait_for_message(p))["type"] == "subscribe"...
TestPubSubSubcommands
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constructor32.py
{ "start": 468, "end": 546 }
class ____(type): def __call__(cls: type[T], x: int, y: str) -> T: ...
BMeta
python
pennersr__django-allauth
tests/apps/socialaccount/providers/battlenet/tests.py
{ "start": 457, "end": 2697 }
class ____(OAuth2TestsMixin, TestCase): provider_id = BattleNetProvider.id _uid = 123456789 _battletag = "LuckyDragon#1953" def get_mocked_response(self): data = {"battletag": self._battletag, "id": self._uid} return MockedResponse(HTTPStatus.OK, json.dumps(data)) def get_expected_...
BattleNetTests
python
airbytehq__airbyte
airbyte-integrations/connectors/source-cart/source_cart/streams.py
{ "start": 5297, "end": 5436 }
class ____(IncrementalCartStream): """ Docs: https://developers.cart.com/docs/rest-api/restapi.json/paths/~1orders/get """
Orders
python
simonw__datasette
tests/test_plugins.py
{ "start": 47462, "end": 63484 }
class ____: __name__ = "SlotPlugin" @hookimpl def top_homepage(self, request): return "Xtop_homepage:" + request.args["z"] @hookimpl def top_database(self, request, database): async def inner(): return "Xtop_database:{}:{}".format(database, request.args["z"]) r...
SlotPlugin
python
google__jax
tests/lax_numpy_test.py
{ "start": 238540, "end": 243038 }
class ____(jtu.JaxTestCase): @parameterized.parameters(itertools.chain.from_iterable( jtu.sample_product_testcases( [dict(op=rec.op, rng_factory=rec.rng_factory, tol=rec.tol, order=rec.order)], shapes=itertools.combinations_with_replacement(nonempty_shapes, rec.nargs), dtype=rec.dty...
NumpyGradTests
python
django__django
tests/user_commands/management/commands/mutually_exclusive_required.py
{ "start": 54, "end": 910 }
class ____(BaseCommand): def add_arguments(self, parser): group = parser.add_mutually_exclusive_group(required=True) group.add_argument("--foo-id", type=int, nargs="?", default=None) group.add_argument("--foo-name", type=str, nargs="?", default=None) group.add_argument("--foo-list", ...
Command
python
dagster-io__dagster
python_modules/libraries/dagster-managed-elements/dagster_managed_elements/types.py
{ "start": 220, "end": 967 }
class ____(enum.Enum): CANNOT_CONNECT = "cannot_connect" SANITIZE_KEY_KEYWORDS = [ "password", "token", "secret", "ssh_key", "credentials_json", "access_key_id", ] SANITIZE_KEY_EXACT_MATCHES = ["pat"] SECRET_MASK_VALUE = "**********" def is_key_secret(key: str): """Rudamentary check...
ManagedElementError
python
google__jax
tests/tree_util_test.py
{ "start": 7999, "end": 36238 }
class ____(jtu.JaxTestCase): @parameterized.parameters(*(TREES + LEAVES)) def testRoundtrip(self, inputs): xs, tree = tree_util.tree_flatten(inputs) actual = tree_util.tree_unflatten(tree, xs) self.assertEqual(actual, inputs) @parameterized.parameters(*(TREES + LEAVES)) def testRoundtripWithFlatte...
TreeTest
python
getsentry__sentry
src/sentry/utils/services.py
{ "start": 1379, "end": 14414 }
class ____: """ The delegator is a class that coordinates and delegates method execution to multiple named backends that share a common API. It can be used to route requests to different backends based on method arguments, as well as execute the same request against multiple backends in parallel for...
Delegator
python
celery__celery
celery/exceptions.py
{ "start": 4231, "end": 4346 }
class ____(CeleryWarning): """Celery hasn't been configured, as no config module has been found."""
NotConfigured
python
pydantic__pydantic
pydantic/v1/errors.py
{ "start": 10080, "end": 10156 }
class ____(PydanticTypeError): msg_template = 'str type expected'
StrError
python
catalyst-team__catalyst
examples/detection/models/yolo_x.py
{ "start": 2536, "end": 2995 }
class ____(nn.Module): "Residual layer with `in_channels` inputs." def __init__(self, in_channels: int): super().__init__() mid_channels = in_channels // 2 self.layer1 = BaseConv(in_channels, mid_channels, ksize=1, stride=1, act="lrelu") self.layer2 = BaseConv(mid_channels, in_c...
ResLayer
python
tiangolo__fastapi
tests/test_security_oauth2_optional_description.py
{ "start": 547, "end": 11487 }
class ____(BaseModel): username: str def get_current_user(oauth_header: Optional[str] = Security(reusable_oauth2)): if oauth_header is None: return None user = User(username=oauth_header) return user @app.post("/login") def login(form_data: OAuth2PasswordRequestFormStrict = Depends()): r...
User
python
walkccc__LeetCode
solutions/900. RLE Iterator/900.py
{ "start": 0, "end": 415 }
class ____: def __init__(self, encoding: list[int]): self.encoding = encoding self.index = 0 def next(self, n: int) -> int: while self.index < len(self.encoding) and self.encoding[self.index] < n: n -= self.encoding[self.index] self.index += 2 if self.index == len(self.encoding): ...
RLEIterator
python
sympy__sympy
sympy/integrals/manualintegrate.py
{ "start": 6989, "end": 7132 }
class ____(TrigRule): """integrate(sin(x), x) -> -cos(x)""" def eval(self) -> Expr: return -cos(self.variable) @dataclass
SinRule