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 | catalyst-team__catalyst | catalyst/contrib/losses/circle.py | {
"start": 706,
"end": 2600
} | class ____(nn.Module):
"""
CircleLoss from
`Circle Loss: A Unified Perspective of Pair Similarity Optimization`_ paper.
Adapter from:
https://github.com/TinyZeaMays/CircleLoss
Example:
>>> import torch
>>> from torch.nn import functional as F
>>> from catalyst.contrib.l... | CircleLoss |
python | huggingface__transformers | src/transformers/models/smolvlm/configuration_smolvlm.py | {
"start": 5401,
"end": 9071
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`SmolVLMModel`]. It is used to instantiate a
SmolVLM model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a similar confi... | SmolVLMConfig |
python | google__pytype | pytype/tests/test_errors_format.py | {
"start": 236,
"end": 3722
} | class ____(test_base.BaseTest):
"""Tests for errors."""
def test_error_format(self):
errors = self.CheckWithErrors("""
def f(x):
y = 42
y.foobar # attribute-error[e]
""")
message = textwrap.dedent("""\
dummy_input_file:3:3: \x1b[1m\x1b[31merror\x1b[39m\x1b[0m: in f: No attr... | ErrorTest |
python | facebook__pyre-check | tools/typeshed_patcher/patch_specs.py | {
"start": 490,
"end": 1187
} | class ____(Exception):
pass
def _read_string(input_object: object, field_name: Optional[str] = None) -> str:
if not isinstance(input_object, str):
field_message = f" for field `{field_name}`" if field_name is not None else ""
raise ReadPatchException(
f"Expect a string{field_messag... | ReadPatchException |
python | django__django | tests/proxy_models/models.py | {
"start": 4011,
"end": 4120
} | class ____(Bug):
"""
Proxy of an inherited class
"""
class Meta:
proxy = True
| ProxyBug |
python | huggingface__transformers | src/transformers/models/patchtsmixer/modeling_patchtsmixer.py | {
"start": 50462,
"end": 51418
} | class ____(ModelOutput):
r"""
loss (*optional*, returned when `y` is provided, `torch.FloatTensor` of shape `()`):
Total loss
prediction_outputs (`torch.FloatTensor` of shape `(batch_size, num_input_channels, num_patches, patch_length)`):
Prediction output from the pretrain head.
last_hi... | PatchTSMixerForPreTrainingOutput |
python | doocs__leetcode | solution/2600-2699/2642.Design Graph With Shortest Path Calculator/Solution.py | {
"start": 0,
"end": 946
} | class ____:
def __init__(self, n: int, edges: List[List[int]]):
self.n = n
self.g = [[inf] * n for _ in range(n)]
for f, t, c in edges:
self.g[f][t] = c
def addEdge(self, edge: List[int]) -> None:
f, t, c = edge
self.g[f][t] = c
def shortestPath(self, no... | Graph |
python | allegroai__clearml | clearml/backend_api/services/v2_13/events.py | {
"start": 49812,
"end": 54379
} | class ____(Request):
"""
Return the debug image per metric and variant for the provided iteration
:param task: Task ID
:type task: str
:param metric: Metric name
:type metric: str
:param variant: Metric variant
:type variant: str
:param iteration: The iteration to bring debug image ... | GetDebugImageSampleRequest |
python | django__django | django/db/migrations/exceptions.py | {
"start": 502,
"end": 603
} | class ____(ValueError):
"""A model's base classes can't be resolved."""
pass
| InvalidBasesError |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py | {
"start": 60419,
"end": 67634
} | class ____:
@mock.patch("google.cloud.aiplatform.datasets.TimeSeriesDataset")
@mock.patch(VERTEX_AI_PATH.format("auto_ml.AutoMLHook"))
def test_execute(self, mock_hook, mock_dataset):
mock_hook.return_value.create_auto_ml_forecasting_training_job.return_value = (None, "training_id")
op = Cre... | TestVertexAICreateAutoMLForecastingTrainingJobOperator |
python | huggingface__transformers | src/transformers/models/idefics3/modeling_idefics3.py | {
"start": 18370,
"end": 21139
} | class ____(Idefics3PreTrainedModel):
config: Idefics3VisionConfig
input_modalities = ("image",)
_supports_sdpa = True
_supports_flash_attn = True
_supports_flex_attn = True
_can_record_outputs = {
"hidden_states": Idefics3EncoderLayer,
"attentions": Idefics3VisionAttention,
}... | Idefics3VisionTransformer |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/attach_features.py | {
"start": 997,
"end": 1483
} | class ____:
def method_with_optionals(self, a: int = 0, b: int = 1) -> None:
_test_sink(b)
def attach_to_returned_sink():
x = _test_source()
return x
def attach_to_returned_source():
return 0
def attach_to_returned_source_2():
return 0
def attach_to_returned_with_captures():
x = ... | HasMethods |
python | kamyu104__LeetCode-Solutions | Python/number-of-subarrays-that-match-a-pattern-i.py | {
"start": 35,
"end": 1119
} | class ____(object):
def countMatchingSubarrays(self, nums, pattern):
"""
:type nums: List[int]
:type pattern: List[int]
:rtype: int
"""
def getPrefix(pattern):
prefix = [-1]*len(pattern)
j = -1
for i in xrange(1, len(pattern)):
... | Solution |
python | getsentry__sentry | tests/sentry/integrations/github/tasks/test_link_all_repos.py | {
"start": 919,
"end": 9703
} | class ____(IntegrationTestCase):
provider = GitHubIntegrationProvider
base_url = "https://api.github.com"
key = "github"
def _add_responses(self):
responses.add(
responses.GET,
self.base_url + "/installation/repositories?per_page=100",
status=200,
... | LinkAllReposTestCase |
python | PrefectHQ__prefect | tests/docker/test_public_api.py | {
"start": 188,
"end": 415
} | class ____(TestCase):
"""this is a regression test for https://github.com/PrefectHQ/prefect/issues/16171"""
def test_warning(self):
with self.assertWarns(UserWarning):
function_that_warns()
| TestWarnings |
python | numba__llvmlite | llvmlite/ir/values.py | {
"start": 18150,
"end": 20458
} | class ____(NamedValue):
"""
A debug information descriptor, containing key-value pairs.
Do not instantiate directly, use Module.add_debug_info() instead.
"""
name_prefix = '!'
def __init__(self, parent, is_distinct, kind, operands, name):
super(DIValue, self).__init__(parent,
... | DIValue |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/cloud_run.py | {
"start": 10415,
"end": 12751
} | class ____(GoogleBaseAsyncHook):
"""
Async hook for the Google Cloud Run services.
:param gcp_conn_id: The connection ID to use when fetching connection info.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required t... | CloudRunServiceAsyncHook |
python | matplotlib__matplotlib | lib/matplotlib/patches.py | {
"start": 32379,
"end": 33728
} | class ____(Patch):
"""A regular polygon patch."""
def __str__(self):
s = "RegularPolygon((%g, %g), %d, radius=%g, orientation=%g)"
return s % (self.xy[0], self.xy[1], self.numvertices, self.radius,
self.orientation)
@_docstring.interpd
def __init__(self, xy, numVert... | RegularPolygon |
python | sympy__sympy | sympy/functions/elementary/trigonometric.py | {
"start": 115946,
"end": 122110
} | class ____(InverseTrigonometricFunction):
r"""
The function ``atan2(y, x)`` computes `\operatorname{atan}(y/x)` taking
two arguments `y` and `x`. Signs of both `y` and `x` are considered to
determine the appropriate quadrant of `\operatorname{atan}(y/x)`.
The range is `(-\pi, \pi]`. The complete de... | atan2 |
python | bokeh__bokeh | src/bokeh/models/filters.py | {
"start": 3618,
"end": 3890
} | class ____(CompositeFilter):
""" Computes intersection of indices resulting from other filters. """
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
| IntersectionFilter |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/layer_order_independence.py | {
"start": 873,
"end": 1559
} | class ____(App[None]):
CSS = """
Screen {
layers: base higher;
}
Overlay {
layer: higher;
dock: top;
width: auto;
height: auto;
padding: 2;
border: solid yellow;
background: red;
color: yellow;
}
Body2 {
background... | Layers |
python | google__pytype | pytype/overlays/special_builtins.py | {
"start": 12009,
"end": 12737
} | class ____(abstract.PyTDClass):
"""Implementation of classes in builtins.pytd.
The module name is passed in to allow classes in other modules to subclass a
module in builtins and inherit the custom behaviour.
"""
_NAME: str = None
@classmethod
def make(cls, ctx):
assert cls._NAME
return cls(cls... | BuiltinClass |
python | dagster-io__dagster | scripts/run-pyright.py | {
"start": 3538,
"end": 3602
} | class ____(TypedDict):
start: Position
end: Position
| Range |
python | django__django | tests/check_framework/tests.py | {
"start": 612,
"end": 675
} | class ____:
def __repr__(self):
return "obj"
| DummyObj |
python | python-excel__xlwt | xlwt/BIFFRecords.py | {
"start": 61918,
"end": 62616
} | class ____(BiffRecord):
"""
Offset Size Contents
0 2 Index to row
2 2 Index to column
4 2 Index to XF record
6 8 Result of the formula
14 2 Option flags:
Bit Mask Contents
0 0001H 1 = Recalculate always
... | FormulaRecord |
python | airbytehq__airbyte | airbyte-integrations/bases/connector-acceptance-test/unit_tests/test_test_full_refresh.py | {
"start": 612,
"end": 7996
} | class ____(ConnectionTestConfig):
ignored_fields: Dict[str, List[IgnoredFieldsConfiguration]] = {
"test_stream": [
IgnoredFieldsConfiguration(name="ignore_me", bypass_reason="test"),
IgnoredFieldsConfiguration(name="ignore_me_too", bypass_reason="test"),
]
}
def record_... | ReadTestConfigWithIgnoreFields |
python | huggingface__transformers | src/transformers/models/jamba/modular_jamba.py | {
"start": 7633,
"end": 9833
} | class ____(LlamaAttention):
def __init__(self, config: JambaConfig, layer_idx: int):
super().__init__(config, layer_idx)
self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads ... | JambaAttention |
python | mkdocstrings__mkdocstrings | src/mkdocstrings/_internal/handlers/rendering.py | {
"start": 10416,
"end": 12016
} | class ____(Extension):
"""Extension that should always be added to Markdown sub-documents that handlers request (and *only* them)."""
def __init__(self, headings: list[Element]):
"""Initialize the object.
Arguments:
headings: A list that will be populated with all HTML heading elem... | MkdocstringsInnerExtension |
python | ray-project__ray | python/ray/util/dask/callbacks.py | {
"start": 1107,
"end": 6056
} | class ____(Callback):
"""
Extends Dask's `Callback` class with Ray-specific hooks. When instantiating
or subclassing this class, both the normal Dask hooks (e.g. pretask,
posttask, etc.) and the Ray-specific hooks can be provided.
See `dask.callbacks.Callback` for usage.
Caveats: Any Dask-Ray ... | RayDaskCallback |
python | kamyu104__LeetCode-Solutions | Python/shuffle-string.py | {
"start": 49,
"end": 600
} | class ____(object):
def restoreString(self, s, indices):
"""
:type s: str
:type indices: List[int]
:rtype: str
"""
result = list(s)
for i, c in enumerate(result):
if indices[i] == i:
continue
move, j = c, indices[i]
... | Solution |
python | spack__spack | lib/spack/spack/vendor/jinja2/runtime.py | {
"start": 12787,
"end": 14124
} | class ____:
"""One block on a template reference."""
def __init__(
self,
name: str,
context: "Context",
stack: t.List[t.Callable[["Context"], t.Iterator[str]]],
depth: int,
) -> None:
self.name = name
self._context = context
self._stack = stac... | BlockReference |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 18372,
"end": 18763
} | class ____(AbstractTemplate):
key = "static_getitem"
def generic(self, args, kws):
tup, idx = args
ret = None
if not isinstance(tup, types.LiteralList):
return
if isinstance(idx, int):
ret = tup.types[idx]
if ret is not None:
sig = sig... | StaticGetItemLiteralList |
python | getsentry__sentry | src/sentry/uptime/grouptype.py | {
"start": 1442,
"end": 3379
} | class ____:
"""
Represents the value passed into the uptime detector
"""
check_result: CheckResult
subscription: UptimeSubscription
metric_tags: dict[str, str]
def build_evidence_display(result: CheckResult) -> list[IssueEvidence]:
evidence_display: list[IssueEvidence] = []
status_re... | UptimePacketValue |
python | langchain-ai__langchain | libs/standard-tests/langchain_tests/integration_tests/cache.py | {
"start": 337,
"end": 3821
} | class ____(BaseStandardTests):
"""Test suite for checking the `BaseCache` API of a caching layer for LLMs.
This test suite verifies the basic caching API of a caching layer for LLMs.
The test suite is designed for synchronous caching layers.
Implementers should subclass this test suite and provide a ... | SyncCacheTestSuite |
python | pytorch__pytorch | torch/_inductor/subgraph_lowering.py | {
"start": 745,
"end": 4729
} | class ____(torch.fx.Interpreter):
"""
Lowers a pointwise subgraph to a single set of buffers with a separate
lowering object. Errors if buffers are created unexpectedly
"""
graph_outputs: Optional[list[ir.IRNode]]
root_graph: GraphLowering
_current_op: Optional[TargetType]
# For backwar... | PointwiseSubgraphLowering |
python | huggingface__transformers | tests/quantization/compressed_tensors_integration/test_compressed_models.py | {
"start": 434,
"end": 6759
} | class ____(unittest.TestCase):
# Define stubs as class attributes
compressed_uncompressed_model_stubs = [
(
"nm-testing/llama2.c-stories42M-gsm8k-quantized-only-compressed",
"nm-testing/llama2.c-stories42M-gsm8k-quantized-only-uncompressed",
),
(
"nm-t... | StackCompressedModelTest |
python | matplotlib__matplotlib | lib/matplotlib/cbook.py | {
"start": 3464,
"end": 4091
} | class ____:
"""
Wrapper similar to a weakref, but keeping a strong reference to the object.
"""
def __init__(self, obj):
self._obj = obj
def __call__(self):
return self._obj
def __eq__(self, other):
return isinstance(other, _StrongRef) and self._obj == other._obj
... | _StrongRef |
python | wandb__wandb | wandb/vendor/pygments/lexers/varnish.py | {
"start": 490,
"end": 6488
} | class ____(RegexLexer):
"""
For Varnish Configuration Language (VCL).
.. versionadded:: 2.2
"""
name = 'VCL'
aliases = ['vcl']
filenames = ['*.vcl']
mimetypes = ['text/x-vclsrc']
def analyse_text(text):
# If the very first line is 'vcl 4.0;' it's pretty much guaranteed
... | VCLLexer |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 669965,
"end": 670362
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("actor", "client_mutation_id", "issue")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
... | UpdateIssuePayload |
python | readthedocs__readthedocs.org | readthedocs/api/v3/serializers.py | {
"start": 2530,
"end": 2745
} | class ____(BaseLinksSerializer):
_self = serializers.SerializerMethodField()
def get__self(self, obj):
path = obj.get_absolute_url()
return self._absolute_url(path)
| NotificationLinksSerializer |
python | django__django | tests/constraints/models.py | {
"start": 5041,
"end": 5257
} | class ____(models.Model):
field = models.CharField(max_length=255)
field_with_db_default = models.CharField(
max_length=255, db_default=models.Value("field_with_db_default")
)
| ModelWithDatabaseDefault |
python | joke2k__faker | tests/providers/test_lorem.py | {
"start": 14809,
"end": 17630
} | class ____:
"""Test fa_IR lorem provider"""
word_list = [word.lower() for word in FaIrLoremProvider.word_list]
def test_paragraph(self, faker, num_samples):
num_sentences = 10
for _ in range(num_samples):
paragraph = faker.paragraph(nb_sentences=num_sentences)
asser... | TestFaIr |
python | explosion__spaCy | spacy/lang/nn/__init__.py | {
"start": 221,
"end": 457
} | class ____(BaseDefaults):
tokenizer_exceptions = TOKENIZER_EXCEPTIONS
prefixes = TOKENIZER_PREFIXES
infixes = TOKENIZER_INFIXES
suffixes = TOKENIZER_SUFFIXES
syntax_iterators = SYNTAX_ITERATORS
| NorwegianNynorskDefaults |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/quux/package.py | {
"start": 1298,
"end": 5922
} | class ____
{
private:
static const int version_major;
static const int version_minor;
public:
Quux();
int get_version() const;
int quuxify() const;
};
#endif // QUUX_H_
"""
quuxifier_cc = """
#include "quux.h"
#include <iostream>
int
main()
{
Quux quux;
quux.quuxify();
return... | Quux |
python | apache__thrift | lib/py/src/server/TNonblockingServer.py | {
"start": 2926,
"end": 7469
} | class ____(object):
"""Basic class is represented connection.
It can be in state:
WAIT_LEN --- connection is reading request len.
WAIT_MESSAGE --- connection is reading request.
WAIT_PROCESS --- connection has just read whole request and
waits for call ready rou... | Connection |
python | great-expectations__great_expectations | contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/metrics/data_profiler_metrics/data_profiler_profile_metric_provider.py | {
"start": 434,
"end": 1073
} | class ____(MetricProvider):
domain_keys = (
"batch_id",
"table",
"row_condition",
"condition_parser",
)
value_keys = ("profile_path",)
@classmethod
def _get_evaluation_dependencies(
cls,
metric: MetricConfiguration,
configuration: Optional[Exp... | DataProfilerProfileMetricProvider |
python | numba__numba | numba/cuda/tests/cudadrv/test_cuda_array_slicing.py | {
"start": 179,
"end": 1831
} | class ____(CUDATestCase):
def test_index_1d(self):
arr = np.arange(10)
darr = cuda.to_device(arr)
x, = arr.shape
for i in range(-x, x):
self.assertEqual(arr[i], darr[i])
with self.assertRaises(IndexError):
darr[-x - 1]
with self.assertRaises(In... | CudaArrayIndexing |
python | donnemartin__interactive-coding-challenges | arrays_strings/rotation/test_rotation.py | {
"start": 18,
"end": 599
} | class ____(unittest.TestCase):
def test_rotation(self):
rotation = Rotation()
self.assertEqual(rotation.is_rotation('o', 'oo'), False)
self.assertEqual(rotation.is_rotation(None, 'foo'), False)
self.assertEqual(rotation.is_rotation('', 'foo'), False)
self.assertEqual(rotatio... | TestRotation |
python | getsentry__sentry | src/sentry/snuba/metrics/extraction.py | {
"start": 19902,
"end": 41899
} | class ____:
"""Result of a check for standard and on-demand metric support."""
standard_metrics: bool
on_demand_metrics: bool
@classmethod
def neither(cls) -> Self:
return cls(standard_metrics=False, on_demand_metrics=False)
@classmethod
def both(cls) -> Self:
return cls(s... | SupportedBy |
python | pyqtgraph__pyqtgraph | pyqtgraph/opengl/items/GLMeshItem.py | {
"start": 544,
"end": 13070
} | class ____(GLGraphicsItem):
"""
**Bases:** :class:`GLGraphicsItem <pyqtgraph.opengl.GLGraphicsItem.GLGraphicsItem>`
Displays a 3D triangle mesh.
"""
def __init__(self, parentItem=None, **kwds):
"""
============== =====================================================
**A... | GLMeshItem |
python | ipython__ipython | IPython/core/shellapp.py | {
"start": 5150,
"end": 19501
} | class ____(Configurable):
"""A Mixin for applications that start InteractiveShell instances.
Provides configurables for loading extensions and executing files
as part of configuring a Shell environment.
The following methods should be called by the :meth:`initialize` method
of the subclass:
... | InteractiveShellApp |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDictClosed7.py | {
"start": 256,
"end": 485
} | class ____(TypedDict, total=False, extra_items=int):
a: int
td1: TD1 = {"a": 1}
reveal_type(td1.clear, expected_text="() -> None")
reveal_type(td1.popitem, expected_text="() -> tuple[str, int]")
td1.clear()
td1.popitem()
| TD1 |
python | joke2k__faker | faker/providers/company/sk_SK/__init__.py | {
"start": 45,
"end": 327
} | class ____(CompanyProvider):
formats = (
"{{last_name}} {{company_suffix}}",
"{{last_name}} {{last_name}} {{company_suffix}}",
"{{last_name}}",
)
company_suffixes = (
"s.r.o.",
"v.o.s.",
"a.s.",
"k.s.",
)
| Provider |
python | pypa__setuptools | setuptools/tests/test_editable_install.py | {
"start": 14238,
"end": 27747
} | class ____:
"""This test focus in getting a particular implementation detail right.
If at some point in time the implementation is changed for something different,
this test can be modified or even excluded.
"""
def install_finder(self, finder):
loc = {}
exec(finder, loc, loc)
... | TestFinderTemplate |
python | jazzband__django-model-utils | tests/test_choices.py | {
"start": 1871,
"end": 2686
} | class ____(TestCase, ChoicesTestsMixin[str]):
def setUp(self) -> None:
self.STATUS = Choices('DRAFT', 'PUBLISHED')
def test_indexing(self) -> None:
self.assertEqual(self.STATUS['PUBLISHED'], 'PUBLISHED')
def test_iteration(self) -> None:
self.assertEqual(tuple(self.STATUS),
... | ChoicesTests |
python | ray-project__ray | python/ray/data/datasource/file_datasink.py | {
"start": 1061,
"end": 6925
} | class ____(Datasink[None]):
def __init__(
self,
path: str,
*,
filesystem: Optional["pyarrow.fs.FileSystem"] = None,
try_create_dir: bool = True,
open_stream_args: Optional[Dict[str, Any]] = None,
filename_provider: Optional[FilenameProvider] = None,
da... | _FileDatasink |
python | crytic__slither | slither/detectors/compiler_bugs/public_mapping_nested.py | {
"start": 2030,
"end": 3741
} | class ____(AbstractDetector):
"""
Detects public mappings with nested variables (returns incorrect values prior to 0.5.x)
"""
ARGUMENT = "public-mappings-nested"
HELP = "Public mappings with nested variables"
IMPACT = DetectorClassification.HIGH
CONFIDENCE = DetectorClassification.HIGH
... | PublicMappingNested |
python | scipy__scipy | scipy/stats/tests/test_morestats.py | {
"start": 48544,
"end": 53642
} | class ____:
def _perturb(self, g, rng=124987234782812):
# g arrays have ties to which statistic is very sensitive; break them
rng = np.random.default_rng(rng)
return (np.asarray(g) + 1e-10 * rng.standard_normal(len(g))).tolist()
@pytest.mark.parametrize('dtype', [None, 'float32', 'floa... | TestFligner |
python | coleifer__peewee | tests/regressions.py | {
"start": 37350,
"end": 38158
} | class ____(ModelTestCase):
requires = [JM]
def test_list_value_conversion(self):
jm = JM.create(key='k1', data=['i0', 'i1'])
jm.key = 'k1-x'
jm.save()
jm_db = JM.get(JM.key == 'k1-x')
self.assertEqual(jm_db.data, ['i0', 'i1'])
JM.update(data=['i1', 'i2']).execu... | TestListValueConversion |
python | kamyu104__LeetCode-Solutions | Python/a-number-after-a-double-reversal.py | {
"start": 29,
"end": 196
} | class ____(object):
def isSameAfterReversals(self, num):
"""
:type num: int
:rtype: bool
"""
return num == 0 or num%10
| Solution |
python | walkccc__LeetCode | solutions/1897. Redistribute Characters to Make All Strings Equal/1897.py | {
"start": 0,
"end": 170
} | class ____:
def makeEqual(self, words: list[str]) -> bool:
return all(c % len(words) == 0
for c in collections.Counter(''.join(words)).values())
| Solution |
python | spyder-ide__spyder | external-deps/python-lsp-server/pylsp/lsp.py | {
"start": 1034,
"end": 1347
} | class ____:
File = 1
Module = 2
Namespace = 3
Package = 4
Class = 5
Method = 6
Property = 7
Field = 8
Constructor = 9
Enum = 10
Interface = 11
Function = 12
Variable = 13
Constant = 14
String = 15
Number = 16
Boolean = 17
Array = 18
| SymbolKind |
python | django__django | tests/generic_views/views.py | {
"start": 5407,
"end": 5475
} | class ____(BookConfig, generic.ArchiveIndexView):
pass
| BookArchive |
python | google__pytype | pytype/tests/test_list1.py | {
"start": 69,
"end": 2499
} | class ____(test_base.BaseTest):
"""Tests for builtins.list."""
def test_add(self):
ty = self.Infer("""
a = []
a = a + [42]
b = []
b = b + [42]
b = b + ["foo"]
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import List, Union
a = ... # type... | ListTest |
python | numba__numba | numba/tests/test_literal_dispatch.py | {
"start": 9891,
"end": 11732
} | class ____(TestCase):
def make_dummy_type(self):
class Dummy(object):
def lit(self, a):
return a
class DummyType(types.Type):
def __init__(self):
super(DummyType, self).__init__(name="dummy")
@register_model(DummyType)
class D... | TestLiteralDispatchWithCustomType |
python | pytorch__pytorch | torch/utils/data/datapipes/iter/combining.py | {
"start": 26488,
"end": 28085
} | class ____(IterDataPipe[tuple[_T_co]]):
r"""
Aggregates elements into a tuple from each of the input DataPipes (functional name: ``zip``).
The output is stopped as soon as the shortest input DataPipe is exhausted.
Args:
*datapipes: Iterable DataPipes being aggregated
Example:
>>> ... | ZipperIterDataPipe |
python | matplotlib__matplotlib | lib/matplotlib/colorizer.py | {
"start": 25806,
"end": 34071
} | class ____(_ScalarMappable, artist.Artist):
"""
Base class for artists that make map data to color using a `.colorizer.Colorizer`.
The `.colorizer.Colorizer` applies data normalization before
returning RGBA colors from a `~matplotlib.colors.Colormap`.
"""
def __init__(self, colorizer, **kwargs... | ColorizingArtist |
python | huggingface__transformers | src/transformers/models/data2vec/modeling_data2vec_audio.py | {
"start": 18055,
"end": 26795
} | class ____(PreTrainedModel):
config: Data2VecAudioConfig
base_model_prefix = "data2vec_audio"
main_input_name = "input_values"
input_modalities = "audio"
supports_gradient_checkpointing = True
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
@torch.no_gra... | Data2VecAudioPreTrainedModel |
python | kamyu104__LeetCode-Solutions | Python/minimum-cost-path-with-teleportations.py | {
"start": 1360,
"end": 2414
} | class ____(object):
def minCost(self, grid, k):
"""
:type grid: List[List[int]]
:type k: int
:rtype: int
"""
dp = [[float("inf")]*len(grid[0]) for _ in xrange(len(grid))]
dp[-1][-1] = 0
mx = max(max(row) for row in grid)
prefix = [float("inf")]... | Solution2 |
python | dagster-io__dagster | python_modules/libraries/dagster-dbt/dagster_dbt/asset_utils.py | {
"start": 15321,
"end": 46651
} | class ____:
manifest: Mapping[str, Any]
dagster_dbt_translator: Annotated[
"DagsterDbtTranslator", ImportFrom("dagster_dbt.dagster_dbt_translator")
]
selection_args: Sequence[str]
indirect_selection: Optional[str]
dbt_project: Optional[DbtProject]
def get_updated_cli_invocation_params_... | DbtCliInvocationPartialParams |
python | encode__django-rest-framework | tests/test_filters.py | {
"start": 13924,
"end": 15593
} | class ____(TestCase):
def setUp(self):
# Sequence of title/text/attributes is:
#
# z abc [1, 2, 3]
# zz bcd [1, 2, 3]
# zzz cde [1, 2, 3]
# ...
for idx in range(3):
label = 'w' * (idx + 1)
AttributeModel.objects.create(label=label)
... | SearchFilterM2MTests |
python | openai__openai-python | src/openai/types/evals/create_eval_completions_run_data_source_param.py | {
"start": 7587,
"end": 8317
} | class ____(TypedDict, total=False):
source: Required[Source]
"""Determines what populates the `item` namespace in this run's data source."""
type: Required[Literal["completions"]]
"""The type of run data source. Always `completions`."""
input_messages: InputMessages
"""Used when sampling from ... | CreateEvalCompletionsRunDataSourceParam |
python | facebook__pyre-check | client/commands/server_event.py | {
"start": 614,
"end": 682
} | class ____:
socket_path: Path
@dataclasses.dataclass
| SocketCreated |
python | gevent__gevent | src/greentest/3.12/test_signal.py | {
"start": 44101,
"end": 51483
} | 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 | doocs__leetcode | lcci/17.23.Max Black Square/Solution.py | {
"start": 0,
"end": 870
} | class ____:
def findSquare(self, matrix: List[List[int]]) -> List[int]:
n = len(matrix)
down = [[0] * n for _ in range(n)]
right = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(n - 1, -1, -1):
if matrix[i][j] == 0:
... | Solution |
python | aio-libs__aiohttp | tests/test_resolver.py | {
"start": 2511,
"end": 2721
} | class ____:
def __init__(self, hosts: Collection[str]) -> None:
self.nodes = [
FakeAIODNSAddrInfoNode(socket.AF_INET, (h.encode(), 0)) for h in hosts
]
| FakeAIODNSAddrInfoIPv4Result |
python | joke2k__faker | faker/providers/date_time/ko_KR/__init__.py | {
"start": 46,
"end": 796
} | class ____(DateTimeProvider):
def day_of_week(self) -> str:
day = self.date("%w")
DAY_NAMES = {
"0": "일요일",
"1": "월요일",
"2": "화요일",
"3": "수요일",
"4": "목요일",
"5": "금요일",
"6": "토요일",
}
return DAY_NAMES[d... | Provider |
python | huggingface__transformers | src/transformers/models/wav2vec2/processing_wav2vec2.py | {
"start": 940,
"end": 5620
} | class ____(ProcessorMixin):
r"""
Constructs a Wav2Vec2 processor which wraps a Wav2Vec2 feature extractor and a Wav2Vec2 CTC tokenizer into a single
processor.
[`Wav2Vec2Processor`] offers all the functionalities of [`Wav2Vec2FeatureExtractor`] and [`PreTrainedTokenizer`].
See the docstring of [`~W... | Wav2Vec2Processor |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_password_is_not_leaked.py | {
"start": 1884,
"end": 4563
} | class ____(ColumnMapExpectation):
"""Expect column values password not leaked (according to haveibeenpwned's API)."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"not_... | ExpectColumnValuesPasswordIsNotLeaked |
python | pypa__setuptools | setuptools/_vendor/importlib_metadata/__init__.py | {
"start": 22286,
"end": 23665
} | class ____:
"""
Micro-optimized class for searching a root for children.
Root is a path on the file system that may contain metadata
directories either as natural directories or within a zip file.
>>> FastPath('').children()
['...']
FastPath objects are cached and recycled for any given r... | FastPath |
python | run-llama__llama_index | llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-redis/llama_index/storage/chat_store/redis/base.py | {
"start": 902,
"end": 15279
} | class ____(BaseChatStore):
"""Redis chat store."""
redis_url: str = Field(default="redis://localhost:6379", description="Redis URL.")
ttl: Optional[int] = Field(default=None, description="Time to live in seconds.")
_redis_client: Optional[Redis] = PrivateAttr()
_aredis_client: Optional[AsyncRedis]... | RedisChatStore |
python | apache__thrift | lib/py/src/TMultiplexedProcessor.py | {
"start": 965,
"end": 3114
} | class ____(TProcessor):
def __init__(self):
self.defaultProcessor = None
self.services = {}
def registerDefault(self, processor):
"""
If a non-multiplexed processor connects to the server and wants to
communicate, use the given processor to handle it. This mechanism
... | TMultiplexedProcessor |
python | bokeh__bokeh | release/logger.py | {
"start": 1217,
"end": 2466
} | class ____:
""""""
def __init__(self) -> None:
self._scrubbers: list[Scrubber] = []
self._record: list[str] = []
def add_scrubber(self, scrubber: Scrubber) -> None:
""""""
self._scrubbers.append(scrubber)
self._scrubbers.sort(key=len)
def record(self, *lines: s... | Log |
python | FactoryBoy__factory_boy | tests/test_using.py | {
"start": 69948,
"end": 74948
} | class ____(unittest.TestCase):
def test_post_generation(self):
class TestObjectFactory(factory.Factory):
class Meta:
model = TestObject
one = 1
@factory.post_generation
def incr_one(self, _create, _increment):
self.one += 1
... | PostGenerationTestCase |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-s3/source_s3/v4/source.py | {
"start": 1281,
"end": 8967
} | class ____(FileBasedSource):
_concurrency_level = DEFAULT_CONCURRENCY
@classmethod
def read_config(cls, config_path: str) -> Mapping[str, Any]:
"""
Used to override the default read_config so that when the new file-based S3 connector processes a config
in the legacy format, it can b... | SourceS3 |
python | streamlit__streamlit | lib/streamlit/runtime/stats.py | {
"start": 877,
"end": 3007
} | class ____(NamedTuple):
"""Describes a single cache entry.
Properties
----------
category_name : str
A human-readable name for the cache "category" that the entry belongs
to - e.g. "st.memo", "session_state", etc.
cache_name : str
A human-readable name for cache instance tha... | CacheStat |
python | falconry__falcon | tests/test_cors_middleware.py | {
"start": 7664,
"end": 13755
} | class ____:
def test_raises(self):
with pytest.raises(ValueError, match='passed to allow_origins'):
falcon.CORSMiddleware(allow_origins=['*'])
with pytest.raises(ValueError, match='passed to allow_credentials'):
falcon.CORSMiddleware(allow_credentials=['*'])
@pytest.mark... | TestCustomCorsMiddleware |
python | scipy__scipy | scipy/special/_support_alternative_backends.py | {
"start": 463,
"end": 28147
} | class ____:
# NumPy-only function. IT MUST BE ELEMENTWISE.
func: Callable
# Number of arguments, not counting out=
# This is for testing purposes only, due to the fact that
# inspect.signature() just returns *args for ufuncs.
n_args: int
# @xp_capabilities decorator, for the purpose of
#... | _FuncInfo |
python | pypa__pip | src/pip/_internal/cli/command_context.py | {
"start": 176,
"end": 817
} | class ____:
def __init__(self) -> None:
super().__init__()
self._in_main_context = False
self._main_context = ExitStack()
@contextmanager
def main_context(self) -> Generator[None, None, None]:
assert not self._in_main_context
self._in_main_context = True
try... | CommandContextMixIn |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 126118,
"end": 128185
} | class ____:
def test_format_timeframe(self):
assert self.locale._format_timeframe("now", 0) == "sasa hivi"
assert self.locale._format_timeframe("second", 1) == "sekunde"
assert self.locale._format_timeframe("seconds", 3) == "sekunde 3"
assert self.locale._format_timeframe("seconds", ... | TestSwahiliLocale |
python | tensorflow__tensorflow | tensorflow/python/debug/cli/debugger_cli_common_test.py | {
"start": 41508,
"end": 44586
} | class ____(test_util.TensorFlowTestCase):
def setUp(self):
self.menu = debugger_cli_common.Menu()
self.assertEqual(0, self.menu.num_items())
self.node1 = debugger_cli_common.MenuItem("water flower", "water_flower")
self.node2 = debugger_cli_common.MenuItem(
"measure wavelength", "measure_wav... | MenuTest |
python | python-openxml__python-docx | src/docx/oxml/text/run.py | {
"start": 7510,
"end": 8052
} | class ____(BaseOxmlElement):
"""`<w:noBreakHyphen>` element, a hyphen ineligible for a line-wrap position.
This maps to a plain-text dash ("-").
NOTE: this complex-type name does not exist in the schema, where `w:noBreakHyphen`
maps to `CT_Empty`. This name was added to give it behavior distinguished ... | CT_NoBreakHyphen |
python | spack__spack | lib/spack/spack/database.py | {
"start": 72585,
"end": 72710
} | class ____(SpackError):
"""Raised when an operation would need to lock an upstream database"""
| UpstreamDatabaseLockingError |
python | langchain-ai__langchain | libs/core/langchain_core/prompts/chat.py | {
"start": 22702,
"end": 25566
} | class ____(BasePromptTemplate, ABC):
"""Base class for chat prompt templates."""
@property
@override
def lc_attributes(self) -> dict:
return {"input_variables": self.input_variables}
def format(self, **kwargs: Any) -> str:
"""Format the chat template into a string.
Args:
... | BaseChatPromptTemplate |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pep8_naming/ignore_names/N803.py | {
"start": 110,
"end": 264
} | class ____:
def method(self, _, a, badAllowed):
return _, a, badAllowed
def method(self, _, a, stillBad):
return _, a, stillBad
| Class |
python | kamyu104__LeetCode-Solutions | Python/unit-conversion-i.py | {
"start": 35,
"end": 645
} | class ____(object):
def baseUnitConversions(self, conversions):
"""
:type conversions: List[List[int]]
:rtype: List[int]
"""
MOD = 10**9+7
adj = [[] for _ in xrange(len(conversions)+1)]
for u, v, w in conversions:
adj[u].append((v, w))
resu... | Solution |
python | weaviate__weaviate-python-client | weaviate/connect/v4.py | {
"start": 3013,
"end": 34131
} | class ____:
def __init__(
self,
connection_params: ConnectionParams,
auth_client_secret: Optional[AuthCredentials],
timeout_config: TimeoutConfig,
proxies: Union[str, Proxies, None],
trust_env: bool,
additional_headers: Optional[Dict[str, Any]],
connec... | _ConnectionBase |
python | kamyu104__LeetCode-Solutions | Python/maximum-profit-in-job-scheduling.py | {
"start": 66,
"end": 614
} | class ____(object):
def jobScheduling(self, startTime, endTime, profit):
"""
:type startTime: List[int]
:type endTime: List[int]
:type profit: List[int]
:rtype: int
"""
jobs = sorted(itertools.izip(endTime, startTime, profit))
dp = [(0, 0)]
for... | Solution |
python | google__flatbuffers | tests/py_flexbuffers_test.py | {
"start": 3546,
"end": 8749
} | class ____(unittest.TestCase):
"""Tests to check FlexBuffer utility functions."""
def _test_type_predicate(self, pred, types):
for type_ in types:
with self.subTest(type=type_, pred=pred):
self.assertTrue(pred(type_))
for type_ in set(Type).difference(types):
with self.subTest(type=typ... | UtilTest |
python | pypa__warehouse | tests/unit/admin/views/test_projects.py | {
"start": 18853,
"end": 22072
} | class ____:
def test_add_observation(self, db_request):
project = ProjectFactory.create()
observer = ObserverFactory.create()
user = UserFactory.create(observer=observer)
db_request.route_path = pretend.call_recorder(
lambda *a, **kw: "/admin/projects/"
)
... | TestProjectAddObservation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.