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 | tensorflow__tensorflow | tensorflow/core/function/trace_type/trace_type_test.py | {
"start": 16784,
"end": 20598
} | class ____(test.Benchmark):
def benchmarkTensor(self):
shapes = [[1], [2, 19], [5, 11, 24], [4, 5, 9, 23]]
tensors = []
for s in shapes:
tensors.append(array_ops.zeros(s))
def encode_tensors(tensors):
trace_type.from_value(tensors)
iterations = 100000
t = timeit.timeit(lambda: e... | TraceTypeGenerationBenchmark |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/enumAuto1.py | {
"start": 82,
"end": 307
} | class ____(Enum):
ALWAYS = auto()
NEVER = auto()
AUTO = auto()
a: CacheBehavior = CacheBehavior.ALWAYS
b: CacheBehavior = CacheBehavior["ALWAYS"]
foo = "A" + "UTO"
c: CacheBehavior = CacheBehavior[foo]
| CacheBehavior |
python | pytorch__pytorch | test/quantization/pt2e/test_quantize_pt2e.py | {
"start": 105894,
"end": 116833
} | class ____(PT2EQuantizationTestCase):
def test_channel_group_quantization(self):
from torch.ao.quantization.observer import MappingType, PerGroup, PerToken
from torch.ao.quantization.pt2e._affine_quantization import (
AffineQuantizedMinMaxObserver,
)
class BackendAQuanti... | TestQuantizePT2EAffineQuantization |
python | pytorch__pytorch | torch/_dynamo/_trace_wrapped_higher_order_op.py | {
"start": 6127,
"end": 9234
} | class ____(HigherOrderOperator):
def __init__(self) -> None:
super().__init__("trace_wrapped")
def __call__(self, *args: Any, **kwargs: Any) -> Any:
return super().__call__(*args, **kwargs)
# TODO(jansel): need to ensure this does not get DCEed
_trace_wrapped_op = TraceWrapped()
def _assert... | TraceWrapped |
python | pytorch__pytorch | torch/testing/_internal/inductor_utils.py | {
"start": 11039,
"end": 13564
} | class ____(GraphLowering):
"""Minimal mock graph handler for testing virtualized context."""
def __init__(self, name_to_buffer=None):
import torch._inductor.sizevars
self.sizevars = torch._inductor.sizevars.SizeVarAllocator()
self.name_to_buffer = name_to_buffer or {}
self.grap... | MockGraphHandler |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclass1.py | {
"start": 1120,
"end": 1195
} | class ____:
aaa: str
ddd: InitVar[int] = 3
@dataclass(init=False)
| DC3 |
python | keras-team__keras | keras/src/ops/image.py | {
"start": 5272,
"end": 7706
} | class ____(Operation):
def __init__(self, data_format=None, *, name=None):
super().__init__(name=name)
self.data_format = backend.standardize_data_format(data_format)
def call(self, images):
return backend.image.hsv_to_rgb(images, data_format=self.data_format)
def compute_output_sp... | HSVToRGB |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_tuple.py | {
"start": 667,
"end": 2203
} | class ____(importlib.abc.MetaPathFinder):
def find_spec(self, fullname, path, target=None):
# Check if the import is the problematic one
if fullname in redirect_imports:
try:
# Attempt to import the standalone module
name = fullname.removeprefix("test.")
... | RedirectImportFinder |
python | django__django | tests/model_forms/models.py | {
"start": 3982,
"end": 4237
} | class ____(models.FileField):
def save_form_data(self, instance, data):
been_here = getattr(self, "been_saved", False)
assert not been_here, "save_form_data called more than once"
setattr(self, "been_saved", True)
| CustomFileField |
python | jazzband__django-oauth-toolkit | oauth2_provider/views/generic.py | {
"start": 1132,
"end": 1317
} | class ____(ScopedResourceMixin, ClientProtectedResourceView):
"""Impose scope restrictions if client protection fallsback to access token."""
pass
| ClientProtectedScopedResourceView |
python | ray-project__ray | python/ray/llm/tests/batch/cpu/stages/test_stage_base.py | {
"start": 1087,
"end": 3659
} | class ____:
class SimpleUDF(StatefulStageUDF):
def __init__(
self,
data_column: str,
expected_input_keys: Optional[List[str]] = None,
udf_output_missing_idx_in_batch_column: bool = False,
):
super().__init__(data_column, expected_input_keys... | TestStatefulStageUDF |
python | keras-team__keras | keras/src/layers/layer_test.py | {
"start": 538,
"end": 949
} | class ____:
"""Mock remat by returning a wrapper Mock calling the original function"""
def __init__(self):
self.rematted_functions = {}
def __call__(self, func):
if func in self.rematted_functions:
return self.rematted_functions[func]
wrapped_func = mock.Mock(wraps=fun... | MockRemat |
python | allegroai__clearml | clearml/backend_api/services/v2_13/events.py | {
"start": 14489,
"end": 20337
} | class ____(NonStrictDataModel):
"""
An entire plot (not single datapoint) and it's layout.
Used for plotting ROC curves, confidence matrices, etc. when evaluating the net.
:param timestamp: Epoch milliseconds UTC, will be set by the server if not set.
:type timestamp: float
:param ... | MetricsPlotEvent |
python | encode__django-rest-framework | rest_framework/fields.py | {
"start": 48649,
"end": 51578
} | class ____(Field):
default_error_messages = {
'invalid': _('Duration has wrong format. Use one of these formats instead: {format}.'),
'max_value': _('Ensure this value is less than or equal to {max_value}.'),
'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
... | DurationField |
python | pandas-dev__pandas | asv_bench/benchmarks/timeseries.py | {
"start": 3490,
"end": 4095
} | class ____:
params = [date_range, period_range, timedelta_range]
param_names = ["time_index"]
def setup(self, time_index):
N = 10**6
if time_index is timedelta_range:
self.idx = time_index(start=0, freq="min", periods=N)
else:
self.idx = time_index(start="201... | Iteration |
python | dateutil__dateutil | src/dateutil/tz/__init__.py | {
"start": 325,
"end": 444
} | class ____(Warning):
"""Warning raised when time zones are parsed from deprecated formats."""
| DeprecatedTzFormatWarning |
python | chroma-core__chroma | chromadb/errors.py | {
"start": 1448,
"end": 1574
} | class ____(ChromaError):
@classmethod
@overrides
def name(cls) -> str:
return "InvalidUUID"
| InvalidUUIDError |
python | getsentry__sentry | tests/sentry/workflow_engine/endpoints/validators/test_base_workflow.py | {
"start": 13755,
"end": 28078
} | class ____(TestCase):
def setUp(self) -> None:
self.context = {
"organization": self.organization,
"request": self.make_request(),
}
self.integration, self.org_integration = self.create_provider_integration_for(
provider="slack", organization=self.organiz... | TestWorkflowValidatorUpdate |
python | tensorflow__tensorflow | tensorflow/python/saved_model/nested_structure_coder_test.py | {
"start": 21542,
"end": 21915
} | class ____(type_spec.TypeSpec):
value_type = property(lambda self: None)
_component_specs = property(lambda self: ())
_to_components = lambda self, v: ()
_from_components = classmethod(lambda cls, c: cls())
_serialize = lambda self: ()
# Trivial TypeSpec class for testing.
@type_spec_registry.register("Nest... | UnregisteredTypeSpec |
python | python-pillow__Pillow | src/PIL/Image.py | {
"start": 107584,
"end": 114029
} | class ____(abc.ABC):
"""
Used as a mixin by geometry transforms
(for use with :py:meth:`~PIL.Image.Image.transform`)
"""
@abc.abstractmethod
def transform(
self,
size: tuple[int, int],
image: Image,
**options: Any,
) -> Image:
pass
# ---------------... | ImageTransformHandler |
python | google__jax | tests/array_interoperability_test.py | {
"start": 15487,
"end": 15887
} | class ____(jtu.JaxTestCase):
@unittest.skipIf((not tf or tf_version < (2, 5, 0)),
"Test requires TensorFlow 2.5.0 or newer")
def testJaxAndTfHaveTheSameBfloat16Type(self):
self.assertEqual(np.dtype(jnp.bfloat16).num,
np.dtype(tf.dtypes.bfloat16.as_numpy_dtype).num)
if ... | Bfloat16Test |
python | kamyu104__LeetCode-Solutions | Python/string-compression.py | {
"start": 29,
"end": 880
} | class ____(object):
def compress(self, chars):
"""
:type chars: List[str]
:rtype: int
"""
anchor, write = 0, 0
for read, c in enumerate(chars):
if read+1 == len(chars) or chars[read+1] != c:
chars[write] = chars[anchor]
writ... | Solution |
python | django-haystack__django-haystack | test_haystack/test_fields.py | {
"start": 21337,
"end": 21980
} | class ____(TestCase):
def test_init(self):
try:
foo = FacetDateField(model_attr="foo")
foo_exact = FacetDateField(facet_for="bar")
except:
self.fail()
self.assertEqual(foo.facet_for, None)
self.assertEqual(foo_exact.null, True)
self.assert... | FacetDateFieldTestCase |
python | kamyu104__LeetCode-Solutions | Python/largest-plus-sign.py | {
"start": 33,
"end": 1029
} | class ____(object):
def orderOfLargestPlusSign(self, N, mines):
"""
:type N: int
:type mines: List[List[int]]
:rtype: int
"""
lookup = {tuple(mine) for mine in mines}
dp = [[0] * N for _ in xrange(N)]
result = 0
for i in xrange(N):
... | Solution |
python | huggingface__transformers | src/transformers/models/depth_anything/modeling_depth_anything.py | {
"start": 7708,
"end": 7950
} | class ____(PreTrainedModel):
config: DepthAnythingConfig
base_model_prefix = "depth_anything"
main_input_name = "pixel_values"
input_modalities = ("image",)
supports_gradient_checkpointing = True
| DepthAnythingPreTrainedModel |
python | great-expectations__great_expectations | great_expectations/render/renderer_configuration.py | {
"start": 4499,
"end": 4652
} | class ____(TypedDict):
"""Notes that can be added to the meta field of an Expectation."""
format: MetaNotesFormat
content: List[str]
| MetaNotes |
python | kamyu104__LeetCode-Solutions | Python/set-matrix-zeroes.py | {
"start": 62,
"end": 977
} | class ____(object):
# @param matrix, a list of lists of integers
# RETURN NOTHING, MODIFY matrix IN PLACE.
def setZeroes(self, matrix):
first_col = reduce(lambda acc, i: acc or matrix[i][0] == 0, xrange(len(matrix)), False)
first_row = reduce(lambda acc, j: acc or matrix[0][j] == 0, xrange(l... | Solution |
python | getsentry__sentry | tests/snuba/tagstore/test_tagstore_backend.py | {
"start": 1511,
"end": 42383
} | class ____(TestCase, SnubaTestCase, SearchIssueTestMixin, PerformanceIssueTestCase):
def setUp(self) -> None:
super().setUp()
self.ts = SnubaTagStorage()
self.proj1 = self.create_project()
env1 = "test"
env2 = "test2"
self.env3 = Environment.objects.create(
... | TagStorageTest |
python | pytorch__pytorch | torch/_dynamo/test_minifier_common.py | {
"start": 1096,
"end": 2208
} | class ____:
minifier_code: str
repro_code: str
def _get_module(self, t: str) -> str:
match = re.search(r"class Repro\(torch\.nn\.Module\):\s+([ ].*\n| *\n)+", t)
assert match is not None, "failed to find module"
r = match.group(0)
r = re.sub(r"\s+$", "\n", r, flags=re.MULTIL... | MinifierTestResult |
python | getsentry__sentry | src/sentry/api/endpoints/auth_config.py | {
"start": 941,
"end": 3609
} | class ____(Endpoint, OrganizationMixin):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
owner = ApiOwner.ENTERPRISE
# Disable authentication and permission requirements.
permission_classes = ()
def dispatch(self, request: HttpRequest, *args, **kwargs) -> HttpResponseBase:
... | AuthConfigEndpoint |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/binary_test.py | {
"start": 2203,
"end": 3299
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, M, N, K, device, dtype_one, dtype_two, op_func):
self.inputs = {
"input_one": torch.randn(M, N, K, device=device).to(dtype=dtype_one),
"input_two": torch.randn(M, N, K, device=device).to(dtype=dtype_two),
}
self.... | BinaryOpBenchmark |
python | mozilla__bleach | bleach/_vendor/html5lib/serializer.py | {
"start": 3635,
"end": 15682
} | class ____(object):
# attribute quoting options
quote_attr_values = "legacy" # be secure by default
quote_char = '"'
use_best_quote_char = True
# tag syntax options
omit_optional_tags = True
minimize_boolean_attributes = True
use_trailing_solidus = False
space_before_trailing_soli... | HTMLSerializer |
python | python-markdown__markdown | markdown/extensions/legacy_em.py | {
"start": 667,
"end": 1294
} | class ____(UnderscoreProcessor):
"""Emphasis processor for handling strong and em matches inside underscores."""
PATTERNS = [
EmStrongItem(re.compile(EM_STRONG2_RE, re.DOTALL | re.UNICODE), 'double', 'strong,em'),
EmStrongItem(re.compile(STRONG_EM2_RE, re.DOTALL | re.UNICODE), 'double', 'em,str... | LegacyUnderscoreProcessor |
python | python__mypy | mypy/test/data.py | {
"start": 17260,
"end": 26402
} | class ____:
"""Parsed test caseitem.
An item is of the form
[id arg]
.. data ..
"""
id: str
arg: str | None
# Processed, collapsed text data
data: list[str]
# Start line: 1-based, inclusive, relative to testcase
line: int
# End line: 1-based, exclusive, relative to ... | TestItem |
python | realpython__materials | game-of-life-python/source_code_final/rplife/grid.py | {
"start": 45,
"end": 1538
} | class ____:
def __init__(self, pattern):
self.pattern = pattern
def evolve(self):
neighbors = (
(-1, -1), # Above left
(-1, 0), # Above
(-1, 1), # Above right
(0, -1), # Left
(0, 1), # Right
(1, -1), # Below left
... | LifeGrid |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/experimental/rapidsmpf/collectives/common.py | {
"start": 1321,
"end": 2913
} | class ____:
"""
Context manager to reserve collective IDs for pipeline execution.
Parameters
----------
ir : IR
The root IR node of the pipeline.
Notes
-----
This context manager:
1. Identifies all Shuffle nodes in the IR
2. Reserves collective IDs from the vacancy pool... | ReserveOpIDs |
python | doocs__leetcode | solution/0800-0899/0829.Consecutive Numbers Sum/Solution.py | {
"start": 0,
"end": 258
} | class ____:
def consecutiveNumbersSum(self, n: int) -> int:
n <<= 1
ans, k = 0, 1
while k * (k + 1) <= n:
if n % k == 0 and (n // k - k + 1) % 2 == 0:
ans += 1
k += 1
return ans
| Solution |
python | nedbat__coveragepy | tests/test_coverage.py | {
"start": 41025,
"end": 44724
} | class ____(CoverageTest):
"""Tests of new syntax in Python 2.5."""
def test_with_statement(self) -> None:
self.check_coverage(
"""\
class Managed:
def __enter__(self):
desc = "enter"
def __exit__(self, type, value, tb):
... | Py25Test |
python | numpy__numpy | numpy/lib/tests/test_function_base.py | {
"start": 81855,
"end": 83724
} | class ____:
def test_simple(self):
x = np.arange(-10, 10, .1)
r = trapezoid(np.exp(-.5 * x ** 2) / np.sqrt(2 * np.pi), dx=0.1)
# check integral of normal equals 1
assert_almost_equal(r, 1, 7)
def test_ndim(self):
x = np.linspace(0, 1, 3)
y = np.linspace(0, 2, 8)... | TestTrapezoid |
python | pytorch__pytorch | torch/ao/nn/quantized/modules/functional_modules.py | {
"start": 163,
"end": 2819
} | class ____(torch.nn.Module):
r"""State collector class for float operations.
The instance of this class can be used instead of the ``torch.`` prefix for
some operations. See example usage below.
.. note::
This class does not provide a ``forward`` hook. Instead, you must use
one of the... | FloatFunctional |
python | huggingface__transformers | src/transformers/models/speecht5/modeling_speecht5.py | {
"start": 9538,
"end": 10649
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, layer_id=0):
super().__init__()
self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1
self.out_conv_dim = config.conv_dim[layer_id]
self.conv = nn.Conv1d(
self.in_conv_dim,
s... | SpeechT5LayerNormConvLayer |
python | great-expectations__great_expectations | great_expectations/expectations/expectation.py | {
"start": 13715,
"end": 14578
} | class ____(ModelMetaclass):
"""MetaExpectation registers Expectations as they are defined, adding them to the Expectation registry.
Any class inheriting from Expectation will be registered based on the value of the "expectation_type" class
attribute, or, if that is not set, by snake-casing the name of the ... | MetaExpectation |
python | django-guardian__django-guardian | guardian/models/models.py | {
"start": 7210,
"end": 8244
} | class ____(GroupObjectPermissionAbstract):
"""The default implementation of the GroupObjectPermissionAbstract model.
If `GUARDIAN_GROUP_OBJ_PERMS_MODEL` is not set at the beginning of the project, this model will be used.
Uses Django's contenttypes framework to store generic relations.
See Also:
... | GroupObjectPermission |
python | coleifer__peewee | tests/model_sql.py | {
"start": 36237,
"end": 38832
} | class ____(ModelDatabaseTestCase):
requires = [Emp, OCTest, UKVP]
def test_atomic_update(self):
query = OCTest.insert(a='foo', b=1).on_conflict(
conflict_target=(OCTest.a,),
update={OCTest.b: OCTest.b + 2})
self.assertSQL(query, (
'INSERT INTO "oc_test" ("a"... | TestOnConflictSQL |
python | sqlalchemy__sqlalchemy | test/sql/test_types.py | {
"start": 14946,
"end": 17226
} | class ____(fixtures.TestBase):
@testing.combinations(
(String(), String()),
(VARBINARY(), LargeBinary()),
(mysql.BINARY(), LargeBinary()),
(mysql.MEDIUMBLOB(), LargeBinary()),
(oracle.RAW(), LargeBinary()),
(pg.BYTEA(), LargeBinary()),
(VARCHAR(length=100), St... | AsGenericTest |
python | getsentry__sentry | tests/acceptance/test_project_servicehooks.py | {
"start": 179,
"end": 2409
} | class ____(AcceptanceTestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user("foo@example.com")
self.org = self.create_organization(name="Rowdy Tiger", owner=None)
self.team = self.create_team(organization=self.org, name="Mariachi Band")
self.project ... | ProjectServiceHooksTest |
python | Textualize__textual | tests/selection_list/test_selection_click_checkbox.py | {
"start": 241,
"end": 1520
} | class ____(App[None]):
"""Test selection list application."""
def __init__(self) -> None:
super().__init__()
self.clicks: list[int] = []
def compose(self) -> ComposeResult:
yield SelectionList[int](*[(str(n), n) for n in range(10)])
@on(SelectionList.SelectionToggled)
def ... | SelectionListApp |
python | pypa__pipenv | pipenv/vendor/packaging/specifiers.py | {
"start": 26456,
"end": 39742
} | class ____(BaseSpecifier):
"""This class abstracts handling of a set of version specifiers.
It can be passed a single specifier (``>=3.0``), a comma-separated list of
specifiers (``>=3.0,!=3.1``), or no specifier at all.
"""
def __init__(self, specifiers: str = "", prereleases: bool | None = None)... | SpecifierSet |
python | sqlalchemy__sqlalchemy | test/orm/test_relationships.py | {
"start": 106554,
"end": 107668
} | class ____(fixtures.TestBase):
"""test that local-remote is correctly determined for m2m"""
def test_local_remote(self, registry):
meta = MetaData()
t1 = Table("t1", meta, Column("id", Integer, primary_key=True))
t2 = Table("t2", meta, Column("id", Integer, primary_key=True))
t... | ViewOnlyLocalRemoteM2M |
python | sphinx-doc__sphinx | sphinx/builders/linkcheck.py | {
"start": 7557,
"end": 9884
} | class ____(SphinxPostTransform):
builders = ('linkcheck',)
default_priority = 800
def run(self, **kwargs: Any) -> None:
for node in self.document.findall():
if uri := self.find_uri(node):
self._add_uri(uri, node)
def find_uri(self, node: nodes.Element) -> str | None... | HyperlinkCollector |
python | apache__airflow | providers/google/tests/unit/google/common/hooks/test_base_google.py | {
"start": 5391,
"end": 6385
} | class ____:
def test_no_arguments(self):
gcp_hook = FallbackToDefaultProjectIdFixtureClass(321)
gcp_hook.method()
gcp_hook.mock.assert_called_once_with(project_id=321)
def test_default_project_id(self):
gcp_hook = FallbackToDefaultProjectIdFixtureClass(321)
gcp_hook.m... | TestFallbackToDefaultProjectId |
python | boto__boto3 | boto3/resources/model.py | {
"start": 7030,
"end": 20336
} | class ____:
"""
A model representing a resource, defined via a JSON description
format. A resource has identifiers, attributes, actions,
sub-resources, references and collections. For more information
on resources, see :ref:`guide_resources`.
:type name: string
:param name: The name of this... | ResourceModel |
python | redis__redis-py | redis/commands/core.py | {
"start": 218306,
"end": 220861
} | class ____(CommandsProtocol):
"""
Redis PubSub commands.
see https://redis.io/topics/pubsub
"""
def publish(self, channel: ChannelT, message: EncodableT, **kwargs) -> ResponseT:
"""
Publish ``message`` on ``channel``.
Returns the number of subscribers the message was deliver... | PubSubCommands |
python | getsentry__sentry | tests/sentry/core/endpoints/test_team_projects.py | {
"start": 613,
"end": 1585
} | class ____(APITestCase):
endpoint = "sentry-api-0-team-project-index"
method = "get"
def setUp(self) -> None:
super().setUp()
self.team = self.create_team(members=[self.user])
self.proj1 = self.create_project(teams=[self.team])
self.proj2 = self.create_project(teams=[self.te... | TeamProjectsListTest |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_multiarray.py | {
"start": 130347,
"end": 133182
} | class ____(TestCase):
def tst_basic(self, x, T, mask, val):
np.putmask(x, mask, val)
assert_equal(x[mask], np.array(val, T))
def test_ip_types(self):
unchecked_types = [bytes, str, np.void]
x = np.random.random(1000) * 100
mask = x < 40
for val in [-100, 0, 15]... | TestPutmask |
python | huggingface__transformers | src/transformers/models/deformable_detr/modeling_deformable_detr.py | {
"start": 12692,
"end": 15129
} | class ____(nn.Module):
"""
BatchNorm2d where the batch statistics and the affine parameters are fixed.
Copy-paste from torchvision.misc.ops with added eps before rqsrt, without which any other models than
torchvision.models.resnet[18,34,50,101] produce nans.
"""
def __init__(self, n):
... | DeformableDetrFrozenBatchNorm2d |
python | Pylons__pyramid | src/pyramid/predicates.py | {
"start": 8395,
"end": 9110
} | class ____:
def __init__(self, predicate):
self.predicate = predicate
def _notted_text(self, val):
# if the underlying predicate doesnt return a value, it's not really
# a predicate, it's just something pretending to be a predicate,
# so dont update the hash
if val:
... | Notted |
python | getsentry__sentry | src/sentry/interfaces/contexts.py | {
"start": 6318,
"end": 6473
} | class ____(ContextType):
type = "browser"
context_to_tag_mapping = {"": "{browser}", "name": "{name}"}
# viewport
@contexttype
| BrowserContextType |
python | getsentry__sentry | tests/sentry/relocation/api/endpoints/artifacts/test_index.py | {
"start": 4624,
"end": 7691
} | class ____(GetRelocationArtifactsTest):
@override_options({"staff.ga-rollout": True})
def test_bad_unprivileged_user(self) -> None:
self.login_as(user=self.owner, superuser=False, staff=False)
# Ensures we don't reveal existence info to improperly authenticated users.
does_not_exist_uui... | GetRelocationArtifactsBadTest |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/rnn_cell_test.py | {
"start": 96037,
"end": 100002
} | class ____(test.TestCase):
def _execute_rnn_on(self,
rnn_device=None,
cell_device=None,
input_device=None):
batch_size = 3
time_steps = 7
input_size = 5
num_units = 10
cell = rnn_cell.LSTMCell(num_units, use_peepholes=True)
gp... | TensorArrayOnCorrectDeviceTest |
python | celery__celery | t/unit/worker/test_request.py | {
"start": 2154,
"end": 2977
} | class ____:
def test_order(self):
class A:
pass
class B(A):
pass
class C(B):
pass
class D(C):
@classmethod
def mro(cls):
return ()
A.x = 10
assert mro_lookup(C, 'x') == A
assert ... | test_mro_lookup |
python | facelessuser__soupsieve | soupsieve/css_types.py | {
"start": 8818,
"end": 10192
} | class ____(Immutable):
"""Selector list."""
__slots__ = ("selectors", "is_not", "is_html", "_hash")
selectors: tuple[Selector | SelectorNull, ...]
is_not: bool
is_html: bool
def __init__(
self,
selectors: Iterable[Selector | SelectorNull] | None = None,
is_not: bool = ... | SelectorList |
python | django__django | tests/admin_views/admin.py | {
"start": 15205,
"end": 16026
} | class ____(admin.ModelAdmin):
list_display = ["title", "public"]
readonly_fields = (
"posted",
"awesomeness_level",
"coolness",
"value",
"multiline",
"multiline_html",
lambda obj: "foo",
"readonly_content",
)
inlines = [LinkInline]
@a... | PostAdmin |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/runtime_wrappers.py | {
"start": 4215,
"end": 4927
} | class ____:
def __init__(self, info, runtime_metadata, trace_joint):
self.base_idx = info.base_idx
self.unwrap_out = _unwrap_tensoralias if trace_joint else _identity
self.requires_grad = info.requires_grad
self.view_meta_sequence = info.view_meta_sequence
self.replay_views =... | AliasOfInputHandler |
python | pdm-project__pdm | src/pdm/pytest.py | {
"start": 6904,
"end": 7170
} | class ____(dict):
def get_all(self, name: str, fallback: list[str] | None = None) -> list[str] | None:
return [self[name]] if name in self else fallback
def __getitem__(self, __key: str) -> str:
return cast(str, dict.get(self, __key))
| Metadata |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1008073,
"end": 1045000
} | class ____(AnyMarkConfig):
"""
RectConfig schema wrapper.
Parameters
----------
align : dict, :class:`Align`, :class:`ExprRef`, Literal['left', 'center', 'right']
The horizontal alignment of the text or ranged marks (area, bar, image, rect, rule).
One of ``"left"``, ``"right"``, ``"... | RectConfig |
python | TheAlgorithms__Python | data_structures/stacks/stack_with_doubly_linked_list.py | {
"start": 185,
"end": 411
} | class ____[T]:
def __init__(self, data: T):
self.data = data # Assign data
self.next: Node[T] | None = None # Initialize next as null
self.prev: Node[T] | None = None # Initialize prev as null
| Node |
python | rapidsai__cudf | python/cudf/cudf/core/indexing_utils.py | {
"start": 1046,
"end": 1141
} | class ____:
"""An indexer for a boolean mask."""
key: BooleanMask
@dataclass
| MaskIndexer |
python | bokeh__bokeh | src/bokeh/models/widgets/markups.py | {
"start": 3177,
"end": 3527
} | class ____(Markup):
''' A block (paragraph) of text.
This Bokeh model corresponds to an HTML ``<p>`` element.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
__example__ = "examples/interactio... | Paragraph |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/solids.py | {
"start": 14588,
"end": 18208
} | class ____:
def __init__(self, represented_pipeline: RepresentedJob, solid_def_name: str):
self._represented_pipeline = check.inst_param(
represented_pipeline, "represented_pipeline", RepresentedJob
)
check.str_param(solid_def_name, "solid_def_name")
self._solid_def_snap ... | ISolidDefinitionMixin |
python | tiangolo__fastapi | tests/test_dependency_class.py | {
"start": 597,
"end": 3379
} | class ____:
def synchronous(self, value: str) -> str:
return value
async def asynchronous(self, value: str) -> str:
return value
def synchronous_gen(self, value: str) -> Generator[str, None, None]:
yield value
async def asynchronous_gen(self, value: str) -> AsyncGenerator[str,... | MethodsDependency |
python | mlflow__mlflow | mlflow/pyfunc/__init__.py | {
"start": 22303,
"end": 26848
} | class ____:
CONDA = "conda"
VIRTUALENV = "virtualenv"
def __init__(self):
raise NotImplementedError("This class is not meant to be instantiated.")
PY_VERSION = "python_version"
_logger = logging.getLogger(__name__)
def add_to_model(
model,
loader_module,
data=None,
code=None,
... | EnvType |
python | spyder-ide__spyder | spyder/api/config/mixins.py | {
"start": 601,
"end": 7026
} | class ____:
"""
Mixin used to access options stored in the Spyder configuration system.
"""
# Name of the configuration section that's going to be
# used to record the object's permanent data in Spyder
# config system.
CONF_SECTION = None
def get_conf(
self,
option: Con... | SpyderConfigurationAccessor |
python | tensorflow__tensorflow | tensorflow/python/ops/lookup_ops.py | {
"start": 35625,
"end": 44032
} | class ____(LookupInterface):
r"""String to Id table wrapper that assigns out-of-vocabulary keys to buckets.
For example, if an instance of `IdTableWithHashBuckets` is initialized with a
string-to-id table that maps:
* `emerson -> 0`
* `lake -> 1`
* `palmer -> 2`
The `IdTableWithHashBuckets` object will... | IdTableWithHashBuckets |
python | dask__distributed | distributed/worker_state_machine.py | {
"start": 27793,
"end": 28094
} | class ____(StateMachineEvent):
"""Scheduler -> Worker message containing updated who_has information.
See also
--------
RequestRefreshWhoHasMsg
"""
__slots__ = ("who_has",)
# {key: [worker address, ...]}
who_has: dict[Key, Collection[str]]
@dataclass
| RefreshWhoHasEvent |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/base.py | {
"start": 44772,
"end": 46480
} | class ____(default.DefaultExecutionContext):
def post_exec(self) -> None:
if (
self.isdelete
and cast(SQLCompiler, self.compiled).effective_returning
and not self.cursor.description
):
# All MySQL/mariadb drivers appear to not include
# cur... | MySQLExecutionContext |
python | django__django | tests/gis_tests/test_measure.py | {
"start": 4949,
"end": 8529
} | class ____(unittest.TestCase):
"Testing the Area object"
def test_init(self):
"Testing initialization from valid units"
a = Area(sq_m=100)
self.assertEqual(a.sq_m, 100)
a = A(sq_m=100)
self.assertEqual(a.sq_m, 100)
a = A(sq_mi=100)
self.assertEqual(a.sq... | AreaTest |
python | pytorch__pytorch | test/distributed/_shard/test_sharder.py | {
"start": 921,
"end": 1552
} | class ____(nn.Module):
def __init__(self, num_bags, num_embeddings_per_bag, num_dims):
super().__init__()
self.num_bags = num_bags
self.embedding_bags: nn.ModuleDict = nn.ModuleDict()
for i in range(num_bags):
self.embedding_bags[f"embedding_bag_{i}"] = nn.EmbeddingBag(
... | CustomEmbeddingBagCollection |
python | google__jax | jax/experimental/sparse/_base.py | {
"start": 772,
"end": 3239
} | class ____(util.StrictABC):
"""Base class for high-level JAX sparse objects."""
data: jax.Array
shape: tuple[int, ...]
nse: property
dtype: property
# Ignore type because of https://github.com/python/mypy/issues/4266.
__hash__ = None # type: ignore
def __len__(self):
return self.shape[0]
@prop... | JAXSparse |
python | numpy__numpy | numpy/_core/tests/test_umath.py | {
"start": 93865,
"end": 95135
} | class ____:
def test_nan_outputs(self):
assert_hypot_isnan(np.nan, np.nan)
assert_hypot_isnan(np.nan, 1)
def test_nan_outputs2(self):
assert_hypot_isinf(np.nan, np.inf)
assert_hypot_isinf(np.inf, np.nan)
assert_hypot_isinf(np.inf, 0)
assert_hypot_isinf(0, np.inf)... | TestHypotSpecialValues |
python | ray-project__ray | python/ray/tests/gpu_objects/test_gpu_objects_gloo.py | {
"start": 767,
"end": 1825
} | class ____:
@ray.method(tensor_transport="gloo")
def echo(self, data):
return data
def add(self, a, b):
return a + b
def double(self, data):
if isinstance(data, list):
return [self.double(d) for d in data]
if support_tensordict and isinstance(data, TensorDic... | GPUTestActor |
python | numba__numba | numba/core/typed_passes.py | {
"start": 7343,
"end": 8402
} | class ____(AnalysisPass):
_name = "annotate_types"
def __init__(self):
AnalysisPass.__init__(self)
def get_analysis_usage(self, AU):
AU.add_required(IRLegalization)
def run_pass(self, state):
"""
Create type annotation after type inference
"""
func_ir =... | AnnotateTypes |
python | sympy__sympy | sympy/geometry/exceptions.py | {
"start": 24,
"end": 131
} | class ____(ValueError):
"""An exception raised by classes in the geometry module."""
pass
| GeometryError |
python | numba__numba | numba/tests/test_analysis.py | {
"start": 30814,
"end": 33327
} | class ____(MemoryLeakMixin, TestCase):
# Tests SSA rewiring of phi nodes after branch pruning.
class SSAPrunerCompiler(CompilerBase):
def define_pipelines(self):
# This is a simple pipeline that does branch pruning on IR in SSA
# form, then types and lowers as per the standard n... | TestBranchPruneSSA |
python | weaviate__weaviate-python-client | weaviate/collections/classes/aggregate.py | {
"start": 4881,
"end": 5422
} | class ____(_MetricsNum):
def to_grpc(self) -> aggregate_pb2.AggregateRequest.Aggregation:
return aggregate_pb2.AggregateRequest.Aggregation(
property=self.property_name,
int=aggregate_pb2.AggregateRequest.Aggregation.Integer(
count=self.count,
maximum=... | _MetricsInteger |
python | ethereum__web3.py | tests/core/middleware/test_transaction_signing.py | {
"start": 1874,
"end": 12590
} | class ____(BaseProvider):
def make_request(self, method, params):
raise NotImplementedError(f"Cannot make request for {method}: {params}")
@pytest.fixture
def w3_dummy(request_mocker):
w3_base = Web3(provider=DummyProvider(), middleware=[])
with request_mocker(
w3_base,
mock_result... | DummyProvider |
python | matplotlib__matplotlib | tools/triage_tests.py | {
"start": 7752,
"end": 12655
} | class ____:
"""
A model for a single image comparison test.
"""
def __init__(self, path, root, source):
self.source = source
self.root = root
self.dir = path.parent
self.diff = path.name
self.reldir = self.dir.relative_to(self.root)
basename = self.diff[:... | Entry |
python | pypa__setuptools | setuptools/tests/test_install_scripts.py | {
"start": 186,
"end": 3433
} | class ____:
settings = dict(
name='foo',
entry_points={'console_scripts': ['foo=foo:foo']},
version='0.0',
)
unix_exe = '/usr/dummy-test-path/local/bin/python'
unix_spaces_exe = '/usr/bin/env dummy-test-python'
win32_exe = 'C:\\Dummy Test Path\\Program Files\\Python 3.6\\pyth... | TestInstallScripts |
python | lazyprogrammer__machine_learning_examples | rl2/mountaincar/pg_tf.py | {
"start": 3395,
"end": 6669
} | class ____:
def __init__(self, D, ft, hidden_layer_sizes=[]):
self.ft = ft
self.costs = []
# create the graph
self.layers = []
M1 = D
for M2 in hidden_layer_sizes:
layer = HiddenLayer(M1, M2)
self.layers.append(layer)
M1 = M2
# final layer
layer = HiddenLayer(M1, 1,... | ValueModel |
python | mahmoud__boltons | boltons/timeutils.py | {
"start": 18183,
"end": 20306
} | class ____(tzinfo):
"""Copied directly from the Python docs, the ``USTimeZone`` is a
:class:`datetime.tzinfo` subtype used to create the
:data:`Eastern`, :data:`Central`, :data:`Mountain`, and
:data:`Pacific` tzinfo types.
"""
def __init__(self, hours, reprname, stdname, dstname):
self.s... | USTimeZone |
python | huggingface__transformers | src/transformers/time_series_utils.py | {
"start": 2384,
"end": 2583
} | class ____(nn.Module):
def __init__(self, function):
super().__init__()
self.function = function
def forward(self, x, *args):
return self.function(x, *args)
| LambdaLayer |
python | django-import-export__django-import-export | tests/core/tests/test_tmp_storages.py | {
"start": 1001,
"end": 3635
} | class ____(TestCase):
def setUp(self):
self.test_string = b"""
id,name,author,author_email,imported,published,price,categories
2,Bar,1,,0,,,
1,Foo,,,0,,,
"""
def test_temp_folder_storage(self):
tmp_storage = TempFolderStorage()
tmp_storage.save(self.test_string)
name = tmp_stora... | TempStoragesTest |
python | pytorch__pytorch | test/dynamo/cpython/3_13/typinganndata/ann_module2.py | {
"start": 402,
"end": 470
} | class ____:
def meth(self, param: complex) -> None:
...
| NTC |
python | facebook__pyre-check | client/commands/daemon_querier.py | {
"start": 2850,
"end": 4259
} | class ____(abc.ABC):
@abc.abstractmethod
async def get_type_errors(
self,
paths: Iterable[Path],
) -> Union[DaemonQueryFailure, Dict[Path, List[error.Error]]]:
raise NotImplementedError()
@abc.abstractmethod
async def get_type_coverage(
self,
path: Path,
... | AbstractDaemonQuerier |
python | spyder-ide__spyder | spyder/plugins/tours/widgets.py | {
"start": 37645,
"end": 43469
} | class ____(QDialog, SvgToScaledPixmap):
"""Initial widget with tour."""
def __init__(self, parent, tour_function):
super().__init__(parent)
if MAC:
flags = (self.windowFlags() | Qt.WindowStaysOnTopHint
& ~Qt.WindowContextHelpButtonHint)
else:
... | OpenTourDialog |
python | pytorch__pytorch | torchgen/_autoheuristic/ah_tree.py | {
"start": 768,
"end": 9899
} | class ____:
"""
Custom decision tree implementation that mimics some of the sklearn API.
The purpose of this class it to be able to perform transformations, such as custom pruning, which
does not seem to be easy with sklearn.
"""
def __init__(self, sklearn_tree: Any, feature_names: list[str]) -... | DecisionTree |
python | run-llama__llama_index | llama-index-core/llama_index/core/postprocessor/node_recency.py | {
"start": 5597,
"end": 7591
} | class ____(BaseNodePostprocessor):
"""
Time-weighted post-processor.
Reranks a set of nodes based on their recency.
"""
time_decay: float = Field(default=0.99)
last_accessed_key: str = "__last_accessed__"
time_access_refresh: bool = True
# optionally set now (makes it easier to test)
... | TimeWeightedPostprocessor |
python | doocs__leetcode | solution/0100-0199/0119.Pascal's Triangle II/Solution.py | {
"start": 0,
"end": 232
} | class ____:
def getRow(self, rowIndex: int) -> List[int]:
f = [1] * (rowIndex + 1)
for i in range(2, rowIndex + 1):
for j in range(i - 1, 0, -1):
f[j] += f[j - 1]
return f
| Solution |
python | marshmallow-code__marshmallow | examples/flask_example.py | {
"start": 671,
"end": 826
} | class ____(db.Model): # type: ignore[name-defined]
id: Mapped[int] = mapped_column(primary_key=True)
first: Mapped[str]
last: Mapped[str]
| Author |
python | TheAlgorithms__Python | data_structures/heap/randomized_heap.py | {
"start": 1812,
"end": 5297
} | class ____[T: bool]:
"""
A data structure that allows inserting a new value and to pop the smallest
values. Both operations take O(logN) time where N is the size of the
structure.
Wiki: https://en.wikipedia.org/wiki/Randomized_meldable_heap
>>> RandomizedHeap([2, 3, 1, 5, 1, 7]).to_sorted_list(... | RandomizedHeap |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.