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 | realpython__materials | chatgpt-mentor/recursion_error.py | {
"start": 64,
"end": 393
} | class ____(list):
def push(self, item):
self.append(item)
def pop(self):
return super().pop()
def __repr__(self) -> str:
return f"{type(self).__name__}({self})"
print(Stack([1, 2, 3]))
# Try the following prompt and see how ChatGPT guides you to a solution:
"""
I have a Python ... | Stack |
python | getsentry__sentry | src/sentry/middleware/integrations/tasks.py | {
"start": 694,
"end": 875
} | class ____:
region: Region
response: Response
def was_successful(self) -> bool:
return 200 <= self.response.status_code < 300
@dataclass(frozen=True)
| _AsyncResult |
python | PyCQA__pylint | tests/test_self.py | {
"start": 3307,
"end": 55758
} | class ____:
def _runtest(
self,
args: list[str],
reporter: Any = None,
out: StringIO | None = None,
code: int | None = None,
) -> None:
if out is None:
out = StringIO()
args = _add_rcfile_default_pylintrc(args)
pylint_code = self._run_p... | TestRunTC |
python | huggingface__transformers | src/transformers/models/conditional_detr/modeling_conditional_detr.py | {
"start": 16818,
"end": 18645
} | class ____(nn.Module):
"""
This is a more standard version of the position embedding, very similar to the one used by the Attention is all you
need paper, generalized to work on images.
"""
def __init__(self, embedding_dim=64, temperature=10000, normalize=False, scale=None):
super().__init_... | ConditionalDetrSinePositionEmbedding |
python | MongoEngine__mongoengine | docs/code/tumblelog.py | {
"start": 682,
"end": 1716
} | class ____(Post):
link_url = StringField()
Post.drop_collection()
john = User(email="jdoe@example.com", first_name="John", last_name="Doe")
john.save()
post1 = TextPost(title="Fun with MongoEngine", author=john)
post1.content = "Took a look at MongoEngine today, looks pretty cool."
post1.tags = ["mongodb", "mon... | LinkPost |
python | pypa__warehouse | tests/unit/accounts/test_views.py | {
"start": 128633,
"end": 141737
} | class ____:
@pytest.mark.parametrize("desired_role", ["Maintainer", "Owner"])
def test_verify_project_role(
self, db_request, user_service, token_service, monkeypatch, desired_role
):
project = ProjectFactory.create()
user = UserFactory.create()
RoleInvitationFactory.create(u... | TestVerifyProjectRole |
python | redis__redis-py | redis/commands/policies.py | {
"start": 5355,
"end": 6189
} | class ____(ABC):
@abstractmethod
async def resolve(self, command_name: str) -> Optional[CommandPolicies]:
"""
Resolves the command name and determines the associated command policies.
Args:
command_name: The name of the command to resolve.
Returns:
Comma... | AsyncPolicyResolver |
python | getsentry__sentry | tests/sentry/workflow_engine/handlers/detector/test_base.py | {
"start": 1887,
"end": 2785
} | class ____(StatefulDetectorHandler[dict, int | None]):
def test_get_empty_counter_state(self):
return {name: None for name in self.state_manager.counter_names}
def extract_dedupe_value(self, data_packet: DataPacket[dict]) -> int:
return data_packet.packet.get("dedupe", 0)
def extract_value... | MockDetectorStateHandler |
python | huggingface__transformers | tests/pipelines/test_pipelines_summarization.py | {
"start": 953,
"end": 8335
} | class ____(unittest.TestCase):
model_mapping = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
def get_test_pipeline(
self,
model,
tokenizer=None,
image_processor=None,
feature_extractor=None,
processor=None,
dtype="float32",
):
summarizer = Summarizat... | SummarizationPipelineTests |
python | Farama-Foundation__Gymnasium | gymnasium/error.py | {
"start": 1457,
"end": 1576
} | class ____(Error):
"""Raised when the user performs an action not contained within the action space."""
| InvalidAction |
python | tensorflow__tensorflow | tensorflow/python/keras/optimizer_v2/learning_rate_schedule.py | {
"start": 11041,
"end": 16483
} | class ____(LearningRateSchedule):
"""A LearningRateSchedule that uses a polynomial decay schedule.
It is commonly observed that a monotonically decreasing learning rate, whose
degree of change is carefully chosen, results in a better performing model.
This schedule applies a polynomial decay function to an opt... | PolynomialDecay |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_composer.py | {
"start": 6571,
"end": 8860
} | class ____:
@mock.patch(COMPOSER_STRING.format("Environment.to_dict"))
@mock.patch(COMPOSER_STRING.format("CloudComposerHook"))
def test_execute(self, mock_hook, to_dict_mode) -> None:
op = CloudComposerUpdateEnvironmentOperator(
task_id=TASK_ID,
project_id=TEST_GCP_PROJECT,
... | TestCloudComposerUpdateEnvironmentOperator |
python | sqlalchemy__sqlalchemy | test/engine/test_pool.py | {
"start": 2084,
"end": 3034
} | class ____(fixtures.TestBase):
def setup_test(self):
self._teardown_conns = []
def teardown_test(self):
for ref in self._teardown_conns:
conn = ref()
if conn:
conn.close()
def _with_teardown(self, connection):
self._teardown_conns.append(weak... | PoolTestBase |
python | readthedocs__readthedocs.org | readthedocs/subscriptions/views.py | {
"start": 904,
"end": 6812
} | class ____(OrganizationMixin, DetailView):
"""Detail for the subscription of a organization."""
model = djstripe.Subscription
form_class = PlanForm
template_name = "subscriptions/subscription_detail.html"
context_object_name = "stripe_subscription"
def get(self, request, *args, **kwargs):
... | DetailSubscription |
python | plotly__plotly.py | plotly/graph_objs/layout/updatemenu/_font.py | {
"start": 235,
"end": 9903
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.updatemenu"
_path_str = "layout.updatemenu.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
... | Font |
python | tiangolo__fastapi | docs_src/query_param_models/tutorial002_pv1.py | {
"start": 155,
"end": 501
} | class ____(BaseModel):
class Config:
extra = "forbid"
limit: int = Field(100, gt=0, le=100)
offset: int = Field(0, ge=0)
order_by: Literal["created_at", "updated_at"] = "created_at"
tags: List[str] = []
@app.get("/items/")
async def read_items(filter_query: FilterParams = Query()):
re... | FilterParams |
python | astropy__astropy | astropy/units/tests/test_quantity_non_ufuncs.py | {
"start": 3514,
"end": 6280
} | class ____(InvariantUnitTestSetup):
# Note: do not parametrize the below, since test names are used
# to check coverage.
def test_reshape(self):
self.check(np.reshape, (9, 1))
def test_ravel(self):
self.check(np.ravel)
def test_moveaxis(self):
self.check(np.moveaxis, 0, 1)
... | TestShapeManipulation |
python | plotly__plotly.py | plotly/graph_objs/waterfall/_legendgrouptitle.py | {
"start": 233,
"end": 2953
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "waterfall"
_path_str = "waterfall.legendgrouptitle"
_valid_props = {"font", "text"}
@property
def font(self):
"""
Sets this legend group's title font.
The 'font' property is an instance of Font
that may be spe... | Legendgrouptitle |
python | tensorflow__tensorflow | tensorflow/python/autograph/converters/conditional_expressions_test.py | {
"start": 922,
"end": 1571
} | class ____(converter_testing.TestCase):
def assertTransformedEquivalent(self, f, *inputs):
tr = self.transform(f, conditional_expressions)
self.assertEqual(f(*inputs), tr(*inputs))
def test_basic(self):
def f(x):
return 1 if x else 0
self.assertTransformedEquivalent(f, 0)
self.assertTr... | ConditionalExpressionsTest |
python | readthedocs__readthedocs.org | readthedocs/projects/tasks/search.py | {
"start": 1026,
"end": 1590
} | class ____:
"""
Base class for doing operations over each file from a build.
The process method should be implemented to apply the operation
over each file, and the collect method should be implemented
to collect the results of the operation after processing all files.
`sync_id` is used to dif... | Indexer |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/configuration_qwen3_omni_moe.py | {
"start": 52093,
"end": 56483
} | class ____(PreTrainedConfig):
"""
This is the configuration class to store the configuration of a [`Qwen3OmniMoeForConditionalGeneration`]. It is used to instantiate a Qwen3Omni
model according to the specified sub-models configurations, defining the model architecture.
Instantiating a configuration wi... | Qwen3OmniMoeConfig |
python | ApeWorX__ape | src/ape_test/config.py | {
"start": 499,
"end": 692
} | class ____(PluginConfig):
chain_id: int = DEFAULT_TEST_CHAIN_ID
auto_mine: bool = True
model_config = SettingsConfigDict(extra="allow", env_prefix="APE_TEST_")
| EthTesterProviderConfig |
python | getsentry__sentry | tests/sentry/api/endpoints/test_check_am2_compatibility.py | {
"start": 308,
"end": 3225
} | class ____(APITestCase):
def setUp(self) -> None:
super().setUp()
self.owner = self.create_user(
email="example@example.com", is_superuser=False, is_staff=True, is_active=True
)
self.org = self.create_organization(owner=self.owner)
self.first_team = self.create_te... | AdminRelayProjectConfigsEndpointTest |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_extend.py | {
"start": 185,
"end": 291
} | class ____:
def bar(self):
return 1
@classmethod
def baz(cls):
return 1
| FooBase |
python | pandas-dev__pandas | pandas/tests/series/methods/test_rename.py | {
"start": 179,
"end": 6059
} | class ____:
def test_rename(self, datetime_series):
ts = datetime_series
renamer = lambda x: x.strftime("%Y%m%d")
renamed = ts.rename(renamer)
assert renamed.index[0] == renamer(ts.index[0])
# dict
rename_dict = dict(zip(ts.index, renamed.index, strict=True))
... | TestRename |
python | django__django | django/core/servers/basehttp.py | {
"start": 2085,
"end": 2696
} | class ____(simple_server.WSGIServer):
"""BaseHTTPServer that implements the Python WSGI protocol"""
request_queue_size = 10
def __init__(self, *args, ipv6=False, allow_reuse_address=True, **kwargs):
if ipv6:
self.address_family = socket.AF_INET6
self.allow_reuse_address = allow... | WSGIServer |
python | huggingface__transformers | src/transformers/models/hiera/modeling_hiera.py | {
"start": 2451,
"end": 4097
} | class ____(ModelOutput):
r"""
pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*, returned when `add_pooling_layer=True` is passed):
Average pooling of the last layer hidden-state.
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):
... | HieraModelOutput |
python | django__django | tests/model_enums/tests.py | {
"start": 880,
"end": 7698
} | class ____(SimpleTestCase):
def test_integerchoices(self):
self.assertEqual(
Suit.choices, [(1, "Diamond"), (2, "Spade"), (3, "Heart"), (4, "Club")]
)
self.assertEqual(Suit.labels, ["Diamond", "Spade", "Heart", "Club"])
self.assertEqual(Suit.values, [1, 2, 3, 4])
... | ChoicesTests |
python | allegroai__clearml | clearml/automation/monitor.py | {
"start": 230,
"end": 6349
} | class ____(object):
"""
Base class for monitoring Tasks on the system.
Inherit to implement specific logic
"""
def __init__(self) -> ():
self._timestamp = None
self._previous_timestamp = None
self._task_name_filter = None
self._project_names_re = None
self._p... | Monitor |
python | weaviate__weaviate-python-client | weaviate/collections/iterator.py | {
"start": 1014,
"end": 2794
} | class ____(
Generic[TProperties, TReferences],
Iterable[Object[TProperties, TReferences]],
):
def __init__(
self,
query: _FetchObjectsQuery[Any, Any],
inputs: _IteratorInputs[TProperties, TReferences],
cache_size: Optional[int] = None,
) -> None:
self.__query = qu... | _ObjectIterator |
python | pytorch__pytorch | tools/gen_vulkan_spv.py | {
"start": 15794,
"end": 25048
} | class ____:
tile_size: list[int]
layouts: list[str]
weight_storage_type: str = ""
bias_storage_type: str = ""
register_for: tuple[str, list[str]] | None = None
def getName(filePath: str) -> str:
return os.path.basename(filePath).replace("/", "_").replace(".", "_")
def isDescriptorLine(lineSt... | ShaderInfo |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/autoVariance1.py | {
"start": 937,
"end": 1223
} | class ____[T]:
def method1(self) -> "ShouldBeCovariant2[T]": ...
vco3_1: ShouldBeCovariant3[float] = ShouldBeCovariant3[int]()
# This should generate an error based on variance.
vco3_2: ShouldBeCovariant3[int] = ShouldBeCovariant3[float]()
@dataclass(frozen=True)
| ShouldBeCovariant3 |
python | donnemartin__interactive-coding-challenges | recursion_dynamic/matrix_mult/test_find_min_cost.py | {
"start": 18,
"end": 718
} | class ____(unittest.TestCase):
def test_find_min_cost(self):
matrix_mult_cost = MatrixMultiplicationCost()
self.assertRaises(TypeError, matrix_mult_cost.find_min_cost, None)
self.assertEqual(matrix_mult_cost.find_min_cost([]), 0)
matrices = [Matrix(2, 3),
Matrix(... | TestMatrixMultiplicationCost |
python | pyinstaller__pyinstaller | bootloader/waflib/Build.py | {
"start": 25285,
"end": 26353
} | class ____(BuildContext):
'''cleans the project'''
cmd = 'clean'
def execute(self):
self.restore()
if not self.all_envs:
self.load_envs()
self.recurse([self.run_dir])
try:
self.clean()
finally:
self.store()
def clean(self):
... | CleanContext |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_tcp_port.py | {
"start": 700,
"end": 1692
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_tcp_port"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(c... | ColumnValuesToBeValidTcpPort |
python | ansible__ansible | test/lib/ansible_test/_internal/ci/__init__.py | {
"start": 2579,
"end": 2705
} | class ____(ApplicationError):
"""Exception for cases where change detection is not supported."""
| ChangeDetectionNotSupported |
python | PyCQA__pylint | doc/data/messages/n/notimplemented-raised/good.py | {
"start": 0,
"end": 66
} | class ____:
def bore(self):
raise NotImplementedError
| Worm |
python | walkccc__LeetCode | solutions/14. Longest Common Prefix/14.py | {
"start": 0,
"end": 284
} | class ____:
def longestCommonPrefix(self, strs: list[str]) -> str:
if not strs:
return ''
for i in range(len(strs[0])):
for j in range(1, len(strs)):
if i == len(strs[j]) or strs[j][i] != strs[0][i]:
return strs[0][:i]
return strs[0]
| Solution |
python | pytorch__pytorch | tools/code_coverage/package/tool/parser/llvm_coverage_parser.py | {
"start": 177,
"end": 2339
} | class ____:
"""
Accepts a parsed json produced by llvm-cov export -- typically,
representing a single C++ test and produces a list
of CoverageRecord(s).
"""
def __init__(self, llvm_coverage: dict[str, Any]) -> None:
self._llvm_coverage = llvm_coverage
@staticmethod
def _skip_c... | LlvmCoverageParser |
python | spack__spack | lib/spack/spack/llnl/util/lock.py | {
"start": 6389,
"end": 25326
} | class ____:
"""This is an implementation of a filesystem lock using Python's lockf.
In Python, ``lockf`` actually calls ``fcntl``, so this should work with
any filesystem implementation that supports locking through the fcntl
calls. This includes distributed filesystems like Lustre (when flock
is ... | Lock |
python | spyder-ide__spyder | spyder/plugins/remoteclient/widgets/connectionpages.py | {
"start": 2312,
"end": 30643
} | class ____(SpyderConfigPage, SpyderFontsMixin):
"""Base class to create connection pages."""
MIN_HEIGHT = 450
NEW_CONNECTION = False
CONF_SECTION = "remoteclient"
def __init__(self, parent, host_id=None):
super().__init__(parent)
# host_id is None only for the new connection page
... | BaseConnectionPage |
python | apache__airflow | providers/apache/flink/src/airflow/providers/apache/flink/sensors/flink_kubernetes.py | {
"start": 1199,
"end": 5878
} | class ____(BaseSensorOperator):
"""
Checks flinkDeployment object in kubernetes cluster.
.. seealso::
For more detail about Flink Deployment Object have a look at the reference:
https://nightlies.apache.org/flink/flink-kubernetes-operator-docs-main/docs/custom-resource/reference/#flinkdeplo... | FlinkKubernetesSensor |
python | allegroai__clearml | clearml/backend_api/services/v2_23/models.py | {
"start": 51310,
"end": 52511
} | class ____(Response):
"""
Response of models.delete_metadata endpoint.
:param updated: Number of models updated (0 or 1)
:type updated: int
"""
_service = "models"
_action = "delete_metadata"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
... | DeleteMetadataResponse |
python | tensorflow__tensorflow | tensorflow/compiler/tests/fake_quant_ops_test.py | {
"start": 946,
"end": 4793
} | class ____(xla_test.XLATestCase):
"""Test cases for FakeQuantWithMinMaxArgs operation."""
# 8 bits, wide range.
def testOp_with8BitsNoScalingNoNudging(self):
self._TestOp(0.0, 255.0, 8, False, 0.0, 255.0, 1.0)
def testOp_with8BitsScalingAndNudgingDown(self):
self._TestOp(0.5, 128.0, 8, False, 0.0, 127... | FakeQuantWithMinMaxArgsTest |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/super_without_brackets.py | {
"start": 0,
"end": 97
} | class ____:
@staticmethod
def speak():
return f"This animal says something."
| Animal |
python | kamyu104__LeetCode-Solutions | Python/my-calendar-ii.py | {
"start": 31,
"end": 586
} | class ____(object):
def __init__(self):
self.__overlaps = []
self.__calendar = []
def book(self, start, end):
"""
:type start: int
:type end: int
:rtype: bool
"""
for i, j in self.__overlaps:
if start < j and end > i:
... | MyCalendarTwo |
python | realpython__materials | tic-tac-toe-ai-python/source_code_bonus/tic-tac-toe/library/src/tic_tac_toe/logic/minimax.py | {
"start": 149,
"end": 3268
} | class ____:
DEFAULT_FILENAME = "minimax.json"
@staticmethod
def key(move: Move) -> str:
return move.before_state.grid.cells + move.after_state.grid.cells
@staticmethod
@cache
def load(filename: str = DEFAULT_FILENAME) -> dict:
with resources.open_text(__package__, filename) as ... | MinimaxSerializer |
python | dagster-io__dagster | examples/with_wandb/with_wandb/assets/model_registry_example.py | {
"start": 459,
"end": 1381
} | class ____(Config):
model_registry: str
@asset(
compute_kind="wandb",
name="registered-model",
ins={"artifact": AssetIn(key=MODEL_NAME)},
output_required=False,
)
def promote_best_model_to_production(
artifact: Artifact,
config: PromoteBestModelToProductionConfig,
):
"""Example that li... | PromoteBestModelToProductionConfig |
python | getsentry__sentry | src/sentry/models/savedsearch.py | {
"start": 1977,
"end": 4420
} | class ____(Model):
"""
A saved search query.
"""
__relocation_scope__ = RelocationScope.Organization
organization = FlexibleForeignKey("sentry.Organization", null=True)
type = models.PositiveSmallIntegerField(default=SearchType.ISSUE.value)
name = models.CharField(max_length=128)
query ... | SavedSearch |
python | numba__numba | numba/tests/enum_usecases.py | {
"start": 202,
"end": 513
} | class ____(Enum):
MERCURY = (3.303e+23, 2.4397e6)
VENUS = (4.869e+24, 6.0518e6)
EARTH = (5.976e+24, 6.37814e6)
MARS = (6.421e+23, 3.3972e6)
JUPITER = (1.9e+27, 7.1492e7)
SATURN = (5.688e+26, 6.0268e7)
URANUS = (8.686e+25, 2.5559e7)
NEPTUNE = (1.024e+26, 2.4746e7)
| Planet |
python | weaviate__weaviate-python-client | profiling/test_refs.py | {
"start": 2205,
"end": 9294
} | class ____:
title: str
datePublished: str
somestring: str
counter: int
author: Reference
hasParagraphs: Reference
uuid: uuid_lib.UUID = field(init=False)
class_name: str = field(init=False)
def to_data_object(self) -> DataObject:
return DataObject(
{"title": self... | Article |
python | jina-ai__jina | tests/integration/instrumentation/__init__.py | {
"start": 2569,
"end": 5481
} | class ____(Executor):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.failure_counter = 0
@requests(on='/search')
def empty(self, docs: DocumentArray, tracing_context: Optional[Context], **kwargs):
if self.tracer:
with self.tracer.start_span('... | ExecutorFailureWithTracing |
python | anthropics__anthropic-sdk-python | src/anthropic/lib/tools/_beta_runner.py | {
"start": 12974,
"end": 21299
} | class ____(
BaseToolRunner[BetaAsyncRunnableTool, ResponseFormatT], Generic[RunnerItemT, ResponseFormatT], ABC
):
def __init__(
self,
*,
params: ParseMessageCreateParamsBase[ResponseFormatT],
options: RequestOptions,
tools: Iterable[BetaAsyncRunnableTool],
client:... | BaseAsyncToolRunner |
python | django__django | tests/gis_tests/rasterapp/models.py | {
"start": 450,
"end": 675
} | class ____(models.Model):
rastermodel = models.ForeignKey(RasterModel, models.CASCADE)
class Meta:
required_db_features = ["supports_raster"]
def __str__(self):
return str(self.id)
| RasterRelatedModel |
python | pypa__warehouse | warehouse/cli/db/dbml.py | {
"start": 1873,
"end": 6685
} | class ____(TypedDict):
fields: dict[str, FieldInfo]
relationships: list[RelationshipInfo]
comment: NotRequired[str]
def generate_dbml_file(tables: Iterable[Table], _output: str | None) -> None:
file = click.open_file(_output, "w") if _output else click.open_file("-", "w")
tables_info = {}
for... | TableInfo |
python | pypa__pip | tests/unit/test_req_file.py | {
"start": 5363,
"end": 6679
} | class ____(Protocol):
def __call__(
self,
line: str,
filename: str,
line_number: int,
finder: PackageFinder | None = None,
options: Values | None = None,
session: PipSession | None = None,
constraint: bool = False,
) -> list[InstallRequirement]: ..... | LineProcessor |
python | getsentry__sentry | tests/sentry/web/frontend/test_oauth_authorize.py | {
"start": 27066,
"end": 31275
} | class ____(TestCase):
"""Tests for organization-scoped OAuth flows using custom URI schemes with strict matching (version 1)."""
@cached_property
def path(self) -> str:
return "/oauth/authorize/"
def setUp(self) -> None:
super().setUp()
self.owner = self.create_user(email="admi... | OAuthAuthorizeOrgScopedCustomSchemeStrictTest |
python | scipy__scipy | scipy/optimize/_dual_annealing.py | {
"start": 15609,
"end": 16089
} | class ____:
def __init__(self, func, maxfun=1e7, *args):
self.func = func
self.args = args
# Number of objective function evaluations
self.nfev = 0
# Number of gradient function evaluation if used
self.ngev = 0
# Number of hessian of the objective function if... | ObjectiveFunWrapper |
python | PrefectHQ__prefect | tests/blocks/test_core.py | {
"start": 76369,
"end": 80907
} | class ____:
def test_to_block_type_from_block(self, test_block: Type[Block]):
block_type = test_block._to_block_type()
assert block_type.name == test_block.__name__
assert str(block_type.logo_url) == str(test_block._logo_url)
assert str(block_type.documentation_url) == str(test_bloc... | TestToBlockType |
python | django__django | django/contrib/postgres/validators.py | {
"start": 345,
"end": 666
} | class ____(MaxLengthValidator):
message = ngettext_lazy(
"List contains %(show_value)d item, it should contain no more than "
"%(limit_value)d.",
"List contains %(show_value)d items, it should contain no more than "
"%(limit_value)d.",
"show_value",
)
| ArrayMaxLengthValidator |
python | numpy__numpy | numpy/lib/tests/test_arraypad.py | {
"start": 42967,
"end": 48371
} | class ____:
def test_check_simple(self):
a = np.arange(100)
a = np.pad(a, (25, 20), 'wrap')
b = np.array(
[75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
95, 96, 97, 98, 99,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
... | TestWrap |
python | python__mypy | mypy/report.py | {
"start": 4702,
"end": 6695
} | class ____(AbstractReporter):
def __init__(self, reports: Reports, output_dir: str) -> None:
super().__init__(reports, output_dir)
self.counts: dict[str, tuple[int, int, int, int]] = {}
def on_file(
self,
tree: MypyFile,
modules: dict[str, MypyFile],
type_map: di... | LineCountReporter |
python | django-guardian__django-guardian | guardian/testapp/tests/test_admin.py | {
"start": 19732,
"end": 21042
} | class ____(TestCase):
org_installed_apps = copy.copy(settings.INSTALLED_APPS)
def _get_gma(self, attrs=None, name=None, model=None):
"""
Returns ``GuardedModelAdmin`` instance.
"""
attrs = attrs or {}
name = str(name or "GMA")
model = model or User
GMA = ... | GrappelliGuardedModelAdminTests |
python | doocs__leetcode | lcof/面试题04. 二维数组中的查找/Solution2.py | {
"start": 0,
"end": 451
} | class ____:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
if not matrix or not matrix[0]:
return False
m, n = len(matrix), len(matrix[0])
i, j = m - 1, 0
while i >= 0 and j < n:
if matrix[i][j] == target:
return T... | Solution |
python | django-haystack__django-haystack | test_haystack/test_indexes.py | {
"start": 24901,
"end": 25041
} | class ____(indexes.ModelSearchIndex):
def get_model(self):
return ManyToManyLeftSideModel
| ModelWithManyToManyFieldModelSearchIndex |
python | scrapy__scrapy | tests/test_addons.py | {
"start": 362,
"end": 658
} | class ____:
def update_settings(self, settings):
pass
def get_addon_cls(config: dict[str, Any]) -> type:
class AddonWithConfig:
def update_settings(self, settings: BaseSettings):
settings.update(config, priority="addon")
return AddonWithConfig
| SimpleAddon |
python | ray-project__ray | python/ray/autoscaler/_private/resource_demand_scheduler.py | {
"start": 1497,
"end": 2784
} | class ____:
"""This fancy class just defines the `UtilizationScore` protocol to be
some type that is a "totally ordered set" (i.e. things that can be sorted).
What we're really trying to express is
```
UtilizationScore = TypeVar("UtilizationScore", bound=Comparable["UtilizationScore"])
```
... | UtilizationScore |
python | Textualize__textual | tests/command_palette/test_events.py | {
"start": 493,
"end": 2153
} | class ____(App[None]):
COMMANDS = {SimpleSource}
def __init__(self) -> None:
super().__init__()
self.events: list[CommandPaletteEvent] = []
def on_mount(self) -> None:
self.action_command_palette()
@on(CommandPalette.Opened)
@on(CommandPalette.Closed)
@on(CommandPalett... | AppWithActiveCommandPalette |
python | kamyu104__LeetCode-Solutions | Python/equalize-strings-by-adding-or-removing-characters-at-ends.py | {
"start": 1444,
"end": 2056
} | class ____(object):
def minOperations(self, initial, target):
"""
:type initial: str
:type target: str
:rtype: int
"""
result = 0
for k in xrange(2):
for i in xrange(k, len(initial)):
curr = 0
for j in xrange(min(len... | Solution2 |
python | sympy__sympy | sympy/series/series_class.py | {
"start": 180,
"end": 2673
} | class ____(Expr):
"""Base Class for series"""
@property
def interval(self):
"""The interval on which the series is defined"""
raise NotImplementedError("(%s).interval" % self)
@property
def start(self):
"""The starting point of the series. This point is included"""
... | SeriesBase |
python | PrefectHQ__prefect | tests/server/models/test_saved_searches.py | {
"start": 4622,
"end": 5567
} | class ____:
async def test_delete_saved_search(self, session):
# create a saved_search to delete
saved_search = await models.saved_searches.create_saved_search(
session=session,
saved_search=schemas.core.SavedSearch(
name="My SavedSearch",
),
... | TestDeleteSavedSearch |
python | pytorch__pytorch | torch/_dynamo/variables/ctx_manager.py | {
"start": 52314,
"end": 54263
} | class ____(VariableTracker):
_nonvar_fields = {
"target",
*VariableTracker._nonvar_fields,
}
def __init__(
self,
ctx: Union[ContextWrappingVariable, GenericContextWrappingVariable],
target: Any,
**kwargs: Any,
) -> None:
super().__init__(**kwargs)... | WithExitFunctionVariable |
python | doocs__leetcode | solution/0500-0599/0554.Brick Wall/Solution.py | {
"start": 0,
"end": 278
} | class ____:
def leastBricks(self, wall: List[List[int]]) -> int:
cnt = Counter()
for row in wall:
s = 0
for x in row[:-1]:
s += x
cnt[s] += 1
return len(wall) - max(cnt.values(), default=0)
| Solution |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/lib/metadata_service/models/generated/ConnectorBreakingChanges.py | {
"start": 1791,
"end": 2163
} | class ____(BaseModel):
class Config:
extra = Extra.forbid
__root__: Dict[constr(regex=r"^\d+\.\d+\.\d+$"), VersionBreakingChange] = Field(
...,
description="Each entry denotes a breaking change in a specific version of a connector that requires user action to upgrade.",
title="C... | ConnectorBreakingChanges |
python | tornadoweb__tornado | tornado/test/util_test.py | {
"start": 6330,
"end": 6467
} | class ____(unittest.TestCase):
def test_unicode_escapes(self):
self.assertEqual(utf8("\u00e9"), b"\xc3\xa9")
| UnicodeLiteralTest |
python | huggingface__transformers | src/transformers/models/encoder_decoder/modeling_encoder_decoder.py | {
"start": 2571,
"end": 23142
} | class ____(PreTrainedModel, GenerationMixin):
r"""
[`EncoderDecoderModel`] is a generic model class that will be instantiated as a transformer architecture with one
of the base model classes of the library as encoder and another one as decoder when created with the
:meth*~transformers.AutoModel.from_pre... | EncoderDecoderModel |
python | apache__airflow | providers/openlineage/src/airflow/providers/openlineage/extractors/bash.py | {
"start": 1134,
"end": 2583
} | class ____(BaseExtractor):
"""
Extract executed bash command and put it into SourceCodeJobFacet.
This extractor provides visibility on what bash task does by extracting
executed bash command and putting it into SourceCodeJobFacet. It does
not extract datasets.
:meta private:
"""
@clas... | BashExtractor |
python | huggingface__transformers | src/transformers/models/bigbird_pegasus/configuration_bigbird_pegasus.py | {
"start": 806,
"end": 8590
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`BigBirdPegasusModel`]. It is used to instantiate
an BigBirdPegasus model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield ... | BigBirdPegasusConfig |
python | pytorch__pytorch | test/distributed/_composable/fsdp/test_fully_shard_extensions.py | {
"start": 5574,
"end": 7136
} | class ____:
@property
def world_size(self) -> int:
return 2
@contextlib.contextmanager
def _patch_two_tensor_fsdp_all_gather(self, pre_all_gather_version: int):
lock = threading.Lock()
if pre_all_gather_version == 1:
TwoTensor.fsdp_pre_all_gather = two_tensor_fsdp_pr... | TestFullyShardAllGatherExtensionsCommon |
python | dask__dask | dask/dataframe/dask_expr/_groupby.py | {
"start": 2418,
"end": 4660
} | class ____:
"""User defined groupby-aggregation.
This class allows users to define their own custom aggregation in terms of
operations on Pandas dataframes in a map-reduce style. You need to specify
what operation to do on each chunk of data, how to combine those chunks of
data together, and then h... | Aggregation |
python | ray-project__ray | python/ray/tests/test_task_metrics.py | {
"start": 12461,
"end": 16755
} | class ____:
async def f(self):
await asyncio.sleep(300)
a = A.remote()
ray.get([a.f.remote() for _ in range(40)])
"""
proc = run_string_as_driver_nonblocking(driver)
expected = {
"RUNNING": 30.0,
"SUBMITTED_TO_WORKER": 10.0,
"FINISHED": 1.0,
}
wait_for_condition(
... | A |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 460912,
"end": 472825
} | class ____(DatumChannelMixin, core.PositionDatumDefBase):
"""
RadiusDatum schema wrapper.
Parameters
----------
bandPosition : float
Relative position on a band of a stacked, binned, time unit, or band scale. For
example, the marks will be positioned at the beginning of the band if ... | RadiusDatum |
python | walkccc__LeetCode | solutions/835. Image Overlap/835.py | {
"start": 0,
"end": 584
} | class ____:
def largestOverlap(self, img1: list[list[int]], img2: list[list[int]]) -> int:
MAGIC = 100
ones1 = [(i, j)
for i, row in enumerate(img1)
for j, num in enumerate(row)
if num == 1]
ones2 = [(i, j)
for i, row in enumerate(img2)
for ... | Solution |
python | huggingface__transformers | src/transformers/models/granitemoehybrid/modeling_granitemoehybrid.py | {
"start": 41439,
"end": 42401
} | class ____(nn.Module):
"""
MLP layer for shared experts
Args:
config:
Configuration object with model hyperparameters.
"""
def __init__(self, config: GraniteMoeHybridConfig):
super().__init__()
self.input_size = config.hidden_size
self.hidden_size = con... | GraniteMoeHybridMLP |
python | dagster-io__dagster | python_modules/libraries/dagster-shared/dagster_shared/libraries/__init__.py | {
"start": 3586,
"end": 4669
} | class ____(Exception):
pass
def get_pypi_package_data(pkg_name: str, timeout: float = 5.0) -> dict[str, Any]:
# defer for import performance
import urllib.request
from urllib.error import HTTPError, URLError
url = f"https://pypi.org/pypi/{pkg_name}/json"
try:
with urllib.request.urlo... | DagsterPyPiAccessError |
python | docker__docker-py | docker/models/configs.py | {
"start": 70,
"end": 537
} | class ____(Model):
"""A config."""
id_attribute = 'ID'
def __repr__(self):
return f"<{self.__class__.__name__}: '{self.name}'>"
@property
def name(self):
return self.attrs['Spec']['Name']
def remove(self):
"""
Remove this config.
Raises:
:p... | Config |
python | spyder-ide__spyder | spyder/plugins/remoteclient/api/modules/base.py | {
"start": 1058,
"end": 6235
} | class ____(metaclass=ABCMeta):
"""
Base class for Jupyter API plugins.
This class must be subclassed to implement the API for a specific
Jupyter extension. It provides a connection method and context manager.
"""
request_timeout = REQUEST_TIMEOUT
verify_ssl = VERIFY_SSL
@abstract_attr... | SpyderBaseJupyterAPI |
python | google__jax | jax/experimental/pallas/ops/gpu/blackwell_ragged_dot_mgpu.py | {
"start": 1171,
"end": 15803
} | class ____:
tile_m: int
tile_n: int
tile_k: int
max_concurrent_steps: int
collective: bool
grid_tile_width: int
grid_minor_dim: blackwell_matmul_mgpu.MatmulDimension
epilogue_tile_n: int = 64
def __str__(self):
return "_".join(f"{k}={v}" for k, v in dataclasses.asdict(self).items())
# TODO(just... | TuningConfig |
python | huggingface__transformers | src/transformers/models/clap/modeling_clap.py | {
"start": 20011,
"end": 20844
} | class ____(nn.Module):
def __init__(self, config, dim, num_heads, window_size):
super().__init__()
self.self = ClapAudioSelfAttention(config, dim, num_heads, window_size)
self.output = ClapAudioSelfOutput(config, dim)
def forward(
self,
hidden_states: torch.Tensor,
... | ClapAudioAttention |
python | pandas-dev__pandas | pandas/core/computation/expr.py | {
"start": 24112,
"end": 25611
} | class ____:
"""
Object encapsulating an expression.
Parameters
----------
expr : str
engine : str, optional, default 'numexpr'
parser : str, optional, default 'pandas'
env : Scope, optional, default None
level : int, optional, default 2
"""
env: Scope
engine: str
pa... | Expr |
python | pydantic__pydantic | pydantic/v1/networks.py | {
"start": 15718,
"end": 16018
} | class ____(AnyUrl):
allowed_schemes = {'mongodb'}
# TODO: Needed to generic "Parts" for "Replica Set", "Sharded Cluster", and other mongodb deployment modes
@staticmethod
def get_default_parts(parts: 'Parts') -> 'Parts':
return {
'port': '27017',
}
| MongoDsn |
python | networkx__networkx | networkx/classes/tests/test_multigraph.py | {
"start": 17775,
"end": 18777
} | class ____(TestMultiGraph):
def setup_method(self):
self.Graph = MultiGraphSubClass
# build K3
self.k3edges = [(0, 1), (0, 2), (1, 2)]
self.k3nodes = [0, 1, 2]
self.K3 = self.Graph()
self.K3._adj = self.K3.adjlist_outer_dict_factory(
{
0: s... | TestMultiGraphSubclass |
python | walkccc__LeetCode | solutions/272. Closest Binary Search Tree Value II/272.py | {
"start": 0,
"end": 489
} | class ____:
def closestKValues(
self,
root: TreeNode | None,
target: float,
k: int,
) -> list[int]:
dq = collections.deque()
def inorder(root: TreeNode | None) -> None:
if not root:
return
inorder(root.left)
dq.append(root.val)
inorder(root.right)
... | Solution |
python | spyder-ide__spyder | spyder/plugins/editor/widgets/codeeditor/tests/test_classfunc_selector.py | {
"start": 353,
"end": 521
} | class ____: # Block number 4
def __init__(self):
pass
def hello_1(self): # Block number 9
pass
def hello_2(self):
pass
| SomeObject |
python | streamlit__streamlit | lib/streamlit/elements/html.py | {
"start": 1287,
"end": 7263
} | class ____:
@gather_metrics("html")
def html(
self,
body: str | Path | SupportsStr | SupportsReprHtml,
*, # keyword-only arguments:
width: Width = "stretch",
unsafe_allow_javascript: bool = False,
) -> DeltaGenerator:
"""Insert HTML into your app.
Ad... | HtmlMixin |
python | TheAlgorithms__Python | graphs/minimum_spanning_tree_kruskal2.py | {
"start": 283,
"end": 1395
} | class ____[T]:
# Disjoint Set DataStructure
def __init__(self) -> None:
# map from node name to the node object
self.map: dict[T, DisjointSetTreeNode[T]] = {}
def make_set(self, data: T) -> None:
# create a new set with x as its member
self.map[data] = DisjointSetTreeNode(da... | DisjointSetTree |
python | joerick__pyinstrument | pyinstrument/renderers/base.py | {
"start": 889,
"end": 3798
} | class ____(Renderer):
"""
An abstract base class for renderers that process Frame objects using
processor functions. Provides a common interface to manipulate the
processors before rendering.
"""
processors: ProcessorList
"""
Processors installed on this renderer. This property is defin... | FrameRenderer |
python | tensorflow__tensorflow | tensorflow/python/keras/engine/training_utils_v1.py | {
"start": 76022,
"end": 77545
} | class ____(object):
"""TrainingLoop is a wrapper class around the training logic.
This class is trying to encapsulate the different logic of fit/eval/predict
with regard to different data input and model condition.
Note that TrainingLoop is stateless, which means it doesn't contain any
internal field and ca... | TrainingLoop |
python | scipy__scipy | scipy/linalg/tests/test_lapack.py | {
"start": 56255,
"end": 138869
} | class ____:
"""
Tests for the blocked QR factorization, namely through geqrt, gemqrt, tpqrt
and tpmqr.
"""
def test_geqrt_gemqrt(self):
rng = np.random.RandomState(1234)
for ind, dtype in enumerate(DTYPES):
n = 20
if ind > 1:
A = (rng.rand(n,... | TestBlockedQR |
python | google__jax | jax/_src/pallas/mosaic/core.py | {
"start": 1305,
"end": 1393
} | class ____(enum.Enum):
TC = 0
SC_SCALAR_SUBCORE = 1
SC_VECTOR_SUBCORE = 2
| KernelType |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.