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 | pallets__flask | tests/test_helpers.py | {
"start": 6141,
"end": 6970
} | class ____:
"""Test Flasks are created without import.
Avoiding ``__import__`` helps create Flask instances where there are errors
at import time. Those runtime errors will be apparent to the user soon
enough, but tools which build Flask instances meta-programmatically benefit
from a Flask which d... | TestNoImports |
python | tensorflow__tensorflow | tensorflow/python/util/module_wrapper.py | {
"start": 3063,
"end": 10217
} | class ____(FastModuleType):
"""Wrapper for TF modules to support deprecation messages and lazyloading."""
# Ensures that compat.v1 API usage is recorded at most once
compat_v1_usage_recorded = False
def __init__(
self,
wrapped,
module_name,
public_apis=None,
deprecation=True,
... | TFModuleWrapper |
python | pypa__warehouse | warehouse/organizations/models.py | {
"start": 7749,
"end": 7843
} | class ____(str, enum.Enum):
Community = "Community"
Company = "Company"
| OrganizationType |
python | pandas-dev__pandas | pandas/tests/window/test_groupby.py | {
"start": 40342,
"end": 47203
} | class ____:
@pytest.mark.parametrize(
"method, expected_data",
[
["mean", [0.0, 0.6666666666666666, 1.4285714285714286, 2.2666666666666666]],
["std", [np.nan, 0.707107, 0.963624, 1.177164]],
["var", [np.nan, 0.5, 0.9285714285714286, 1.3857142857142857]],
]... | TestEWM |
python | PrefectHQ__prefect | tests/events/server/test_in_memory_ordering.py | {
"start": 8115,
"end": 10451
} | class ____:
async def test_record_and_forget_follower(
self,
causal_ordering: CausalOrdering,
event_one: ReceivedEvent,
event_two: ReceivedEvent,
):
# Initially no followers
assert await causal_ordering.get_followers(event_one) == []
# Record follower
... | TestFollowerLeaderTracking |
python | tensorflow__tensorflow | tensorflow/python/debug/cli/debugger_cli_common_test.py | {
"start": 44586,
"end": 45241
} | class ____(test_util.TensorFlowTestCase):
def testGetVersionWithoutDependencies(self):
out = debugger_cli_common.get_tensorflow_version_lines()
self.assertEqual(2, len(out.lines))
self.assertEqual("TensorFlow version: %s" % pywrap_tf_session.__version__,
out.lines[0])
def testGetV... | GetTensorFlowVersionLinesTest |
python | ansible__ansible | test/units/module_utils/common/test_sys_info.py | {
"start": 4604,
"end": 5812
} | class ____:
class LinuxTest:
pass
class Foo(LinuxTest):
platform = "Linux"
distribution = None
class Bar(LinuxTest):
platform = "Linux"
distribution = "Bar"
def test_not_linux(self):
# if neither match, the fallback should be the top-level class
... | TestGetPlatformSubclass |
python | tornadoweb__tornado | tornado/test/testing_test.py | {
"start": 1864,
"end": 2618
} | class ____(AsyncTestCase):
def tearDown(self):
super().tearDown()
# Trigger a gc to make warnings more deterministic.
gc.collect()
def test_leaked_coroutine(self):
# This test verifies that "leaked" coroutines are shut down
# without triggering warnings like "task was de... | LeakTest |
python | getsentry__sentry | tests/sentry/users/models/test_user_merge_verification_code.py | {
"start": 391,
"end": 1569
} | class ____(TestCase):
@freeze_time()
def test_regenerate_token(self) -> None:
code = UserMergeVerificationCode(user=self.user)
token = code.token
code.expires_at = datetime(2025, 3, 14, 5, 32, 21, tzinfo=UTC)
code.save()
code.regenerate_token()
assert code.token ... | TestUserMergeVerificationCode |
python | getsentry__sentry | src/sentry/integrations/msteams/link_identity.py | {
"start": 1180,
"end": 2002
} | class ____(MsTeamsIdentityLinkageView, LinkIdentityView):
def get_success_template_and_context(
self, params: Mapping[str, Any], integration: Integration | None
) -> tuple[str, dict[str, Any]]:
return "sentry/integrations/msteams/linked.html", {}
def notify_on_success(
self, externa... | MsTeamsLinkIdentityView |
python | django__django | tests/forms_tests/tests/test_renderers.py | {
"start": 849,
"end": 1103
} | class ____(SimpleTestCase):
def test_get_renderer(self):
with self.assertRaisesMessage(
NotImplementedError, "subclasses must implement get_template()"
):
BaseRenderer().get_template("")
| BaseTemplateRendererTests |
python | django__django | tests/select_related_onetoone/models.py | {
"start": 31,
"end": 139
} | class ____(models.Model):
username = models.CharField(max_length=100)
email = models.EmailField()
| User |
python | pypa__hatch | backend/src/hatchling/metadata/custom.py | {
"start": 260,
"end": 1424
} | class ____:
PLUGIN_NAME = "custom"
def __new__( # type: ignore[misc]
cls,
root: str,
config: dict[str, Any],
*args: Any,
**kwargs: Any,
) -> MetadataHookInterface:
build_script = config.get("path", DEFAULT_BUILD_SCRIPT)
if not isinstance(build_script... | CustomMetadataHook |
python | huggingface__transformers | src/transformers/models/sam3_video/modeling_sam3_video.py | {
"start": 20832,
"end": 92333
} | class ____(Sam3VideoPreTrainedModel):
all_tied_weights_keys = {}
def __init__(self, config: Sam3VideoConfig):
super().__init__(config)
self.config = config
self.detector_model = AutoModel.from_config(config.detector_config)
self.tracker_model = AutoModel.from_config(config.track... | Sam3VideoModel |
python | tensorflow__tensorflow | tensorflow/compiler/mlir/quantization/tensorflow/python/integration_test/quantize_model_test_base.py | {
"start": 2667,
"end": 52416
} | class ____(test.TestCase, parameterized.TestCase):
"""Base test class for TF-quant tests."""
def setUp(self) -> None:
super().setUp()
# Many test cases for quantization involve creating and saving the input
# model and saving the output quantized model. These two member
# attributes can be used to... | QuantizedModelTest |
python | numpy__numpy | numpy/lib/tests/test_function_base.py | {
"start": 74422,
"end": 77403
} | class ____:
def test_forward(self):
x = np.arange(-6, 5)
bins = np.arange(-5, 5)
assert_array_equal(digitize(x, bins), np.arange(11))
def test_reverse(self):
x = np.arange(5, -6, -1)
bins = np.arange(5, -5, -1)
assert_array_equal(digitize(x, bins), np.arange(11)... | TestDigitize |
python | charliermarsh__ruff | crates/ruff_python_parser/resources/valid/statement/class.py | {
"start": 119,
"end": 171
} | class ____:
def method():
a, b = data
| Test |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 57698,
"end": 58041
} | class ____(BaseModel):
usage: Optional["Usage"] = Field(default=None, description="")
time: Optional[float] = Field(default=None, description="Time spent to process this request")
status: Optional[str] = Field(default=None, description="")
result: Optional["CountResult"] = Field(default=None, descriptio... | InlineResponse20019 |
python | kamyu104__LeetCode-Solutions | Python/maximum-balanced-subsequence-sum.py | {
"start": 2341,
"end": 4402
} | class ____(object):
def maxBalancedSubsequenceSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
NEG_INF = float("-inf")
# Range Maximum Query
class SegmentTree(object):
def __init__(self, N,
build_fn=lambda _: None... | Solution3 |
python | kamyu104__LeetCode-Solutions | Python/second-minimum-time-to-reach-destination.py | {
"start": 1933,
"end": 3461
} | class ____(object):
def secondMinimum(self, n, edges, time, change):
"""
:type n: int
:type edges: List[List[int]]
:type time: int
:type change: int
:rtype: int
"""
INF = float("inf")
def bfs(adj, start):
q = [start]
dis... | Solution2 |
python | fluentpython__example-code | attic/iterables/vector.py | {
"start": 1354,
"end": 2546
} | class ____:
"""An n-dimensional vector"""
def __init__(self, *components): # <1>
self._components = tuple(components) # <2>
def __repr__(self):
return 'Vector' + (reprlib.repr(self._components)) # <3>
def __iter__(self):
return iter(self._components) # <4>
def __abs__... | Vector |
python | PrefectHQ__prefect | tests/runtime/test_task_run.py | {
"start": 3385,
"end": 3818
} | class ____:
async def test_tags_is_attribute(self):
assert "tags" in dir(task_run)
async def test_tags_is_empty_when_not_set(self):
assert task_run.tags == []
async def test_tags_returns_tags_when_present_dynamically(self):
with TaskRunContext.model_construct(
task_run=... | TestTags |
python | tensorflow__tensorflow | tensorflow/python/data/ops/readers.py | {
"start": 14741,
"end": 18690
} | class ____(dataset_ops.DatasetV2):
"""A `Dataset` comprising records from one or more TFRecord files.
This dataset loads TFRecords from the files as bytes, exactly as they were
written.`TFRecordDataset` does not do any parsing or decoding on its own.
Parsing and decoding can be done by applying `Dataset.map` t... | TFRecordDatasetV2 |
python | kamyu104__LeetCode-Solutions | Python/subarrays-with-xor-at-least-k.py | {
"start": 92,
"end": 2427
} | class ____(object):
def countXorSubarrays(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
class Trie(object):
def __init__(self, bit_length):
self.__lefts = [-1]*(1+(1+len(nums))*bit_length) # preallocate to speed up... | Solution |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-scrapegraph/examples/scrapegraph-smartscraper-lama-index.py | {
"start": 367,
"end": 661
} | class ____(BaseModel):
"""Schema for representing a company founder."""
name: str = Field(description="Name of the founder")
role: str = Field(description="Role of the founder")
social_media: str = Field(description="Social media URL of the founder", default="N/A")
| FounderSchema |
python | huggingface__transformers | src/transformers/processing_utils.py | {
"start": 24590,
"end": 24790
} | class ____(TypedDict, total=False):
processor_kwargs: ProcessingKwargs
mm_load_kwargs: ChatTemplateLoadKwargs
template_kwargs: ProcessorChatTemplateKwargs
@dataclass
| AllKwargsForChatTemplate |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/cloud_tasks.py | {
"start": 1274,
"end": 2125
} | class ____(BaseGoogleLink):
"""Helper class for constructing Cloud Task Queue Link."""
name = "Cloud Tasks Queue"
key = "cloud_task_queue"
format_str = CLOUD_TASKS_QUEUE_LINK
@staticmethod
def extract_parts(queue_name: str | None):
"""
Extract project_id, location and queue id ... | CloudTasksQueueLink |
python | google__jax | jax/experimental/mosaic/gpu/constraints.py | {
"start": 2454,
"end": 2632
} | class ____:
expression: Expression
axes: tuple[int, ...]
def __str__(self):
return f"Reduce([{self.axes}], {self.expression})"
@dataclasses.dataclass(frozen=True)
| Reduce |
python | great-expectations__great_expectations | great_expectations/core/serdes.py | {
"start": 178,
"end": 322
} | class ____(BaseModel):
datasource: _IdentifierBundle
asset: _IdentifierBundle
batch_definition: _IdentifierBundle
| _EncodedValidationData |
python | FactoryBoy__factory_boy | tests/test_regression.py | {
"start": 208,
"end": 294
} | class ____(T.NamedTuple):
fullname: str
pseudonym: T.Optional[str] = None
| Author |
python | walkccc__LeetCode | solutions/2517. Maximum Tastiness of Candy Basket/2517.py | {
"start": 0,
"end": 510
} | class ____:
def maximumTastiness(self, price: list[int], k: int) -> int:
price.sort()
def numBaskets(m: int) -> int:
"""Returns the number of baskets we can pick for m tastiness."""
baskets = 0
prevPrice = -m
for p in price:
if p >= prevPrice + m:
prevPrice = p
... | Solution |
python | huggingface__transformers | tests/models/bart/test_modeling_bart.py | {
"start": 15788,
"end": 21979
} | class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(BartModel, BartForConditionalGeneration, BartForSequenceClassification, BartForQuestionAnswering)
if is_torch_available()
else ()
)
pipeline_model_mapping = (
{... | BartModelTest |
python | allegroai__clearml | clearml/datasets/dataset.py | {
"start": 2815,
"end": 3293
} | class ____(object):
link = attrib(default=None, type=str)
relative_path = attrib(default=None, type=str)
parent_dataset_id = attrib(default=None, type=str)
size = attrib(default=None, type=int)
hash = attrib(default=None, type=str)
def as_dict(self) -> Dict:
return dict(
lin... | LinkEntry |
python | sphinx-doc__sphinx | sphinx/registry.py | {
"start": 2529,
"end": 24032
} | class ____:
def __init__(self) -> None:
#: special attrgetter for autodoc; class object -> attrgetter
self.autodoc_attrgetters: dict[type, Callable[[Any, str, Any], Any]] = {}
#: builders; a dict of builder name -> builder class
self.builders: dict[str, type[Builder]] = {}
... | SphinxComponentRegistry |
python | google__pytype | pytype/load_pytd_test.py | {
"start": 536,
"end": 1034
} | class ____(test_base.UnitTest):
"""Tests for load_pytd.Module."""
def test_is_package(self):
for filename, is_package in [
("foo/bar.pyi", False),
("foo/__init__.pyi", True),
("foo/__init__.pyi-1", True),
("foo/__init__.pickled", True),
(os.devnull, True),
]:
w... | ModuleTest |
python | kamyu104__LeetCode-Solutions | Python/find-if-digit-game-can-be-won.py | {
"start": 56,
"end": 425
} | class ____(object):
def canAliceWin(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
total1 = total2 = 0
for x in nums:
if x < 10:
total1 += x
else:
total2 += x
return total1 != total2
# Time: O... | Solution |
python | PrefectHQ__prefect | src/prefect/client/schemas/actions.py | {
"start": 22324,
"end": 22826
} | class ____(ActionBaseModel):
"""Data used by the Prefect REST API to update a v2 concurrency limit."""
active: Optional[bool] = Field(default=None)
name: Optional[Name] = Field(default=None)
limit: Optional[NonNegativeInteger] = Field(default=None)
active_slots: Optional[NonNegativeInteger] = Field... | ConcurrencyLimitV2Update |
python | doocs__leetcode | solution/1200-1299/1284.Minimum Number of Flips to Convert Binary Matrix to Zero Matrix/Solution.py | {
"start": 0,
"end": 1135
} | class ____:
def minFlips(self, mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
state = sum(1 << (i * n + j) for i in range(m) for j in range(n) if mat[i][j])
q = deque([state])
vis = {state}
ans = 0
dirs = [0, -1, 0, 1, 0, 0]
while q:
fo... | Solution |
python | streamlit__streamlit | lib/tests/streamlit/web/server/stats_handler_test.py | {
"start": 1090,
"end": 5801
} | class ____(tornado.testing.AsyncHTTPTestCase):
def get_app(self):
self.mock_stats = []
mock_stats_manager = MagicMock()
mock_stats_manager.get_stats = MagicMock(side_effect=lambda: self.mock_stats)
return tornado.web.Application(
[
(
rf... | StatsHandlerTest |
python | prabhupant__python-ds | data_structures/segment_tree/seg_tree_max.py | {
"start": 12,
"end": 1456
} | class ____():
def __init__(self, n, arr = None):
self._t = [-sys.maxsize - 1] * (4 * n)
self._n = n
if arr: self._build(arr, 1 , 0 , n - 1)
def _build(self, a, v, tl, tr):
if tl == tr:
self._t[v] = a[tl]
else:
tm = (tl + tr) // 2
self... | MaxSegTree |
python | scikit-learn__scikit-learn | sklearn/utils/_param_validation.py | {
"start": 24032,
"end": 28589
} | class ____:
"""Class encapsulating a constraint not meant to be exposed to the user.
Parameters
----------
constraint : str or _Constraint instance
The constraint to be used internally.
"""
def __init__(self, constraint):
self.constraint = constraint
def generate_invalid_para... | Hidden |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/datafusion.py | {
"start": 1667,
"end": 2092
} | class ____:
"""Data Fusion pipeline states."""
PENDING = "PENDING"
STARTING = "STARTING"
RUNNING = "RUNNING"
SUSPENDED = "SUSPENDED"
RESUMING = "RESUMING"
COMPLETED = "COMPLETED"
FAILED = "FAILED"
KILLED = "KILLED"
REJECTED = "REJECTED"
FAILURE_STATES = [PipelineStates.FAILED,... | PipelineStates |
python | mahmoud__boltons | boltons/statsutils.py | {
"start": 5764,
"end": 6396
} | class ____:
def __init__(self, name, func):
self.name = name
self.func = func
self.internal_name = '_' + name
doc = func.__doc__ or ''
pre_doctest_doc, _, _ = doc.partition('>>>')
self.__doc__ = pre_doctest_doc
def __get__(self, obj, objtype=None):
if ob... | _StatsProperty |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/externalmodule/package.py | {
"start": 217,
"end": 431
} | class ____(Package):
homepage = "http://somewhere.com"
url = "http://somewhere.com/module-1.0.tar.gz"
version("1.0", md5="1234567890abcdef1234567890abcdef")
depends_on("externalprereq")
| Externalmodule |
python | walkccc__LeetCode | solutions/2673. Make Costs of Paths Equal in a Binary Tree/2673.py | {
"start": 0,
"end": 395
} | class ____:
def minIncrements(self, n: int, cost: list[int]) -> int:
ans = 0
for i in range(n // 2 - 1, -1, -1):
l = i * 2 + 1
r = i * 2 + 2
ans += abs(cost[l] - cost[r])
# Record the information in the parent from the children. So, there's need to actually
# update the values i... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/override1.py | {
"start": 1812,
"end": 1859
} | class ____:
def method1(self):
pass
| F |
python | getsentry__sentry | tests/sentry/rules/conditions/test_every_event.py | {
"start": 199,
"end": 473
} | class ____(RuleTestCase):
rule_cls = EveryEventCondition
def test_applies_correctly(self) -> None:
rule = self.get_rule()
self.assertPasses(rule, self.event, is_new=True)
self.assertPasses(rule, self.event, is_new=False)
| EveryEventConditionTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-iterable/source_iterable/streams.py | {
"start": 4553,
"end": 9307
} | class ____(IterableStream, CheckpointMixin, ABC):
"""
This stream utilize "export" Iterable api for getting large amount of data.
It can return data in form of new line separater strings each of each
representing json object.
Data could be windowed by date ranges by applying startDateTime and
en... | IterableExportStream |
python | conda__conda | conda/api.py | {
"start": 14511,
"end": 17516
} | class ____:
"""
**Beta** While in beta, expect both major and minor changes across minor releases.
High-level management and usage of conda environment prefixes.
"""
def __init__(self, prefix_path):
"""
**Beta** While in beta, expect both major and minor changes across minor releas... | PrefixData |
python | optuna__optuna | optuna/trial/_fixed.py | {
"start": 758,
"end": 6419
} | class ____(BaseTrial):
"""A trial class which suggests a fixed value for each parameter.
This object has the same methods as :class:`~optuna.trial.Trial`, and it suggests pre-defined
parameter values. The parameter values can be determined at the construction of the
:class:`~optuna.trial.FixedTrial` ob... | FixedTrial |
python | pallets__flask | src/flask/json/tag.py | {
"start": 3863,
"end": 4193
} | class ____(JSONTag):
__slots__ = ()
key = " t"
def check(self, value: t.Any) -> bool:
return isinstance(value, tuple)
def to_json(self, value: t.Any) -> t.Any:
return [self.serializer.tag(item) for item in value]
def to_python(self, value: t.Any) -> t.Any:
return tuple(val... | TagTuple |
python | instagram__MonkeyType | monkeytype/db/base.py | {
"start": 1926,
"end": 2398
} | class ____(CallTraceLogger):
"""A CallTraceLogger that stores logged traces in a CallTraceStore."""
def __init__(self, store: CallTraceStore) -> None:
self.store = store
self.traces: List[CallTrace] = []
def log(self, trace: CallTrace) -> None:
if not trace.func.__module__ == "__ma... | CallTraceStoreLogger |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/asyncpg.py | {
"start": 16506,
"end": 16666
} | class ____(Protocol):
async def start(self) -> None: ...
async def commit(self) -> None: ...
async def rollback(self) -> None: ...
| _AsyncpgTransaction |
python | crytic__slither | slither/slithir/variables/reference.py | {
"start": 313,
"end": 2153
} | class ____(Variable):
def __init__(self, node: "Node", index: Optional[int] = None) -> None:
super().__init__()
if index is None:
self._index = node.compilation_unit.counter_slithir_reference
node.compilation_unit.counter_slithir_reference += 1
else:
self.... | ReferenceVariable |
python | spyder-ide__spyder | external-deps/qtconsole/qtconsole/call_tip_widget.py | {
"start": 161,
"end": 10683
} | class ____(QtWidgets.QLabel):
""" Shows call tips by parsing the current text of Q[Plain]TextEdit.
"""
#--------------------------------------------------------------------------
# 'QObject' interface
#--------------------------------------------------------------------------
def __init__(self... | CallTipWidget |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/basecamp/tests.py | {
"start": 244,
"end": 1538
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = BasecampProvider.id
def get_mocked_response(self):
return MockedResponse(
HTTPStatus.OK,
"""
{
"expires_at": "2012-03-22T16:56:48-05:00",
"identity": {
"id": 9999999,
... | BasecampTests |
python | pytorch__pytorch | torch/_inductor/pattern_matcher.py | {
"start": 15275,
"end": 16341
} | class ____(ABC):
"""
Base class for types of patterns.
"""
@abstractmethod
def _match(self, node: torch.fx.Node, ctx: MatchContext) -> MatchResult: ...
def match(self, node: torch.fx.Node) -> MatchResult:
try:
return MatchContext([self], graph=node.graph).match(self, node)
... | PatternExpr |
python | jazzband__django-oauth-toolkit | tests/test_scopes.py | {
"start": 4786,
"end": 11832
} | class ____(BaseTest):
def test_scopes_protection_valid(self):
"""
Test access to a scope protected resource with correct scopes provided
"""
self.oauth2_settings.PKCE_REQUIRED = False
self.client.login(username="test_user", password="123456")
# retrieve a valid autho... | TestScopesProtection |
python | oauthlib__oauthlib | oauthlib/oauth2/rfc6749/errors.py | {
"start": 4344,
"end": 4412
} | class ____(OAuth2Error):
error = 'missing_token'
| MissingTokenError |
python | ApeWorX__ape | tests/functional/test_plugins.py | {
"start": 12722,
"end": 15248
} | class ____:
def test_version_range(self):
actual = ape_version.version_range
expected = f">=0.{ape_version[2]},<0.{int(ape_version[2]) + 1}"
assert actual == expected
def test_next_version_range(self):
actual = ape_version.next_version_range
expected = f">=0.{int(ape_ver... | TestApeVersion |
python | wireservice__csvkit | tests/test_utilities/test_csvformat.py | {
"start": 198,
"end": 2716
} | class ____(CSVKitTestCase, EmptyFileTests):
Utility = CSVFormat
def test_launch_new_instance(self):
with patch.object(sys, 'argv', [self.Utility.__name__.lower(), 'examples/dummy.csv']):
launch_new_instance()
def test_skip_lines(self):
self.assertLines(['--skip-lines', '3', '-D... | TestCSVFormat |
python | gevent__gevent | src/greentest/3.13/test_queue.py | {
"start": 22523,
"end": 22601
} | class ____(LifoQueueTest, unittest.TestCase):
queue = c_queue
| CLifoQueueTest |
python | pytorch__pytorch | torch/nn/modules/flatten.py | {
"start": 1723,
"end": 5760
} | class ____(Module):
r"""
Unflattens a tensor dim expanding it to a desired shape. For use with :class:`~nn.Sequential`.
* :attr:`dim` specifies the dimension of the input tensor to be unflattened, and it can
be either `int` or `str` when `Tensor` or `NamedTensor` is used, respectively.
* :attr:`... | Unflatten |
python | huggingface__transformers | src/transformers/models/prophetnet/modeling_prophetnet.py | {
"start": 52258,
"end": 65891
} | class ____(ProphetNetPreTrainedModel):
def __init__(self, config: ProphetNetConfig):
super().__init__(config)
self.ngram = config.ngram
self.num_buckets = config.num_buckets
self.relative_max_distance = config.relative_max_distance
self.dropout = config.dropout
self.... | ProphetNetDecoder |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-motherduck/destination_motherduck/destination.py | {
"start": 1665,
"end": 1854
} | class ____(AirbyteStateMessage):
"""Declare the `id` attribute that platform sends."""
id: int | None = None
"""Injected by the platform."""
@dataclass
| PatchedAirbyteStateMessage |
python | numba__numba | numba/core/untyped_passes.py | {
"start": 3294,
"end": 4069
} | class ____(FunctionPass):
_name = "fixup_args"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
state['nargs'] = state['func_ir'].arg_count
if not state['args'] and state['flags'].force_pyobject:
# Allow an empty argument types specification wh... | FixupArgs |
python | astropy__astropy | astropy/visualization/wcsaxes/tests/test_frame.py | {
"start": 1043,
"end": 4620
} | class ____(BaseImageTests):
@figure_test(tolerance=0.5)
def test_custom_frame(self):
wcs = WCS(self.msx_header)
fig = Figure(figsize=(4, 4))
ax = WCSAxes(fig, [0.15, 0.15, 0.7, 0.7], wcs=wcs, frame_class=HexagonalFrame)
fig.add_axes(ax)
ax.coords.grid(color="white")
... | TestFrame |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_superfences.py | {
"start": 9063,
"end": 9951
} | class ____(util.MdCase):
"""Test highlight line wraps."""
extension = ['pymdownx.highlight', 'pymdownx.superfences']
extension_configs = {
'pymdownx.highlight': {
'line_anchors': '__my_span',
'linenums_style': 'pymdownx-inline'
}
}
def test_linespans(self):
... | TestHighlightLineAnchorsPymdownxInline |
python | pytest-dev__pytest | testing/test_assertion.py | {
"start": 44278,
"end": 53093
} | class ____:
# The number of lines in the truncation explanation message. Used
# to calculate that results have the expected length.
LINES_IN_TRUNCATION_MSG = 2
def test_doesnt_truncate_when_input_is_empty_list(self) -> None:
expl: list[str] = []
result = truncate._truncate_explanation(e... | TestTruncateExplanation |
python | huggingface__transformers | src/transformers/models/xlm_roberta/modeling_xlm_roberta.py | {
"start": 39017,
"end": 42783
} | class ____(XLMRobertaPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.config = config
self.classifier = XLMRobertaClassificationHead(config)
self.roberta = XLMRobertaModel(config, add_pooling_layer=False)
... | XLMRobertaForSequenceClassification |
python | sympy__sympy | sympy/combinatorics/pc_groups.py | {
"start": 214,
"end": 1308
} | class ____(DefaultPrinting):
is_group = True
is_solvable = True
def __init__(self, pc_sequence, pc_series, relative_order, collector=None):
"""
Parameters
==========
pc_sequence : list
A sequence of elements whose classes generate the cyclic factor
... | PolycyclicGroup |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws_tests/ecs_tests/stubbed_ecs.py | {
"start": 1674,
"end": 2324
} | class ____:
def __init__(self, region_name):
storage = StubStorage()
self.stubs = defaultdict(
lambda: StubbedEcs(
# Hack: Build the client from the Session because we monkeypatch
# boto3.client elsewhere to return an instance of this class and
... | ThreadsafeStubbedEcs |
python | django__django | tests/prefetch_related/tests.py | {
"start": 19024,
"end": 43487
} | class ____(TestCase):
@classmethod
def traverse_qs(cls, obj_iter, path):
"""
Helper method that returns a list containing a list of the objects in
the obj_iter. Then for each object in the obj_iter, the path will be
recursively travelled and the found objects are added to the ret... | CustomPrefetchTests |
python | sympy__sympy | sympy/stats/crv_types.py | {
"start": 114470,
"end": 117267
} | class ____(SingleContinuousDistribution):
_argnames = ('n',)
@property
def set(self):
return Interval(0, self.n)
@staticmethod
def check(n):
_value_check((n > 0, n.is_integer),
"Parameter n must be positive integer.")
def pdf(self, x):
n = self.n
k = Du... | UniformSumDistribution |
python | sympy__sympy | sympy/liealgebras/type_b.py | {
"start": 77,
"end": 4547
} | class ____(Standard_Cartan):
def __new__(cls, n):
if n < 2:
raise ValueError("n cannot be less than 2")
return Standard_Cartan.__new__(cls, "B", n)
def dimension(self):
"""Dimension of the vector space V underlying the Lie algebra
Examples
========
... | TypeB |
python | huggingface__transformers | tests/models/udop/test_modeling_udop.py | {
"start": 21789,
"end": 22725
} | class ____(unittest.TestCase):
@cached_property
def image(self):
ds = load_dataset("hf-internal-testing/fixtures_docvqa", split="test")
return ds[1]["image"]
@cached_property
def processor(self):
return UdopProcessor.from_pretrained("microsoft/udop-large")
@cached_property
... | UdopModelIntegrationTests |
python | tensorflow__tensorflow | tensorflow/python/feature_column/sequence_feature_column_test.py | {
"start": 1771,
"end": 5822
} | class ____(test.TestCase, parameterized.TestCase):
"""Tests the utility fn concatenate_context_input."""
def test_concatenate_context_input(self):
seq_input = ops.convert_to_tensor(np.arange(12).reshape(2, 3, 2))
context_input = ops.convert_to_tensor(np.arange(10).reshape(2, 5))
seq_input = math_ops.ca... | ConcatenateContextInputTest |
python | simonw__sqlite-utils | sqlite_utils/db.py | {
"start": 5990,
"end": 6055
} | class ____(Exception):
"Specified table does not exist"
| NoTable |
python | allegroai__clearml | clearml/backend_api/services/v2_23/models.py | {
"start": 40910,
"end": 42624
} | class ____(Request):
"""
Delete a model.
:param model: Model ID
:type model: str
:param force: Force. Required if there are tasks that use the model as an
execution model, or if the model's creating task is published.
:type force: bool
"""
_service = "models"
_action = "del... | DeleteRequest |
python | jazzband__django-oauth-toolkit | tests/admin.py | {
"start": 35,
"end": 112
} | class ____(admin.ModelAdmin):
list_display = ("id",)
| CustomApplicationAdmin |
python | encode__django-rest-framework | rest_framework/fields.py | {
"start": 58488,
"end": 58776
} | class ____(Field):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.allow_blank = True
self.allow_null = True
def to_internal_value(self, data):
return data
def to_representation(self, value):
return value
| _UnvalidatedField |
python | getsentry__sentry | tests/sentry/snuba/test_metrics_enhanced_performance.py | {
"start": 630,
"end": 3727
} | class ____(MetricsEnhancedPerformanceTestCase, SnubaTestCase):
def setUp(self) -> None:
super().setUp()
self.snuba_params = SnubaParams(
organization=self.organization.id,
projects=[self.project],
start=before_now(days=1),
end=self.now,
)
... | MetricsEnhancedPerformanceTest |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/tests/test_bases.py | {
"start": 240,
"end": 3208
} | class ____:
class DummyStep(steps.Step):
title = "Dummy step"
max_retries = 3
max_duration = timedelta(seconds=2)
async def _run(self, run_duration: timedelta) -> steps.StepResult:
await anyio.sleep(run_duration.total_seconds())
return steps.StepResult(step=s... | TestStep |
python | django__django | django/contrib/gis/db/models/functions.py | {
"start": 9735,
"end": 9966
} | class ____:
@cached_property
def output_field(self):
return DistanceField(self.geo_field)
def source_is_geography(self):
return self.geo_field.geography and self.geo_field.srid == 4326
| DistanceResultMixin |
python | sqlalchemy__sqlalchemy | test/ext/asyncio/test_session.py | {
"start": 24347,
"end": 25541
} | class ____(AsyncFixture):
run_inserts = None
@classmethod
def setup_mappers(cls):
User, Address = cls.classes("User", "Address")
users, addresses = cls.tables("users", "addresses")
cls.mapper(
User,
users,
properties={
"addresses"... | AsyncCascadesTest |
python | h5py__h5py | h5py/tests/test_dataset.py | {
"start": 79887,
"end": 81593
} | class ____(BaseDataset):
"""
Test the symmetry of operators, at least with the numpy types.
Issue: https://github.com/h5py/h5py/issues/1947
"""
def test_numpy_commutative(self,):
"""
Create a h5py dataset, extract one element convert to numpy
Check that it returns symmetric r... | TestCommutative |
python | coleifer__peewee | tests/models.py | {
"start": 1895,
"end": 2060
} | class ____(TestModel):
name = CharField()
city = ForeignKeyField(City, backref='venues')
city_n = ForeignKeyField(City, backref='venues_n', null=True)
| Venue |
python | PyCQA__pylint | tests/functional/a/async_functions.py | {
"start": 314,
"end": 387
} | class ____:
@staticmethod
def test():
return 42
| OtherClass |
python | jmcnamara__XlsxWriter | xlsxwriter/feature_property_bag.py | {
"start": 354,
"end": 4283
} | class ____(xmlwriter.XMLwriter):
"""
A class for writing the Excel XLSX FeaturePropertyBag file.
"""
###########################################################################
#
# Public API.
#
###########################################################################
def __ini... | FeaturePropertyBag |
python | huggingface__transformers | src/transformers/models/qwen3_vl/modular_qwen3_vl.py | {
"start": 15594,
"end": 17855
} | class ____(LlamaRotaryEmbedding):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: Qwen3VLTextConfig, device=None):
super().__init__(config, device=device)
self.mrope_section = config.rope_parameters.get("mrope_section", [24, 20, 20])
def apply_interl... | Qwen3VLTextRotaryEmbedding |
python | gevent__gevent | src/gevent/resolver/dnspython.py | {
"start": 11053,
"end": 12975
} | class ____(object):
def __init__(self):
self.hosts_resolver = _HostsResolver()
self.network_resolver = resolver.get_default_resolver()
self.network_resolver.cache = resolver.LRUCache()
def query(self, qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN,
tcp=False, so... | _DualResolver |
python | fastapi__sqlmodel | docs_src/tutorial/fastapi/update/tutorial001_py39.py | {
"start": 469,
"end": 2281
} | class ____(SQLModel):
name: Optional[str] = None
secret_name: Optional[str] = None
age: Optional[int] = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
connect_args = {"check_same_thread": False}
engine = create_engine(sqlite_url, echo=True, connect_args=connect_args)
... | HeroUpdate |
python | weaviate__weaviate-python-client | weaviate/groups/async_.py | {
"start": 165,
"end": 312
} | class ____:
def __init__(self, connection: ConnectionAsync):
self.oidc = _GroupsOIDCAsync(connection)
@executor.wrap("sync")
| _GroupsAsync |
python | bokeh__bokeh | src/bokeh/models/formatters.py | {
"start": 13745,
"end": 28853
} | class ____(TickFormatter):
''' A ``TickFormatter`` for displaying datetime values nicely across a
range of scales.
``DatetimeTickFormatter`` has the following properties (listed together
with their default values) that can be used to control the formatting
of axis ticks at different scales:
{d... | DatetimeTickFormatter |
python | numba__numba | numba/core/datamodel/models.py | {
"start": 26916,
"end": 27619
} | class ____(StructModel):
def __init__(self, dmm, fe_type):
payload_type = types.SetPayload(fe_type.container)
members = [
# The meminfo data points to a SetPayload (shared with the
# original set object)
('meminfo', types.MemInfoPointer(payload_type)),
... | SetIterModel |
python | allegroai__clearml | clearml/backend_api/services/v2_9/models.py | {
"start": 61832,
"end": 66505
} | class ____(Response):
"""
Response of models.get_by_id endpoint.
:param model: Model info
:type model: Model
"""
_service = "models"
_action = "get_by_id"
_version = "2.9"
_schema = {
"definitions": {
"model": {
"properties": {
... | GetByIdResponse |
python | PrefectHQ__prefect | src/prefect/events/schemas/events.py | {
"start": 764,
"end": 2173
} | class ____(Labelled):
"""An observable business object of interest to the user"""
@model_validator(mode="after")
def enforce_maximum_labels(self) -> Self:
if len(self.root) > PREFECT_EVENTS_MAXIMUM_LABELS_PER_RESOURCE.value():
raise ValueError(
"The maximum number of lab... | Resource |
python | optuna__optuna | optuna/samplers/nsgaii/_crossovers/_blxalpha.py | {
"start": 295,
"end": 1675
} | class ____(BaseCrossover):
"""Blend Crossover operation used by :class:`~optuna.samplers.NSGAIISampler`.
Uniformly samples child individuals from the hyper-rectangles created
by the two parent individuals. For further information about BLX-alpha crossover,
please refer to the following paper:
- `E... | BLXAlphaCrossover |
python | tensorflow__tensorflow | tensorflow/python/keras/engine/base_layer_v1.py | {
"start": 3301,
"end": 96367
} | class ____(base_layer.Layer):
"""Base layer class.
This is the class from which all layers inherit.
A layer is a class implementing common neural networks operations, such
as convolution, batch norm, etc. These operations require managing weights,
losses, updates, and inter-layer connectivity.
Users will... | Layer |
python | kamyu104__LeetCode-Solutions | Python/minimum-number-of-valid-strings-to-form-target-i.py | {
"start": 3316,
"end": 3786
} | class ____(object):
def minValidStrings(self, words, target):
"""
:type words: List[str]
:type target: str
:rtype: int
"""
trie = AhoTrie(words)
dp = [0]*(len(target)+1)
for i in xrange(len(target)):
l = trie.step(target[i])
if ... | Solution2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.