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 | django-mptt__django-mptt | tests/myapp/models.py | {
"start": 7808,
"end": 8048
} | class ____(models.Model):
name = models.CharField(max_length=100)
TreeForeignKey(
Group, blank=True, null=True, on_delete=models.CASCADE
).contribute_to_class(Group, "parent")
mptt.register(Group, order_insertion_by=("name",))
| Group |
python | spack__spack | lib/spack/spack/vendor/jsonschema/validators.py | {
"start": 18978,
"end": 29452
} | class ____(object):
"""
Resolve JSON References.
Arguments:
base_uri (str):
The URI of the referring document
referrer:
The actual referring document
store (dict):
A mapping from URIs to documents to cache
cache_remote (bool):
... | RefResolver |
python | tensorflow__tensorflow | tensorflow/python/distribute/integration_test/saved_model_test.py | {
"start": 20974,
"end": 26476
} | class ____(test.TestCase):
# Test saved_model saving and loading for parameter server strategy. These
# tests are different enough than the tests in `SaveAndLoadForXXX` so we make
# a separate test class for them.
@classmethod
def setUpClass(cls):
super().setUpClass()
cluster_def = multi_worker_test_... | PSStrategySaveAndLoadTest |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/graphql_callees.py | {
"start": 367,
"end": 1669
} | class ____:
x: str
def __init__(self, x) -> None:
self.x = x
@method_decorator
def callee(self) -> None:
_test_sink(self)
# This should not be called
def not_callee(self) -> None:
_test_sink(self)
def entrypoint_decorator(callable: Callable[[Any], Any]) -> Callable[[... | GraphQLEntrypoint |
python | mlflow__mlflow | mlflow/genai/judges/utils/prompt_utils.py | {
"start": 379,
"end": 3607
} | class ____(NamedTuple):
"""Result of splitting ChatMessage list for Databricks API."""
system_prompt: str | None
user_prompt: str
def format_prompt(prompt: str, **values) -> str:
"""Format double-curly variables in the prompt template."""
for key, value in values.items():
# Escape backsla... | DatabricksLLMJudgePrompts |
python | huggingface__transformers | tests/models/vision_encoder_decoder/test_modeling_vision_encoder_decoder.py | {
"start": 38374,
"end": 43433
} | class ____(EncoderDecoderMixin, unittest.TestCase):
supports_sdpa = True # both submodels support SDPA
def get_encoder_decoder_model(self, config, decoder_config):
encoder_model = ViTModel(config).eval()
decoder_model = GPT2LMHeadModel(decoder_config).eval()
return encoder_model, decod... | VIT2GPT2Test |
python | readthedocs__readthedocs.org | readthedocs/metrics/tasks.py | {
"start": 839,
"end": 1093
} | class ____(Metrics1mTaskBase):
metrics = Metrics1mTaskBase.metrics + [
RedislenMetric(queue_name="build-large"),
RunningBuildsMetric(builder="large"),
ConcurrencyLimitedBuildsMetric(builder="large"),
]
| CommunityMetrics1mTask |
python | mahmoud__glom | glom/core.py | {
"start": 62608,
"end": 63526
} | class ____:
"""
:class:`Vars` is a helper that can be used with **S** in order to
store shared mutable state.
Takes the same arguments as :class:`dict()`.
Arguments here should be thought of the same way as default arguments
to a function. Each time the spec is evaluated, the same arguments
... | Vars |
python | jazzband__django-simple-history | simple_history/registry_tests/tests.py | {
"start": 3038,
"end": 3500
} | class ____(TestCase):
def test_using_app_label(self):
try:
from ..tests.models import HistoricalConcreteExternal
except ImportError:
self.fail("HistoricalConcreteExternal is in wrong module")
def test_default(self):
try:
from ..tests.models import His... | TestInheritedModule |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/auth/managers/models/resource_details.py | {
"start": 1570,
"end": 1687
} | class ____:
"""Represents the details of an asset alias."""
id: str | None = None
@dataclass
| AssetAliasDetails |
python | gevent__gevent | src/gevent/tests/test__greenio.py | {
"start": 1544,
"end": 5523
} | class ____(TestCase):
def test_close_with_makefile(self):
def accept_close_early(listener):
# verify that the makefile and the socket are truly independent
# by closing the socket prior to using the made file
try:
conn, _ = listener.accept()
... | TestGreenIo |
python | keon__algorithms | tests/test_matrix.py | {
"start": 6361,
"end": 7201
} | class ____(unittest.TestCase):
"""[summary]
Test for the file matrix_exponentiation.py
Arguments:
unittest {[type]} -- [description]
"""
def test_matrix_exponentiation(self):
mat = [[1, 0, 2], [2, 1, 0], [0, 2, 1]]
self.assertEqual(matrix_exponentiation.matrix_exponentiati... | TestMatrixExponentiation |
python | RaRe-Technologies__gensim | gensim/models/doc2vec.py | {
"start": 4714,
"end": 5632
} | class ____(namedtuple('TaggedDocument', 'words tags')):
"""Represents a document along with a tag, input document format for :class:`~gensim.models.doc2vec.Doc2Vec`.
A single document, made up of `words` (a list of unicode string tokens) and `tags` (a list of tokens).
Tags may be one or more unicode string... | TaggedDocument |
python | python-markdown__markdown | tests/test_legacy.py | {
"start": 1151,
"end": 1240
} | class ____(LegacyTestCase):
location = os.path.join(parent_test_dir, 'basic')
| TestBasic |
python | django__django | tests/flatpages_tests/test_middleware.py | {
"start": 2458,
"end": 5830
} | class ____(TestDataMixin, TestCase):
def test_view_flatpage(self):
"""
A flatpage can be served through a view, even when the middleware is in
use
"""
response = self.client.get("/flatpage_root/flatpage/")
self.assertContains(response, "<p>Isn't it flat!</p>")
de... | FlatpageMiddlewareTests |
python | pytorch__pytorch | torch/ao/ns/_numeric_suite_fx.py | {
"start": 4438,
"end": 8590
} | class ____(nn.Module):
"""
Base class for capturing intermediate values.
"""
stats: list[torch.Tensor]
stats_rnn: list[RNNReturnType]
# Mark as impure so that calls to it will not be removed during DCE.
_is_impure = True
def __init__(
self,
ref_node_name: str,
... | OutputLogger |
python | pytorch__pytorch | torch/_dynamo/utils.py | {
"start": 74015,
"end": 74559
} | class ____:
"""Remove a global variable when hook is called"""
scope: dict[str, Any]
name: str
def __call__(self, *args: Any) -> None:
# Make sure we're not shutting down
if CleanupManager is not None:
CleanupManager.count -= 1
del self.scope[self.name]
@static... | CleanupHook |
python | pypa__pip | src/pip/_internal/commands/uninstall.py | {
"start": 711,
"end": 3868
} | class ____(Command, SessionCommandMixin):
"""
Uninstall packages.
pip is able to uninstall most installed packages. Known exceptions are:
- Pure distutils packages installed with ``python setup.py install``, which
leave behind no metadata to determine what files were installed.
- Script wrap... | UninstallCommand |
python | squidfunk__mkdocs-material | material/plugins/group/config.py | {
"start": 1411,
"end": 1513
} | class ____(Config):
enabled = Type(bool, default = False)
plugins = Type((list, dict))
| GroupConfig |
python | mlflow__mlflow | dev/clint/src/clint/rules/forbidden_trace_ui_in_notebook.py | {
"start": 36,
"end": 422
} | class ____(Rule):
def _message(self) -> str:
return (
"Found the MLflow Trace UI iframe in the notebook. "
"The trace UI in cell outputs will not render correctly in previews or the website. "
"Please run `mlflow.tracing.disable_notebook_display()` and rerun the cell "
... | ForbiddenTraceUIInNotebook |
python | kamyu104__LeetCode-Solutions | Python/sum-of-digits-in-base-k.py | {
"start": 32,
"end": 285
} | class ____(object):
def sumBase(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
result = 0
while n:
n, r = divmod(n, k)
result += r
return result
| Solution |
python | allegroai__clearml | clearml/utilities/gpu/pynvml.py | {
"start": 55671,
"end": 56033
} | class ____(_PrintableStructure):
_fields_ = [
('engineId', c_uint),
('schedulerPolicy', c_uint),
('isEnabledARR', c_uint),
('schedulerParams', c_nvmlVgpuSchedulerParams_t),
('entriesCount', c_uint),
('logEntries', c_nvmlVgpuSchedulerLogEntry_t * NVML_SCHEDULER_SW_MAX_... | c_nvmlVgpuSchedulerLog_t |
python | pypa__installer | src/installer/scripts.py | {
"start": 1154,
"end": 1272
} | class ____(ValueError):
"""Raised if the user provides incorrect script section or kind."""
@dataclass
| InvalidScript |
python | ray-project__ray | python/ray/data/_internal/block_batching/util.py | {
"start": 9700,
"end": 10480
} | class ____(BlockPrefetcher):
"""Block prefetcher using a local actor."""
def __init__(self):
self.prefetch_actor = self._get_or_create_actor_prefetcher()
@staticmethod
def _get_or_create_actor_prefetcher() -> "ActorHandle":
node_id = ray.get_runtime_context().get_node_id()
acto... | ActorBlockPrefetcher |
python | pypa__pip | src/pip/_vendor/packaging/_parser.py | {
"start": 1043,
"end": 10221
} | class ____(NamedTuple):
name: str
url: str
extras: list[str]
specifier: str
marker: MarkerList | None
# --------------------------------------------------------------------------------------
# Recursive descent parser for dependency specifier
# -----------------------------------------------------... | ParsedRequirement |
python | pytorch__pytorch | test/ao/sparsity/test_structured_sparsifier.py | {
"start": 905,
"end": 1084
} | class ____(BaseStructuredSparsifier):
def update_mask(self, module, tensor_name, **kwargs):
getattr(module.parametrizations, tensor_name)[0].mask[1] = False
| SimplePruner |
python | huggingface__transformers | src/transformers/models/lfm2_moe/modeling_lfm2_moe.py | {
"start": 8522,
"end": 10438
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.top_k = config.num_experts_per_tok
self.routed_scaling_factor = config.routed_scaling_factor
self.norm_topk_prob = config.norm_topk_prob
self.use_expert_bias = config.use_expert_bias
self.gate... | Lfm2MoeSparseMoeBlock |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclass6.py | {
"start": 827,
"end": 1085
} | class ____:
prop_1: str
prop_2: str
prop_3: str = field(default="")
prop_4: str = field(init=False)
prop_5: str = field(init=False)
def __post_init__(self):
cprop_1 = "calculated value"
cprop_2 = "calculated value"
| ClassB |
python | huggingface__transformers | src/transformers/models/kosmos2/modeling_kosmos2.py | {
"start": 18192,
"end": 22246
} | class ____(nn.Module):
"""
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
[`Kosmos2VisionEncoderLayer`].
Args:
config: Kosmos2VisionConfig
"""
def __init__(self, config: Kosmos2VisionConfig):
super().__init__()
self.c... | Kosmos2VisionEncoder |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_internal/network/session.py | {
"start": 10261,
"end": 18741
} | class ____(requests.Session):
timeout: Optional[int] = None
def __init__(
self,
*args: Any,
retries: int = 0,
cache: Optional[str] = None,
trusted_hosts: Sequence[str] = (),
index_urls: Optional[List[str]] = None,
ssl_context: Optional["SSLContext"] = Non... | PipSession |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_Y.py | {
"start": 1540,
"end": 2839
} | class ____(Benchmark):
r"""
Yao-Liu 9 objective function.
This class defines the Yao-Liu [1]_ function 9 global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{YaoLiu09}}(x) = \sum_{i=1}^n \left [ x_i^2
... | YaoLiu09 |
python | apache__airflow | airflow-core/tests/unit/jobs/test_triggerer_job.py | {
"start": 43394,
"end": 46522
} | class ____:
def test_message_types_in_triggerer(self):
"""
Test that ToSupervisor is a superset of ToTriggerSupervisor and ToTask is a superset of ToTriggerRunner.
This test ensures that when new message types are added to ToSupervisor or ToTask,
they are also properly handled in To... | TestTriggererMessageTypes |
python | python-poetry__poetry | src/poetry/puzzle/provider.py | {
"start": 2259,
"end": 3138
} | class ____(Exception):
"""
Exception when there are duplicate dependencies with incompatible constraints.
"""
def __init__(
self, package: Package, *dependencies: Dependency, with_sources: bool = False
) -> None:
constraints = []
for dep in dependencies:
constrai... | IncompatibleConstraintsError |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 181724,
"end": 182370
} | class ____:
def test_zero(self):
assert_equal(stats.expon.pdf(0), 1)
def test_tail(self): # Regression test for ticket 807
assert_equal(stats.expon.cdf(1e-18), 1e-18)
assert_equal(stats.expon.isf(stats.expon.sf(40)), 40)
def test_nan_raises_error(self):
# see gh-issue 1030... | TestExpon |
python | getsentry__sentry | src/sentry/models/deploy.py | {
"start": 464,
"end": 3549
} | class ____(Model):
__relocation_scope__ = RelocationScope.Excluded
organization_id = BoundedBigIntegerField(db_index=True)
release = FlexibleForeignKey("sentry.Release")
environment_id = BoundedPositiveIntegerField(db_index=True)
date_finished = models.DateTimeField(default=timezone.now, db_index=T... | Deploy |
python | doocs__leetcode | solution/2400-2499/2453.Destroy Sequential Targets/Solution.py | {
"start": 0,
"end": 318
} | class ____:
def destroyTargets(self, nums: List[int], space: int) -> int:
cnt = Counter(v % space for v in nums)
ans = mx = 0
for v in nums:
t = cnt[v % space]
if t > mx or (t == mx and v < ans):
ans = v
mx = t
return ans
| Solution |
python | pytorch__pytorch | test/test_maskedtensor.py | {
"start": 21883,
"end": 35072
} | class ____(TestCase):
def test_max_not_implemented(self):
d = torch.tensor([[0, 1, 2], [3, 4, 5.0]])
m = torch.tensor([[True, False, False], [False, True, False]])
mt = masked_tensor(d, m)
with self.assertRaisesRegex(TypeError, "torch._ops.aten.max.default"):
mt.max()
... | TestReductions |
python | imageio__imageio | tests/test_grab.py | {
"start": 855,
"end": 2603
} | class ____:
has_clipboard = True
@classmethod
def grab(cls):
return np.zeros((8, 8, 3), np.uint8)
@classmethod
def grabclipboard(cls):
if cls.has_clipboard:
return np.zeros((9, 9, 3), np.uint8)
else:
return None
def test_grab_simulated():
# Har... | FakeImageGrab |
python | cython__cython | docs/examples/tutorial/pure/cclass.py | {
"start": 31,
"end": 398
} | class ____:
cython.declare(a=cython.int, b=cython.int)
c = cython.declare(cython.int, visibility='public')
d = cython.declare(cython.int) # private by default.
e = cython.declare(cython.int, visibility='readonly')
def __init__(self, a, b, c, d=5, e=3):
self.a = a
self.b = b
... | A |
python | openai__openai-python | src/openai/types/moderation.py | {
"start": 3133,
"end": 4983
} | class ____(BaseModel):
harassment: List[Literal["text"]]
"""The applied input type(s) for the category 'harassment'."""
harassment_threatening: List[Literal["text"]] = FieldInfo(alias="harassment/threatening")
"""The applied input type(s) for the category 'harassment/threatening'."""
hate: List[Li... | CategoryAppliedInputTypes |
python | apache__thrift | lib/py/src/transport/TTransport.py | {
"start": 3352,
"end": 3560
} | class ____(object):
"""Factory transport that builds buffered transports"""
def getTransport(self, trans):
buffered = TBufferedTransport(trans)
return buffered
| TBufferedTransportFactory |
python | astropy__astropy | astropy/units/tests/test_format.py | {
"start": 13896,
"end": 39498
} | class ____(RoundtripBase):
format_ = u_format.OGIP
@pytest.mark.parametrize(
"unit",
[
unit
for unit in u_format.OGIP._units.values()
if (isinstance(unit, UnitBase) and not isinstance(unit, PrefixUnit))
],
ids=str,
)
def test_roundtrip... | TestRoundtripOGIP |
python | PyCQA__pylint | pylint/config/callback_actions.py | {
"start": 12340,
"end": 13391
} | class ____(_CallbackAction):
"""Action that has access to the ArgumentParser object."""
def __init__(
self,
option_strings: Sequence[str],
dest: str,
nargs: None = None,
const: None = None,
default: None = None,
type: None = None,
choices: None = ... | _AccessParserAction |
python | doocs__leetcode | solution/0300-0399/0370.Range Addition/Solution.py | {
"start": 0,
"end": 275
} | class ____:
def getModifiedArray(self, length: int, updates: List[List[int]]) -> List[int]:
d = [0] * length
for l, r, c in updates:
d[l] += c
if r + 1 < length:
d[r + 1] -= c
return list(accumulate(d))
| Solution |
python | coleifer__peewee | peewee.py | {
"start": 262084,
"end": 262146
} | class ____(_ModelWriteQueryHelper, Delete):
pass
| ModelDelete |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 45411,
"end": 45526
} | class ____(BaseModel):
collection_data: Dict[str, "HardwareUsage"] = Field(..., description="")
| HardwareTelemetry |
python | encode__httpx | httpx/_exceptions.py | {
"start": 3237,
"end": 3342
} | class ____(TimeoutException):
"""
Timed out while receiving data from the host.
"""
| ReadTimeout |
python | tiangolo__fastapi | tests/test_serialize_response_model.py | {
"start": 170,
"end": 4276
} | class ____(BaseModel):
name: str = Field(alias="aliased_name")
price: Optional[float] = None
owner_ids: Optional[List[int]] = None
@app.get("/items/valid", response_model=Item)
def get_valid():
return Item(aliased_name="valid", price=1.0)
@app.get("/items/coerce", response_model=Item)
def get_coerce... | Item |
python | chroma-core__chroma | chromadb/utils/embedding_functions/huggingface_embedding_function.py | {
"start": 249,
"end": 4646
} | class ____(EmbeddingFunction[Documents]):
"""
This class is used to get embeddings for a list of texts using the HuggingFace API.
It requires an API key and a model name. The default model name is "sentence-transformers/all-MiniLM-L6-v2".
"""
def __init__(
self,
api_key: Optional[st... | HuggingFaceEmbeddingFunction |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py | {
"start": 3652,
"end": 4160
} | class ____(BaseModel):
class Config:
extra = Extra.allow
type: Literal["CustomErrorHandler"]
class_name: str = Field(
...,
description="Fully-qualified name of the class that will be implementing the custom error handler. The format is `source_<name>.<package>.<class_name>`.",
... | CustomErrorHandler |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-konko/llama_index/llms/konko/base.py | {
"start": 1458,
"end": 23123
} | class ____(LLM):
"""
Konko LLM.
Examples:
`pip install llama-index-llms-konko`
```python
import os
from llama_index.llms.konko import Konko
from llama_index.core.llms import ChatMessage
# Set up the Konko LLM with the desired model
llm = Konko(model... | Konko |
python | pandas-dev__pandas | pandas/tests/series/accessors/test_sparse_accessor.py | {
"start": 28,
"end": 296
} | class ____:
def test_sparse_accessor_updates_on_inplace(self):
ser = Series([1, 1, 2, 3], dtype="Sparse[int]")
return_value = ser.drop([0, 1], inplace=True)
assert return_value is None
assert ser.sparse.density == 1.0
| TestSparseAccessor |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-vectara/destination_vectara/client.py | {
"start": 601,
"end": 8113
} | class ____:
BASE_URL = "https://api.vectara.io/v1"
def __init__(self, config: VectaraConfig):
if isinstance(config, dict):
config = VectaraConfig.parse_obj(config)
self.customer_id = config.customer_id
self.corpus_name = config.corpus_name
self.client_id = config.oau... | VectaraClient |
python | patrick-kidger__equinox | equinox/internal/_noinline.py | {
"start": 4469,
"end": 5006
} | class ____(Module):
undefined: PyTree[jax.core.ShapedArray]
def __call__(self, static_fn):
def _transpose_transform_impl(args):
defined, cts_out = args
def _to_transpose(_undefined):
_args = combine(defined, _undefined)
return static_fn(_args)
... | _MetaTransposeTransform |
python | walkccc__LeetCode | solutions/104. Maximum Depth of Binary Tree/104.py | {
"start": 0,
"end": 172
} | class ____:
def maxDepth(self, root: TreeNode | None) -> int:
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
| Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_type_checking/singledispatchmethod.py | {
"start": 183,
"end": 468
} | class ____:
@singledispatchmethod
def foo(self, x: Union[MutableMapping, Mapping]) -> int:
raise NotImplementedError
@foo.register
def _(self, x: MutableMapping) -> int:
return 0
@foo.register
def _(self, x: Mapping) -> int:
return 0
| Foo |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/antlr_asset_selection/antlr_asset_selection.py | {
"start": 1199,
"end": 7707
} | class ____(AssetSelectionVisitor):
def __init__(self, include_sources: bool):
self.include_sources = include_sources
def visitStart(self, ctx: AssetSelectionParser.StartContext):
return self.visit(ctx.expr())
def visitTraversalAllowedExpression(
self, ctx: AssetSelectionParser.Trav... | AntlrAssetSelectionVisitor |
python | getsentry__sentry | src/sentry/incidents/models/alert_rule.py | {
"start": 13482,
"end": 14221
} | class ____:
def __init__(self) -> None:
# Two kinds of index. The value sets should be equal at all times.
self.by_action_service: dict[ActionService, ActionHandlerFactory] = {}
self.by_slug: dict[str, ActionHandlerFactory] = {}
def register(self, factory: ActionHandlerFactory) -> None:... | _FactoryRegistry |
python | eventlet__eventlet | tests/db_pool_test.py | {
"start": 15648,
"end": 17078
} | class ____:
dummy_table_sql = """CREATE TEMPORARY TABLE test_table
(
row_id SERIAL PRIMARY KEY,
value_int INTEGER,
value_float FLOAT,
value_string VARCHAR(200),
value_uuid CHAR(36),
value_binary BYTEA,
value_binary_string BYTEA,
created TIMESTA... | Psycopg2ConnectionPool |
python | tensorflow__tensorflow | tensorflow/python/ops/linalg/linear_operator_addition.py | {
"start": 11517,
"end": 12253
} | class ____(_Adder):
"""Handles additions resulting in a TriL operator."""
def can_add(self, op1, op2):
types = {_type(op1), _type(op2)}
return not types.difference(_DIAG_LIKE.union({_TRIL}))
def _add(self, op1, op2, operator_name, hints):
if _type(op1) in _EFFICIENT_ADD_TO_TENSOR:
op_add_to_te... | _AddAndReturnTriL |
python | tornadoweb__tornado | tornado/web.py | {
"start": 80712,
"end": 93476
} | class ____(ReversibleRouter):
r"""A collection of request handlers that make up a web application.
Instances of this class are callable and can be passed directly to
HTTPServer to serve the application::
application = web.Application([
(r"/", MainPageHandler),
])
http_s... | Application |
python | mlflow__mlflow | mlflow/genai/judges/tools/types.py | {
"start": 1332,
"end": 1743
} | class ____:
"""Feedback for a trace (simplified for judge tools)."""
name: str
source: str
rationale: str | None
span_id: str | None
assessment_id: str | None
value: FeedbackValueType | None
error_code: str | None
error_message: str | None
stack_trace: str | None
overrides: ... | JudgeToolFeedback |
python | run-llama__llama_index | llama-index-core/llama_index/core/agent/react/types.py | {
"start": 410,
"end": 867
} | class ____(BaseReasoningStep):
"""Action Reasoning step."""
thought: str
action: str
action_input: Dict
def get_content(self) -> str:
"""Get content."""
return (
f"Thought: {self.thought}\nAction: {self.action}\n"
f"Action Input: {self.action_input}"
... | ActionReasoningStep |
python | scipy__scipy | benchmarks/benchmarks/interpolate.py | {
"start": 12149,
"end": 13632
} | class ____(interpolate.RegularGridInterpolator):
def __init__(self, points, xi, **kwargs):
# create fake values for initialization
values = np.zeros(tuple([len(pt) for pt in points]))
super().__init__(points, values, **kwargs)
self._is_initialized = False
# precompute values
... | RegularGridInterpolatorValues |
python | ansible__ansible | lib/ansible/playbook/attribute.py | {
"start": 5668,
"end": 7033
} | class ____(Attribute):
def __init__(self, extend=False, prepend=False, **kwargs):
super().__init__(**kwargs)
self.extend = extend
self.prepend = prepend
def __get__(self, obj, obj_type=None):
if getattr(obj, '_squashed', False) or getattr(obj, '_finalized', False):
... | FieldAttribute |
python | python-poetry__poetry | src/poetry/repositories/installed_repository.py | {
"start": 726,
"end": 11270
} | class ____(Repository):
def __init__(self, packages: Sequence[Package] | None = None) -> None:
super().__init__("poetry-installed", packages)
self.system_site_packages: list[Package] = []
def add_package(self, package: Package, *, is_system_site: bool = False) -> None:
super().add_packa... | InstalledRepository |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_deployment_schedules.py | {
"start": 11815,
"end": 15250
} | class ____:
@pytest.fixture
async def schedule_to_delete(
self,
get_server_session: AsyncSessionGetter,
deployment_with_schedules,
):
async with get_server_session() as session:
schedules = await models.deployments.read_deployment_schedules(
sessio... | TestDeleteDeploymentSchedule |
python | tensorflow__tensorflow | tensorflow/lite/python/metrics/metrics_nonportable.py | {
"start": 4398,
"end": 5037
} | class ____(TFLiteMetrics):
"""Similar to TFLiteMetrics but specialized for converter.
A unique session id will be created for each new TFLiteConverterMetrics.
"""
def __init__(self) -> None:
super(TFLiteConverterMetrics, self).__init__()
session_id = uuid.uuid4().hex
self._metrics_exporter = metri... | TFLiteConverterMetrics |
python | apache__airflow | providers/grpc/tests/unit/grpc/operators/test_grpc.py | {
"start": 1025,
"end": 3993
} | class ____:
def custom_conn_func(self, connection):
pass
@mock.patch("airflow.providers.grpc.operators.grpc.GrpcHook")
def test_with_interceptors(self, mock_hook):
operator = GrpcOperator(
stub_class=StubClass,
call_func="stream_call",
interceptors=[],
... | TestGrpcOperator |
python | pydantic__pydantic | tests/mypy/modules/root_models.py | {
"start": 388,
"end": 481
} | class ____(RootModel[list[str]]):
pets: list[str]
T = TypeVar('T')
V = TypeVar('V')
| Pets4 |
python | ansible__ansible | lib/ansible/_internal/_templating/_datatag.py | {
"start": 752,
"end": 830
} | class ____:
template: str
deprecated: Deprecated
| _TrippedDeprecationInfo |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess1.py | {
"start": 1364,
"end": 1551
} | class ____:
abc: DescriptorD[str] = DescriptorD()
stack: ExitStack
def test(self, value: ContextManager[str]) -> None:
self.abc = self.stack.enter_context(value)
| ClassD |
python | numba__numba | numba/tests/npyufunc/test_gufunc.py | {
"start": 3203,
"end": 5326
} | class ____(MemoryLeakMixin, TestCase):
target = 'cpu'
def test_multiple_outputs_same_type_passed_in(self):
@guvectorize('(x)->(x),(x)',
target=self.target)
def copy(A, B, C):
for i in range(B.size):
B[i] = A[i]
C[i] = A[i]
... | TestMultipleOutputs |
python | pyca__cryptography | src/cryptography/x509/base.py | {
"start": 17409,
"end": 23208
} | class ____:
_extensions: list[Extension[ExtensionType]]
_revoked_certificates: list[RevokedCertificate]
def __init__(
self,
issuer_name: Name | None = None,
last_update: datetime.datetime | None = None,
next_update: datetime.datetime | None = None,
extensions: list[E... | CertificateRevocationListBuilder |
python | mlflow__mlflow | mlflow/gateway/schemas/chat.py | {
"start": 1139,
"end": 1882
} | class ____(RequestModel):
"""
A tool definition for the chat endpoint with Unity Catalog integration.
The Gateway request accepts a special tool type 'uc_function' for Unity Catalog integration.
https://mlflow.org/docs/latest/llms/deployments/uc_integration.html
"""
type: Literal["function", "u... | ChatToolWithUC |
python | great-expectations__great_expectations | contrib/experimental/great_expectations_experimental/rule_based_profiler/data_assistant_result/statistics_data_assistant_result.py | {
"start": 243,
"end": 1666
} | class ____(DataAssistantResult):
"""
Note (9/30/2022): Plotting functionality is experimental.
"""
@property
def metric_expectation_map(self) -> Dict[Union[str, Tuple[str]], str]:
"""
A mapping is defined for which metrics to plot and their associated expectations.
"""
... | StatisticsDataAssistantResult |
python | MongoEngine__mongoengine | tests/fields/test_file_field.py | {
"start": 823,
"end": 16994
} | class ____(MongoDBTestCase):
def tearDown(self):
self.db.drop_collection("fs.files")
self.db.drop_collection("fs.chunks")
def test_file_field_optional(self):
# Make sure FileField is optional and not required
class DemoFile(Document):
the_file = FileField()
... | TestFileField |
python | falconry__falcon | tests/test_request_media.py | {
"start": 1340,
"end": 1619
} | class ____:
def __init__(self, expected_error):
self._expected_error = expected_error
def on_post(self, req, resp, **kwargs):
with pytest.raises(self._expected_error) as error:
req.media
self.captured_error = error
| ResourceInvalidMedia |
python | scrapy__scrapy | tests/test_pipeline_files.py | {
"start": 1999,
"end": 9353
} | class ____:
def setup_method(self):
self.tempdir = mkdtemp()
settings_dict = {"FILES_STORE": self.tempdir}
crawler = get_crawler(DefaultSpider, settings_dict=settings_dict)
crawler.spider = crawler._create_spider()
self.pipeline = FilesPipeline.from_crawler(crawler)
s... | TestFilesPipeline |
python | huggingface__transformers | src/transformers/models/pop2piano/configuration_pop2piano.py | {
"start": 786,
"end": 6005
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Pop2PianoForConditionalGeneration`]. It is used
to instantiate a Pop2PianoForConditionalGeneration model according to the specified arguments, defining the model
architecture. Instantiating a configurati... | Pop2PianoConfig |
python | pytorch__pytorch | torch/_inductor/codecache.py | {
"start": 173260,
"end": 174474
} | class ____(CodeCacheFuture):
"""
A statically launchable CachingAutotuner, loaded from TritonBundler
"""
def __init__(self, static_autotuner: CachingAutotuner) -> None:
# Pickled version of CachingAutotuner
self.static_autotuner = static_autotuner
# This needs to be set in Async... | StaticAutotunerFuture |
python | pytorch__pytorch | torch/onnx/_internal/exporter/_registration.py | {
"start": 1243,
"end": 6066
} | class ____:
"""A wrapper of onnx-script function with additional metadata.
onnx_function: The onnx-script function from torchlib.
fx_target: The PyTorch node callable target.
signature: The ONNX signature of the function. When None, the signature is inferred.
is_custom: Whether the function is a cu... | OnnxDecompMeta |
python | tensorflow__tensorflow | tensorflow/python/keras/utils/generic_utils.py | {
"start": 5175,
"end": 5497
} | class ____(object):
"""The default shared object loading scope. It does nothing.
Created to simplify serialization code that doesn't care about shared objects
(e.g. when serializing a single object).
"""
def get(self, unused_object_id):
return None
def set(self, object_id, obj):
pass
| NoopLoadingScope |
python | bokeh__bokeh | tests/unit/bokeh/models/test_plots.py | {
"start": 12017,
"end": 17639
} | class ____(BaseTwinAxis):
"""Test whether extra x and y ranges can be Range1d"""
@staticmethod
def get_range_instance():
return Range1d(0, 42)
def test_plot_with_no_title_specified_creates_an_empty_title() -> None:
plot = Plot()
assert plot.title.text == ""
def test_plot_if_title_is_con... | TestLinearTwinAxis |
python | vyperlang__vyper | vyper/warnings.py | {
"start": 1579,
"end": 1670
} | class ____(VyperWarning):
"""
General deprecation warning
"""
pass
| Deprecation |
python | encode__django-rest-framework | tests/test_relations_slug.py | {
"start": 7258,
"end": 11817
} | class ____(TestCase):
def setUp(self):
target = ForeignKeyTarget(name='target-1')
target.save()
for idx in range(1, 4):
if idx == 3:
target = None
source = NullableForeignKeySource(name='source-%d' % idx, target=target)
source.save()
d... | SlugNullableForeignKeyTests |
python | boto__boto3 | boto3/docs/subresource.py | {
"start": 937,
"end": 5766
} | class ____(NestedDocumenter):
def document_sub_resources(self, section):
add_resource_type_overview(
section=section,
resource_type='Sub-resources',
description=(
'Sub-resources are methods that create a new instance of a'
' child resource.... | SubResourceDocumenter |
python | ray-project__ray | rllib/evaluation/sample_batch_builder.py | {
"start": 2215,
"end": 10039
} | class ____:
"""Util to build SampleBatches for each policy in a multi-agent env.
Input data is per-agent, while output data is per-policy. There is an M:N
mapping between agents and policies. We retain one local batch builder
per agent. When an agent is done, then its local batch is appended into the
... | MultiAgentSampleBatchBuilder |
python | pypa__setuptools | setuptools/_vendor/more_itertools/more.py | {
"start": 114664,
"end": 128554
} | class ____:
"""Convert a function that uses callbacks to an iterator.
Let *func* be a function that takes a `callback` keyword argument.
For example:
>>> def func(callback=None):
... for i, c in [(1, 'a'), (2, 'b'), (3, 'c')]:
... if callback:
... callback(i, c)
... | callback_iter |
python | django__django | django/tasks/base.py | {
"start": 801,
"end": 1367
} | class ____(TextChoices):
# The Task has just been enqueued, or is ready to be executed again.
READY = ("READY", pgettext_lazy("Task", "Ready"))
# The Task is currently running.
RUNNING = ("RUNNING", pgettext_lazy("Task", "Running"))
# The Task raised an exception during execution, or was unable to s... | TaskResultStatus |
python | streamlit__streamlit | lib/streamlit/testing/v1/element_tree.py | {
"start": 9712,
"end": 9901
} | class ____(AlertBase):
def __init__(self, proto: AlertProto, root: ElementTree) -> None:
super().__init__(proto, root)
self.type = "success"
@dataclass(repr=False)
| Success |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/elements.py | {
"start": 111327,
"end": 113710
} | class ____(ClauseList, ColumnElement[TupleAny]):
"""Represent a SQL tuple."""
__visit_name__ = "tuple"
_traverse_internals: _TraverseInternalsType = (
ClauseList._traverse_internals + []
)
type: TupleType
@util.preload_module("sqlalchemy.sql.sqltypes")
def __init__(
self,... | Tuple |
python | cython__cython | Cython/Compiler/TreeFragment.py | {
"start": 3824,
"end": 7548
} | class ____(VisitorTransform):
"""
Makes a copy of a template tree while doing substitutions.
A dictionary "substitutions" should be passed in when calling
the transform; mapping names to replacement nodes. Then replacement
happens like this:
- If an ExprStatNode contains a single NameNode, who... | TemplateTransform |
python | RaRe-Technologies__gensim | gensim/interfaces.py | {
"start": 672,
"end": 4896
} | class ____(utils.SaveLoad):
"""Interface for corpus classes from :mod:`gensim.corpora`.
Corpus is simply an iterable object, where each iteration step yields one document:
.. sourcecode:: pycon
>>> from gensim.corpora import MmCorpus # inherits from the CorpusABC class
>>> from gensim.te... | CorpusABC |
python | google__jax | jax/experimental/mosaic/gpu/fragmented_array.py | {
"start": 1520,
"end": 10593
} | class ____:
"""A tiling expression describing a permutation of elements of an nd-array.
To apply one level of tiling to an array, each of the trailing dimensions (up
to the rank of the tile) is unfolded into two dimensions: first equal to the
ratio of the dimension size and the tile size, and second equal to t... | Tiling |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-google-genai/tests/test_llms_google_genai.py | {
"start": 1445,
"end": 68985
} | class ____(BaseModel):
"""A model of a schema in a database."""
schema_name: str = Field(description="Schema name")
tables: List[Table] = Field(description="List of random Table objects")
# Define the models to test against
GEMINI_MODELS_TO_TEST = (
[
{"model": "models/gemini-2.5-flash-lite",... | Schema |
python | django__django | tests/admin_views/admin.py | {
"start": 30724,
"end": 30793
} | class ____(admin.ModelAdmin):
search_fields = ["name"]
| CountryAdmin |
python | getsentry__sentry | src/sentry/sentry_apps/installations.py | {
"start": 7347,
"end": 8702
} | class ____:
sentry_app_installation: SentryAppInstallation
user: User | RpcUser
action: str
def run(self) -> None:
if self.action not in VALID_ACTIONS:
raise SentryAppSentryError(
f"Invalid action '{self.action} for installation notifier for {self.sentry_app}"
... | SentryAppInstallationNotifier |
python | apache__airflow | airflow-core/tests/unit/dags/test_parsing_context.py | {
"start": 1147,
"end": 1908
} | class ____(EmptyOperator):
def execute(self, context: Context):
import os
parsing_context_file = Path("/tmp/airflow_parsing_context")
self.log.info("Executing")
# signal to the test that we've started
parsing_context = (
f"{_AIRFLOW_PARSING_CONTEXT_DAG_ID}={os.en... | DagWithParsingContext |
python | pydantic__pydantic | tests/test_forward_ref.py | {
"start": 10254,
"end": 11947
} | class ____(BaseModel):
name: str
owner: Owner
subaccounts: list[Account] = []
"""
)
Account = module.Account
assert Account.model_json_schema() == {
'$ref': '#/$defs/Account',
'$defs': {
'Account': {
'title': 'Account',
'type': 'object',... | Account |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.