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 | joke2k__faker | faker/providers/person/es_MX/__init__.py | {
"start": 46,
"end": 18571
} | class ____(PersonProvider):
formats = (
"{{first_name}} {{last_name}} {{last_name}}",
"{{first_name}} {{first_name}} {{last_name}}",
"{{first_name}} {{first_name}} {{last_name}} {{last_name}}",
"{{first_name}} {{last_name}}",
"{{prefix}} {{first_name}} {{last_name}}",
)
... | Provider |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/convolutional.py | {
"start": 45168,
"end": 57442
} | class ____(Conv2D):
"""Transposed convolution layer (sometimes called Deconvolution).
The need for transposed convolutions generally arises
from the desire to use a transformation going in the opposite direction
of a normal convolution, i.e., from something that has the shape of the
output of some convolutio... | Conv2DTranspose |
python | sdispater__pendulum | src/pendulum/tz/exceptions.py | {
"start": 169,
"end": 218
} | class ____(TimezoneError):
pass
| InvalidTimezone |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 14547,
"end": 14699
} | class ____(BaseModel):
"""
Response for the external log URL endpoint.
"""
url: Annotated[str, Field(title="Url")]
| ExternalLogUrlResponse |
python | sqlalchemy__sqlalchemy | test/base/test_examples.py | {
"start": 308,
"end": 454
} | class ____(
test_versioning.TestVersioning,
fixtures.RemoveORMEventsGlobally,
fixtures.TestBase,
):
pass
| VersionedRowsTestLegacyBase |
python | getsentry__sentry | tests/sentry/api/serializers/test_release.py | {
"start": 40475,
"end": 55598
} | class ____(TestCase):
def test_get_users_for_authors_finds_by_username(self) -> None:
user = self.create_user(email="john@company.com", name="John Smith")
project = self.create_project()
self.create_member(user=user, organization=project.organization)
integration = self.create_provid... | GetUsersForAuthorsUserMappingsTest |
python | kamyu104__LeetCode-Solutions | Python/minimum-reverse-operations.py | {
"start": 954,
"end": 1982
} | class ____(object):
def minReverseOperations(self, n, p, banned, k):
"""
:type n: int
:type p: int
:type banned: List[int]
:type k: int
:rtype: List[int]
"""
lookup = [False]*n
for i in banned:
lookup[i] = True
d = 0
... | Solution |
python | joke2k__faker | tests/providers/test_automotive.py | {
"start": 2103,
"end": 2263
} | class ____(_SimpleAutomotiveTestMixin):
"""Test az_AZ automotive provider methods"""
license_plate_pattern = re.compile(r"\d{2}-[A-Z]{2}-\d{3}")
| TestAzAz |
python | pytorch__pytorch | test/fx/test_z3_gradual_types.py | {
"start": 87827,
"end": 91084
} | class ____(unittest.TestCase):
def test_alexnet1(self):
alexnet = models.alexnet()
symbolic_traced: torch.fx.GraphModule = symbolic_trace(alexnet)
for n in symbolic_traced.graph.nodes:
n.type = Dyn
# print(symbolic_traced)
res = alexnet.forward(torch.rand(10, 3... | TestAlexNet |
python | django-haystack__django-haystack | test_haystack/elasticsearch5_tests/test_backend.py | {
"start": 50907,
"end": 55342
} | class ____(TestCase):
fixtures = ["bulk_data.json"]
def setUp(self):
super().setUp()
# Stow.
self.old_ui = connections["elasticsearch"].get_unified_index()
self.ui = UnifiedIndex()
self.smmi = Elasticsearch5AutocompleteMockModelSearchIndex()
self.ui.build(indexe... | LiveElasticsearch5AutocompleteTestCase |
python | donnemartin__interactive-coding-challenges | recursion_dynamic/longest_inc_subseq/test_longest_increasing_subseq.py | {
"start": 18,
"end": 611
} | class ____(unittest.TestCase):
def test_longest_increasing_subseq(self):
subseq = Subsequence()
self.assertRaises(TypeError, subseq.longest_inc_subseq, None)
self.assertEqual(subseq.longest_inc_subseq([]), [])
seq = [3, 4, -1, 0, 6, 2, 3]
expected = [-1, 0, 2, 3]
sel... | TestLongestIncreasingSubseq |
python | openai__openai-python | src/openai/types/beta/realtime/response_done_event.py | {
"start": 243,
"end": 494
} | class ____(BaseModel):
event_id: str
"""The unique ID of the server event."""
response: RealtimeResponse
"""The response resource."""
type: Literal["response.done"]
"""The event type, must be `response.done`."""
| ResponseDoneEvent |
python | kamyu104__LeetCode-Solutions | Python/sort-matrix-by-diagonals.py | {
"start": 47,
"end": 757
} | class ____(object):
def sortMatrix(self, grid):
"""
:type grid: List[List[int]]
:rtype: List[List[int]]
"""
lookup = [[] for _ in xrange((len(grid)-1)+(len(grid[0])-1)-(0-(len(grid[0])-1))+1)]
for i in xrange(len(grid)):
for j in xrange(len(grid[0])):
... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/overloadOverlap1.py | {
"start": 4877,
"end": 5394
} | class ____:
@overload
def method1(self, x: type) -> bool: ...
@overload
def method1(self, x: Any) -> str | bool: ...
def method1(self, x: Any) -> Any: ...
@overload
def func18(s: Sequence[_T1], extra: Literal[False]) -> list[_T1]: ...
@overload
def func18(s: Sequence[_T1], extra: Literal[True]... | ClassC |
python | django__django | django/contrib/redirects/admin.py | {
"start": 114,
"end": 270
} | class ____(admin.ModelAdmin):
list_display = ("old_path", "new_path")
list_filter = ("site",)
search_fields = ("old_path", "new_path")
| RedirectAdmin |
python | django__django | tests/generic_views/views.py | {
"start": 6469,
"end": 6900
} | class ____(generic.detail.SingleObjectMixin, generic.View):
model = Book
object = Book(name="dummy")
def get_object(self):
return Book(name="dummy")
def get_context_data(self, **kwargs):
context = {"custom_key": "custom_value"}
context.update(kwargs)
return super().get_... | CustomContextView |
python | numba__numba | numba/tests/test_ndarray_subclasses.py | {
"start": 2355,
"end": 3810
} | class ____(types.Array):
def __init__(self, dtype, ndim, layout, readonly=False, aligned=True):
name = f"MyArray({ndim}, {dtype}, {layout})"
super().__init__(dtype, ndim, layout, readonly=readonly,
aligned=aligned, name=name)
def copy(self, *args, **kwargs):
# T... | MyArrayType |
python | pytorch__pytorch | torch/export/unflatten.py | {
"start": 59848,
"end": 70202
} | class ____:
"""
Collect the intermediate values of mutations in a graph.
Example: in the following graph, suppose that buf_in and buf_out
are the input and output values of a buffer.
buf_in = placeholder()
...
ival1 = f0(buf_in, ...) # inside self.n0(...)
...
i... | _IVals |
python | scrapy__scrapy | tests/test_pipeline_files.py | {
"start": 12205,
"end": 12321
} | class ____(TestFilesPipelineFieldsMixin):
item_class = FilesPipelineTestAttrsItem
| TestFilesPipelineFieldsAttrsItem |
python | gevent__gevent | src/greentest/3.11/test_signal.py | {
"start": 44229,
"end": 51624
} | class ____(unittest.TestCase):
"""
Stress signal delivery, especially when a signal arrives in
the middle of recomputing the signal state or executing
previously tripped signal handlers.
"""
def setsig(self, signum, handler):
old_handler = signal.signal(signum, handler)
self.add... | StressTest |
python | tornadoweb__tornado | tornado/websocket.py | {
"start": 51391,
"end": 64092
} | class ____(simple_httpclient._HTTPConnection):
"""WebSocket client connection.
This class should not be instantiated directly; use the
`websocket_connect` function instead.
"""
protocol = None # type: WebSocketProtocol
def __init__(
self,
request: httpclient.HTTPRequest,
... | WebSocketClientConnection |
python | huggingface__transformers | src/transformers/models/dac/modeling_dac.py | {
"start": 11153,
"end": 17769
} | class ____(nn.Module):
"""
ResidualVectorQuantize block - Introduced in SoundStream: An end2end neural audio codec (https://huggingface.co/papers/2107.03312)
"""
def __init__(self, config: DacConfig):
super().__init__()
n_codebooks = config.n_codebooks
quantizer_dropout = confi... | DacResidualVectorQuantize |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/qr_op_test.py | {
"start": 1742,
"end": 6358
} | class ____(test.TestCase):
@test_util.run_in_graph_and_eager_modes(use_gpu=True)
def testWrongDimensions(self):
# The input to qr should be a tensor of at least rank 2.
scalar = constant_op.constant(1.)
with self.assertRaisesRegex((ValueError, errors_impl.InvalidArgumentError),
... | QrOpTest |
python | ray-project__ray | python/ray/tune/integration/pytorch_lightning.py | {
"start": 2436,
"end": 6224
} | class ____(TuneCallback):
"""PyTorch Lightning report and checkpoint callback
Saves checkpoints after each validation step. Also reports metrics to Tune,
which is needed for checkpoint registration.
Args:
metrics: Metrics to report to Tune. If this is a list,
each item describes th... | TuneReportCheckpointCallback |
python | pytorch__pytorch | torch/_dynamo/utils.py | {
"start": 168577,
"end": 169485
} | class ____:
_counter: int = 0
_id: int = -1
_depth = 0
@classmethod
def start(cls) -> None:
cls._depth = cls._depth + 1
if cls._depth == 1:
cls._id = _instruction_counter.start()
@classmethod
def end(cls) -> None:
cls._depth = cls._depth - 1
if c... | CompileTimeInstructionCounter |
python | getsentry__sentry | src/sentry/core/endpoints/project_details.py | {
"start": 3680,
"end": 4113
} | class ____(serializers.Serializer):
id = serializers.ChoiceField(required=True, choices=get_supported_biases_ids())
active = serializers.BooleanField(default=False)
def validate(self, data):
if data.keys() != {"id", "active"}:
raise serializers.ValidationError(
"Error: O... | DynamicSamplingBiasSerializer |
python | realpython__materials | inheritance-and-composition/composition/productivity.py | {
"start": 959,
"end": 1073
} | class ____:
def perform_duties(self, hours):
return f"manufactures gadgets for {hours} hours."
| FactoryRole |
python | PyCQA__pylint | tests/functional/m/mixin_class_rgx.py | {
"start": 880,
"end": 1084
} | class ____:
"""Class that does match the option pattern"""
def set_attribute(self):
"""Set an attribute outside of __init__"""
self.attr = 1
# Tests for no-member
| OutsideInitMixin |
python | streamlit__streamlit | lib/tests/streamlit/elements/markdown_test.py | {
"start": 8707,
"end": 12487
} | class ____(DeltaGeneratorTestCase):
"""Test st.badge API."""
def test_st_badge(self):
"""Test st.badge with all parameters."""
# Test with all parameters
st.badge(
"Badge with all params",
icon=":material/warning:",
color="red",
)
el ... | StBadgeAPITest |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pie/PIE796.py | {
"start": 514,
"end": 588
} | class ____(enum.Enum):
A = "A"
B = "B"
C = "C"
@unique
| FakeEnum7 |
python | walkccc__LeetCode | solutions/2975. Maximum Square Area by Removing Fences From a Field/2975.py | {
"start": 0,
"end": 628
} | class ____:
def maximizeSquareArea(
self,
m: int,
n: int,
hFences: list[int],
vFences: list[int],
) -> int:
hFences = sorted(hFences + [1, m])
vFences = sorted(vFences + [1, n])
hGaps = {hFences[i] - hFences[j]
for i in range(len(hFences))
for j in... | Solution |
python | walkccc__LeetCode | solutions/228. Summary Ranges/228.py | {
"start": 0,
"end": 385
} | class ____:
def summaryRanges(self, nums: list[int]) -> list[str]:
ans = []
i = 0
while i < len(nums):
begin = nums[i]
while i < len(nums) - 1 and nums[i] == nums[i + 1] - 1:
i += 1
end = nums[i]
if begin == end:
ans.append(str(begin))
else:
ans.appen... | Solution |
python | tensorflow__tensorflow | tensorflow/python/saved_model/load_test.py | {
"start": 5585,
"end": 97818
} | class ____(test.TestCase, parameterized.TestCase):
def test_structure_import(self, cycles, use_cpp_bindings):
# TODO(b/264869228) Fix LoadTest
if use_cpp_bindings:
self.skipTest("Not implemented for cpp.")
root = autotrackable.AutoTrackable()
root.dep_one = autotrackable.AutoTrackable()
roo... | LoadTest |
python | plotly__plotly.py | plotly/graph_objs/histogram/unselected/_marker.py | {
"start": 233,
"end": 3335
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "histogram.unselected"
_path_str = "histogram.unselected.marker"
_valid_props = {"color", "opacity"}
@property
def color(self):
"""
Sets the marker color of unselected points, applied only when a
selection exists.
... | Marker |
python | huggingface__transformers | src/transformers/models/jetmoe/configuration_jetmoe.py | {
"start": 876,
"end": 7548
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`JetMoeModel`]. It is used to instantiate a
JetMoe model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a configuration o... | JetMoeConfig |
python | numpy__numpy | numpy/polynomial/tests/test_laguerre.py | {
"start": 3265,
"end": 5919
} | class ____:
# coefficients of 1 + 2*x + 3*x**2
c1d = np.array([9., -14., 6.])
c2d = np.einsum('i,j->ij', c1d, c1d)
c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)
# some random values in [-1, 1)
x = np.random.random((3, 5)) * 2 - 1
y = polyval(x, [1., 2., 3.])
def test_lagval(self):
... | TestEvaluation |
python | python-pillow__Pillow | src/PIL/MpoImagePlugin.py | {
"start": 3096,
"end": 6722
} | class ____(JpegImagePlugin.JpegImageFile):
format = "MPO"
format_description = "MPO (CIPA DC-007)"
_close_exclusive_fp_after_loading = False
def _open(self) -> None:
self.fp.seek(0) # prep the fp in order to pass the JPEG test
JpegImagePlugin.JpegImageFile._open(self)
self._aft... | MpoImageFile |
python | getsentry__sentry | tests/sentry/seer/explorer/test_custom_tool_utils.py | {
"start": 4335,
"end": 9699
} | class ____(TestCase):
def setUp(self):
super().setUp()
create_test_regions()
self.organization = self.create_organization()
def test_validate_tool_class_nested(self):
"""Test validation fails for nested classes."""
class OuterClass:
class NestedTool(Explorer... | CustomToolUtilsTest |
python | astropy__astropy | astropy/visualization/interval.py | {
"start": 7813,
"end": 11601
} | class ____(BaseInterval):
"""
Interval based on IRAF's zscale.
Original implementation:
https://github.com/spacetelescope/stsci.numdisplay/blob/master/lib/stsci/numdisplay/zscale.py
Licensed under a 3-clause BSD style license (see AURA_LICENSE.rst).
Parameters
----------
n_samples : i... | ZScaleInterval |
python | ray-project__ray | python/ray/llm/_internal/common/utils/download_utils.py | {
"start": 609,
"end": 3721
} | class ____(enum.Enum):
"""Defines which files to download from cloud storage."""
MODEL_AND_TOKENIZER = enum.auto()
TOKENIZER_ONLY = enum.auto()
EXCLUDE_SAFETENSORS = enum.auto()
NONE = enum.auto()
def __bool__(self):
return self != NodeModelDownloadable.NONE
def union(self, other:... | NodeModelDownloadable |
python | huggingface__transformers | src/transformers/models/nllb_moe/modeling_nllb_moe.py | {
"start": 26208,
"end": 29855
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: NllbMoeConfig, is_sparse: bool = False, layer_idx: Optional[int] = None):
super().__init__()
self.embed_dim = config.d_model
self.is_sparse = is_sparse
self.self_attn = NllbMoeAttention(
embed_dim=self.emb... | NllbMoeDecoderLayer |
python | numba__numba | numba/tests/test_obj_lifetime.py | {
"start": 1054,
"end": 3806
} | class ____(object):
"""
An object which records events when instances created through it
are deleted. Custom events can also be recorded to aid in
diagnosis.
"""
def __init__(self):
self._counts = collections.defaultdict(int)
self._events = []
self._wrs = {}
def ma... | RefRecorder |
python | davidhalter__jedi | jedi/inference/gradual/typing.py | {
"start": 14907,
"end": 15601
} | class ____(Value):
def __init__(self, inference_state, parent_context, tree_node, type_value_set):
super().__init__(inference_state, parent_context)
self._type_value_set = type_value_set
self.tree_node = tree_node
def py__class__(self):
c, = self._type_value_set.py__class__()
... | NewType |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py | {
"start": 19222,
"end": 19512
} | class ____(graphene.ObjectType):
class Meta:
interfaces = (
GrapheneMessageEvent,
GrapheneDisplayableEvent,
GrapheneStepEvent,
GrapheneMarkerEvent,
)
name = "ResourceInitSuccessEvent"
| GrapheneResourceInitSuccessEvent |
python | python-pillow__Pillow | src/PIL/WebPImagePlugin.py | {
"start": 825,
"end": 10054
} | class ____(ImageFile.ImageFile):
format = "WEBP"
format_description = "WebP image"
__loaded = 0
__logical_frame = 0
def _open(self) -> None:
# Use the newer AnimDecoder API to parse the (possibly) animated file,
# and access muxed chunks like ICC/EXIF/XMP.
self._decoder = _w... | WebPImageFile |
python | ray-project__ray | doc/source/ray-core/doc_code/placement_group_example.py | {
"start": 1730,
"end": 3537
} | class ____:
def __init__(self):
pass
def ready(self):
pass
# Create a GPU actor on the first bundle of index 0.
actor2 = Actor.options(
scheduling_strategy=PlacementGroupSchedulingStrategy(
placement_group=pg,
placement_group_bundle_index=0,
)
).remote()
# Verify that... | Actor |
python | GoogleCloudPlatform__python-docs-samples | functions/v2/typed/googlechatbot/main.py | {
"start": 997,
"end": 2008
} | class ____:
cardId: str
card: Dict[str, Any]
# Required to serialize the response
def to_dict(self) -> dict:
return {
"cardsV2": {
"cardId": self.cardId,
"card": self.card,
}
}
@functions_framework.typed
def googlechatbot(req: Ch... | ChatResponse |
python | plotly__plotly.py | plotly/graph_objs/icicle/_hoverlabel.py | {
"start": 233,
"end": 11234
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "icicle"
_path_str = "icicle.hoverlabel"
_valid_props = {
"align",
"alignsrc",
"bgcolor",
"bgcolorsrc",
"bordercolor",
"bordercolorsrc",
"font",
"namelength",
"namelengthsrc",
... | Hoverlabel |
python | getsentry__sentry | src/sentry/analytics/event_manager.py | {
"start": 157,
"end": 661
} | class ____:
def __init__(self) -> None:
self._event_types: MutableMapping[Any, type[Event]] = {}
def register(self, event_cls: type[Event]) -> None:
event_type = event_cls.type
if event_type in self._event_types:
assert self._event_types[event_type] == event_cls
else... | EventManager |
python | astropy__astropy | astropy/units/tests/test_quantity_erfa_ufuncs.py | {
"start": 626,
"end": 12866
} | class ____:
@classmethod
def setup_class(cls):
cls.pv_unit = u.Unit("AU,AU/day")
cls.pv_value = np.array(
[
([1.0, 0.0, 0.0], [0.0, 0.0125, 0.0]),
([0.0, 1.0, 0.0], [-0.0125, 0.0, 0.0]),
],
dtype=erfa_ufunc.dt_pv,
)
... | TestPVUfuncs |
python | optuna__optuna | optuna/artifacts/_filesystem.py | {
"start": 230,
"end": 2416
} | class ____:
"""An artifact store for file systems.
Args:
base_path:
The base path to a directory to store artifacts.
Example:
.. code-block:: python
import os
import optuna
from optuna.artifacts import FileSystemArtifactStore
fr... | FileSystemArtifactStore |
python | crytic__slither | slither/solc_parsing/slither_compilation_unit_solc.py | {
"start": 3347,
"end": 39496
} | class ____(CallerContextExpression):
# pylint: disable=too-many-instance-attributes
def __init__(self, compilation_unit: SlitherCompilationUnit) -> None:
super().__init__()
self._compilation_unit: SlitherCompilationUnit = compilation_unit
self._contracts_by_id: Dict[int, Contract] = {}... | SlitherCompilationUnitSolc |
python | ray-project__ray | python/ray/autoscaler/_private/spark/spark_job_server.py | {
"start": 7271,
"end": 11357
} | class ____(ThreadingHTTPServer):
"""
High level design:
1. In Ray on spark autoscaling mode, How to start and terminate Ray worker node ?
It uses spark job to launch Ray worker node,
and each spark job contains only one spark task, the corresponding spark task
creates Ray worker node as subpro... | SparkJobServer |
python | mahmoud__boltons | boltons/dictutils.py | {
"start": 26465,
"end": 30935
} | class ____(dict):
"""Implements a one-to-one mapping dictionary. In addition to
inheriting from and behaving exactly like the builtin
:class:`dict`, all values are automatically added as keys on a
reverse mapping, available as the `inv` attribute. This
arrangement keeps key and value namespaces dist... | OneToOne |
python | huggingface__transformers | tests/models/mm_grounding_dino/test_modeling_mm_grounding_dino.py | {
"start": 3136,
"end": 9847
} | class ____:
def __init__(
self,
parent,
batch_size=4,
is_training=True,
use_labels=True,
hidden_size=32,
num_hidden_layers=2,
num_attention_heads=4,
intermediate_size=4,
hidden_act="gelu",
hidden_dropout_prob=0.1,
attent... | MMGroundingDinoModelTester |
python | tensorflow__tensorflow | tensorflow/python/autograph/tests/basic_list_test.py | {
"start": 2450,
"end": 4106
} | class ____(reference_test_base.TestCase):
def setUp(self):
super(ReferenceTest, self).setUp()
self.autograph_opts = tf.autograph.experimental.Feature.LISTS
def test_tensor_mutation(self):
self.assertConvertedMatchesNative(mutation, [0] * 10, 10)
def test_basic(self):
self.all_inputs_tensors = T... | ReferenceTest |
python | django__django | django/contrib/postgres/search.py | {
"start": 11957,
"end": 12213
} | class ____(Func):
output_field = FloatField()
def __init__(self, expression, string, **extra):
if not hasattr(string, "resolve_expression"):
string = Value(string)
super().__init__(expression, string, **extra)
| TrigramBase |
python | django-extensions__django-extensions | django_extensions/management/commands/dumpscript.py | {
"start": 28804,
"end": 28899
} | class ____(Exception):
"""Value could not be parsed or should simply be skipped."""
| SkipValue |
python | huggingface__transformers | tests/models/instructblipvideo/test_modeling_instructblipvideo.py | {
"start": 8276,
"end": 11263
} | class ____:
def __init__(
self,
parent,
batch_size=12,
seq_length=7,
is_training=True,
use_input_mask=True,
use_labels=True,
vocab_size=99,
hidden_size=32,
projection_dim=32,
num_hidden_layers=2,
num_attention_heads=4,
... | InstructBlipVideoQFormerModelTester |
python | huggingface__transformers | src/transformers/models/dpt/modeling_dpt.py | {
"start": 27404,
"end": 29257
} | class ____(nn.Module):
"""
ResidualConvUnit, pre-activate residual unit.
Args:
config (`[DPTConfig]`):
Model configuration class defining the model architecture.
"""
def __init__(self, config: DPTConfig):
super().__init__()
self.use_batch_norm = config.use_batc... | DPTPreActResidualLayer |
python | getsentry__sentry | src/sentry/taskworker/state.py | {
"start": 168,
"end": 1133
} | class ____:
id: str
namespace: str
taskname: str
attempt: int
processing_deadline_duration: int
retries_remaining: bool
def current_task() -> CurrentTaskState | None:
if not hasattr(_current_state, "state"):
_current_state.state = None
return _current_state.state
def set_cur... | CurrentTaskState |
python | redis__redis-py | tests/test_pubsub.py | {
"start": 33924,
"end": 34440
} | class ____:
@skip_if_server_version_lt("3.0.0")
@skip_if_redis_enterprise()
def test_connection_error_raised_when_connection_dies(self, r):
p = r.pubsub()
p.subscribe("foo")
assert wait_for_message(p) == make_message("subscribe", "foo", 1)
for client in r.client_list():
... | TestPubSubConnectionKilled |
python | plotly__plotly.py | _plotly_utils/png.py | {
"start": 10275,
"end": 10392
} | class ____(Exception):
def __str__(self):
return self.__class__.__name__ + ": " + " ".join(self.args)
| Error |
python | pytorch__pytorch | torch/testing/_internal/common_distributed.py | {
"start": 55644,
"end": 57469
} | class ____(nn.Module):
def __init__(
self,
forward_inputs: dict[nn.Module, torch.Tensor],
cast_forward_inputs: bool,
) -> None:
super().__init__()
self.c1 = SaveForwardInputsModule(forward_inputs, cast_forward_inputs)
self.c2 = SaveForwardInputsModule(forward_inpu... | SaveForwardInputsModel |
python | huggingface__transformers | src/transformers/models/exaone4/modeling_exaone4.py | {
"start": 24150,
"end": 24253
} | class ____(GenericForTokenClassification, Exaone4PreTrainedModel):
pass
| Exaone4ForTokenClassification |
python | plotly__plotly.py | plotly/graph_objs/layout/_selection.py | {
"start": 235,
"end": 17147
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout"
_path_str = "layout.selection"
_valid_props = {
"line",
"name",
"opacity",
"path",
"templateitemname",
"type",
"x0",
"x1",
"xref",
"y0",
"y1",
"yr... | Selection |
python | huggingface__transformers | src/transformers/models/blip/modeling_blip_text.py | {
"start": 3299,
"end": 9306
} | class ____(nn.Module):
def __init__(self, config, is_cross_attention, layer_idx=None):
super().__init__()
self.config = config
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
"The hidden size (%d... | BlipTextSelfAttention |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramSpec27.py | {
"start": 513,
"end": 1252
} | class ____(Protocol[P]):
def __call__(self, a: int, /, *args: P.args, **kwargs: P.kwargs) -> None: ...
ConcatCallableHandler: TypeAlias = Callable[Concatenate[int, P], None]
handler_callable1: Callable[..., None] = func1
concat_handler_callable1: ConcatCallableHandler[...] = func1
# This should generate an err... | ConcatHandler |
python | sqlalchemy__sqlalchemy | test/orm/test_attributes.py | {
"start": 97728,
"end": 105093
} | class ____(fixtures.ORMTest):
def test_receive_changes(self):
"""test that Listeners can mutate the given value."""
class Foo:
pass
class Bar:
pass
def append(state, child, initiator):
b2 = Bar()
b2.data = b1.data + " appended"
... | ListenerTest |
python | getsentry__sentry | fixtures/integrations/mock_service.py | {
"start": 295,
"end": 3725
} | class ____(StubService):
"""
A mock is a service that replicates the functionality of a real software
system by implementing the same interface with simplified business logic.
For example, a mocked random dice_roll function might return `hash(time()) % 6`.
Like stubs, mocks can make tests simpler an... | MockService |
python | pypa__warehouse | tests/unit/admin/views/test_users.py | {
"start": 57353,
"end": 59686
} | class ____:
def test_burns_recovery_codes(self, db_request, monkeypatch, user_service):
user = UserFactory.create()
codes = user_service.generate_recovery_codes(user.id)
user_service._check_ratelimits = pretend.call_recorder(
user_service._check_ratelimits
)
# Bu... | TestUserBurnRecoveryCodes |
python | numba__numba | numba/core/bytecode.py | {
"start": 22797,
"end": 25041
} | class ____(serialize.ReduceMixin):
"""
A function's identity and metadata.
Note this typically represents a function whose bytecode is
being compiled, not necessarily the top-level user function
(the two might be distinct).
"""
_unique_ids = itertools.count(1)
@classmethod
def from... | FunctionIdentity |
python | getsentry__sentry | src/sentry/api/permissions.py | {
"start": 1854,
"end": 2609
} | class ____(BasePermission):
"""
This permission class is used for endpoints that should ONLY be accessible
by staff.
"""
def has_permission(self, request: Request, view: object) -> bool:
return is_active_staff(request)
# NOTE(schew2381): This is a temporary permission that does NOT perfor... | StaffPermission |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/one_hot_op_test.py | {
"start": 981,
"end": 12875
} | class ____(test.TestCase, parameterized.TestCase):
def _testOneHot(self,
truth,
use_gpu=False,
expected_err_re=None,
raises=None,
dtype=None,
**inputs):
with self.cached_session(use_gpu=use_gpu):
if ... | OneHotTest |
python | python-pillow__Pillow | src/PIL/PdfParser.py | {
"start": 7719,
"end": 9318
} | class ____(_DictBase):
def __setattr__(self, key: str, value: Any) -> None:
if key == "data":
collections.UserDict.__setattr__(self, key, value)
else:
self[key.encode("us-ascii")] = value
def __getattr__(self, key: str) -> str | time.struct_time:
try:
... | PdfDict |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 8905,
"end": 9967
} | class ____(VOTableSpecWarning):
r"""Nonstandard XML id.
XML ids must match the following regular expression::
^[A-Za-z_][A-Za-z0-9_\.\-]*$
The VOTable 1.1 says the following:
According to the XML standard, the attribute ``ID`` is a
string beginning with a letter or underscore (``... | W02 |
python | kamyu104__LeetCode-Solutions | Python/distinct-echo-substrings.py | {
"start": 1273,
"end": 1979
} | class ____(object):
def distinctEchoSubstrings(self, text):
"""
:type text: str
:rtype: int
"""
result = set()
for l in xrange(1, len(text)//2+1):
count = sum(text[i] == text[i+l] for i in xrange(l))
for i in xrange(len(text)-2*l):
... | Solution2 |
python | kamyu104__LeetCode-Solutions | Python/self-crossing.py | {
"start": 29,
"end": 1050
} | class ____(object):
def isSelfCrossing(self, x):
"""
:type x: List[int]
:rtype: bool
"""
if len(x) >= 5 and x[3] == x[1] and x[4] + x[0] >= x[2]:
# Crossing in a loop:
# 2
# 3 ┌────┐
# └─══>┘1
# 4 0 (overla... | Solution |
python | tensorflow__tensorflow | tensorflow/python/distribute/sharded_variable.py | {
"start": 6423,
"end": 8878
} | class ____(Partitioner):
"""Partitioner that keeps shards below `max_shard_bytes`.
This partitioner ensures each shard has at most `max_shard_bytes`, and tries
to allocate as few shards as possible, i.e., keeping shard size as large
as possible.
If the partitioner hits the `max_shards` limit, then each shar... | MaxSizePartitioner |
python | jazzband__django-oauth-toolkit | tests/test_auth_backends.py | {
"start": 5881,
"end": 7543
} | class ____(BaseTest):
def dummy_get_response(self, request):
return HttpResponse()
def test_middleware_wrong_headers(self):
m = OAuth2ExtraTokenMiddleware(self.dummy_get_response)
request = self.factory.get("/a-resource")
m(request)
self.assertFalse(hasattr(request, "acc... | TestOAuth2ExtraTokenMiddleware |
python | matplotlib__matplotlib | lib/matplotlib/testing/compare.py | {
"start": 2639,
"end": 2941
} | class ____:
def __call__(self, orig, dest):
try:
subprocess.run(
[mpl._get_executable_info("magick").executable, orig, dest],
check=True)
except subprocess.CalledProcessError as e:
raise _ConverterError() from e
| _MagickConverter |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/binary_test.py | {
"start": 3299,
"end": 4672
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, in_one, in_two, dtype, device, op_func):
self.inputs = {
"in_one": torch.bernoulli(0.5 * torch.ones(in_one, device=device)).to(
dtype=dtype
),
"in_two": torch.bernoulli(0.5 * torch.ones(in_two, device... | BinaryOpBcastBenchmark |
python | kamyu104__LeetCode-Solutions | Python/distribute-candies-to-people.py | {
"start": 1031,
"end": 1966
} | class ____(object):
def distributeCandies(self, candies, num_people):
"""
:type candies: int
:type num_people: int
:rtype: List[int]
"""
# find max integer p s.t. sum(1 + 2 + ... + p) <= C
left, right = 1, candies
while left <= right:
mid =... | Solution2 |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/roles.py | {
"start": 3878,
"end": 4330
} | class ____(TypedColumnsClauseRole[_T_co]):
# note when using generics for ExpressionElementRole,
# the generic type needs to be in
# sqlalchemy.sql.coercions._impl_lookup mapping also.
# these are set up for basic types like int, bool, str, float
# right now
__slots__ = ()
_role_name = "SQL... | ExpressionElementRole |
python | apache__airflow | providers/standard/src/airflow/providers/standard/utils/weekday.py | {
"start": 961,
"end": 2685
} | class ____(enum.IntEnum):
"""Python Enum containing Days of the Week."""
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
SUNDAY = 7
@classmethod
def get_weekday_number(cls, week_day_str: str):
"""
Return the ISO Week Day Number for a We... | WeekDay |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/exceptions.py | {
"start": 987,
"end": 1334
} | class ____(Exception):
"""Raise when ECS tasks fail to start AFTER processing the request."""
def __init__(self, message: str):
self.message = message
super().__init__(message)
def __reduce__(self):
"""Return ECSTask state and its message."""
return EcsTaskFailToStart, (sel... | EcsTaskFailToStart |
python | plotly__plotly.py | plotly/graph_objs/scatter3d/_marker.py | {
"start": 233,
"end": 28903
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter3d"
_path_str = "scatter3d.marker"
_valid_props = {
"autocolorscale",
"cauto",
"cmax",
"cmid",
"cmin",
"color",
"coloraxis",
"colorbar",
"colorscale",
"colorsrc",
... | Marker |
python | GoogleCloudPlatform__python-docs-samples | containeranalysis/snippets/samples_test.py | {
"start": 1991,
"end": 2653
} | class ____:
"""Custom class to handle incoming Pub/Sub messages."""
def __init__(self, expected_msg_nums: int, done_event: threading.Event) -> None:
# initialize counter to 0 on initialization
self.msg_count = 0
self.expected_msg_nums = expected_msg_nums
self.done_event = done_e... | MessageReceiver |
python | numpy__numpy | numpy/distutils/tests/test_fcompiler_gnu.py | {
"start": 1168,
"end": 1643
} | class ____:
def test_g77_version(self):
fc = numpy.distutils.fcompiler.new_fcompiler(compiler='gnu')
for vs, version in g77_version_strings:
v = fc.version_match(vs)
assert_(v == version, (vs, v))
def test_not_g77(self):
fc = numpy.distutils.fcompiler.new_fcompil... | TestG77Versions |
python | optuna__optuna | optuna/visualization/_terminator_improvement.py | {
"start": 869,
"end": 7458
} | class ____(NamedTuple):
trial_numbers: list[int]
improvements: list[float]
errors: list[float] | None
@experimental_func("3.2.0")
def plot_terminator_improvement(
study: Study,
plot_error: bool = False,
improvement_evaluator: BaseImprovementEvaluator | None = None,
error_evaluator: BaseErr... | _ImprovementInfo |
python | PrefectHQ__prefect | tests/cli/test_work_pool.py | {
"start": 21228,
"end": 27827
} | class ____:
async def test_update_description(self, prefect_client, work_pool):
assert work_pool.description is None
assert work_pool.type is not None
assert work_pool.base_job_template is not None
assert work_pool.is_paused is not None
assert work_pool.concurrency_limit is N... | TestUpdate |
python | TheAlgorithms__Python | machine_learning/astar.py | {
"start": 687,
"end": 1395
} | class ____:
"""
Class cell represents a cell in the world which have the properties:
position: represented by tuple of x and y coordinates initially set to (0,0).
parent: Contains the parent cell object visited before we arrived at this cell.
g, h, f: Parameters used when calling our heuristic funct... | Cell |
python | mlflow__mlflow | dev/clint/tests/rules/test_no_class_based_tests.py | {
"start": 304,
"end": 508
} | class ____:
def test_feature_a(self):
assert True
def test_feature_b(self):
assert True
def helper_method(self):
return 42
# Bad - another class-based test
| TestSomething |
python | aimacode__aima-python | probabilistic_learning.py | {
"start": 122,
"end": 5334
} | class ____:
"""
A probability distribution formed by observing and counting examples.
If p is an instance of this class and o is an observed value, then
there are 3 main operations:
p.add(o) increments the count for observation o by 1.
p.sample() returns a random element from the distribution.
... | CountingProbDist |
python | huggingface__transformers | src/transformers/models/emu3/modeling_emu3.py | {
"start": 19105,
"end": 21207
} | class ____(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: Optional[int] = None,
quant_channels: Optional[int] = None,
):
super().__init__()
self.in_channels = in_channels
out_channels = in_channels if out_channels is None else out_channels... | Emu3VQVAEResnetBlock |
python | kamyu104__LeetCode-Solutions | Python/super-ugly-number.py | {
"start": 808,
"end": 1553
} | class ____(object):
def nthSuperUglyNumber(self, n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
uglies, idx, heap, ugly_set = [0] * n, [0] * len(primes), [], set([1])
uglies[0] = 1
for k, p in enumerate(primes):
heapq... | Solution2 |
python | PyCQA__pylint | doc/data/messages/s/super-init-not-called/bad.py | {
"start": 118,
"end": 224
} | class ____(Fruit):
def __init__(self): # [super-init-not-called]
print("Creating an apple")
| Apple |
python | Textualize__textual | src/textual/widgets/_button.py | {
"start": 946,
"end": 1052
} | class ____(Exception):
"""Exception raised if an invalid button variant is used."""
| InvalidButtonVariant |
python | scikit-learn__scikit-learn | benchmarks/bench_plot_nmf.py | {
"start": 6555,
"end": 15395
} | class ____(NMF):
"""Non-Negative Matrix Factorization (NMF) with projected gradient solver.
This class is private and for comparison purpose only.
It may change or disappear without notice.
"""
def __init__(
self,
n_components=None,
solver="pg",
init=None,
... | _PGNMF |
python | pyca__cryptography | src/cryptography/hazmat/primitives/hashes.py | {
"start": 4349,
"end": 4725
} | class ____(HashAlgorithm):
name = "blake2b"
_max_digest_size = 64
_min_digest_size = 1
block_size = 128
def __init__(self, digest_size: int):
if digest_size != 64:
raise ValueError("Digest size must be 64")
self._digest_size = digest_size
@property
def digest_s... | BLAKE2b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.