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 | doocs__leetcode | solution/3100-3199/3138.Minimum Length of Anagram Concatenation/Solution.py | {
"start": 0,
"end": 474
} | class ____:
def minAnagramLength(self, s: str) -> int:
def check(k: int) -> bool:
for i in range(0, n, k):
cnt1 = Counter(s[i : i + k])
for c, v in cnt.items():
if cnt1[c] * (n // k) != v:
return False
return... | Solution |
python | has2k1__plotnine | plotnine/scales/scale_xy.py | {
"start": 7143,
"end": 7202
} | class ____(scale_x_discrete):
pass
@alias
| scale_x_ordinal |
python | getsentry__sentry | tests/sentry/discover/test_dashboard_widget_split.py | {
"start": 24674,
"end": 24841
} | class ____(DashboardWidgetDatasetSplitTestCase):
def setUp(self) -> None:
super().setUp()
self.dry_run = True
| DashboardWidgetDatasetSplitDryRunTestCase |
python | huggingface__transformers | src/transformers/models/layoutlmv2/modeling_layoutlmv2.py | {
"start": 8991,
"end": 9654
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(sel... | LayoutLMv2SelfOutput |
python | run-llama__llama_index | llama-index-integrations/indices/llama-index-indices-managed-vectara/llama_index/indices/managed/vectara/base.py | {
"start": 1087,
"end": 1294
} | class ____(IndexDict):
"""Vectara Index Struct."""
@classmethod
def get_type(cls) -> IndexStructType:
"""Get index struct type."""
return IndexStructType.VECTARA
| VectaraIndexStruct |
python | django-guardian__django-guardian | guardian/testapp/migrations/0006_auto_20230727_0658.py | {
"start": 93,
"end": 2641
} | class ____(migrations.Migration):
dependencies = [
("testapp", "0005_uuidpkmodel"),
]
operations = [
migrations.AlterField(
model_name="customuser",
name="first_name",
field=models.CharField(blank=True, max_length=150, verbose_name="first name"),
... | Migration |
python | python-pillow__Pillow | src/PIL/SgiImagePlugin.py | {
"start": 1052,
"end": 5378
} | class ____(ImageFile.ImageFile):
format = "SGI"
format_description = "SGI Image File Format"
def _open(self) -> None:
# HEAD
assert self.fp is not None
headlen = 512
s = self.fp.read(headlen)
if not _accept(s):
msg = "Not an SGI image file"
... | SgiImageFile |
python | PyCQA__pylint | tests/functional/m/member/member_checks_typed_annotations.py | {
"start": 140,
"end": 284
} | class ____(C, B):
pass
a = A()
print(a.myfield)
b = B()
print(b.myfield)
d = D()
print(d.myfield)
c = C()
print(c.myfield) # [no-member]
| D |
python | python-openxml__python-docx | src/docx/enum/base.py | {
"start": 284,
"end": 881
} | class ____(int, enum.Enum):
"""Base class for Enums that do not map XML attr values.
The enum's value will be an integer, corresponding to the integer assigned the
corresponding member in the MS API enum of the same name.
"""
def __new__(cls, ms_api_value: int, docstr: str):
self = int.__n... | BaseEnum |
python | encode__django-rest-framework | tests/test_pagination.py | {
"start": 10531,
"end": 12437
} | class ____:
"""
Unit tests for `pagination.PageNumberPagination`.
the Django Paginator Class is overridden.
"""
def setup_method(self):
class OverriddenDjangoPaginator(DjangoPaginator):
# override the count in our overridden Django Paginator
# we will only return on... | TestPageNumberPaginationOverride |
python | openai__openai-python | src/openai/types/chat/chat_completion_audio_param.py | {
"start": 249,
"end": 811
} | class ____(TypedDict, total=False):
format: Required[Literal["wav", "aac", "mp3", "flac", "opus", "pcm16"]]
"""Specifies the output audio format.
Must be one of `wav`, `mp3`, `flac`, `opus`, or `pcm16`.
"""
voice: Required[
Union[str, Literal["alloy", "ash", "ballad", "coral", "echo", "sag... | ChatCompletionAudioParam |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/nocover/test_strategy_state.py | {
"start": 998,
"end": 5335
} | class ____(RuleBasedStateMachine):
def __init__(self):
super().__init__()
self.database = None
strategies = Bundle("strategy")
strategy_tuples = Bundle("tuples")
objects = Bundle("objects")
basic_data = Bundle("basic")
varied_floats = Bundle("varied_floats")
def teardown(se... | HypothesisSpec |
python | kamyu104__LeetCode-Solutions | Python/most-frequent-prime.py | {
"start": 1644,
"end": 2378
} | class ____(object):
def mostFrequentPrime(self, mat):
"""
:type mat: List[List[int]]
:rtype: int
"""
DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1))
def numbers(i, j, di, dj):
curr = 0
while 0 <= i < len(mat)... | Solution2 |
python | doocs__leetcode | solution/3200-3299/3280.Convert Date to Binary/Solution.py | {
"start": 0,
"end": 133
} | class ____:
def convertDateToBinary(self, date: str) -> str:
return "-".join(f"{int(s):b}" for s in date.split("-"))
| Solution |
python | tartley__colorama | colorama/ansitowin32.py | {
"start": 2236,
"end": 11112
} | class ____:
'''
Implements a 'write()' method which, on Windows, will strip ANSI character
sequences from the text, and if outputting to a tty, will convert them into
win32 function calls.
'''
ANSI_CSI_RE = re.compile('\001?\033\\[((?:\\d|;)*)([a-zA-Z])\002?') # Control Sequence Introducer
... | AnsiToWin32 |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol30.py | {
"start": 160,
"end": 196
} | class ____(Protocol):
v1: float
| P1 |
python | realpython__materials | inheritance-and-composition/choosing/productivity.py | {
"start": 850,
"end": 960
} | class ____:
def perform_duties(self, hours):
return f"expends {hours} hours on the phone."
| SalesRole |
python | kamyu104__LeetCode-Solutions | Python/closest-node-to-path-in-tree.py | {
"start": 1159,
"end": 2444
} | class ____(object): # Time: O(N), Space: O(N + Q), N is the number of nodes
def __init__(self, children, pairs):
def preprocess(curr, parent):
# depth of the node i
D[curr] = 1 if parent == -1 else D[parent]+1
def divide(curr, parent):
stk.append(partial(postpro... | TreeInfos |
python | pandas-dev__pandas | pandas/tests/series/indexing/test_setitem.py | {
"start": 33691,
"end": 34451
} | class ____(SetitemCastingEquivalents):
# Setting compatible NA values into Series with PeriodDtype
@pytest.fixture
def expected(self, key):
exp = Series(period_range("2000-01-01", periods=10, freq="D"))
exp._values.view("i8")[key] = NaT._value
assert exp[key] is NaT or all(x is NaT ... | TestSetitemNAPeriodDtype |
python | getsentry__sentry | src/sentry/snuba/metrics/fields/base.py | {
"start": 19585,
"end": 25021
} | class ____(ABC):
@abstractmethod
def validate_can_orderby(self) -> None:
"""
Validate that the expression can be used to order a query
"""
raise NotImplementedError
@abstractmethod
def get_entity(
self, projects: QuerySet[Project] | Sequence[Project], use_case_id... | MetricExpressionBase |
python | PyCQA__pylint | doc/data/messages/i/invalid-bool-returned/bad.py | {
"start": 0,
"end": 121
} | class ____:
"""__bool__ returns an int"""
def __bool__(self): # [invalid-bool-returned]
return 1
| CustomBool |
python | getsentry__sentry-python | tests/integrations/asgi/test_asgi.py | {
"start": 13808,
"end": 13863
} | class ____:
def __call__():
pass
| MockAsgi2App |
python | weaviate__weaviate-python-client | weaviate/collections/classes/cluster.py | {
"start": 566,
"end": 739
} | class ____:
"""The statistics of a collection."""
object_count: int
shard_count: int
Shards = List[Shard]
Sh = TypeVar("Sh")
St = TypeVar("St")
@dataclass
| Stats |
python | pydantic__pydantic | pydantic-core/tests/benchmarks/test_micro_benchmarks.py | {
"start": 39364,
"end": 44910
} | class ____(str, Enum):
foo = 'foo_val'
bar = 'bar_val'
baz = 'baz_val'
LARGE_STR_PREFIX = 'a' * 50
@pytest.mark.benchmark(group='validate_literal')
@pytest.mark.parametrize(
'allowed_values,input,expected_val_res',
[
(list(range(5)), 4, 4),
([f'abc{i}' for i in range(5)], 'abc4',... | SomeStrEnum |
python | facelessuser__soupsieve | tests/test_level3/test_nth_of_type.py | {
"start": 58,
"end": 1669
} | class ____(util.TestCase):
"""Test `nth` of type selectors."""
def test_nth_of_type(self):
"""Test `nth` of type."""
markup = """
<body>
<p id="0"></p>
<p id="1"></p>
<span id="2"></span>
<span id="3"></span>
<span id="4"></span>
<span id... | TestNthOfType |
python | allegroai__clearml | clearml/backend_api/services/v2_23/events.py | {
"start": 53903,
"end": 54151
} | class ____(BatchRequest):
"""
Adds a batch of events in a single call (json-lines format, stream-friendly)
"""
_service = "events"
_action = "add_batch"
_version = "2.23"
_batched_request_cls = AddRequest
| AddBatchRequest |
python | huggingface__transformers | src/transformers/utils/generic.py | {
"start": 14667,
"end": 14906
} | class ____(ExplicitEnum):
"""
Possible values for the `return_tensors` argument in [`PreTrainedTokenizerBase.__call__`]. Useful for
tab-completion in an IDE.
"""
PYTORCH = "pt"
NUMPY = "np"
MLX = "mlx"
| TensorType |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 230114,
"end": 233557
} | class ____(Request):
"""
Delete task hyper parameters
:param task: Task ID
:type task: str
:param hyperparams: List of hyper parameters to delete. In case a parameter
with an empty name is passed all the section will be deleted
:type hyperparams: Sequence[ParamKey]
:param force: If ... | DeleteHyperParamsRequest |
python | pytorch__pytorch | test/torch_np/numpy_tests/linalg/test_linalg.py | {
"start": 17577,
"end": 17830
} | class ____(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
def do(self, a, b, tags):
ev = linalg.eigvals(a)
evalues, evectors = linalg.eig(a)
assert_almost_equal(ev, evalues)
@instantiate_parametrized_tests
| EigvalsCases |
python | chroma-core__chroma | chromadb/test/configurations/test_collection_configuration.py | {
"start": 57131,
"end": 57229
} | class ____(TypedDict):
task: str
@register_embedding_function
| CustomEmbeddingFunctionQueryConfig |
python | Lightning-AI__lightning | tests/tests_pytorch/trainer/connectors/test_data_connector.py | {
"start": 19005,
"end": 27257
} | class ____:
def overridden_func(self, batch, *args, **kwargs):
return batch
def reset_instances(self):
warning_cache.clear()
return BoringDataModule(), BoringModel(), Trainer()
def test_no_datamodule_no_overridden(self, hook_name):
model, _, trainer = self.reset_instances()... | TestDataHookSelector |
python | numba__numba | numba/tests/test_dyn_array.py | {
"start": 969,
"end": 1500
} | class ____(TestCase):
def check_outputs(self, pyfunc, argslist, exact=True):
cfunc = nrtjit(pyfunc)
for args in argslist:
expected = pyfunc(*args)
ret = cfunc(*args)
self.assertEqual(ret.size, expected.size)
self.assertEqual(ret.dtype, expected.dtype)... | BaseTest |
python | FactoryBoy__factory_boy | tests/djapp/models.py | {
"start": 1068,
"end": 1116
} | class ____(AbstractSon):
pass
| ConcreteGrandSon |
python | pydantic__pydantic | pydantic/types.py | {
"start": 85792,
"end": 86976
} | class ____(BaseModel):
base64_str: Base64Str
# Initialize the model with base64 data
m = Model(base64_str='VGhlc2UgYXJlbid0IHRoZSBkcm9pZHMgeW91J3JlIGxvb2tpbmcgZm9y')
# Access decoded value
print(m.base64_str)
#> These aren't the droids you're looking for
# Serialize into the base64 form
print(m.model_dump())
#> ... | Model |
python | aio-libs__aiohttp | aiohttp/_websocket/models.py | {
"start": 2288,
"end": 2449
} | class ____(NamedTuple):
data: None = None
size: int = 0
extra: str | None = None
type: Literal[WSMsgType.CLOSED] = WSMsgType.CLOSED
| WSMessageClosed |
python | django__django | tests/foreign_object/test_tuple_lookups.py | {
"start": 380,
"end": 19564
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
super().setUpTestData()
cls.customer_1 = Customer.objects.create(customer_id=1, company="a")
cls.customer_2 = Customer.objects.create(customer_id=1, company="b")
cls.customer_3 = Customer.objects.create(customer_id=2, com... | TupleLookupsTests |
python | doocs__leetcode | solution/3300-3399/3310.Remove Methods From Project/Solution.py | {
"start": 0,
"end": 887
} | class ____:
def remainingMethods(
self, n: int, k: int, invocations: List[List[int]]
) -> List[int]:
def dfs(i: int):
suspicious[i] = True
for j in g[i]:
if not suspicious[j]:
dfs(j)
def dfs2(i: int):
vis[i] = True
... | Solution |
python | getsentry__sentry | src/sentry/migrations/0973_safe_del_dashboardwidgetsnapshot.py | {
"start": 240,
"end": 1509
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | scikit-learn__scikit-learn | sklearn/utils/tests/test_set_output.py | {
"start": 13453,
"end": 14024
} | class ____(_SetOutputMixin):
def __init__(self, OutputTuple):
self.OutputTuple = OutputTuple
def transform(self, X, y=None):
return self.OutputTuple(X, 2 * X)
def test_set_output_named_tuple_out():
"""Check that namedtuples are kept by default."""
Output = namedtuple("Output", "X, Y")... | EstimatorReturnTuple |
python | wandb__wandb | wandb/vendor/pygments/lexers/c_like.py | {
"start": 3314,
"end": 4954
} | class ____(RegexLexer):
"""
For `Clay <http://claylabs.com/clay/>`_ source.
.. versionadded:: 2.0
"""
name = 'Clay'
filenames = ['*.clay']
aliases = ['clay']
mimetypes = ['text/x-clay']
tokens = {
'root': [
(r'\s', Text),
(r'//.*?$', Comment.Singlelin... | ClayLexer |
python | doocs__leetcode | solution/1700-1799/1766.Tree of Coprimes/Solution.py | {
"start": 0,
"end": 887
} | class ____:
def getCoprimes(self, nums: List[int], edges: List[List[int]]) -> List[int]:
def dfs(i, fa, depth):
t = k = -1
for v in f[nums[i]]:
stk = stks[v]
if stk and stk[-1][1] > k:
t, k = stk[-1]
ans[i] = t
... | Solution |
python | python-markdown__markdown | markdown/test_tools.py | {
"start": 4070,
"end": 4627
} | class ____(dict):
""" A `dict` like class for holding keyword arguments. """
pass
def _normalize_whitespace(text):
""" Normalize whitespace for a string of HTML using `tidylib`. """
output, errors = tidylib.tidy_fragment(text, options={
'drop_empty_paras': 0,
'fix_backslash': 0,
... | Kwargs |
python | huggingface__transformers | tests/test_configuration_common.py | {
"start": 901,
"end": 11998
} | class ____:
def __init__(self, parent, config_class=None, has_text_modality=True, common_properties=None, **kwargs):
self.parent = parent
self.config_class = config_class
self.has_text_modality = has_text_modality
self.inputs_dict = kwargs
self.common_properties = common_prop... | ConfigTester |
python | getsentry__sentry | src/sentry/preprod/migrations/0006_add_analysis_file_id_field.py | {
"start": 186,
"end": 1530
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/streams/streams.py | {
"start": 11996,
"end": 12064
} | class ____(AdsInsights):
breakdowns = ["region"]
| AdsInsightsRegion |
python | PrefectHQ__prefect | src/prefect/server/events/actions.py | {
"start": 57357,
"end": 57802
} | class ____(WorkQueueCommandAction):
"""Pauses a Work Queue"""
type: Literal["pause-work-queue"] = "pause-work-queue"
_action_description: ClassVar[str] = "Pausing work queue"
async def command(
self,
orchestration: "OrchestrationClient",
work_queue_id: UUID,
triggered_... | PauseWorkQueue |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/cat_test.py | {
"start": 3316,
"end": 4433
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, sizes, N, dim, device):
random.seed(42)
inputs = []
gen_sizes = []
if type(sizes) is list and N == -1:
gen_sizes = sizes
else:
for i in range(N):
gen_sizes.append(
... | CatBenchmark |
python | pandas-dev__pandas | doc/source/conf.py | {
"start": 19571,
"end": 19803
} | class ____(AccessorLevelDocumenter, MethodDocumenter):
objtype = "accessormethod"
directivetype = "method"
# lower than MethodDocumenter so this is not chosen for normal methods
priority = 0.6
| AccessorMethodDocumenter |
python | django-extensions__django-extensions | tests/db/fields/test_uniq_field_mixin.py | {
"start": 346,
"end": 5534
} | class ____(TestCase):
def setUp(self):
class MockField(UniqueFieldMixin):
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
self.uniq_field = MockField(
attname="uniq_field",
max_length=2... | UniqFieldMixinTestCase |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/asyncpg.py | {
"start": 10864,
"end": 10996
} | class ____(sqltypes.JSON.JSONIntIndexType):
__visit_name__ = "json_int_index"
render_bind_cast = True
| AsyncpgJSONIntIndexType |
python | python-poetry__poetry | tests/installation/test_executor.py | {
"start": 1570,
"end": 54560
} | class ____(BaseChef):
_directory_wheels: list[Path] | None = None
_sdist_wheels: list[Path] | None = None
def set_directory_wheel(self, wheels: Path | list[Path]) -> None:
if not isinstance(wheels, list):
wheels = [wheels]
self._directory_wheels = wheels
def set_sdist_whee... | Chef |
python | PrefectHQ__prefect | src/prefect/client/schemas/filters.py | {
"start": 26802,
"end": 27202
} | class ____(PrefectBaseModel, OperatorMixin):
"""Filter work queues. Only work queues matching all criteria will be
returned"""
id: Optional[WorkQueueFilterId] = Field(
default=None, description="Filter criteria for `WorkQueue.id`"
)
name: Optional[WorkQueueFilterName] = Field(
defa... | WorkQueueFilter |
python | huggingface__transformers | src/transformers/models/instructblipvideo/modeling_instructblipvideo.py | {
"start": 28538,
"end": 35685
} | class ____(InstructBlipVideoPreTrainedModel):
"""
Querying Transformer (Q-Former), used in InstructBlipVideo. Slightly modified from BLIP-2 as it also takes the
instruction as input.
"""
_supports_attention_backend = False # adds position on attn weights before last matmul
_supports_flash_attn... | InstructBlipVideoQFormerModel |
python | readthedocs__readthedocs.org | readthedocs/proxito/exceptions.py | {
"start": 3548,
"end": 4177
} | class ____(ContextualizedHttp404):
"""Raised if a page inside an existing project was not found."""
template_name = "errors/proxito/404/no_project.html"
not_found_subject = pgettext_lazy(_not_found_subject_translation_context, "documentation page")
def __init__(self, project, **kwargs):
"""
... | ProjectFilenameHttp404 |
python | sympy__sympy | sympy/matrices/expressions/special.py | {
"start": 2725,
"end": 4128
} | class ____(MatrixExpr):
"""The Matrix Identity I - multiplicative identity
Examples
========
>>> from sympy import Identity, MatrixSymbol
>>> A = MatrixSymbol('A', 3, 5)
>>> I = Identity(3)
>>> I*A
A
>>> I.as_explicit()
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
... | Identity |
python | run-llama__llama_index | llama-index-core/llama_index/core/langchain_helpers/memory_wrapper.py | {
"start": 971,
"end": 3602
} | class ____(Memory):
"""
Langchain memory wrapper (for LlamaIndex).
Args:
human_prefix (str): Prefix for human input. Defaults to "Human".
ai_prefix (str): Prefix for AI output. Defaults to "AI".
memory_key (str): Key for memory. Defaults to "history".
index (BaseIndex): Llam... | GPTIndexMemory |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_basic.py | {
"start": 23178,
"end": 24673
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
global t1
t1 = Table(
"t1",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("type", Boolean, null... | FalseDiscriminatorTest |
python | huggingface__transformers | src/transformers/models/phi3/modeling_phi3.py | {
"start": 16171,
"end": 19401
} | class ____(Phi3PreTrainedModel):
def __init__(self, config: Phi3Config):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.layers ... | Phi3Model |
python | numpy__numpy | benchmarks/benchmarks/bench_linalg.py | {
"start": 3479,
"end": 7061
} | class ____(Benchmark):
param_names = ['dtype']
params = [[np.float32, np.float64]]
def setup(self, dtype):
self.one_dim_small = np.arange(600, dtype=dtype)
self.one_dim = np.arange(3000, dtype=dtype)
self.one_dim_big = np.arange(480000, dtype=dtype)
self.two_dim_small = np.a... | Einsum |
python | django__django | django/contrib/gis/db/backends/base/adapter.py | {
"start": 0,
"end": 592
} | class ____:
"""
An adaptor for Geometries sent to the MySQL and Oracle database backends.
"""
def __init__(self, geom):
self.wkt = geom.wkt
self.srid = geom.srid
def __eq__(self, other):
return (
isinstance(other, WKTAdapter)
and self.wkt == other.wk... | WKTAdapter |
python | mkdocs__mkdocs | mkdocs/tests/config/config_options_tests.py | {
"start": 1744,
"end": 3233
} | class ____(TestCase):
def test_single_type(self) -> None:
class Schema(Config):
option = c.Type(str)
conf = self.get_config(Schema, {'option': "Testing"})
assert_type(conf.option, str)
self.assertEqual(conf.option, "Testing")
def test_multiple_types(self) -> None:
... | TypeTest |
python | conda__conda | conda/plugins/types.py | {
"start": 12856,
"end": 13564
} | class ____(CondaPlugin):
"""
Return type to use when defining a conda reporter backend plugin hook.
For details on how this is used, see:
:meth:`~conda.plugins.hookspec.CondaSpecs.conda_reporter_backends`.
:param name: name of the reporter backend (e.g., ``email_reporter``)
This i... | CondaReporterBackend |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/execution_tests/engine_tests/test_step_delegating_executor.py | {
"start": 1090,
"end": 13960
} | class ____(StepHandler):
# This step handler waits for all processes to exit, because windows tests flake when processes
# are left alive when the test ends. Non-test step handlers should not keep their own state in memory.
processes = []
launch_step_count = 0
saw_baz_op = False
check_step_healt... | TestStepHandler |
python | PrefectHQ__prefect | src/prefect/settings/models/server/services.py | {
"start": 13936,
"end": 15153
} | class ____(ServicesBaseSetting):
"""
Settings for controlling the pause expiration service
"""
model_config: ClassVar[SettingsConfigDict] = build_settings_config(
("server", "services", "pause_expirations")
)
enabled: bool = Field(
default=True,
description="""
... | ServerServicesPauseExpirationsSettings |
python | streamlit__streamlit | lib/streamlit/elements/deck_gl_json_chart.py | {
"start": 7697,
"end": 8644
} | class ____:
"""PydeckSelectionSerde is used to serialize and deserialize the Pydeck selection state."""
def deserialize(self, ui_value: str | None) -> PydeckState:
empty_selection_state: PydeckState = {
"selection": {
"indices": {},
"objects": {},
... | PydeckSelectionSerde |
python | huggingface__transformers | src/transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py | {
"start": 18053,
"end": 19601
} | class ____(PreTrainedModel):
config: Dinov2WithRegistersConfig
base_model_prefix = "dinov2_with_registers"
main_input_name = "pixel_values"
input_modalities = ("image",)
supports_gradient_checkpointing = True
_no_split_modules = ["Dinov2WithRegistersLayer"]
_supports_sdpa = True
_support... | Dinov2WithRegistersPreTrainedModel |
python | Pylons__pyramid | tests/test_viewderivers.py | {
"start": 70816,
"end": 70982
} | class ____:
def __init__(self):
self.messages = []
def info(self, msg):
self.messages.append(msg)
warn = info
debug = info
| DummyLogger |
python | sphinx-doc__sphinx | sphinx/search/sv.py | {
"start": 193,
"end": 596
} | class ____(SearchLanguage):
lang = 'sv'
language_name = 'Swedish'
js_stemmer_rawcode = 'swedish-stemmer.js'
stopwords = SWEDISH_STOPWORDS
def __init__(self, options: dict[str, str]) -> None:
super().__init__(options)
self.stemmer = snowballstemmer.stemmer('swedish')
def stem(se... | SearchSwedish |
python | rushter__MLAlgorithms | mla/neuralnet/optimizers.py | {
"start": 7549,
"end": 8784
} | class ____(Optimizer):
def __init__(self, learning_rate=0.002, beta_1=0.9, beta_2=0.999, epsilon=1e-8):
self.epsilon = epsilon
self.beta_2 = beta_2
self.beta_1 = beta_1
self.lr = learning_rate
self.t = 1
def update(self, network):
for i, layer in enumerate(networ... | Adamax |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1120131,
"end": 1120706
} | class ____(sgqlc.types.Type, Contribution):
"""Represents the contribution a user made by committing to a
repository.
"""
__schema__ = github_schema
__field_names__ = ("commit_count", "repository")
commit_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="commitCount")
"""Ho... | CreatedCommitContribution |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 36227,
"end": 37480
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
entry_point: Optional[str] = Field(
None,
description=(
"Named entry point to use, if it does not exist in the metadata of the"
... | PythonWheelTask |
python | sqlalchemy__sqlalchemy | test/sql/test_operators.py | {
"start": 37591,
"end": 42781
} | class ____(fixtures.TestBase, testing.AssertsCompiledSQL):
def setup_test(self):
class MyTypeCompiler(compiler.GenericTypeCompiler):
def visit_mytype(self, type_, **kw):
return "MYTYPE"
def visit_myothertype(self, type_, **kw):
return "MYOTHERTYPE"
... | JSONIndexOpTest |
python | getsentry__sentry | fixtures/safe_migrations_apps/good_flow_add_column_with_notnull_db_default_app/models.py | {
"start": 31,
"end": 108
} | class ____(models.Model):
field = models.IntegerField(db_default=0)
| TestTable |
python | huggingface__transformers | tests/cli/test_serve.py | {
"start": 9390,
"end": 13939
} | class ____:
"""
Mixin class for the Completions API tests, to seamlessly replicate tests across the two versions of the API
(`generate` and `continuous_batching`).
"""
@retry
def run_server(self, request):
with InferenceClient(f"http://localhost:{self.port}") as client:
retu... | ServeCompletionsMixin |
python | networkx__networkx | networkx/algorithms/tree/tests/test_recognition.py | {
"start": 2214,
"end": 4521
} | class ____(TestTreeRecognition):
graph = nx.DiGraph
multigraph = nx.MultiDiGraph
def test_disconnected_graph():
# https://github.com/networkx/networkx/issues/1144
G = nx.Graph()
G.add_edges_from([(0, 1), (1, 2), (2, 0), (3, 4)])
assert not nx.is_tree(G)
G = nx.DiGraph()
G.add_edges_fr... | TestDirectedTreeRecognition |
python | walkccc__LeetCode | solutions/2859. Sum of Values at Indices With K Set Bits/2859.py | {
"start": 0,
"end": 171
} | class ____:
def sumIndicesWithKSetBits(self, nums: list[int], k: int) -> int:
return sum(num for i, num in enumerate(nums)
if i.bit_count() == k)
| Solution |
python | django__django | tests/proxy_model_inheritance/models.py | {
"start": 149,
"end": 201
} | class ____(ProxyModel):
pass
| ConcreteModelSubclass |
python | eventlet__eventlet | eventlet/support/greendns.py | {
"start": 11371,
"end": 35489
} | class ____:
"""Resolver class which can also use /etc/hosts
Initialise with a HostsResolver instance in order for it to also
use the hosts file.
"""
def __init__(self, hosts_resolver=None, filename='/etc/resolv.conf'):
"""Initialise the resolver proxy
:param hosts_resolver: An ins... | ResolverProxy |
python | getsentry__sentry | tests/sentry/integrations/slack/webhooks/commands/__init__.py | {
"start": 834,
"end": 3885
} | class ____(APITestCase, TestCase):
endpoint = "sentry-integration-slack-commands"
method = "post"
def setUp(self) -> None:
super().setUp()
self.slack_id = "UXXXXXXX1"
self.external_id = "new-slack-id"
self.channel_name = "my-channel"
self.channel_id = "my-channel_id... | SlackCommandsTest |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/cloud_storage_compute_log_manager.py | {
"start": 7662,
"end": 11105
} | class ____:
def __init__(self, manager):
self._manager = manager
self._subscriptions = defaultdict(list)
self._shutdown_event = None
self._polling_thread = None
def _log_key(self, subscription: CapturedLogSubscription) -> Sequence[str]:
return subscription.log_key
d... | PollingComputeLogSubscriptionManager |
python | davidhalter__jedi | sith.py | {
"start": 1697,
"end": 2224
} | class ____(object):
_files = None
@staticmethod
def fetch(file_path):
if not os.path.isdir(file_path):
yield file_path
return
for root, dirnames, filenames in os.walk(file_path):
for name in filenames:
if name.endswith('.py'):
... | SourceFinder |
python | pytorch__pytorch | test/inductor/test_torchinductor.py | {
"start": 29228,
"end": 29808
} | class ____:
def __init__(self, reason: str = "") -> None:
self.reason = reason
def __call__(self, fn, *args, **kwargs):
@functools.wraps(fn)
def wrapper(test_self):
if config.cpp_wrapper:
raise unittest.SkipTest(f"cpp wrapper bug to be fixed: {self.reason}")
... | skip_if_cpp_wrapper |
python | tiangolo__fastapi | tests/test_serialize_response_dataclass.py | {
"start": 199,
"end": 4998
} | class ____:
name: str
date: datetime
price: Optional[float] = None
owner_ids: Optional[List[int]] = None
@app.get("/items/valid", response_model=Item)
def get_valid():
return {"name": "valid", "date": datetime(2021, 7, 26), "price": 1.0}
@app.get("/items/object", response_model=Item)
def get_obj... | Item |
python | oauthlib__oauthlib | tests/oauth2/rfc6749/endpoints/test_resource_owner_association.py | {
"start": 370,
"end": 4311
} | class ____(TestCase):
auth_uri = 'http://example.com/path?client_id=abc'
token_uri = 'http://example.com/path'
def set_client(self, request):
request.client = mock.MagicMock()
request.client.client_id = 'mocked'
return True
def set_user(self, client_id, code, client, request):... | ResourceOwnerAssociationTest |
python | python-openxml__python-docx | src/docx/enum/section.py | {
"start": 888,
"end": 1474
} | class ____(BaseXmlEnum):
"""Alias: **WD_ORIENT**
Specifies the page layout orientation.
Example::
from docx.enum.section import WD_ORIENT
section = document.sections[-1] section.orientation = WD_ORIENT.LANDSCAPE
MS API name: `WdOrientation`
MS API URL: http://msdn.microsoft.com/... | WD_ORIENTATION |
python | pytorch__pytorch | test/dynamo/test_utils.py | {
"start": 36792,
"end": 39752
} | class ____(TestCase):
"""
Test for parsing inductor config for logging in CompilationMetrics.
"""
class TestObject:
def __init__(self, a, b):
self.a = a
self.b = b
def test_inductor_config_jsonify(self):
"""
Sanity check if the actual inductor config... | TestInductorConfigParsingForLogging |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/build_systems/sourceforge.py | {
"start": 199,
"end": 919
} | class ____(PackageBase):
sourceforge_mirror_path: Optional[str] = None
base_mirrors = [
"https://prdownloads.sourceforge.net/",
"https://freefr.dl.sourceforge.net/",
"https://netcologne.dl.sourceforge.net/",
"https://pilotfiber.dl.sourceforge.net/",
"https://downloads.sou... | SourceforgePackage |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/config_migrations.py | {
"start": 3684,
"end": 3815
} | class ____(MigrateStringToArray):
migrate_from_key: str = "repository"
migrate_to_key: str = "repositories"
| MigrateRepository |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_ordered_dict.py | {
"start": 38846,
"end": 38989
} | class ____(CPythonOrderedDictTests):
module = c_coll
class OrderedDict(c_coll.OrderedDict):
pass
| CPythonOrderedDictSubclassTests |
python | huggingface__transformers | src/transformers/models/mamba/modeling_mamba.py | {
"start": 6280,
"end": 21609
} | class ____(nn.Module):
"""
Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
∆, B, C are input-dependent (this is a key difference between Mamba and ... | MambaMixer |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_run.py | {
"start": 3111,
"end": 11879
} | class ____:
def test_template_fields(self):
operator = CloudRunExecuteJobOperator(
task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, job_name=JOB_NAME, overrides=OVERRIDES
)
_assert_common_template_fields(operator.template_fields)
assert "job_name" in operator.templ... | TestCloudRunExecuteJobOperator |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_H.py | {
"start": 10119,
"end": 11255
} | class ____(Benchmark):
r"""
Hosaki objective function.
This class defines the Hosaki [1]_ global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{Hosaki}}(x) = \left ( 1 - 8 x_1 + 7 x_1^2 - \frac{7}{3} x_1^3
+ \frac{1}{4} x_1^... | Hosaki |
python | bokeh__bokeh | src/bokeh/document/callbacks.py | {
"start": 2686,
"end": 17040
} | class ____:
''' Manage and provide access to all of the models that belong to a Bokeh
Document.
The set of "all models" means specifically all the models reachable from
references form a Document's roots.
'''
_document: weakref.ReferenceType[Document]
_change_callbacks: dict[Any, Documen... | DocumentCallbackManager |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 289584,
"end": 289945
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("EnterpriseAdministratorInvitation", graphql_name="n... | EnterpriseAdministratorInvitationEdge |
python | django__django | django/core/serializers/xml_serializer.py | {
"start": 17645,
"end": 18171
} | class ____(DefusedXmlException):
"""Entity definition is forbidden."""
def __init__(self, name, value, base, sysid, pubid, notation_name):
super().__init__()
self.name = name
self.value = value
self.base = base
self.sysid = sysid
self.pubid = pubid
self.n... | EntitiesForbidden |
python | numba__numba | numba/core/typed_passes.py | {
"start": 7034,
"end": 7176
} | class ____(BaseTypeInference):
_name = "nopython_type_inference"
@register_pass(mutates_CFG=True, analysis_only=False)
| NopythonTypeInference |
python | kamyu104__LeetCode-Solutions | Python/find-smallest-common-element-in-all-rows.py | {
"start": 491,
"end": 895
} | class ____(object):
def smallestCommonElement(self, mat):
"""
:type mat: List[List[int]]
:rtype: int
"""
# assumed value is unique in each row
counter = collections.Counter()
for row in mat:
for c in row:
counter[c] += 1
... | Solution2 |
python | huggingface__transformers | tests/models/bigbird_pegasus/test_modeling_bigbird_pegasus.py | {
"start": 18951,
"end": 101497
} | class ____(unittest.TestCase):
def _get_dummy_input_ids(self):
# fmt: off
ids = torch.tensor(
[[685, 560, 630, 193, 836, 764, 708, 360, 10, 724, 278, 755, 805, 600, 71, 473, 601, 397, 315, 706, 487, 552, 88, 175, 601, 850, 678, 538, 846, 73, 778, 917, 116, 977, 756, 710, 1023, 848, 432, ... | BigBirdPegasusModelIntegrationTests |
python | Textualize__textual | src/textual/containers.py | {
"start": 4066,
"end": 4317
} | class ____(Widget):
"""An expanding container with vertical layout and no scrollbars."""
DEFAULT_CSS = """
Vertical {
width: 1fr;
height: 1fr;
layout: vertical;
overflow: hidden hidden;
}
"""
| Vertical |
python | pytorch__pytorch | test/test_matmul_cuda.py | {
"start": 42809,
"end": 47158
} | class ____(TestCase):
@dtypes(torch.float16, torch.bfloat16)
def test_mixed_dtypes_linear(self, dtype: torch.dtype, device: str = "cuda"):
version = _get_torch_cuda_version()
if version < (11, 8):
self.skipTest("_mixed_dtypes_linear only compiled for CUDA 11.8+")
def run_tes... | TestMixedDtypesLinearCuda |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.