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 | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 65395,
"end": 65725
} | class ____(BaseModel):
shard_id: int = Field(..., description="Local shard id")
shard_key: Optional["ShardKey"] = Field(default=None, description="User-defined sharding key")
points_count: int = Field(..., description="Number of points in the shard")
state: "ReplicaState" = Field(..., description="")
| LocalShardInfo |
python | django__django | django/contrib/auth/mixins.py | {
"start": 2627,
"end": 3920
} | class ____(AccessMixin):
"""Verify that the current user has all specified permissions."""
permission_required = None
def get_permission_required(self):
"""
Override this method to override the permission_required attribute.
Must return an iterable.
"""
if self.perm... | PermissionRequiredMixin |
python | pikepdf__pikepdf | src/pikepdf/models/image.py | {
"start": 1359,
"end": 1509
} | class ____(NotExtractableError):
"""Image contains high fidelity printing information and cannot be extracted."""
| HifiPrintImageNotTranscodableError |
python | walkccc__LeetCode | solutions/2201. Count Artifacts That Can Be Extracted/2201.py | {
"start": 0,
"end": 426
} | class ____:
def digArtifacts(
self,
n: int,
artifacts: list[list[int]],
dig: list[list[int]],
) -> int:
digged = set((r, c) for r, c in dig)
def canExtract(a: list[int]) -> bool:
for i in range(a[0], a[2] + 1):
for j in range(a[1], a[3] + 1):
if (i, j) not in... | Solution |
python | pypa__warehouse | tests/common/db/packaging.py | {
"start": 4176,
"end": 4420
} | class ____(WarehouseFactory):
class Meta:
model = RoleInvitation
invite_status = "pending"
token = "test_token"
user = factory.SubFactory(UserFactory)
project = factory.SubFactory(ProjectFactory)
| RoleInvitationFactory |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 24598,
"end": 24733
} | class ____(Interface):
"""
Marker interface for a list of accept headers with the most important
first.
"""
| IAcceptOrder |
python | django__django | tests/select_related/tests.py | {
"start": 375,
"end": 9144
} | class ____(TestCase):
@classmethod
def create_tree(cls, stringtree):
"""
Helper to create a complete tree.
"""
names = stringtree.split()
models = [Domain, Kingdom, Phylum, Klass, Order, Family, Genus, Species]
assert len(names) == len(models), (names, models)
... | SelectRelatedTests |
python | PyCQA__flake8 | src/flake8/exceptions.py | {
"start": 150,
"end": 249
} | class ____(Flake8Exception):
"""Except raised when encountering a KeyboardInterrupt."""
| EarlyQuit |
python | optuna__optuna | optuna/importance/_fanova/_evaluator.py | {
"start": 741,
"end": 4828
} | class ____(BaseImportanceEvaluator):
"""fANOVA importance evaluator.
Implements the fANOVA hyperparameter importance evaluation algorithm in
`An Efficient Approach for Assessing Hyperparameter Importance
<http://proceedings.mlr.press/v32/hutter14.html>`__.
fANOVA fits a random forest regression mo... | FanovaImportanceEvaluator |
python | falconry__falcon | falcon/redirects.py | {
"start": 818,
"end": 1647
} | class ____(HTTPStatus):
"""301 Moved Permanently.
The 301 (Moved Permanently) status code indicates that the target
resource has been assigned a new permanent URI.
Note:
For historical reasons, a user agent MAY change the request
method from POST to GET for the subsequent request. If ... | HTTPMovedPermanently |
python | tensorflow__tensorflow | tensorflow/python/saved_model/registration/registration_test.py | {
"start": 1417,
"end": 4587
} | class ____(test.TestCase, parameterized.TestCase):
@parameterized.parameters([
(RegisteredClass, "Custom.RegisteredClass"),
(RegisteredSubclass, "Custom.Subclass"),
(CustomPackage, "testing.CustomPackage"),
(CustomPackageAndName, "testing.name"),
])
def test_registration(self, expected_cl... | SerializableRegistrationTest |
python | ApeWorX__ape | tests/functional/test_trace.py | {
"start": 12245,
"end": 12710
} | class ____:
@pytest.mark.parametrize(
"key",
("geth", "geth-struct-log", "GETH_STRUCT_LOGS", TraceApproach.GETH_STRUCT_LOG_PARSE.value),
)
def test_from_key_geth_struct_log(self, key):
actual = TraceApproach.from_key(key)
assert actual == TraceApproach.GETH_STRUCT_LOG_PARSE
... | TestTraceApproach |
python | getsentry__sentry | src/sentry/api/endpoints/project_symbol_sources.py | {
"start": 4071,
"end": 8985
} | class ____(serializers.Serializer):
type = serializers.ChoiceField(
choices=[
("http", "SymbolServer (HTTP)"),
("gcs", "Google Cloud Storage"),
("s3", "Amazon S3"),
],
required=True,
help_text="The type of the source.",
)
id = serializers.C... | SourceSerializer |
python | mlflow__mlflow | tests/sagemaker/test_sagemaker_deployment_client.py | {
"start": 1021,
"end": 65170
} | class ____(NamedTuple):
model_path: str
run_id: str
model_uri: str
@pytest.fixture
def pretrained_model():
model_path = "model"
with mlflow.start_run():
X = np.array([-2, -1, 0, 1, 2, 1]).reshape(-1, 1)
y = np.array([0, 0, 1, 1, 1, 0])
lr = LogisticRegression(solver="lbfgs"... | TrainedModel |
python | matplotlib__matplotlib | lib/matplotlib/tri/_trirefine.py | {
"start": 1527,
"end": 13179
} | class ____(TriRefiner):
"""
Uniform mesh refinement by recursive subdivisions.
Parameters
----------
triangulation : `~matplotlib.tri.Triangulation`
The encapsulated triangulation (to be refined)
"""
# See Also
# --------
# :class:`~matplotlib.tri.CubicTriInterpolator` and
# ... | UniformTriRefiner |
python | bokeh__bokeh | src/bokeh/protocol/message.py | {
"start": 3391,
"end": 3425
} | class ____(TypedDict):
pass
| Empty |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeParams5.py | {
"start": 1266,
"end": 1404
} | class ____[R: (1, str)]: ...
v: type[int] = int
# This should generate an error because constraints must be legal
# type expressions.
| ClassM |
python | google__jax | jax/_src/core.py | {
"start": 13207,
"end": 14674
} | class ____:
__slots__ = ['compute_type', 'threefry_partitionable', 'xla_metadata',
'cur_abstract_mesh']
compute_type: str | None
threefry_partitionable: bool
xla_metadata: dict[str, Any] | None
cur_abstract_mesh: mesh_lib.AbstractMesh
def __init__(self, compute_type: str | None, threefry_p... | JaxprEqnContext |
python | davidhalter__parso | test/normalizer_issue_files/E30not.py | {
"start": 981,
"end": 1462
} | class ____():
"""Class Foo"""
def b():
pass
# comment
def c():
pass
# comment
def d():
pass
# This is a
# ... multi-line comment
# And this one is
# ... a second paragraph
# ... which spans on 3 lines
# Function `e` is below
# NOTE: Hey this is a testcase
def e():
pass
def a()... | Foo |
python | huggingface__transformers | src/transformers/processing_utils.py | {
"start": 23456,
"end": 24084
} | class ____(TypedDict, total=False):
"""
Keyword arguments used to load multimodal data in processor chat templates.
num_frames (`int`, *optional*):
Number of frames to sample uniformly. If not passed, the whole video is loaded.
load_audio_from_video (`bool`, *optional*):
Whether to ... | ChatTemplateLoadKwargs |
python | huggingface__transformers | tests/models/groupvit/test_modeling_groupvit.py | {
"start": 4531,
"end": 12463
} | class ____(ModelTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as GROUPVIT does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
all_model_classes = (GroupViTVisionModel,) if is_torch_available() else ()
test_resize... | GroupViTVisionModelTest |
python | Netflix__metaflow | metaflow/_vendor/click/utils.py | {
"start": 15142,
"end": 15940
} | class ____(object):
"""This wrapper is used to catch and suppress BrokenPipeErrors resulting
from ``.flush()`` being called on broken pipe during the shutdown/final-GC
of the Python interpreter. Notably ``.flush()`` is always called on
``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on a... | PacifyFlushWrapper |
python | scrapy__scrapy | tests/test_scheduler_base.py | {
"start": 2511,
"end": 3593
} | class ____(InterfaceCheckMixin):
def setup_method(self):
self.scheduler = MinimalScheduler()
def test_open_close(self):
with pytest.raises(AttributeError):
self.scheduler.open(Spider("foo"))
with pytest.raises(AttributeError):
self.scheduler.close("finished")
... | TestMinimalScheduler |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/ops/data_service_ops.py | {
"start": 17953,
"end": 57968
} | class ____(dataset_ops.DatasetV1Adapter):
"""A `Dataset` that executes its input through the tf.data service."""
@functools.wraps(_DataServiceDatasetV2.__init__)
def __init__(self, dataset_id, processing_mode, address, element_spec,
protocol, data_transfer_protocol, job_name, consumer_index,
... | _DataServiceDatasetV1 |
python | kamyu104__LeetCode-Solutions | Python/minimum-cost-to-convert-string-ii.py | {
"start": 5713,
"end": 8241
} | class ____(object):
def minimumCost(self, source, target, original, changed, cost):
"""
:type source: str
:type target: str
:type original: List[str]
:type changed: List[str]
:type cost: List[int]
:rtype: int
"""
INF = float("inf")
loo... | Solution3 |
python | huggingface__transformers | src/transformers/utils/import_utils.py | {
"start": 78196,
"end": 79337
} | class ____(Enum):
EQUAL = operator.eq
NOT_EQUAL = operator.ne
GREATER_THAN = operator.gt
LESS_THAN = operator.lt
GREATER_THAN_OR_EQUAL = operator.ge
LESS_THAN_OR_EQUAL = operator.le
@staticmethod
def from_string(version_string: str) -> "VersionComparison":
string_to_operator = {... | VersionComparison |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_magiclink.py | {
"start": 12751,
"end": 14949
} | class ____(util.MdCase):
"""Test cases for social link shortener."""
extension = [
'pymdownx.magiclink'
]
extension_configs = {
'pymdownx.magiclink': {
'social_url_shortener': True,
'social_url_shorthand': True
}
}
def test_deprecated_twitter(se... | TestMagicLinkWarning |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/fr_units.py | {
"start": 175,
"end": 964
} | class ____(App):
CSS = """
StaticText {
height: 1fr;
background: $boost;
border: heavy white;
}
#foo {
width: 10;
}
#bar {
width: 1fr;
}
#baz {
width: 8;
}
#header {
height: 1fr
}
Horizontal {
height: 2fr;
... | FRApp |
python | pytorch__pytorch | test/fx/quantization.py | {
"start": 2626,
"end": 2774
} | class ____(NoObserver):
def quantize(self, quantizer, node, load_arg):
return quantizer.quantized_graph.node_copy(node, load_arg)
| CopyNode |
python | streamlit__streamlit | lib/streamlit/errors.py | {
"start": 13293,
"end": 13690
} | class ____(LocalizableStreamlitException):
"""Exception raised when the format string for `st.number_input` contains
invalid characters.
"""
def __init__(self, format: str) -> None:
super().__init__(
"Format string for `st.number_input` contains invalid characters: {format}",
... | StreamlitInvalidNumberFormatError |
python | scikit-learn__scikit-learn | sklearn/utils/tests/test_estimator_checks.py | {
"start": 6651,
"end": 6782
} | class ____(BaseBadClassifier):
def fit(self, X, y):
X, y = validate_data(self, X, y)
return self
| NoCheckinPredict |
python | pypa__warehouse | tests/unit/admin/test_flags.py | {
"start": 178,
"end": 329
} | class ____(enum.Enum):
__test__ = False
NOT_A_REAL_FLAG = "not-a-real-flag"
THIS_FLAG_IS_ENABLED = "this-flag-is-enabled"
| TestAdminFlagValues |
python | huggingface__transformers | src/transformers/models/unispeech/modular_unispeech.py | {
"start": 3323,
"end": 5439
} | class ____(Wav2Vec2GumbelVectorQuantizer):
@staticmethod
def _compute_perplexity(probs):
marginal_probs = probs.mean(dim=0)
perplexity = torch.exp(-torch.sum(marginal_probs * torch.log(marginal_probs + 1e-7), dim=-1)).sum()
return perplexity
def forward(self, hidden_states):
... | UniSpeechGumbelVectorQuantizer |
python | kamyu104__LeetCode-Solutions | Python/find-the-index-of-the-large-integer.py | {
"start": 143,
"end": 581
} | class ____(object):
def getIndex(self, reader):
"""
:type reader: ArrayReader
:rtype: integer
"""
left, right = 0, reader.length()-1
while left < right:
mid = left + (right-left)//2
if reader.compareSub(left, mid, mid if (right-left+1)%2 else m... | Solution |
python | huggingface__transformers | tests/quantization/fp_quant_integration/test_fp_quant.py | {
"start": 5705,
"end": 5889
} | class ____(FPQuantBaseTest):
@classmethod
def getQuantizationConfig(cls):
return FPQuantConfig(forward_dtype="mxfp4", pseudoquantization=True)
| FPQuantMXFP4PseudoquantTest |
python | mwaskom__seaborn | seaborn/_core/properties.py | {
"start": 11659,
"end": 12231
} | class ____(IntervalProperty):
"""Font size for textual marks, in points."""
_legend = False
@property
def default_range(self) -> tuple[float, float]:
"""Min and max values used by default for semantic mapping."""
base = mpl.rcParams["font.size"]
return base * .5, base * 2
# ==... | FontSize |
python | encode__django-rest-framework | tests/test_model_serializer.py | {
"start": 51146,
"end": 51666
} | class ____(TestCase):
def test_model_serializer_custom_manager(self):
instance = Issue6110ModelSerializer().create({'name': 'test_name'})
self.assertEqual(instance.name, 'test_name')
def test_model_serializer_custom_manager_error_message(self):
msginitial = ('Got a `TypeError` when call... | Issue6110Test |
python | FactoryBoy__factory_boy | factory/fuzzy.py | {
"start": 8134,
"end": 8887
} | class ____(BaseFuzzyDateTime):
"""Random timezone-aware datetime within a given range.
If no upper bound is given, will default to datetime.datetime.now()
If no timezone is given, will default to utc.
"""
def _now(self):
return datetime.datetime.now(tz=datetime.timezone.utc)
def _chec... | FuzzyDateTime |
python | ray-project__ray | python/ray/serve/_private/replica.py | {
"start": 4579,
"end": 19923
} | class ____:
"""Manages metrics for the replica.
A variety of metrics are managed:
- Fine-grained metrics are set for every request.
- Autoscaling statistics are periodically pushed to the controller.
- Queue length metrics are periodically recorded as user-facing gauges.
"""
PU... | ReplicaMetricsManager |
python | joke2k__faker | tests/providers/test_company.py | {
"start": 12543,
"end": 13868
} | class ____:
"""Test en_PH company provider methods"""
@classmethod
def setup_class(cls):
cls.company_types = EnPhCompanyProvider.company_types
cls.company_suffixes = EnPhCompanyProvider.company_suffixes.keys()
cls.company_products = EnPhCompanyProvider.company_products
cls.n... | TestEnPh |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linalg_ops_test.py | {
"start": 14370,
"end": 14555
} | class ____(test.TestCase, _PinvTest):
dtype = np.float32
use_static_shape = False
use_default_rcond = False
@test_util.run_all_in_graph_and_eager_modes
| PinvTestDynamic32CustomtRcond |
python | allegroai__clearml | clearml/backend_api/services/v2_20/projects.py | {
"start": 45448,
"end": 50823
} | class ____(Response):
"""
Response of projects.delete endpoint.
:param deleted: Number of projects deleted (0 or 1)
:type deleted: int
:param disassociated_tasks: Number of tasks disassociated from the deleted project
:type disassociated_tasks: int
:param urls: The urls of the files that we... | DeleteResponse |
python | getsentry__sentry | src/sentry/integrations/utils/metrics.py | {
"start": 14687,
"end": 14879
} | class ____(StrEnum):
# OAuth identity
TOKEN_EXCHANGE_ERROR = "token_exchange_error"
TOKEN_EXCHANGE_MISMATCHED_STATE = "token_exchange_mismatched_state"
| IntegrationPipelineErrorReason |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/errors.py | {
"start": 16226,
"end": 17053
} | class ____(DagsterError):
"""Thrown when provided config is invalid (does not type check against the relevant config
schema).
"""
def __init__(self, preamble, errors, config_value, *args, **kwargs):
from dagster._config import EvaluationError
check.str_param(preamble, "preamble")
... | DagsterInvalidConfigError |
python | huggingface__transformers | src/transformers/models/granite/modeling_granite.py | {
"start": 8640,
"end": 9367
} | class ____(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""
GraniteRMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states):
inpu... | GraniteRMSNorm |
python | allegroai__clearml | examples/datasets/urbansounds_dataset_preprocessing.py | {
"start": 583,
"end": 2049
} | class ____:
def __init__(self):
self.configuration = {"number_of_mel_filters": 64, "resample_freq": 22050}
task.connect(self.configuration)
def preprocess_sample(self, sample, original_sample_freq):
if self.configuration["resample_freq"] > 0:
resample_transform = torchaudio.... | PreProcessor |
python | pytorch__pytorch | test/dynamo/test_after_aot.py | {
"start": 618,
"end": 4007
} | class ____(torch._dynamo.test_case.TestCase):
@unittest.skipIf(IS_FBCODE, "NotImplementedError")
def test_save_graph_repro(self):
# TODO: This triggers CUDA context initialization, even though
# it is CPU only
saved_kernel_state = None
if has_triton():
import triton
... | TestAfterAot |
python | getsentry__sentry | tests/sentry/workflow_engine/migrations/test_0094_backfill_issue_stream_detector_workflows.py | {
"start": 154,
"end": 3018
} | class ____(TestMigrations):
migrate_from = "0093_add_action_config_index"
migrate_to = "0094_backfill_issue_stream_detector_workflows"
app = "workflow_engine"
def setup_initial_state(self):
self.test_org = self.create_organization(
name="test-email-fix-org", slug="test-email-fix-org... | TestBackfillIssueStreamDetectorWorkflows |
python | sqlalchemy__sqlalchemy | test/dialect/mssql/test_types.py | {
"start": 2160,
"end": 3548
} | class ____(fixtures.TablesTest):
__only_on__ = "mssql"
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"time_t",
metadata,
Column("id", Integer, primary_key=True, autoincrement=False),
Column("time_col", Time),
)
... | TimeParameterTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefaultClass3.py | {
"start": 704,
"end": 954
} | class ____[T1 = str, T2 = T1](dict[T2, T1]): ...
d1 = ClassD[int]()
reveal_type(d1, expected_text="ClassD[int, int]")
d2 = ClassD()
reveal_type(d2, expected_text="ClassD[str, str]")
# This should generate an error because T5 refers to itself.
| ClassD |
python | django-import-export__django-import-export | import_export/instance_loaders.py | {
"start": 278,
"end": 956
} | class ____(BaseInstanceLoader):
"""
Instance loader for Django model.
Lookup for model instance by ``import_id_fields``.
"""
def get_queryset(self):
return self.resource.get_queryset()
def get_instance(self, row):
try:
params = {}
for key in self.resour... | ModelInstanceLoader |
python | more-itertools__more-itertools | tests/test_recipes.py | {
"start": 35563,
"end": 38629
} | class ____(TestCase):
def test_empty(self):
actual = list(mi.reshape([], 3))
self.assertEqual(actual, [])
def test_zero(self):
matrix = [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)]
with self.assertRaises(ValueError):
list(mi.reshape(matrix, 0))
def test_basic(se... | ReshapeTests |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDict12.py | {
"start": 2596,
"end": 2936
} | class ____(TypedDict, total=False):
a: dict[str, str]
b: list[str]
def func2(td7: TD7):
v1 = td7.get("a", [])
reveal_type(v1, expected_text="dict[str, str] | list[Any]")
v2 = td7.get("a", {})
reveal_type(v2, expected_text="dict[str, str]")
v3 = td7.get("b", [])
reveal_type(v3, expect... | TD7 |
python | openai__openai-python | src/openai/resources/containers/containers.py | {
"start": 8787,
"end": 16506
} | class ____(AsyncAPIResource):
@cached_property
def files(self) -> AsyncFiles:
return AsyncFiles(self._client)
@cached_property
def with_raw_response(self) -> AsyncContainersWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
the ... | AsyncContainers |
python | pytorch__pytorch | scripts/release_notes/commitlist.py | {
"start": 762,
"end": 1269
} | class ____:
commit_hash: str
category: str
topic: str
title: str
files_changed: str
pr_link: str
author: str
# This is not a list so that it is easier to put in a spreadsheet
accepter_1: str
accepter_2: str
accepter_3: str
merge_into: str = None
def __repr__(self):... | Commit |
python | neetcode-gh__leetcode | python/0050-powx-n.py | {
"start": 0,
"end": 347
} | class ____:
def myPow(self, x: float, n: int) -> float:
def helper(x, n):
if x == 0:
return 0
if n == 0:
return 1
res = helper(x * x, n // 2)
return x * res if n % 2 else res
res = helper(x, abs(n))
return res ... | Solution |
python | encode__django-rest-framework | tests/test_serializer_lists.py | {
"start": 761,
"end": 2017
} | class ____:
"""
Tests for using a ListSerializer as a top-level serializer.
Note that this is in contrast to using ListSerializer as a field.
"""
def setup_method(self):
class IntegerListSerializer(serializers.ListSerializer):
child = serializers.IntegerField()
self.Seri... | TestListSerializer |
python | cython__cython | Cython/Plex/Errors.py | {
"start": 100,
"end": 154
} | class ____(PlexError, TypeError):
pass
| PlexTypeError |
python | huggingface__transformers | src/transformers/models/phi4_multimodal/image_processing_phi4_multimodal_fast.py | {
"start": 1371,
"end": 10461
} | class ____(BaseImageProcessorFast):
resample = PILImageResampling.BICUBIC
size = {"height": 448, "width": 448}
patch_size = 14
dynamic_hd = 36
image_mean = [0.5, 0.5, 0.5]
image_std = [0.5, 0.5, 0.5]
do_resize = True
do_rescale = True
do_normalize = True
do_convert_rgb = True
... | Phi4MultimodalImageProcessorFast |
python | streamlit__streamlit | lib/streamlit/elements/widgets/file_uploader.py | {
"start": 3452,
"end": 5035
} | class ____:
accept_multiple_files: AcceptMultipleFiles
allowed_types: Sequence[str] | None = None
def deserialize(self, ui_value: FileUploaderStateProto | None) -> SomeUploadedFiles:
upload_files = _get_upload_files(ui_value)
for file in upload_files:
if isinstance(file, Delete... | FileUploaderSerde |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/backfill.py | {
"start": 12493,
"end": 28702
} | class ____(graphene.ObjectType):
class Meta:
interfaces = (GrapheneRunsFeedEntry,)
name = "PartitionBackfill"
id = graphene.NonNull(graphene.ID)
status = graphene.NonNull(GrapheneBulkActionStatus)
runStatus = graphene.Field(
graphene.NonNull(
GrapheneRunStatus,
... | GraphenePartitionBackfill |
python | wandb__wandb | wandb/sdk/artifacts/_generated/input_types.py | {
"start": 5134,
"end": 5395
} | class ____(GQLInput):
alias: str = Field(max_length=128)
entity_name: str = Field(alias="entityName")
project_name: str = Field(alias="projectName")
artifact_collection_name: str = Field(alias="artifactCollectionName")
| ArtifactCollectionAliasInput |
python | tensorflow__tensorflow | tensorflow/compiler/tf2xla/light_outside_compilation_test.py | {
"start": 1262,
"end": 8021
} | class ____(test_util.TensorFlowTestCase):
def setUp(self):
super().setUp()
if not test_util.is_gpu_available():
self.skipTest('Light outside compilation only works for GPUs now')
def assertFilecheck(self, actual, expected):
"""Assert that FileCheck runs successfully."""
if not fw.check(actua... | LightOutsideCompilationTest |
python | getsentry__sentry | src/sentry/analytics/events/issue_alert_fired.py | {
"start": 74,
"end": 242
} | class ____(analytics.Event):
issue_id: int
project_id: int
organization_id: int
rule_id: int
analytics.register(IssueAlertFiredEvent)
| IssueAlertFiredEvent |
python | great-expectations__great_expectations | great_expectations/_docs_decorators.py | {
"start": 758,
"end": 854
} | class ____:
type: str
name: str
qualname: str
module: Optional[str]
| _PublicApiInfo |
python | pydata__xarray | asv_bench/benchmarks/dataset_io.py | {
"start": 4013,
"end": 4781
} | class ____(IOReadSingleNetCDF4):
def setup(self):
# TODO: Lazily skipped in CI as it is very demanding and slow.
# Improve times and remove errors.
_skip_slow()
self.make_ds()
self.filepath = "test_single_file.nc3.nc"
self.format = "NETCDF3_64BIT"
self.ds.to... | IOReadSingleNetCDF3 |
python | readthedocs__readthedocs.org | readthedocs/api/v2/utils.py | {
"start": 9251,
"end": 9330
} | class ____(PageNumberPagination):
page_size = 25
| RemoteOrganizationPagination |
python | python-pillow__Pillow | Tests/test_decompression_bomb.py | {
"start": 2728,
"end": 3781
} | class ____:
@classmethod
def setup_class(cls) -> None:
width, height = 128, 128
Image.MAX_IMAGE_PIXELS = height * width * 4 - 1
@classmethod
def teardown_class(cls) -> None:
Image.MAX_IMAGE_PIXELS = ORIGINAL_LIMIT
def test_enlarge_crop(self) -> None:
# Crops can ext... | TestDecompressionCrop |
python | gevent__gevent | src/gevent/_config.py | {
"start": 5146,
"end": 6638
} | class ____(object):
"""
Global configuration for gevent.
There is one instance of this object at ``gevent.config``. If you
are going to make changes in code, instead of using the documented
environment variables, you need to make the changes before using
any parts of gevent that might need thos... | Config |
python | milvus-io__pymilvus | pymilvus/exceptions.py | {
"start": 3004,
"end": 3094
} | class ____(MilvusException):
"""Raise when primarykey are invalid"""
| PrimaryKeyException |
python | walkccc__LeetCode | solutions/173. Binary Search Tree Iterator/173.py | {
"start": 0,
"end": 436
} | class ____:
def __init__(self, root: TreeNode | None):
self.i = 0
self.vals = []
self._inorder(root)
def next(self) -> int:
self.i += 1
return self.vals[self.i - 1]
def hasNext(self) -> bool:
return self.i < len(self.vals)
def _inorder(self, root: TreeNode | None) -> None:
if not ... | BSTIterator |
python | django__django | django/db/models/fields/composite.py | {
"start": 490,
"end": 1318
} | class ____:
def __init__(self, field):
self.field = field
@property
def attnames(self):
return [field.attname for field in self.field.fields]
def __get__(self, instance, cls=None):
return tuple(getattr(instance, attname) for attname in self.attnames)
def __set__(self, inst... | CompositeAttribute |
python | falconry__falcon | falcon/errors.py | {
"start": 32061,
"end": 34415
} | class ____(HTTPError):
"""411 Length Required.
The server refuses to accept the request without a defined Content-
Length.
The client MAY repeat the request if it adds a valid Content-Length
header field containing the length of the message body in the
request message.
(See also: RFC 7231... | HTTPLengthRequired |
python | sphinx-doc__sphinx | sphinx/directives/other.py | {
"start": 9495,
"end": 10770
} | class ____(SphinxDirective):
"""Directive for a list that gets compacted horizontally."""
has_content = True
required_arguments = 0
optional_arguments = 0
final_argument_whitespace = False
option_spec: ClassVar[OptionSpec] = {
'columns': int,
}
def run(self) -> list[Node]:
... | HList |
python | pypa__pip | src/pip/_vendor/rich/layout.py | {
"start": 1874,
"end": 2420
} | class ____(ABC):
"""Base class for a splitter."""
name: str = ""
@abstractmethod
def get_tree_icon(self) -> str:
"""Get the icon (emoji) used in layout.tree"""
@abstractmethod
def divide(
self, children: Sequence["Layout"], region: Region
) -> Iterable[Tuple["Layout", Regi... | Splitter |
python | encode__django-rest-framework | tests/test_relations_hyperlink.py | {
"start": 18995,
"end": 25214
} | class ____(TestCase):
def setUp(self):
target = ForeignKeyTarget(name='target-1')
target.save()
for idx in range(1, 4):
if idx == 3:
target = None
source = NullableForeignKeySource(name='source-%d' % idx, target=target)
source.save()
d... | HyperlinkedNullableForeignKeyTests |
python | getsentry__sentry | src/sentry_plugins/trello/plugin.py | {
"start": 892,
"end": 10504
} | class ____(CorePluginMixin, IssuePlugin2):
description = DESCRIPTION
slug = "trello"
title = "Trello"
conf_title = title
conf_key = "trello"
auth_provider = None
resource_links = [("Trello Setup Instructions", SETUP_URL)] + CorePluginMixin.resource_links
required_field = "key"
featur... | TrelloPlugin |
python | pypa__setuptools | setuptools/_distutils/command/bdist.py | {
"start": 905,
"end": 1299
} | class ____(dict[str, tuple[str, str]]):
# adapter to allow for Setuptools compatibility in format_commands
@deprecated("format_commands is now a dict. append is deprecated.")
def append(self, item: object) -> None:
warnings.warn(
"format_commands is now a dict. append is deprecated.",
... | ListCompat |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/attributes.py | {
"start": 1321,
"end": 1651
} | class ____:
def __init__(self, a, b):
self.a = a
self.b = b
def test_attribute_via_dunder_dict():
obj = UseViaDict(a=_test_source(), b=None)
# First two should be flows, and the third shouldn't.
_test_sink(obj.__dict__)
_test_sink(obj.__dict__["a"])
_test_sink(obj.__dict__["b"]... | UseViaDict |
python | walkccc__LeetCode | solutions/2100. Find Good Days to Rob the Bank/2100.py | {
"start": 0,
"end": 587
} | class ____:
def goodDaysToRobBank(self, security: list[int], time: int) -> list[int]:
n = len(security)
dec = [0] * n # dec[i] := the number of continuous decreasing numbers before i
inc = [0] * n # inc[i] := the number of continuous increasing numbers after i
for i in range(1, n):
if securit... | Solution |
python | tensorflow__tensorflow | tensorflow/python/keras/engine/base_preprocessing_layer.py | {
"start": 12370,
"end": 18795
} | class ____(PreprocessingLayer):
"""Base class for PreprocessingLayers that do computation using a Combiner.
This class provides several helper methods to make creating a
PreprocessingLayer easier. It assumes that the core of your computation will
be done via a Combiner object. Subclassing this class to create ... | CombinerPreprocessingLayer |
python | huggingface__transformers | src/transformers/models/poolformer/modeling_poolformer.py | {
"start": 6844,
"end": 9509
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
# stochastic depth decay rule
dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu")]
# patch embeddings
embeddings = []
fo... | PoolFormerEncoder |
python | langchain-ai__langchain | libs/text-splitters/langchain_text_splitters/character.py | {
"start": 179,
"end": 2737
} | class ____(TextSplitter):
"""Splitting text that looks at characters."""
def __init__(
self,
separator: str = "\n\n",
is_separator_regex: bool = False, # noqa: FBT001,FBT002
**kwargs: Any,
) -> None:
"""Create a new TextSplitter."""
super().__init__(**kwargs... | CharacterTextSplitter |
python | pandas-dev__pandas | pandas/tests/indexes/timedeltas/test_setops.py | {
"start": 7956,
"end": 9727
} | class ____:
def test_difference_freq(self, sort):
# GH14323: Difference of TimedeltaIndex should not preserve frequency
index = timedelta_range("0 days", "5 days", freq="D")
other = timedelta_range("1 days", "4 days", freq="D")
expected = TimedeltaIndex(["0 days", "5 days"], freq=N... | TestTimedeltaIndexDifference |
python | prabhupant__python-ds | data_structures/graphs/dag_shortest_path.py | {
"start": 480,
"end": 1899
} | class ____:
def __init__(self, vertices):
self.graph = defaultdict(list)
self.vertices = vertices
def add_edge(self, u, v, w):
self.graph[u].append((v, w))
def topological_sort_util(self, vertex, visited, stack):
visited[vertex] = True
for v, weight in self.gra... | Graph |
python | huggingface__transformers | tests/models/aimv2/test_modeling_aimv2.py | {
"start": 4107,
"end": 5857
} | class ____(ModelTesterMixin):
"""
Subclass of ModelTesterMixin with methods specific to testing Aimv2 models.
The SDPA equivalence test is overridden here because Aimv2 models may have test/vision/text+vision inputs,
different output logits, and are not supposed to be used or tested with padding_side="l... | Aimv2ModelTesterMixin |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/ops/index_flat_map_op.py | {
"start": 4054,
"end": 6444
} | class ____(dataset_ops.UnaryDataset):
"""A `Dataset` that maps a function over its input and flattens the result."""
def __init__(
self,
input_dataset: dataset_ops.Dataset,
map_func: Callable[[Any], tensor.Tensor],
index_map_func: Callable[[_IndexType], tuple[_IndexType, _IndexType]],
... | _IndexFlatMapDataset |
python | tensorflow__tensorflow | tensorflow/compiler/tests/unstack_test.py | {
"start": 1033,
"end": 1586
} | class ____(xla_test.XLATestCase, parameterized.TestCase):
def _test(self, size):
with self.session() as sess:
x_tf = array_ops.placeholder(np.float32, shape=[size, 512])
with self.test_scope():
ret = array_ops_stack.unstack(x_tf)
ret_vals = sess.run([ret], feed_dict={x_tf: np.zeros([siz... | UnstackOpTest |
python | neetcode-gh__leetcode | python/0115-distinct-subsequences.py | {
"start": 0,
"end": 533
} | class ____:
def numDistinct(self, s: str, t: str) -> int:
cache = {}
for i in range(len(s) + 1):
cache[(i, len(t))] = 1
for j in range(len(t)):
cache[(len(s), j)] = 0
for i in range(len(s) - 1, -1, -1):
for j in range(len(t) - 1, -1, -1):
... | Solution |
python | mitmproxy__pdoc | test/testdata/misc.py | {
"start": 5741,
"end": 6036
} | class ____:
"""
# Heading 1
Here is some text.
## Heading 2
Here is some text.
### Heading 3
Here is some text.
#### Heading 4
Here is some text.
##### Heading 5
Here is some text.
###### Heading 6
Here is some text.
"""
| Headings |
python | davidhalter__jedi | test/completion/stdlib.py | {
"start": 4787,
"end": 4987
} | class ____(metaclass=Meta):
def test_function(self):
result = super(Test, self).test_function()
#? []
result.
# -----------------
# Enum
# -----------------
import enum
| Test |
python | jazzband__django-pipeline | pipeline/compressors/yuglify.py | {
"start": 91,
"end": 563
} | class ____(SubProcessCompressor):
def compress_common(self, content, compress_type, arguments):
command = (settings.YUGLIFY_BINARY, f"--type={compress_type}", arguments)
return self.execute_command(command, content)
def compress_js(self, js):
return self.compress_common(js, "js", settin... | YuglifyCompressor |
python | scrapy__scrapy | tests/test_spidermiddleware_output_chain.py | {
"start": 10518,
"end": 19356
} | class ____:
mockserver: MockServer
@classmethod
def setup_class(cls):
cls.mockserver = MockServer()
cls.mockserver.__enter__()
@classmethod
def teardown_class(cls):
cls.mockserver.__exit__(None, None, None)
async def crawl_log(self, spider: type[Spider]) -> LogCapture:... | TestSpiderMiddleware |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/label_widths.py | {
"start": 101,
"end": 917
} | class ____(App):
CSS = """
Screen {
align: center middle;
}
#l_data {
border: blank;
background: lightgray;
}
#s_data {
border: blank;
background: lightgreen;
}
#p_data {
border: blank;
background: lightgray;
}
"""
d... | LabelWrap |
python | walkccc__LeetCode | solutions/2413. Smallest Even Multiple/2413.py | {
"start": 0,
"end": 92
} | class ____:
def smallestEvenMultiple(self, n: int) -> int:
return n * (n % 2 + 1)
| Solution |
python | euske__pdfminer | pdfminer/pdffont.py | {
"start": 17376,
"end": 17523
} | class ____(PDFFontError):
pass
LITERAL_STANDARD_ENCODING = LIT('StandardEncoding')
LITERAL_TYPE1C = LIT('Type1C')
# PDFFont
| PDFUnicodeNotDefined |
python | mlflow__mlflow | mlflow/models/resources.py | {
"start": 5574,
"end": 6262
} | class ____(DatabricksResource):
"""
Define Databricks UC Function to serve a model.
Args:
function_name (str): The name of the function used by the model
on_behalf_of_user (Optional[bool]): If True, the resource is accessed with
with the permission of the invoker of the model in the... | DatabricksFunction |
python | pytorch__pytorch | test/dynamo/test_deviceguard.py | {
"start": 297,
"end": 1707
} | class ____(torch._dynamo.test_case.TestCase):
"""
Unit tests for the DeviceGuard class using a mock DeviceInterface.
"""
def setUp(self):
super().setUp()
self.device_interface = Mock()
self.device_interface.exchange_device = Mock(return_value=0)
self.device_interface.ma... | TestDeviceGuard |
python | ray-project__ray | release/microbenchmark/experimental/gpu_object_microbenchmark.py | {
"start": 443,
"end": 1340
} | class ____:
init_actor_kwargs: dict
send_method_kwargs: dict
device: torch.device
collective_group_backend: Optional[str]
BACKEND_CONFIG = {
"gloo": BackendConfig(
init_actor_kwargs={},
send_method_kwargs={"tensor_transport": "gloo"},
device=torch.device("cpu"),
col... | BackendConfig |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_defined_name04.py | {
"start": 314,
"end": 2218
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("defined_name04.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with defined names."""
workbook... | TestCompareXLSXFiles |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.