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
scrapy__scrapy
scrapy/core/spidermw.py
{ "start": 1451, "end": 25300 }
class ____(MiddlewareManager): component_name = "spider middleware" @classmethod def _get_mwlist_from_settings(cls, settings: BaseSettings) -> list[Any]: return build_component_list(settings.getwithbase("SPIDER_MIDDLEWARES")) def __init__(self, *middlewares: Any, crawler: Crawler | None = None...
SpiderMiddlewareManager
python
readthedocs__readthedocs.org
readthedocs/api/v3/tests/test_users.py
{ "start": 615, "end": 5462 }
class ____(APIEndpointMixin): def test_users_list(self): # We don't have this endpoint enabled on purpose with self.assertRaises(NoReverseMatch) as e: reverse("users-list") def test_users_detail(self): # We don't have this endpoint enabled on purpose with self.assert...
UsersEndpointTests
python
pydata__xarray
xarray/tests/test_combine.py
{ "start": 9198, "end": 9795 }
class ____: @pytest.mark.parametrize( "old_id, new_id", [((3, 0, 1), (0, 1)), ((0, 0), (0,)), ((1,), ()), ((0,), ()), ((1, 0), (0,))], ) def test_new_tile_id(self, old_id, new_id): ds = create_test_data assert _new_tile_id((old_id, ds)) == new_id def test_get_new_tile_id...
TestNewTileIDs
python
huggingface__transformers
src/transformers/models/autoformer/modeling_autoformer.py
{ "start": 32463, "end": 38663 }
class ____(GradientCheckpointingLayer): def __init__(self, config: AutoformerConfig, layer_idx=None): super().__init__() self.embed_dim = config.d_model self.self_attn = AutoformerAttention( embed_dim=self.embed_dim, num_heads=config.decoder_attention_heads, ...
AutoformerDecoderLayer
python
walkccc__LeetCode
solutions/204. Count Primes/204.py
{ "start": 0, "end": 401 }
class ____: def countPrimes(self, n: int) -> int: if n <= 2: return 0 return sum(self._sieveEratosthenes(n)) def _sieveEratosthenes(self, n: int) -> list[bool]: isPrime = [True] * n isPrime[0] = False isPrime[1] = False for i in range(2, int(n**0.5) + 1): if isPrime[i]: ...
Solution
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_H.py
{ "start": 7687, "end": 8677 }
class ____(Benchmark): r""" HimmelBlau objective function. This class defines the HimmelBlau [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{HimmelBlau}}({x}) = (x_1^2 + x_2 - 11)^2 + (x_1 + x_2^2 - 7)^2 with :math:...
HimmelBlau
python
pytorch__pytorch
tools/linter/adapters/_linter/python_file.py
{ "start": 435, "end": 5142 }
class ____: contents: str lines: list[str] path: Path | None linter_name: str def __init__( self, linter_name: str, path: Path | None = None, contents: str | None = None, ) -> None: self.linter_name = linter_name self.path = path and (path.relativ...
PythonFile
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 695561, "end": 696165 }
class ____(sgqlc.types.Type): """Autogenerated return type of MergePullRequest""" __schema__ = github_schema __field_names__ = ("actor", "client_mutation_id", "pull_request") actor = sgqlc.types.Field(Actor, graphql_name="actor") """Identifies the actor who performed the event.""" client_mutat...
MergePullRequestPayload
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 17522, "end": 17666 }
class ____(axis_title_x, axis_title_y): """ Axis labels Parameters ---------- theme_element : element_text """
axis_title
python
tensorflow__tensorflow
tensorflow/compiler/mlir/tfr/python/op_reg_gen.py
{ "start": 1203, "end": 4219 }
class ____(transformer.CodeGenerator): """Visit the AST and generate C++ op registration functions.""" def __init__(self, ctx): super(OpRegGenImpl, self).__init__(ctx) self.ctx = ctx def visit_Name(self, node): return node.id def visit_Constant(self, node): return node.value def visit_keyw...
OpRegGenImpl
python
keras-team__keras
keras/src/ops/symbolic_arguments.py
{ "start": 71, "end": 1628 }
class ____: def __init__(self, *args, **kwargs): self.args = tree.map_structure(lambda x: x, args) self.kwargs = tree.map_structure(lambda x: x, kwargs) self._flat_arguments = tree.flatten((self.args, self.kwargs)) # Used to avoid expensive `tree` operations in the most common case....
SymbolicArguments
python
scipy__scipy
benchmarks/benchmarks/interpolate.py
{ "start": 15001, "end": 15937 }
class ____(interpolate.CloughTocher2DInterpolator): """Subclass of the CT2DInterpolator with optional `values`. This is mainly a demo of the functionality. See https://github.com/scipy/scipy/pull/18376 for discussion """ def __init__(self, points, xi, tol=1e-6, maxiter=400, **kwargs): inter...
CloughTocherInterpolatorValues
python
realpython__materials
hangman-pysimplegui/source_code_step_3/hangman.py
{ "start": 27, "end": 504 }
class ____: def __init__(self) -> None: self._window = sg.Window( title="Hangman", layout=[[]], finalize=True, margins=(100, 100) ) def read_event(self): return self._window.read() def close(self): self._window.close() if __name__ == "__main__": game = Han...
Hangman
python
python-markdown__markdown
tests/test_apis.py
{ "start": 22761, "end": 25378 }
class ____(unittest.TestCase): """ Test that `AtomicStrings` are honored (not parsed). """ def setUp(self): self.md = markdown.Markdown() self.inlineprocessor = self.md.treeprocessors['inline'] def testString(self): """ Test that a regular string is parsed. """ tree = etree...
testAtomicString
python
pypa__warehouse
warehouse/oidc/models/google.py
{ "start": 3841, "end": 4296 }
class ____(GooglePublisherMixin, OIDCPublisher): __tablename__ = "google_oidc_publishers" __mapper_args__ = {"polymorphic_identity": "google_oidc_publishers"} __table_args__ = ( UniqueConstraint( "email", "sub", name="_google_oidc_publisher_uc", ), ) ...
GooglePublisher
python
huggingface__transformers
src/transformers/pipelines/image_text_to_text.py
{ "start": 1485, "end": 21328 }
class ____(Pipeline): """ Image-text-to-text pipeline using an `AutoModelForImageTextToText`. This pipeline generates text given an image and text. When the underlying model is a conversational model, it can also accept one or more chats, in which case the pipeline will operate in chat mode and will con...
ImageTextToTextPipeline
python
getsentry__sentry
src/sentry/incidents/endpoints/project_alert_rule_index.py
{ "start": 661, "end": 1712 }
class ____(ProjectEndpoint, AlertRuleIndexMixin): owner = ApiOwner.ISSUES publish_status = { "GET": ApiPublishStatus.EXPERIMENTAL, "POST": ApiPublishStatus.EXPERIMENTAL, } permission_classes = (ProjectAlertRulePermission,) @track_alert_endpoint_execution("GET", "sentry-api-0-project...
ProjectAlertRuleIndexEndpoint
python
scrapy__scrapy
tests/test_feedexport.py
{ "start": 22418, "end": 22583 }
class ____(DummyBlockingFeedStorage): def _store_in_thread(self, file): raise OSError("Cannot store") @implementer(IFeedStorage)
FailingBlockingFeedStorage
python
pypa__pip
src/pip/_internal/commands/search.py
{ "start": 957, "end": 5782 }
class ____(Command, SessionCommandMixin): """Search for PyPI packages whose name or summary contains <query>.""" usage = """ %prog [options] <query>""" ignore_require_venv = True def add_options(self) -> None: self.cmd_opts.add_option( "-i", "--index", ...
SearchCommand
python
nryoung__algorithms
tests/test_sorting.py
{ "start": 1284, "end": 1525 }
class ____(SortingAlgorithmTestCase): """ Tests Comb sort on a small range from 0-9 """ def test_combsort(self): self.output = comb_sort.sort(self.input) self.assertEqual(self.correct, self.output)
TestCombSort
python
kamyu104__LeetCode-Solutions
Python/count-pairs-of-similar-strings.py
{ "start": 93, "end": 490 }
class ____(object): def similarPairs(self, words): """ :type words: List[str] :rtype: int """ cnt = collections.Counter() result = 0 for w in words: mask = reduce(lambda total, x: total|x, itertools.imap(lambda c: 1<<(ord(c)-ord('a')), w)) ...
Solution
python
tensorflow__tensorflow
tensorflow/python/framework/ops.py
{ "start": 39056, "end": 62180 }
class ____(pywrap_tf_session.PyOperation): """Represents a graph node that performs computation on tensors. An `Operation` is a node in a `tf.Graph` that takes zero or more `Tensor` objects as input, and produces zero or more `Tensor` objects as output. Objects of type `Operation` are created by calling a Pyth...
Operation
python
cython__cython
Cython/Compiler/MatchCaseNodes.py
{ "start": 4187, "end": 4309 }
class ____(Node): """ Common base for a MatchCaseNode and a substituted node """ pass
MatchCaseBaseNode
python
pytorch__pytorch
torch/_inductor/fx_passes/reinplace.py
{ "start": 2299, "end": 30996 }
class ____: target: torch._ops.OpOverload args: tuple[Any, ...] kwargs: dict[str, Any] def _inplace_generalized_scatter( inp: torch.Tensor, src: torch.Tensor, view_ops: list[ViewOp] ) -> torch.Tensor: tmp = inp for view in view_ops: fake_args, fake_kwargs = pytree.tree_map( ...
ViewOp
python
getsentry__sentry
src/sentry/notifications/platform/msteams/provider.py
{ "start": 1009, "end": 4290 }
class ____(NotificationRenderer[MSTeamsRenderable]): provider_key = NotificationProviderKey.MSTEAMS @classmethod def render[DataT: NotificationData]( cls, *, data: DataT, rendered_template: NotificationRenderedTemplate ) -> MSTeamsRenderable: from sentry.integrations.msteams.card_builde...
MSTeamsRenderer
python
ray-project__ray
python/ray/tests/test_node_label_scheduling_strategy.py
{ "start": 181, "end": 11068 }
class ____: def __init__(self): self.value = 0 def value(self): return self.value def get_node_id(self): return ray.get_runtime_context().get_node_id() @ray.remote def get_node_id(): return ray.get_runtime_context().get_node_id() @pytest.mark.parametrize( "call_ray_star...
MyActor
python
modin-project__modin
modin/core/computation/ops.py
{ "start": 5516, "end": 8740 }
class ____: """ Hold an operator of arbitrary arity. """ op: str def __init__(self, op: str, operands: Iterable[Term | Op], encoding=None) -> None: self.op = _bool_op_map.get(op, op) self.operands = operands self.encoding = encoding def __iter__(self) -> Iterator: ...
Op
python
lepture__authlib
authlib/oidc/core/errors.py
{ "start": 2270, "end": 2424 }
class ____(OAuth2Error): """The request parameter contains an invalid Request Object.""" error = "invalid_request_object"
InvalidRequestObjectError
python
getsentry__sentry
src/sentry/apidocs/parameters.py
{ "start": 17456, "end": 19537 }
class ____: QUERY = OpenApiParameter( name="query", location="query", required=False, type=str, description="""Filters results by using [query syntax](/product/sentry-basics/search/). Example: `query=(transaction:foo AND release:abc) OR (transaction:[bar,baz] AND release:def...
VisibilityParams
python
explosion__spaCy
spacy/lang/lt/__init__.py
{ "start": 235, "end": 452 }
class ____(BaseDefaults): infixes = TOKENIZER_INFIXES suffixes = TOKENIZER_SUFFIXES tokenizer_exceptions = TOKENIZER_EXCEPTIONS stop_words = STOP_WORDS lex_attr_getters = LEX_ATTRS
LithuanianDefaults
python
pytorch__pytorch
test/inductor/test_compiled_optimizers.py
{ "start": 5104, "end": 23478 }
class ____(NamedTuple): multitensor: int singletensor: int # With different settings for certain # tests you can get different kernel counts # This maps the test name to the # expected kernel count # fmt: off # expecttest got error after PYFMT add line break for the triple quotes KERNEL_COUNT_OVERRIDES = { ...
KernelCounts
python
kamyu104__LeetCode-Solutions
Python/partition-equal-subset-sum.py
{ "start": 55, "end": 485 }
class ____(object): def canPartition(self, nums): """ :type nums: List[int] :rtype: bool """ s = sum(nums) if s % 2: return False dp = [False] * (s/2 + 1) dp[0] = True for num in nums: for i in reversed(xrange(1, len(dp...
Solution
python
pytorch__pytorch
torch/nn/modules/pooling.py
{ "start": 46521, "end": 48874 }
class ____(_LPPoolNd): r"""Applies a 2D power-average pooling over an input signal composed of several input planes. On each window, the function computed is: .. math:: f(X) = \sqrt[p]{\sum_{x \in X} x^{p}} - At p = :math:`\infty`, one gets Max Pooling - At p = 1, one gets Sum Pooling (wh...
LPPool2d
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 17469, "end": 18044 }
class ____(BaseModel): id: str = Field(..., description="") init_time_ms: int = Field(..., description="") config: "CollectionConfigTelemetry" = Field(..., description="") shards: Optional[List["ReplicaSetTelemetry"]] = Field(default=None, description="") transfers: Optional[List["ShardTransferInfo"...
CollectionTelemetry
python
has2k1__plotnine
plotnine/stats/stat_density_2d.py
{ "start": 288, "end": 5844 }
class ____(stat): """ Compute 2D kernel density estimation {usage} Parameters ---------- {common_parameters} contour : bool, default=True Whether to create contours of the 2d density estimate. n : int, default=64 Number of equally spaced points at which the density is t...
stat_density_2d
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/unique_test.py
{ "start": 3671, "end": 4268 }
class ____(checkpoint_test_base.CheckpointTestBase, parameterized.TestCase): @combinations.generate( combinations.times(test_base.default_test_combinations(), checkpoint_test_base.default_test_combinations())) def test(self, verify_fn): def build_datas...
UniqueCheckpointTest
python
google__pytype
pytype/tests/test_match_case.py
{ "start": 247, "end": 830 }
class ____(test_base.BaseTest): """Tests for matching match-case statements.""" def test_match_case_with_classes(self): self.CheckWithErrors(""" import dataclasses @dataclasses.dataclass(frozen=True) class A: a: str @dataclasses.dataclass(frozen=True) class B: b: i...
MatchCaseTest
python
numba__numba
numba/core/typing/context.py
{ "start": 1186, "end": 4431 }
class ____(Sequence): """ A compile-time call stack """ def __init__(self): self._stack = [] self._lock = threading.RLock() # fail_cache only last for the current compilation session self._fail_cache = {} def __getitem__(self, index): """ Returns ite...
CallStack
python
run-llama__llama_index
llama-index-core/llama_index/core/base/embeddings/base.py
{ "start": 1073, "end": 2014 }
class ____(str, Enum): """Modes for similarity/distance.""" DEFAULT = "cosine" DOT_PRODUCT = "dot_product" EUCLIDEAN = "euclidean" def mean_agg(embeddings: List[Embedding]) -> Embedding: """Mean aggregation for embeddings.""" return np.array(embeddings).mean(axis=0).tolist() def similarity(...
SimilarityMode
python
huggingface__transformers
src/transformers/models/oneformer/image_processing_oneformer.py
{ "start": 1784, "end": 14354 }
class ____(ImagesKwargs, total=False): r""" repo_path (`str`, *optional*, defaults to `shi-labs/oneformer_demo`): Path to a local directory or Hugging Face Hub repository containing model metadata. class_info_file (`str`, *optional*): Path to the JSON file within the repository that contains...
OneFormerImageProcessorKwargs
python
plotly__plotly.py
plotly/io/_base_renderers.py
{ "start": 4375, "end": 5103 }
class ____(ImageRenderer): """ Renderer to display figures as static SVG images. This renderer requires either the kaleido package or the orca command-line utility and is broadly compatible across IPython environments (classic Jupyter Notebook, JupyterLab, QtConsole, VSCode, PyCharm, etc) and nbcon...
SvgRenderer
python
getsentry__sentry
tests/sentry/integrations/api/endpoints/test_doc_integration_details.py
{ "start": 426, "end": 1303 }
class ____(APITestCase): endpoint = "sentry-api-0-doc-integration-details" def setUp(self) -> None: self.user = self.create_user(email="jinx@lol.com") self.superuser = self.create_user(email="vi@lol.com", is_superuser=True) self.staff_user = self.create_user(is_staff=True) self....
DocIntegrationDetailsTest
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/check_ops_test.py
{ "start": 54908, "end": 58963 }
class ____(test.TestCase): @test_util.run_in_graph_and_eager_modes def test_rank_zero_tensor_raises_if_rank_too_small_static_rank(self): tensor = constant_op.constant(1, name="my_tensor") desired_rank = 1 with self.assertRaisesRegex(ValueError, "rank at least 1"): with ops.control_dependencies( ...
AssertRankAtLeastTest
python
weaviate__weaviate-python-client
weaviate/collections/queries/near_text/generate/executor.py
{ "start": 998, "end": 21196 }
class ____( Generic[ConnectionType, Properties, References], _BaseExecutor[ConnectionType] ): @overload def near_text( self, query: Union[List[str], str], *, single_prompt: Union[str, _SinglePrompt, None] = None, grouped_task: Union[str, _GroupedTask, None] = None, ...
_NearTextGenerateExecutor
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP046_1.py
{ "start": 292, "end": 339 }
class ____(Generic[AnyStr]): var: AnyStr
BadStr
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/take_while_test.py
{ "start": 1321, "end": 5194 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate( combinations.times( test_base.default_test_combinations(), combinations.combine(num_elements=[14, 15], window_size=[2]) + combinations.combine(num_elements=[100], window_size=[3]))) def testTa...
TakeWhileTest
python
huggingface__transformers
src/transformers/pipelines/base.py
{ "start": 23212, "end": 28294 }
class ____(ABC): """ Interface layer for the Scikit and Keras compatibility. """ @abstractmethod def transform(self, X): raise NotImplementedError() @abstractmethod def predict(self, X): raise NotImplementedError() def build_pipeline_init_args( has_tokenizer: bool = F...
_ScikitCompat
python
doocs__leetcode
solution/1500-1599/1577.Number of Ways Where Square of Number Is Equal to Product of Two Numbers/Solution.py
{ "start": 0, "end": 534 }
class ____: def numTriplets(self, nums1: List[int], nums2: List[int]) -> int: def count(nums: List[int]) -> Counter: cnt = Counter() for j in range(len(nums)): for k in range(j + 1, len(nums)): cnt[nums[j] * nums[k]] += 1 return cnt ...
Solution
python
apache__airflow
airflow-core/src/airflow/utils/log/file_task_handler.py
{ "start": 4907, "end": 5827 }
class ____(BaseModel): """An individual log message.""" timestamp: datetime | None = None event: str # Collisions of sort_key may occur due to duplicated messages. If this happens, the heap will use the second element, # which is the StructuredLogMessage for comparison. Therefore, we need to defin...
StructuredLogMessage
python
gevent__gevent
src/gevent/testing/testcase.py
{ "start": 8805, "end": 9285 }
class ____(object): def setUp(self): super(SubscriberCleanupMixin, self).setUp() from gevent import events self.__old_subscribers = events.subscribers[:] def addSubscriber(self, sub): from gevent import events events.subscribers.append(sub) def tearDown(self): ...
SubscriberCleanupMixin
python
skorch-dev__skorch
skorch/tests/test_net.py
{ "start": 160350, "end": 167042 }
class ____: """Test functionality related to torch.compile (if available)""" @pytest.fixture(scope='module') def data(self, classifier_data): return classifier_data @pytest.fixture(scope='module') def module_cls(self, classifier_module): return classifier_module @pytest.fixture...
TestTorchCompile
python
pytorch__pytorch
test/distributed/test_c10d_pypg.py
{ "start": 3025, "end": 4710 }
class ____(test_c10d_common.CommonDistributedDataParallelTest): def setUp(self): super().setUp() self._spawn_threads() @property def world_size(self): return 1 def _get_process_group(self): return LonelyRankProcessGroup(self.rank, self.world_size, self.use_wrapper) ...
AbstractDDPSingleRank
python
pandas-dev__pandas
pandas/core/indexing.py
{ "start": 88270, "end": 89524 }
class ____(NDFrameIndexerBase): """ Access scalars quickly. """ # sub-classes need to set _takeable _takeable: bool def _convert_key(self, key): raise AbstractMethodError(self) def __getitem__(self, key): if not isinstance(key, tuple): # we could have a convert...
_ScalarAccessIndexer
python
Textualize__textual
docs/examples/guide/command_palette/command02.py
{ "start": 266, "end": 1395 }
class ____(Provider): """A command provider to open a Python file in the current working directory.""" def read_files(self) -> list[Path]: """Get a list of Python files in the current working directory.""" return list(Path("./").glob("*.py")) async def startup(self) -> None: # (1)! ...
PythonFileCommands
python
pytorch__pytorch
test/dynamo/test_modules.py
{ "start": 14885, "end": 14976 }
class ____(NamedTuple): x: dict[str, dict[str, torch.Tensor]] y: torch.Tensor
MyInput
python
huggingface__transformers
src/transformers/models/mllama/modeling_mllama.py
{ "start": 11284, "end": 12879 }
class ____(nn.Module): def __init__(self, config: MllamaVisionConfig, is_gated: bool = False): super().__init__() self.hidden_size = config.hidden_size self.num_attention_heads = config.attention_heads self.is_gated = is_gated self.intermediate_size = config.intermediate_siz...
MllamaVisionEncoderLayer
python
getsentry__sentry
src/sentry/deletions/defaults/alert_rule_trigger_action.py
{ "start": 153, "end": 835 }
class ____(ModelDeletionTask[AlertRuleTriggerAction]): manager_name = "objects_for_deletion" def get_child_relations(self, instance: AlertRuleTriggerAction) -> list[BaseRelation]: from sentry.notifications.models.notificationmessage import NotificationMessage from sentry.workflow_engine.models ...
AlertRuleTriggerActionDeletionTask
python
plotly__plotly.py
tests/test_core/test_offline/test_offline.py
{ "start": 2052, "end": 15395 }
class ____(PlotlyOfflineBaseTestCase): def setUp(self): pio.templates.default = None def tearDown(self): pio.templates.default = "plotly" super().tearDown() def _read_html(self, file_url): """Read and return the HTML contents from a file_url in the form e.g. file://...
PlotlyOfflineTestCase
python
django__django
tests/check_framework/test_templates.py
{ "start": 3430, "end": 7755 }
class ____(SimpleTestCase): def get_settings(self, module_name, module_path, name="django"): return { "BACKEND": "django.template.backends.django.DjangoTemplates", "NAME": name, "OPTIONS": { "libraries": { module_name: f"check_framework...
CheckTemplateTagLibrariesWithSameName
python
tensorflow__tensorflow
tensorflow/python/checkpoint/graph_view.py
{ "start": 1032, "end": 6793 }
class ____(trackable_view.TrackableView): """Gathers and serializes an object graph.""" def __init__(self, root, attached_dependencies=None): """Configure the graph view. Args: root: A `Trackable` object whose variables (including the variables of dependencies, recursively) should be saved. ...
ObjectGraphView
python
getsentry__sentry
src/sentry/api/validators/broadcast.py
{ "start": 99, "end": 206 }
class ____(serializers.Serializer): hasSeen = serializers.BooleanField(required=False)
BroadcastValidator
python
great-expectations__great_expectations
tests/integration/backend_dependencies.py
{ "start": 14, "end": 414 }
class ____(enum.Enum): AWS = "AWS" AWS_GLUE = "AWS_GLUE" ATHENA = "ATHENA" AZURE = "AZURE" BIGQUERY = "BIGQUERY" GCS = "GCS" MYSQL = "MYSQL" MSSQL = "MSSQL" PANDAS = "PANDAS" POSTGRESQL = "POSTGRESQL" REDSHIFT = "REDSHIFT" SPARK = "SPARK" SQLALCHEMY = "SQLALCHEMY" ...
BackendDependencies
python
django__django
tests/gis_tests/geoapp/feeds.py
{ "start": 1345, "end": 1809 }
class ____(TestGeoRSS1): feed_type = feeds.W3CGeoFeed def item_geometry(self, item): from django.contrib.gis.geos import Polygon return Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) # The feed dictionary to use for URLs. feed_dict = { "rss1": TestGeoRSS1, "rss2": TestGeoRSS2, ...
TestW3CGeo3
python
pytorch__pytorch
test/test_mps.py
{ "start": 26432, "end": 29711 }
class ____(TestCaseMPS): def _helper(self, shape_tensor_1, shape_tensor_2, expand_tensor_1_shape=None, expand_tensor_2_shape=None): if expand_tensor_1_shape: tensor1_mps = torch.randn(shape_tensor_1, device="mps").expand(expand_tensor_1_shape) else: tensor1_mps = torch.randn(...
MatmulTest
python
scikit-learn__scikit-learn
sklearn/naive_bayes.py
{ "start": 45400, "end": 57251 }
class ____(_BaseDiscreteNB): """Naive Bayes classifier for categorical features. The categorical Naive Bayes classifier is suitable for classification with discrete features that are categorically distributed. The categories of each feature are drawn from a categorical distribution. Read more in t...
CategoricalNB
python
numba__numba
numba/cuda/tests/cudasim/test_cudasim_issues.py
{ "start": 185, "end": 3179 }
class ____(CUDATestCase): def test_record_access(self): backyard_type = [('statue', np.float64), ('newspaper', np.float64, (6,))] goose_type = [('garden', np.float64, (12,)), ('town', np.float64, (42,)), ('backyard', backyard_type...
TestCudaSimIssues
python
FactoryBoy__factory_boy
factory/declarations.py
{ "start": 13737, "end": 15130 }
class ____(BaseDeclaration): """Base class for attributes based upon a sub-factory. Attributes: defaults (dict): Overrides to the defaults defined in the wrapped factory factory (base.Factory): the wrapped factory """ # Whether to align the attribute's sequence counter to t...
SubFactory
python
numba__numba
numba/core/typing/builtins.py
{ "start": 12668, "end": 13035 }
class ____(ConcreteTemplate): cases = [signature(types.boolean, types.boolean, types.boolean)] cases += [signature(types.boolean, op, op) for op in sorted(types.signed_domain)] cases += [signature(types.boolean, op, op) for op in sorted(types.unsigned_domain)] cases += [signature(types.boolean, op, op) ...
OrderedCmpOp
python
pydata__xarray
xarray/tests/test_units.py
{ "start": 10336, "end": 46678 }
class ____: """wrapper class for numpy functions Same as method, but the name is used for referencing numpy functions """ def __init__(self, name_or_function, *args, function_label=None, **kwargs): if callable(name_or_function): self.name = ( function_label ...
function
python
joke2k__faker
tests/providers/test_automotive.py
{ "start": 8725, "end": 8888 }
class ____(_SimpleAutomotiveTestMixin): """Test no_NO automotive provider methods""" license_plate_pattern: Pattern = re.compile(r"[A-Z]{2} \d{5}")
TestNoNo
python
chardet__chardet
chardet/enums.py
{ "start": 1028, "end": 1370 }
class ____: """ This enum represents the likelihood of a character following the previous one. """ NEGATIVE = 0 UNLIKELY = 1 LIKELY = 2 POSITIVE = 3 @classmethod def get_num_categories(cls) -> int: """:returns: The number of likelihood categories in the enum.""" ret...
SequenceLikelihood
python
pytorch__pytorch
torch/multiprocessing/queue.py
{ "start": 136, "end": 769 }
class ____: """Proxy class for _multiprocessing.Connection which uses ForkingPickler for object serialization.""" def __init__(self, conn): self.conn = conn def send(self, obj): buf = io.BytesIO() ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(obj) self.send_bytes(buf.ge...
ConnectionWrapper
python
apache__airflow
providers/fab/src/airflow/providers/fab/auth_manager/models/__init__.py
{ "start": 4784, "end": 5410 }
class ____(Model): """Represents a user role to which permissions can be assigned.""" __tablename__ = "ab_role" id: Mapped[int] = mapped_column( Integer, Sequence("ab_role_id_seq", start=1, increment=1, minvalue=1, cycle=False), primary_key=True, ) name: Mapped[str] = mappe...
Role
python
networkx__networkx
networkx/tests/test_convert.py
{ "start": 320, "end": 12731 }
class ____: def edgelists_equal(self, e1, e2): return sorted(sorted(e) for e in e1) == sorted(sorted(e) for e in e2) def test_simple_graphs(self): for dest, source in [ (to_dict_of_dicts, from_dict_of_dicts), (to_dict_of_lists, from_dict_of_lists), ]: ...
TestConvert
python
pydantic__pydantic
pydantic-core/tests/serializers/test_any.py
{ "start": 14931, "end": 16152 }
class ____: def __init__(self, v): self.v = v def __repr__(self): return f'<FoobarCount {self.v} repr>' @pytest.mark.skipif( platform.python_implementation() == 'PyPy' and pydantic_core._pydantic_core.build_profile == 'debug', reason='PyPy does not have enough stack space for Rust deb...
FoobarCount
python
pydata__xarray
xarray/tests/test_datatree.py
{ "start": 3448, "end": 4354 }
class ____: def test_child_gets_named_on_attach(self) -> None: sue = DataTree() mary = DataTree(children={"Sue": sue}) assert mary.children["Sue"].name == "Sue" def test_dataset_containing_slashes(self) -> None: xda: xr.DataArray = xr.DataArray( [[1, 2]], ...
TestNames
python
huggingface__transformers
tests/models/layoutxlm/test_processing_layoutxlm.py
{ "start": 1184, "end": 5326 }
class ____(ProcessorTesterMixin, unittest.TestCase): processor_class = LayoutXLMProcessor @classmethod def _setup_image_processor(cls): # hardcode as we can't use IMAGE_PROCESSOR_MAPPING to get the class from the config (layoutxlm is not in the mapping) image_processor_class = LayoutLMv2Ima...
LayoutXLMProcessorTest
python
pytest-dev__pytest
src/_pytest/capture.py
{ "start": 28893, "end": 36829 }
class ____(Generic[AnyStr]): """Object returned by the :fixture:`capsys`, :fixture:`capsysbinary`, :fixture:`capfd` and :fixture:`capfdbinary` fixtures.""" def __init__( self, captureclass: type[CaptureBase[AnyStr]], request: SubRequest, *, config: dict[str, Any] | N...
CaptureFixture
python
google__pytype
pytype/overlays/sys_overlay.py
{ "start": 473, "end": 1219 }
class ____(abstract.Tuple): ATTRIBUTES = ("major", "minor", "micro", "releaselevel", "serial") def get_special_attribute(self, node, name, valself): try: index = self.ATTRIBUTES.index(name) except ValueError: return None return self.pyval[index] def build_platform(ctx): return ctx.conv...
VersionInfo
python
sphinx-doc__sphinx
sphinx/domains/c/_ast.py
{ "start": 8998, "end": 10079 }
class ____(ASTLiteral): def __init__(self, prefix: str, data: str) -> None: self.prefix = prefix # may be None when no prefix self.data = data decoded = data.encode().decode('unicode-escape') if len(decoded) == 1: self.value = ord(decoded) else: raise...
ASTCharLiteral
python
pypa__pip
src/pip/_vendor/rich/console.py
{ "start": 10854, "end": 12149 }
class ____: """A context manager that 'pages' content. See :meth:`~rich.console.Console.pager` for usage.""" def __init__( self, console: "Console", pager: Optional[Pager] = None, styles: bool = False, links: bool = False, ) -> None: self._console = console ...
PagerContext
python
psf__requests
tests/test_help.py
{ "start": 214, "end": 839 }
class ____: def __init__(self, version): self.__version__ = version def test_idna_without_version_attribute(): """Older versions of IDNA don't provide a __version__ attribute, verify that if we have such a package, we don't blow up. """ with mock.patch("requests.help.idna", new=None): ...
VersionedPackage
python
pytorch__pytorch
torch/_dynamo/variables/higher_order_ops.py
{ "start": 132529, "end": 133189 }
class ____(TorchHigherOrderOperatorVariable): def _call_function( self, tx, args: "list[VariableTracker]", kwargs: "dict[str, VariableTracker]" ) -> "VariableTracker": from .builder import wrap_fx_proxy p_args = tuple(arg.as_proxy() for arg in args) p_kwargs = {key: arg.as_proxy...
AutoFunctionalizeHigherOrderVariable
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/random/random_ops_test.py
{ "start": 15773, "end": 17383 }
class ____(test.TestCase): @test_util.run_deprecated_v1 def testTruncatedNormal(self): # Fully known shape. rnd1 = random_ops.truncated_normal([1, 2, 3]) self.assertEqual([1, 2, 3], rnd1.get_shape()) # Partially known shape. rnd2 = random_ops.truncated_normal( array_ops.placeholder(dtyp...
RandomShapeTest
python
gevent__gevent
src/gevent/tests/test__select.py
{ "start": 1486, "end": 3067 }
class ____(gevent.testing.timing.AbstractGenericWaitTestCase): def wait(self, timeout): # On darwin, the read pipe is reported as writable # immediately, for some reason. So we carefully register # it only for read events (the default is read and write) r, w = os.pipe() try: ...
TestPollRead
python
PyCQA__pylint
tests/functional/t/too/too_many_arguments.py
{ "start": 282, "end": 1020 }
class ____: text = "MyText" def mymethod1(self): return self.text def mymethod2(self): return self.mymethod1.__get__(self, MyClass) MyClass().mymethod2()() # Check a false positive does not occur from functools import partial def root_function(first, second, third): return first ...
MyClass
python
falconry__falcon
tests/test_before_hooks.py
{ "start": 11398, "end": 12740 }
class ____: def __init__(self): self._items = {} self._sequence = 0 @falcon.before(_another_fish.hook) def on_delete(self, req, resp, fish, itemid): del self._items[itemid] resp.set_header('X-Fish-Trait', fish) resp.status = falcon.HTTP_NO_CONTENT @falcon.before...
PiggybackingCollection
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 773761, "end": 774150 }
class ____( sgqlc.types.Type, Node, Comment, Deletable, Minimizable, Updatable, UpdatableComment ): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("database_id", "gist") database_id = sgqlc.types.Field(Int, graphql_name="databaseId") gist = sgqlc.t...
GistComment
python
django__django
django/contrib/postgres/aggregates/statistics.py
{ "start": 622, "end": 673 }
class ____(StatAggregate): function = "CORR"
Corr
python
tensorflow__tensorflow
tensorflow/python/ops/linalg/linear_operator_kronecker.py
{ "start": 2501, "end": 20505 }
class ____(linear_operator.LinearOperator): """Kronecker product between two `LinearOperators`. This operator composes one or more linear operators `[op1,...,opJ]`, building a new `LinearOperator` representing the Kronecker product: `op1 x op2 x .. opJ` (we omit parentheses as the Kronecker product is associ...
LinearOperatorKronecker
python
ethereum__web3.py
ens/exceptions.py
{ "start": 1745, "end": 1865 }
class ____(ENSException): """ Raised if you supply incorrect data to generate the bid hash. """
InvalidBidHash
python
scrapy__scrapy
tests/test_feedexport.py
{ "start": 7880, "end": 8004 }
class ____(BlockingFeedStorage): def _store_in_thread(self, file: IO[bytes]) -> None: return
MyBlockingFeedStorage
python
python-attrs__attrs
src/attr/_make.py
{ "start": 87612, "end": 92849 }
class ____: """ Effective class properties as derived from parameters to `attr.s()` or `define()` decorators. This is the same data structure that *attrs* uses internally to decide how to construct the final class. Warning: This feature is currently **experimental** and is not covered...
ClassProps
python
ray-project__ray
release/ray_release/result.py
{ "start": 161, "end": 512 }
class ____(enum.Enum): """ Overall status of the result test run """ SUCCESS = "success" UNKNOWN = "unknown" RUNTIME_ERROR = "runtime_error" TRANSIENT_INFRA_ERROR = "transient_infra_error" INFRA_ERROR = "infra_error" INFRA_TIMEOUT = "infra_timeout" ERROR = "error" TIMEOUT = ...
ResultStatus
python
matplotlib__matplotlib
lib/matplotlib/axes/__init__.py
{ "start": 76, "end": 250 }
class ____(type): def __instancecheck__(self, obj): return (isinstance(obj, _base._AxesBase) and obj.get_subplotspec() is not None)
_SubplotBaseMeta
python
readthedocs__readthedocs.org
readthedocs/storage/rclone.py
{ "start": 3696, "end": 4127 }
class ____(BaseRClone): """ RClone remote implementation for the local file system. Used for local testing only. See https://rclone.org/local/. :param location: Root directory where the files will be stored. """ remote_type = "local" def __init__(self, location): self.locati...
RCloneLocal
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0093_migrate_null_fields.py
{ "start": 504, "end": 717 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0092_add_new_fields"), ] operations = [ migrations.RunPython(forwards_func), ]
Migration
python
google__pytype
pytype/tests/test_typing_self.py
{ "start": 12958, "end": 18578 }
class ____(test_base.BaseTest): """Tests for outputting typing.Self to a stub and reading the stub back in.""" def test_output(self): ty = self.Infer(""" from typing_extensions import Self class A: def f(self) -> Self: return self """) # We do a string comparison because t...
SelfReingestTest
python
walkccc__LeetCode
solutions/1682. Longest Palindromic Subsequence II/1682.py
{ "start": 0, "end": 491 }
class ____: def longestPalindromeSubseq(self, s: str) -> int: n = len(s) @functools.lru_cache(None) def dp(i: int, j: int, k: int) -> int: """ Returns the length of LPS(s[i..j]), where the previous letter is ('a' + k). """ if i >= j: return 0 if s[i] == s[j] an...
Solution
python
kamyu104__LeetCode-Solutions
Python/frog-jump-ii.py
{ "start": 38, "end": 287 }
class ____(object): def maxJump(self, stones): """ :type stones: List[int] :rtype: int """ return stones[1]-stones[0] if len(stones) == 2 else max(stones[i+2]-stones[i] for i in xrange(len(stones)-2))
Solution