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 | davidhalter__jedi | test/completion/keywords.py | {
"start": 318,
"end": 574
} | class ____
#? []
continue i
# More syntax details, e.g. while only after newline, but not after semicolon,
# continue also after semicolon
#? ['while']
while
#? []
x while
#? []
x; while
#? ['continue']
x; continue
#? []
and
#? ['and']
x and
#? []
x * and
| i |
python | pydantic__pydantic | tests/mypy/outputs/mypy-default_ini/plugin_success.py | {
"start": 405,
"end": 843
} | class ____(BaseModel):
submodel: Optional['SelfReferencingModel']
@property
def prop(self) -> None:
...
SelfReferencingModel.model_rebuild()
model = Model(x=1, y='y')
Model(x=1, y='y', z='z')
# MYPY: error: Unexpected keyword argument "z" for "Model" [call-arg]
model.x = 2
model.model_validate(... | SelfReferencingModel |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/workspace/load_target.py | {
"start": 6725,
"end": 7281
} | class ____(WorkspaceLoadTarget):
python_file: str
attribute: Optional[str]
working_directory: Optional[str]
location_name: Optional[str]
def create_origins(self) -> Sequence[ManagedGrpcPythonEnvCodeLocationOrigin]:
return [
location_origin_from_python_file(
pytho... | PythonFileTarget |
python | google__jax | jax/_src/export/serialization_generated.py | {
"start": 1456,
"end": 1541
} | class ____(object):
Missing = 0
Device = 1
Host = 2
Any = 3
| MemorySpace |
python | wandb__wandb | wandb/vendor/pygments/lexers/javascript.py | {
"start": 13291,
"end": 17034
} | class ____(RegexLexer):
"""
For `Dart <http://dartlang.org/>`_ source code.
.. versionadded:: 1.5
"""
name = 'Dart'
aliases = ['dart']
filenames = ['*.dart']
mimetypes = ['text/x-dart']
flags = re.MULTILINE | re.DOTALL
tokens = {
'root': [
include('string_... | DartLexer |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-mangadex/llama_index/readers/mangadex/base.py | {
"start": 276,
"end": 4738
} | class ____(BaseReader):
def __init__(self) -> None:
self.base_url = "https://api.mangadex.org"
def _get_manga_info(self, title: str):
try:
manga_response = requests.get(
f"{self.base_url}/manga", params={"title": title}
)
manga_response.raise_... | MangaDexReader |
python | openai__openai-python | src/openai/pagination.py | {
"start": 4051,
"end": 4770
} | class ____(BaseAsyncPage[_T], BasePage[_T], Generic[_T]):
data: List[_T]
has_more: Optional[bool] = None
last_id: Optional[str] = None
@override
def _get_page_items(self) -> List[_T]:
data = self.data
if not data:
return []
return data
@override
def has_... | AsyncConversationCursorPage |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-fusion-retriever/llama_index/packs/fusion_retriever/hybrid_fusion/base.py | {
"start": 482,
"end": 3142
} | class ____(BaseLlamaPack):
"""
Hybrid fusion retriever pack.
Ensembles vector and bm25 retrievers using fusion.
"""
def __init__(
self,
nodes: List[TextNode] = None,
chunk_size: int = 256,
mode: str = "reciprocal_rerank",
vector_similarity_top_k: int = 2,
... | HybridFusionRetrieverPack |
python | google__pytype | pytype/main_test.py | {
"start": 559,
"end": 21512
} | class ____(test_base.UnitTest):
"""Integration test for pytype."""
DEFAULT_PYI = builtin_stubs.DEFAULT_SRC
INCLUDE = object()
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.pytype_dir = path_utils.dirname(path_utils.dirname(parser.__file__))
def setUp(self):
super().setUp()
se... | PytypeTest |
python | pytorch__pytorch | test/distributed/checkpoint/test_dedup_tensors.py | {
"start": 1213,
"end": 1897
} | class ____(TestCase):
"""
Test class for deduplication of tensor write items across different ranks.
"""
def test_dedup_shards(self):
rank0 = create_plan("r0")
rank1 = create_plan("r1")
dedup_plans = dedup_tensors([rank0, rank1])
self.assertEqual(2, len(dedup_plans[0].... | TestDedupTensor |
python | pytest-dev__pytest | src/_pytest/nodes.py | {
"start": 17164,
"end": 19231
} | class ____(Node, abc.ABC):
"""Base class of all collectors.
Collector create children through `collect()` and thus iteratively build
the collection tree.
"""
class CollectError(Exception):
"""An error during collection, contains a custom message."""
@abc.abstractmethod
def collect... | Collector |
python | mlflow__mlflow | tests/artifacts/test_artifacts.py | {
"start": 266,
"end": 5762
} | class ____(NamedTuple):
uri: str
content: str
@pytest.fixture
def run_with_artifact(tmp_path):
artifact_path = "test"
artifact_content = "content"
local_path = tmp_path.joinpath("file.txt")
local_path.write_text(artifact_content)
with mlflow.start_run() as run:
mlflow.log_artifact(... | Artifact |
python | PyCQA__pylint | tests/functional/n/none_dunder_protocols.py | {
"start": 171,
"end": 225
} | class ____(type):
__getitem__ = None
| MetaOldIterable |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_data_labels48.py | {
"start": 315,
"end": 1822
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_data_labels48.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(se... | TestCompareXLSXFiles |
python | getsentry__sentry | src/sentry/monitors/processing_errors/errors.py | {
"start": 2260,
"end": 2541
} | class ____(TypedDict):
"""
Checkin format was invalid
"""
type: Literal[ProcessingErrorType.CHECKIN_VALIDATION_FAILED]
errors: Mapping[str, Sequence[str]]
"""
Mapping of check-in field name to the problems with that field
"""
| CheckinValidationFailed |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_annotations/mypy_init_return.py | {
"start": 76,
"end": 133
} | class ____:
def __init__(self):
...
# Error
| Foo |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/unstack_op_test.py | {
"start": 1329,
"end": 8420
} | class ____(test.TestCase):
def randn(self, shape, dtype):
data = np.random.randn(*shape)
if dtype == np.bool_:
return data < 0 # Naive casting yields True with P(1)!
else:
return data.astype(dtype)
def unstackReference(self, data, axis):
"""Use numpy primitives to implement unstack eq... | UnstackOpTest |
python | tensorflow__tensorflow | tensorflow/python/ops/linalg/linear_operator_circulant.py | {
"start": 40797,
"end": 50732
} | class ____(_BaseLinearOperatorCirculant):
"""`LinearOperator` acting like a block circulant matrix.
This operator acts like a block circulant matrix `A` with
shape `[B1,...,Bb, N, N]` for some `b >= 0`. The first `b` indices index a
batch member. For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is
... | LinearOperatorCirculant2D |
python | doocs__leetcode | solution/2700-2799/2707.Extra Characters in a String/Solution2.py | {
"start": 161,
"end": 945
} | class ____:
def minExtraChar(self, s: str, dictionary: List[str]) -> int:
root = Node()
for w in dictionary:
node = root
for c in w[::-1]:
i = ord(c) - ord('a')
if node.children[i] is None:
node.children[i] = Node()
... | Solution |
python | langchain-ai__langchain | libs/langchain/langchain_classic/agents/agent_toolkits/vectorstore/toolkit.py | {
"start": 2071,
"end": 3239
} | class ____(BaseToolkit):
"""Toolkit for routing between Vector Stores."""
vectorstores: list[VectorStoreInfo] = Field(exclude=True)
llm: BaseLanguageModel
model_config = ConfigDict(
arbitrary_types_allowed=True,
)
def get_tools(self) -> list[BaseTool]:
"""Get the tools in the ... | VectorStoreRouterToolkit |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/ghostwriter/test_ghostwriter.py | {
"start": 7729,
"end": 8719
} | class ____:
@classmethod
def to_json(cls, obj: dict | list) -> str:
return json.dumps(obj)
@classmethod
def from_json(cls, obj: str) -> dict | list:
return json.loads(obj)
@staticmethod
def static_sorter(seq: Sequence[int]) -> list[int]:
return sorted(seq)
@pytest.mar... | A |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 3295,
"end": 3432
} | class ____(models.Model):
ip_address = models.GenericIPAddressField()
class Meta:
abstract = True
| IPAddressHistoricalModel |
python | pypa__pip | src/pip/_vendor/cachecontrol/caches/file_cache.py | {
"start": 485,
"end": 3034
} | class ____:
"""Shared implementation for both FileCache variants."""
def __init__(
self,
directory: str | Path,
forever: bool = False,
filemode: int = 0o0600,
dirmode: int = 0o0700,
lock_class: type[BaseFileLock] | None = None,
) -> None:
try:
... | _FileCacheMixin |
python | great-expectations__great_expectations | contrib/great_expectations_geospatial_expectations/great_expectations_geospatial_expectations/expectations/expect_column_values_to_be_polygon_area_between.py | {
"start": 2867,
"end": 10710
} | class ____(ColumnMapExpectation):
"""Expect the area of polygons in the column are between two specified values.
This expectation will compute the area of each polygon/multipolygon in square kilometers and check if it's between two values.
"""
world = geopandas.read_file(geopandas.datasets.get_path("n... | ExpectColumnValuesToBePolygonAreaBetween |
python | viewflow__viewflow | viewflow/forms/renderers.py | {
"start": 20504,
"end": 22585
} | class ____(LayoutNode):
"""Spread elements over a single line.
Example:
layout = Layout(
Row(
'first_name',
Row('last_name', 'sex', tablet=5)
)
)
"""
def __init__(self, *elements, **kwargs):
self.id_ = kwargs.pop("id_", N... | Row |
python | pypa__setuptools | setuptools/tests/test_find_packages.py | {
"start": 5688,
"end": 7819
} | class ____:
EXAMPLES = {
"hidden-folders": (
[".pkg/__init__.py", "pkg/__init__.py", "pkg/nested/file.txt"],
["pkg", "pkg.nested"],
),
"private-packages": (
["_pkg/__init__.py", "pkg/_private/__init__.py"],
["pkg", "pkg._private"],
),
... | TestFlatLayoutPackageFinder |
python | huggingface__transformers | src/transformers/models/opt/modeling_opt.py | {
"start": 3708,
"end": 7653
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
config: OPTConfig,
layer_idx: Optional[int] = None,
**kwargs,
):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size... | OPTAttention |
python | dateutil__dateutil | tests/test_tz.py | {
"start": 96588,
"end": 100415
} | class ____(unittest.TestCase):
def testCanberraForward(self):
tzi = tz.gettz('Australia/Canberra')
dt = datetime(2018, 10, 7, 2, 30, tzinfo=tzi)
dt_act = tz.resolve_imaginary(dt)
dt_exp = datetime(2018, 10, 7, 3, 30, tzinfo=tzi)
self.assertEqual(dt_act, dt_exp)
def testL... | ImaginaryDateTest |
python | kamyu104__LeetCode-Solutions | Python/power-of-four.py | {
"start": 308,
"end": 525
} | class ____(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
while num and not (num & 0b11):
num >>= 2
return (num == 1)
| Solution2 |
python | aio-libs__aiohttp | aiohttp/multipart.py | {
"start": 27499,
"end": 38054
} | class ____(Payload):
"""Multipart body writer."""
_value: None
# _consumed = False (inherited) - Can be encoded multiple times
_autoclose = True # No file handles, just collects parts in memory
def __init__(self, subtype: str = "mixed", boundary: str | None = None) -> None:
boundary = bou... | MultipartWriter |
python | openai__openai-python | src/openai/_types.py | {
"start": 6190,
"end": 6252
} | class ____(Protocol):
__origin__: type[object]
| _GenericAlias |
python | pytorch__pytorch | tools/linter/adapters/test_device_bias_linter.py | {
"start": 2401,
"end": 8465
} | class ____(ast.NodeVisitor):
def __init__(self, filename: str, is_gpu_test_suite: bool) -> None:
self.filename = filename
self.lint_messages: list[LintMessage] = []
self.is_gpu_test_suite = is_gpu_test_suite
def _has_proper_decorator(self, node: ast.FunctionDef) -> bool:
for d i... | DeviceBiasVisitor |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/rich/table.py | {
"start": 832,
"end": 5557
} | class ____:
"""Defines a column within a ~Table.
Args:
title (Union[str, Text], optional): The title of the table rendered at the top. Defaults to None.
caption (Union[str, Text], optional): The table caption rendered below. Defaults to None.
width (int, optional): The width in characte... | Column |
python | sphinx-doc__sphinx | sphinx/ext/extlinks.py | {
"start": 1414,
"end": 4879
} | class ____(SphinxPostTransform):
"""For each external link, check if it can be replaced by an extlink.
We treat each ``reference`` node without ``internal`` attribute as an external link.
"""
default_priority = 500
def run(self, **kwargs: Any) -> None:
if not self.config.extlinks_detect_h... | ExternalLinksChecker |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 28104,
"end": 28279
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("CLOSED", "MERGED", "OPEN")
| PullRequestState |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF023.py | {
"start": 1961,
"end": 3700
} | class ____:
__slots__ = (
# The `_raw_paths` slot stores unnormalized string paths. This is set
# in the `__init__()` method.
'_raw_paths',
# The `_drv`, `_root` and `_tail_cached` slots store parsed and
# normalized parts of the path. They are set when any of the `drive`,
... | PurePath |
python | py-pdf__pypdf | pypdf/annotations/_markup_annotations.py | {
"start": 5890,
"end": 6608
} | class ____(MarkupAnnotation):
def __init__(
self,
vertices: list[Vertex],
**kwargs: Any,
) -> None:
super().__init__(**kwargs)
if len(vertices) == 0:
raise ValueError("A polygon needs at least 1 vertex with two coordinates")
coord_list = []
for... | PolyLine |
python | huggingface__transformers | tests/models/flava/test_modeling_flava.py | {
"start": 32809,
"end": 35722
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (FlavaModel,) if is_torch_available() else ()
pipeline_model_mapping = {"feature-extraction": FlavaModel} if is_torch_available() else {}
class_for_tester = FlavaModelTester
test_resize_embeddings = False
test... | FlavaModelTest |
python | PyCQA__pylint | tests/functional/u/unused/unused_name_in_string_literal_type_annotation.py | {
"start": 832,
"end": 925
} | class ____:
"""unused-import shouldn't be emitted for Namespace"""
cls: "Namespace"
| Class |
python | ray-project__ray | python/ray/llm/_internal/serve/engines/vllm/kv_transfer/nixl.py | {
"start": 109,
"end": 2540
} | class ____(BaseConnectorBackend):
def _set_side_channel_port(self):
from vllm import envs as vllm_envs, utils as vllm_utils
if not vllm_envs.is_set("VLLM_NIXL_SIDE_CHANNEL_PORT"):
base_port: int = int(
self.llm_config.experimental_configs.get(
"NIXL_S... | NixlConnectorBackend |
python | PrefectHQ__prefect | tests/cli/test_api_command.py | {
"start": 11006,
"end": 13534
} | class ____:
"""Test error handling and exit codes."""
def test_404_error_exit_code(self, respx_mock: MockRouter) -> None:
"""Test 404 errors exit with code 4."""
respx_mock.get("http://localhost:4200/api/flows/invalid-id").mock(
return_value=httpx.Response(404, json={"detail": "Flow... | TestErrorHandling |
python | getsentry__sentry | src/sentry/search/events/fields.py | {
"start": 84982,
"end": 86645
} | class ____(SnQLFunction):
"""Metrics needs to differentiate between aggregate types so we can send queries to the right table"""
def __init__(self, *args, **kwargs) -> None:
self.snql_distribution = kwargs.pop("snql_distribution", None)
self.snql_set = kwargs.pop("snql_set", None)
self.... | MetricsFunction |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/metaclass3.py | {
"start": 371,
"end": 405
} | class ____(Meta3):
pass
| SubMeta3 |
python | pytorch__pytorch | benchmarks/transformer/sdpa.py | {
"start": 1573,
"end": 1809
} | class ____:
forward_time: float # microseconds
backward_time: float # microseconds
forward_tflops: float
backward_tflops: float
def asdict(self):
return asdict(self)
@dataclass(frozen=True)
| ExperimentResults |
python | python-attrs__attrs | tests/test_make.py | {
"start": 65167,
"end": 66374
} | class ____:
def test_default(self):
"""
If all are set to None, set both eq and order to the passed default.
"""
assert (42, 42) == _determine_attrs_eq_order(None, None, None, 42)
@pytest.mark.parametrize("eq", [True, False])
def test_order_mirrors_eq_by_default(self, eq):
... | TestDetermineAttrsEqOrder |
python | huggingface__transformers | src/transformers/models/sam3/modeling_sam3.py | {
"start": 21779,
"end": 23063
} | 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: Sam3ViTConfig):
... | Sam3ViTPatchEmbeddings |
python | django__django | tests/model_forms/tests.py | {
"start": 133208,
"end": 135035
} | class ____(SimpleTestCase):
"""
Should a model do anything special with __setattr__() or descriptors which
raise a ValidationError, a model form should catch the error (#24706).
"""
def test_setattr_raises_validation_error_field_specific(self):
"""
A model ValidationError using the ... | StrictAssignmentTests |
python | pytorch__pytorch | torch/masked/maskedtensor/_ops_refs.py | {
"start": 4426,
"end": 18130
} | class ____(torch.autograd.Function):
@staticmethod
# pyrefly: ignore [bad-override]
def forward(ctx, cond, self, other):
ctx.mark_non_differentiable(cond)
ctx.save_for_backward(cond)
return torch.ops.aten.where(cond, self, other)
@staticmethod
# pyrefly: ignore [bad-override... | _MaskedWhere |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/links/test_athena.py | {
"start": 1173,
"end": 2192
} | class ____(BaseAwsLinksTestCase):
link_class = AthenaQueryResultsLink
def test_extra_link(self, mock_supervisor_comms):
if AIRFLOW_V_3_0_PLUS and mock_supervisor_comms:
mock_supervisor_comms.send.return_value = XComResult(
key=AthenaQueryResultsLink.key,
valu... | TestAthenaQueryResultsLink |
python | yaml__pyyaml | lib/yaml/cyaml.py | {
"start": 1283,
"end": 2139
} | class ____(CEmitter, BaseRepresenter, BaseResolver):
def __init__(self, stream,
default_style=None, default_flow_style=False,
canonical=None, indent=None, width=None,
allow_unicode=None, line_break=None,
encoding=None, explicit_start=None, explicit_end=None,
... | CBaseDumper |
python | python-excel__xlwt | xlwt/BIFFRecords.py | {
"start": 44593,
"end": 46843
} | class ____(BiffRecord):
"""
This record occurs in conjunction with the SST record. It is used
by Excel to create a hash table with stream offsets to the SST record
to optimise string search operations. Excel may not shorten this record
if strings are deleted from the shared string table, s... | ExtSSTRecord |
python | mlflow__mlflow | dev/clint/src/clint/__init__.py | {
"start": 439,
"end": 2984
} | class ____:
files: list[str]
output_format: Literal["text", "json"]
@classmethod
def parse(cls) -> Self:
parser = argparse.ArgumentParser(description="Custom linter for mlflow.")
parser.add_argument(
"files",
nargs="*",
help="Files to lint. If not spe... | Args |
python | explosion__spaCy | spacy/lang/mk/lemmatizer.py | {
"start": 126,
"end": 1715
} | class ____(Lemmatizer):
def rule_lemmatize(self, token: Token) -> List[str]:
string = token.text
univ_pos = token.pos_.lower()
if univ_pos in ("", "eol", "space"):
return [string.lower()]
if string[-3:] == "јќи":
string = string[:-3]
univ_pos = "... | MacedonianLemmatizer |
python | PyCQA__pylint | tests/functional/a/alternative/alternative_union_syntax.py | {
"start": 2066,
"end": 2201
} | class ____:
pass
class_list = [WithForward | DefaultMetaclass]
class_list_reversed = [WithReverse | DefaultMetaclass]
| DefaultMetaclass |
python | getsentry__sentry | src/sentry/integrations/source_code_management/metrics.py | {
"start": 3374,
"end": 3697
} | class ____(StrEnum):
"""
Common reasons why a link all repos task may halt without success/failure.
"""
MISSING_INTEGRATION = "missing_integration"
MISSING_ORGANIZATION = "missing_organization"
RATE_LIMITED = "rate_limited"
REPOSITORY_NOT_CREATED = "repository_not_created"
| LinkAllReposHaltReason |
python | tensorflow__tensorflow | tensorflow/python/training/saving/saveable_object_util_test.py | {
"start": 6190,
"end": 7640
} | class ____(test.TestCase):
def test_checkpoint_comparison(self):
saveable_state = SaveableState(5.)
trackable_state = TrackableState(10.)
# First test that SaveableState and TrackableState are equivalent by
# saving a checkpoint with both objects and swapping values.
self.assertEqual(5, self.ev... | SaveableCompatibilityEndToEndTest |
python | huggingface__transformers | tests/models/vision_text_dual_encoder/test_processing_vision_text_dual_encoder.py | {
"start": 1056,
"end": 2046
} | class ____(ProcessorTesterMixin, unittest.TestCase):
processor_class = VisionTextDualEncoderProcessor
@classmethod
def _setup_image_processor(cls):
image_processor_map = {
"do_resize": True,
"size": {"height": 18, "width": 18},
"do_normalize": True,
"... | VisionTextDualEncoderProcessorTest |
python | apache__airflow | providers/apache/hdfs/src/airflow/providers/apache/hdfs/hooks/webhdfs.py | {
"start": 1503,
"end": 7532
} | class ____(BaseHook):
"""
Interact with HDFS. This class is a wrapper around the hdfscli library.
:param webhdfs_conn_id: The connection id for the webhdfs client to connect to.
:param proxy_user: The user used to authenticate.
"""
conn_type = "webhdfs"
conn_name_attr = "webhdfs_conn_id"
... | WebHDFSHook |
python | pytorch__pytorch | torch/testing/_internal/common_fsdp.py | {
"start": 13058,
"end": 16437
} | class ____(FSDPTestModel):
def __init__(
self,
group: dist.ProcessGroup,
wrap_fsdp: bool,
device_init_mode: DEVICEInitMode,
deterministic: bool,
**fsdp_kwargs,
):
super().__init__()
self.rank = group.rank()
self.world_size = group.size()
... | NestedWrappedModule |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pydoclint/DOC201_google.py | {
"start": 1007,
"end": 1404
} | class ____:
# OK
@cached_property
def baz(self) -> str:
"""
Do something
Args:
num (int): A number
"""
return 'test'
# OK
def f():
"""Returns 1."""
return 1
# OK
def f():
"""Return 1."""
return 1
# OK
def f(num: int):
"""Returns ... | Baz |
python | sqlalchemy__sqlalchemy | test/orm/test_cascade.py | {
"start": 60814,
"end": 65212
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"t1",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("data", String(50)),
Column("t2i... | M2OCascadeDeleteOrphanTestTwo |
python | Pylons__pyramid | tests/test_integration.py | {
"start": 33940,
"end": 34700
} | class ____(unittest.TestCase):
def tearDown(self):
import pyramid.config
pyramid.config.global_registries.empty()
def get_gc_count(self):
last_collected = 0
while True:
collected = gc.collect()
if collected == last_collected:
break
... | MemoryLeaksTest |
python | neetcode-gh__leetcode | python/1189-maximum-number-of-balloons.py | {
"start": 34,
"end": 318
} | class ____:
def maxNumberOfBalloons(self, text: str) -> int:
countText = Counter(text)
balloon = Counter("balloon")
res = len(text) # or float("inf")
for c in balloon:
res = min(res, countText[c] // balloon[c])
return res
| Solution |
python | getsentry__sentry | tests/sentry/integrations/gitlab/test_integration.py | {
"start": 29150,
"end": 31491
} | class ____(GitLabTestCase):
@responses.activate
def test_integration_proxy_is_active(self) -> None:
gitlab_id = 123
commit = "a" * 40
gitlab_response = responses.add(
method=responses.GET,
url=f"https://example.gitlab.com/api/v4/projects/{gitlab_id}/repository/com... | GitlabApiClientTest |
python | tensorflow__tensorflow | tensorflow/python/distribute/coordinator/utils.py | {
"start": 1802,
"end": 2596
} | class ____(object):
"""Threaded Repeated Timer from http://shortn/_3hMZTFr1Iv."""
def __init__(self, interval, function, *args):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.start_time = time.time()
self.is_running = False
self.start()
de... | RepeatedTimer |
python | catalyst-team__catalyst | examples/catalyst_rl/db.py | {
"start": 598,
"end": 11925
} | class ____(ABC):
@property
@abstractmethod
def training_enabled(self) -> bool:
pass
@property
@abstractmethod
def sampling_enabled(self) -> bool:
pass
@property
@abstractmethod
def epoch(self) -> int:
pass
@property
@abstractmethod
def num_traje... | IRLDatabase |
python | tensorflow__tensorflow | tensorflow/python/grappler/memory_optimizer_test.py | {
"start": 4451,
"end": 14617
} | class ____(test.TestCase):
"""Tests the Python interface to recomputation rewrites.
See core/grappler/optimizers/memory_optimizer_test.cc for functional tests.
"""
def _GetMetaGraph(self, batch_size=14, image_dim=12, optimizer_scope_name=''):
"""A simple layered graph with conv, an intermediate op, and a ... | MemoryOptimizerRecomputeTest |
python | plotly__plotly.py | plotly/graph_objs/_barpolar.py | {
"start": 215,
"end": 55387
} | class ____(_BaseTraceType):
_parent_path_str = ""
_path_str = "barpolar"
_valid_props = {
"base",
"basesrc",
"customdata",
"customdatasrc",
"dr",
"dtheta",
"hoverinfo",
"hoverinfosrc",
"hoverlabel",
"hovertemplate",
"hov... | Barpolar |
python | kamyu104__LeetCode-Solutions | Python/make-lexicographically-smallest-array-by-swapping-elements.py | {
"start": 40,
"end": 659
} | class ____(object):
def lexicographicallySmallestArray(self, nums, limit):
"""
:type nums: List[int]
:type limit: int
:rtype: List[int]
"""
idxs = range(len(nums))
idxs.sort(key=lambda x: nums[x])
groups = []
for i in xrange(len(nums)):
... | Solution |
python | plotly__plotly.py | plotly/graph_objs/scatterpolargl/hoverlabel/_font.py | {
"start": 233,
"end": 17179
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatterpolargl.hoverlabel"
_path_str = "scatterpolargl.hoverlabel.font"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsr... | Font |
python | pypa__hatch | tests/env/plugin/test_interface.py | {
"start": 62309,
"end": 65320
} | class ____:
def test_default(self, isolation, isolated_data_dir, platform, global_application):
config = {"project": {"name": "my_app", "version": "0.0.1"}}
project = Project(isolation, config=config)
environment = MockEnvironment(
isolation,
project.metadata,
... | TestPreInstallCommands |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/styles/style.py | {
"start": 5964,
"end": 11493
} | class ____(BaseStyle):
"""
Create a ``Style`` instance from a list of style rules.
The `style_rules` is supposed to be a list of ('classnames', 'style') tuples.
The classnames are a whitespace separated string of class names and the
style string is just like a Pygments style definition, but with a ... | Style |
python | realpython__materials | python-class/workers.py | {
"start": 454,
"end": 749
} | class ____(Worker):
def __init__(self, name, address, hourly_salary, hourly_bonus):
super().__init__(name, address, hourly_salary)
self.hourly_bonus = hourly_bonus
def calculate_payroll(self, hours=40):
return (self.hourly_salary + self.hourly_bonus) * hours
| Manager |
python | getsentry__sentry | tests/sentry/integrations/gitlab/test_integration.py | {
"start": 26848,
"end": 29150
} | class ____(IntegrationTestCase):
provider = GitlabIntegrationProvider
base_url = "https://gitlab.example.com"
access_token = "xxxxx-xxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxx"
default_group_id = 4
@responses.activate
def test_integration_proxy_is_active(self) -> None:
response_payload = {
... | GitlabSetupApiClientTest |
python | kamyu104__LeetCode-Solutions | Python/maximal-network-rank.py | {
"start": 3464,
"end": 4030
} | class ____(object):
def maximalNetworkRank(self, n, roads):
"""
:type n: int
:type roads: List[List[int]]
:rtype: int
"""
degree = [0]*n
adj = collections.defaultdict(set)
for a, b in roads:
degree[a] += 1
degree[b] += 1
... | Solution3 |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_set.py | {
"start": 56630,
"end": 56920
} | class ____(_TestOnlySetsInBinaryOps, __TestCase):
def setUp(self):
self.set = set((1, 2, 3))
self.other = 'abc'
self.otherIsIterable = True
super().setUp()
#------------------------------------------------------------------------------
| TestOnlySetsString |
python | pytorch__pytorch | torch/_inductor/sizevars.py | {
"start": 1726,
"end": 46184
} | class ____:
"""
A class that manages symbolic size variables and their relationships.
This class works with the ShapeEnv to handle symbolic shape expressions,
simplify them, and provide utilities for guarding, checking, and evaluating
symbolic expressions. It also manages precomputed replacements a... | SizeVarAllocator |
python | doocs__leetcode | solution/2100-2199/2122.Recover the Original Array/Solution.py | {
"start": 0,
"end": 824
} | class ____:
def recoverArray(self, nums: List[int]) -> List[int]:
nums.sort()
n = len(nums)
for i in range(1, n):
d = nums[i] - nums[0]
if d == 0 or d % 2 == 1:
continue
vis = [False] * n
vis[i] = True
ans = [(nums[0... | Solution |
python | pydantic__pydantic | pydantic-core/tests/validators/test_callable.py | {
"start": 170,
"end": 1531
} | class ____:
def __call__(self, *args, **kwargs):
pass
def test_callable():
v = SchemaValidator(cs.callable_schema())
assert v.validate_python(func) == func
assert v.isinstance_python(func) is True
with pytest.raises(ValidationError) as exc_info:
v.validate_python(42)
assert e... | CallableClass |
python | run-llama__llama_index | llama-index-core/llama_index/core/llama_dataset/simple.py | {
"start": 942,
"end": 1747
} | class ____(BaseLlamaPredictionDataset):
"""RagDataset class."""
_prediction_type = SimpleExamplePrediction
def to_pandas(self) -> Any:
"""Create pandas dataframe."""
try:
import pandas as pd
except ImportError:
raise ImportError(
"pandas is r... | SimplePredictionDataset |
python | getsentry__sentry | src/sentry_plugins/redmine/client.py | {
"start": 56,
"end": 1480
} | class ____:
def __init__(self, host, key):
self.host = host.rstrip("/")
self.key = key
def request(self, method, path, data=None):
headers = {"X-Redmine-API-Key": self.key, "Content-Type": "application/json"}
url = f"{self.host}{path}"
with http.build_session() as sessio... | RedmineClient |
python | tox-dev__tox | src/tox/execute/local_sub_process/read_via_thread_windows.py | {
"start": 619,
"end": 2950
} | class ____(ReadViaThread): # pragma: win32 cover
def __init__(self, file_no: int, handler: Callable[[bytes], None], name: str, drain: bool) -> None: # noqa: FBT001
super().__init__(file_no, handler, name, drain)
self.closed = False
self._ov: _overlapped.Overlapped | None = None
sel... | ReadViaThreadWindows |
python | donnemartin__interactive-coding-challenges | staging/sorting_searching/group_ordered/test_group_ordered.py | {
"start": 18,
"end": 1040
} | class ____(unittest.TestCase):
def test_group_ordered(self, func):
self.assertEqual(func(None), None)
print('Success: ' + func.__name__ + " None case.")
self.assertEqual(func([]), [])
print('Success: ' + func.__name__ + " Empty case.")
self.assertEqual(func([1]), [1])
... | TestGroupOrdered |
python | google__python-fire | fire/test_components.py | {
"start": 10346,
"end": 10526
} | class ____:
def double(self, number):
return 2 * number
def __getattr__(self, name):
def _missing():
return 'Undefined function'
return _missing
| DefaultMethod |
python | ray-project__ray | python/ray/serve/_private/benchmarks/streaming/_grpc/grpc_server.py | {
"start": 263,
"end": 1860
} | class ____(test_server_pb2_grpc.GRPCTestServerServicer):
def __init__(self, tokens_per_request):
self._tokens_per_request = tokens_per_request
async def Unary(self, request, context):
if request.request_data == "error":
await context.abort(
code=grpc.StatusCode.INTER... | TestGRPCServer |
python | pytorch__pytorch | torch/distributed/tensor/placement_types.py | {
"start": 28197,
"end": 31346
} | class ____(torch._C._distributed.Partial):
"""
The ``Partial(reduce_op)`` placement describes the DTensor that is pending
reduction on a specified ``DeviceMesh`` dimension, where each rank on the
DeviceMesh dimension holds the partial value of the global Tensor. User can
redistribute the ``Partial``... | Partial |
python | Netflix__metaflow | metaflow/plugins/argo/argo_workflows.py | {
"start": 214086,
"end": 214962
} | class ____(object):
# https://github.com/argoproj/argo-events/blob/master/api/sensor.md#argoproj.io/v1alpha1.Trigger
def __init__(self):
tree = lambda: defaultdict(tree)
self.payload = tree()
def template(self, trigger_template):
self.payload["template"] = trigger_template.to_json(... | Trigger |
python | getsentry__sentry | src/sentry/integrations/msteams/card_builder/block.py | {
"start": 2136,
"end": 2260
} | class ____(TypedDict, total=False):
size: ImageSize
height: str
width: str
altText: str
| _ImageBlockNotRequired |
python | py-pdf__pypdf | pypdf/_doc_common.py | {
"start": 3264,
"end": 8636
} | class ____(DictionaryObject):
"""
A class representing the basic document metadata provided in a PDF File.
This class is accessible through
:py:class:`PdfReader.metadata<pypdf.PdfReader.metadata>`.
All text properties of the document metadata have
*two* properties, e.g. author and author_raw. T... | DocumentInformation |
python | cython__cython | Cython/Compiler/Builtin.py | {
"start": 4313,
"end": 42343
} | class ____:
# read only for now
def __init__(self, py_name, property_type, call_cname,
exception_value=None, exception_check=None, utility_code=None):
self.py_name = py_name
self.property_type = property_type
self.call_cname = call_cname
self.utility_code = utili... | BuiltinProperty |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_work_queues.py | {
"start": 37544,
"end": 38124
} | class ____:
async def test_delete_work_queue(self, client, work_queue):
response = await client.delete(f"/work_queues/{work_queue.id}")
assert response.status_code == status.HTTP_204_NO_CONTENT
response = await client.get(f"/work_queues/{work_queue.id}")
assert response.status_code ... | TestDeleteWorkQueue |
python | ray-project__ray | rllib/examples/rl_modules/classes/vpg_using_shared_encoder_rlm.py | {
"start": 7190,
"end": 7851
} | class ____(TorchRLModule):
"""A shared encoder that can be used with `VPGMultiRLModuleWithSharedEncoder`."""
def setup(self):
super().setup()
input_dim = self.observation_space.shape[0]
embedding_dim = self.model_config["embedding_dim"]
# A very simple encoder network.
... | SharedEncoder |
python | getsentry__sentry | src/sentry/notifications/platform/api/endpoints/internal_registered_templates.py | {
"start": 955,
"end": 4605
} | class ____(Endpoint):
owner = ApiOwner.ECOSYSTEM
permission_classes = (SentryIsAuthenticated,)
publish_status = {"GET": ApiPublishStatus.PRIVATE}
def get(self, request: Request) -> Response:
response: dict[str, list[dict[str, Any]]] = defaultdict(list)
for source, template_cls in templa... | InternalRegisteredTemplatesEndpoint |
python | pandas-dev__pandas | pandas/tests/indexes/datetimes/test_join.py | {
"start": 318,
"end": 4915
} | class ____:
def test_does_not_convert_mixed_integer(self):
df = DataFrame(np.ones((3, 2)), columns=date_range("2020-01-01", periods=2))
cols = df.columns.join(df.index, how="outer")
joined = cols.join(df.columns)
assert cols.dtype == np.dtype("O")
assert cols.dtype == joined.... | TestJoin |
python | numba__numba | numba/cuda/tests/cudapy/test_retrieve_autoconverted_arrays.py | {
"start": 142,
"end": 511
} | class ____(object):
def prepare_args(self, ty, val, **kwargs):
return ty, wrap_arg(val, default=cuda.In)
def nocopy(kernel):
kernel.extensions.append(DefaultIn())
return kernel
def set_array_to_three(arr):
arr[0] = 3
def set_record_to_three(rec):
rec[0]['b'] = 3
recordtype = np.dtype... | DefaultIn |
python | TheAlgorithms__Python | data_structures/linked_list/doubly_linked_list.py | {
"start": 236,
"end": 6719
} | class ____:
def __init__(self):
self.head = None
self.tail = None
def __iter__(self):
"""
>>> linked_list = DoublyLinkedList()
>>> linked_list.insert_at_head('b')
>>> linked_list.insert_at_head('a')
>>> linked_list.insert_at_tail('c')
>>> tuple(li... | DoublyLinkedList |
python | networkx__networkx | networkx/classes/tests/test_coreviews.py | {
"start": 4433,
"end": 6192
} | class ____:
# node->data
def setup_method(self):
self.s = {0: {"color": "blue", "weight": 1.2}, 1: {}, 2: {"color": 1}}
self.p = {3: {"color": "blue", "weight": 1.2}, 4: {}, 2: {"watch": 2}}
self.av = nx.classes.coreviews.UnionAtlas(self.s, self.p)
def test_pickle(self):
vie... | TestUnionAtlas |
python | celery__celery | t/unit/worker/test_native_delayed_delivery.py | {
"start": 392,
"end": 19929
} | class ____:
@patch('celery.worker.consumer.delayed_delivery.detect_quorum_queues', return_value=[False, ""])
def test_include_if_no_quorum_queues_detected(self, _):
consumer_mock = Mock()
delayed_delivery = DelayedDelivery(consumer_mock)
assert delayed_delivery.include_if(consumer_mock... | test_DelayedDelivery |
python | huggingface__transformers | src/transformers/models/granitemoeshared/modeling_granitemoeshared.py | {
"start": 8666,
"end": 13898
} | class ____(nn.Module):
"""
A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts.
Args:
config:
Configuration object with model hyperparameters.
"""
def __init__(self, config: GraniteMoeSharedConfig):
super().__init__()
self.in... | GraniteMoeSharedMoE |
python | jmcnamara__XlsxWriter | xlsxwriter/test/relationships/test_relationships01.py | {
"start": 353,
"end": 2208
} | class ____(unittest.TestCase):
"""
Test assembling a complete Relationships file.
"""
def test_assemble_xml_file(self):
"""Test writing an Relationships file."""
self.maxDiff = None
fh = StringIO()
rels = Relationships()
rels._set_filehandle(fh)
rels._... | TestAssembleRelationships |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.