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 | ansible__ansible | lib/ansible/plugins/doc_fragments/url_windows.py | {
"start": 193,
"end": 5491
} | class ____:
# Common options for Ansible.ModuleUtils.WebRequest
DOCUMENTATION = r"""
options:
method:
description:
- The HTTP Method of the request.
type: str
follow_redirects:
description:
- Whether or the module should follow redirects.
- V(all) will follow all redirect.
- V(n... | ModuleDocFragment |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/util/typing.py | {
"start": 18438,
"end": 18704
} | class ____(Protocol):
def __get__(self, instance: object, owner: Any) -> Any: ...
def __set__(self, instance: Any, value: Any) -> None: ...
def __delete__(self, instance: Any) -> None: ...
_DESC = TypeVar("_DESC", bound=DescriptorProto)
| DescriptorProto |
python | coleifer__peewee | tests/db_tests.py | {
"start": 28208,
"end": 31747
} | class ____(ModelTestCase):
database = db_loader('sqlite3')
requires = [Data]
def test_attach(self):
database = self.database
Data.create(key='k1', value='v1')
Data.create(key='k2', value='v2')
# Attach an in-memory cache database.
database.attach(':memory:', 'cache'... | TestAttachDatabase |
python | gevent__gevent | src/greentest/3.14/test_urllib2.py | {
"start": 11898,
"end": 12208
} | class ____(io.StringIO):
def __init__(self, code, msg, headers, data, url=None):
io.StringIO.__init__(self, data)
self.code, self.msg, self.headers, self.url = code, msg, headers, url
def info(self):
return self.headers
def geturl(self):
return self.url
| MockResponse |
python | h5py__h5py | h5py/tests/test_file.py | {
"start": 26076,
"end": 27388
} | class ____(TestCase):
"""
Ensure that closing a file invalidates object IDs, as appropriate
"""
def test_close(self):
""" Closing a file invalidates any of the file's open objects """
with File(self.mktemp(), 'w') as f1:
g1 = f1.create_group('foo')
self.asse... | TestCloseInvalidatesOpenObjectIDs |
python | ray-project__ray | rllib/algorithms/tests/test_env_runner_failures.py | {
"start": 6074,
"end": 6946
} | class ____(MultiAgentEnvRunner):
"""Configure EnvRunner to error in specific condition is hard.
So we take a short-cut, and simply forward ping() to env.sample().
"""
def ping(self) -> str:
# See if Env wants to throw error.
self.sample(num_timesteps=1, random_actions=True)
# I... | ForwardHealthCheckToEnvWorkerMultiAgent |
python | getsentry__sentry | tests/sentry/integrations/vsts/test_client.py | {
"start": 17932,
"end": 23453
} | class ____(VstsIntegrationTestCase):
def setUp(self) -> None:
super().setUp()
self.integration, _, _, _ = self.create_identity_integration(
user=self.user,
organization=self.organization,
integration_params={
"provider": "vsts",
"ex... | VstsProxyApiClientTest |
python | pytorch__pytorch | test/inductor/test_profiler.py | {
"start": 653,
"end": 11748
} | class ____(torch._inductor.test_case.TestCase):
@skipIfXpu(
msg="AssertionError: False is not true, "
"https://github.com/intel/torch-xpu-ops/issues/2335"
)
@unittest.skipIf(not HAS_TRITON, "requires cuda & triton")
def test_inductor_profiling_triton_launch(self):
# Verify that w... | DynamoProfilerTests |
python | tensorflow__tensorflow | tensorflow/python/saved_model/model_utils/mode_keys_test.py | {
"start": 821,
"end": 2287
} | class ____(test.TestCase):
def test_map(self):
mode_map = mode_keys.ModeKeyMap(**{
mode_keys.KerasModeKeys.PREDICT: 3,
mode_keys.KerasModeKeys.TEST: 1
})
# Test dictionary __getitem__
self.assertEqual(3, mode_map[mode_keys.KerasModeKeys.PREDICT])
self.assertEqual(3, mode_map[mode... | ModeKeyMapTest |
python | numba__numba | numba/tests/test_ir_utils.py | {
"start": 721,
"end": 796
} | class ____(object):
def __init__(self, val):
self.val = val
| Dummy |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 145507,
"end": 149767
} | class ____:
def test_format_timeframe(self):
# Now
assert self.locale._format_timeframe("now", 0) == "දැන්"
# Second(s)
assert self.locale._format_timeframe("second", -1) == "තත්පරයක"
assert self.locale._format_timeframe("second", 1) == "තත්පරයකින්"
assert self.local... | TestSinhalaLocale |
python | getsentry__sentry | tests/sentry/models/test_grouphistory.py | {
"start": 306,
"end": 1150
} | class ____(TestCase):
def test_owner(self) -> None:
team = self.create_team()
GroupAssignee.objects.assign(self.group, self.user)
history = GroupHistory.objects.filter(group_id=self.group.id).first()
assert history
actor = Actor.from_id(user_id=self.user.id)
assert ... | GroupHistoryTest |
python | Netflix__metaflow | metaflow/plugins/airflow/airflow_utils.py | {
"start": 1099,
"end": 1437
} | class ____(Exception):
headline = (
"Kubernetes Provider version is incompatible with Metaflow `foreach`s. "
"Install the provider via "
"`%s -m pip install apache-airflow-providers-cncf-kubernetes==%s`"
) % (sys.executable, KUBERNETES_PROVIDER_FOREACH_VERSION)
| IncompatibleKubernetesProviderVersionException |
python | conda__conda | conda/auxlib/entity.py | {
"start": 11963,
"end": 17398
} | class ____:
"""
Fields are doing something very similar to boxing and unboxing
of c#/java primitives. __set__ should take a "primitive" or "raw" value and create a "boxed"
or "programmatically usable" value of it. While __get__ should return the boxed value,
dump in turn should unbox the value int... | Field |
python | kamyu104__LeetCode-Solutions | Python/buildings-with-an-ocean-view.py | {
"start": 29,
"end": 399
} | class ____(object):
def findBuildings(self, heights):
"""
:type heights: List[int]
:rtype: List[int]
"""
result = []
for i, h in enumerate(heights):
while result and heights[result[-1]] <= h:
result.pop()
result.append(i)
... | Solution |
python | getsentry__sentry | src/sentry/workflow_engine/endpoints/serializers/workflow_group_history_serializer.py | {
"start": 777,
"end": 966
} | class ____(TypedDict):
group: BaseGroupSerializerResponse
count: int
lastTriggered: datetime
eventId: str
detector: NotRequired[dict[str, Any]]
| WorkflowFireHistoryResponse |
python | pytorch__pytorch | torch/backends/miopen/__init__.py | {
"start": 804,
"end": 1208
} | class ____(PropModule):
immediate = ContextProp(
torch._C._get_miopen_immediate, torch._C._set_miopen_immediate
)
# This is the sys.modules replacement trick, see
# https://stackoverflow.com/questions/2447353/getattr-on-a-module/7668273#7668273
sys.modules[__name__] = MiopenModule(sys.modules[__name__... | MiopenModule |
python | pytorch__pytorch | test/test_tensorboard.py | {
"start": 4123,
"end": 7469
} | class ____(BaseTestCase):
def test_pytorch_np(self):
tensors = [torch.rand(3, 10, 10), torch.rand(1), torch.rand(1, 2, 3, 4, 5)]
for tensor in tensors:
# regular tensor
self.assertIsInstance(make_np(tensor), np.ndarray)
# CUDA tensor
if torch.cuda.is_... | TestTensorBoardPyTorchNumpy |
python | pytorch__pytorch | test/test_autograd.py | {
"start": 464098,
"end": 471155
} | class ____(TestCase):
def assertClonedLenEqual(self, ctx, n):
self.assertEqual(len(list(ctx.cloned.items())), n)
def assertTIDMapLenEqual(self, ctx, n):
self.assertEqual(len(list(ctx.tid_to_weakhandle.items())), n)
def test_basic(self):
a = torch.rand(2, 3, requires_grad=True)
... | TestAllowMutationOnSaved |
python | doocs__leetcode | solution/2600-2699/2610.Convert an Array Into a 2D Array With Conditions/Solution.py | {
"start": 0,
"end": 308
} | class ____:
def findMatrix(self, nums: List[int]) -> List[List[int]]:
cnt = Counter(nums)
ans = []
for x, v in cnt.items():
for i in range(v):
if len(ans) <= i:
ans.append([])
ans[i].append(x)
return ans
| Solution |
python | getsentry__sentry | tests/sentry/workflow_engine/test_task.py | {
"start": 832,
"end": 1624
} | class ____(TestCase):
def test_fetch_event_retries_on_retry_error(self) -> None:
"""Test that fetch_event retries when encountering RetryError."""
event_id = "test_event_id"
project_id = self.project.id
# Mock nodestore to fail with RetryError twice, then succeed
with mock.p... | FetchEventTests |
python | pandas-dev__pandas | asv_bench/benchmarks/strftime.py | {
"start": 69,
"end": 1669
} | class ____:
timeout = 1500
params = [1000, 10000]
param_names = ["nobs"]
def setup(self, nobs):
d = "2018-11-29"
dt = "2018-11-26 11:18:27.0"
self.data = pd.DataFrame(
{
"dt": [np.datetime64(dt)] * nobs,
"d": [np.datetime64(d)] * nobs,... | DatetimeStrftime |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/matrix_band_part_op_test.py | {
"start": 1497,
"end": 2501
} | class ____(test_lib.TestCase):
pass # Filled in below
def _GetMatrixBandPartTest(dtype_, batch_shape_, shape_):
@test_util.run_v1_only("b/120545219")
def Test(self):
mat = np.ones(shape_).astype(dtype_)
batch_mat = np.tile(mat, batch_shape_ + (1, 1))
for lower in -1, 0, 1, shape_[-2] - 1:
fo... | MatrixBandPartTest |
python | sympy__sympy | sympy/codegen/cfunctions.py | {
"start": 6450,
"end": 7439
} | class ____(Function):
"""
Represents "fused multiply add".
Explanation
===========
The benefit of using ``fma(x, y, z)`` over ``x*y + z``
is that, under finite precision arithmetic, the former is
supported by special instructions on some CPUs.
Examples
========
>>> from sympy... | fma |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 289679,
"end": 290162
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of RetireSponsorsTier"""
__schema__ = github_schema
__field_names__ = ("tier_id", "client_mutation_id")
tier_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="tierId")
"""The ID of the published tier to retire."""
client_m... | RetireSponsorsTierInput |
python | mlflow__mlflow | mlflow/projects/submitted_run.py | {
"start": 222,
"end": 1727
} | class ____:
"""
Wrapper around an MLflow project run (e.g. a subprocess running an entry point
command or a Databricks job run) and exposing methods for waiting on and cancelling the run.
This class defines the interface that the MLflow project runner uses to manage the lifecycle
of runs launched in... | SubmittedRun |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 745753,
"end": 746033
} | class ____(VegaLiteSchema):
"""MarkPropDefstringnullTypeForShape schema wrapper."""
_schema = {"$ref": "#/definitions/MarkPropDef<(string|null),TypeForShape>"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| MarkPropDefstringnullTypeForShape |
python | zarr-developers__zarr-python | src/zarr/core/dtype/common.py | {
"start": 5818,
"end": 5907
} | class ____(ValueError): ...
@dataclass(frozen=True, kw_only=True)
| ScalarTypeValidationError |
python | astropy__astropy | astropy/units/errors.py | {
"start": 1028,
"end": 1129
} | class ____(AstropyWarning):
"""
The base class for unit-specific warnings.
"""
| UnitsWarning |
python | pypa__warehouse | tests/unit/manage/test_forms.py | {
"start": 12996,
"end": 13818
} | class ____:
"""
Covers ConfirmPasswordForm
"""
def test_validate_confirm_password(self):
request = pretend.stub(
remote_addr=REMOTE_ADDR, banned=pretend.stub(by_ip=lambda ip_address: False)
)
user_service = pretend.stub(
find_userid=pretend.call_recorder(... | TestDeleteTOTPForm |
python | ray-project__ray | python/ray/serve/_private/benchmarks/streaming/common.py | {
"start": 507,
"end": 572
} | class ____(enum.Enum):
SYNC = "SYNC"
ASYNC = "ASYNC"
| IOMode |
python | pennersr__django-allauth | allauth/socialaccount/providers/soundcloud/provider.py | {
"start": 450,
"end": 930
} | class ____(OAuth2Provider):
id = "soundcloud"
name = "SoundCloud"
account_class = SoundCloudAccount
oauth2_adapter_class = SoundCloudOAuth2Adapter
def extract_uid(self, data):
return str(data["urn"])
def extract_common_fields(self, data):
return dict(
name=data.get(... | SoundCloudProvider |
python | great-expectations__great_expectations | great_expectations/expectations/window.py | {
"start": 319,
"end": 611
} | class ____(pydantic.BaseModel):
"""
A definition for a temporal window across <`range`> number of previous invocations
"""
constraint_fn: str
parameter_name: str
range: int
offset: Offset
strict: bool = False
class Config:
extra = Extra.forbid
| Window |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/classVar1.py | {
"start": 123,
"end": 264
} | class ____:
def __get__(self, *args: Any) -> str:
return ""
def __set__(self, obj: Any, value: str):
pass
| MyDescriptor |
python | django__django | tests/i18n/test_extraction.py | {
"start": 48647,
"end": 49885
} | class ____(ExtractorTests):
work_subdir = "unchanged"
def setUp(self):
super().setUp()
po_file = Path(self.PO_FILE)
po_file_tmp = Path(self.PO_FILE + ".tmp")
if os.name == "nt":
# msgmerge outputs Windows style paths on Windows.
po_contents = po_file_tmp.... | UnchangedPoExtractionTests |
python | mlflow__mlflow | mlflow/models/evaluation/base.py | {
"start": 2485,
"end": 22765
} | class ____:
'''
An evaluation metric.
Args:
eval_fn: A function that computes the metric with the following signature:
.. code-block:: python
def eval_fn(
predictions: pandas.Series,
targets: pandas.Series,
me... | EvaluationMetric |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linear_operator_householder_test.py | {
"start": 1385,
"end": 4633
} | class ____(
linear_operator_test_util.SquareLinearOperatorDerivedClassTest):
"""Most tests done in the base class LinearOperatorDerivedClassTest."""
def tearDown(self):
config.enable_tensor_float_32_execution(self.tf32_keep_)
def setUp(self):
self.tf32_keep_ = config.tensor_float_32_execution_enable... | LinearOperatorHouseholderTest |
python | django__django | tests/queries/tests.py | {
"start": 164490,
"end": 165108
} | class ____(TestCase):
def test_double_subquery_in(self):
lfa1 = LeafA.objects.create(data="foo")
lfa2 = LeafA.objects.create(data="bar")
lfb1 = LeafB.objects.create(data="lfb1")
lfb2 = LeafB.objects.create(data="lfb2")
Join.objects.create(a=lfa1, b=lfb1)
Join.objects.... | DoubleInSubqueryTests |
python | langchain-ai__langchain | libs/langchain/langchain_classic/evaluation/criteria/eval_chain.py | {
"start": 2707,
"end": 5737
} | class ____(BaseOutputParser[dict]):
"""A parser for the output of the CriteriaEvalChain."""
@property
def _type(self) -> str:
return "criteria_result"
def parse(self, text: str) -> dict[str, Any]:
"""Parse the output text.
Args:
text: The output text to parse.
... | CriteriaResultOutputParser |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-milvus/llama_index/vector_stores/milvus/utils.py | {
"start": 6370,
"end": 7123
} | class ____(ABC):
@abstractmethod
def encode_queries(self, queries: List[str]) -> List[Dict[int, float]]:
pass
async def async_encode_queries(self, queries: List[str]) -> List[Dict[int, float]]:
"""
Encode queries asynchronously. Use sync method if not implemented.
"""
... | BaseSparseEmbeddingFunction |
python | matplotlib__matplotlib | lib/mpl_toolkits/axes_grid1/axes_divider.py | {
"start": 9416,
"end": 11575
} | class ____(Divider):
"""
The Divider class whose rectangle area is specified as a subplot geometry.
"""
def __init__(self, fig, *args, horizontal=None, vertical=None,
aspect=None, anchor='C'):
"""
Parameters
----------
fig : `~matplotlib.figure.Figure`
... | SubplotDivider |
python | pennersr__django-allauth | allauth/mfa/internal/constants.py | {
"start": 24,
"end": 174
} | class ____(str, Enum):
MFA_SIGNUP_WEBAUTHN = "mfa_signup_webauthn"
MFA_AUTHENTICATE = "mfa_authenticate"
MFA_TRUST = "mfa_trust"
| LoginStageKey |
python | davidhalter__jedi | test/refactor/extract_function.py | {
"start": 3617,
"end": 6909
} | class ____():
a = 3
#? 11 text {'new_name': 'f'}
c = f(a)
# -------------------------------------------------- in-closure
def x(z):
def y(x):
#? 15 text {'new_name': 'f'}
return -x * z
# ++++++++++++++++++++++++++++++++++++++++++++++++++
def f(x, z):
return -x * z
def x(z):
def... | Ya |
python | pennersr__django-allauth | allauth/account/apps.py | {
"start": 214,
"end": 715
} | class ____(AppConfig):
name = "allauth.account"
verbose_name = _("Accounts")
default_auto_field = app_settings.DEFAULT_AUTO_FIELD or "django.db.models.AutoField"
def ready(self):
from allauth.account import checks # noqa
required_mw = "allauth.account.middleware.AccountMiddleware"
... | AccountConfig |
python | coleifer__peewee | tests/regressions.py | {
"start": 20262,
"end": 20712
} | class ____(ModelTestCase):
requires = [TS]
def test_zero_timestamp(self):
t0 = TS.create(key='t0', timestamp=0)
t1 = TS.create(key='t1', timestamp=1)
t0_db = TS.get(TS.key == 't0')
self.assertEqual(t0_db.timestamp, datetime.datetime(1970, 1, 1))
t1_db = TS.get(TS.key =... | TestZeroTimestamp |
python | getsentry__sentry | src/sentry/integrations/messaging/linkage.py | {
"start": 14972,
"end": 21796
} | class ____(TeamLinkageView, ABC):
@property
def metrics_operation_key(self) -> str:
return "link_team_view"
def execute(
self, request: HttpRequest, integration: RpcIntegration, params: Mapping[str, Any]
) -> HttpResponseBase:
from sentry.integrations.slack.analytics import Slac... | LinkTeamView |
python | jazzband__django-model-utils | tests/models.py | {
"start": 12451,
"end": 12725
} | class ____(models.IntegerField):
def contribute_to_class(self, cls: type[models.Model], name: str, *args: Any, **kwargs: Any) -> None:
super().contribute_to_class(cls, name, *args, **kwargs)
setattr(cls, name, StringyDescriptor(name))
| CustomDescriptorField |
python | django__django | tests/test_client_regress/tests.py | {
"start": 14618,
"end": 28539
} | class ____(ExtraAssertMixin, SimpleTestCase):
def test_redirect_page(self):
"""
An assertion is raised if the original page couldn't be retrieved as
expected
"""
# This page will redirect with code 301, not 302
response = self.client.get("/permanent_redirect_view/")
... | AssertRedirectsTests |
python | tqdm__tqdm | tqdm/contrib/discord.py | {
"start": 3077,
"end": 5243
} | class ____(tqdm_auto):
"""
Standard `tqdm.auto.tqdm` but also sends updates to a Discord Bot.
May take a few seconds to create (`__init__`).
- create a discord bot (not public, no requirement of OAuth2 code
grant, only send message permissions) & invite it to a channel:
<https://discordpy.r... | tqdm_discord |
python | django__django | tests/invalid_models_tests/test_relative_fields.py | {
"start": 48639,
"end": 51623
} | class ____(SimpleTestCase):
def test_fk_to_integer(self):
self._test_explicit_related_name_clash(
target=models.IntegerField(),
relative=models.ForeignKey("Target", models.CASCADE, related_name="clash"),
)
def test_fk_to_fk(self):
self._test_explicit_related_name... | ExplicitRelatedNameClashTests |
python | allegroai__clearml | clearml/backend_api/services/v2_20/queues.py | {
"start": 85808,
"end": 86991
} | class ____(Response):
"""
Response of queues.remove_task endpoint.
:param removed: Number of tasks removed (0 or 1)
:type removed: int
"""
_service = "queues"
_action = "remove_task"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
"remov... | RemoveTaskResponse |
python | PyCQA__pylint | doc/data/messages/n/non-iterator-returned/bad.py | {
"start": 16,
"end": 546
} | class ____:
def __init__(self, signs, predictions):
self.signs = signs
self.predictions = predictions
def __iter__(self): # [non-iterator-returned]
self.index = 0
self.number_of_prediction = len(self.predictions)
return self
SIGNS = ["Aries", "Taurus", "Gemini", "Canc... | GenericAstrology |
python | kamyu104__LeetCode-Solutions | Python/construct-the-longest-new-string.py | {
"start": 61,
"end": 277
} | class ____(object):
def longestString(self, x, y, z):
"""
:type x: int
:type y: int
:type z: int
:rtype: int
"""
return ((min(x, y)*2+int(x != y))+z)*2
| Solution |
python | doocs__leetcode | solution/1800-1899/1886.Determine Whether Matrix Can Be Obtained By Rotation/Solution.py | {
"start": 0,
"end": 650
} | class ____:
def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:
def rotate(matrix):
n = len(matrix)
for i in range(n // 2):
for j in range(i, n - 1 - i):
t = matrix[i][j]
matrix[i][j] = matrix[n - j - ... | Solution |
python | python__mypy | mypy/nodes.py | {
"start": 66930,
"end": 67112
} | class ____(Expression):
"""Ellipsis (...)"""
__slots__ = ()
def accept(self, visitor: ExpressionVisitor[T]) -> T:
return visitor.visit_ellipsis(self)
| EllipsisExpr |
python | astropy__astropy | astropy/cosmology/_src/tests/flrw/test_lambdacdm.py | {
"start": 1364,
"end": 4511
} | class ____(FLRWTest):
"""Test :class:`astropy.cosmology.LambdaCDM`."""
def setup_class(self):
"""Setup for testing."""
super().setup_class(self)
self.cls = LambdaCDM
# ===============================================================
# Method & Attribute Tests
_FLRW_redshift... | TestLambdaCDM |
python | allegroai__clearml | clearml/backend_api/services/v2_13/events.py | {
"start": 34576,
"end": 34824
} | class ____(BatchRequest):
"""
Adds a batch of events in a single call (json-lines format, stream-friendly)
"""
_service = "events"
_action = "add_batch"
_version = "2.13"
_batched_request_cls = AddRequest
| AddBatchRequest |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-pgvector/destination_pgvector/config.py | {
"start": 522,
"end": 1932
} | class ____(BaseModel):
host: str = Field(
...,
title="Host",
order=1,
description="Enter the account name you want to use to access the database.",
examples=["AIRBYTE_ACCOUNT"],
)
port: int = Field(
default=5432,
title="Port",
order=2,
... | PGVectorIndexingModel |
python | tensorflow__tensorflow | tensorflow/python/training/saving/saveable_object_util_test.py | {
"start": 5458,
"end": 5818
} | class ____(saveable_object.SaveableObject):
def __init__(self, obj, name):
spec = saveable_object.SaveSpec(obj.read(), "", name)
self.obj = obj
super(_StateSaveable, self).__init__(obj, [spec], name)
def restore(self, restored_tensors, restored_shapes):
del restored_shapes # Unused.
self.obj.... | _StateSaveable |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 514623,
"end": 518003
} | class ____(Response):
"""
Response of tasks.stop_many endpoint.
:param succeeded:
:type succeeded: Sequence[dict]
:param failed:
:type failed: Sequence[dict]
"""
_service = "tasks"
_action = "stop_many"
_version = "2.23"
_schema = {
"definitions": {},
"prop... | StopManyResponse |
python | google__jax | tests/multiprocess_gpu_test.py | {
"start": 1141,
"end": 7404
} | class ____(jtu.JaxTestCase):
def test_gpu_distributed_initialize(self):
if not jtu.test_device_matches(['gpu']):
raise unittest.SkipTest('Tests only for GPU.')
port = portpicker.pick_unused_port()
num_gpus = 4
num_gpus_per_task = 1
num_tasks = num_gpus // num_gpus_per_task
if jax.devi... | MultiProcessGpuTest |
python | pandas-dev__pandas | pandas/core/dtypes/dtypes.py | {
"start": 23998,
"end": 32383
} | class ____(PandasExtensionDtype):
"""
An ExtensionDtype for timezone-aware datetime data.
**This is not an actual numpy dtype**, but a duck type.
Parameters
----------
unit : str, default "ns"
The precision of the datetime data. Valid options are
``"s"``, ``"ms"``, ``"us"``, ``... | DatetimeTZDtype |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py | {
"start": 154673,
"end": 155473
} | class ____(nn.Module):
def __init__(self, hidden_size, eps: float = 1e-6) -> None:
"""
Qwen3OmniMoeCode2WavRMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self... | Qwen3OmniMoeCode2WavRMSNorm |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/util/langhelpers.py | {
"start": 47072,
"end": 47543
} | class ____(Generic[_T]):
def __init__(self, func: Callable[..., _T]):
self.func = func
self.clslevel = func
def __get__(self, instance: Any, owner: Any) -> _T:
if instance is None:
clsval = self.clslevel(owner)
return clsval
else:
return self.... | hybridproperty |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/single_string_slots.py | {
"start": 10,
"end": 98
} | class ____:
__slots__ = "bar"
def __init__(self, bar):
self.bar = bar
| Foo |
python | django-mptt__django-mptt | tests/myapp/models.py | {
"start": 2007,
"end": 2161
} | class ____(MPTTModel):
parent = models.ForeignKey(
"self", null=True, blank=True, related_name="children", on_delete=models.CASCADE
)
| Insert |
python | huggingface__transformers | src/transformers/models/clip/modeling_clip.py | {
"start": 39389,
"end": 41744
} | class ____(CLIPPreTrainedModel):
config: CLIPVisionConfig
main_input_name = "pixel_values"
input_modalities = ("image",)
def __init__(self, config: CLIPVisionConfig):
super().__init__(config)
vision_model = CLIPVisionModel._from_config(config)
self.vision_model = vision_model.v... | CLIPVisionModelWithProjection |
python | kamyu104__LeetCode-Solutions | Python/find-all-people-with-secret.py | {
"start": 1087,
"end": 2031
} | class ____(object):
def findAllPeople(self, n, meetings, firstPerson):
"""
:type n: int
:type meetings: List[List[int]]
:type firstPerson: int
:rtype: List[int]
"""
meetings.sort(key=lambda x: x[2])
result = {0, firstPerson}
adj = collections.d... | Solution2 |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_blocks/test_tab.py | {
"start": 93,
"end": 1349
} | class ____(util.MdCase):
"""Test tab slug cases."""
extension = ['pymdownx.blocks.tab', 'toc']
extension_configs = {
'pymdownx.blocks.tab': {'slugify': slugify(case='lower'), 'alternate_style': True}
}
MD = r"""
### Here is some text
/// tab | Here is some text
content
///... | TestTabSlugs |
python | pytorch__pytorch | torch/nn/modules/transformer.py | {
"start": 1434,
"end": 13176
} | class ____(Module):
r"""A basic transformer layer.
This Transformer layer implements the original Transformer architecture described
in the `Attention Is All You Need <https://arxiv.org/abs/1706.03762>`_ paper. The
intent of this layer is as a reference implementation for foundational understanding
... | Transformer |
python | openai__openai-python | src/openai/types/beta/realtime/session_update_event_param.py | {
"start": 10428,
"end": 10749
} | class ____(TypedDict, total=False):
session: Required[Session]
"""Realtime session object configuration."""
type: Required[Literal["session.update"]]
"""The event type, must be `session.update`."""
event_id: str
"""Optional client-generated ID used to identify this event."""
| SessionUpdateEventParam |
python | apache__airflow | airflow-core/src/airflow/models/dagrun.py | {
"start": 4658,
"end": 5297
} | class ____(NamedTuple):
"""Type of return for DagRun.task_instance_scheduling_decisions."""
tis: list[TI]
schedulable_tis: list[TI]
changed_tis: bool
unfinished_tis: list[TI]
finished_tis: list[TI]
def _default_run_after(ctx):
params = ctx.get_current_parameters()
return params["data_... | TISchedulingDecision |
python | walkccc__LeetCode | solutions/605. Can Place Flowers/605.py | {
"start": 0,
"end": 366
} | class ____:
def canPlaceFlowers(self, flowerbed: list[int], n: int) -> bool:
for i, flower in enumerate(flowerbed):
if flower == 0 and (
i == 0 or flowerbed[i - 1] == 0) and (
i == len(flowerbed) - 1 or flowerbed[i + 1] == 0):
flowerbed[i] = 1
n -= 1
if n <=... | Solution |
python | gevent__gevent | src/greentest/3.13/test_socket.py | {
"start": 160361,
"end": 180144
} | class ____(SendrecvmsgServerTimeoutBase):
# Test sendmsg() and recvmsg[_into]() using the ancillary data
# features of the RFC 3542 Advanced Sockets API for IPv6.
# Currently we can only handle certain data items (e.g. traffic
# class, hop limit, MTU discovery and fragmentation settings)
# without r... | RFC3542AncillaryTest |
python | walkccc__LeetCode | solutions/3237. Alt and Tab Simulation/3237.py | {
"start": 0,
"end": 392
} | class ____:
def simulationResult(
self,
windows: list[int],
queries: list[int],
) -> list[int]:
ans = []
seen = set()
for query in reversed(queries):
if query not in seen:
ans.append(query)
seen.add(query)
for window in windows:
if window not in seen:
... | Solution |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_function_base.py | {
"start": 32418,
"end": 41380
} | class ____(TestCase):
def test_basic(self):
v = [[1, 1], [3, 4]]
x = np.array(v)
dx = [np.array([[2.0, 3.0], [2.0, 3.0]]), np.array([[0.0, 0.0], [1.0, 1.0]])]
assert_array_equal(gradient(x), dx)
assert_array_equal(gradient(v), dx)
def test_args(self):
dx = np.cum... | TestGradient |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/qembedding_pack_test.py | {
"start": 1629,
"end": 2050
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, num_embeddings, embedding_dim, batch_size, op_func):
self.inputs = {
"weight": torch.rand(
batch_size, num_embeddings, embedding_dim, dtype=torch.float
)
+ 1
}
self.op_func = op_func
... | EmbeddingBagThreeDimFloatToFusedBase |
python | astropy__astropy | astropy/modeling/parameters.py | {
"start": 695,
"end": 821
} | class ____(ValueError, ParameterError):
"""Used for incorrect input parameter values and definitions."""
| InputParameterError |
python | pyca__cryptography | src/cryptography/hazmat/primitives/asymmetric/ec.py | {
"start": 7720,
"end": 7902
} | class ____(EllipticCurve):
name = "sect283k1"
key_size = 281
group_order = 0x1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE9AE2ED07577265DFF7F94451E061E163C61 # noqa: E501
| SECT283K1 |
python | huggingface__transformers | tests/models/afmoe/test_modeling_afmoe.py | {
"start": 3298,
"end": 4328
} | class ____(CausalLMModelTest, unittest.TestCase):
model_tester_class = AfmoeModelTester
all_model_classes = (AfmoeModel, AfmoeForCausalLM) if is_torch_available() else ()
pipeline_model_mapping = (
{"feature-extraction": AfmoeModel, "text-generation": AfmoeForCausalLM} if is_torch_available() else {... | AfmoeModelTest |
python | pennersr__django-allauth | allauth/account/admin.py | {
"start": 266,
"end": 1648
} | class ____(admin.ModelAdmin):
list_display = ("email", "user", "primary", "verified")
list_filter = ("primary", "verified")
search_fields = []
raw_id_fields = ("user",)
actions = ["make_verified"]
def get_search_fields(self, request):
base_fields = get_adapter().get_user_search_fields()... | EmailAddressAdmin |
python | huggingface__transformers | src/transformers/models/bros/modeling_bros.py | {
"start": 3187,
"end": 3808
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dim_bbox = config.dim_bbox
self.x_pos_emb = BrosPositionalEmbedding1D(config)
self.y_pos_emb = BrosPositionalEmbedding1D(config)
def forward(self, bbox: torch.Tensor) -> torch.Tensor:
stack = []
... | BrosPositionalEmbedding2D |
python | optuna__optuna | tests/artifacts_tests/test_gcs.py | {
"start": 928,
"end": 3577
} | class ____:
def __init__(self, blob_name: str) -> None:
self.blob_name = blob_name
def download_as_bytes(self) -> bytes:
return _MOCK_BUCKET_CONTENT[self.blob_name]
def upload_from_string(self, data: bytes) -> None:
_MOCK_BUCKET_CONTENT[self.blob_name] = data
@contextlib.contextm... | MockBlob |
python | python-poetry__poetry | src/poetry/installation/installer.py | {
"start": 1106,
"end": 12957
} | class ____:
def __init__(
self,
io: IO,
env: Env,
package: ProjectPackage,
locker: Locker,
pool: RepositoryPool,
config: Config,
installed: InstalledRepository | None = None,
executor: Executor | None = None,
disable_cache: bool = False... | Installer |
python | numba__llvmlite | llvmlite/binding/value.py | {
"start": 13987,
"end": 19477
} | class ____(_ValueIterator):
kind = 'block'
def _dispose(self):
self._capi.LLVMPY_DisposeIncomingBlocksIter(self)
def _next(self):
return ffi.lib.LLVMPY_IncomingBlocksIterNext(self)
# FFI
ffi.lib.LLVMPY_PrintValueToString.argtypes = [
ffi.LLVMValueRef,
POINTER(c_char_p)
]
ffi.l... | _IncomingBlocksIterator |
python | joblib__joblib | joblib/numpy_pickle.py | {
"start": 14729,
"end": 28791
} | class ____(Unpickler):
"""A subclass of the Unpickler to unpickle our numpy pickles.
Attributes
----------
mmap_mode: str
The memorymap mode to use for reading numpy arrays.
file_handle: file_like
File object to unpickle from.
ensure_native_byte_order: bool
If True, coer... | NumpyUnpickler |
python | ansible__ansible | test/units/module_utils/facts/test_facts.py | {
"start": 17602,
"end": 23266
} | class ____(unittest.TestCase):
# FIXME: mock.patch instead
def setUp(self):
# The @timeout tracebacks if there isn't a GATHER_TIMEOUT is None (the default until get_all_facts sets it via global)
facts.GATHER_TIMEOUT = 10
def tearDown(self):
facts.GATHER_TIMEOUT = None
# The Ha... | TestFactsLinuxHardwareGetMountFacts |
python | sympy__sympy | sympy/polys/series/ringflint.py | {
"start": 2270,
"end": 17652
} | class ____:
"""
Flint implementation of power series ring over integers :ref:`ZZ`.
This class provides high-performance power series operations over the integer ring,
leveraging the FLINT library for optimized arithmetic and series manipulations
precision handling and truncation.
Parameters
... | FlintPowerSeriesRingZZ |
python | walkccc__LeetCode | solutions/431. Encode N-ary Tree to Binary Tree/431-2.py | {
"start": 0,
"end": 894
} | class ____:
# Encodes an n-ary tree to a binary tree.
def encode(self, root: 'Node') -> TreeNode | None:
if not root:
return None
rootTreeNode = TreeNode(root.val)
if root.children:
rootTreeNode.left = self.encode(root.children[0])
# The parent for the rest of the children
currTree... | Codec |
python | lazyprogrammer__machine_learning_examples | rl/comparing_epsilons.py | {
"start": 386,
"end": 1820
} | class ____:
def __init__(self, m):
self.m = m
self.mean = 0
self.N = 0
def pull(self):
return np.random.randn() + self.m
def update(self, x):
self.N += 1
self.mean = (1 - 1.0/self.N)*self.mean + 1.0/self.N*x
def run_experiment(m1, m2, m3, eps, N):
bandits = [Bandit(m1), Bandit(m2), B... | Bandit |
python | getsentry__sentry | src/sentry/testutils/helpers/apigateway.py | {
"start": 763,
"end": 1009
} | class ____(ControlSiloOrganizationEndpoint):
permission_classes: tuple[type[BasePermission], ...] = (AllowAny,)
def get(self, request, organization, **kwargs):
return Response({"proxy": False})
@region_silo_endpoint
| ControlEndpoint |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance19.py | {
"start": 1890,
"end": 2140
} | class ____(metaclass=Meta2):
pass
def func9(v: type[Class2] | Iterable[type[Class2]]):
if isinstance(v, Meta2):
reveal_type(v, expected_text="type[Class2]")
else:
reveal_type(v, expected_text="Iterable[type[Class2]]")
| Class2 |
python | getsentry__sentry | src/sentry/api/bases/organizationmember.py | {
"start": 2582,
"end": 2820
} | class ____(TypedDict):
organization: Organization
user_id: NotRequired[int]
user_is_active: NotRequired[bool]
id: NotRequired[int | str]
organization_id: NotRequired[int]
invite_status: NotRequired[int]
| _FilterKwargs |
python | sqlalchemy__sqlalchemy | test/orm/test_backref_mutations.py | {
"start": 15337,
"end": 16745
} | class ____(_fixtures.FixtureTest):
run_inserts = None
@classmethod
def setup_mappers(cls):
Address, addresses, users, User = (
cls.classes.Address,
cls.tables.addresses,
cls.tables.users,
cls.classes.User,
)
cls.mapper_registry.map_im... | O2OScalarMoveTest |
python | Netflix__metaflow | metaflow/exception.py | {
"start": 1841,
"end": 2232
} | class ____(MetaflowException):
headline = "Parameter field failed"
def __init__(self, name, field):
exc = traceback.format_exc()
msg = (
"When evaluating the field *%s* for the Parameter *%s*, "
"the following exception occurred:\n\n%s" % (field, name, exc)
)
... | ParameterFieldFailed |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1533498,
"end": 1545890
} | class ____(VegaLiteSchema):
r"""
TypedFieldDef schema wrapper.
Definition object for a data field, its type and transformation of an encoding channel.
Parameters
----------
aggregate : dict, :class:`Aggregate`, :class:`ArgmaxDef`, :class:`ArgminDef`, :class:`NonArgAggregateOp`, Literal['averag... | TypedFieldDef |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 220158,
"end": 220713
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of DeleteRepositoryRuleset"""
__schema__ = github_schema
__field_names__ = ("repository_ruleset_id", "client_mutation_id")
repository_ruleset_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="repositoryRulesetId")
"""The global... | DeleteRepositoryRulesetInput |
python | MongoEngine__mongoengine | tests/fields/test_embedded_document_field.py | {
"start": 402,
"end": 7831
} | class ____(MongoDBTestCase):
def test___init___(self):
class MyDoc(EmbeddedDocument):
name = StringField()
field = EmbeddedDocumentField(MyDoc)
assert field.document_type_obj == MyDoc
field2 = EmbeddedDocumentField("MyDoc")
assert field2.document_type_obj == "My... | TestEmbeddedDocumentField |
python | getsentry__sentry | src/sentry/integrations/slack/unfurl/types.py | {
"start": 505,
"end": 616
} | class ____(enum.Enum):
ISSUES = "issues"
METRIC_ALERT = "metric_alert"
DISCOVER = "discover"
| LinkType |
python | pypa__pip | src/pip/_vendor/urllib3/exceptions.py | {
"start": 3105,
"end": 3233
} | class ____(TimeoutError):
"""Raised when a socket timeout occurs while connecting to a server"""
pass
| ConnectTimeoutError |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.