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 | django__django | django/contrib/gis/db/models/functions.py | {
"start": 12311,
"end": 13036
} | class ____(GeoFunc):
arity = 2
geom_param_pos = ()
def __init__(self, expression, srid=0, **extra):
expressions = [
expression,
self._handle_param(srid, "srid", int),
]
if "output_field" not in extra:
extra["output_field"] = GeometryField(srid=sri... | FromWKB |
python | getsentry__sentry | tests/sentry/integrations/slack/notifications/test_resolved_in_pull_request.py | {
"start": 540,
"end": 5761
} | class ____(
SlackActivityNotificationTest, PerformanceIssueTestCase
):
def setUp(self) -> None:
super().setUp()
self.pull_request_url = "https://github.com/example/pull/123"
def create_notification(self, group):
return ResolvedInPullRequestActivityNotification(
Activity(... | SlackResolvedInPullRequestNotificationTest |
python | google__jax | jax/experimental/jax2tf/tests/flax_models/transformer_wmt.py | {
"start": 1126,
"end": 3089
} | class ____:
"""Global hyperparameters used to minimize obnoxious kwarg plumbing."""
vocab_size: int
output_vocab_size: int
share_embeddings: bool = False
logits_via_embedding: bool = False
dtype: Any = jnp.float32
emb_dim: int = 512
num_heads: int = 8
num_layers: int = 6
qkv_dim: int = 512
mlp_dim... | TransformerConfig |
python | getsentry__sentry | src/sentry/monitors/serializers.py | {
"start": 4935,
"end": 5042
} | class ____(TypedDict):
targetIdentifier: int
targetType: str
| MonitorAlertRuleTargetSerializerResponse |
python | coleifer__peewee | tests/reflection.py | {
"start": 22732,
"end": 23431
} | class ____(ModelTestCase):
requires = [Category, Event]
def test_generate_models(self):
M = generate_models(self.database)
self.assertTrue('category' in M)
self.assertTrue('event' in M)
def assertFields(m, expected):
actual = [(f.name, f.field_type) for f in m._meta... | TestInteractiveHelpers |
python | PrefectHQ__prefect | src/prefect/client/schemas/filters.py | {
"start": 32431,
"end": 33229
} | class ____(PrefectBaseModel):
"""Filter by `ArtifactCollection.key`."""
any_: Optional[List[str]] = Field(
default=None, description="A list of artifact keys to include"
)
like_: Optional[str] = Field(
default=None,
description=(
"A string to match artifact keys aga... | ArtifactCollectionFilterKey |
python | huggingface__transformers | tests/models/switch_transformers/test_modeling_switch_transformers.py | {
"start": 21387,
"end": 28718
} | class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(SwitchTransformersModel, SwitchTransformersForConditionalGeneration) if is_torch_available() else ()
)
pipeline_model_mapping = (
{
"feature-extraction": SwitchTran... | SwitchTransformersModelTest |
python | pytorch__pytorch | test/test_fx.py | {
"start": 3031,
"end": 4585
} | class ____(torch.nn.Module):
def forward(self, x):
return torch.relu(x + 3.0)
def a_non_torch_leaf(a, b):
return a + b
# Used for test_autowrap_function. Autowrapped functions need to be global
def fx_int(x: float) -> int:
return int(x)
def fx_int_x2(x: float) -> int:
return int(x) * 2
#... | SimpleTest |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/agave/tests.py | {
"start": 238,
"end": 981
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = AgaveProvider.id
def get_mocked_response(self):
return MockedResponse(
HTTPStatus.OK,
"""
{
"status": "success",
"message": "User details retrieved successfully.",
"version": "2.0.0-SNAPSHOT-rc... | AgaveTests |
python | spyder-ide__spyder | external-deps/spyder-kernels/spyder_kernels/console/kernelapp.py | {
"start": 1413,
"end": 2363
} | class ____(IPKernelApp):
outstream_class = DottedObjectName(
'spyder_kernels.console.outstream.TTYOutStream'
)
kernel_class = SpyderKernel
def init_pdb(self):
"""
This method was added in IPykernel 5.3.1 and it replaces
the debugger used by the kernel with a new class
... | SpyderKernelApp |
python | getsentry__sentry | src/sentry/web/frontend/debug/debug_unassigned_email.py | {
"start": 217,
"end": 412
} | class ____(ActivityMailDebugView):
def get_activity(self, request: HttpRequest, event):
return {"type": ActivityType.UNASSIGNED.value, "user_id": request.user.id}
| DebugUnassignedEmailView |
python | pypa__warehouse | tests/unit/email/test_init.py | {
"start": 51922,
"end": 56855
} | class ____:
def test_primary_email_change_email(
self, pyramid_request, pyramid_config, monkeypatch
):
stub_user = pretend.stub(
id="id", email="new_email@example.com", username="username", name=""
)
subject_renderer = pyramid_config.testing_add_renderer(
... | TestPrimaryEmailChangeEmail |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_resolver.py | {
"start": 26357,
"end": 26489
} | class ____(ResolverAltSetUp, ResolverDomainTests):
pass
@override_settings(PUBLIC_DOMAIN="readthedocs.org")
| ResolverDomainTestsAlt |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-duckdb/llama_index/vector_stores/duckdb/base.py | {
"start": 2104,
"end": 22660
} | class ____(BasePydanticVectorStore):
"""
DuckDB vector store.
In this vector store, embeddings are stored within a DuckDB database.
During query time, the index uses DuckDB to query for the top
k most similar nodes.
Examples:
`pip install llama-index-vector-stores-duckdb`
```... | DuckDBVectorStore |
python | pennersr__django-allauth | allauth/socialaccount/providers/openid/provider.py | {
"start": 720,
"end": 2966
} | class ____(Provider):
id = "openid"
name = "OpenID"
account_class = OpenIDAccount
uses_apps = False
def get_login_url(self, request, **kwargs):
url = reverse("openid_login")
if kwargs:
url += "?" + urlencode(kwargs)
return url
def get_brands(self):
d... | OpenIDProvider |
python | getsentry__sentry | src/sentry/analytics/events/first_event_sent.py | {
"start": 445,
"end": 671
} | class ____(FirstEventSentEvent):
sdk_name: str | None = None
# first error with minified stack trace for a project
@analytics.eventclass("first_event_with_minified_stack_trace_for_project.sent")
| FirstEventSentForProjectEvent |
python | allegroai__clearml | clearml/backend_api/services/v2_23/queues.py | {
"start": 75943,
"end": 77250
} | class ____(Response):
"""
Response of queues.move_task_backward endpoint.
:param position: The new position of the task entry in the queue (index, -1
represents bottom of queue)
:type position: int
"""
_service = "queues"
_action = "move_task_backward"
_version = "2.23"
_sc... | MoveTaskBackwardResponse |
python | chroma-core__chroma | chromadb/utils/embedding_functions/open_clip_embedding_function.py | {
"start": 395,
"end": 6070
} | class ____(EmbeddingFunction[Embeddable]):
"""
This class is used to generate embeddings for a list of texts or images using the Open CLIP model.
"""
def __init__(
self,
model_name: str = "ViT-B-32",
checkpoint: str = "laion2b_s34b_b79k",
device: Optional[str] = "cpu",
... | OpenCLIPEmbeddingFunction |
python | tensorflow__tensorflow | tensorflow/python/tpu/tests/tpu_embedding_v2_mp_strategy_test.py | {
"start": 1683,
"end": 6957
} | class ____(
tpu_embedding_base_test.TPUEmbeddingBaseTest
):
def setUp(self):
super().setUp()
self._num_replicas = 1
self._num_cores_per_replica = 2
def _get_strategy(self) -> tpu_strategy.TPUStrategy:
topology = self._init_tpu_system()
d_assign = device_lib.device_assignment(
top... | TPUEmbeddingTPUStrategyV2Test |
python | spack__spack | lib/spack/spack/vendor/attr/exceptions.py | {
"start": 661,
"end": 834
} | class ____(ValueError):
"""
An ``attrs`` function couldn't find an attribute that the user asked for.
.. versionadded:: 16.2.0
"""
| AttrsAttributeNotFoundError |
python | kamyu104__LeetCode-Solutions | Python/next-greater-node-in-linked-list.py | {
"start": 165,
"end": 579
} | class ____(object):
def nextLargerNodes(self, head):
"""
:type head: ListNode
:rtype: List[int]
"""
result, stk = [], []
while head:
while stk and stk[-1][1] < head.val:
result[stk.pop()[0]] = head.val
stk.append([len(result), h... | Solution |
python | pydantic__pydantic | pydantic/types.py | {
"start": 35822,
"end": 36082
} | class ____(BaseModel):
uuid4: UUID4
Model(uuid4=uuid.uuid4())
```
"""
UUID5 = Annotated[UUID, UuidVersion(5)]
"""A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 5.
```python
import uuid
from pydantic import UUID5, BaseModel
| Model |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_permissions.py | {
"start": 2323,
"end": 2501
} | class ____:
@check_permission(Permissions.LAUNCH_PIPELINE_REEXECUTION)
def mutate(self, graphene_info: ResolveInfo, **_kwargs):
pass
| FakeOtherEnumPermissionMutation |
python | ray-project__ray | python/ray/dag/tests/experimental/test_execution_schedule.py | {
"start": 2733,
"end": 16147
} | class ____:
"""
Test whether `_select_next_nodes` function selects the next nodes for
topological sort to generate execution schedule correctly.
task_idx: Each DAG node has a unique global index.
exec_task_idx: The DAG node's index in the actor's `executable_tasks` list.
"""
def test_two_c... | TestSelectNextNodes |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_unary_operand_type.py | {
"start": 1595,
"end": 1765
} | class ____:
def __init__(self):
"""https://github.com/pylint-dev/pylint/issues/8554"""
if not isinstance(super(), float):
pass
| NoArgumentSuper |
python | ansible__ansible | lib/ansible/parsing/vault/__init__.py | {
"start": 44911,
"end": 50844
} | class ____:
"""
Vault implementation using AES-CTR with an HMAC-SHA256 authentication code.
Keys are derived using PBKDF2
"""
# http://www.daemonology.net/blog/2009-06-11-cryptographic-right-answers.html
# Note: strings in this class should be byte strings by default.
def __init__(self):... | VaultAES256 |
python | huggingface__transformers | src/transformers/models/camembert/modeling_camembert.py | {
"start": 22243,
"end": 23653
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.layer = nn.ModuleList([CamembertLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: O... | CamembertEncoder |
python | django__django | tests/test_utils/test_testcase.py | {
"start": 5796,
"end": 6413
} | class ____(TestCase):
"""
In-memory data isolation is respected for model instances assigned to class
attributes during setUpTestData.
"""
@classmethod
def setUpTestData(cls):
cls.car = Car.objects.create(name="Volkswagen Beetle")
def test_book_name_deutsh(self):
self.asser... | SetupTestDataIsolationTests |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDict9.py | {
"start": 148,
"end": 197
} | class ____(TypedDict):
inner_key: Inner1
| Inner2 |
python | google__pytype | pytype/tests/test_builtins3.py | {
"start": 254,
"end": 10535
} | class ____(test_base.BaseTest):
"""Tests for builtin methods and classes."""
def test_super_attribute(self):
ty = self.Infer("""
x = super.__name__
""")
self.assertTypesMatchPytd(
ty,
"""
x = ... # type: str
""",
)
def test_slice(self):
ty = self.Infer("""
... | BuiltinTests3 |
python | python-jsonschema__jsonschema | jsonschema/cli.py | {
"start": 670,
"end": 723
} | class ____(Exception):
pass
@define
| _CannotLoadFile |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_overrides.py | {
"start": 6923,
"end": 13445
} | class ____:
"""Test the ToolCallRequest.override() method."""
def test_override_tool_call(self) -> None:
"""Test overriding tool_call dict."""
from langchain_core.tools import tool
@tool
def test_tool(x: int) -> str:
"""A test tool."""
return f"Result: {... | TestToolCallRequestOverride |
python | wandb__wandb | wandb/sdk/data_types/saved_model.py | {
"start": 1824,
"end": 10981
} | class ____(WBValue, Generic[SavedModelObjType]):
"""Internal W&B Artifact model storage.
_model_type_id: (str) The id of the SavedModel subclass used to serialize the model.
"""
_log_type: ClassVar[str]
_path_extension: ClassVar[str]
_model_obj: SavedModelObjType | None
_path: str | None
... | _SavedModel |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/tuple7.py | {
"start": 651,
"end": 1071
} | class ____(tuple[_T, ...]):
def __new__(cls) -> Self: ...
objB = ClassB[complex]()
(x, y, z) = objB
reveal_type(x, expected_text="complex")
reveal_type(y, expected_text="complex")
reveal_type(z, expected_text="complex")
xx2: complex = objB[0]
yy2: complex = objB[1]
zz2: complex = objB[2]
def func1(lst: list[... | ClassB |
python | huggingface__transformers | tests/models/lxmert/test_modeling_lxmert.py | {
"start": 28346,
"end": 29441
} | class ____(unittest.TestCase):
@slow
def test_inference_no_head_absolute_embedding(self):
model = LxmertModel.from_pretrained("unc-nlp/lxmert-base-uncased")
input_ids = torch.tensor([[101, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 102]])
num_visual_features = 10
_, visual_fe... | LxmertModelIntegrationTest |
python | numba__numba | numba/core/types/containers.py | {
"start": 16230,
"end": 16547
} | class ____(Type):
"""
Internal type class for the entries of a Set's hash table.
"""
def __init__(self, set_type):
self.set_type = set_type
name = "entry(%s)" % set_type
super(SetEntry, self).__init__(name)
@property
def key(self):
return self.set_type
| SetEntry |
python | agronholm__apscheduler | src/apscheduler/triggers/combining.py | {
"start": 4353,
"end": 5726
} | class ____(BaseCombiningTrigger):
"""
Fires on every fire time of every trigger in chronological order.
If two or more triggers produce the same fire time, it will only be used once.
This trigger will be finished when none of the enclosed triggers can produce any new
fire times.
:param trigger... | OrTrigger |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pie/PIE794.py | {
"start": 407,
"end": 561
} | class ____(BaseModel):
@property
def buzz(self) -> str:
...
@buzz.setter
def buzz(self, value: str | int) -> None:
...
| User |
python | google__python-fire | fire/test_components.py | {
"start": 4714,
"end": 4889
} | class ____:
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
def run(self, arg1, arg2):
return (self.arg1, self.arg2, arg1, arg2)
| InstanceVars |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/known_directives.py | {
"start": 146,
"end": 3434
} | class ____(ValidationRule):
def enter_Directive(self, node, key, parent, path, ancestors):
directive_def = next((
definition for definition in self.context.get_schema().get_directives()
if definition.name == node.name.value
), None)
if not directive_def:
... | KnownDirectives |
python | pytorch__pytorch | torch/ao/quantization/utils.py | {
"start": 1728,
"end": 30101
} | class ____:
"""A node pattern that matches all nodes, used in defining
fusion patterns in FX Graph Mode Quantization
"""
module_type_list = {
torch.nn.ReLU,
torch.nn.ReLU6,
torch.nn.AdaptiveAvgPool1d,
torch.nn.AdaptiveAvgPool2d,
torch.nn.AdaptiveAvgPool3d,
torch.nn.AvgPool1d,
t... | MatchAllNode |
python | getsentry__sentry | src/sentry/integrations/msteams/card_builder/issues.py | {
"start": 1509,
"end": 10506
} | class ____(MSTeamsMessageBuilder):
def __init__(
self,
group: Group,
event: Event | GroupEvent,
rules: Sequence[Rule],
integration: RpcIntegration,
):
self.group = group
self.event = event
self.rules = rules
self.integration = integration
... | MSTeamsIssueMessageBuilder |
python | django__django | tests/model_fields/test_jsonfield.py | {
"start": 6066,
"end": 7840
} | class ____(SimpleTestCase):
test_data = (
'[{"fields": {"value": %s}, "model": "model_fields.jsonmodel", "pk": null}]'
)
test_values = (
# (Python value, serialized value),
({"a": "b", "c": None}, '{"a": "b", "c": null}'),
("abc", '"abc"'),
('{"a": "a"}', '"{\\"a\\": ... | TestSerialization |
python | graphql-python__graphene | graphene/types/tests/test_generic.py | {
"start": 102,
"end": 2226
} | class ____(ObjectType):
generic = GenericScalar(input=GenericScalar())
def resolve_generic(self, info, input=None):
return input
schema = Schema(query=Query)
def test_generic_query_variable():
for generic_value in [
1,
1.1,
True,
"str",
[1, 2, 3],
... | Query |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-github/llama_index/readers/github/repository/utils.py | {
"start": 2244,
"end": 6166
} | class ____(BufferedAsyncIterator):
"""
Buffered async iterator for Git blobs.
This class is an async iterator that buffers the results of the get_blob operation.
It is used to retrieve the contents of the files in a Github repository.
getBlob endpoint supports up to 100 megabytes of content for blo... | BufferedGitBlobDataIterator |
python | getsentry__sentry | src/sentry/api/endpoints/project_filters.py | {
"start": 658,
"end": 797
} | class ____(TypedDict):
id: str
active: bool | list[str]
@region_silo_endpoint
@extend_schema(tags=["Projects"])
| ProjectFilterResponse |
python | jazzband__django-pipeline | tests/tests/test_storage.py | {
"start": 490,
"end": 896
} | class ____(PipelineStorage):
"""Storage without an implemented path method"""
def path(self, *args):
raise NotImplementedError()
def delete(self, *args):
return
def exists(self, *args):
return True
def save(self, *args):
return
def open(self, *args):
... | PipelineNoPathStorage |
python | networkx__networkx | networkx/algorithms/tests/test_distance_regular.py | {
"start": 441,
"end": 2264
} | class ____:
def test_is_distance_regular(self):
assert nx.is_distance_regular(nx.icosahedral_graph())
assert nx.is_distance_regular(nx.petersen_graph())
assert nx.is_distance_regular(nx.cubical_graph())
assert nx.is_distance_regular(nx.complete_bipartite_graph(3, 3))
assert n... | TestDistanceRegular |
python | plotly__plotly.py | plotly/graph_objs/choroplethmapbox/_legendgrouptitle.py | {
"start": 233,
"end": 3003
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "choroplethmapbox"
_path_str = "choroplethmapbox.legendgrouptitle"
_valid_props = {"font", "text"}
@property
def font(self):
"""
Sets this legend group's title font.
The 'font' property is an instance of Font
t... | Legendgrouptitle |
python | matplotlib__matplotlib | lib/matplotlib/tests/test_datetime.py | {
"start": 110,
"end": 32647
} | class ____:
@mpl.style.context("default")
def test_annotate(self):
mpl.rcParams["date.converter"] = 'concise'
fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, layout="constrained")
start_date = datetime.datetime(2023, 10, 1)
dates = [start_date + datetime.timedelta(days=i) for i i... | TestDatetimePlotting |
python | huggingface__transformers | src/transformers/models/fastspeech2_conformer/modeling_fastspeech2_conformer.py | {
"start": 59650,
"end": 64537
} | class ____(PreTrainedModel):
config: FastSpeech2ConformerHifiGanConfig
main_input_name = "spectrogram"
def __init__(self, config: FastSpeech2ConformerHifiGanConfig):
super().__init__(config)
self.num_kernels = len(config.resblock_kernel_sizes)
self.num_upsamples = len(config.upsampl... | FastSpeech2ConformerHifiGan |
python | ray-project__ray | python/ray/serve/tests/test_model_composition.py | {
"start": 5504,
"end": 5677
} | class ____:
def __init__(self, child):
self._child = child
async def __call__(self, *args):
return await self._child.remote()
@serve.deployment
| Parent |
python | keon__algorithms | algorithms/graph/strongly_connected_components_kosaraju.py | {
"start": 145,
"end": 1909
} | class ____:
"""
Kosaraju's algorithm use depth first search approach to find strongly connected components in a directed graph.
Approach:
1. Make a DFS call to keep track of finish time of each vertex.
2. Tranpose the original graph. ie 1->2 transpose is 1<-2
3. Make another DFS call... | Kosaraju |
python | wandb__wandb | wandb/sdk/internal/_generated/server_features_query.py | {
"start": 335,
"end": 453
} | class ____(GQLResult):
features: List[Optional[ServerFeaturesQueryServerInfoFeatures]]
| ServerFeaturesQueryServerInfo |
python | huggingface__transformers | src/transformers/models/qwen2_vl/modeling_qwen2_vl.py | {
"start": 20750,
"end": 25183
} | class ____(nn.Module):
"""
Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
and "Generating Long Sequences with Sparse Transformers".
"""
def __init__(self, config: Qwen2VLTextConfig, layer_idx: Optional[int] = None):
super(... | Qwen2VLAttention |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/hooks/lambda_function.py | {
"start": 1112,
"end": 9520
} | class ____(AwsBaseHook):
"""
Interact with AWS Lambda.
Provide thin wrapper around :external+boto3:py:class:`boto3.client("lambda") <Lambda.Client>`.
Additional arguments (such as ``aws_conn_id``) may be specified and
are passed down to the underlying AwsBaseHook.
.. seealso::
- :clas... | LambdaHook |
python | milvus-io__pymilvus | pymilvus/orm/iterator.py | {
"start": 15492,
"end": 17074
} | class ____(LoopBase):
"""Since we only support nq=1 in search iteration, so search iteration response
should be different from raw response of search operation"""
def __init__(self, res: Hits, session_ts: Optional[int] = 0):
super().__init__()
self._session_ts = session_ts
self._res... | SearchPage |
python | huggingface__transformers | tests/models/speecht5/test_tokenization_speecht5.py | {
"start": 1108,
"end": 17614
} | class ____(TokenizerTesterMixin, unittest.TestCase):
from_pretrained_id = "microsoft/speecht5_asr"
tokenizer_class = SpeechT5Tokenizer
test_rust_tokenizer = False
test_sentencepiece = True
@classmethod
def setUpClass(cls):
super().setUpClass()
# We have a SentencePiece fixture ... | SpeechT5TokenizerTest |
python | pennersr__django-allauth | allauth/headless/account/views.py | {
"start": 12525,
"end": 13156
} | class ____(AuthenticatedAPIView):
input_class = ChangePasswordInput
def post(self, request, *args, **kwargs):
password_change.change_password(
self.request.user, self.input.cleaned_data["new_password"]
)
is_set = not self.input.cleaned_data.get("current_password")
if... | ChangePasswordView |
python | Netflix__metaflow | test/core/metaflow_extensions/test_org/exceptions/mfextinit_test_org.py | {
"start": 51,
"end": 263
} | class ____(MetaflowException):
headline = "Subservice error"
def __init__(self, error):
msg = "Test error: '%s'" % error
super(MetaflowTestException, self).__init__(msg)
| MetaflowTestException |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/nocover/test_type_lookup_future_annotations.py | {
"start": 704,
"end": 1203
} | class ____(TypedDict):
a: A
b: alias
@given(st.from_type(B))
def test_complex_forward_ref_in_typed_dict(d):
assert isinstance(d["a"], dict)
assert isinstance(d["a"]["a"], int)
assert isinstance(d["b"], (int, str))
def test_complex_forward_ref_in_typed_dict_local():
local_alias = int | str
... | B |
python | MongoEngine__mongoengine | benchmarks/test_save_with_indexes.py | {
"start": 358,
"end": 463
} | class ____(Document):
name = StringField()
age = IntField()
meta = {"indexes": [["name"]]}
| User1 |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_internal/commands/show.py | {
"start": 1524,
"end": 7507
} | class ____(NamedTuple):
name: str
version: str
location: str
editable_project_location: Optional[str]
requires: List[str]
required_by: List[str]
installer: str
metadata_version: str
classifiers: List[str]
summary: str
homepage: str
project_urls: List[str]
author: str
... | _PackageInfo |
python | getsentry__sentry | tests/sentry/rules/history/endpoints/test_project_rule_group_history.py | {
"start": 532,
"end": 1069
} | class ____(TestCase):
def test(self) -> None:
current_date = datetime.now()
group_history = RuleGroupHistory(self.group, 50, current_date)
result = serialize([group_history], self.user, RuleGroupHistorySerializer())
assert result == [
{
"group": serialize(... | RuleGroupHistorySerializerTest |
python | plotly__plotly.py | plotly/graph_objs/layout/coloraxis/colorbar/title/_font.py | {
"start": 235,
"end": 9962
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.coloraxis.colorbar.title"
_path_str = "layout.coloraxis.colorbar.title.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
... | Font |
python | pola-rs__polars | py-polars/src/polars/_utils/async_.py | {
"start": 383,
"end": 2313
} | class ____(Generic[T]):
__slots__ = ("_result", "_value", "_watcher")
def __init__(self) -> None:
if not _GEVENT_AVAILABLE:
msg = (
"gevent is required for using LazyFrame.collect_async(gevent=True) or"
"polars.collect_all_async(gevent=True)"
)
... | _GeventDataFrameResult |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/model_query.py | {
"start": 749,
"end": 886
} | class ____(Child):
def baz(self, z):
return 0
@lru_cache(maxsize=1)
def positional_decorated(x, y) -> int:
...
| GrandChild |
python | django__django | tests/backends/models.py | {
"start": 3089,
"end": 3356
} | class ____(models.Model):
related_objects = models.ManyToManyField(
"self", db_constraint=False, symmetrical=False
)
obj_ref = models.ForeignKey("ObjectReference", models.CASCADE, null=True)
def __str__(self):
return str(self.id)
| Object |
python | python-markdown__markdown | markdown/extensions/footnotes.py | {
"start": 14138,
"end": 16601
} | class ____(Treeprocessor):
""" Amend footnote div with duplicates. """
def __init__(self, footnotes: FootnoteExtension):
self.footnotes = footnotes
def add_duplicates(self, li: etree.Element, duplicates: int) -> None:
""" Adjust current `li` and add the duplicates: `fnref2`, `fnref3`, etc.... | FootnotePostTreeprocessor |
python | scipy__scipy | scipy/signal/tests/test_signaltools.py | {
"start": 155964,
"end": 174050
} | class ____:
@staticmethod
def assert_rp_almost_equal(r, p, r_true, p_true, decimal=7):
xp = array_namespace(r, p)
r_true = xp.asarray(r_true)
p_true = xp.asarray(p_true)
distance = xp.hypot(abs(p[:, None] - p_true),
abs(r[:, None] - r_true))
... | TestPartialFractionExpansion |
python | pytorch__pytorch | test/dynamo/test_fake_distributed.py | {
"start": 1776,
"end": 2482
} | class ____(torch.nn.Module):
def forward(self, primals_1: "Sym(s77)", primals_2: "Sym(s27)", primals_3: "f32[s77, s27]"):
floordiv: "Sym((s77//2))" = primals_1 // 2
all_to_all_single: "f32[2*((s77//2)), s27]" = torch.ops._c10d_functional.all_to_all_single.default(primals_3, [floordiv, floordiv], [f... | GraphModule |
python | django__django | django/contrib/gis/gdal/field.py | {
"start": 4735,
"end": 4770
} | class ____(Field):
pass
| OFTString |
python | ethereum__web3.py | web3/_utils/module_testing/web3_module.py | {
"start": 747,
"end": 18176
} | class ____:
def test_web3_client_version(self, w3: Web3) -> None:
client_version = w3.client_version
self._check_web3_client_version(client_version)
def _check_web3_client_version(self, client_version: str) -> NoReturn:
raise NotImplementedError("Must be implemented by subclasses")
... | Web3ModuleTest |
python | walkccc__LeetCode | solutions/3295. Report Spam Message/3295.py | {
"start": 0,
"end": 193
} | class ____:
def reportSpam(self, message: list[str], bannedWords: list[str]) -> bool:
bannedWordsSet = set(bannedWords)
return sum(word in bannedWordsSet for word in message) > 1
| Solution |
python | fastai__fastai | fastai/torch_core.py | {
"start": 23304,
"end": 23540
} | class ____:
"Base class that adds a simple `show`"
_show_args = {'label': 'text'}
def show(self, ctx=None, **kwargs):
"Show self"
return show_title(str(self), ctx=ctx, **merge(self._show_args, kwargs))
| ShowTitle |
python | joke2k__faker | faker/providers/date_time/id_ID/__init__.py | {
"start": 46,
"end": 861
} | class ____(DateTimeProvider):
def day_of_week(self) -> str:
day = self.date("%w")
DAY_NAMES = {
"0": "Senin",
"1": "Selasa",
"2": "Rabu",
"3": "Kamis",
"4": "Jumat",
"5": "Sabtu",
"6": "Minggu",
}
re... | Provider |
python | django__django | tests/gis_tests/gis_migrations/test_operations.py | {
"start": 15587,
"end": 16269
} | class ____(OperationTestCase):
def test_create_raster_model_on_db_without_raster_support(self):
msg = "Raster fields require backends with raster support."
with self.assertRaisesMessage(ImproperlyConfigured, msg):
self.set_up_test_model(force_raster_creation=True)
def test_add_raste... | NoRasterSupportTests |
python | pydantic__pydantic | tests/mypy/modules/plugin_fail_baseConfig.py | {
"start": 1578,
"end": 1651
} | class ____(Model):
class Config:
frozen = False
| InheritingModel |
python | sqlalchemy__sqlalchemy | test/orm/test_query.py | {
"start": 169498,
"end": 171045
} | class ____(QueryTest, AssertsCompiledSQL):
def test_one_prefix(self):
User = self.classes.User
sess = fixture_session()
query = sess.query(User.name).prefix_with("PREFIX_1")
expected = "SELECT PREFIX_1 users.name AS users_name FROM users"
self.assert_compile(query, expected, ... | PrefixSuffixWithTest |
python | viewflow__viewflow | viewflow/contrib/auth.py | {
"start": 1073,
"end": 1552
} | class ____(auth_forms.AuthenticationForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["username"].widget = forms.TextInput(
attrs={"autofocus": True, "leading-icon": "account_box"},
)
self.fields["password"].widget = forms.Password... | AuthenticationForm |
python | EpistasisLab__tpot | tpot/search_spaces/pipelines/tree.py | {
"start": 2303,
"end": 3339
} | class ____(SearchSpace):
def __init__(self, root_search_space : SearchSpace,
leaf_search_space : SearchSpace = None,
inner_search_space : SearchSpace =None,
min_size: int = 2,
max_size: int = 10,
... | TreePipeline |
python | encode__django-rest-framework | tests/test_fields.py | {
"start": 73874,
"end": 74227
} | class ____(FieldValues):
"""
Values for an valid `ImageField`.
"""
valid_inputs = [
(MockFile(name='example.png', size=10), MockFile(name='example.png', size=10))
]
invalid_inputs = {}
outputs = {}
field = serializers.ImageField(_DjangoImageField=PassImageValidation)
# Composit... | TestValidImageField |
python | zarr-developers__zarr-python | tests/test_dtype/test_npy/test_bytes.py | {
"start": 235,
"end": 1898
} | class ____(BaseTestZDType):
test_cls = NullTerminatedBytes
valid_dtype = (np.dtype("|S10"), np.dtype("|S4"))
invalid_dtype = (
np.dtype(np.int8),
np.dtype(np.float64),
np.dtype("|U10"),
)
valid_json_v2 = (
{"name": "|S1", "object_codec_id": None},
{"name": "|S... | TestNullTerminatedBytes |
python | has2k1__plotnine | plotnine/scales/scale_identity.py | {
"start": 1897,
"end": 2124
} | class ____(
MapTrainMixin, scale_continuous[Literal["legend"] | None]
):
"""
No size scaling
"""
_aesthetics = ["size"]
_: KW_ONLY
guide: Literal["legend"] | None = None
@dataclass
| scale_size_identity |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/sagemaker.py | {
"start": 9497,
"end": 18288
} | class ____(SageMakerBaseOperator):
"""
Use Amazon SageMaker Processing to analyze data and evaluate machine learning models on Amazon SageMaker.
With Processing, you can use a simplified, managed experience on SageMaker
to run your data processing workloads, such as feature engineering, data
valida... | SageMakerProcessingOperator |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_qtagg.py | {
"start": 333,
"end": 3343
} | class ____(FigureCanvasAgg, FigureCanvasQT):
def paintEvent(self, event):
"""
Copy the image from the Agg canvas to the qt.drawable.
In Qt, all drawing should be done inside of here when a widget is
shown onscreen.
"""
self._draw_idle() # Only does something if a d... | FigureCanvasQTAgg |
python | davidhalter__jedi | test/completion/django.py | {
"start": 452,
"end": 523
} | class ____(models.Model):
category_name = models.CharField()
| Category |
python | PyCQA__flake8 | src/flake8/plugins/finder.py | {
"start": 2351,
"end": 11129
} | class ____(NamedTuple):
"""Options related to plugin loading."""
local_plugin_paths: tuple[str, ...]
enable_extensions: frozenset[str]
require_plugins: frozenset[str]
@classmethod
def blank(cls) -> PluginOptions:
"""Make a blank PluginOptions, mostly used for tests."""
return c... | PluginOptions |
python | jazzband__django-oauth-toolkit | oauth2_provider/forms.py | {
"start": 27,
"end": 734
} | class ____(forms.Form):
allow = forms.BooleanField(required=False)
redirect_uri = forms.CharField(widget=forms.HiddenInput())
scope = forms.CharField(widget=forms.HiddenInput())
nonce = forms.CharField(required=False, widget=forms.HiddenInput())
client_id = forms.CharField(widget=forms.HiddenInput()... | AllowForm |
python | django__django | tests/introspection/models.py | {
"start": 831,
"end": 1458
} | class ____(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
body = models.TextField(default="")
reporter = models.ForeignKey(Reporter, models.CASCADE)
response_to = models.ForeignKey("self", models.SET_NULL, null=True)
unmanaged_reporters = models.ManyToMa... | Article |
python | ray-project__ray | python/ray/_private/worker.py | {
"start": 7823,
"end": 8732
} | class ____(HasOptions, Generic[R, T0, T1, T2, T3, T4, T5, T6]):
def __init__(self, function: Callable[[T0, T1, T2, T3, T4, T5, T6], R]) -> None:
pass
def remote(
self,
__arg0: "Union[T0, ObjectRef[T0]]",
__arg1: "Union[T1, ObjectRef[T1]]",
__arg2: "Union[T2, ObjectRef[T2... | RemoteFunction6 |
python | allegroai__clearml | clearml/backend_api/services/v2_9/workers.py | {
"start": 60187,
"end": 66576
} | class ____(Request):
"""
Returns statistics for the selected workers and time range aggregated by date intervals.
:param worker_ids: List of worker ids to collect metrics for. If not provided
or empty then all the company workers metrics are analyzed.
:type worker_ids: Sequence[str]
:param ... | GetStatsRequest |
python | h5py__h5py | h5py/tests/test_dataset_getitem.py | {
"start": 15759,
"end": 16309
} | class ____(TestCase):
def setUp(self):
TestCase.setUp(self)
self.data = np.ones((0,3), dtype='f')
self.dset = self.f.create_dataset('x', data=self.data)
def test_ndim(self):
""" Verify number of dimensions """
self.assertEqual(self.dset.ndim, 2)
def test_shape(self... | Test2DZeroFloat |
python | pypa__pip | docs/pip_sphinxext.py | {
"start": 6138,
"end": 6297
} | class ____(PipOptions):
def process_options(self) -> None:
self._format_options([o() for o in cmdoptions.general_group["options"]])
| PipGeneralOptions |
python | python-openxml__python-docx | src/docx/image/tiff.py | {
"start": 6706,
"end": 8196
} | class ____:
"""Base class for IFD entry classes.
Subclasses are differentiated by value type, e.g. ASCII, long int, etc.
"""
def __init__(self, tag_code, value):
super(_IfdEntry, self).__init__()
self._tag_code = tag_code
self._value = value
@classmethod
def from_strea... | _IfdEntry |
python | getlogbook__logbook | src/logbook/handlers.py | {
"start": 40831,
"end": 52666
} | class ____(Handler, StringFormatterHandlerMixin, LimitingHandlerMixin):
"""A handler that sends error mails. The format string used by this
handler are the contents of the mail plus the headers. This is handy
if you want to use a custom subject or ``X-`` header:
.. blacken-docs:off
.. code-block... | MailHandler |
python | mlflow__mlflow | mlflow/projects/_project_spec.py | {
"start": 12595,
"end": 14290
} | class ____:
"""A parameter in an MLproject entry point."""
def __init__(self, name, yaml_obj):
self.name = name
if is_string_type(yaml_obj):
self.type = yaml_obj
self.default = None
else:
self.type = yaml_obj.get("type", "string")
self.def... | Parameter |
python | sympy__sympy | sympy/utilities/codegen.py | {
"start": 12835,
"end": 13006
} | class ____(Variable):
"""An abstract Argument data structure: a name and a data type.
This structure is refined in the descendants below.
"""
pass
| Argument |
python | mlflow__mlflow | tests/resources/mlflow-test-plugin/mlflow_test_plugin/dummy_backend.py | {
"start": 600,
"end": 1109
} | class ____(AbstractBackend):
def run(
self,
project_uri,
entry_point,
params,
version,
backend_config,
tracking_uri,
experiment_id,
):
work_dir = fetch_and_validate_project(project_uri, version, entry_point, params)
active_run = get... | PluginDummyProjectBackend |
python | sphinx-doc__sphinx | tests/roots/test-ext-math-compat/conf.py | {
"start": 267,
"end": 502
} | class ____(Directive):
def run(self):
text = 'E = mc^2'
return [nodes.math_block(text, text)]
def setup(app):
app.add_role('my_math', my_math_role)
app.add_directive('my-math', MyMathDirective)
| MyMathDirective |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.