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 | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/conditionally_patch_dependency/package.py | {
"start": 218,
"end": 630
} | class ____(Package):
"""Package that conditionally requries a patched version
of a dependency."""
homepage = "http://www.example.com"
url = "http://www.example.com/patch-a-dependency-1.0.tar.gz"
version("1.0", md5="0123456789abcdef0123456789abcdef")
variant("jasper", default=False)
depends... | ConditionallyPatchDependency |
python | ray-project__ray | python/ray/tune/error.py | {
"start": 816,
"end": 1115
} | class ____(_SubCategoryTuneError):
"""Error that happens when waiting to get the next event to
handle from RayTrialExecutor.
Note: RayTaskError will be raised by itself and will not be using
this category. This category is for everything else."""
pass
| _TuneNoNextExecutorEventError |
python | pytorch__pytorch | test/torch_np/numpy_tests/linalg/test_linalg.py | {
"start": 3126,
"end": 10256
} | class ____:
def __init__(self, name, a, b, tags=None):
"""
A bundle of arguments to be passed to a test case, with an identifying
name, the operands a and b, and a set of tags to filter the tests
"""
if tags is None:
tags = set()
assert_(isinstance(name, s... | LinalgCase |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_doi.py | {
"start": 1571,
"end": 3865
} | class ____(ColumnMapExpectation):
"""Expect column values to be valid DOI format."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"well_formed_doi": [
... | ExpectColumnValuesToBeValidDoi |
python | streamlit__streamlit | lib/streamlit/runtime/caching/cache_resource_api.py | {
"start": 18084,
"end": 20856
} | class ____(Cache[R]):
"""Manages cached values for a single st.cache_resource function."""
def __init__(
self,
key: str,
max_entries: float,
ttl_seconds: float,
validate: ValidateFunc | None,
display_name: str,
) -> None:
super().__init__()
se... | ResourceCache |
python | scipy__scipy | scipy/io/_idl.py | {
"start": 4208,
"end": 4339
} | class ____:
'''Class used to define pointers'''
def __init__(self, index):
self.index = index
return
| Pointer |
python | protocolbuffers__protobuf | python/google/protobuf/internal/descriptor_pool_test.py | {
"start": 31311,
"end": 32867
} | class ____(DescriptorPoolTestBase, unittest.TestCase):
def setUp(self):
self.pool = descriptor_pool.Default()
self.factory_test1_fd = descriptor_pb2.FileDescriptorProto.FromString(
factory_test1_pb2.DESCRIPTOR.serialized_pb)
self.factory_test2_fd = descriptor_pb2.FileDescriptorProto.FromString(
... | DefaultDescriptorPoolTest |
python | automl__auto-sklearn | test/test_pipeline/components/data_preprocessing/test_minority_coalescence.py | {
"start": 339,
"end": 1045
} | class ____(unittest.TestCase):
def test_data_type_consistency(self):
X = np.random.randint(3, 6, (3, 4))
Y = MinorityCoalescer().fit_transform(X)
self.assertFalse(scipy.sparse.issparse(Y))
X = scipy.sparse.csc_matrix(
([3, 6, 4, 5], ([0, 1, 2, 1], [3, 2, 1, 0])), shape=(... | MinorityCoalescerTest |
python | kubernetes-client__python | kubernetes/client/models/v1_binding.py | {
"start": 383,
"end": 6673
} | 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... | V1Binding |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/never2.py | {
"start": 522,
"end": 657
} | class ____(Generic[T_contra]):
def __init__(self, x: T_contra): ...
def func3(x: U) -> U | ClassC[Never]:
return ClassC(x)
| ClassC |
python | getsentry__sentry | src/sentry/plugins/sentry_useragents/apps.py | {
"start": 36,
"end": 344
} | class ____(AppConfig):
name = "sentry.plugins.sentry_useragents"
def ready(self) -> None:
from sentry.plugins.base import register
from .models import BrowserPlugin, DevicePlugin, OsPlugin
register(BrowserPlugin)
register(OsPlugin)
register(DevicePlugin)
| Config |
python | dask__distributed | distributed/diagnostics/tests/test_nanny_plugin.py | {
"start": 6910,
"end": 7988
} | class ____(NannyPlugin):
def teardown(self, nanny):
raise RuntimeError("test error")
@gen_cluster(client=True, nthreads=[("", 1)], Worker=Nanny)
async def test_unregister_nanny_plugin_with_broken_teardown_raises(c, s, a):
await c.register_plugin(BrokenTeardownPlugin(), name="TestPlugin1")
with pyt... | BrokenTeardownPlugin |
python | joerick__pyinstrument | test/low_level/test_frame_info.py | {
"start": 154,
"end": 2671
} | class ____:
def get_frame_info_for_a_method(self, getter_function, del_local):
if del_local:
del self
frame = inspect.currentframe()
assert frame
return getter_function(frame)
def get_frame_info_with_cell_variable(self, getter_function, del_local):
def an_inn... | AClass |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_flow_runs.py | {
"start": 87418,
"end": 89923
} | class ____:
@pytest.fixture
def url(self) -> str:
return "/flow_runs/lateness"
@pytest.fixture()
async def late_flow_runs(self, session, flow):
flow_runs = []
for i in range(5):
one_minute_ago = now("UTC") - datetime.timedelta(minutes=1)
flow_run = await ... | TestFlowRunLateness |
python | pytorch__pytorch | torch/fx/passes/net_min_base.py | {
"start": 1184,
"end": 2297
} | class ____:
"""
Args:
`accumulate_error`: Instead of using a's input for both converted module to verify
, use the previous outputs of each converted module as input to accumulate the
errors.
`traverse_method`: "sequential" or "binary" or "accumulate"
Determine the way of traverse the nodes... | _MinimizerSettingBase |
python | getsentry__sentry | tests/apidocs/endpoints/teams/test_projects.py | {
"start": 136,
"end": 807
} | class ____(APIDocsTestCase):
def setUp(self) -> None:
team = self.create_team(organization=self.organization)
self.create_project(name="foo", organization=self.organization, teams=[team])
self.url = reverse(
"sentry-api-0-team-project-index",
kwargs={
... | TeamsProjectsDocs |
python | realpython__materials | python-unittest/skip_tests.py | {
"start": 29,
"end": 684
} | class ____(unittest.TestCase):
@unittest.skip("Unconditionally skipped test")
def test_unimportant(self):
self.fail("The test should be skipped")
@unittest.skipIf(sys.version_info < (3, 12), "Requires Python >= 3.12")
def test_using_calendar_constants(self):
import calendar
sel... | SkipTestExample |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/batch_test.py | {
"start": 2032,
"end": 11937
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(
count=[0, 28],
batch_size=[14, 15],
drop_remainder=[True, False],
n... | BatchTest |
python | allegroai__clearml | clearml/utilities/gpu/pyrsmi.py | {
"start": 3041,
"end": 5095
} | class ____(c_int):
RSMI_STATUS_SUCCESS = 0x0
RSMI_STATUS_INVALID_ARGS = 0x1
RSMI_STATUS_NOT_SUPPORTED = 0x2
RSMI_STATUS_FILE_ERROR = 0x3
RSMI_STATUS_PERMISSION = 0x4
RSMI_STATUS_OUT_OF_RESOURCES = 0x5
RSMI_STATUS_INTERNAL_EXCEPTION = 0x6
RSMI_STATUS_INPUT_OUT_OF_BOUNDS = 0x7
RSMI_STA... | rsmi_status_t |
python | psf__black | tests/data/cases/trailing_comma_optional_parens1.py | {
"start": 581,
"end": 1127
} | class ____:
def b(self):
if self.connection.mysql_is_mariadb and (
10,
4,
3,
) < self.connection.mysql_version < (10, 5, 2):
pass
# output
if e1234123412341234.winerror not in (
_winapi.ERROR_SEM_TIMEOUT,
_winapi.ERROR_PIPE_BUSY,
) or _check... | A |
python | pytorch__pytorch | torch/_subclasses/fake_tensor.py | {
"start": 45280,
"end": 128572
} | class ____(TorchDispatchMode):
cache: dict[_DispatchCacheKey, _DispatchCacheEntry] = {}
cache_hits: int = 0
cache_misses: int = 0
cache_bypasses: dict[str, int] = defaultdict(int)
# Every time you retrace using the same fake tensor mode, you should
# advance the epoch so we don't reuse unbacked ... | FakeTensorMode |
python | mlflow__mlflow | dev/pyproject.py | {
"start": 291,
"end": 4968
} | class ____(Enum):
SKINNY = "skinny"
RELEASE = "release"
DEV = "dev"
TRACING = "tracing"
def description(self) -> str:
WARNING = "# Auto-generated by dev/pyproject.py. Do not edit manually."
if self is PackageType.TRACING:
return f"""{WARNING}
# This file defines the pac... | PackageType |
python | Pylons__pyramid | src/pyramid/authentication.py | {
"start": 22464,
"end": 24227
} | class ____:
"""
This class represents an authentication token. You must pass in
the shared secret, the userid, and the IP address. Optionally you
can include tokens (a list of strings, representing role names),
'user_data', which is arbitrary data available for your own use in
later scripts. ... | AuthTicket |
python | django__django | tests/queries/models.py | {
"start": 6185,
"end": 6499
} | class ____(models.Model):
id = models.CharField(max_length=20, primary_key=True)
custom_pk = models.ManyToManyField(CustomPk)
tag = models.CharField(max_length=20)
# An inter-related setup with a model subclass that has a nullable
# path to another model, and a return path from that model.
| CustomPkTag |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1171661,
"end": 1171875
} | class ____(VegaLiteSchema):
"""SelectionInit schema wrapper."""
_schema = {"$ref": "#/definitions/SelectionInit"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| SelectionInit |
python | sqlalchemy__sqlalchemy | test/orm/test_core_compilation.py | {
"start": 111531,
"end": 112192
} | class ____(fixtures.DeclarativeMappedTest, _CoreCorrelateTest):
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class T1(Base):
__tablename__ = "t1"
a = Column(Integer, primary_key=True)
@hybridproperty
def c(self):
... | CorrelateTest |
python | ethereum__web3.py | web3/exceptions.py | {
"start": 8155,
"end": 8342
} | class ____(TaskNotRunning):
"""
Raised to alert the subscription manager that an exception occurred in the
subscription processing task.
"""
| SubscriptionHandlerTaskException |
python | kubernetes-client__python | kubernetes/client/models/v1_local_object_reference.py | {
"start": 383,
"end": 3958
} | 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... | V1LocalObjectReference |
python | getsentry__sentry | src/sentry/sentry_metrics/indexer/limiters/writes.py | {
"start": 7700,
"end": 8682
} | class ____:
"""
The WritesLimiterFactory is in charge of initializing the WritesLimiter
based on a configuration's namespace and options. Ideally this logic would
live in the initialization of the backends (postgres etc) but
since each backend supports multiple use cases dynamically we just keep the... | WritesLimiterFactory |
python | bokeh__bokeh | src/bokeh/models/ui/ui_element.py | {
"start": 1835,
"end": 3864
} | class ____(Model):
""" A base class for DOM-based UI elements with configurable styling.
"""
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
html_attributes = Dict(String, String, default={}, help="""
... | StyledElement |
python | pytorch__pytorch | test/quantization/pt2e/test_x86inductor_quantizer.py | {
"start": 22345,
"end": 23808
} | class ____(QuantizationTestCase):
def _test_quantizer(
self,
model,
example_inputs,
quantizer,
expected_node_occurrence,
expected_node_list=None,
is_qat=False,
debug=False,
lower=False,
):
m_eager = model.train() if is_qat else mode... | X86InductorQuantTestCase |
python | astropy__astropy | astropy/visualization/stretch.py | {
"start": 7094,
"end": 10264
} | class ____(BaseStretch):
r"""
A power stretch.
The stretch is given by:
.. math::
y = x^a
Parameters
----------
a : float
The power index (see the above formula). ``a`` must be greater
than 0.
Examples
--------
.. plot::
:show-source-link:
... | PowerStretch |
python | redis__redis-py | redis/commands/policies.py | {
"start": 7349,
"end": 8558
} | class ____(AsyncPolicyResolver):
"""
Async base class for policy resolvers.
"""
def __init__(
self, policies: PolicyRecords, fallback: Optional[AsyncPolicyResolver] = None
) -> None:
self._policies = policies
self._fallback = fallback
async def resolve(self, command_nam... | AsyncBasePolicyResolver |
python | eventlet__eventlet | tests/wsgi_test.py | {
"start": 4327,
"end": 6572
} | class ____(Exception):
pass
def send_expect_close(sock, buf):
# Some tests will induce behavior that causes the remote end to
# close the connection before all of the data has been written.
# With small kernel buffer sizes, this can cause an EPIPE error.
# Since the test expects an early close, th... | ConnectionClosed |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/assets/graph/remote_asset_graph.py | {
"start": 8587,
"end": 9149
} | class ____:
"""RemoteRepositoryAssetNode paired with additional information from that repository.
This split allows repository scoped asset graph to be constructed without depending on schedules/sensors
as defining schedule/sensors needs an asset graph.
"""
asset_node: RemoteRepositoryAssetNode
... | RepositoryScopedAssetInfo |
python | tensorflow__tensorflow | tensorflow/python/tpu/tpu_test.py | {
"start": 6591,
"end": 8583
} | class ____(test.TestCase):
def test_all_to_all_zero_split_count(self):
with self.assertRaisesRegex(
ValueError, "split_count 0 must at least be one"):
tpu_ops.all_to_all(
x=[0.0, 0.1652, 0.6543],
group_assignment=[1, -1],
concat_dimension=0,
split_dimension=0... | TPUOpsTest |
python | python-visualization__folium | folium/plugins/boat_marker.py | {
"start": 150,
"end": 2051
} | class ____(JSCSSMixin, Marker):
"""Add a Marker in the shape of a boat.
Parameters
----------
location: tuple of length 2, default None
The latitude and longitude of the marker.
If None, then the middle of the map is used.
heading: int, default 0
Heading of the boat to an an... | BoatMarker |
python | getsentry__sentry | src/sentry/quotas/base.py | {
"start": 8724,
"end": 8835
} | class ____(RateLimit):
def __init__(self, **kwargs):
super().__init__(False, **kwargs)
| NotRateLimited |
python | altair-viz__altair | altair/jupyter/jupyter_chart.py | {
"start": 3026,
"end": 15231
} | class ____(anywidget.AnyWidget):
_esm = load_js_src()
_css = r"""
.vega-embed {
/* Make sure action menu isn't cut off */
overflow: visible;
}
"""
# Public traitlets
chart = traitlets.Instance(TopLevelSpec, allow_none=True)
spec = traitlets.Dict(allow_none=True).tag(sync... | JupyterChart |
python | psf__black | tests/data/cases/class_methods_new_line.py | {
"start": 983,
"end": 1060
} | class ____:
a = 1
class Inner:
pass
| ClassWithSingleFieldWithInner |
python | geekcomputers__Python | AutoComplete_App/backend.py | {
"start": 29,
"end": 5339
} | class ____:
"""
It works by building a `WordMap` that stores words to word-follower-count
----------------------------
e.g. To train the following statement:
It is not enough to just know how tools work and what they worth,
we have got to learn how to use them and to use them well.
And with... | AutoComplete |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 15487,
"end": 16206
} | class ____(VOTableSpecWarning):
"""
The parser has encountered an element that does not exist in the
specification, or appears in an invalid context. Check the file
against the VOTable schema (with a tool such as `xmllint
<http://xmlsoft.org/xmllint.html>`__. If the file validates
against the ... | W10 |
python | scrapy__scrapy | tests/test_downloader_handlers_http_base.py | {
"start": 1882,
"end": 16388
} | class ____(ABC):
is_secure = False
@property
@abstractmethod
def download_handler_cls(self) -> type[DownloadHandlerProtocol]:
raise NotImplementedError
@async_yield_fixture
async def download_handler(self) -> AsyncGenerator[DownloadHandlerProtocol]:
dh = build_from_crawler(self... | TestHttpBase |
python | facebook__pyre-check | api/query.py | {
"start": 1343,
"end": 1961
} | class ____:
def __init__(self, call: Dict[str, Any]) -> None:
self.target: str = ""
if "target" in call:
self.target = call["target"]
else:
self.target = call["direct_target"]
self.kind: str = call["kind"]
self.locations: List[Location] = [
... | CallGraphTarget |
python | python__mypy | mypy/typeanal.py | {
"start": 104136,
"end": 104817
} | class ____(BoolTypeQuery):
def __init__(self) -> None:
super().__init__(ANY_STRATEGY)
def visit_any(self, t: AnyType) -> bool:
return t.type_of_any == TypeOfAny.explicit
def visit_typeddict_type(self, t: TypedDictType) -> bool:
# typeddict is checked during TypedDict declaration, s... | HasExplicitAny |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/quantization_test.py | {
"start": 2075,
"end": 4389
} | class ____(op_bench.TorchBenchmarkBase):
r"""Benchmarks both quantization and dequantization."""
def init(self, C, M, N, dtype, axis, mode):
assert mode in ("Q", "D")
self.input = torch.rand(C, M, N)
self.op = torch.quantize_per_channel
channel_len = (C, M, N)[axis]
se... | QuantizePerChannelBenchmark |
python | doocs__leetcode | solution/2900-2999/2954.Count the Number of Infection Sequences/Solution.py | {
"start": 111,
"end": 541
} | class ____:
def numberOfSequence(self, n: int, sick: List[int]) -> int:
nums = [b - a - 1 for a, b in pairwise([-1] + sick + [n])]
ans = 1
s = sum(nums)
ans = fac[s]
for x in nums:
if x:
ans = ans * pow(fac[x], mod - 2, mod) % mod
for x in ... | Solution |
python | getsentry__sentry | tests/sentry/analytics/test_event.py | {
"start": 466,
"end": 3305
} | class ____(TestCase):
@patch("sentry.analytics.event.uuid1")
def test_simple(self, mock_uuid1: MagicMock) -> None:
mock_uuid1.return_value = self.get_mock_uuid()
result = EventEnvelope(
event=ExampleEvent(
id=1,
map={"key": "value"},
o... | EventTest |
python | networkx__networkx | networkx/algorithms/link_analysis/tests/test_hits.py | {
"start": 371,
"end": 2546
} | class ____:
@classmethod
def setup_class(cls):
G = nx.DiGraph()
edges = [(1, 3), (1, 5), (2, 1), (3, 5), (5, 4), (5, 3), (6, 5)]
G.add_edges_from(edges, weight=1)
cls.G = G
cls.G.a = dict(
zip(sorted(G), [0.000000, 0.000000, 0.366025, 0.133975, 0.500000, 0.0... | TestHITS |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/trainer/trainer_factory.py | {
"start": 534,
"end": 5007
} | class ____:
def __init__(
self,
trainer_config: Dict[str, TrainerSettings],
output_path: str,
train_model: bool,
load_model: bool,
seed: int,
param_manager: EnvironmentParameterManager,
init_path: str = None,
multi_gpu: bool = False,
):
... | TrainerFactory |
python | miyuchina__mistletoe | test/test_block_token.py | {
"start": 17479,
"end": 19406
} | class ____(unittest.TestCase):
def test_match(self):
with patch('mistletoe.block_token.TableCell') as mock:
line = '| cell 1 | cell 2 |\n'
token = block_token.TableRow(line, line_number=10)
self.assertEqual(token.row_align, [None])
mock.assert_has_calls([call(... | TestTableRow |
python | chroma-core__chroma | chromadb/segment/impl/manager/cache/cache.py | {
"start": 200,
"end": 562
} | class ____(ABC):
@abstractmethod
def get(self, key: uuid.UUID) -> Optional[Segment]:
pass
@abstractmethod
def pop(self, key: uuid.UUID) -> Optional[Segment]:
pass
@abstractmethod
def set(self, key: uuid.UUID, value: Segment) -> None:
pass
@abstractmethod
def re... | SegmentCache |
python | Pylons__pyramid | src/pyramid/config/assets.py | {
"start": 7267,
"end": 9151
} | class ____:
"""
An asset source relative to a package.
If this asset source is a file, then we expect the ``prefix`` to point
to the new name of the file, and the incoming ``resource_name`` will be
the empty string, as returned by the ``FileOverride``.
"""
def __init__(self, package, pref... | PackageAssetSource |
python | doocs__leetcode | solution/1400-1499/1451.Rearrange Words in a Sentence/Solution.py | {
"start": 0,
"end": 222
} | class ____:
def arrangeWords(self, text: str) -> str:
words = text.split()
words[0] = words[0].lower()
words.sort(key=len)
words[0] = words[0].title()
return " ".join(words)
| Solution |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/strings_reduce_join_op_test.py | {
"start": 1086,
"end": 5378
} | class ____(test_util.TensorFlowTestCase,
parameterized.TestCase):
def test_rank_one(self):
input_array = [b'this', b'is', b'a', b'test']
truth = b'thisisatest'
truth_shape = []
with self.cached_session():
output = ragged_string_ops.reduce_join(
inputs=inp... | StringsReduceJoinOpTest |
python | google__jax | jax/_src/pallas/mosaic_gpu/core.py | {
"start": 48891,
"end": 49193
} | class ____:
def reduce(self, axes: int | Sequence[int]) -> "SomeLayout":
if isinstance(axes, int):
axes = (axes,)
return ReducedLayout(self, axes)
def to_mgpu(self, *args, **kwargs) -> mgpu.FragmentedLayout:
raise NotImplementedError
@dataclasses.dataclass(frozen=True)
| SomeLayout |
python | Lightning-AI__lightning | tests/tests_pytorch/loops/test_fetchers.py | {
"start": 1496,
"end": 3962
} | class ____(Dataset):
def __len__(self):
return 3
def __getitem__(self, idx):
return idx + 1
@pytest.mark.parametrize("multiple_iterables", [False, True])
@pytest.mark.parametrize("dataset_cls", [IterDataset, SizedDataset])
@pytest.mark.parametrize("prefetch_batches", list(range(5)))
def test_... | SizedDataset |
python | getsentry__sentry | tests/sentry/monitors/test_validators.py | {
"start": 34796,
"end": 35876
} | class ____(MonitorTestCase):
"""Base class for monitor validator tests with common setup."""
def setUp(self):
super().setUp()
self.user = self.create_user()
self.request = RequestFactory().get("/")
self.request.user = self.user
access = MagicMock()
access.has_any... | BaseMonitorValidatorTestCase |
python | matplotlib__matplotlib | lib/matplotlib/transforms.py | {
"start": 23215,
"end": 37747
} | class ____(BboxBase):
"""
A mutable bounding box.
Examples
--------
**Create from known bounds**
The default constructor takes the boundary "points" ``[[xmin, ymin],
[xmax, ymax]]``.
>>> Bbox([[1, 1], [3, 7]])
Bbox([[1.0, 1.0], [3.0, 7.0]])
Alternatively, a Bbox can b... | Bbox |
python | tensorflow__tensorflow | tensorflow/python/keras/saving/utils_v1/export_output.py | {
"start": 5989,
"end": 7136
} | class ____(ExportOutput):
"""Represents the output of a regression head."""
def __init__(self, value):
"""Constructor for `RegressionOutput`.
Args:
value: a float `Tensor` giving the predicted values. Required.
Raises:
ValueError: if the value is not a `Tensor` with dtype tf.float32.
... | RegressionOutput |
python | huggingface__transformers | src/transformers/models/plbart/modeling_plbart.py | {
"start": 51774,
"end": 58162
} | class ____(PLBartPreTrainedModel):
def __init__(self, config: PLBartConfig, **kwargs):
super().__init__(config, **kwargs)
self.model = PLBartModel(config)
self.classification_head = PLBartClassificationHead(
config.d_model,
config.d_model,
config.num_label... | PLBartForSequenceClassification |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride1.py | {
"start": 9334,
"end": 9416
} | class ____(A):
def test(self, t: Sequence[int]) -> list[str]: ...
| NarrowerReturn |
python | getsentry__sentry | src/sentry/backup/crypto.py | {
"start": 1678,
"end": 1934
} | class ____(Encryptor):
"""
Encrypt using a public key stored on the local machine.
"""
def __init__(self, fp: IO[bytes]):
self.__key = fp.read()
def get_public_key_pem(self) -> bytes:
return self.__key
| LocalFileEncryptor |
python | pytorch__pytorch | benchmarks/fastrnns/custom_lstms.py | {
"start": 6389,
"end": 6928
} | class ____(jit.ScriptModule):
def __init__(self, cell, *cell_args):
super().__init__()
self.cell = cell(*cell_args)
@jit.script_method
def forward(
self, input: Tensor, state: tuple[Tensor, Tensor]
) -> tuple[Tensor, tuple[Tensor, Tensor]]:
inputs = input.unbind(0)
... | LSTMLayer |
python | pallets__jinja | src/jinja2/exceptions.py | {
"start": 4126,
"end": 4458
} | class ____(TemplateSyntaxError):
"""Like a template syntax error, but covers cases where something in the
template caused an error at compile time that wasn't necessarily caused
by a syntax error. However it's a direct subclass of
:exc:`TemplateSyntaxError` and has the same attributes.
"""
| TemplateAssertionError |
python | bokeh__bokeh | tests/unit/bokeh/util/test_version.py | {
"start": 2365,
"end": 3097
} | class ____:
def test_release_version_unchanged(self) -> None:
assert buv._base_version_helper("0.2.3") == "0.2.3"
assert buv._base_version_helper("1.2.3") == "1.2.3"
def test_dev_version_stripped(self) -> None:
assert buv._base_version_helper("0.2.3.dev2") == "0.2.3"
assert buv.... | Test__base_version_helper |
python | pypa__pip | tests/unit/test_req.py | {
"start": 22862,
"end": 42207
} | class ____:
def setup_method(self) -> None:
self.tempdir = tempfile.mkdtemp()
def teardown_method(self) -> None:
shutil.rmtree(self.tempdir, ignore_errors=True)
def test_url_with_query(self) -> None:
"""InstallRequirement should strip the fragment, but not the query."""
url... | TestInstallRequirement |
python | django__django | tests/select_related/models.py | {
"start": 1233,
"end": 1360
} | class ____(models.Model):
name = models.CharField(max_length=50)
family = models.ForeignKey(Family, models.CASCADE)
| Genus |
python | cython__cython | tests/run/pyclass_scope_T671.py | {
"start": 38,
"end": 133
} | class ____(object):
"""
>>> SimpleAssignment.A
1234
"""
A = A
| SimpleAssignment |
python | coleifer__peewee | playhouse/sqlcipher_ext.py | {
"start": 2356,
"end": 3484
} | class ____(object):
server_version = __sqlcipher_version__
def _connect(self):
params = dict(self.connect_params)
passphrase = params.pop('passphrase', '').replace("'", "''")
conn = sqlcipher.connect(self.database, isolation_level=None, **params)
try:
if passphrase:... | _SqlCipherDatabase |
python | faif__python-patterns | patterns/other/hsm/hsm.py | {
"start": 5026,
"end": 5190
} | class ____(OutOfService):
"""No need to override any method."""
def __init__(self, HierachicalStateMachine):
self._hsm = HierachicalStateMachine
| Failed |
python | mlflow__mlflow | mlflow/utils/process.py | {
"start": 165,
"end": 6522
} | class ____(Exception):
@classmethod
def from_completed_process(cls, process):
lines = [
f"Non-zero exit code: {process.returncode}",
f"Command: {process.args}",
]
if process.stdout:
lines += [
"",
"STDOUT:",
... | ShellCommandException |
python | SmileyChris__easy-thumbnails | easy_thumbnails/tests/test_pixel_processors.py | {
"start": 6680,
"end": 8566
} | class ____(TestCase):
def test_standard(self):
image = Image.new('RGB', (800, 600))
processed = processors.colorspace(image)
self.assertEqual(processed.mode, 'RGB')
image = Image.new('L', (800, 600))
processed = processors.colorspace(image)
self.assertEqual(processe... | ColorspaceTest |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_font09.py | {
"start": 315,
"end": 1458
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_font09.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
python | django__django | tests/proxy_models/models.py | {
"start": 541,
"end": 665
} | class ____(models.Manager):
def get_queryset(self):
return super().get_queryset().exclude(name="wilma")
| SubManager |
python | pallets__werkzeug | src/werkzeug/formparser.py | {
"start": 4780,
"end": 10705
} | class ____:
"""This class implements parsing of form data for Werkzeug. By itself
it can parse multipart and url encoded form data. It can be subclassed
and extended but for most mimetypes it is a better idea to use the
untouched stream and expose it as separate attributes on a request
object.
... | FormDataParser |
python | kamyu104__LeetCode-Solutions | Python/find-duplicate-subtrees.py | {
"start": 50,
"end": 810
} | class ____(object):
def findDuplicateSubtrees(self, root):
"""
:type root: TreeNode
:rtype: List[TreeNode]
"""
def getid(root, lookup, trees):
if not root:
return -1
node_id = lookup[root.val,
getid(root.lef... | Solution |
python | astropy__astropy | astropy/modeling/functional_models.py | {
"start": 35760,
"end": 38714
} | class ____(_InverseTrigonometric1D):
"""
One dimensional ArcSine model returning values between -pi/2 and pi/2
only.
Parameters
----------
amplitude : float
Oscillation amplitude for corresponding Sine
frequency : float
Oscillation frequency for corresponding Sine
phase ... | ArcSine1D |
python | jina-ai__jina | tests/integration/pods/test_pod.py | {
"start": 15558,
"end": 17366
} | class ____(Executor):
@requests
def foo(self, docs, **kwargs):
for doc in docs:
if doc.text == 'slow':
time.sleep(1.0)
async def _start_create_pod(pod, port_generator, type='worker', executor=None):
port = port_generator()
pod = _create_worker_pod(port, f'{pod}/{typ... | FastSlowExecutor |
python | django-compressor__django-compressor | compressor/finders.py | {
"start": 96,
"end": 448
} | class ____(staticfiles.finders.BaseStorageFinder):
"""
A staticfiles finder that looks in COMPRESS_ROOT
for compressed files, to be used during development
with staticfiles development file server or during
deployment.
"""
storage = CompressorFileStorage
def list(self, ignore_patterns)... | CompressorFinder |
python | readthedocs__readthedocs.org | readthedocs/gold/views.py | {
"start": 822,
"end": 1976
} | class ____(
PrivateViewMixin,
DetailView,
FormView,
):
"""Gold subscription view."""
model = GoldUser
form_class = GoldSubscriptionForm
template_name = "gold/subscription_detail.html"
def get(self, *args, **kwargs):
subscribed = self.request.GET.get("subscribed", None)
... | GoldSubscription |
python | Lightning-AI__lightning | src/lightning/fabric/strategies/fsdp.py | {
"start": 3410,
"end": 34791
} | class ____(ParallelStrategy, _Sharded):
r"""Strategy for Fully Sharded Data Parallel provided by torch.distributed.
Fully Sharded Training shards the entire model across all available GPUs, allowing you to scale model
size, whilst using efficient communication to reduce overhead. In practice, this means we... | FSDPStrategy |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_maryland_zip.py | {
"start": 1751,
"end": 4094
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid Maryland zipcodes.
See https://pypi.org/project/zipcodes/ for more information.
"""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
... | ExpectColumnValuesToBeValidMarylandZip |
python | huggingface__transformers | src/transformers/models/mistral3/modeling_mistral3.py | {
"start": 7069,
"end": 7939
} | class ____(BaseModelOutputWithPast):
r"""
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
C... | Mistral3ModelOutputWithPast |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/dsl/ir.py | {
"start": 53408,
"end": 54600
} | class ____(IR):
"""
Produce a new dataframe selecting given expressions from an input.
This is a special case of :class:`Select` where all outputs are a single row.
"""
__slots__ = ("exprs",)
_non_child = ("schema", "exprs")
exprs: tuple[expr.NamedExpr, ...]
"""List of expressions to e... | Reduce |
python | numba__numba | numba/typed/listobject.py | {
"start": 1452,
"end": 1800
} | class ____(models.StructModel):
def __init__(self, dmm, fe_type):
members = [
('meminfo', _meminfo_listptr),
('data', types.voidptr), # ptr to the C list
]
super(ListModel, self).__init__(dmm, fe_type, members)
@register_model(ListTypeIterableType)
@register_model... | ListModel |
python | numpy__numpy | numpy/f2py/tests/test_modules.py | {
"start": 1853,
"end": 2301
} | class ____(util.F2PyTest):
module_name = "fmath"
sources = [
util.getpath("tests", "src", "modules", "use_modules.f90"),
]
def test_gh25867(self):
compiled_mods = [x for x in dir(self.module) if "__" not in x]
assert "useops" in compiled_mods
assert self.module.useops.su... | TestUsedModule |
python | doocs__leetcode | solution/1200-1299/1277.Count Square Submatrices with All Ones/Solution.py | {
"start": 0,
"end": 534
} | class ____:
def countSquares(self, matrix: List[List[int]]) -> int:
m, n = len(matrix), len(matrix[0])
f = [[0] * n for _ in range(m)]
ans = 0
for i, row in enumerate(matrix):
for j, v in enumerate(row):
if v == 0:
continue
... | Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/single_string_slots.py | {
"start": 299,
"end": 390
} | class ____:
__slots__ = ("bar",)
def __init__(self, bar):
self.bar = bar
| Foo |
python | huggingface__transformers | src/transformers/models/qwen3_next/modeling_qwen3_next.py | {
"start": 56254,
"end": 56361
} | class ____(GenericForTokenClassification, Qwen3NextPreTrainedModel):
pass
| Qwen3NextForTokenClassification |
python | crytic__slither | slither/detectors/functions/cyclomatic_complexity.py | {
"start": 508,
"end": 1856
} | class ____(AbstractDetector):
"""
Detects functions with high (> 11) cyclomatic complexity.
"""
ARGUMENT = "cyclomatic-complexity"
HELP = "Detects functions with high (> 11) cyclomatic complexity"
IMPACT = DetectorClassification.INFORMATIONAL
CONFIDENCE = DetectorClassification.HIGH
WI... | CyclomaticComplexity |
python | Pylons__pyramid | tests/test_testing.py | {
"start": 15030,
"end": 16773
} | class ____(unittest.TestCase):
def _callFUT(self, **kw):
from pyramid.testing import tearDown
return tearDown(**kw)
def tearDown(self):
from pyramid.threadlocal import manager
manager.clear()
getSiteManager.reset()
def _assertSMHook(self, hook):
result = g... | Test_tearDown |
python | getsentry__sentry | src/sentry/releases/endpoints/project_release_files.py | {
"start": 6907,
"end": 8475
} | class ____:
"""Provides artifact data to ChainPaginator on-demand"""
def __init__(
self, dist: Distribution | None, files: dict, query: list[str], checksums: list[str]
):
self._dist = dist
self._files = files
self._query = query
self._checksums = checksums
@cach... | ArtifactSource |
python | realpython__materials | duck-typing-python/shapes.py | {
"start": 147,
"end": 375
} | class ____:
def __init__(self, radius: float) -> None:
self.radius = radius
def area(self) -> float:
return pi * self.radius**2
def perimeter(self) -> float:
return 2 * pi * self.radius
| Circle |
python | getsentry__sentry | tests/sentry/workflow_engine/endpoints/test_validators.py | {
"start": 3150,
"end": 3420
} | class ____(MetricIssueComparisonConditionValidator):
supported_conditions = frozenset([Condition.GREATER_OR_EQUAL, Condition.LESS_OR_EQUAL])
supported_condition_results = frozenset([DetectorPriorityLevel.HIGH, DetectorPriorityLevel.LOW])
| MockDataConditionValidator |
python | pandas-dev__pandas | pandas/tests/test_nanops.py | {
"start": 33808,
"end": 36100
} | class ____:
# xref GH 11974
# Test data + skewness value (computed with scipy.stats.skew)
@pytest.fixture
def samples(self):
return np.sin(np.linspace(0, 1, 200))
@pytest.fixture
def actual_skew(self):
return -0.1875895205961754
@pytest.mark.parametrize("val", [3075.2, 3075... | TestNanskewFixedValues |
python | astropy__astropy | astropy/table/tests/test_masked.py | {
"start": 461,
"end": 1129
} | class ____:
def setup_method(self, method):
self.a = MaskedColumn(name="a", data=[1, 2, 3], fill_value=1)
self.b = MaskedColumn(name="b", data=[4, 5, 6], mask=True)
self.c = MaskedColumn(name="c", data=[7, 8, 9], mask=False)
self.d_mask = np.array([False, True, False])
self.d... | SetupData |
python | tiangolo__fastapi | docs_src/body/tutorial002_py310.py | {
"start": 61,
"end": 441
} | class ____(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
item_dict = item.dict()
if item.tax is not None:
price_with_tax = item.price + item.tax
item_dict.upda... | Item |
python | google__jax | tests/pallas/gpu_attention_test.py | {
"start": 6373,
"end": 6526
} | class ____(DecodeAttentionTest):
INTERPRET = True
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
| DecodeAttentionInterpretTest |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 105435,
"end": 105917
} | class ____(Blockwise):
_parameters = ["frame", "method", "skip_check"]
operation = staticmethod(methods.fillna_check)
_projection_passthrough = True
@functools.cached_property
def _meta(self):
return self.frame._meta
def _task(self, name: Key, index: int) -> Task:
args = [self.... | FillnaCheck |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.