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 | xlwings__xlwings | xlwings/constants.py | {
"start": 128218,
"end": 128856
} | class ____:
xlGuess = 0 # from enum XlYesNoGuess
xlNo = 2 # from enum XlYesNoGuess
xlYes = 1 # from enum XlYesNoGuess
shape_types = [
"auto_shape",
"callout",
"canvas",
"chart",
"comment",
"content_app",
"diagram",
"embedded_ole_object",
"form_control",
"free_for... | YesNoGuess |
python | tensorflow__tensorflow | tensorflow/python/ops/numpy_ops/tests/np_indexing_test.py | {
"start": 16719,
"end": 32939
} | class ____(jtu.TestCase):
"""Tests for Numpy indexing translation rules."""
@parameterized.named_parameters(jtu.cases_from_list({
"testcase_name": "{}_inshape={}_indexer={}".format(
name, jtu.format_shape_dtype_string( shape, dtype), indexer),
"shape": shape, "dtype": dtype, "rng_factory": r... | IndexingTest |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 1054579,
"end": 1054754
} | class ____(sgqlc.types.Union):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__types__ = (EnterpriseUserAccount, User)
| EnterpriseMember |
python | openai__openai-python | src/openai/types/beta/realtime/conversation_item_create_event_param.py | {
"start": 292,
"end": 1101
} | class ____(TypedDict, total=False):
item: Required[ConversationItemParam]
"""The item to add to the conversation."""
type: Required[Literal["conversation.item.create"]]
"""The event type, must be `conversation.item.create`."""
event_id: str
"""Optional client-generated ID used to identify this... | ConversationItemCreateEventParam |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/scheduler_tests/test_pythonic_resources.py | {
"start": 1136,
"end": 6398
} | class ____(
dg.ConfigurableResource, dg.IAttachDifferentObjectToOpContext
):
a_str: str
def get_object_to_set_on_execution_context(self) -> str:
return self.a_str
@schedule(job_name="the_job", cron_schedule="* * * * *", required_resource_keys={"my_resource"})
def schedule_from_context(context: Sc... | MyResourceAttachDifferentObject |
python | psf__black | src/black/mode.py | {
"start": 7982,
"end": 10769
} | class ____:
target_versions: set[TargetVersion] = field(default_factory=set)
line_length: int = DEFAULT_LINE_LENGTH
string_normalization: bool = True
is_pyi: bool = False
is_ipynb: bool = False
skip_source_first_line: bool = False
magic_trailing_comma: bool = True
python_cell_magics: set... | Mode |
python | mlflow__mlflow | mlflow/store/jobs/sqlalchemy_store.py | {
"start": 596,
"end": 10829
} | class ____(AbstractJobStore):
"""
SQLAlchemy compliant backend store for storing Job metadata.
This store interacts with SQL store using SQLAlchemy abstractions defined
for MLflow Job entities.
"""
def __init__(self, db_uri):
"""
Create a database backed store.
Args:
... | SqlAlchemyJobStore |
python | kamyu104__LeetCode-Solutions | Python/find-minimum-time-to-finish-all-jobs.py | {
"start": 103,
"end": 1114
} | class ____(object):
def minimumTimeRequired(self, jobs, k):
"""
:type jobs: List[int]
:type k: int
:rtype: int
"""
def backtracking(jobs, i, cap, counts):
if i == len(jobs):
return True
for j in xrange(len(counts)):
... | Solution |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py | {
"start": 33793,
"end": 33871
} | class ____(Enum):
None_ = "None"
Default = "Default"
| SchemaNormalization |
python | docker__docker-py | tests/integration/api_container_test.py | {
"start": 38634,
"end": 41613
} | class ____(BaseAPIIntegrationTest):
def test_kill(self):
container = self.client.create_container(TEST_IMG, ['sleep', '9999'])
id = container['Id']
self.client.start(id)
self.tmp_containers.append(id)
self.client.kill(id)
container_info = self.client.inspect_container... | KillTest |
python | ethereum__web3.py | ens/_normalization.py | {
"start": 1355,
"end": 2035
} | class ____:
type: Literal[TokenType.TEXT, TokenType.EMOJI]
_original_text: str
_original_codepoints: list[int]
_normalized_codepoints: list[int] | None = None
restricted: bool = False
def __init__(self, codepoints: list[int]) -> None:
self._original_codepoints = codepoints
self... | Token |
python | tensorflow__tensorflow | third_party/xla/xla/hlo/tools/generate_hlo_test_checks.py | {
"start": 14533,
"end": 21950
} | class ____:
"""Generates FileCheck comments from HLO IR."""
_MODULE_REGEX: re.Pattern[str] = re.compile(
r"^HloModule\b",
)
_CHECK_LINE_REGEX: re.Pattern[str] = re.compile(
r"^// (CHECK(?:-\w+)?): .*?%[\w.\-]+ *(=|$)",
)
_SYMBOL_NAME_REGEX: re.Pattern[str] = re.compile(
r"(?<=%)[\w\-]+(?:... | HloFileCheckLines |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/layout/processors.py | {
"start": 17330,
"end": 18055
} | class ____(BeforeInput):
"""
Display the 'arg' in front of the input.
This was used by the `PromptSession`, but now it uses the
`Window.get_line_prefix` function instead.
"""
def __init__(self) -> None:
super().__init__(self._get_text_fragments)
def _get_text_fragments(self) -> St... | ShowArg |
python | great-expectations__great_expectations | tests/datasource/fluent/_fake_cloud_api.py | {
"start": 1744,
"end": 1925
} | class ____(pydantic.BaseModel, extra="allow"):
id: Optional[str] = None
type: str
name: str
assets: List[dict] = pydantic.Field(default_factory=list)
| _DatasourceSchema |
python | jazzband__django-polymorphic | src/polymorphic/tests/test_orm.py | {
"start": 2101,
"end": 48925
} | class ____(TransactionTestCase):
"""
The test suite
"""
def test_annotate_aggregate_order(self):
# create a blog of type BlogA
# create two blog entries in BlogA
# create some blogs of type BlogB to make the BlogBase table data really polymorphic
blog = BlogA.objects.cre... | PolymorphicTests |
python | PyCQA__pylint | tests/functional/i/inherit_non_class.py | {
"start": 819,
"end": 904
} | class ____(Empty()): # [inherit-non-class]
""" Can't inherit from instance. """
| Bad4 |
python | ray-project__ray | python/ray/data/tests/test_download_expression.py | {
"start": 9658,
"end": 13702
} | class ____:
"""Test error conditions and edge cases for download expressions."""
def test_download_expression_invalid_uri_column(self):
"""Test download expression with non-existent URI column."""
table = pa.Table.from_arrays(
[
pa.array(["local://test.txt"]),
... | TestDownloadExpressionErrors |
python | getsentry__sentry | src/sentry/replays/usecases/query/conditions/selector.py | {
"start": 5717,
"end": 6498
} | class ____(ComputedBase):
"""Click selector composite condition class."""
@staticmethod
def visit_eq(value: list[QueryType]) -> Condition:
if len(value) == 0:
# TODO: raise in the field or return the default condition in the field?
return Condition(Function("identity", param... | ClickSelectorComposite |
python | realpython__materials | python-async-iterators/async_range_v2.py | {
"start": 17,
"end": 322
} | class ____:
def __init__(self, start, end):
self.data = range(start, end)
async def __aiter__(self):
for i in self.data:
await asyncio.sleep(0.5)
yield i
async def main():
async for i in AsyncRange(0, 5):
print(i)
asyncio.run(main())
| AsyncRange |
python | pallets__click | src/click/exceptions.py | {
"start": 2868,
"end": 4484
} | class ____(UsageError):
"""An exception that formats out a standardized error message for a
bad parameter. This is useful when thrown from a callback or type as
Click will attach contextual information to it (for instance, which
parameter it is).
.. versionadded:: 2.0
:param param: the parame... | BadParameter |
python | ray-project__ray | python/ray/autoscaler/_private/resource_demand_scheduler.py | {
"start": 3032,
"end": 41312
} | class ____:
def __init__(
self,
provider: NodeProvider,
node_types: Dict[NodeType, NodeTypeConfigDict],
max_workers: int,
head_node_type: NodeType,
upscaling_speed: float,
) -> None:
self.provider = provider
self.node_types = copy.deepcopy(node_typ... | ResourceDemandScheduler |
python | wandb__wandb | wandb/vendor/pygments/lexers/supercollider.py | {
"start": 457,
"end": 3516
} | class ____(RegexLexer):
"""
For `SuperCollider <http://supercollider.github.io/>`_ source code.
.. versionadded:: 2.1
"""
name = 'SuperCollider'
aliases = ['sc', 'supercollider']
filenames = ['*.sc', '*.scd']
mimetypes = ['application/supercollider', 'text/supercollider', ]
flags ... | SuperColliderLexer |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-of-operations-with-the-same-score-i.py | {
"start": 37,
"end": 378
} | class ____(object):
def maxOperations(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 1
target = nums[0]+nums[1]
for i in xrange(2, len(nums)-1, 2):
if nums[i]+nums[i+1] != target:
break
result += 1
... | Solution |
python | pytorch__pytorch | test/dynamo/test_backends.py | {
"start": 648,
"end": 982
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.layers = torch.nn.Sequential(
torch.nn.Linear(10, 10),
torch.nn.ReLU(),
torch.nn.Linear(10, 10),
torch.nn.Sigmoid(),
)
def forward(self, x):
return se... | Seq |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/gcs.py | {
"start": 1744,
"end": 6212
} | class ____(GoogleCloudBaseOperator):
"""
Creates a new bucket.
Google Cloud Storage uses a flat namespace, so you
can't create a bucket with a name that is already in use.
.. seealso::
For more information, see Bucket Naming Guidelines:
https://cloud.google.com/storage/... | GCSCreateBucketOperator |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/random_color_degeneration.py | {
"start": 290,
"end": 4896
} | class ____(BaseImagePreprocessingLayer):
"""Randomly performs the color degeneration operation on given images.
The sharpness operation first converts an image to gray scale, then back to
color. It then takes a weighted average between original image and the
degenerated image. This makes colors appear ... | RandomColorDegeneration |
python | fastapi__sqlmodel | docs_src/tutorial/delete/tutorial001.py | {
"start": 100,
"end": 2796
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_u... | Hero |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py | {
"start": 30976,
"end": 34658
} | class ____(AwsBaseOperator[DmsHook]):
"""
Stops an AWS DMS Serverless replication.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:DmsStopReplicationOperator`
:param replication_config_arn: ARN of the replication config
... | DmsStopReplicationOperator |
python | joke2k__faker | faker/providers/company/fr_CH/__init__.py | {
"start": 75,
"end": 1312
} | class ____(CompanyProvider):
company_suffixes = ("SA", "Sàrl.")
def ide(self) -> str:
"""
Generates a IDE number (9 digits).
http://www.bfs.admin.ch/bfs/portal/fr/index/themen/00/05/blank/03/02.html
"""
def _checksum(digits: List[int]) -> int:
factors = (5, ... | Provider |
python | kamyu104__LeetCode-Solutions | Python/rearrange-array-elements-by-sign.py | {
"start": 1031,
"end": 1565
} | class ____(object):
def rearrangeArray(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
pos, neg = [], []
for i in reversed(xrange(len(nums))):
if nums[i] > 0:
pos.append(nums[i])
else:
neg.append(num... | Solution3 |
python | django__django | tests/i18n/test_extraction.py | {
"start": 32972,
"end": 34470
} | class ____(ExtractorTests):
def test_ignore_directory(self):
out, po_contents = self._run_makemessages(
ignore_patterns=[
os.path.join("ignore_dir", "*"),
]
)
self.assertIn("ignoring directory ignore_dir", out)
self.assertMsgId("This literal sh... | IgnoredExtractorTests |
python | ZoranPandovski__al-go-rithms | puzzles/CollectRubicCube/Python/solve_rubic_cube.py | {
"start": 10235,
"end": 10629
} | class ____:
def __init__(self):
self.items = []
def empty(self):
return len(self.items) == 0
def pushBack(self, item):
self.items.append(item)
def popFront(self):
if self.empty():
raise Exception("Queue: 'popFront' applied to empty container")
retur... | Queue |
python | dask__dask | dask/dataframe/dask_expr/_cumulative.py | {
"start": 1644,
"end": 1970
} | class ____(Blockwise):
_parameters = ["frame", "skipna"]
_projection_passthrough = True
@staticmethod
def operation(a, skipna=True):
if skipna:
if a.ndim == 1 and (a.empty or a.isna().all()):
return None
a = a.ffill()
return a.tail(n=1).squeeze()
... | TakeLast |
python | pypa__pip | docs/pip_sphinxext.py | {
"start": 6297,
"end": 6571
} | class ____(PipOptions):
required_arguments = 1
def process_options(self) -> None:
cmd_name = self.arguments[0]
self._format_options(
[o() for o in cmdoptions.index_group["options"]],
cmd_name=cmd_name,
)
| PipIndexOptions |
python | wandb__wandb | tools/perf/scripts/bench_run_log.py | {
"start": 11258,
"end": 24301
} | class ____:
"""A class to run the performance test.
Args:
num_steps: The number of logging steps per run.
num_metrics: The number of metrics to log per step.
metric_key_size: The length of metric names.
output_file: The output file to store the performance test results.
... | Experiment |
python | django__django | tests/admin_views/admin.py | {
"start": 7333,
"end": 8074
} | class ____(admin.ModelAdmin):
"""
Tests various hooks for using custom templates and contexts.
"""
change_list_template = "custom_admin/change_list.html"
change_form_template = "custom_admin/change_form.html"
add_form_template = "custom_admin/add_form.html"
object_history_template = "custom... | CustomArticleAdmin |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/assignment2.py | {
"start": 830,
"end": 1056
} | class ____:
def __setitem__(self, i: int, value: object) -> None: ...
def __getitem__(self, i: int) -> int: ...
v5 = Asymmetric()
v5[0] = 3
reveal_type(v5[0], expected_text="int")
v6 = [1, 2, 3]
v6[1:] = []
| Asymmetric |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 571953,
"end": 572711
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for DeploymentReview."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("DeploymentReviewEdge"), graphql_name="edges")
"""A list of edges."""
... | DeploymentReviewConnection |
python | kamyu104__LeetCode-Solutions | Python/number-of-ways-of-cutting-a-pizza.py | {
"start": 55,
"end": 1439
} | class ____(object):
def ways(self, pizza, k):
"""
:type pizza: List[str]
:type k: int
:rtype: int
"""
MOD = 10**9+7
prefix = [[0]*len(pizza[0]) for _ in xrange(len(pizza))]
for j in reversed(xrange(len(pizza[0]))):
accu = 0
for ... | Solution |
python | doocs__leetcode | solution/0700-0799/0708.Insert into a Sorted Circular Linked List/Solution.py | {
"start": 140,
"end": 693
} | class ____:
def insert(self, head: 'Optional[Node]', insertVal: int) -> 'Node':
node = Node(insertVal)
if head is None:
node.next = node
return node
prev, curr = head, head.next
while curr != head:
if prev.val <= insertVal <= curr.val or (
... | Solution |
python | docker__docker-py | docker/models/secrets.py | {
"start": 537,
"end": 1845
} | class ____(Collection):
"""Secrets on the Docker server."""
model = Secret
def create(self, **kwargs):
obj = self.client.api.create_secret(**kwargs)
obj.setdefault("Spec", {})["Name"] = kwargs.get("name")
return self.prepare_model(obj)
create.__doc__ = APIClient.create_secret.__... | SecretCollection |
python | doocs__leetcode | solution/1500-1599/1564.Put Boxes Into the Warehouse I/Solution.py | {
"start": 0,
"end": 482
} | class ____:
def maxBoxesInWarehouse(self, boxes: List[int], warehouse: List[int]) -> int:
n = len(warehouse)
left = [warehouse[0]] * n
for i in range(1, n):
left[i] = min(left[i - 1], warehouse[i])
boxes.sort()
i, j = 0, n - 1
while i < len(boxes):
... | Solution |
python | pytorch__pytorch | test/autograd/test_functional.py | {
"start": 2833,
"end": 60627
} | class ____(TestCase):
def _assert_same_struct(self, res, base):
# base and res should be Tensors or tuple of Tensors with the same size
if isinstance(base, torch.Tensor):
self.assertTrue(isinstance(res, torch.Tensor))
self.assertEqual(base.size(), res.size())
elif isi... | TestAutogradFunctional |
python | huggingface__transformers | tests/models/clipseg/test_modeling_clipseg.py | {
"start": 1569,
"end": 4535
} | class ____:
def __init__(
self,
parent,
batch_size=12,
image_size=30,
patch_size=2,
num_channels=3,
is_training=True,
hidden_size=32,
num_hidden_layers=2,
num_attention_heads=4,
intermediate_size=37,
dropout=0.1,
... | CLIPSegVisionModelTester |
python | huggingface__transformers | src/transformers/models/patchtsmixer/modeling_patchtsmixer.py | {
"start": 20694,
"end": 23521
} | class ____(nn.Module):
"""Linear head for Classification and Regression.
Args:
config (`PatchTSMixerConfig`):
Configuration.
"""
def __init__(self, config: PatchTSMixerConfig, distribution_output=None):
super().__init__()
self.head_aggregation = config.head_aggrega... | PatchTSMixerLinearHead |
python | doocs__leetcode | solution/0000-0099/0031.Next Permutation/Solution.py | {
"start": 0,
"end": 358
} | class ____:
def nextPermutation(self, nums: List[int]) -> None:
n = len(nums)
i = next((i for i in range(n - 2, -1, -1) if nums[i] < nums[i + 1]), -1)
if ~i:
j = next((j for j in range(n - 1, i, -1) if nums[j] > nums[i]))
nums[i], nums[j] = nums[j], nums[i]
nu... | Solution |
python | PrefectHQ__prefect | tests/test_transactions.py | {
"start": 32875,
"end": 38614
} | class ____:
class TestTransaction:
def test_get_and_set_data(self):
with transaction(key="test") as txn:
txn.set("x", 42)
assert txn.get("x") == 42
def test_get_and_set_data_in_nested_context(self):
with transaction(key="test") as top:
... | TestGetAndSetData |
python | huggingface__transformers | src/transformers/models/whisper/english_normalizer.py | {
"start": 19372,
"end": 22815
} | class ____:
def __init__(self, english_spelling_mapping):
self.ignore_patterns = r"\b(hmm|mm|mhm|mmm|uh|um)\b"
self.replacers = {
# common contractions
r"\bwon't\b": "will not",
r"\bcan't\b": "can not",
r"\blet's\b": "let us",
r"\bain't\b":... | EnglishTextNormalizer |
python | kamyu104__LeetCode-Solutions | Python/find-the-duplicate-number.py | {
"start": 802,
"end": 1359
} | class ____(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
left, right = 1, len(nums) - 1
while left <= right:
mid = left + (right - left) / 2
# Get count of num <= mid.
count = 0
for n... | Solution2 |
python | apache__airflow | airflow-core/tests/unit/core/test_stats.py | {
"start": 1690,
"end": 6433
} | class ____:
def setup_method(self):
self.statsd_client = Mock(spec=statsd.StatsClient)
self.stats = SafeStatsdLogger(self.statsd_client)
def test_increment_counter_with_valid_name(self):
self.stats.incr("test_stats_run")
self.statsd_client.incr.assert_called_once_with("test_stat... | TestStats |
python | numpy__numpy | numpy/random/tests/test_random.py | {
"start": 1879,
"end": 2403
} | class ____:
def test_n_zero(self):
# Tests the corner case of n == 0 for the binomial distribution.
# binomial(0, p) should be zero for any p in [0, 1].
# This test addresses issue #3480.
zeros = np.zeros(2, dtype='int')
for p in [0, .5, 1]:
assert_(random.binomia... | TestBinomial |
python | google__jax | jax/experimental/mosaic/gpu/layout_inference.py | {
"start": 2833,
"end": 4891
} | class ____:
"""A unique identifier for a variable.
This class describes a particular role of a Value, either as a result of an
operation, an operand of an operation, or a block argument.
"""
# A MLIR operation. If the type is `ARGUMENT`, this is the owner of the block
# and region_index is the region that ... | ValueSite |
python | huggingface__transformers | src/transformers/models/kosmos2/modeling_kosmos2.py | {
"start": 24731,
"end": 29933
} | class ____(nn.Module):
"""This module produces sinusoidal positional embeddings of any length."""
# Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100SinusoidalPositionalEmbedding.__init__
def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None):
su... | Kosmos2TextSinusoidalPositionalEmbedding |
python | dagster-io__dagster | python_modules/libraries/dagster-airflow/dagster_airflow/hooks/dagster_hook.py | {
"start": 728,
"end": 9290
} | class ____(BaseHook):
conn_name_attr = "dagster_conn_id"
default_conn_name = "dagster_default"
conn_type = "dagster"
hook_name = "Dagster"
@staticmethod
def get_ui_field_behaviour() -> Mapping[str, Any]:
"""Returns custom field behaviour."""
return {
"hidden_fields":... | DagsterHook |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_itertools.py | {
"start": 101106,
"end": 101444
} | class ____:
'Test propagation of exceptions after two iterations'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
def __next__(self):
if self.i == 2:
raise ZeroDivisionError
v = self.seqn[self.i]
self.i += ... | E2 |
python | pytorch__pytorch | torch/testing/_internal/common_utils.py | {
"start": 13987,
"end": 16693
} | class ____:
def __init__(
self,
child_iter,
input_type_desc,
item_callback=None,
track_callback=None,
set_seed=True,
restrict_to_index=None
):
self.child_iter = enumerate(child_iter)
# Input type describes the things we're tracking (e.g. "s... | TrackedInputIter |
python | ray-project__ray | python/ray/serve/tests/test_config_files/test_dag/dir/subdir/a/add_and_sub.py | {
"start": 558,
"end": 889
} | class ____:
# Requires the test_module repo as a py_module:
# https://github.com/ray-project/test_module
def subtract(self, input: int) -> int:
from test_module.test import one
return input - one() # Returns input - 2
@serve.deployment(
ray_actor_options={
"num_cpus": 0.1,
... | Subtract |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/generator4.py | {
"start": 755,
"end": 1401
} | class ____:
def __init__(self):
self.x = 1
def __iter__(self) -> Iterator[int]:
yield self.x
async def func1() -> SomeIterable:
return SomeIterable()
def func2() -> Iterator[int]:
yield 2
def g5() -> None:
val = (y for y in func2())
reveal_type(val, expected_text="Generato... | SomeIterable |
python | pyinstaller__pyinstaller | PyInstaller/fake-modules/_pyi_rth_utils/_win32.py | {
"start": 1187,
"end": 1488
} | class ____(ctypes.Structure):
_fields_ = [
("TokenAppContainer", PSID),
]
PTOKEN_APPCONTAINER_INFORMATION = ctypes.POINTER(TOKEN_APPCONTAINER_INFORMATION)
# SECURITY_ATTRIBUTES structure for CreateDirectoryW
PSECURITY_DESCRIPTOR = ctypes.wintypes.LPVOID
| TOKEN_APPCONTAINER_INFORMATION |
python | scrapy__scrapy | tests/test_http2_client_protocol.py | {
"start": 1796,
"end": 1926
} | class ____(Spider):
name = "dummy"
start_urls: list = []
def parse(self, response):
print(response)
| DummySpider |
python | viewflow__viewflow | tests/fsm/test_fsm__advanced.py | {
"start": 250,
"end": 1328
} | class ____(object):
stage = State(ReviewState, default=ReviewState.NEW)
def __init__(self, text):
self.text = text
@stage.transition(source=ReviewState.NEW)
def notify(self):
pass
@stage.transition(
source={ReviewState.NEW, ReviewState.HIDDEN}, target=ReviewState.PUBLISHED... | Publication |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 153540,
"end": 156955
} | class ____(
AssertsCompiledSQL, _RangeTests, fixtures.TestBase
):
__dialect__ = "postgresql"
@property
def _col_str_arr(self):
return self._col_str
# operator tests
@classmethod
def setup_test_class(cls):
table = Table(
"data_table",
MetaData(),
... | _RangeTypeCompilation |
python | falconry__falcon | examples/asgilook/asgilook/config.py | {
"start": 61,
"end": 732
} | class ____:
DEFAULT_CONFIG_PATH = '/tmp/asgilook'
DEFAULT_MIN_THUMB_SIZE = 64
DEFAULT_REDIS_FROM_URL = redis.asyncio.from_url
DEFAULT_REDIS_HOST = 'redis://localhost'
DEFAULT_UUID_GENERATOR = uuid.uuid4
def __init__(self):
self.storage_path = pathlib.Path(
os.environ.get('AS... | Config |
python | huggingface__transformers | src/transformers/models/gemma2/modular_gemma2.py | {
"start": 25131,
"end": 25389
} | class ____(GemmaForTokenClassification):
pass
__all__ = [
"Gemma2Config",
"Gemma2ForCausalLM",
"Gemma2Model",
"Gemma2PreTrainedModel",
"Gemma2ForSequenceClassification",
"Gemma2ForTokenClassification",
]
| Gemma2ForTokenClassification |
python | readthedocs__readthedocs.org | readthedocs/doc_builder/environments.py | {
"start": 22971,
"end": 36667
} | class ____(BaseBuildEnvironment):
"""
Docker build environment, uses docker to contain builds.
If :py:data:`settings.DOCKER_ENABLE` is true, build documentation inside a
docker container, instead of the host system, using this build environment
class. The build command creates a docker container f... | DockerBuildEnvironment |
python | Lightning-AI__lightning | src/lightning/fabric/plugins/precision/double.py | {
"start": 997,
"end": 1963
} | class ____(Precision):
"""Plugin for training with double (``torch.float64``) precision."""
precision: Literal["64-true"] = "64-true"
@override
def convert_module(self, module: Module) -> Module:
return module.double()
@override
def tensor_init_context(self) -> AbstractContextManager:... | DoublePrecision |
python | MongoEngine__mongoengine | tests/fields/test_geo_fields.py | {
"start": 85,
"end": 16440
} | class ____(MongoDBTestCase):
def _test_for_expected_error(self, Cls, loc, expected):
try:
Cls(loc=loc).validate()
self.fail(f"Should not validate the location {loc}")
except ValidationError as e:
assert expected == e.to_dict()["loc"]
def test_geopoint_validat... | TestGeoField |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/transformer.py | {
"start": 4193,
"end": 5163
} | class ____(object):
"""Syntactic sugar for accessing an instance of a StateStack context manager.
This structure offers syntactic sugar over a dict of stacks of objects
of known type. These structures are useful to keep state during AST walks.
Multiple different scopes can be tracked in parallel. For example:
... | _State |
python | getsentry__sentry | tests/sentry/workflow_engine/processors/test_detector.py | {
"start": 1854,
"end": 2760
} | class ____(BaseDetectorHandlerTest):
def setUp(self) -> None:
super().setUp()
self.detector = self.create_detector(
type=self.handler_type.slug,
workflow_condition_group=self.create_data_condition_group(),
)
cache.clear()
def test_no_caching(self) -> None... | TestInit |
python | gevent__gevent | src/greentest/3.12/test_ssl.py | {
"start": 105011,
"end": 114714
} | class ____(threading.Thread):
# this one's based on asyncore.dispatcher
class EchoServer (asyncore.dispatcher):
class ConnectionHandler(asyncore.dispatcher_with_send):
def __init__(self, conn, certfile):
self.socket = test_wrap_socket(conn, server_side=True,
... | AsyncoreEchoServer |
python | apache__airflow | airflow-core/src/airflow/task/trigger_rule.py | {
"start": 847,
"end": 1749
} | class ____(str, Enum):
"""Class with task's trigger rules."""
ALL_SUCCESS = "all_success"
ALL_FAILED = "all_failed"
ALL_DONE = "all_done"
ALL_DONE_MIN_ONE_SUCCESS = "all_done_min_one_success"
ALL_DONE_SETUP_SUCCESS = "all_done_setup_success"
ONE_SUCCESS = "one_success"
ONE_FAILED = "one... | TriggerRule |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_legacy_slugs.py | {
"start": 3080,
"end": 3743
} | class ____(util.MdCase):
"""Test encoded GitHub Flavored Markdown style slugs."""
extension = ['markdown.extensions.toc']
extension_configs = {
'markdown.extensions.toc': {
"slugify": slugs.gfm_encoded
}
}
def test_slug(self):
"""Test the slug output."""
... | TestGFMEncoded |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 472478,
"end": 472966
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of ApproveVerifiableDomain"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "domain")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the... | ApproveVerifiableDomainPayload |
python | vyperlang__vyper | vyper/utils.py | {
"start": 357,
"end": 3414
} | class ____(Generic[_T]):
"""
a minimal "ordered set" class. this is needed in some places
because, while dict guarantees you can recover insertion order
vanilla sets do not.
no attempt is made to fully implement the set API, will add
functionality as needed.
"""
def __init__(self, itera... | OrderedSet |
python | gevent__gevent | src/gevent/_config.py | {
"start": 8554,
"end": 8738
} | class ____(object):
def validate(self, value):
if value is not None and value <= 0:
raise ValueError("Must be positive")
return value
| _PositiveValueMixin |
python | kamyu104__LeetCode-Solutions | Python/make-array-non-decreasing.py | {
"start": 38,
"end": 327
} | class ____(object):
def maximumPossibleSize(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = prev = 0
for x in nums:
if prev <= x:
prev = x
result += 1
return result
| Solution |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 209060,
"end": 209267
} | class ____(AnyMark):
"""CompositeMark schema wrapper."""
_schema = {"$ref": "#/definitions/CompositeMark"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| CompositeMark |
python | great-expectations__great_expectations | tests/datasource/fluent/test_sql_datasources.py | {
"start": 14115,
"end": 18569
} | class ____:
@pytest.mark.parametrize("schema_name", ["my_schema", "MY_SCHEMA", "My_Schema"])
def test_unquoted_schema_names_are_added_as_lowercase(
self,
sql_datasource_table_asset_test_connection_noop: SQLDatasource,
schema_name: str,
):
my_datasource: SQLDatasource = sql_da... | TestTableAsset |
python | getsentry__sentry | src/sentry/integrations/models/integration.py | {
"start": 1310,
"end": 6407
} | class ____(DefaultFieldsModelExisting):
"""
An integration tied to a particular instance of a third-party provider (a single Slack
workspace, a single GH org, etc.), which can be shared by multiple Sentry orgs.
"""
__relocation_scope__ = RelocationScope.Global
provider = models.CharField(max_l... | Integration |
python | run-llama__llama_index | llama-index-core/llama_index/core/query_engine/router_query_engine.py | {
"start": 12408,
"end": 15552
} | class ____(BaseQueryEngine):
"""
Tool Retriever router query engine.
Selects a set of candidate query engines to execute a query.
Args:
retriever (ObjectRetriever): A retriever that retrieves a set of
query engine tools.
summarizer (Optional[TreeSummarize]): Tree summarizer... | ToolRetrieverRouterQueryEngine |
python | getsentry__sentry | tests/sentry/utils/test_function_cache.py | {
"start": 331,
"end": 736
} | class ____(models.Model):
__relocation_scope__ = RelocationScope.Excluded
some_field = models.TextField()
class Meta:
app_label = "fixtures"
def count_func(text_search: str):
return CacheModel.objects.filter(some_field=text_search).count()
def simple_func(val: str):
return val + "_yay"
... | CacheModel |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 89797,
"end": 90111
} | class ____:
xlColumnField = 2 # from enum XlPivotFieldOrientation
xlDataField = 4 # from enum XlPivotFieldOrientation
xlHidden = 0 # from enum XlPivotFieldOrientation
xlPageField = 3 # from enum XlPivotFieldOrientation
xlRowField = 1 # from enum XlPivotFieldOrientation
| PivotFieldOrientation |
python | pytorch__pytorch | test/inductor/test_perf.py | {
"start": 9796,
"end": 18252
} | class ____(TestCase):
"""
Tests that things can be fused into a single kernel
"""
def test_horizontal_reduction_pointwise(self):
def f(a):
b = a.sum(dim=1)
c = a.cos()
return b, c
inp = (T(10, 10),)
self.assertExpectedInline(count_numel(f, *i... | FusionTests |
python | donnemartin__interactive-coding-challenges | graphs_trees/graph_build_order/test_build_order.py | {
"start": 18,
"end": 1633
} | class ____(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestBuildOrder, self).__init__()
self.dependencies = [
Dependency('d', 'g'),
Dependency('f', 'c'),
Dependency('f', 'b'),
Dependency('f', 'a'),
Dependency('c', 'a'),
... | TestBuildOrder |
python | openai__openai-python | src/openai/types/responses/response_code_interpreter_tool_call.py | {
"start": 519,
"end": 807
} | class ____(BaseModel):
type: Literal["image"]
"""The type of the output. Always `image`."""
url: str
"""The URL of the image output from the code interpreter."""
Output: TypeAlias = Annotated[Union[OutputLogs, OutputImage], PropertyInfo(discriminator="type")]
| OutputImage |
python | huggingface__transformers | tests/models/zoedepth/test_image_processing_zoedepth.py | {
"start": 1223,
"end": 3847
} | class ____:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
image_size=18,
min_resolution=30,
max_resolution=400,
do_resize=True,
size=None,
ensure_multiple_of=32,
keep_aspect_ratio=False,
do_normalize=True,
... | ZoeDepthImageProcessingTester |
python | getsentry__sentry | src/sentry/seer/endpoints/trace_explorer_ai_translate_agentic.py | {
"start": 2928,
"end": 5107
} | class ____(OrganizationEndpoint):
"""
Endpoint to call Seer's agentic search API for translating natural language queries.
"""
publish_status = {
"POST": ApiPublishStatus.EXPERIMENTAL,
}
owner = ApiOwner.ML_AI
permission_classes = (OrganizationTraceExplorerAIPermission,)
def p... | SearchAgentTranslateEndpoint |
python | apache__airflow | task-sdk/src/airflow/sdk/bases/operator.py | {
"start": 4251,
"end": 6984
} | class ____(str, Enum):
"""
Reasons for trigger failures.
Internal use only.
:meta private:
"""
TRIGGER_TIMEOUT = "Trigger timeout"
TRIGGER_FAILURE = "Trigger failure"
TRIGGER_FAIL_REPR = "__fail__"
"""String value to represent trigger failure.
Internal use only.
:meta private:
"""
d... | TriggerFailureReason |
python | kamyu104__LeetCode-Solutions | Python/average-salary-excluding-the-minimum-and-maximum-salary.py | {
"start": 49,
"end": 429
} | class ____(object):
def average(self, salary):
"""
:type salary: List[int]
:rtype: float
"""
total, mi, ma = 0, float("inf"), float("-inf")
for s in salary:
total += s
mi, ma = min(mi, s), max(ma, s)
return 1.0*(total-mi-ma)/(len(salary... | Solution |
python | facelessuser__soupsieve | tests/test_level4/test_indeterminate.py | {
"start": 58,
"end": 2407
} | class ____(util.TestCase):
"""Test indeterminate selectors."""
def test_indeterminate(self):
"""Test indeterminate."""
markup = """
<input type="radio" name="" id="radio-no-name1">
<label>No name 1</label>
<input type="radio" name="" id="radio-no-name2" checked>
... | TestIndeterminate |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 134374,
"end": 134642
} | class ____(Layout):
"""A Tensor layout we cannot change"""
def make_indexer(self) -> Callable[[Sequence[Expr]], Expr]:
"""A closure containing math to read a given element"""
return _fixed_indexer(self.size, self.stride, self.offset)
| FixedLayout |
python | spyder-ide__spyder | external-deps/spyder-remote-services/spyder_remote_services/services/files/handlers.py | {
"start": 6611,
"end": 6910
} | class ____(BaseFSHandler):
@web.authenticated
@authorized
def delete(self):
result = self.fs_rmdir(
self.get_path_argument("path"),
non_empty=(self.get_argument("non_empty", "false").lower() == "true"),
)
self.write_json(result)
| RmdirHandler |
python | Netflix__metaflow | metaflow/plugins/cards/card_modules/test_cards.py | {
"start": 5363,
"end": 5876
} | class ____(MetaflowCard):
"""Card that renders a tiny PNG using ``TaskToDict.parse_image``."""
type = "test_image_card"
def render(self, task):
from .convert_to_native_type import TaskToDict
import base64
png_bytes = base64.b64decode(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABC... | TestImageCard |
python | apache__airflow | airflow-core/src/airflow/cli/commands/task_command.py | {
"start": 8915,
"end": 11217
} | class ____:
"""Marker for listener hooks, to properly detect from which component they are called."""
@cli_utils.action_cli(check_db=False)
@providers_configuration_loaded
def task_failed_deps(args) -> None:
"""
Get task instance dependencies that were not met.
Returns the unmet dependencies for a ta... | TaskCommandMarker |
python | numpy__numpy | numpy/_array_api_info.py | {
"start": 429,
"end": 10354
} | class ____:
"""
Get the array API inspection namespace for NumPy.
The array API inspection namespace defines the following functions:
- capabilities()
- default_device()
- default_dtypes()
- dtypes()
- devices()
See
https://data-apis.org/array-api/latest/API_specification/insp... | __array_namespace_info__ |
python | milvus-io__pymilvus | pymilvus/client/types.py | {
"start": 23869,
"end": 24467
} | class ____:
"""
RoleInfo groups:
- UserItem: <role_name:admin>, <users:('root',)>
"""
def __init__(self, results: List[milvus_types.RoleResult]) -> None:
groups = []
for result in results:
if isinstance(result, milvus_types.RoleResult):
groups.append(Role... | RoleInfo |
python | spyder-ide__spyder | spyder/plugins/completion/providers/snippets/widgets/snippetsconfig.py | {
"start": 16804,
"end": 19160
} | class ____(QAbstractTableModel):
TRIGGER = 0
DESCRIPTION = 1
def __init__(self, parent):
QAbstractTableModel.__init__(self)
self.parent = parent
self.snippets = []
self.delete_queue = []
self.snippet_map = {}
self.rich_text = []
self.normal_text = []... | SnippetsModel |
python | readthedocs__readthedocs.org | readthedocs/integrations/models.py | {
"start": 11511,
"end": 11859
} | class ____(Integration):
integration_type_id = Integration.GITHUB_WEBHOOK
has_sync = True
class Meta:
proxy = True
@property
def can_sync(self):
try:
return all((k in self.provider_data) for k in ["id", "url"])
except (ValueError, TypeError):
return ... | GitHubWebhook |
python | scikit-image__scikit-image | benchmarks/benchmark_filters.py | {
"start": 2002,
"end": 2668
} | class ____:
"""Benchmark for transform routines in scikit-image."""
def setup(self):
self.image = np.zeros((2000, 2000), dtype=np.uint8)
self.image3D = np.zeros((30, 300, 300), dtype=np.uint8)
idx = np.arange(500, 700)
idx3D = np.arange(10, 200)
self.image[idx[::-1], i... | ThresholdSauvolaSuite |
python | h5py__h5py | h5py/tests/test_group.py | {
"start": 26371,
"end": 26638
} | class ____:
""" Class for exercise 'visit' and 'visititems' methods """
def __init__(self):
self._names = []
def __call__(self, name, obj=None):
self._names.append(name)
@property
def names(self):
return self._names
| Visitor |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.