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 | getsentry__sentry | tests/sentry/issues/endpoints/test_organization_group_index.py | {
"start": 114619,
"end": 173668
} | class ____(APITestCase, SnubaTestCase):
endpoint = "sentry-api-0-organization-group-index"
method = "put"
def setUp(self) -> None:
super().setUp()
self.min_ago = timezone.now() - timedelta(minutes=1)
def get_response(self, *args: Any, **kwargs: Any) -> Response:
if not args:
... | GroupUpdateTest |
python | PyCQA__pylint | tests/functional/ext/docstyle/docstyle_quotes.py | {
"start": 141,
"end": 825
} | class ____:
def method1(self): # [bad-docstring-quotes]
'''
Test Triple Single Quotes docstring
'''
def method2(self): # [bad-docstring-quotes]
"bad docstring 1"
def method3(self): # [bad-docstring-quotes]
'bad docstring 2'
def method4(self): # [bad-docstri... | FFFF |
python | docker__docker-py | docker/errors.py | {
"start": 4843,
"end": 5024
} | class ____(DockerException):
def __init__(self, name):
self.name = name
def __str__(self):
return (f"context {self.name} already exists")
| ContextAlreadyExists |
python | allegroai__clearml | clearml/backend_api/services/v2_13/queues.py | {
"start": 5186,
"end": 6761
} | class ____(NonStrictDataModel):
"""
:param task: Queued task ID
:type task: str
:param added: Time this entry was added to the queue
:type added: datetime.datetime
"""
_schema = {
"properties": {
"added": {
"description": "Time this entry was added to the... | Entry |
python | openai__openai-python | src/openai/pagination.py | {
"start": 1112,
"end": 1674
} | class ____(BaseAsyncPage[_T], BasePage[_T], Generic[_T]):
"""Note: no pagination actually occurs yet, this is for forwards-compatibility."""
data: List[_T]
object: str
@override
def _get_page_items(self) -> List[_T]:
data = self.data
if not data:
return []
retur... | AsyncPage |
python | huggingface__transformers | src/transformers/models/nystromformer/modeling_nystromformer.py | {
"start": 21497,
"end": 24467
} | class ____(NystromformerPreTrainedModel):
_tied_weights_keys = {
"cls.predictions.decoder.weight": "nystromformer.embeddings.word_embeddings.weight",
"cls.predictions.decoder.bias": "cls.predictions.bias",
}
def __init__(self, config):
super().__init__(config)
self.nystromf... | NystromformerForMaskedLM |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_highlight.py | {
"start": 2094,
"end": 2865
} | class ____(util.MdCase):
"""Test title cases."""
extension = ['pymdownx.highlight', 'pymdownx.superfences']
extension_configs = {
'pymdownx.highlight': {
'auto_title': True
}
}
def test_auto_tile(self):
"""Test auto title."""
self.check_markdown(
... | TestHighlightAutoTitle |
python | FactoryBoy__factory_boy | tests/test_mongoengine.py | {
"start": 526,
"end": 667
} | class ____(MongoEngineFactory):
class Meta:
model = Address
street = factory.Sequence(lambda n: 'street%d' % n)
| AddressFactory |
python | getsentry__sentry | src/sentry/core/endpoints/scim/members.py | {
"start": 16009,
"end": 24119
} | class ____(SCIMEndpoint):
publish_status = {
"GET": ApiPublishStatus.PUBLIC,
"POST": ApiPublishStatus.PUBLIC,
}
permission_classes = (OrganizationSCIMMemberPermission,)
@extend_schema(
operation_id="List an Organization's SCIM Members",
parameters=[GlobalParams.ORG_ID_OR... | OrganizationSCIMMemberIndex |
python | PyCQA__pylint | doc/data/messages/n/no-member/bad.py | {
"start": 75,
"end": 158
} | class ____:
def meow(self):
print("Meow")
Cat().roar() # [no-member]
| Cat |
python | FactoryBoy__factory_boy | factory/base.py | {
"start": 685,
"end": 2906
} | class ____(type):
"""Factory metaclass for handling ordered declarations."""
def __call__(cls, **kwargs):
"""Override the default Factory() syntax to call the default strategy.
Returns an instance of the associated class.
"""
if cls._meta.strategy == enums.BUILD_STRATEGY:
... | FactoryMetaClass |
python | spyder-ide__spyder | spyder/plugins/editor/panels/linenumber.py | {
"start": 601,
"end": 11927
} | class ____(Panel):
"""Line number area (on the left side of the text editor widget)"""
# --- Qt Overrides
# -----------------------------------------------------------------
def __init__(self):
Panel.__init__(self)
self.setMouseTracking(True)
self.scrollable = True
sel... | LineNumberArea |
python | pandas-dev__pandas | asv_bench/benchmarks/plotting.py | {
"start": 473,
"end": 959
} | class ____:
params = [["line", "bar", "area", "barh", "hist", "kde", "pie"]]
param_names = ["kind"]
def setup(self, kind):
if kind in ["bar", "barh", "pie"]:
n = 100
elif kind in ["kde"]:
n = 10000
else:
n = 1000000
self.s = Series(np.ran... | SeriesPlotting |
python | google__jax | jaxlib/xla_client.py | {
"start": 11712,
"end": 12103
} | class ____(enum.IntFlag):
DEFAULT = 0
# Calls to custom call are safe to trace into the command buffer. It means
# that calls to custom call always launch exactly the same device operations
# (can depend on attribute values) that can be captured and then replayed.
#
# Supported only for custom calls impleme... | CustomCallTargetTraits |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/matchClass5.py | {
"start": 221,
"end": 1166
} | class ____(int): ...
def func1(subj: A | B):
match subj:
# This should generate an error because A accepts only
# one positional pattern.
case A(1, 2):
pass
case A(1):
pass
case A():
pass
case B(1, 2):
pass
... | D |
python | lazyprogrammer__machine_learning_examples | rnn_class/tf_parity.py | {
"start": 1417,
"end": 4474
} | class ____:
def __init__(self, M):
self.M = M # hidden layer size
def fit(self, X, Y, batch_sz=20, learning_rate=0.1, mu=0.9, activation=tf.nn.sigmoid, epochs=100, show_fig=False):
N, T, D = X.shape # X is of size N x T(n) x D
K = len(set(Y.flatten()))
M = self.M
self.f = activation
# ini... | SimpleRNN |
python | apache__airflow | dev/breeze/src/airflow_breeze/utils/console.py | {
"start": 2284,
"end": 2580
} | class ____(Enum):
SUCCESS = "success"
INFO = "info"
WARNING = "warning"
ERROR = "error"
SPECIAL = "special"
def message_type_from_return_code(return_code: int) -> MessageType:
if return_code == 0:
return MessageType.SUCCESS
return MessageType.ERROR
| MessageType |
python | davidhalter__jedi | jedi/inference/names.py | {
"start": 17859,
"end": 18943
} | class ____(_ActualTreeParamName):
@plugin_manager.decorate(name='goto_anonymous_param')
def goto(self):
return super().goto()
@plugin_manager.decorate(name='infer_anonymous_param')
def infer(self):
values = super().infer()
if values:
return values
from jedi.i... | AnonymousParamName |
python | django__django | tests/known_related_objects/models.py | {
"start": 147,
"end": 224
} | class ____(models.Model):
name = models.CharField(max_length=30)
| Tournament |
python | python-attrs__attrs | tests/test_functional.py | {
"start": 700,
"end": 798
} | class ____:
x = attr.ib(default=foo)
y = attr.ib(default=attr.Factory(list))
@attr.s
| C2Slots |
python | huggingface__transformers | src/transformers/models/rt_detr/modeling_rt_detr.py | {
"start": 51548,
"end": 60847
} | class ____(nn.Module):
"""
Decoder consisting of a projection layer, a set of `RTDetrEncoder`, a top-down Feature Pyramid Network
(FPN) and a bottom-up Path Aggregation Network (PAN). More details on the paper: https://huggingface.co/papers/2304.08069
Args:
config: RTDetrConfig
"""
def... | RTDetrHybridEncoder |
python | getsentry__sentry | tests/sentry/seer/endpoints/test_organization_trace_summary.py | {
"start": 417,
"end": 5317
} | class ____(APITestCase, SnubaTestCase):
def setUp(self) -> None:
super().setUp()
self.org = self.create_organization(owner=self.user)
self.login_as(user=self.user)
self.trace_id = "trace123"
self.mock_trace_tree = [
SerializedSpan(
description="ht... | OrganizationTraceSummaryEndpointTest |
python | huggingface__transformers | src/transformers/integrations/bitsandbytes.py | {
"start": 3300,
"end": 4432
} | class ____(ConversionOps):
def __init__(self, hf_quantizer):
self.hf_quantizer = hf_quantizer
def convert(
self,
input_dict: dict[str, list[torch.Tensor]],
model: torch.nn.Module | None = None,
full_layer_name: str | None = None,
**kwargs,
) -> dict[str, torc... | Bnb8bitQuantize |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance2.py | {
"start": 139,
"end": 277
} | class ____:
def get_value(self) -> int:
if isinstance(self, ChildB):
return self.calculate()
return 7
| ClassA |
python | tensorflow__tensorflow | tensorflow/python/ops/resource_variable_ops.py | {
"start": 64496,
"end": 92050
} | class ____(BaseResourceVariable, composite_tensor.CompositeTensor):
"""Variable based on resource handles.
See the [Variables How To](https://tensorflow.org/guide/variables)
for a high level overview.
A `ResourceVariable` allows you to maintain state across subsequent calls to
session.run.
The `ResourceV... | ResourceVariable |
python | MongoEngine__mongoengine | mongoengine/base/fields.py | {
"start": 11844,
"end": 21897
} | class ____(BaseField):
"""Handles complex fields, such as lists / dictionaries.
Allows for nesting of embedded documents inside complex types.
Handles the lazy dereferencing of a queryset by lazily dereferencing all
items in a list / dict rather than one at a time.
"""
def __init__(self, field... | ComplexBaseField |
python | huggingface__transformers | src/transformers/models/videomae/configuration_videomae.py | {
"start": 785,
"end": 6600
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`VideoMAEModel`]. It is used to instantiate a
VideoMAE model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar con... | VideoMAEConfig |
python | run-llama__llama_index | llama-index-core/llama_index/core/tools/types.py | {
"start": 2932,
"end": 4591
} | class ____(BaseModel):
"""Tool output."""
blocks: List[ContentBlock]
tool_name: str
raw_input: Dict[str, Any]
raw_output: Any
is_error: bool = False
_exception: Optional[Exception] = PrivateAttr(default=None)
def __init__(
self,
tool_name: str,
content: Optiona... | ToolOutput |
python | kubernetes-client__python | kubernetes/client/models/v1_grpc_action.py | {
"start": 383,
"end": 4721
} | 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... | V1GRPCAction |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/dependency.py | {
"start": 31243,
"end": 43887
} | class ____:
@staticmethod
def from_definitions(
nodes: Mapping[str, Node], dep_dict: DependencyMapping[str]
) -> "DependencyStructure":
return DependencyStructure(
list(dep_dict.keys()),
_create_handle_dict(nodes, dep_dict),
dep_dict,
)
_node_... | DependencyStructure |
python | scipy__scipy | scipy/cluster/tests/test_hierarchy.py | {
"start": 17877,
"end": 21859
} | class ____:
@pytest.mark.parametrize("nrow, ncol, valid", [(2, 5, False), (2, 3, False),
(1, 4, True), (2, 4, True)])
def test_is_valid_linkage_various_size(self, nrow, ncol, valid, xp):
# Tests is_valid_linkage(Z) with linkage matrices of various sizes... | TestIsValidLinkage |
python | joke2k__faker | tests/providers/test_ssn.py | {
"start": 23317,
"end": 24969
} | class ____:
def setup_method(self):
self.fake = Faker("es_MX")
Faker.seed(0)
def test_ssn(self):
for _ in range(100):
ssn = self.fake.ssn()
assert len(ssn) == 11
assert ssn.isnumeric()
assert mx_ssn_checksum(map(int, ssn[:-1])) == int(ssn... | TestEsMX |
python | ray-project__ray | doc/source/ray-overview/examples/e2e-rag/notebooks/rag_utils.py | {
"start": 2624,
"end": 3270
} | class ____:
def __init__(self, model_name: str = "intfloat/multilingual-e5-large-instruct"):
self.model_name = model_name
self.model = SentenceTransformer(
self.model_name, device="cuda" if torch.cuda.is_available() else "cpu"
)
def embed_single(self, text: str) -> np.ndarra... | Embedder |
python | has2k1__plotnine | plotnine/scales/scale_alpha.py | {
"start": 1378,
"end": 1675
} | class ____(scale_alpha_ordinal):
"""
Discrete Alpha Scale
"""
def __post_init__(self, range):
warn(
"Using alpha for a discrete variable is not advised.",
PlotnineWarning,
)
super().__post_init__(range)
@dataclass
| scale_alpha_discrete |
python | getsentry__sentry | src/social_auth/backends/bitbucket.py | {
"start": 2503,
"end": 4263
} | class ____(BaseOAuth1):
"""Bitbucket OAuth authentication mechanism"""
AUTHORIZATION_URL = BITBUCKET_AUTHORIZATION_URL
REQUEST_TOKEN_URL = BITBUCKET_REQUEST_TOKEN_URL
ACCESS_TOKEN_URL = BITBUCKET_ACCESS_TOKEN_URL
AUTH_BACKEND = BitbucketBackend
SETTINGS_KEY_NAME = "BITBUCKET_CONSUMER_KEY"
S... | BitbucketAuth |
python | sphinx-doc__sphinx | sphinx/domains/_index.py | {
"start": 312,
"end": 1035
} | class ____(NamedTuple):
"""An index entry.
.. note::
The *qualifier* and *description* are not rendered for some output formats,
such as LaTeX.
"""
#: The name of the index entry to be displayed.
name: str
#: The sub-entry related type. One of:
#:
#: ``0``
#: A no... | IndexEntry |
python | aio-libs__aiohttp | aiohttp/web_urldispatcher.py | {
"start": 27627,
"end": 28627
} | class ____(AbstractRoute):
"""A route with resource"""
def __init__(
self,
method: str,
handler: Handler | type[AbstractView],
resource: AbstractResource,
*,
expect_handler: _ExpectHandler | None = None,
) -> None:
super().__init__(
method... | ResourceRoute |
python | aio-libs__aiohttp | aiohttp/web_exceptions.py | {
"start": 11300,
"end": 11371
} | class ____(HTTPServerError):
status_code = 503
| HTTPServiceUnavailable |
python | PyCQA__pylint | pylint/config/callback_actions.py | {
"start": 11038,
"end": 11411
} | class ____(_XableAction):
"""Callback action for disabling a message."""
def __call__(
self,
parser: argparse.ArgumentParser,
namespace: argparse.Namespace,
values: str | Sequence[Any] | None,
option_string: str | None = "--disable",
) -> None:
self._call(sel... | _DisableAction |
python | getsentry__sentry | src/sentry/api/endpoints/organization_profiling_functions.py | {
"start": 1626,
"end": 2098
} | class ____(serializers.Field):
def to_representation(self, trend_type: TrendType):
return trend_type.value
def to_internal_value(self, data: Any) -> TrendType | None:
for trend_type in TrendType:
if data == trend_type.value:
return trend_type
expected = " or... | TrendTypeField |
python | HIPS__autograd | autograd/numpy/numpy_wrapper.py | {
"start": 4186,
"end": 5666
} | class ____:
def __getitem__(self, args):
raw_array = _np.c_[args]
return wrap_if_boxes_inside(raw_array, slow_op_name="c_")
c_ = c_class()
# ----- misc -----
@primitive
def make_diagonal(D, offset=0, axis1=0, axis2=1):
# Numpy doesn't offer a complement to np.diagonal: a function to create n... | c_class |
python | conda__conda | tests/plugins/test_pre_solves.py | {
"start": 504,
"end": 2144
} | class ____:
def pre_solve_action(self) -> None:
pass
@plugins.hookimpl
def conda_pre_solves(self):
yield plugins.CondaPreSolve(
name="custom-pre-solve",
action=self.pre_solve_action,
)
@pytest.fixture
def pre_solve_plugin(
mocker: MockerFixture,
plu... | PreSolvePlugin |
python | wntrblm__nox | nox/sessions.py | {
"start": 4306,
"end": 4763
} | class ____:
def __init__(self, dir: str | os.PathLike[str]) -> None:
self._prev_working_dir = os.getcwd()
os.chdir(dir)
def __enter__(self) -> _WorkingDirContext: # noqa: PYI034
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_value... | _WorkingDirContext |
python | ray-project__ray | rllib/policy/torch_mixins.py | {
"start": 366,
"end": 1906
} | class ____:
"""Mixin for TorchPolicy that adds a learning rate schedule."""
def __init__(self, lr, lr_schedule, lr2=None, lr2_schedule=None):
self._lr_schedule = None
self._lr2_schedule = None
# Disable any scheduling behavior related to learning if Learner API is active.
# Sche... | LearningRateSchedule |
python | bokeh__bokeh | src/bokeh/server/contexts.py | {
"start": 4523,
"end": 12613
} | class ____:
''' Server-side holder for ``bokeh.application.Application`` plus any associated data.
This holds data that's global to all sessions, while ``ServerSession`` holds
data specific to an "instance" of the application.
'''
_sessions: dict[ID, ServerSession]
_pending_sessions: d... | ApplicationContext |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType9.py | {
"start": 489,
"end": 531
} | class ____(ClassA[_T2]):
pass
| ClassASub1 |
python | great-expectations__great_expectations | great_expectations/core/expectation_validation_result.py | {
"start": 18938,
"end": 30176
} | class ____(SerializableDictDot):
"""The result of a batch of data validated against an Expectation Suite.
When a Checkpoint is run, it produces an instance of this class. The primary property
of this class is `results`, which contains the individual ExpectationValidationResult
instances which were prod... | ExpectationSuiteValidationResult |
python | spack__spack | lib/spack/spack/cmd/create.py | {
"start": 9453,
"end": 9802
} | class ____(PackageTemplate):
"""Provides appropriate override for Waf-based packages"""
base_class_name = "WafPackage"
package_class_import = "from spack_repo.builtin.build_systems.waf import WafPackage"
body_def = """\
# FIXME: Override configure_args(), build_args(),
# or install_args() if n... | WafPackageTemplate |
python | ray-project__ray | python/ray/air/util/data_batch_conversion.py | {
"start": 970,
"end": 12539
} | class ____(str, Enum):
"""Internal Dataset block format enum."""
PANDAS = "pandas"
ARROW = "arrow"
SIMPLE = "simple"
def _convert_batch_type_to_pandas(
data: DataBatchType,
cast_tensor_columns: bool = False,
) -> "pd.DataFrame":
"""Convert the provided data to a Pandas DataFrame.
Arg... | BlockFormat |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/rebatch_test.py | {
"start": 1335,
"end": 14481
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
##############################################################################
# The following tests exercise our static computation of output_shapes.
##############################################################################
@combinations.gen... | RebatchTest |
python | getsentry__sentry | src/sentry/notifications/platform/types.py | {
"start": 7314,
"end": 8267
} | class ____[T: NotificationData](abc.ABC):
category: NotificationCategory
"""
The category that a notification belongs to. This will be used to determine which settings a
user needs to modify to manage receipt of these notifications (if applicable).
"""
example_data: T
"""
The example dat... | NotificationTemplate |
python | huggingface__transformers | src/transformers/models/qwen3_vl_moe/modeling_qwen3_vl_moe.py | {
"start": 3076,
"end": 6522
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.num_experts = config.num_experts
self.intermediate_size = config.moe_intermediate_size
self.hidden_size = config.hidden_size
self.expert_dim = self.intermediate_size
self.gate_up_proj = nn.Para... | Qwen3VLMoeTextExperts |
python | kamyu104__LeetCode-Solutions | Python/all-paths-from-source-to-target.py | {
"start": 142,
"end": 669
} | class ____(object):
def allPathsSourceTarget(self, graph):
"""
:type graph: List[List[int]]
:rtype: List[List[int]]
"""
def dfs(graph, curr, path, result):
if curr == len(graph)-1:
result.append(path[:])
return
for node ... | Solution |
python | nedbat__coveragepy | tests/test_cmdline.py | {
"start": 858,
"end": 7379
} | class ____(CoverageTest):
"""Tests of execution paths through the command line interpreter."""
run_in_temp_dir = False
# Make a dict mapping function names to the default values that cmdline.py
# uses when calling the function.
_defaults = mock.Mock()
_defaults.Coverage().annotate(
dir... | BaseCmdLineTest |
python | ApeWorX__ape | src/ape/cli/paramtype.py | {
"start": 91,
"end": 397
} | class ____(click.Path):
"""
This class exists to encourage the consistent usage
of ``pathlib.Path`` for path_type.
"""
def __init__(self, *args, **kwargs):
if "path_type" not in kwargs:
kwargs["path_type"] = PathLibPath
super().__init__(*args, **kwargs)
| Path |
python | ray-project__ray | python/ray/llm/_internal/batch/stages/vllm_engine_stage.py | {
"start": 13586,
"end": 21604
} | class ____(StatefulStageUDF):
def __init__(
self,
data_column: str,
expected_input_keys: List[str],
batch_size: int,
max_concurrent_batches: int,
model: str,
engine_kwargs: Dict[str, Any],
task_type: vLLMTaskType = vLLMTaskType.GENERATE,
max_pe... | vLLMEngineStageUDF |
python | lazyprogrammer__machine_learning_examples | rl3/a2c/atari_wrappers.py | {
"start": 186,
"end": 1222
} | class ____(gym.Wrapper):
def __init__(self, env, noop_max=30):
"""Sample initial states by taking random number of no-ops on reset.
No-op is assumed to be action 0.
"""
gym.Wrapper.__init__(self, env)
self.noop_max = noop_max
self.override_num_noops = None
sel... | NoopResetEnv |
python | python__mypy | mypy/modulefinder.py | {
"start": 4442,
"end": 5354
} | class ____:
"""A single source file."""
def __init__(
self,
path: str | None,
module: str | None,
text: str | None = None,
base_dir: str | None = None,
followed: bool = False,
) -> None:
self.path = path # File where it's found (e.g. 'xxx/yyy/foo/bar... | BuildSource |
python | pytorch__pytorch | test/distributed/test_c10d_functional_native.py | {
"start": 21220,
"end": 23409
} | class ____(TestCase):
"""
Native functional collectives have some interesting interactions with
PyProcessGroup due to Python reference counting and pybind trampoline
classes with C++ types. This validates that PyProcessGroup and PyWork
aren't getting prematurely freed.
"""
def test_wait_ten... | PyWorkTest |
python | nedbat__coveragepy | tests/test_arcs.py | {
"start": 56232,
"end": 58229
} | class ____(CoverageTest):
"""Tests of lambdas"""
def test_multiline_lambda(self) -> None:
self.check_coverage(
"""\
fn = (lambda x:
x + 2
)
assert fn(4) == 6
""",
branchz="",
branchz_missing="",
... | LambdaArcTest |
python | sympy__sympy | sympy/physics/biomechanics/tests/test_musculotendon.py | {
"start": 1520,
"end": 2434
} | class ____:
@staticmethod
def test_rigid_tendon_member():
assert MusculotendonFormulation(0) == 0
assert MusculotendonFormulation.RIGID_TENDON == 0
@staticmethod
def test_fiber_length_explicit_member():
assert MusculotendonFormulation(1) == 1
assert MusculotendonFormulat... | TestMusculotendonFormulation |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP046_0.py | {
"start": 1698,
"end": 1799
} | class ____(Generic[T], Generic[S]):
var: T
var: S
# These cases are not handled
| TooManyGenerics |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_views.py | {
"start": 6440,
"end": 7585
} | class ____(TestCase):
fixtures = ["eric", "test_data"]
def setUp(self):
self.client.login(username="eric", password="test")
self.pip = Project.objects.get(slug="pip")
self.pip.privacy_level = PUBLIC
self.pip.external_builds_privacy_level = PUBLIC
self.pip.save()
... | BuildViewTests |
python | apache__airflow | airflow-core/src/airflow/executors/workloads.py | {
"start": 1863,
"end": 2786
} | class ____(BaseModel):
"""Schema for TaskInstance with minimal required fields needed for Executors and Task SDK."""
id: uuid.UUID
dag_version_id: uuid.UUID
task_id: str
dag_id: str
run_id: str
try_number: int
map_index: int = -1
pool_slots: int
queue: str
priority_weight: ... | TaskInstance |
python | falconry__falcon | examples/ws_tutorial/ws_tutorial/app.py | {
"start": 2052,
"end": 2159
} | class ____:
async def on_get(self, req, resp):
resp.media = {'hello': 'world'}
| HelloWorldResource |
python | pydata__xarray | xarray/tests/test_backends.py | {
"start": 193917,
"end": 203150
} | class ____(NetCDF4Base):
engine: T_NetcdfEngine = "h5netcdf"
@contextlib.contextmanager
def create_store(self):
with create_tmp_file() as tmp_file:
yield backends.H5NetCDFStore.open(tmp_file, "w")
@pytest.mark.skipif(
has_h5netcdf_1_4_0_or_above, reason="only valid for h5ne... | TestH5NetCDFData |
python | pytorch__pytorch | test/distributed/checkpoint/_experimental/test_checkpoint_process.py | {
"start": 5111,
"end": 5888
} | class ____(TestCase):
"""Test CheckpointProcessConfig configuration."""
def test_default_options(self) -> None:
"""Test default CheckpointProcessConfig."""
options = CheckpointProcessConfig()
# Test default values
self.assertEqual(options.subprocess_init_timeout_secs, 30)
... | TestCheckpointProcessConfig |
python | pytorch__pytorch | torch/__init__.py | {
"start": 71643,
"end": 71867
} | class ____(_LegacyStorage):
@classproperty
def dtype(self):
_warn_typed_storage_removal(stacklevel=3)
return self._dtype
@classproperty
def _dtype(self):
return torch.short
| ShortStorage |
python | zostera__django-bootstrap4 | tests/test_buttons.py | {
"start": 174,
"end": 1546
} | class ____(TestCase):
def test_button(self):
self.assertEqual(render_button("button"), '<button class="btn btn-primary">button</button>')
def test_button_with_illegal_type(self):
try:
self.assertEqual(
render_button("button", button_type="illegal"), '<button class="b... | ButtonsTest |
python | huggingface__transformers | tests/models/led/test_modeling_led.py | {
"start": 20316,
"end": 96283
} | class ____(unittest.TestCase):
"""All the below results were obtained with the original checkpoints and code
base from https://github.com/allenai/longformer.
IMPORTANT: Note that the original checkpoints include a `position_embeddings` "hack"
and have to be cut to have the correct shape.
See: https:... | LEDModelIntegrationTests |
python | numpy__numpy | numpy/_core/tests/test_scalarinherit.py | {
"start": 257,
"end": 281
} | class ____(B0):
pass
| C0 |
python | PrefectHQ__prefect | src/prefect/flow_engine.py | {
"start": 29461,
"end": 61774
} | class ____(BaseFlowRunEngine[P, R]):
"""
Async version of the flow run engine.
NOTE: This has not been fully asyncified yet which may lead to async flows
not being fully asyncified.
"""
_client: Optional[PrefectClient] = None
parameters: dict[str, Any] | None = None
flow_run: FlowRun |... | AsyncFlowRunEngine |
python | ray-project__ray | rllib/core/models/tests/test_catalog.py | {
"start": 1470,
"end": 15265
} | class ____(unittest.TestCase):
def _check_model_outputs(self, model, framework, model_config_dict, input_space):
"""Checks the model's outputs for the given input space.
Args:
model: The model to check.
framework: The framework to use (torch).
model_config_dict: ... | TestCatalog |
python | kamyu104__LeetCode-Solutions | Python/binary-search-tree-iterator-ii.py | {
"start": 232,
"end": 1253
} | class ____(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.__stk = []
self.__traversalLeft(root)
self.__vals = []
self.__pos = -1
def hasNext(self):
"""
:rtype: bool
"""
return self.__pos+1 != len(self... | BSTIterator |
python | python-attrs__attrs | tests/test_filters.py | {
"start": 573,
"end": 1735
} | class ____:
"""
Tests for `include`.
"""
@pytest.mark.parametrize(
("incl", "value"),
[
((int,), 42),
((str,), "hello"),
((str, fields(C).a), 42),
((str, fields(C).b), "hello"),
(("a",), 42),
(("a",), "hello"),
... | TestInclude |
python | tensorflow__tensorflow | tensorflow/python/ops/init_ops_v2.py | {
"start": 16020,
"end": 18448
} | class ____(Initializer):
"""Initializer that generates a truncated normal distribution.
Initializers allow you to pre-specify an initialization strategy, encoded in
the Initializer object, without knowing the shape and dtype of the variable
being initialized.
These values are similar to values from a `tf.in... | TruncatedNormal |
python | keras-team__keras | guides/writing_your_own_callbacks.py | {
"start": 6457,
"end": 8835
} | class ____(keras.callbacks.Callback):
def on_train_batch_end(self, batch, logs=None):
print(
"Up to batch {}, the average loss is {:7.2f}.".format(
batch, logs["loss"]
)
)
def on_test_batch_end(self, batch, logs=None):
print(
"Up to ba... | LossAndErrorPrintingCallback |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 239317,
"end": 241045
} | class ____(GeneratedAirbyteSource):
class OAuth20:
@public
def __init__(self, client_id: str, client_secret: str, access_token: str):
self.auth_method = "oauth2.0"
self.client_id = check.str_param(client_id, "client_id")
self.client_secret = check.str_param(client... | ZendeskSunshineSource |
python | getsentry__sentry | tests/sentry/snuba/test_transactions_timeseries_query.py | {
"start": 497,
"end": 1687
} | class ____(SnubaTestCase, TestCase):
def setUp(self) -> None:
super().setUp()
self.one_min_ago = before_now(minutes=1)
self.day_ago = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0)
# transaction event
data = load_data("transaction", timestamp=self.da... | TimeseriesBase |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_axis38.py | {
"start": 315,
"end": 1428
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_axis38.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/tasks.py | {
"start": 1792,
"end": 3827
} | class ____(BaseModel):
"""Task serializer for responses."""
task_id: str | None
task_display_name: str | None
owner: str | None
start_date: datetime | None
end_date: datetime | None
trigger_rule: str | None
depends_on_past: bool
wait_for_downstream: bool
retries: float | None
... | TaskResponse |
python | keras-team__keras | keras/src/ops/node_test.py | {
"start": 158,
"end": 194
} | class ____(Layer):
pass
| DummyLayer |
python | getsentry__sentry | src/sentry/api/bases/organization.py | {
"start": 8899,
"end": 11830
} | class ____(Endpoint):
"""
A base class for endpoints that use an organization scoping but lives in the control silo
"""
permission_classes: tuple[type[BasePermission], ...] = (OrganizationPermission,)
def convert_args(
self,
request: Request,
*args: Any,
**kwargs: A... | ControlSiloOrganizationEndpoint |
python | pallets__werkzeug | tests/test_datastructures.py | {
"start": 39267,
"end": 42087
} | class ____:
storage_class = ds.FileStorage
def test_mimetype_always_lowercase(self):
file_storage = self.storage_class(content_type="APPLICATION/JSON")
assert file_storage.mimetype == "application/json"
@pytest.mark.parametrize("data", [io.StringIO("one\ntwo"), io.BytesIO(b"one\ntwo")])
... | TestFileStorage |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_us_state_abbreviation.py | {
"start": 1832,
"end": 4453
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid state abbreviations.
See https://pypi.org/project/us/ for more information. \
DC statehood is a perennial issue in data science, and the owners of the us repo addressed it differently than we have: https://github.com/unitedstates... | ExpectColumnValuesToBeValidUSStateAbbreviation |
python | lazyprogrammer__machine_learning_examples | rl3/a2c/atari_wrappers.py | {
"start": 4420,
"end": 5160
} | class ____(gym.RewardWrapper):
def reward(self, reward):
"""Bin reward to {+1, 0, -1} by its sign."""
return np.sign(reward)
# class WarpFrame(gym.ObservationWrapper):
# def __init__(self, env):
# """Warp frames to 84x84 as done in the Nature paper and later work."""
# gym.Obse... | ClipRewardEnv |
python | jazzband__django-formtools | tests/wizard/test_forms.py | {
"start": 1975,
"end": 2175
} | class ____(TestWizard):
form_list = [Step1, Step2]
condition_dict = {'step2': True}
initial_dict = {'start': {'name': 'value1'}}
instance_dict = {'start': User()}
| TestWizardWithInitAttrs |
python | matplotlib__matplotlib | lib/matplotlib/backend_tools.py | {
"start": 14524,
"end": 18755
} | class ____(ToolBase):
"""
Auxiliary Tool to handle changes in views and positions.
Runs in the background and should get used by all the tools that
need to access the figure's history of views and positions, e.g.
* `ToolZoom`
* `ToolPan`
* `ToolHome`
* `ToolBack`
* `ToolForward`
... | ToolViewsPositions |
python | dagster-io__dagster | scripts/run-pyright.py | {
"start": 3476,
"end": 3538
} | class ____(TypedDict):
line: int
character: int
| Position |
python | ray-project__ray | rllib/core/models/torch/primitives.py | {
"start": 8853,
"end": 15305
} | class ____(nn.Module):
"""A model containing a CNN with N Conv2D layers.
All layers share the same activation function, bias setup (use bias or not),
and LayerNorm setup (use layer normalization or not).
Note that there is no flattening nor an additional dense layer at the end of the
stack. The ou... | TorchCNN |
python | pytorch__pytorch | torch/export/unflatten.py | {
"start": 9398,
"end": 10018
} | class ____(abc.ABC):
"""
Adapts input arguments with ``input_spec`` to align ``target_spec``.
"""
@abc.abstractmethod
def adapt(
self,
target_spec: pytree.TreeSpec,
input_spec: pytree.TreeSpec,
input_args: list[Any],
metadata: Optional[dict[str, Any]] = None,... | FlatArgsAdapter |
python | python-openxml__python-docx | tests/image/test_tiff.py | {
"start": 9382,
"end": 12183
} | class ____:
def it_constructs_the_right_class_for_a_given_ifd_entry(self, fixture):
stream_rdr, offset, entry_cls_, ifd_entry_ = fixture
ifd_entry = _IfdEntryFactory(stream_rdr, offset)
entry_cls_.from_stream.assert_called_once_with(stream_rdr, offset)
assert ifd_entry is ifd_entry_
... | Describe_IfdEntryFactory |
python | run-llama__llama_index | llama-index-core/llama_index/core/instrumentation/events/embedding.py | {
"start": 156,
"end": 547
} | class ____(BaseEvent):
"""
EmbeddingStartEvent.
Args:
model_dict (dict): Model dictionary containing details about the embedding model.
"""
model_config = ConfigDict(protected_namespaces=("pydantic_model_",))
model_dict: dict
@classmethod
def class_name(cls) -> str:
"... | EmbeddingStartEvent |
python | coleifer__peewee | tests/schema.py | {
"start": 27964,
"end": 28104
} | class ____(TestModel):
content = TextField()
timestamp = TimestampField()
status = IntegerField()
flags = IntegerField()
| NoteX |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_block_documents.py | {
"start": 10523,
"end": 11069
} | class ____:
async def test_read_missing_block_document(self, client):
response = await client.get(f"/block_documents/{uuid4()}")
assert response.status_code == status.HTTP_404_NOT_FOUND
async def test_read_nonsense_block_document(self, client):
"""Regression test for an issue we observe... | TestReadBlockDocument |
python | pyparsing__pyparsing | pyparsing/core.py | {
"start": 236231,
"end": 237437
} | class ____(TokenConverter):
"""Converter to return the matched tokens as a list - useful for
returning tokens of :class:`ZeroOrMore` and :class:`OneOrMore` expressions.
The optional ``aslist`` argument when set to True will return the
parsed tokens as a Python list instead of a pyparsing ParseResults.
... | Group |
python | pyqtgraph__pyqtgraph | pyqtgraph/opengl/items/GLTextItem.py | {
"start": 155,
"end": 4329
} | class ____(GLGraphicsItem):
"""Draws text in 3D."""
def __init__(self, parentItem=None, **kwds):
"""All keyword arguments are passed to setData()"""
super().__init__(parentItem=parentItem)
glopts = kwds.pop('glOptions', 'additive')
self.setGLOptions(glopts)
self.pos = n... | GLTextItem |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_shape_base_.py | {
"start": 11202,
"end": 16885
} | class ____(TestCase):
def test_integer_0_split(self):
a = np.arange(10)
assert_raises(ValueError, array_split, a, 0)
def test_integer_split(self):
a = np.arange(10)
res = array_split(a, 1)
desired = [np.arange(10)]
compare_results(res, desired)
res = arr... | TestArraySplit |
python | apache__airflow | airflow-ctl/tests/airflow_ctl/ctl/commands/test_variable_command.py | {
"start": 1145,
"end": 4377
} | class ____:
key = "key"
value = "value"
description = "description"
export_file_name = "exported_json.json"
parser = cli_parser.get_parser()
variable_collection_response = VariableCollectionResponse(
variables=[
VariableResponse(
key=key,
value... | TestCliVariableCommands |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/hyperparameter_tuning_job.py | {
"start": 19430,
"end": 21935
} | class ____(GoogleCloudBaseOperator):
"""
Deletes a HyperparameterTuningJob.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
:param hyperparameter_tuning_job_id: Requi... | DeleteHyperparameterTuningJobOperator |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.