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 | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 467111,
"end": 470791
} | class ____(Response):
"""
Response of tasks.publish_many endpoint.
:param succeeded:
:type succeeded: Sequence[dict]
:param failed:
:type failed: Sequence[dict]
"""
_service = "tasks"
_action = "publish_many"
_version = "2.23"
_schema = {
"definitions": {},
... | PublishManyResponse |
python | astropy__astropy | astropy/utils/data_info.py | {
"start": 6371,
"end": 8091
} | class ____(type):
def __new__(cls, name, bases, dct):
# Ensure that we do not gain a __dict__, which would mean
# arbitrary attributes could be set.
dct.setdefault("__slots__", [])
return super().__new__(cls, name, bases, dct)
def __init__(cls, name, bases, dct):
super()... | DataInfoMeta |
python | getsentry__sentry | tests/sentry/incidents/test_logic.py | {
"start": 95166,
"end": 96645
} | class ____(TestCase):
@cached_property
def alert_rule(self):
return self.create_alert_rule()
def test(self) -> None:
label = "hello"
alert_threshold = 1000
trigger = create_alert_rule_trigger(self.alert_rule, label, alert_threshold)
assert trigger.label == label
... | CreateAlertRuleTriggerTest |
python | chroma-core__chroma | chromadb/test/test_config.py | {
"start": 308,
"end": 646
} | class ____(Component):
def __init__(self, system: System):
data.inits += "A"
super().__init__(system)
self.require(ComponentB)
self.require(ComponentC)
@overrides
def start(self) -> None:
data.starts += "A"
@overrides
def stop(self) -> None:
data.sto... | ComponentA |
python | django__django | django/db/models/fields/__init__.py | {
"start": 87900,
"end": 92009
} | class ____(DateTimeCheckMixin, Field):
empty_strings_allowed = False
default_error_messages = {
"invalid": _(
"“%(value)s” value has an invalid format. It must be in "
"HH:MM[:ss[.uuuuuu]] format."
),
"invalid_time": _(
"“%(value)s” value has the corre... | TimeField |
python | pypa__warehouse | warehouse/email/ses/models.py | {
"start": 7031,
"end": 7766
} | class ____(db.Model):
__tablename__ = "ses_events"
created: Mapped[datetime_now]
email_id: Mapped[UUID] = mapped_column(
PG_UUID(as_uuid=True),
ForeignKey(
"ses_emails.id", deferrable=True, initially="DEFERRED", ondelete="CASCADE"
),
index=True,
)
email:... | Event |
python | falconry__falcon | falcon/errors.py | {
"start": 39965,
"end": 40300
} | class ____(HTTPContentTooLarge):
"""Compatibility alias of :class:`falcon.HTTPContentTooLarge`."""
@deprecation.deprecated(
'HTTPPayloadTooLarge is deprecated; use HTTPContentTooLarge instead.'
)
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
| HTTPPayloadTooLarge |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 46535,
"end": 47107
} | class ____(PrefectFilterBaseModel):
"""Filter by `Log.name`."""
any_: Optional[list[str]] = Field(
default=None,
description="A list of log names to include",
examples=[["prefect.logger.flow_runs", "prefect.logger.task_runs"]],
)
def _get_filter_list(
self, db: "Prefect... | LogFilterName |
python | doocs__leetcode | solution/2300-2399/2305.Fair Distribution of Cookies/Solution.py | {
"start": 0,
"end": 571
} | class ____:
def distributeCookies(self, cookies: List[int], k: int) -> int:
def dfs(i):
if i >= len(cookies):
nonlocal ans
ans = max(cnt)
return
for j in range(k):
if cnt[j] + cookies[i] >= ans or (j and cnt[j] == cnt[j ... | Solution |
python | doocs__leetcode | solution/0100-0199/0149.Max Points on a Line/Solution.py | {
"start": 0,
"end": 530
} | class ____:
def maxPoints(self, points: List[List[int]]) -> int:
n = len(points)
ans = 1
for i in range(n):
x1, y1 = points[i]
for j in range(i + 1, n):
x2, y2 = points[j]
cnt = 2
for k in range(j + 1, n):
... | Solution |
python | pypa__setuptools | setuptools/build_meta.py | {
"start": 5125,
"end": 9899
} | class ____:
"""Translate ``config_settings`` into distutils-style command arguments.
Only a limited number of options is currently supported.
"""
# See pypa/setuptools#1928 pypa/setuptools#2491
def _get_config(self, key: str, config_settings: _ConfigSettings) -> list[str]:
"""
Get ... | _ConfigSettingsTranslator |
python | wandb__wandb | wandb/errors/warnings.py | {
"start": 0,
"end": 57
} | class ____(Warning):
"""Base W&B Warning."""
| WandbWarning |
python | sympy__sympy | sympy/stats/drv.py | {
"start": 9520,
"end": 9675
} | class ____(ProductDomain, DiscreteDomain):
def as_boolean(self):
return And(*[domain.as_boolean for domain in self.domains])
| ProductDiscreteDomain |
python | getsentry__sentry | tests/sentry/releases/endpoints/test_organization_release_details.py | {
"start": 45139,
"end": 49701
} | class ____(APITestCase):
def test_simple(self) -> None:
user = self.create_user(is_staff=False, is_superuser=False)
org = self.organization
org.flags.allow_joinleave = False
org.save()
team = self.create_team(organization=org)
project = self.create_project(teams=[te... | ReleaseDeleteTest |
python | encode__django-rest-framework | tests/test_serializer.py | {
"start": 28856,
"end": 30172
} | class ____(TestCase):
def test_warning_many_to_many(self):
"""Tests that using a PrimaryKeyRelatedField for a ManyToMany field breaks with default=None."""
class ManyToManySourceSerializer(serializers.ModelSerializer):
targets = serializers.PrimaryKeyRelatedField(
many=Tr... | TestWarningManyToMany |
python | streamlit__streamlit | lib/tests/streamlit/runtime/scriptrunner/code_exec_test.py | {
"start": 1357,
"end": 4377
} | class ____(unittest.TestCase):
def setUp(self) -> None:
self.ctx = ScriptRunContext(
session_id="test session id",
_enqueue=ForwardMsgQueue().enqueue,
query_string="",
session_state=SafeSessionState(SessionState(), lambda: None),
uploaded_file_mgr=... | TestWrapInTryAndExec |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/bigtable.py | {
"start": 20700,
"end": 24051
} | class ____(GoogleCloudBaseOperator, BigtableValidationMixin):
"""
Deletes the Cloud Bigtable table.
For more details about deleting table have a look at the reference:
https://googleapis.github.io/google-cloud-python/latest/bigtable/table.html#google.cloud.bigtable.table.Table.delete
.. seealso::
... | BigtableDeleteTableOperator |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/data_asset/path/spark/orc_asset.py | {
"start": 1393,
"end": 1982
} | class ____(DirectoryDataAsset, ORCAssetBase):
type: Literal["directory_orc"] = "directory_orc"
@classmethod
@override
def _get_reader_method(cls) -> str:
return "orc"
@override
def _get_reader_options_include(self) -> set[str]:
"""These options are available as of spark v3.4.0
... | DirectoryORCAsset |
python | huggingface__transformers | src/transformers/pipelines/text_generation.py | {
"start": 393,
"end": 541
} | class ____(enum.Enum):
TENSORS = 0
NEW_TEXT = 1
FULL_TEXT = 2
@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
| ReturnType |
python | Netflix__metaflow | metaflow/plugins/env_escape/override_decorators.py | {
"start": 585,
"end": 627
} | class ____(Override):
pass
| LocalOverride |
python | gevent__gevent | src/greentest/3.10/test_signal.py | {
"start": 20677,
"end": 24078
} | class ____(unittest.TestCase):
def readpipe_interrupted(self, interrupt):
"""Perform a read during which a signal will arrive. Return True if the
read is interrupted by the signal and raises an exception. Return False
if it returns normally.
"""
# use a subprocess to have ... | SiginterruptTest |
python | pytorch__pytorch | test/nn/test_lazy_modules.py | {
"start": 394,
"end": 479
} | class ____(torch.nn.modules.lazy.LazyModuleMixin, torch.nn.Module):
pass
| LazyModule |
python | pytorch__pytorch | torch/distributed/checkpoint/_consolidate_hf_safetensors.py | {
"start": 612,
"end": 1178
} | class ____:
"""
Dataclass to store information about a tensor (identified by its fully qualified name).
Attributes:
offset_in_file: Byte offset where this tensor's data begins in the output file
shape_in_file: Shape of the tensor in the output file
dtype_size: Size of the tensor's d... | _FqnData |
python | allegroai__clearml | clearml/utilities/version.py | {
"start": 1603,
"end": 11303
} | class ____(_BaseVersion):
VERSION_PATTERN = r"""
v?
(?:
(?:(?P<epoch>[0-9]+)!)? # epoch
(?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
(?P<pre> # pre-release
[-... | Version |
python | bokeh__bokeh | src/bokeh/core/serialization.py | {
"start": 2379,
"end": 2413
} | class ____(TypedDict):
id: ID
| Ref |
python | coleifer__peewee | tests/regressions.py | {
"start": 38699,
"end": 39267
} | class ____(ModelTestCase):
requires = [BoolModel]
def test_boolean_compare(self):
b1 = BoolModel.create(key='b1', active=True)
b2 = BoolModel.create(key='b2', active=False)
expr2key = (
((BoolModel.active == True), 'b1'),
((BoolModel.active == False), 'b2'),
... | TestBooleanCompare |
python | python__mypy | mypy/nodes.py | {
"start": 79544,
"end": 79916
} | class ____(Expression):
"""TypeForm(type) expression."""
__slots__ = ("type",)
__match_args__ = ("type",)
type: mypy.types.Type
def __init__(self, typ: mypy.types.Type) -> None:
super().__init__()
self.type = typ
def accept(self, visitor: ExpressionVisitor[T]) -> T:
... | TypeFormExpr |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 20952,
"end": 21427
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
error_code: Optional[str] = Field(
None, description="Error code", examples=["INTERNAL_ERROR"]
)
message: Optional[str] = Field(
None,
d... | Error |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/equalization_test.py | {
"start": 199,
"end": 4962
} | class ____(testing.TestCase):
def assertAllInRange(self, array, min_val, max_val):
self.assertTrue(np.all(array >= min_val))
self.assertTrue(np.all(array <= max_val))
@pytest.mark.requires_trainable_backend
def test_layer(self):
self.run_layer_test(
layers.Equalization,
... | EqualizationTest |
python | getsentry__sentry | src/sentry/search/events/datasets/spans_indexed.py | {
"start": 22504,
"end": 49635
} | class ____(SpansIndexedDatasetConfig):
"""Eventually should just write the eap dataset from scratch, but inheriting for now to move fast"""
sampling_weight = Column("sampling_weight")
def __init__(self, builder: BaseQueryBuilder):
super().__init__(builder)
self._cached_count_and_weighted: ... | SpansEAPDatasetConfig |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_hyperlink49.py | {
"start": 315,
"end": 975
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("hyperlink49.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workb... | TestCompareXLSXFiles |
python | tensorflow__tensorflow | tensorflow/python/feature_column/feature_column_v2.py | {
"start": 102744,
"end": 114905
} | class ____(
DenseColumn,
SequenceDenseColumn,
fc_old._DenseColumn, # pylint: disable=protected-access
fc_old._SequenceDenseColumn, # pylint: disable=protected-access
collections.namedtuple(
'EmbeddingColumn',
('categorical_column', 'dimension', 'combiner', 'initializer',
'... | EmbeddingColumn |
python | milvus-io__pymilvus | pymilvus/bulk_writer/stage_manager.py | {
"start": 183,
"end": 1464
} | class ____:
def __init__(self, cloud_endpoint: str, api_key: str):
"""
private preview feature. Please submit a request and contact us if you need it.
Args:
cloud_endpoint (str): The fixed cloud endpoint URL.
- For international regions: https://api.cloud.zilliz.... | StageManager |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataproc.py | {
"start": 26192,
"end": 43732
} | class ____(GoogleCloudBaseOperator):
"""
Create a new cluster on Google Cloud Dataproc.
The operator will wait until the creation is successful or an error occurs
in the creation process.
If the cluster already exists and ``use_if_exists`` is True, then the operator will:
- if cluster state is... | DataprocCreateClusterOperator |
python | tensorflow__tensorflow | tensorflow/python/data/ops/options.py | {
"start": 5612,
"end": 6891
} | class ____(enum.Enum):
"""Represents how to handle external state during serialization.
See the `tf.data.Options.experimental_external_state_policy` documentation
for more information.
"""
WARN = 0
IGNORE = 1
FAIL = 2
@classmethod
def _to_proto(cls, obj):
"""Convert enum to proto."""
if obj ... | ExternalStatePolicy |
python | huggingface__transformers | src/transformers/models/hiera/configuration_hiera.py | {
"start": 882,
"end": 9319
} | class ____(BackboneConfigMixin, PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`HieraModel`]. It is used to instantiate a Hiera
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yiel... | HieraConfig |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-microsoft-onedrive/source_microsoft_onedrive/spec.py | {
"start": 1376,
"end": 2574
} | class ____(BaseModel):
"""
ServiceCredentials class for service key authentication.
This class is structured similarly to OAuthCredentials but for a different authentication method.
"""
class Config:
title = "Service Key Authentication"
# Fields for the Service authentication, similar ... | ServiceCredentials |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_internal/req/req_file.py | {
"start": 2688,
"end": 9673
} | class ____:
def __init__(
self,
filename: str,
lineno: int,
args: str,
opts: Values,
constraint: bool,
) -> None:
self.filename = filename
self.lineno = lineno
self.opts = opts
self.constraint = constraint
if args:
... | ParsedLine |
python | pytorch__pytorch | torch/_inductor/codecache.py | {
"start": 129894,
"end": 145068
} | class ____(CppPythonBindingsCodeCache):
cache: dict[str, Callable[[], ModuleType | CDLL]] = {}
cache_clear = staticmethod(cache.clear)
_standalone_runtime_path: str | None = None
prefix = textwrap.dedent(
"""
#include "{halideruntime_h}"
#include "{headerfile}"
#include <... | HalideCodeCache |
python | Netflix__metaflow | metaflow/plugins/aws/step_functions/schedule_decorator.py | {
"start": 120,
"end": 1940
} | class ____(FlowDecorator):
"""
Specifies the times when the flow should be run when running on a
production scheduler.
Parameters
----------
hourly : bool, default False
Run the workflow hourly.
daily : bool, default True
Run the workflow daily.
weekly : bool, default Fa... | ScheduleDecorator |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/selectable.py | {
"start": 67549,
"end": 68476
} | class ____(FromClauseAlias, LateralFromClause):
"""Represent a LATERAL subquery.
This object is constructed from the :func:`_expression.lateral` module
level function as well as the :meth:`_expression.FromClause.lateral`
method available
on all :class:`_expression.FromClause` subclasses.
While... | Lateral |
python | django-import-export__django-import-export | tests/core/tests/test_widgets.py | {
"start": 477,
"end": 729
} | class ____(TestCase):
def setUp(self):
self.widget = widgets.Widget()
def test_clean(self):
self.assertEqual("a", self.widget.clean("a"))
def test_render(self):
self.assertEqual("1", self.widget.render(1))
| WidgetTest |
python | pytorch__pytorch | torch/distributed/elastic/rendezvous/_etcd_stub.py | {
"start": 1475,
"end": 1555
} | class ____:
def __init__(self) -> None:
raise EtcdStubError
| EtcdResult |
python | scrapy__scrapy | tests/test_signals.py | {
"start": 625,
"end": 983
} | class ____:
@deferred_f_from_coro_f
async def test_scheduler_empty(self):
crawler = get_crawler()
calls = []
def track_call():
calls.append(object())
crawler.signals.connect(track_call, signals.scheduler_empty)
await maybe_deferred_to_future(crawler.crawl())... | TestMain |
python | allegroai__clearml | clearml/backend_api/services/v2_20/projects.py | {
"start": 128989,
"end": 131200
} | class ____(Response):
"""
Response of projects.get_task_tags endpoint.
:param tags: The list of unique tag values
:type tags: Sequence[str]
:param system_tags: The list of unique system tag values. Returned only if 'include_system' is set to 'true'
in the request
:type system_tags: Sequ... | GetTaskTagsResponse |
python | kamyu104__LeetCode-Solutions | Python/partition-array-into-two-arrays-to-minimize-sum-difference.py | {
"start": 70,
"end": 843
} | class ____(object):
def minimumDifference(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
left, right = nums[:len(nums)//2], nums[len(nums)//2:]
total1, total2 = sum(left), sum(right)
result = float("inf")
for k in xrange(len(left)+1):
... | Solution |
python | openai__openai-python | src/openai/types/chat/chat_completion_token_logprob.py | {
"start": 213,
"end": 867
} | class ____(BaseModel):
token: str
"""The token."""
bytes: Optional[List[int]] = None
"""A list of integers representing the UTF-8 bytes representation of the token.
Useful in instances where characters are represented by multiple tokens and
their byte representations must be combined to genera... | TopLogprob |
python | tiangolo__fastapi | docs_src/path_operation_configuration/tutorial004_py310.py | {
"start": 78,
"end": 638
} | class ____(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
tags: set[str] = set()
@app.post("/items/", response_model=Item, summary="Create an item")
async def create_item(item: Item):
"""
Create an item with all the information:
- **name**: ... | Item |
python | keras-team__keras | guides/custom_train_step_in_jax.py | {
"start": 8945,
"end": 10713
} | class ____(keras.Model):
def test_step(self, state, data):
# Unpack the data.
x, y = data
(
trainable_variables,
non_trainable_variables,
metrics_variables,
) = state
# Compute predictions and loss.
y_pred, non_trainable_variables ... | CustomModel |
python | dagster-io__dagster | python_modules/libraries/dagster-looker/dagster_looker_tests/api/test_component.py | {
"start": 3107,
"end": 4712
} | class ____(TestTranslation):
"""Test translation of asset attributes for Looker components."""
def test_translation(
self,
looker_api_mocks,
attributes: Mapping[str, Any],
assertion: Callable[[AssetSpec], bool],
key_modifier: Optional[Callable[[AssetKey], AssetKey]],
... | TestLookerTranslation |
python | django__django | tests/model_inheritance/models.py | {
"start": 4451,
"end": 4612
} | class ____(CommonAncestor):
first_ancestor = models.OneToOneField(
CommonAncestor, models.CASCADE, primary_key=True, parent_link=True
)
| FirstParent |
python | getsentry__sentry | src/sentry/audit_log/events.py | {
"start": 11712,
"end": 12227
} | class ____(AuditLogEvent):
def __init__(self) -> None:
super().__init__(event_id=111, name="INTEGRATION_EDIT", api_name="integration.edit")
def render(self, audit_log_entry: AuditLogEntry) -> str:
if audit_log_entry.data.get("provider"):
return "edited the {name} for the {provider} ... | IntegrationEditAuditLogEvent |
python | kamyu104__LeetCode-Solutions | Python/delete-the-middle-node-of-a-linked-list.py | {
"start": 182,
"end": 575
} | class ____(object):
def deleteMiddle(self, head):
"""
:type head: Optional[ListNode]
:rtype: Optional[ListNode]
"""
dummy = ListNode()
dummy.next = head
slow = fast = dummy
while fast.next and fast.next.next:
slow, fast = slow.next, fast.ne... | Solution |
python | coleifer__peewee | peewee.py | {
"start": 163747,
"end": 164870
} | class ____(Field):
field_type = 'BLOB'
def _db_hook(self, database):
if database is None:
self._constructor = bytearray
else:
self._constructor = database.get_binary_type()
def bind(self, model, name, set_attribute=True):
self._constructor = bytearray
... | BlobField |
python | celery__celery | celery/exceptions.py | {
"start": 6967,
"end": 7064
} | class ____(TaskError):
"""The task is already registered."""
# XXX Unused
| AlreadyRegistered |
python | ray-project__ray | python/ray/serve/_private/request_router/pow_2_router.py | {
"start": 495,
"end": 3129
} | class ____(
FIFOMixin, LocalityMixin, MultiplexMixin, RequestRouter
):
"""Chooses a replica for each request using the "power of two choices" procedure.
Requests are routed in FIFO order.
When a request comes in, two candidate replicas are chosen randomly. Each replica
is sent a control message to... | PowerOfTwoChoicesRequestRouter |
python | pydantic__pydantic | pydantic-core/tests/serializers/test_list_tuple.py | {
"start": 8005,
"end": 8086
} | class ____:
def __iter__(self):
return iter([1, 2, 5])
| ImplicitContains |
python | sphinx-doc__sphinx | sphinx/search/no.py | {
"start": 197,
"end": 610
} | class ____(SearchLanguage):
lang = 'no'
language_name = 'Norwegian'
js_stemmer_rawcode = 'norwegian-stemmer.js'
stopwords = NORWEGIAN_STOPWORDS
def __init__(self, options: dict[str, str]) -> None:
super().__init__(options)
self.stemmer = snowballstemmer.stemmer('norwegian')
def... | SearchNorwegian |
python | mwaskom__seaborn | seaborn/_stats/aggregation.py | {
"start": 1252,
"end": 3587
} | class ____(Stat):
"""
Calculate a point estimate and error bar interval.
For more information about the various `errorbar` choices, see the
:doc:`errorbar tutorial </tutorial/error_bars>`.
Additional variables:
- **weight**: When passed to a layer that uses this stat, a weighted estimate
... | Est |
python | crytic__slither | slither/slithir/operations/send.py | {
"start": 660,
"end": 1683
} | class ____(Call, OperationWithLValue):
def __init__(
self,
destination: Union[LocalVariable, LocalIRVariable],
value: Constant,
result: Union[TemporaryVariable, TemporaryVariableSSA],
) -> None:
assert is_valid_lvalue(result)
assert isinstance(destination, (Variab... | Send |
python | getsentry__sentry | src/sentry/seer/endpoints/organization_trace_summary.py | {
"start": 908,
"end": 3031
} | class ____(OrganizationEndpoint):
publish_status = {
"POST": ApiPublishStatus.EXPERIMENTAL,
}
owner = ApiOwner.ML_AI
enforce_rate_limit = True
# Keeping same rate limits as GroupAISummary endpoint for now
rate_limits = RateLimitConfig(
limit_overrides={
"POST": {
... | OrganizationTraceSummaryEndpoint |
python | numba__llvmlite | llvmlite/ir/values.py | {
"start": 20458,
"end": 20819
} | class ____(NamedValue, _ConstOpMixin, _HasMetadata):
"""
A global value.
"""
name_prefix = '@'
deduplicate_name = False
def __init__(self, *args, **kwargs):
super(GlobalValue, self).__init__(*args, **kwargs)
self.linkage = ''
self.storage_class = ''
self.section ... | GlobalValue |
python | langchain-ai__langchain | libs/standard-tests/tests/unit_tests/test_basic_tool.py | {
"start": 917,
"end": 1671
} | class ____(ToolsUnitTests):
@property
def tool_constructor(self) -> type[ParrotMultiplyTool]:
return ParrotMultiplyTool
@property
def tool_constructor_params(self) -> dict:
# if your tool constructor instead required initialization arguments like
# `def __init__(self, some_arg: ... | TestParrotMultiplyToolUnit |
python | kamyu104__LeetCode-Solutions | Python/shortest-path-in-a-hidden-grid.py | {
"start": 216,
"end": 2100
} | class ____(object):
def findShortestPath(self, master):
"""
:type master: GridMaster
:rtype: int
"""
directions = {'L': (0, -1), 'R': (0, 1), 'U': (-1, 0), 'D': (1, 0)}
rollback = {'L': 'R', 'R': 'L', 'U': 'D', 'D': 'U'}
def dfs(pos, target, master, lookup, a... | Solution |
python | huggingface__transformers | tests/models/kyutai_speech_to_text/test_modeling_kyutai_speech_to_text.py | {
"start": 24831,
"end": 31805
} | class ____(unittest.TestCase):
_dataset = None
def setUp(self):
self.model_checkpoint = "kyutai/stt-2.6b-en-trfs"
def tearDown(self):
cleanup(torch_device, gc_collect=True)
@classmethod
def _load_dataset(cls):
# Lazy loading of the dataset. Because it is a class method, it... | KyutaiSpeechToTextForConditionalGenerationIntegrationTests |
python | apache__avro | lang/py/avro/io.py | {
"start": 14558,
"end": 21728
} | class ____:
"""Write leaf values."""
_writer: IO[bytes]
def __init__(self, writer: IO[bytes]) -> None:
"""
writer is a Python object on which we can call write.
"""
self._writer = writer
@property
def writer(self) -> IO[bytes]:
return self._writer
def ... | BinaryEncoder |
python | PrefectHQ__prefect | src/prefect/events/schemas/automations.py | {
"start": 755,
"end": 2783
} | class ____(PrefectBaseModel, abc.ABC, extra="ignore"): # type: ignore[call-arg]
"""
Base class describing a set of criteria that must be satisfied in order to trigger
an automation.
"""
type: str
@abc.abstractmethod
def describe_for_cli(self, indent: int = 0) -> str:
"""Return a h... | Trigger |
python | PyCQA__pyflakes | pyflakes/messages.py | {
"start": 622,
"end": 870
} | class ____(Message):
message = 'redefinition of unused %r from line %r'
def __init__(self, filename, loc, name, orig_loc):
Message.__init__(self, filename, loc)
self.message_args = (name, orig_loc.lineno)
| RedefinedWhileUnused |
python | spack__spack | lib/spack/spack/cmd/common/arguments.py | {
"start": 1469,
"end": 2996
} | class ____(argparse.Action):
"""Constructs a list of specs based on constraints from the command line
An instance of this class is supposed to be used as an argument action
in a parser. It will read a constraint and will attach a function to the
arguments that accepts optional keyword arguments.
T... | ConstraintAction |
python | falconry__falcon | tests/test_cmd_inspect_app.py | {
"start": 4423,
"end": 6179
} | class ____:
def check(self, actual, expect):
if _WIN32:
# windows randomly returns the driver name as lowercase
assert actual.casefold() == expect.casefold()
else:
assert actual == expect
def test_routes_only(self, verbose, internal, monkeypatch):
arg... | TestMain |
python | joke2k__faker | tests/providers/test_internet.py | {
"start": 33282,
"end": 34547
} | class ____:
"""Test ru_RU internet provider methods"""
def test_free_email_domain(self, faker):
assert faker.free_email_domain() in RuRuInternetProvider.free_email_domains
def test_tld(self, faker):
assert faker.tld() in RuRuInternetProvider.tlds
@patch(
"faker.providers.inter... | TestRuRu |
python | scikit-learn__scikit-learn | sklearn/metrics/tests/test_score_objects.py | {
"start": 5163,
"end": 5358
} | class ____(BaseEstimator):
"""Dummy estimator to test scoring validators"""
def fit(self, X, y):
return self
def score(self, X, y):
return 1.0
| EstimatorWithFitAndScore |
python | getsentry__sentry | src/sentry/api/paginator.py | {
"start": 8213,
"end": 8493
} | class ____(BasePaginator):
def get_item_key(self, item, for_prev=False):
value = getattr(item, self.key)
return int(math.floor(value) if self._is_asc(for_prev) else math.ceil(value))
def value_from_cursor(self, cursor):
return cursor.value
| Paginator |
python | ZoranPandovski__al-go-rithms | data_structures/Arrays/Python/running_sum_of_1D_array.py | {
"start": 640,
"end": 993
} | class ____:
def runningSum(self, nums: List[int]) -> List[int]:
# In this algorithm we keep replacing the i th element with the running sum.
# This allows us to achieve O(1) space and O(n) time complexity
sum = 0
for i in range(len(nums)):
sum += nums[i]
nums... | Solution |
python | django__django | django/core/management/commands/sqlsequencereset.py | {
"start": 105,
"end": 1101
} | class ____(AppCommand):
help = (
"Prints the SQL statements for resetting sequences for the given app name(s)."
)
output_transaction = True
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
"--database",
default=DEFAULT_... | Command |
python | pytorch__pytorch | torch/nn/utils/_expanded_weights/embedding_expanded_weights.py | {
"start": 289,
"end": 3073
} | class ____(torch.autograd.Function):
@staticmethod
# pyrefly: ignore [bad-override]
def forward(
ctx: Any, kwarg_names: list[str], _: Any, *expanded_args_and_kwargs: Any
) -> torch.Tensor:
expanded_args, expanded_kwargs = standard_kwargs(
kwarg_names, expanded_args_and_kwargs... | EmbeddingPerSampleGrad |
python | Textualize__textual | docs/examples/styles/border_title_align.py | {
"start": 64,
"end": 583
} | class ____(App):
CSS_PATH = "border_title_align.tcss"
def compose(self):
lbl = Label("My title is on the left.", id="label1")
lbl.border_title = "< Left"
yield lbl
lbl = Label("My title is centered", id="label2")
lbl.border_title = "Centered!"
yield lbl
... | BorderTitleAlignApp |
python | readthedocs__readthedocs.org | readthedocs/config/tests/test_validation.py | {
"start": 1400,
"end": 2219
} | class ____:
def test_it_accepts_list_types(self):
result = validate_list(["choice", "another_choice"])
assert result == ["choice", "another_choice"]
result = validate_list(("choice", "another_choice"))
assert result == ["choice", "another_choice"]
def iterator():
... | TestValidateList |
python | realpython__materials | hashtable/01_hashtable_prototype/10_make_the_hash_table_iterable/hashtable.py | {
"start": 107,
"end": 1501
} | class ____:
def __init__(self, capacity):
if capacity < 1:
raise ValueError("Capacity must be a positive number")
self._slots = capacity * [None]
def __len__(self):
return len(self.pairs)
def __iter__(self):
yield from self.keys
def __delitem__(self, key):
... | HashTable |
python | apache__airflow | airflow-core/src/airflow/utils/db_cleanup.py | {
"start": 11660,
"end": 23303
} | class ____(Executable, ClauseElement):
"""Custom sqlalchemy clause element for CTAS operations."""
inherit_cache = False
def __init__(self, name, query):
self.name = name
self.query = query
@compiles(CreateTableAs)
def _compile_create_table_as__other(element, compiler, **kw):
return ... | CreateTableAs |
python | tensorflow__tensorflow | third_party/xla/xla/backends/cpu/codegen/tiled/tiled_kernel_test.py | {
"start": 1020,
"end": 2650
} | class ____:
def __init__(self, shape: tuple[int, ...]):
"""Initializes the InputSpec.
Args:
shape: The shape of the input array.
"""
self.shape = shape
def get_random_array(shape: tuple[int, ...], dtype: np.dtype) -> np.ndarray:
rng = np.random.default_rng()
return rng.uniform(low=-5, hi... | InputSpec |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-oci-genai/llama_index/embeddings/oci_genai/base.py | {
"start": 534,
"end": 761
} | class ____(Enum):
"""OCI authentication types as enumerator."""
API_KEY = 1
SECURITY_TOKEN = 2
INSTANCE_PRINCIPAL = 3
RESOURCE_PRINCIPAL = 4
CUSTOM_ENDPOINT_PREFIX = "ocid1.generativeaiendpoint"
| OCIAuthType |
python | Textualize__rich | examples/top_lite_simulator.py | {
"start": 275,
"end": 2063
} | class ____:
pid: int
command: str
cpu_percent: float
memory: int
start_time: datetime.datetime
thread_count: int
state: Literal["running", "sleeping"]
@property
def memory_str(self) -> str:
if self.memory > 1e6:
return f"{int(self.memory/1e6)}M"
if self.m... | Process |
python | pandas-dev__pandas | pandas/tests/scalar/timestamp/methods/test_to_julian_date.py | {
"start": 31,
"end": 810
} | class ____:
def test_compare_1700(self):
ts = Timestamp("1700-06-23")
res = ts.to_julian_date()
assert res == 2_342_145.5
def test_compare_2000(self):
ts = Timestamp("2000-04-12")
res = ts.to_julian_date()
assert res == 2_451_646.5
def test_compare_2100(self... | TestTimestampToJulianDate |
python | scikit-learn__scikit-learn | sklearn/tests/metadata_routing_common.py | {
"start": 11019,
"end": 11436
} | class ____(ConsumingClassifier):
"""ConsumingClassifier without a predict_proba method, but with predict_log_proba.
Used to mimic dynamic method selection such as in the `_parallel_predict_proba()`
function called by `BaggingClassifier`.
"""
@property
def predict_proba(self):
raise Att... | ConsumingClassifierWithoutPredictProba |
python | pytorch__pytorch | setup.py | {
"start": 47478,
"end": 48872
} | class ____:
"""Merge LICENSE and LICENSES_BUNDLED.txt as a context manager
LICENSE is the main PyTorch license, LICENSES_BUNDLED.txt is auto-generated
from all the licenses found in ./third_party/. We concatenate them so there
is a single license file in the sdist and wheels with all of the necessary
... | concat_license_files |
python | apache__airflow | airflow-core/tests/unit/utils/log/test_stream_accumulator.py | {
"start": 1239,
"end": 6381
} | class ____:
"""Test cases for the LogStreamAccumulator class."""
@pytest.fixture
def structured_logs(self):
"""Create a stream of mock structured log messages."""
def generate_logs():
yield from (
StructuredLogMessage(
event=f"test_event_{i +... | TestLogStreamAccumulator |
python | jmcnamara__XlsxWriter | xlsxwriter/test/app/test_initialisation.py | {
"start": 289,
"end": 792
} | class ____(unittest.TestCase):
"""
Test initialisation of the App class and call a method.
"""
def setUp(self):
self.fh = StringIO()
self.app = App()
self.app._set_filehandle(self.fh)
def test_xml_declaration(self):
"""Test App xml_declaration()"""
self.ap... | TestInitialisation |
python | aio-libs__aiohttp | aiohttp/streams.py | {
"start": 2367,
"end": 16716
} | class ____(AsyncStreamReaderMixin):
"""An enhancement of asyncio.StreamReader.
Supports asynchronous iteration by line, chunk or as available::
async for line in reader:
...
async for chunk in reader.iter_chunked(1024):
...
async for slice in reader.iter_any():
... | StreamReader |
python | dask__distributed | distributed/utils.py | {
"start": 9476,
"end": 12969
} | class ____:
"""
A mixin for adding an `asynchronous` attribute and `sync` method to a class.
Subclasses must define a `loop` attribute for an associated
`tornado.IOLoop`, and may also add a `_asynchronous` attribute indicating
whether the class should default to asynchronous behavior.
"""
... | SyncMethodMixin |
python | getsentry__sentry | src/sentry/uptime/endpoints/project_uptime_alert_checks_index.py | {
"start": 1744,
"end": 8374
} | class ____(ProjectUptimeAlertEndpoint):
owner = ApiOwner.CRONS
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
}
def get(
self,
request: Request,
project: Project,
uptime_detector: Detector,
) -> Response:
uptime_subscription = get_uptime_su... | ProjectUptimeAlertCheckIndexEndpoint |
python | sympy__sympy | sympy/codegen/fnodes.py | {
"start": 3863,
"end": 4763
} | class ____(Node):
""" Represents a subroutine in Fortran.
Examples
========
>>> from sympy import fcode, symbols
>>> from sympy.codegen.ast import Print
>>> from sympy.codegen.fnodes import Subroutine
>>> x, y = symbols('x y', real=True)
>>> sub = Subroutine('mysub', [x, y], [Print([x*... | Subroutine |
python | django__django | tests/admin_inlines/admin.py | {
"start": 1960,
"end": 2512
} | class ____:
model = Photo
extra = 2
fieldsets = [
(None, {"fields": ["image", "title"], "description": "First group"}),
(
"Details",
{
"fields": ["description", "creation_date"],
"classes": ["collapse"],
"description": "... | PhotoInlineMixin |
python | MongoEngine__mongoengine | tests/fields/test_enum_field.py | {
"start": 293,
"end": 339
} | class ____(Enum):
RED = 1
BLUE = 2
| Color |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1595428,
"end": 1597270
} | class ____(sgqlc.types.Union):
"""An item in a pull request timeline"""
__schema__ = github_schema
__types__ = (
AddedToMergeQueueEvent,
AddedToProjectEvent,
AssignedEvent,
AutoMergeDisabledEvent,
AutoMergeEnabledEvent,
AutoRebaseEnabledEvent,
AutoSqu... | PullRequestTimelineItems |
python | pandas-dev__pandas | pandas/io/sas/sas7bdat.py | {
"start": 2384,
"end": 3002
} | class ____:
col_id: int
name: str | bytes
label: str | bytes
format: str | bytes
ctype: bytes
length: int
def __init__(
self,
col_id: int,
# These can be bytes when convert_header_text is False
name: str | bytes,
label: str | bytes,
format: st... | _Column |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_contextlib.py | {
"start": 3849,
"end": 14231
} | class ____(__TestCase):
def test_contextmanager_plain(self):
state = []
@contextmanager
def woohoo():
state.append(1)
yield 42
state.append(999)
with woohoo() as x:
self.assertEqual(state, [1])
self.assertEqual(x, 42)
... | ContextManagerTestCase |
python | qdrant__qdrant-client | qdrant_client/auth/bearer_auth.py | {
"start": 87,
"end": 1567
} | class ____(httpx.Auth):
def __init__(
self,
auth_token_provider: Union[Callable[[], str], Callable[[], Awaitable[str]]],
):
self.async_token: Optional[Callable[[], Awaitable[str]]] = None
self.sync_token: Optional[Callable[[], str]] = None
if asyncio.iscoroutinefunction(... | BearerAuth |
python | realpython__materials | python-class/shapes.py | {
"start": 567,
"end": 714
} | class ____:
side = PositiveNumber()
def __init__(self, side):
self.side = side
def area(self):
return self.side**2
| Square |
python | facelessuser__soupsieve | tests/test_level4/test_out_of_range.py | {
"start": 57,
"end": 10928
} | class ____(util.TestCase):
"""Test out of range selectors."""
def test_out_of_range_number(self):
"""Test in range number."""
markup = """
<!-- These should not match -->
<input id="0" type="number" min="0" max="10" value="5">
<input id="1" type="number" min="-1" max="1... | TestOutOfRange |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.