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 | google__pytype | pytype/tools/traces/traces_test.py | {
"start": 11137,
"end": 12139
} | class ____(MatchAstTestCase):
def test_basic(self):
matches = self._get_traces("lambda x: x.upper()", ast.Lambda)
sym = "<lambda>"
self.assertTracesEqual(
matches, [((1, 0), "MAKE_FUNCTION", sym, ("Callable[[Any], Any]",))])
def test_function_locals(self):
matches = self._get_traces("""
... | MatchLambdaTest |
python | ansible__ansible | lib/ansible/playbook/base.py | {
"start": 29575,
"end": 33809
} | class ____(FieldAttributeBase):
name = NonInheritableFieldAttribute(isa='string', default='', always_post_validate=True)
# connection/transport
connection = ConnectionFieldAttribute(isa='string', default=context.cliargs_deferred_get('connection'))
port = FieldAttribute(isa='int')
remote_user = Fie... | Base |
python | getsentry__sentry | tests/sentry/api/endpoints/test_api_applications.py | {
"start": 209,
"end": 875
} | class ____(APITestCase):
def test_simple(self) -> None:
app1 = ApiApplication.objects.create(owner=self.user, name="a")
app2 = ApiApplication.objects.create(owner=self.user, name="b")
ApiApplication.objects.create(owner=self.create_user("foo@example.com"))
self.login_as(self.user)
... | ApiApplicationsListTest |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/lib/metadata_service/models/generated/ConnectorMetadataDefinitionV0.py | {
"start": 6090,
"end": 6787
} | class ____(BaseModel):
class Config:
extra = Extra.forbid
commit_sha: Optional[str] = Field(
None,
description="The git commit sha of the last commit that modified this file.",
)
commit_timestamp: Optional[datetime] = Field(
None,
description="The git commit time... | GitInfo |
python | spack__spack | lib/spack/spack/cmd/stage.py | {
"start": 441,
"end": 3646
} | class ____:
"""
Encapsulation of reasons to skip staging
"""
def __init__(self, exclusions, skip_installed):
"""
:param exclusions: A list of specs to skip if satisfied.
:param skip_installed: A boolean indicating whether to skip already installed specs.
"""
self... | StageFilter |
python | pallets__click | src/click/exceptions.py | {
"start": 9042,
"end": 9561
} | class ____(ClickException):
"""Raised if a file cannot be opened."""
def __init__(self, filename: str, hint: str | None = None) -> None:
if hint is None:
hint = _("unknown error")
super().__init__(hint)
self.ui_filename: str = format_filename(filename)
self.filename... | FileError |
python | django__django | tests/gis_tests/geos_tests/test_mutable_list.py | {
"start": 1306,
"end": 17053
} | class ____(SimpleTestCase):
"""
Tests base class ListMixin by comparing a list clone which is
a ListMixin subclass with a real Python list.
"""
limit = 3
listType = UserListA
def lists_of_len(self, length=None):
if length is None:
length = self.limit
pl = list(r... | ListMixinTest |
python | mwaskom__seaborn | seaborn/_stats/aggregation.py | {
"start": 413,
"end": 1252
} | class ____(Stat):
"""
Aggregate data along the value axis using given method.
Parameters
----------
func : str or callable
Name of a :class:`pandas.Series` method or a vector -> scalar function.
See Also
--------
objects.Est : Aggregation with error bars.
Examples
----... | Agg |
python | doocs__leetcode | solution/3100-3199/3165.Maximum Sum of Subsequence With Non-adjacent Elements/Solution.py | {
"start": 63,
"end": 263
} | class ____:
__slots__ = "l", "r", "s00", "s01", "s10", "s11"
def __init__(self, l: int, r: int):
self.l = l
self.r = r
self.s00 = self.s01 = self.s10 = self.s11 = 0
| Node |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/util/langhelpers.py | {
"start": 48928,
"end": 50664
} | class ____(int):
"""A constant symbol.
>>> symbol("foo") is symbol("foo")
True
>>> symbol("foo")
<symbol 'foo>
A slight refinement of the MAGICCOOKIE=object() pattern. The primary
advantage of symbol() is its repr(). They are also singletons.
Repeated calls of symbol('name') will al... | symbol |
python | ray-project__ray | python/ray/_private/ray_logging/constants.py | {
"start": 783,
"end": 1317
} | class ____(str, Enum):
# Core context
JOB_ID = "job_id"
WORKER_ID = "worker_id"
NODE_ID = "node_id"
ACTOR_ID = "actor_id"
TASK_ID = "task_id"
ACTOR_NAME = "actor_name"
TASK_NAME = "task_name"
TASK_FUNCTION_NAME = "task_func_name"
# Logger built-in context
ASCTIME = "asctime"... | LogKey |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_getnewargs/invalid_getnewargs_returned.py | {
"start": 1201,
"end": 1308
} | class ____:
""" Uninferable return value """
__getnewargs__ = lambda self: Missing
| AmbigousGetNewArgs |
python | huggingface__transformers | src/transformers/models/esm/modeling_esm.py | {
"start": 19666,
"end": 20847
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.layer = nn.ModuleList([EsmLayer(config) for _ in range(config.num_hidden_layers)])
self.emb_layer_norm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.grad... | EsmEncoder |
python | PrefectHQ__prefect | src/prefect/server/database/orm_models.py | {
"start": 28142,
"end": 31910
} | class ____(Base):
"""SQLAlchemy model of a deployment."""
name: Mapped[str]
version: Mapped[Optional[str]]
description: Mapped[Optional[str]] = mapped_column(sa.Text())
work_queue_name: Mapped[Optional[str]] = mapped_column(index=True)
infra_overrides: Mapped[dict[str, Any]] = mapped_column(
... | Deployment |
python | numpy__numpy | numpy/random/tests/test_generator_mt19937.py | {
"start": 1571,
"end": 2793
} | class ____:
def test_scalar(self):
s = Generator(MT19937(0))
assert_equal(s.integers(1000), 479)
s = Generator(MT19937(4294967295))
assert_equal(s.integers(1000), 324)
def test_array(self):
s = Generator(MT19937(range(10)))
assert_equal(s.integers(1000), 465)
... | TestSeed |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/hooks/test_cosmos.py | {
"start": 1452,
"end": 12687
} | class ____:
# Set up an environment to test with
@pytest.fixture(autouse=True)
def setup_test_cases(self, create_mock_connection):
# set up some test variables
self.test_end_point = "https://test_endpoint:443"
self.test_master_key = "magic_test_key"
self.test_database_name = ... | TestAzureCosmosDbHook |
python | PrefectHQ__prefect | src/prefect/types/_concurrency.py | {
"start": 105,
"end": 354
} | class ____(BaseModel):
"""Model for validating concurrency lease holder information."""
model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
type: Literal["flow_run", "task_run", "deployment"]
id: UUID
| ConcurrencyLeaseHolder |
python | getsentry__sentry | src/sentry/grouping/strategies/base.py | {
"start": 7907,
"end": 11533
} | class ____(Generic[ConcreteInterface]):
"""Base class for all strategies."""
def __init__(
self,
id: str,
name: str,
interface: str,
score: int | None,
func: StrategyFunc[ConcreteInterface],
):
self.id = id
self.strategy_class = id.split(":", ... | Strategy |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_ssm.py | {
"start": 4030,
"end": 10200
} | class ____:
@pytest.fixture
def mock_hook(self) -> Generator[mock.MagicMock, None, None]:
with mock.patch.object(SsmGetCommandInvocationOperator, "hook") as _hook:
yield _hook
def setup_method(self):
self.command_id = "test-command-id-123"
self.instance_id = "i-123456789... | TestSsmGetCommandInvocationOperator |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 56468,
"end": 56652
} | class ____(_ConfigBase):
preset: StopwordsPreset
additions: Optional[List[str]]
removals: Optional[List[str]]
StopwordsConfig = _StopwordsConfig
@dataclass
| _StopwordsConfig |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/classes9.py | {
"start": 591,
"end": 697
} | class ____(B1):
pass
# This should generate an error because B0.M is not
# type compatible with B1.M.
| E1 |
python | conda__conda | conda/common/configuration.py | {
"start": 9098,
"end": 13661
} | class ____(RawParameter):
# this class should encapsulate all direct use of ruamel.yaml in this module
def __init__(self, source, key, raw_value, key_comment):
self._key_comment = key_comment
super().__init__(source, key, raw_value)
if isinstance(self._raw_value, CommentedSeq):
... | YamlRawParameter |
python | kubernetes-client__python | kubernetes/client/models/v1_priority_level_configuration_condition.py | {
"start": 383,
"end": 7641
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1PriorityLevelConfigurationCondition |
python | numba__numba | numba/tests/test_parfors.py | {
"start": 30159,
"end": 31818
} | class ____(TestParforsBase):
""" Miscellaneous 'classical' numerical tests """
def test_pi(self):
def test_impl(n):
x = 2 * np.random.ranf(n) - 1
y = 2 * np.random.ranf(n) - 1
return 4 * np.sum(x**2 + y**2 < 1) / n
self.check(test_impl, 100000, decimal=1)
... | TestParforNumericalMisc |
python | readthedocs__readthedocs.org | readthedocs/core/views/hooks.py | {
"start": 580,
"end": 7190
} | class ____:
"""
Version information.
If type is None, it means that the version can be either a branch or a tag.
"""
name: str
type: Literal["branch", "tag", None]
log = structlog.get_logger(__name__)
def _build_version(project, version):
"""
Where we actually trigger builds for a ... | VersionInfo |
python | numpy__numpy | numpy/random/tests/test_randomstate.py | {
"start": 5893,
"end": 8115
} | class ____:
def test_basic(self):
random.multinomial(100, [0.2, 0.8])
def test_zero_probability(self):
random.multinomial(100, [0.2, 0.8, 0.0, 0.0, 0.0])
def test_int_negative_interval(self):
assert_(-5 <= random.randint(-5, -1) < -1)
x = random.randint(-5, -1, 5)
a... | TestMultinomial |
python | doocs__leetcode | solution/1900-1999/1998.GCD Sort of an Array/Solution.py | {
"start": 0,
"end": 685
} | class ____:
def gcdSort(self, nums: List[int]) -> bool:
n = 10**5 + 10
p = list(range(n))
f = defaultdict(list)
mx = max(nums)
for i in range(2, mx + 1):
if f[i]:
continue
for j in range(i, mx + 1, i):
f[j].append(i)
... | Solution |
python | spack__spack | lib/spack/spack/modules/tcl.py | {
"start": 2100,
"end": 2370
} | class ____(BaseContext):
"""Context class for tcl module files."""
@tengine.context_property
def prerequisites(self):
"""List of modules that needs to be loaded automatically."""
return self._create_module_list_of("specs_to_prereq")
| TclContext |
python | pyqtgraph__pyqtgraph | pyqtgraph/parametertree/parameterTypes/text.py | {
"start": 115,
"end": 530
} | class ____(WidgetParameterItem):
"""ParameterItem displaying a QTextEdit widget."""
def makeWidget(self):
self.hideWidget = False
self.asSubItem = True
self.textBox = w = QtWidgets.QTextEdit()
w.sizeHint = lambda: QtCore.QSize(300, 100)
w.value = w.toPlainText
w.... | TextParameterItem |
python | huggingface__transformers | src/transformers/models/sam3_tracker_video/modular_sam3_tracker_video.py | {
"start": 18776,
"end": 18862
} | class ____(Sam2VideoMemoryAttentionLayer):
pass
| Sam3TrackerVideoMemoryAttentionLayer |
python | pytest-dev__pytest | src/_pytest/assertion/rewrite.py | {
"start": 21894,
"end": 48206
} | class ____(ast.NodeVisitor):
"""Assertion rewriting implementation.
The main entrypoint is to call .run() with an ast.Module instance,
this will then find all the assert statements and rewrite them to
provide intermediate values and a detailed assertion error. See
http://pybites.blogspot.be/2011/0... | AssertionRewriter |
python | modin-project__modin | modin/tests/pandas/test_io.py | {
"start": 8097,
"end": 47384
} | class ____:
# delimiter tests
@pytest.mark.parametrize("sep", ["_", ",", "."])
@pytest.mark.parametrize("decimal", [".", "_"])
@pytest.mark.parametrize("thousands", [None, ",", "_", " "])
def test_read_csv_seps(self, make_csv_file, sep, decimal, thousands):
unique_filename = make_csv_file(
... | TestCsv |
python | walkccc__LeetCode | solutions/2022. Convert 1D Array Into 2D Array/2022.py | {
"start": 0,
"end": 298
} | class ____:
def construct2DArray(self, original: list[int],
m: int, n: int) -> list[list[int]]:
if len(original) != m * n:
return []
ans = [[0] * n for _ in range(m)]
for i, num in enumerate(original):
ans[i // n][i % n] = num
return ans
| Solution |
python | astropy__astropy | astropy/units/tests/test_structured.py | {
"start": 9031,
"end": 9656
} | class ____(StructuredTestBaseWithUnits):
def test_copy(self):
su_copy = copy.copy(self.pv_t_unit)
assert su_copy is not self.pv_t_unit
assert su_copy == self.pv_t_unit
assert su_copy._units is self.pv_t_unit._units
def test_deepcopy(self):
su_copy = copy.deepcopy(self.pv... | TestStructuredUnitsCopyPickle |
python | django__django | tests/files/tests.py | {
"start": 9505,
"end": 9810
} | class ____(unittest.TestCase):
def test_open_resets_file_to_start_and_returns_context_manager(self):
uf = InMemoryUploadedFile(StringIO("1"), "", "test", "text/plain", 1, "utf8")
uf.read()
with uf.open() as f:
self.assertEqual(f.read(), "1")
| InMemoryUploadedFileTests |
python | doocs__leetcode | solution/3000-3099/3068.Find the Maximum Sum of Node Values/Solution.py | {
"start": 0,
"end": 243
} | class ____:
def maximumValueSum(self, nums: List[int], k: int, edges: List[List[int]]) -> int:
f0, f1 = 0, -inf
for x in nums:
f0, f1 = max(f0 + x, f1 + (x ^ k)), max(f1 + x, f0 + (x ^ k))
return f0
| Solution |
python | Lightning-AI__lightning | tests/tests_pytorch/trainer/test_dataloaders.py | {
"start": 29862,
"end": 31319
} | class ____(Callback):
def __init__(self, expected_seeds=(0, 0, 0)):
self.expected_seed = expected_seeds
def on_train_start(self, trainer, pl_module):
train_sampler = trainer.train_dataloader.sampler
assert isinstance(train_sampler, DistributedSampler)
assert train_sampler.shuffl... | DistribSamplerCallback |
python | huggingface__transformers | tests/tensor_parallel/test_tensor_parallel.py | {
"start": 4132,
"end": 14520
} | class ____(TestCasePlus):
def test_tp_plan_property_setter_getter(self):
"""Test that tp_plan property can be set and retrieved correctly."""
model_id = "JackFram/llama-68m"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="auto")
# Test setting empty plan
model.... | TestTensorParallelProperties |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 399746,
"end": 402031
} | class ____(sgqlc.types.Interface):
"""Represents a GitHub Enterprise Importer (GEI) migration."""
__schema__ = github_schema
__field_names__ = (
"continue_on_error",
"created_at",
"database_id",
"failure_reason",
"id",
"migration_log_url",
"migration_... | Migration |
python | streamlit__streamlit | e2e_playwright/st_magic.py | {
"start": 2372,
"end": 2551
} | class ____:
"""MyClass: this help block should be printed."""
def __init__(self):
"""Should not be printed."""
MyClass
my_instance = MyClass()
my_instance
| MyClass |
python | pytorch__pytorch | test/distributed/checkpoint/e2e/test_fsdp_ep.py | {
"start": 672,
"end": 823
} | class ____(nn.Module):
def __init__(self) -> None:
super().__init__()
def forward(self, x):
raise NotImplementedError
| Dummymodel |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/instrumentation.py | {
"start": 18004,
"end": 19213
} | class ____:
"""Provide serialization of a :class:`.ClassManager`.
The :class:`.InstanceState` uses ``__init__()`` on serialize
and ``__call__()`` on deserialize.
"""
def __init__(self, state: state.InstanceState[Any], d: Dict[str, Any]):
self.class_ = state.class_
manager = state.... | _SerializeManager |
python | allegroai__clearml | clearml/backend_api/services/v2_20/models.py | {
"start": 108998,
"end": 110128
} | class ____(Request):
"""
Convert company models to public
:param ids: Ids of the models to convert
:type ids: Sequence[str]
"""
_service = "models"
_action = "make_public"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
"ids": {
... | MakePublicRequest |
python | huggingface__transformers | src/transformers/models/musicgen_melody/modeling_musicgen_melody.py | {
"start": 13434,
"end": 16634
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: MusicgenMelodyDecoderConfig, layer_idx=None):
super().__init__()
self.embed_dim = config.hidden_size
self.self_attn = MusicgenMelodyAttention(
embed_dim=self.embed_dim,
num_heads=config.num_attention_... | MusicgenMelodyDecoderLayer |
python | pypa__setuptools | setuptools/_vendor/typeguard/_exceptions.py | {
"start": 57,
"end": 218
} | class ____(UserWarning):
"""
A warning that is emitted when a type hint in string form could not be resolved to
an actual type.
"""
| TypeHintWarning |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/autoVariance1.py | {
"start": 1223,
"end": 1440
} | class ____[T]:
x: T
vo4_1: ShouldBeCovariant4[float] = ShouldBeCovariant4[int](1)
# This should generate an error based on variance.
vo4_2: ShouldBeCovariant4[int] = ShouldBeCovariant4[float](1)
| ShouldBeCovariant4 |
python | pytorch__pytorch | torch/distributed/flight_recorder/components/types.py | {
"start": 3218,
"end": 3277
} | class ____(NamedTuple):
id: int
frames: str
| Traceback |
python | astropy__astropy | astropy/units/tests/test_structured.py | {
"start": 531,
"end": 1228
} | class ____:
@classmethod
def setup_class(cls):
cls.pv_dtype = np.dtype([("p", "f8"), ("v", "f8")])
cls.pv_t_dtype = np.dtype([("pv", cls.pv_dtype), ("t", "f8")])
cls.p_unit = u.km
cls.v_unit = u.km / u.s
cls.t_unit = u.s
cls.pv_dtype = np.dtype([("p", "f8"), ("v",... | StructuredTestBase |
python | keras-team__keras | keras/src/optimizers/sgd_test.py | {
"start": 165,
"end": 3734
} | class ____(testing.TestCase):
def test_config(self):
optimizer = SGD(
learning_rate=0.5,
momentum=0.06,
nesterov=True,
weight_decay=0.004,
)
self.run_class_serialization_test(optimizer)
def test_single_step(self):
optimizer = SGD(l... | SGDTest |
python | django__django | tests/db_functions/math/test_pi.py | {
"start": 123,
"end": 381
} | class ____(TestCase):
def test(self):
FloatModel.objects.create(f1=2.5, f2=15.9)
obj = FloatModel.objects.annotate(pi=Pi()).first()
self.assertIsInstance(obj.pi, float)
self.assertAlmostEqual(obj.pi, math.pi, places=5)
| PiTests |
python | scipy__scipy | scipy/fftpack/tests/test_basic.py | {
"start": 7483,
"end": 7612
} | class ____(_TestIFFTBase):
def setup_method(self):
self.cdt = np.complex64
self.rdt = np.float32
| TestSingleIFFT |
python | walkccc__LeetCode | solutions/1838. Frequency of the Most Frequent Element/1838.py | {
"start": 0,
"end": 309
} | class ____:
def maxFrequency(self, nums: list[int], k: int) -> int:
ans = 0
summ = 0
nums.sort()
l = 0
for r, num in enumerate(nums):
summ += num
while summ + k < num * (r - l + 1):
summ -= nums[l]
l += 1
ans = max(ans, r - l + 1)
return ans
| Solution |
python | tensorflow__tensorflow | tensorflow/python/keras/callbacks.py | {
"start": 65320,
"end": 70859
} | class ____(Callback):
"""Stop training when a monitored metric has stopped improving.
Assuming the goal of a training is to minimize the loss. With this, the
metric to be monitored would be `'loss'`, and mode would be `'min'`. A
`model.fit()` training loop will check at end of every epoch whether
the loss is... | EarlyStopping |
python | ansible__ansible | test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/doc_fragments/frag.py | {
"start": 37,
"end": 261
} | class ____(object):
DOCUMENTATION = r"""
options:
normal_doc_frag:
description:
- an option
"""
OTHER_DOCUMENTATION = r"""
options:
other_doc_frag:
description:
- another option
"""
| ModuleDocFragment |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_name/invalid_name_issue_3405.py | {
"start": 151,
"end": 326
} | class ____:
"""ClassVar attribute should be matched against class-attribute-rgx, not attr-rgx"""
# class-attribute-rgx='^y$'
x: ClassVar[int] = 0 # [invalid-name]
| Foo |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/events.py | {
"start": 59408,
"end": 59961
} | class ____(_EventsHold[_ET]):
all_holds = weakref.WeakKeyDictionary()
def resolve(
self, class_: Union[Type[_T], _InternalEntityType[_T]]
) -> Optional[Mapper[_T]]:
return _mapper_or_none(class_)
# this fails on pyright if you use Any. Fails on mypy if you use _ET
class HoldMapper... | _MapperEventsHold |
python | django-extensions__django-extensions | tests/management/test_email_notifications.py | {
"start": 217,
"end": 3176
} | class ____(TestCase):
"""Tests for EmailNotificationCommand class."""
@override_settings(ADMINS=[])
@patch("sys.stdout", new_callable=StringIO)
def test_should_print_that_no_email_recipients_available(self, m_stdout):
with self.assertRaises(Exception):
call_command(
... | EmailNotificationCommandTests |
python | Netflix__metaflow | metaflow/sidecar/sidecar_messages.py | {
"start": 561,
"end": 1071
} | class ____(object):
def __init__(self, msg_type, payload):
self.msg_type = msg_type
self.payload = payload
def serialize(self):
msg = {
"msg_type": self.msg_type,
"payload": self.payload,
}
return json.dumps(msg) + "\n"
@staticmethod
def ... | Message |
python | EpistasisLab__tpot | tpot/search_spaces/nodes/genetic_feature_selection.py | {
"start": 1789,
"end": 2806
} | class ____(SelectorMixin, BaseEstimator):
"""Select predefined feature subsets."""
def __init__(self, mask, set_output_transform=None):
self.mask = mask
self.set_output_transform = set_output_transform
if set_output_transform is not None:
self.set_output(transform=set_output... | MaskSelector |
python | google__pytype | pytype/pyi/visitor.py | {
"start": 172,
"end": 1295
} | class ____(ast_visitor.BaseVisitor):
"""Base visitor for all ast visitors.
- Reraises ParseError with position information.
- Handles literal constants
- Has an optional Definitions member
"""
def __init__(self, *, filename=None, src_code=None, visit_decorators=False):
super().__init__(astlib, visit_d... | BaseVisitor |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_iter.py | {
"start": 3343,
"end": 3430
} | class ____:
def __getitem__(self, i):
return i
__iter__ = None
| NoIterClass |
python | tornadoweb__tornado | tornado/tcpclient.py | {
"start": 6934,
"end": 12135
} | class ____:
"""A non-blocking TCP connection factory.
.. versionchanged:: 5.0
The ``io_loop`` argument (deprecated since version 4.1) has been removed.
"""
def __init__(self, resolver: Optional[Resolver] = None) -> None:
if resolver is not None:
self.resolver = resolver
... | TCPClient |
python | pytorch__pytorch | test/distributed/tensor/test_dtensor_export.py | {
"start": 1964,
"end": 2296
} | class ____(torch.nn.Module):
def __init__(self, device):
super().__init__()
self.mlp_0 = MLPModule(device)
self.mlp_1 = MLPModule(device)
def forward(self, input):
if input.shape[0] > 4:
return self.mlp_0(input.sin())
return self.mlp_1(input.cos())
| SimpleModelDynamicShapes |
python | sphinx-doc__sphinx | sphinx/search/da.py | {
"start": 191,
"end": 589
} | class ____(SearchLanguage):
lang = 'da'
language_name = 'Danish'
js_stemmer_rawcode = 'danish-stemmer.js'
stopwords = DANISH_STOPWORDS
def __init__(self, options: dict[str, str]) -> None:
super().__init__(options)
self.stemmer = snowballstemmer.stemmer('danish')
def stem(self, ... | SearchDanish |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP046_0.py | {
"start": 1364,
"end": 1404
} | class ____(A[S], Generic[S]):
var: S
| B |
python | readthedocs__readthedocs.org | readthedocs/subscriptions/notifications.py | {
"start": 1732,
"end": 2965
} | class ____(SubscriptionNotificationMixin, EmailNotification):
"""
Subscription has ended a month ago.
Notify the user that the organization will be disabled soon. After this
notification is sent, we are safe to disable the organization since the
customer was notified twice.
"""
name = "org... | OrganizationDisabledNotification |
python | pyca__cryptography | tests/hazmat/primitives/test_hash_vectors.py | {
"start": 526,
"end": 864
} | class ____:
test_sha1 = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "SHA1"),
["SHA1LongMsg.rsp", "SHA1ShortMsg.rsp"],
hashes.SHA1(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.hash_supported(hashes.SHA224()),
skip_message="Does not suppo... | TestSHA1 |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/scheduler/instigation.py | {
"start": 1739,
"end": 2153
} | class ____(Enum):
# User has taken some manual action to change the status of the run instigator
RUNNING = "RUNNING"
STOPPED = "STOPPED"
# The run instigator status is controlled by its default setting in code
DECLARED_IN_CODE = "DECLARED_IN_CODE"
# DEPRECATED: use InstigatorStatus.DECLARED_IN... | InstigatorStatus |
python | redis__redis-py | tests/test_multidb/test_pipeline.py | {
"start": 10559,
"end": 20106
} | class ____:
@pytest.mark.parametrize(
"mock_multi_db_config,mock_db, mock_db1, mock_db2",
[
(
{},
{"weight": 0.2, "circuit": {"state": CBState.CLOSED}},
{"weight": 0.7, "circuit": {"state": CBState.CLOSED}},
{"weight": 0.5, ... | TestTransaction |
python | mitmproxy__pdoc | test/testdata/misc.py | {
"start": 5325,
"end": 5407
} | class ____(type):
def __call__(cls, *args, **kwargs):
pass
| Issue352bMeta |
python | numba__numba | numba/tests/test_ir_inlining.py | {
"start": 38911,
"end": 44716
} | class ____(TestCase):
def test_issue4691(self):
def output_factory(array, dtype):
pass
@overload(output_factory, inline='always')
def ol_output_factory(array, dtype):
if isinstance(array, types.npytypes.Array):
def impl(array, dtype):
... | TestInlineMiscIssues |
python | bokeh__bokeh | tests/unit/bokeh/models/test_plots.py | {
"start": 5036,
"end": 11311
} | class ____:
def test_missing_renderers(self) -> None:
p = figure()
p.renderers = []
with mock.patch('bokeh.core.validation.check.log') as mock_logger:
issues = check_integrity([p])
process_validation_issues(issues)
assert mock_logger.warning.call_count == 1
... | TestPlotValidation |
python | pyca__cryptography | tests/hazmat/primitives/test_aes.py | {
"start": 4149,
"end": 5103
} | class ____:
test_cbc = generate_encrypt_test(
load_nist_vectors,
os.path.join("ciphers", "AES", "CBC"),
[
"CBCGFSbox128.rsp",
"CBCGFSbox192.rsp",
"CBCGFSbox256.rsp",
"CBCKeySbox128.rsp",
"CBCKeySbox192.rsp",
"CBCKeySbox2... | TestAESModeCBC |
python | great-expectations__great_expectations | tests/integration/test_utils/data_source_config/big_query.py | {
"start": 1541,
"end": 2570
} | class ____(SQLBatchTestSetup[BigQueryDatasourceTestConfig]):
@property
@override
def connection_string(self) -> str:
return self.big_query_connection_config.connection_string
@property
@override
def use_schema(self) -> bool:
# BigQuery calls its schemas "datasets". Their docs sh... | BigQueryBatchTestSetup |
python | PrefectHQ__prefect | tests/server/schemas/test_core.py | {
"start": 9925,
"end": 12172
} | class ____:
async def test_validates_metadata_sizes(self):
artifact = schemas.core.Artifact(
metadata_={"a very long key": "x" * 5000, "a very short key": "o" * 10}
)
assert len(artifact.metadata_["a very short key"]) == 10
assert len(artifact.metadata_["a very long key"]... | TestArtifacts |
python | bottlepy__bottle | bottle.py | {
"start": 85172,
"end": 86386
} | class ____(MultiDict):
""" This :class:`MultiDict` subclass is used to store request form data.
Additionally to the normal dict-like item access methods, this container
also supports attribute-like access to its values. Missing attributes
default to an empty string.
.. versionchange... | FormsDict |
python | ray-project__ray | python/ray/_private/runtime_env/packaging.py | {
"start": 1753,
"end": 34757
} | class ____:
"""Asyncio version used to prevent blocking event loop."""
def __init__(self, lock_file: str):
self.file = FileLock(lock_file)
async def __aenter__(self):
while True:
try:
self.file.acquire(timeout=0)
return
except Timeout... | _AsyncFileLock |
python | jazzband__django-model-utils | tests/models.py | {
"start": 1728,
"end": 2009
} | class ____(InheritanceManagerTestParent):
non_related_field_using_descriptor_2 = models.FileField(upload_to="test")
normal_field_2 = models.TextField()
objects: ClassVar[InheritanceManager[InheritanceManagerTestParent]] = InheritanceManager()
| InheritanceManagerTestChild1 |
python | PyCQA__pylint | doc/data/messages/i/implicit-flag-alias/bad.py | {
"start": 27,
"end": 127
} | class ____(IntFlag):
READ = 1
WRITE = 2
EXECUTE = 3 # [implicit-flag-alias]
| FilePermissions |
python | aio-libs__aiohttp | aiohttp/web_urldispatcher.py | {
"start": 30647,
"end": 31181
} | class ____(Sized, Iterable[AbstractRoute], Container[AbstractRoute]):
def __init__(self, resources: list[AbstractResource]):
self._routes: list[AbstractRoute] = []
for resource in resources:
for route in resource:
self._routes.append(route)
def __len__(self) -> int:
... | RoutesView |
python | chroma-core__chroma | chromadb/utils/embedding_functions/huggingface_sparse_embedding_function.py | {
"start": 480,
"end": 7003
} | class ____(SparseEmbeddingFunction[Documents]):
# Since we do dynamic imports we have to type this as Any
models: Dict[str, Any] = {}
def __init__(
self,
model_name: str,
device: str,
task: Optional[TaskType] = "document",
query_config: Optional[HuggingFaceSparseEmbe... | HuggingFaceSparseEmbeddingFunction |
python | numpy__numpy | numpy/lib/tests/test_index_tricks.py | {
"start": 14373,
"end": 14581
} | class ____:
def test_basic(self):
a = np.array([[1, 2], [3, 4]])
assert_equal(list(ndenumerate(a)),
[((0, 0), 1), ((0, 1), 2), ((1, 0), 3), ((1, 1), 4)])
| TestNdenumerate |
python | scrapy__scrapy | tests/mockserver/http_resources.py | {
"start": 8190,
"end": 8525
} | class ____(resource.Resource):
def render(self, request):
from twisted.internet import reactor
def response():
for i in range(1024):
request.write(b"x" * 1024)
request.finish()
reactor.callLater(0, response)
return server.NOT_DONE_YET
| LargeChunkedFileResource |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/assertsql.py | {
"start": 14179,
"end": 14614
} | class ____:
def __init__(self, context, clauseelement, multiparams, params):
self.context = context
self.clauseelement = clauseelement
if multiparams:
self.parameters = multiparams
elif params:
self.parameters = [params]
else:
self.paramet... | SQLExecuteObserved |
python | getsentry__sentry | src/sentry/api/endpoints/organization_trace_item_stats.py | {
"start": 1053,
"end": 2259
} | class ____(OrganizationEventsV2EndpointBase):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
owner = ApiOwner.DATA_BROWSING
def get(self, request: Request, organization: Organization) -> Response:
try:
snuba_params = self.get_snuba_params(request, organization)
... | OrganizationTraceItemsStatsEndpoint |
python | pandas-dev__pandas | pandas/tests/arrays/datetimes/test_reductions.py | {
"start": 208,
"end": 5525
} | class ____:
@pytest.fixture
def arr1d(self, tz_naive_fixture):
"""Fixture returning DatetimeArray with parametrized timezones"""
tz = tz_naive_fixture
dtype = DatetimeTZDtype(tz=tz) if tz is not None else np.dtype("M8[ns]")
arr = DatetimeArray._from_sequence(
[
... | TestReductions |
python | neetcode-gh__leetcode | python/0201-bitwise-and-of-numbers-range.py | {
"start": 66,
"end": 533
} | class ____:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
res = 0
for i in range(32):
bit = (left >> i) & 1
if not bit:
continue
remain = left % (1 << (i + 1))
diff = (1 << (i + 1)) - remain
if right... | Solution |
python | openai__openai-python | src/openai/types/beta/realtime/conversation_item_truncated_event.py | {
"start": 208,
"end": 704
} | class ____(BaseModel):
audio_end_ms: int
"""The duration up to which the audio was truncated, in milliseconds."""
content_index: int
"""The index of the content part that was truncated."""
event_id: str
"""The unique ID of the server event."""
item_id: str
"""The ID of the assistant m... | ConversationItemTruncatedEvent |
python | optuna__optuna | optuna/samplers/_grid.py | {
"start": 701,
"end": 11674
} | class ____(BaseSampler):
"""Sampler using grid search.
With :class:`~optuna.samplers.GridSampler`, the trials suggest all combinations of parameters
in the given search space during the study.
Example:
.. testcode::
import optuna
def objective(trial):
... | GridSampler |
python | pytorch__pytorch | torch/_inductor/runtime/caching/interfaces.py | {
"start": 956,
"end": 5291
} | class ____(Enum):
REPLAY = "replay"
RECORD_INSERTED = "record_inserted"
RECORD_NOT_INSERTED = "record_not_inserted"
RECORD_NOT_INSERTED_REPLAY = "record_not_inserted_replay"
HIT = "hit"
MISS = "miss"
INSERTED = "inserted"
NOT_INSERTED = "not_inserted"
def _intf_callback(
origin: _I... | _IntfCallbackAction |
python | PrefectHQ__prefect | src/prefect/client/schemas/filters.py | {
"start": 27803,
"end": 28232
} | class ____(PrefectBaseModel, OperatorMixin):
id: Optional[WorkPoolFilterId] = Field(
default=None, description="Filter criteria for `WorkPool.id`"
)
name: Optional[WorkPoolFilterName] = Field(
default=None, description="Filter criteria for `WorkPool.name`"
)
type: Optional[WorkPoolFi... | WorkPoolFilter |
python | astropy__astropy | astropy/utils/data.py | {
"start": 2576,
"end": 4089
} | class ____(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.utils.data`.
"""
dataurl = _config.ConfigItem(
"http://data.astropy.org/", "Primary URL for astropy remote data site."
)
dataurl_mirror = _config.ConfigItem(
"http://www.astropy.org/astropy-data/",
... | Conf |
python | sympy__sympy | sympy/codegen/fnodes.py | {
"start": 18363,
"end": 18470
} | class ____(FFunction):
""" Fortran sign intrinsic for double precision arguments. """
nargs = 2
| dsign |
python | neetcode-gh__leetcode | python/0622-design-circular-queue.py | {
"start": 0,
"end": 96
} | class ____:
def __init__(self, val: int):
self.val = val
self.next = None
| Node |
python | bokeh__bokeh | src/bokeh/models/expressions.py | {
"start": 5691,
"end": 6451
} | class ____(Expression):
''' An expression for generating arrays by summing different columns from
a ``ColumnDataSource``.
This expression is useful for implementing stacked bar charts at a low
level.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwarg... | Stack |
python | doocs__leetcode | solution/1100-1199/1163.Last Substring in Lexicographical Order/Solution.py | {
"start": 0,
"end": 408
} | class ____:
def lastSubstring(self, s: str) -> str:
i, j, k = 0, 1, 0
while j + k < len(s):
if s[i + k] == s[j + k]:
k += 1
elif s[i + k] < s[j + k]:
i += k + 1
k = 0
if i >= j:
j = i + 1
... | Solution |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_threading.py | {
"start": 2464,
"end": 2618
} | class ____:
@given(st.integers())
@pytest.mark.parametrize("x", range(2))
def test_a(self, x, i):
pass
| TestNoDifferingExecutorsHealthCheck |
python | mkdocs__mkdocs | mkdocs/tests/utils/templates_tests.py | {
"start": 137,
"end": 1801
} | class ____(unittest.TestCase):
def test_script_tag(self):
cfg_yaml = dedent(
'''
extra_javascript:
- some_plain_javascript.js
- implicitly_as_module.mjs
- path: explicitly_as_module.mjs
type: module
- path: defer... | UtilsTemplatesTests |
python | spack__spack | lib/spack/spack/spec.py | {
"start": 24319,
"end": 25002
} | class ____(lang.DeprecatedProperty):
def __init__(self):
super().__init__(name="compiler")
def factory(self, instance, owner):
if instance.original_spec_format() < 5:
compiler = instance.annotations.compiler_node_attribute
assert compiler is not None, "a compiler spec is... | DeprecatedCompilerSpec |
python | numpy__numpy | numpy/_core/tests/test_scalar_methods.py | {
"start": 5118,
"end": 7268
} | class ____:
@pytest.mark.parametrize("cls", [
np.number,
np.integer,
np.inexact,
np.unsignedinteger,
np.signedinteger,
np.floating,
])
def test_abc(self, cls: type[np.number]) -> None:
alias = cls[Any]
assert isinstance(alias, types.GenericAlia... | TestClassGetItem |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.