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 | run-llama__llama_index | llama-index-integrations/memory/llama-index-memory-bedrock-agentcore/llama_index/memory/bedrock_agentcore/base.py | {
"start": 771,
"end": 4578
} | class ____(BaseMemory):
"""Base class for Bedrock Agent Core Memory."""
_config: Any = PrivateAttr()
_client: Any = PrivateAttr()
_boto_client_kwargs: Any = PrivateAttr()
def __init__(self, client: Any) -> None:
super().__init__()
if client is not None:
self._client = c... | BaseAgentCoreMemory |
python | python__mypy | mypy/nodes.py | {
"start": 36906,
"end": 40030
} | class ____(SymbolNode, Statement):
"""A decorated function.
A single Decorator object can include any number of function decorators.
"""
__slots__ = ("func", "decorators", "original_decorators", "var", "is_overload")
__match_args__ = ("decorators", "var", "func")
func: FuncDef # Decorated f... | Decorator |
python | pyqtgraph__pyqtgraph | pyqtgraph/examples/DateAxisItem_QtDesigner.py | {
"start": 587,
"end": 1412
} | class ____(QtWidgets.QMainWindow, Design):
def __init__(self):
super().__init__()
self.setupUi(self)
now = time.time()
# Plot random values with timestamps in the last 6 months
timestamps = np.linspace(now - 6*30*24*3600, now, 100)
self.curve = self.plotWidget.plot(x=... | ExampleApp |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/waiters/test_comprehend.py | {
"start": 1621,
"end": 3170
} | class ____(TestComprehendCustomWaitersBase):
WAITER_NAME = "pii_entities_detection_job_complete"
@pytest.fixture
def mock_get_job(self):
with mock.patch.object(self.client, "describe_pii_entities_detection_job") as mock_getter:
yield mock_getter
@pytest.mark.parametrize("state", Co... | TestComprehendStartPiiEntitiesDetectionJobCompleteWaiter |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/executors/ecs/ecs_executor.py | {
"start": 2543,
"end": 27461
} | class ____(BaseExecutor):
"""
Executes the provided Airflow command on an ECS instance.
The Airflow Scheduler creates a shell command, and passes it to the executor. This ECS Executor
runs said Airflow command on a remote Amazon ECS Cluster with a task-definition configured to
launch the same conta... | AwsEcsExecutor |
python | numba__llvmlite | llvmlite/binding/orcjit.py | {
"start": 8036,
"end": 11856
} | class ____(ffi.ObjectRef):
"""
A OrcJIT-based LLVM JIT engine that can compile and run LLVM IR as a
collection of JITted dynamic libraries
The C++ OrcJIT API has a lot of memory ownership patterns that do not work
with Python. This API attempts to provide ones that are safe at the expense
of so... | LLJIT |
python | pandas-dev__pandas | pandas/tests/io/sas/test_sas7bdat.py | {
"start": 1086,
"end": 14818
} | class ____:
@pytest.mark.slow
def test_from_file(self, dirpath, data_test_ix):
expected, test_ix = data_test_ix
for k in test_ix:
fname = os.path.join(dirpath, f"test{k}.sas7bdat")
df = pd.read_sas(fname, encoding="utf-8")
tm.assert_frame_equal(df, expected)
... | TestSAS7BDAT |
python | PyCQA__pylint | tests/functional/u/useless/useless_parent_delegation_py38.py | {
"start": 170,
"end": 293
} | class ____(Egg):
def __init__(self, first: float, /, second: float) -> None:
super().__init__(first, second)
| Spam |
python | ray-project__ray | release/ray_release/exception.py | {
"start": 3787,
"end": 3862
} | class ____(CommandError):
exit_code = ExitCode.COMMAND_ALERT
| ResultsAlert |
python | gevent__gevent | src/gevent/libuv/watcher.py | {
"start": 1959,
"end": 3318
} | class ____(object):
# Makes sure that everything stored as a function
# on the wrapper instances (classes, actually,
# because this is used by the metaclass)
# checks its return value and raises an error.
# This expects that everything we call has an int
# or void return value and follows the co... | libuv_error_wrapper |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/missing_maxsplit_arg.py | {
"start": 162,
"end": 4730
} | class ____():
split = "1,2,3"
# Errors
## Test split called directly on string literal
"1,2,3".split(",")[0] # [missing-maxsplit-arg]
"1,2,3".split(",")[-1] # [missing-maxsplit-arg]
"1,2,3".rsplit(",")[0] # [missing-maxsplit-arg]
"1,2,3".rsplit(",")[-1] # [missing-maxsplit-arg]
## Test split called on string ... | Bar |
python | fastai__fastai | fastai/learner.py | {
"start": 24099,
"end": 24717
} | class ____(Metric):
"Use to include a pre-calculated metric value (for instance calculated in a `Callback`) and returned by `func`"
def __init__(self, func, metric_name=None): store_attr('func, metric_name')
@property
def value(self): return self.func()
@property
def name(self): return self.me... | ValueMetric |
python | joblib__joblib | joblib/test/test_memory.py | {
"start": 48714,
"end": 50660
} | class ____:
"Tests for the MemorizedFunc and NotMemorizedFunc classes"
@staticmethod
def f(x, counter):
counter[x] = counter.get(x, 0) + 1
return counter[x]
def test_call_method_memorized(self, memory):
"Test calling the function"
f = memory.cache(self.f, ignore=["coun... | TestMemorizedFunc |
python | django__django | django/urls/converters.py | {
"start": 627,
"end": 1358
} | class ____(StringConverter):
regex = ".+"
DEFAULT_CONVERTERS = {
"int": IntConverter(),
"path": PathConverter(),
"slug": SlugConverter(),
"str": StringConverter(),
"uuid": UUIDConverter(),
}
REGISTERED_CONVERTERS = {}
def register_converter(converter, type_name):
if type_name in REGIST... | PathConverter |
python | numba__numba | numba/tests/test_dictobject.py | {
"start": 49866,
"end": 51778
} | class ____(TestCase):
def test_check_untyped_dict_ops(self):
# Check operation on untyped dictionary
d = Dict()
self.assertFalse(d._typed)
self.assertEqual(len(d), 0)
self.assertEqual(str(d), str({}))
self.assertEqual(list(iter(d)), [])
# Test __getitem__
... | TestNonCompiledInfer |
python | pypa__pip | src/pip/_vendor/rich/_null_file.py | {
"start": 98,
"end": 1394
} | class ____(IO[str]):
def close(self) -> None:
pass
def isatty(self) -> bool:
return False
def read(self, __n: int = 1) -> str:
return ""
def readable(self) -> bool:
return False
def readline(self, __limit: int = 1) -> str:
return ""
def readlines(self... | NullFile |
python | langchain-ai__langchain | libs/partners/anthropic/langchain_anthropic/output_parsers.py | {
"start": 397,
"end": 3446
} | class ____(BaseGenerationOutputParser):
"""Output parser for tool calls."""
first_tool_only: bool = False
"""Whether to return only the first tool call."""
args_only: bool = False
"""Whether to return only the arguments of the tool calls."""
pydantic_schemas: list[type[BaseModel]] | None = None... | ToolsOutputParser |
python | gevent__gevent | src/gevent/tests/test__greenlet.py | {
"start": 14479,
"end": 14637
} | class ____(AbstractGenericWaitTestCase):
g = gevent.Greenlet()
def wait(self, timeout):
gevent.joinall([self.g], timeout=timeout)
| TestJoinAll0 |
python | ray-project__ray | python/ray/serve/tests/test_target_capacity.py | {
"start": 14858,
"end": 30955
} | class ____:
def check_num_replicas(
self,
expected_num_replicas: int,
app_name: str,
deployment_name: str,
replica_state: ReplicaState = ReplicaState.RUNNING,
controller_handle=None,
) -> bool:
"""Checks that the number of replicas are as expected.
... | TestTargetCapacityUpdateAndServeStatus |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 541220,
"end": 549364
} | class ____(
DatumChannelMixin, core.FieldOrDatumDefWithConditionDatumDefstringnull
):
"""
ShapeDatum schema wrapper.
Parameters
----------
bandPosition : float
Relative position on a band of a stacked, binned, time unit, or band scale. For
example, the marks will be positioned a... | ShapeDatum |
python | doocs__leetcode | solution/1600-1699/1681.Minimum Incompatibility/Solution.py | {
"start": 0,
"end": 1187
} | class ____:
def minimumIncompatibility(self, nums: List[int], k: int) -> int:
n = len(nums)
m = n // k
g = [-1] * (1 << n)
for i in range(1, 1 << n):
if i.bit_count() != m:
continue
s = set()
mi, mx = 20, 0
for j, x in e... | Solution |
python | mlflow__mlflow | mlflow/gateway/schemas/chat.py | {
"start": 2660,
"end": 3007
} | class ____(ChatMessage, ResponseModel):
# Override the `tool_call_id` field to be excluded from the response.
# This is a band-aid solution to avoid exposing the tool_call_id in the response,
# while we use the same ChatMessage model for both request and response.
tool_call_id: str | None = Field(None, ... | ResponseMessage |
python | kubernetes-client__python | kubernetes/client/models/v1_webhook_conversion.py | {
"start": 383,
"end": 5789
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1WebhookConversion |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowing7.py | {
"start": 59,
"end": 1915
} | class ____:
val: list[list[str | None]] = []
def func1(v1: list[complex | None]):
if v1[0] and v1[1]:
reveal_type(v1[0], expected_text="complex")
reveal_type(v1[1], expected_text="complex")
reveal_type(v1[2], expected_text="complex | None")
v1[0], v1[1] = None, None
re... | Foo |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-youtube-transcript/llama_index/readers/youtube_transcript/base.py | {
"start": 354,
"end": 2303
} | class ____(BasePydanticReader):
"""Youtube Transcript reader."""
is_remote: bool = True
@classmethod
def class_name(cls) -> str:
"""Get the name identifier of the class."""
return "YoutubeTranscriptReader"
def load_data(
self,
ytlinks: List[str],
languages:... | YoutubeTranscriptReader |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 53126,
"end": 53853
} | class ____(DDLEventWCreateHarness, fixtures.TestBase):
__sparse_driver_backend__ = True
__only_on__ = "postgresql > 8.3"
creates_implicitly_with_table = False
drops_implicitly_with_table = False
requires_table_to_exist = False
@testing.fixture
def produce_subject(self):
return DOM... | DomainDDLEventTest |
python | walkccc__LeetCode | solutions/933. Number of Recent Calls/933.py | {
"start": 0,
"end": 209
} | class ____:
def __init__(self):
self.q = collections.deque()
def ping(self, t: int) -> int:
self.q.append(t)
while self.q[0] < t - 3000:
self.q.popleft()
return len(self.q)
| RecentCounter |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 210444,
"end": 211477
} | class ____(TestCase):
def test_simple(self):
iterable = [0, 1, 2]
actual = list(mi.powerset_of_sets(iterable))
expected = [set(), {0}, {1}, {2}, {0, 1}, {0, 2}, {1, 2}, {0, 1, 2}]
self.assertEqual(actual, expected)
def test_hash_count(self):
hash_count = 0
class... | PowersetOfSetsTests |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/engine/characteristics.py | {
"start": 499,
"end": 2953
} | class ____(abc.ABC):
"""An abstract base for an object that can set, get and reset a
per-connection characteristic, typically one that gets reset when the
connection is returned to the connection pool.
transaction isolation is the canonical example, and the
``IsolationLevelCharacteristic`` implemen... | ConnectionCharacteristic |
python | getsentry__sentry | src/sentry/codecov/endpoints/repository_tokens/serializers.py | {
"start": 409,
"end": 2389
} | class ____(serializers.Serializer):
"""
Serializer for repository tokens response
"""
results = RepositoryTokenNodeSerializer(many=True)
pageInfo = PageInfoSerializer()
totalCount = serializers.IntegerField()
def to_representation(self, graphql_response):
"""
Transform the ... | RepositoryTokensSerializer |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_hitl.py | {
"start": 15203,
"end": 17025
} | class ____:
@pytest.mark.usefixtures("sample_hitl_detail")
def test_should_respond_200_with_existing_response(
self,
test_client: TestClient,
sample_ti_url_identifier: str,
expected_sample_hitl_detail_dict: dict[str, Any],
) -> None:
response = test_client.get(f"{samp... | TestGetHITLDetailEndpoint |
python | getsentry__sentry | tests/sentry/deletions/test_detector.py | {
"start": 614,
"end": 6114
} | class ____(BaseWorkflowTest, HybridCloudTestMixin):
def setUp(self) -> None:
self.data_condition_group = self.create_data_condition_group()
self.data_condition = self.create_data_condition(condition_group=self.data_condition_group)
self.snuba_query = self.create_snuba_query()
self.su... | DeleteDetectorTest |
python | ray-project__ray | python/ray/tune/tests/test_searchers.py | {
"start": 902,
"end": 10914
} | class ____(unittest.TestCase):
"""
Test searcher handling of invalid values (NaN, -inf, inf).
Implicitly tests automatic config conversion and default (anonymous)
mode handling.
Also tests that searcher save doesn't throw any errors during
experiment checkpointing.
"""
def setUp(self):
... | InvalidValuesTest |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/nocover/test_conjecture_int_list.py | {
"start": 824,
"end": 1659
} | class ____(RuleBasedStateMachine):
@initialize(ls=st.lists(INTEGERS))
def starting_lists(self, ls):
self.model = list(ls)
self.target = IntList(ls)
@invariant()
def lists_are_equivalent(self):
if hasattr(self, "model"):
assert isinstance(self.model, list)
... | IntListRules |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/context/invocation.py | {
"start": 7453,
"end": 32535
} | class ____(OpExecutionContext, BaseDirectExecutionContext):
"""The ``context`` object available as the first argument to an op's compute function when
being invoked directly. Can also be used as a context manager.
"""
def __init__(
self,
op_config: Any,
resources_dict: Mapping[s... | DirectOpExecutionContext |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/events/__init__.py | {
"start": 75028,
"end": 76189
} | class ____(
NamedTuple(
"_LoadedInputData",
[
("input_name", str),
("manager_key", str),
("upstream_output_name", Optional[str]),
("upstream_step_key", Optional[str]),
("metadata", Mapping[str, MetadataValue]),
],
)
):
def _... | LoadedInputData |
python | plotly__plotly.py | plotly/graph_objs/sunburst/_textfont.py | {
"start": 233,
"end": 17124
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "sunburst"
_path_str = "sunburst.textfont"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc",
"size",
"s... | Textfont |
python | pytorch__pytorch | torch/nn/modules/module.py | {
"start": 1315,
"end": 2345
} | class ____(
# pyrefly: ignore [invalid-inheritance]
namedtuple("IncompatibleKeys", ["missing_keys", "unexpected_keys"]),
):
__slots__ = ()
def __repr__(self) -> str:
# pyrefly: ignore [missing-attribute]
if not self.missing_keys and not self.unexpected_keys:
return "<All key... | _IncompatibleKeys |
python | huggingface__transformers | src/transformers/models/sew/modeling_sew.py | {
"start": 6738,
"end": 7685
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.projection = nn.Linear(config.hidden_size, config.hidden_size * config.squeeze_factor)
self.activation = ACT2FN[config.feat_extract_activation]
self.squeeze_factor = config.squeeze_factor
def forward(self... | SEWUpsampling |
python | google__jax | tests/logging_test.py | {
"start": 3247,
"end": 10239
} | class ____(jtu.JaxTestCase):
@unittest.skipIf(platform.system() == "Windows",
"Subprocess test doesn't work on Windows")
def test_no_log_spam(self):
if jtu.is_cloud_tpu() and xla_bridge._backends:
raise self.skipTest(
"test requires fresh process on Cloud TPU because only one... | LoggingTest |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/batch_prediction_job.py | {
"start": 18443,
"end": 21573
} | class ____(GoogleCloudBaseOperator):
"""
Deletes a BatchPredictionJob. Can only be called on jobs that already finished.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service belongs to.
... | DeleteBatchPredictionJobOperator |
python | kamyu104__LeetCode-Solutions | Python/maximum-points-after-collecting-coins-from-all-nodes.py | {
"start": 1236,
"end": 2080
} | class ____(object):
def maximumPoints(self, edges, coins, k):
"""
:type edges: List[List[int]]
:type coins: List[int]
:type k: int
:rtype: int
"""
def memoization(u, p, d):
if d >= max_d:
return 0
if lookup[u][d] is None... | Solution2 |
python | conda__conda | conda/exceptions.py | {
"start": 41826,
"end": 42131
} | class ____(CondaError):
def __init__(self, username: str, packagename: str, *args, **kwargs):
msg = f"{username}/{packagename} file not downloaded"
self.username = username
self.packagename = packagename
super().__init__(msg, *args, **kwargs)
| EnvironmentFileNotDownloaded |
python | pypa__setuptools | setuptools/_distutils/errors.py | {
"start": 2576,
"end": 2737
} | class ____(DistutilsError):
"""Any problems executing an external program (such as the C
compiler, when compiling C files)."""
pass
| DistutilsExecError |
python | jina-ai__jina | jina/helper.py | {
"start": 31016,
"end": 47294
} | class ____:
"""Class for cache invalidation, remove strategy.
:param func: func to wrap as a decorator.
:param attribute: String as the function name to invalidate cached
data. E.g. in :class:`cached_property` we cache data inside the class obj
with the `key`: `CACHED_{func.__name__}`, the ... | _cache_invalidate |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_use_orig_params.py | {
"start": 54739,
"end": 55608
} | class ____(FSDPTest):
@skip_if_lt_x_gpu(2)
def test_non_uniform_requires_grad(self):
model = nn.Sequential(
nn.Linear(3, 3, device=device_type),
nn.Linear(3, 3, device=device_type),
)
# Freeze biases only and flatten both weights and biases into the same
#... | TestFSDPUseOrigParamsInit |
python | Pylons__pyramid | tests/test_integration.py | {
"start": 19149,
"end": 20490
} | class ____(IntegrationBase, unittest.TestCase):
package = 'tests.pkgs.exceptionviewapp'
root_factory = lambda *arg: excroot
def test_root(self):
res = self.testapp.get('/', status=200)
self.assertTrue(b'maybe' in res.body)
def test_notanexception(self):
res = self.testapp.get('... | TestExceptionViewsApp |
python | django__django | django/test/testcases.py | {
"start": 62796,
"end": 63114
} | class ____(FSFilesHandler):
"""
Handler for serving the media files. A private class that is meant to be
used solely as a convenience by LiveServerThread.
"""
def get_base_dir(self):
return settings.MEDIA_ROOT
def get_base_url(self):
return settings.MEDIA_URL
| _MediaFilesHandler |
python | sanic-org__sanic | sanic/pages/css.py | {
"start": 525,
"end": 1105
} | class ____(ABCMeta):
"""Cascade stylesheets, i.e. combine all ancestor styles"""
def __new__(cls, name, bases, attrs):
Page = super().__new__(cls, name, bases, attrs)
# Use a locally defined STYLE or the one from styles directory
Page.STYLE = _extract_style(attrs.get("STYLE_FILE"), name... | CSS |
python | marshmallow-code__marshmallow | tests/test_schema.py | {
"start": 73958,
"end": 75399
} | class ____:
class MySchema(Schema):
class Meta:
load_only = ("str_load_only",)
dump_only = ("str_dump_only",)
str_dump_only = fields.String()
str_load_only = fields.String()
str_regular = fields.String()
@pytest.fixture
def schema(self):
retu... | TestLoadOnly |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/event_log/sqlite/sqlite_event_log.py | {
"start": 2372,
"end": 21684
} | class ____(SqlEventLogStorage, ConfigurableClass):
"""SQLite-backed event log storage.
Users should not directly instantiate this class; it is instantiated by internal machinery when
``dagster-webserver`` and ``dagster-graphql`` load, based on the values in the ``dagster.yaml`` file insqliteve
``$DAGST... | SqliteEventLogStorage |
python | dagster-io__dagster | examples/docs_projects/project_dagster_modal_pipes/src/modal_project/config.py | {
"start": 74,
"end": 1755
} | class ____:
name: str
params: str
relative_speed: int # Higher is faster
def get_logger(name, level=logging.INFO):
logger = logging.getLogger(name)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(levelname)s: %(asctime)s: %(name)s %(message)s"))
logger.addHand... | ModelSpec |
python | openai__openai-python | src/openai/resources/beta/realtime/transcription_sessions.py | {
"start": 6829,
"end": 12886
} | class ____(AsyncAPIResource):
@cached_property
def with_raw_response(self) -> AsyncTranscriptionSessionsWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
the raw response object instead of the parsed content.
For more information, see ... | AsyncTranscriptionSessions |
python | pytorch__pytorch | torch/testing/_internal/common_pruning.py | {
"start": 11111,
"end": 12485
} | class ____(nn.Module):
r"""Model with Conv2d layers, all with bias, some in a Sequential and some following, and then a Pool2d
and a Flatten module followed by a Linear layer.
Activation functions and Pool2ds in between each layer also.
Used to test pruned Conv2d-Pool2d-Flatten-Linear fusion."""
de... | Conv2dPoolFlatten |
python | sympy__sympy | sympy/stats/crv.py | {
"start": 2210,
"end": 2826
} | class ____(ProductDomain, ContinuousDomain):
"""
A collection of independent domains with continuous support
"""
def compute_expectation(self, expr, variables=None, **kwargs):
if variables is None:
variables = self.symbols
for domain in self.domains:
domain_vars ... | ProductContinuousDomain |
python | PyCQA__pylint | tests/functional/a/arguments_differ.py | {
"start": 5065,
"end": 5163
} | class ____(ParentT2):
async def func(self, user_input: typing.List) -> None:
pass
| ChildT2 |
python | wepe__MachineLearning | DeepLearning Tutorials/FaceRecognition_CNN(olivettifaces)/train_CNN_olivettifaces.py | {
"start": 2472,
"end": 3631
} | class ____(object):
def __init__(self, input, n_in, n_out):
self.W = theano.shared(
value=numpy.zeros(
(n_in, n_out),
dtype=theano.config.floatX
),
name='W',
borrow=True
)
self.b = theano.shared(
valu... | LogisticRegression |
python | getsentry__sentry-python | tests/test_conftest.py | {
"start": 1716,
"end": 1896
} | class ____: # noqa: B903
def __init__(self, name=None, age=None, description=None):
self.name = name
self.age = age
self.description = description
| Animal |
python | pytorch__pytorch | test/distributed/test_c10d_nccl.py | {
"start": 249140,
"end": 255116
} | class ____(MultiProcessTestCase):
def _create_process_group_nccl(self, store, opts, device_id=None):
# create nccl processgroup with opts
c10d.init_process_group(
"nccl",
world_size=self.world_size,
rank=self.rank,
store=store,
pg_options=o... | ProcessGroupNCCLLargerScaleTest |
python | graphql-python__graphene | graphene/tests/issues/test_1293.py | {
"start": 160,
"end": 496
} | class ____(graphene.InputObjectType):
datetime_after = graphene.DateTime(
required=False,
default_value=datetime.fromtimestamp(1434549820.776, timezone.utc),
)
datetime_before = graphene.DateTime(
required=False,
default_value=datetime.fromtimestamp(1444549820.776, timezone.u... | Filters |
python | numba__numba | numba/tests/test_compiler_lock.py | {
"start": 160,
"end": 511
} | class ____(TestCase):
def test_gcl_as_context_manager(self):
with global_compiler_lock:
require_global_compiler_lock()
def test_gcl_as_decorator(self):
@global_compiler_lock
def func():
require_global_compiler_lock()
func()
if __name__ == '__main__':
... | TestCompilerLock |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py | {
"start": 53891,
"end": 55058
} | class ____(BaseModel):
type: Literal["ListPartitionRouter"]
cursor_field: str = Field(
...,
description='While iterating over list values, the name of field used to reference a list value. The partition value can be accessed with string interpolation. e.g. "{{ stream_partition[\'my_key\'] }}" wh... | ListPartitionRouter |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/data_asset/path/file_asset.py | {
"start": 1392,
"end": 1730
} | class ____(ValueError):
def __init__(self, missing_groups: set[str]):
message = (
"The following group(s) are required but are "
f"missing from the regex: {', '.join(missing_groups)}"
)
super().__init__(message)
self.missing_groups = missing_groups
| RegexMissingRequiredGroupsError |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/tokens.py | {
"start": 8993,
"end": 9061
} | class ____(Token):
__slots__ = ()
id = '}'
| FlowMappingEndToken |
python | getsentry__sentry | src/sentry/ratelimits/leaky_bucket.py | {
"start": 486,
"end": 840
} | class ____:
burst_limit: int # maximum number of requests allowed in a burst
drip_rate: int # number of requests allowed per second
last_drip: float = 0 # unix timestamp of the last drip
current_level: float = 0 # current level of the bucket
wait_time: float = 0 # seconds to wait until next req... | LeakyBucketLimitInfo |
python | tensorflow__tensorflow | third_party/xla/build_tools/lint/diff_parser_test.py | {
"start": 776,
"end": 4084
} | class ____(absltest.TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
testdata = test_utils.xla_src_root() / "build_tools" / "lint" / "testdata"
with (testdata / "bad_cc.diff").open() as f:
cls.bad_cc_diff = f.read()
with (testdata / "important_cc.diff").open() as f:
... | ParseDiffTest |
python | cython__cython | Demos/benchmarks/bm_raytrace.py | {
"start": 406,
"end": 2435
} | class ____(object):
def __init__(self, initx, inity, initz):
self.x = initx
self.y = inity
self.z = initz
def __str__(self):
return '(%s,%s,%s)' % (self.x, self.y, self.z)
def __repr__(self):
return 'Vector(%s,%s,%s)' % (self.x, self.y, self.z)
def magnitude(s... | Vector |
python | eventlet__eventlet | tests/db_pool_test.py | {
"start": 9984,
"end": 10046
} | class ____:
def rollback(self):
pass
| DummyConnection |
python | keras-team__keras | keras/src/metrics/iou_metrics.py | {
"start": 15690,
"end": 19272
} | class ____(IoU):
"""Computes the mean Intersection-Over-Union metric.
Formula:
```python
iou = true_positives / (true_positives + false_positives + false_negatives)
```
Intersection-Over-Union is a common evaluation metric for semantic image
segmentation.
To compute IoUs, the predicti... | MeanIoU |
python | getsentry__sentry | src/sentry/integrations/discord/actions/issue_alert/form.py | {
"start": 543,
"end": 2920
} | class ____(forms.Form):
# NOTE: server (guild id) maps directly to the integration ID
server = forms.ChoiceField(choices=(), widget=forms.Select())
channel_id = forms.CharField(widget=forms.TextInput())
tags = forms.CharField(required=False, widget=forms.TextInput())
def __init__(self, *args: Any, ... | DiscordNotifyServiceForm |
python | pandas-dev__pandas | pandas/tests/test_nanops.py | {
"start": 27464,
"end": 29536
} | class ____:
def test_numeric_values(self):
# Test integer
assert nanops._ensure_numeric(1) == 1
# Test float
assert nanops._ensure_numeric(1.1) == 1.1
# Test complex
assert nanops._ensure_numeric(1 + 2j) == 1 + 2j
def test_ndarray(self):
# Test numeric ... | TestEnsureNumeric |
python | huggingface__transformers | src/transformers/models/grounding_dino/modeling_grounding_dino.py | {
"start": 7346,
"end": 12393
} | class ____(ModelOutput):
r"""
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the decoder of the model.
init_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
... | GroundingDinoModelOutput |
python | apache__airflow | providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/executors/local_kubernetes_executor.py | {
"start": 1751,
"end": 12243
} | class ____(BaseExecutor):
"""
Chooses between LocalExecutor and KubernetesExecutor based on the queue defined on the task.
When the task's queue is the value of ``kubernetes_queue`` in section ``[local_kubernetes_executor]``
of the configuration (default value: `kubernetes`), KubernetesExecutor is sele... | LocalKubernetesExecutor |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_unshard_params.py | {
"start": 1400,
"end": 8094
} | class ____(FSDPTest):
"""
This contains any methods common to both the sharded and non-sharded cases.
"""
def _test_unshard_params_writeback(
self,
writeback: bool,
check_outer: bool,
**fsdp_kwargs: dict[str, Any],
):
model = nn.Sequential(
nn.Lin... | TestUnshardParamsBase |
python | ray-project__ray | rllib/offline/output_writer.py | {
"start": 461,
"end": 660
} | class ____(OutputWriter):
"""Output writer that discards its outputs."""
@override(OutputWriter)
def write(self, sample_batch: SampleBatchType):
# Do nothing.
pass
| NoopOutput |
python | huggingface__transformers | src/transformers/models/longt5/modeling_longt5.py | {
"start": 45419,
"end": 46712
} | class ____(nn.Module):
def __init__(self, config, has_relative_attention_bias=False, layer_idx: Optional[int] = None):
super().__init__()
self.SelfAttention = LongT5Attention(
config, has_relative_attention_bias=has_relative_attention_bias, layer_idx=layer_idx
)
self.laye... | LongT5LayerSelfAttention |
python | django__django | tests/sitemaps_tests/urls/http.py | {
"start": 2980,
"end": 3152
} | class ____(Sitemap):
location = "/location/"
def items(self):
return []
def lastmod(self, obj):
return obj.lastmod
| CallableLastmodNoItemsSitemap |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_display_units11.py | {
"start": 315,
"end": 1177
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_display_units11.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(... | TestCompareXLSXFiles |
python | PyCQA__pylint | tests/functional/ext/no_self_use/no_self_use.py | {
"start": 1459,
"end": 1869
} | class ____(Super):
"""override method with need for self"""
def method(self):
"""no i can not be a function"""
print(42)
def __len__(self):
"""no i can not be a function"""
return 42
def __cmp__(self, other):
"""no i can not be a function"""
print(42)
... | Sub1 |
python | plotly__plotly.py | plotly/graph_objs/layout/ternary/aaxis/_tickfont.py | {
"start": 235,
"end": 9925
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.ternary.aaxis"
_path_str = "layout.ternary.aaxis.tickfont"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
... | Tickfont |
python | sphinx-doc__sphinx | sphinx/domains/c/_ast.py | {
"start": 16425,
"end": 17478
} | class ____(ASTExpression):
def __init__(self, op: str, expr: ASTExpression) -> None:
self.op = op
self.expr = expr
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTUnaryOpExpr):
return NotImplemented
return self.op == other.op and self.expr == oth... | ASTUnaryOpExpr |
python | instagram__MonkeyType | demo/inbox.py | {
"start": 2709,
"end": 3430
} | class ____(AggregatorInterface[FollowedEvent]):
type = EventType.FOLLOWED
def __init__(self, repo: RepoInterface) -> None:
self.events: List[FollowedEvent] = []
self.user_ids: Set[UserId] = set()
super().__init__(repo)
def add(self, event):
self.events.append(event)
... | FollowersAggregator |
python | walkccc__LeetCode | solutions/2565. Subsequence With the Minimum Score/2565.py | {
"start": 0,
"end": 1465
} | class ____:
def minimumScore(self, s: str, t: str) -> int:
# leftmost[j] := the minimum index i s.t. t[0..j] is a subsequence of s[0..i].
# -1 := impossible
leftmost = [-1] * len(t)
# rightmost[j] := the maximum index i s.t. t[j:] is a subsequence of s[i..n).
# -1 := impossible
... | Solution |
python | tensorflow__tensorflow | tensorflow/python/distribute/mirrored_values_test.py | {
"start": 3945,
"end": 9295
} | class ____(test.TestCase, parameterized.TestCase):
def _assign_mirrored(self, v, new):
for var, n in zip(v.values, new):
self.evaluate(var.assign(n))
def _save_return_saver(self, sess, var):
saver = saver_lib.Saver(var_list=[var])
test_dir = self.get_temp_dir()
prefix = os.path.join(test_dir... | MirroredVariableSaveRestoreTest |
python | pypa__warehouse | tests/unit/admin/views/test_projects.py | {
"start": 6589,
"end": 9359
} | class ____:
def test_add_observation(self, db_request):
release = ReleaseFactory.create()
user = UserFactory.create()
db_request.route_path = pretend.call_recorder(
lambda *a, **kw: "/admin/projects/"
)
db_request.matchdict["project_name"] = release.project.normal... | TestReleaseAddObservation |
python | walkccc__LeetCode | solutions/2940. Find Building Where Alice and Bob Can Meet/2940.py | {
"start": 47,
"end": 220
} | class ____:
queryIndex: int
a: int # Alice's index
b: int # Bob's index
def __iter__(self):
yield self.queryIndex
yield self.a
yield self.b
| IndexedQuery |
python | dabeaz-course__practical-python | Work/Data/stocksim.py | {
"start": 5060,
"end": 5152
} | class ____(object):
def update(self,record):
print(csv_record(record))
| BasicPrinter |
python | django-crispy-forms__django-crispy-forms | crispy_forms/bootstrap.py | {
"start": 35471,
"end": 37901
} | class ____(LayoutObject):
"""
Bootstrap layout object for rendering crispy forms objects inside a
bootstrap modal.
Attributes
----------
template : str
The default template which this Layout Object will be rendered
with.
Parameters
----------
*fields : str
T... | Modal |
python | pydata__xarray | xarray/core/_aggregations.py | {
"start": 180197,
"end": 235067
} | class ____:
_obj: Dataset
def reduce(
self,
func: Callable[..., Any],
dim: Dims = None,
*,
axis: int | Sequence[int] | None = None,
keep_attrs: bool | None = None,
keepdims: bool = False,
**kwargs: Any,
) -> Dataset:
raise NotImplement... | DatasetResampleAggregations |
python | kamyu104__LeetCode-Solutions | Python/convert-to-base-2.py | {
"start": 380,
"end": 767
} | class ____(object):
def baseNeg2(self, N):
"""
:type N: int
:rtype: str
"""
BASE = -2
result = []
while N:
N, r = divmod(N, BASE)
if r < 0:
r -= BASE
N += 1
result.append(str(r))
resul... | Solution2 |
python | django__django | tests/model_inheritance_regress/models.py | {
"start": 48,
"end": 212
} | class ____(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
class Meta:
ordering = ("name",)
| Place |
python | geekcomputers__Python | Snake_water_gun/main.py | {
"start": 276,
"end": 2735
} | class ____:
HEADERS = "\033[95m"
OKBLUE = "\033[94m"
OKGREEN = "\033[93m"
WARNING = "\033[92m"
FAIL = "\033[91m"
ENDC = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
run = True
li = ["s", "w", "g"]
while True:
system("clear")
b = input(
bcolors.OKBLUE
+ bcol... | bcolors |
python | astropy__astropy | astropy/io/registry/tests/test_registries.py | {
"start": 10143,
"end": 25256
} | class ____(TestUnifiedIORegistryBase):
"""Test :class:`astropy.io.registry.UnifiedInputRegistry`."""
def setup_class(self):
"""Setup class. This is called 1st by pytest."""
self._cls = UnifiedInputRegistry
# ===========================================
def test_inherited_read_registrat... | TestUnifiedInputRegistry |
python | oauthlib__oauthlib | tests/openid/connect/core/grant_types/test_hybrid.py | {
"start": 386,
"end": 639
} | class ____(AuthorizationCodeGrantTest):
"""Test that OpenID don't interfere with normal OAuth 2 flows."""
def setUp(self):
super().setUp()
self.auth = HybridGrant(request_validator=self.mock_validator)
| OpenIDHybridInterferenceTest |
python | sympy__sympy | sympy/physics/quantum/tests/test_innerproduct.py | {
"start": 702,
"end": 936
} | class ____(Ket, FooState):
@classmethod
def dual_class(self):
return FooBra
def _eval_innerproduct_FooBra(self, bra):
return Integer(1)
def _eval_innerproduct_BarBra(self, bra):
return I
| FooKet |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/convolutional.py | {
"start": 124320,
"end": 126087
} | class ____(Layer):
"""Cropping layer for 1D input (e.g. temporal sequence).
It crops along the time dimension (axis 1).
Examples:
>>> input_shape = (2, 3, 2)
>>> x = np.arange(np.prod(input_shape)).reshape(input_shape)
>>> print(x)
[[[ 0 1]
[ 2 3]
[ 4 5]]
[[ 6 7]
[ 8 9]
[10 11]]... | Cropping1D |
python | PrefectHQ__prefect | src/prefect/server/events/schemas/automations.py | {
"start": 7959,
"end": 15630
} | class ____(ResourceTrigger):
"""
A trigger that fires based on the presence or absence of events within a given
period of time.
"""
type: Literal["event"] = "event"
after: Set[str] = Field(
default_factory=set,
description=(
"The event(s) which must first been seen ... | EventTrigger |
python | openai__openai-python | src/openai/_base_client.py | {
"start": 7761,
"end": 8889
} | class ____(Generic[_T, AsyncPageT]):
def __init__(
self,
client: AsyncAPIClient,
options: FinalRequestOptions,
page_cls: Type[AsyncPageT],
model: Type[_T],
) -> None:
self._model = model
self._client = client
self._options = options
self._p... | AsyncPaginator |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataplex.py | {
"start": 106402,
"end": 110183
} | class ____(DataplexCatalogBaseOperator):
"""
List EntryGroup resources.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:DataplexCatalogListEntryGroupsOperator`
:param filter_by: Optional. Filter to apply on the list results.... | DataplexCatalogListEntryGroupsOperator |
python | sympy__sympy | sympy/physics/quantum/qft.py | {
"start": 2817,
"end": 4768
} | class ____(Gate):
"""Superclass of Quantum Fourier and Inverse Quantum Fourier Gates."""
@classmethod
def _eval_args(self, args):
if len(args) != 2:
raise QuantumError(
'QFT/IQFT only takes two arguments, got: %r' % args
)
if args[0] >= args[1]:
... | Fourier |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.