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 | langchain-ai__langchain | libs/core/langchain_core/runnables/fallbacks.py | {
"start": 1013,
"end": 24463
} | class ____(RunnableSerializable[Input, Output]):
"""`Runnable` that can fallback to other `Runnable`s if it fails.
External APIs (e.g., APIs for a language model) may at times experience
degraded performance or even downtime.
In these cases, it can be useful to have a fallback `Runnable` that can be
... | RunnableWithFallbacks |
python | oauthlib__oauthlib | tests/openid/connect/core/test_server.py | {
"start": 609,
"end": 5198
} | class ____(TestCase):
def setUp(self):
self.mock_validator = mock.MagicMock()
self.mock_validator.get_code_challenge.return_value = None
self.addCleanup(setattr, self, 'mock_validator', mock.MagicMock())
auth_code = AuthorizationCodeGrant(request_validator=self.mock_validator)
... | AuthorizationEndpointTest |
python | patrick-kidger__equinox | equinox/_module/_module.py | {
"start": 3468,
"end": 3743
} | class ____(eqx.Module):
linear: Callable
def __init__(self, ...):
self.linear = eqx.nn.Linear(...)
def __call__(self, ...):
... = jax.vmap(self.linear)(...)
```
or by using `eqx.filter_vmap` instead (which *does* return a PyTree):
```python
| MyModule |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/origin_info.py | {
"start": 1675,
"end": 5152
} | class ____(
collections.namedtuple(
'OriginInfo',
('loc', 'function_name', 'source_code_line', 'comment'))):
"""Container for information about the source code before conversion.
Attributes:
loc: Location
function_name: Optional[Text]
source_code_line: Text
comment: Optional[Tex... | OriginInfo |
python | sphinx-doc__sphinx | sphinx/ext/autosummary/generate.py | {
"start": 3192,
"end": 5834
} | class ____:
"""A helper class for rendering."""
def __init__(self, app: Sphinx) -> None:
if isinstance(app, Builder):
msg = 'Expected a Sphinx application object!'
raise TypeError(msg)
system_templates_path = [
package_dir.joinpath('ext', 'autosummary', 'tem... | AutosummaryRenderer |
python | google__pytype | pytype/blocks/process_blocks.py | {
"start": 774,
"end": 3517
} | class ____(pyc.CodeVisitor):
"""Collect opcodes that might have annotations attached."""
def __init__(self):
super().__init__()
# A mutable map of line: opcode for STORE_* opcodes. This is modified as the
# visitor runs, and contains the last opcode for each line.
self.store_ops = {}
# A mutabl... | CollectAnnotationTargetsVisitor |
python | PyCQA__pylint | pylint/pyreverse/inspector.py | {
"start": 12078,
"end": 14205
} | class ____(AbstractRelationshipHandler):
"""Handle composition relationships where parent creates child objects."""
def handle(
self, node: nodes.AssignAttr | nodes.AssignName, parent: nodes.ClassDef
) -> None:
# If the node is not part of an assignment, pass to next handler
if not ... | CompositionsHandler |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 360806,
"end": 361135
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("IssueTimelineItem", graphql_name="node")
| IssueTimelineItemEdge |
python | python-attrs__attrs | typing-examples/mypy.py | {
"start": 523,
"end": 587
} | class ____:
a: int = attr.ib()
cc = CC(1)
CC(a=1)
@attr.s
| CC |
python | openai__openai-python | src/openai/types/vector_store_search_response.py | {
"start": 259,
"end": 408
} | class ____(BaseModel):
text: str
"""The text content returned from search."""
type: Literal["text"]
"""The type of content."""
| Content |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 6530,
"end": 6663
} | class ____(_PathValueError):
code = 'path.not_a_file'
msg_template = 'path "{path}" does not point to a file'
| PathNotAFileError |
python | django__django | tests/admin_views/test_forms.py | {
"start": 948,
"end": 1575
} | class ____(SimpleTestCase):
def test_repr(self):
fieldsets = (
(
"My fields",
{
"classes": ["collapse"],
"fields": ("url", "title", "content", "sites"),
},
),
)
form = ArticleForm(... | AdminFormTests |
python | plotly__plotly.py | plotly/graph_objs/scatterternary/_textfont.py | {
"start": 233,
"end": 17139
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatterternary"
_path_str = "scatterternary.textfont"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc",
"size"... | Textfont |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_annotations/allow_nested_overload.py | {
"start": 0,
"end": 146
} | class ____:
from typing import overload
@overload
def f(self, x: int, y: int) -> None:
...
def f(self, x, y):
pass
| C |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 139421,
"end": 143369
} | class ____(TestCase):
@staticmethod
def _normalize_partition(p):
"""
Return a normalized, hashable, version of a partition using
_FrozenMultiset
"""
return _FrozenMultiset(_FrozenMultiset(g) for g in p)
@staticmethod
def _normalize_partitions(ps):
"""
... | SetPartitionsTests |
python | getsentry__sentry | src/sentry/dynamic_sampling/tasks/common.py | {
"start": 6224,
"end": 6695
} | class ____:
"""
Represents the total and indexed number of transactions received by an organization
(in a particular interval of time).
"""
# organization id
org_id: int
# total number of transactions
total: int
# number of transactions indexed (i.e. stored)
indexed: int | None
... | OrganizationDataVolume |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-hubspot/unit_tests/integrations/__init__.py | {
"start": 7140,
"end": 11354
} | class ____(HubspotTestCase):
def _ms(self, dt) -> int:
return int(dt.timestamp() * 1000)
def request(self, page_token: Optional[Dict[str, str]] = None):
start = self.start_date()
end = self.now()
builder = (
CRMSearchRequestBuilder()
.for_entity(self.OBJ... | HubspotCRMSearchStream |
python | GoogleCloudPlatform__python-docs-samples | monitoring/snippets/v3/uptime-check-client/snippets.py | {
"start": 7172,
"end": 11138
} | class ____(Exception):
pass
def project_id() -> str:
"""Retrieves the project id from the environment variable.
Raises:
MissingProjectIdError -- When not set.
Returns:
str -- the project name
"""
project_id = os.environ["GOOGLE_CLOUD_PROJECT"]
if not project_id:
... | MissingProjectIdError |
python | ethereum__web3.py | web3/datastructures.py | {
"start": 657,
"end": 2471
} | class ____(Mapping[TKey, TValue]):
"""
The read attributes for the AttributeDict types
"""
def __init__(
self, dictionary: dict[TKey, TValue], *args: Any, **kwargs: Any
) -> None:
# type ignored on 46/50 b/c dict() expects str index type not TKey
self.__dict__ = dict(diction... | ReadableAttributeDict |
python | realpython__materials | python-maze-solver/source_code_final/src/maze_solver/models/solution.py | {
"start": 204,
"end": 904
} | class ____:
squares: tuple[Square, ...]
def __post_init__(self) -> None:
assert self.squares[0].role is Role.ENTRANCE
assert self.squares[-1].role is Role.EXIT
reduce(validate_corridor, self.squares)
def __iter__(self) -> Iterator[Square]:
return iter(self.squares)
def... | Solution |
python | django__django | django/conf/__init__.py | {
"start": 7664,
"end": 9216
} | class ____:
"""Holder for user configured settings."""
# SETTINGS_MODULE doesn't make much sense in the manually configured
# (standalone) case.
SETTINGS_MODULE = None
def __init__(self, default_settings):
"""
Requests for configuration variables not in this class are satisfied
... | UserSettingsHolder |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 383229,
"end": 384036
} | class ____(StatNode):
"""
Used as the 'finally' block in a GILStatNode
state string 'gil' or 'nogil'
# scope_gil_state_known bool For nogil functions this can be False, since they can also be run with gil
# set to False by GilCheck transform
"""
child_attr... | GILExitNode |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/package_base_extendee/package.py | {
"start": 149,
"end": 352
} | class ____(PackageBase):
"""Simple package with one optional dependency"""
homepage = "http://www.example.com"
url = "http://www.example.com/a-1.0.tar.gz"
version("1.0")
| PackageBaseExtendee |
python | ray-project__ray | doc/source/ray-overview/examples/mcp-ray-serve/translator_mcp_ray.py | {
"start": 1481,
"end": 1650
} | class ____:
def __init__(self):
pass
# Ray Serve entry point.
app = TranslatorMCP.bind()
## Run in terminal.
# serve run translator_mcp_ray:app
| TranslatorMCP |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/events/__init__.py | {
"start": 63164,
"end": 63552
} | class ____(
NamedTuple("_AssetObservation", [("asset_observation", AssetObservation)])
):
def __new__(cls, asset_observation: AssetObservation):
return super().__new__(
cls,
asset_observation=check.inst_param(
asset_observation, "asset_observation", AssetObservati... | AssetObservationData |
python | celery__celery | t/unit/concurrency/test_prefork.py | {
"start": 1209,
"end": 3597
} | class ____:
@staticmethod
def Loader(*args, **kwargs):
loader = Mock(*args, **kwargs)
loader.conf = {}
loader.override_backends = {}
return loader
@patch('celery.platforms.signals')
def test_process_initializer(self, _signals, set_mp_process_title, restore_logging):
... | test_process_initializer |
python | Lightning-AI__lightning | tests/tests_pytorch/checkpointing/test_model_checkpoint.py | {
"start": 34456,
"end": 34609
} | class ____(BoringModel):
def backward(self, loss):
if self.current_epoch == 1:
raise RuntimeError("Trouble!")
| TroubledModelBackward |
python | qdrant__qdrant-client | qdrant_client/local/local_collection.py | {
"start": 3193,
"end": 113459
} | class ____:
"""
LocalCollection is a class that represents a collection of vectors in the local storage.
"""
LARGE_DATA_THRESHOLD = 20_000
def __init__(
self,
config: models.CreateCollection,
location: Optional[str] = None,
force_disable_check_same_thread: bool = Fa... | LocalCollection |
python | encode__django-rest-framework | rest_framework/fields.py | {
"start": 1888,
"end": 7671
} | class ____(Exception):
"""
Built-in function signatures are not inspectable. This exception is raised
so the serializer can raise a helpful error message.
"""
pass
def is_simple_callable(obj):
"""
True if the object is a callable that takes no arguments.
"""
if not callable(obj):
... | BuiltinSignatureError |
python | astropy__astropy | astropy/units/tests/test_structured.py | {
"start": 1512,
"end": 9031
} | class ____(StructuredTestBase):
def test_initialization_and_keying(self):
su = StructuredUnit((self.p_unit, self.v_unit), ("p", "v"))
assert su["p"] is self.p_unit
assert su["v"] is self.v_unit
su2 = StructuredUnit((su, self.t_unit), ("pv", "t"))
assert isinstance(su2["pv"], ... | TestStructuredUnitBasics |
python | huggingface__transformers | src/transformers/models/edgetam_video/modeling_edgetam_video.py | {
"start": 65494,
"end": 66228
} | class ____(ModelOutput):
r"""
object_ids (`list[int]`, *optional*):
List of object IDs being tracked in the current frame.
pred_masks (`torch.FloatTensor` of shape `(batch_size, num_masks, height, width)`):
The predicted masks stored at the model's resolution.
object_score_logits (`torch... | EdgeTamVideoSegmentationOutput |
python | tiangolo__fastapi | tests/test_dependency_class.py | {
"start": 250,
"end": 367
} | class ____:
def __call__(self, value: str) -> Generator[str, None, None]:
yield value
| CallableGenDependency |
python | vyperlang__vyper | vyper/exceptions.py | {
"start": 8826,
"end": 8904
} | class ____(VyperException):
"""Type is invalid for an action."""
| InvalidType |
python | spack__spack | lib/spack/spack/vendor/jinja2/compiler.py | {
"start": 8312,
"end": 9047
} | class ____(NodeVisitor):
"""A visitor that checks if a name is accessed without being
declared. This is different from the frame visitor as it will
not stop at closure frames.
"""
def __init__(self, names: t.Iterable[str]) -> None:
self.names = set(names)
self.undeclared: t.Set[str... | UndeclaredNameVisitor |
python | pytorch__pytorch | torch/nn/modules/distance.py | {
"start": 140,
"end": 2038
} | class ____(Module):
r"""
Computes the pairwise distance between input vectors, or between columns of input matrices.
Distances are computed using ``p``-norm, with constant ``eps`` added to avoid division by zero
if ``p`` is negative, i.e.:
.. math ::
\mathrm{dist}\left(x, y\right) = \left\... | PairwiseDistance |
python | sqlalchemy__sqlalchemy | test/sql/test_syntax_extensions.py | {
"start": 2984,
"end": 4439
} | class ____(SyntaxExtension, ClauseElement):
_traverse_internals: _TraverseInternalsType = [
("_exprs", InternalTraversal.dp_clauseelement_tuple),
]
def __init__(self, *exprs):
self._exprs = tuple(
coercions.expect(roles.ByOfRole, e, apply_propagate_attrs=self)
for e ... | ColumnExpressionExt |
python | spyder-ide__spyder | spyder/plugins/outlineexplorer/main_widget.py | {
"start": 1146,
"end": 9607
} | class ____(PluginMainWidget):
"""Class browser"""
edit_goto = Signal(str, int, str)
edit = Signal(str)
is_visible = Signal()
sig_update_configuration = Signal()
ENABLE_SPINNER = True
CONF_SECTION = 'outline_explorer'
def __init__(self, name, plugin, parent=None, context=None):
... | OutlineExplorerWidget |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 6781,
"end": 7029
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.linear1 = torch.nn.Linear(10, 10)
def forward(self, x):
return test_functions.constant3(torch.sigmoid(self.linear1(x)), x)
| ViaModuleCall |
python | matplotlib__matplotlib | lib/matplotlib/testing/compare.py | {
"start": 1553,
"end": 2639
} | class ____:
def __init__(self):
self._proc = None
# Explicitly register deletion from an atexit handler because if we
# wait until the object is GC'd (which occurs later), then some module
# globals (e.g. signal.SIGKILL) has already been set to None, and
# kill() doesn't work... | _Converter |
python | networkx__networkx | networkx/algorithms/isomorphism/tests/test_temporalisomorphvf2.py | {
"start": 4942,
"end": 7343
} | class ____:
"""
A test class for the directed time-respecting graph matcher.
"""
def provide_g1_topology(self):
G1 = nx.DiGraph()
G1.add_edges_from(provide_g1_edgelist())
return G1
def provide_g2_path_3edges(self):
G2 = nx.DiGraph()
G2.add_edges_from([(0, 1)... | TestDiTimeRespectingGraphMatcher |
python | keon__algorithms | algorithms/tree/bst/array_to_bst.py | {
"start": 108,
"end": 449
} | class ____(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def array_to_bst(nums):
if not nums:
return None
mid = len(nums)//2
node = TreeNode(nums[mid])
node.left = array_to_bst(nums[:mid])
node.right = array_to_bst(nums[mid+1:])... | TreeNode |
python | mlflow__mlflow | mlflow/models/resources.py | {
"start": 10346,
"end": 12224
} | class ____:
"""
Private builder class to build the resources dictionary.
"""
@staticmethod
def from_resources(
resources: list[Resource], api_version: str = DEFAULT_API_VERSION
) -> dict[str, dict[ResourceType, list[dict[str, Any]]]]:
resource_dict = {}
for resource in r... | _ResourceBuilder |
python | optuna__optuna | optuna/search_space/group_decomposed.py | {
"start": 225,
"end": 1163
} | class ____:
def __init__(self) -> None:
self._search_spaces: list[dict[str, BaseDistribution]] = []
@property
def search_spaces(self) -> list[dict[str, BaseDistribution]]:
return self._search_spaces
def add_distributions(self, distributions: dict[str, BaseDistribution]) -> None:
... | _SearchSpaceGroup |
python | huggingface__transformers | src/transformers/models/biogpt/modeling_biogpt.py | {
"start": 10280,
"end": 14195
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: BioGptConfig, layer_idx: Optional[int] = None):
super().__init__()
self.embed_dim = config.hidden_size
self.self_attn = BioGptAttention(
embed_dim=self.embed_dim,
num_heads=config.num_attention_heads,... | BioGptDecoderLayer |
python | scikit-learn__scikit-learn | sklearn/linear_model/_bayes.py | {
"start": 16243,
"end": 28995
} | class ____(RegressorMixin, LinearModel):
"""Bayesian ARD regression.
Fit the weights of a regression model, using an ARD prior. The weights of
the regression model are assumed to be in Gaussian distributions.
Also estimate the parameters lambda (precisions of the distributions of the
weights) and a... | ARDRegression |
python | ansible__ansible | lib/ansible/module_utils/facts/virtual/freebsd.py | {
"start": 862,
"end": 3360
} | class ____(Virtual, VirtualSysctlDetectionMixin):
"""
This is a FreeBSD-specific subclass of Virtual. It defines
- virtualization_type
- virtualization_role
"""
platform = 'FreeBSD'
def get_virtual_facts(self):
virtual_facts = {}
host_tech = set()
guest_tech = set()... | FreeBSDVirtual |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-braintree/source_braintree/schemas/subscription.py | {
"start": 261,
"end": 1091
} | class ____(CatalogModel):
add_ons: List[AddOn]
balance: Decimal
billing_day_of_month: Decimal
billing_period_start_date: date
billing_period_end_date: date
created_at: datetime
current_billing_cycle: Decimal
days_past_due: Decimal
description: str
discounts: List[Discount]
fa... | Subscription |
python | scipy__scipy | scipy/optimize/tests/test_regression.py | {
"start": 172,
"end": 1077
} | class ____:
def test_newton_x0_is_0(self):
# Regression test for gh-1601
tgt = 1
res = scipy.optimize.newton(lambda x: x - 1, 0)
assert_almost_equal(res, tgt)
def test_newton_integers(self):
# Regression test for gh-1741
root = scipy.optimize.newton(lambda x: x*... | TestRegression |
python | dask__distributed | distributed/shuffle/_rechunk.py | {
"start": 7905,
"end": 28882
} | class ____(Layer):
name: str
token: str
chunks: ChunkedAxes
chunks_input: ChunkedAxes
name_input: str
disk: bool
keepmap: np.ndarray
_cached_dict: _T_LowLevelGraph | None
def __init__(
self,
name: str,
token: str,
chunks: ChunkedAxes,
chunks_... | P2PRechunkLayer |
python | doocs__leetcode | solution/2800-2899/2825.Make String a Subsequence Using Cyclic Increments/Solution.py | {
"start": 0,
"end": 275
} | class ____:
def canMakeSubsequence(self, str1: str, str2: str) -> bool:
i = 0
for c in str1:
d = "a" if c == "z" else chr(ord(c) + 1)
if i < len(str2) and str2[i] in (c, d):
i += 1
return i == len(str2)
| Solution |
python | ray-project__ray | python/ray/serve/tests/test_config_files/logging_config_test.py | {
"start": 200,
"end": 666
} | class ____:
def __call__(self):
logger.debug("this_is_debug_info")
logger.info("this_is_access_log", extra={"serve_access_log": True})
log_file = logger.handlers[1].target.baseFilename
return {
"log_file": log_file,
"replica": serve.get_replica_context().rep... | Model |
python | huggingface__transformers | src/transformers/models/swin/modeling_swin.py | {
"start": 44822,
"end": 47193
} | class ____(SwinPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.swin = SwinModel(config)
# Classifier head
self.classifier = (
nn.Linear(self.swin.num_features, config.num_labels) if config.num_label... | SwinForImageClassification |
python | apache__airflow | airflow-core/tests/unit/utils/test_db_cleanup.py | {
"start": 2549,
"end": 29701
} | class ____:
@pytest.fixture(autouse=True)
def clear_airflow_tables(self):
drop_tables_with_prefix("_airflow_")
@pytest.mark.parametrize(
("kwargs", "called"),
[
pytest.param(dict(confirm=True), True, id="true"),
pytest.param(dict(), True, id="not supplied"),
... | TestDBCleanup |
python | psf__requests | src/requests/exceptions.py | {
"start": 3277,
"end": 3359
} | class ____(InvalidURL):
"""The proxy URL provided is invalid."""
| InvalidProxyURL |
python | doocs__leetcode | solution/0200-0299/0202.Happy Number/Solution2.py | {
"start": 0,
"end": 340
} | class ____:
def isHappy(self, n: int) -> bool:
def next(x):
y = 0
while x:
x, v = divmod(x, 10)
y += v * v
return y
slow, fast = n, next(n)
while slow != fast:
slow, fast = next(slow), next(next(fast))
r... | Solution |
python | kamyu104__LeetCode-Solutions | Python/minimum-cost-to-make-at-least-one-valid-path-in-a-grid.py | {
"start": 1199,
"end": 2097
} | class ____(object):
def minCost(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
b, t = (0, 0), (len(grid)-1, len(grid[0])-1)
dq = collections.deque([(b, 0)])
lookup = set()
while dq:
... | Solution2 |
python | PyCQA__pylint | doc/data/messages/d/duplicate-code/bad/apple.py | {
"start": 0,
"end": 417
} | class ____:
def __init__(self):
self.remaining_bites = 3
def take_bite(self):
if self.remaining_bites > 0:
print("You take a bite of the apple.")
self.remaining_bites -= 1
else:
print("The apple is already eaten up!")
def eaten_by_animal(self, an... | Apple |
python | allegroai__clearml | clearml/automation/optimization.py | {
"start": 49447,
"end": 53171
} | class ____(SearchStrategy):
"""
Random search strategy controller. Random uniform sampling of hyperparameters.
"""
# Number of already chosen random samples before assuming we covered the entire hyper-parameter space
_hp_space_cover_samples = 42
def __init__(
self,
base_task_id... | RandomSearch |
python | keras-team__keras | keras/src/utils/dtype_utils_test.py | {
"start": 1137,
"end": 1936
} | class ____(test_case.TestCase):
def test_is_float_float16(self):
self.assertTrue(dtype_utils.is_float("float16"))
def test_is_float_float32(self):
self.assertTrue(dtype_utils.is_float("float32"))
def test_is_float_float64(self):
self.assertTrue(dtype_utils.is_float("float64"))
... | IsFloatTests |
python | MongoEngine__mongoengine | tests/fields/test_enum_field.py | {
"start": 562,
"end": 4831
} | class ____(MongoDBTestCase):
def test_storage(self):
model = ModelWithEnum(status=Status.NEW).save()
assert get_as_pymongo(model) == {"_id": model.id, "status": "new"}
def test_set_enum(self):
ModelWithEnum.drop_collection()
ModelWithEnum(status=Status.NEW).save()
assert... | TestStringEnumField |
python | docker__docker-py | docker/credentials/errors.py | {
"start": 43,
"end": 93
} | class ____(StoreError):
pass
| CredentialsNotFound |
python | huggingface__transformers | src/transformers/models/yolos/modeling_yolos.py | {
"start": 20707,
"end": 21375
} | class ____(nn.Module):
def __init__(self, config: YolosConfig):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.activation = nn.Tanh()
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
# We "pool" the model by simply taking th... | YolosPooler |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 485690,
"end": 486283
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("PackageEdge"), graphql_name="edges")
nodes = sgqlc.types.Field(sgqlc.t... | PackageConnection |
python | tiangolo__fastapi | docs_src/security/tutorial005_an_py310.py | {
"start": 1248,
"end": 1337
} | class ____(BaseModel):
username: str | None = None
scopes: list[str] = []
| TokenData |
python | pypa__pip | src/pip/_vendor/pygments/util.py | {
"start": 770,
"end": 8330
} | class ____(Exception):
"""
This exception will be raised by all option processing functions if
the type or value of the argument is not correct.
"""
def get_choice_opt(options, optname, allowed, default=None, normcase=False):
"""
If the key `optname` from the dictionary is not in the sequence
... | OptionError |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 35763,
"end": 35900
} | class ____(BaseModel):
error: Optional[str] = Field(default=None, description="Description of the occurred error.")
| ErrorResponseStatus |
python | django__django | tests/modeladmin/test_checks.py | {
"start": 45021,
"end": 45847
} | class ____(CheckTestCase):
def test_not_integer(self):
class ValidationTestInline(TabularInline):
model = ValidationTestInlineModel
max_num = "hello"
class TestModelAdmin(ModelAdmin):
inlines = [ValidationTestInline]
self.assertIsInvalid(
Tes... | MaxNumCheckTests |
python | scrapy__scrapy | tests/test_squeues_request.py | {
"start": 4115,
"end": 4383
} | class ____(TestRequestQueueBase):
is_fifo = False
@pytest.fixture
def q(self, crawler, tmp_path):
return MarshalLifoDiskQueue.from_crawler(
crawler=crawler, key=str(tmp_path / "marshal" / "lifo")
)
| TestMarshalLifoDiskQueueRequest |
python | spyder-ide__spyder | spyder/plugins/updatemanager/workers.py | {
"start": 8229,
"end": 8349
} | class ____(Exception):
"""Download for installer to update was cancelled."""
pass
| UpdateDownloadCancelledException |
python | pytest-dev__pytest | src/_pytest/fixtures.py | {
"start": 30117,
"end": 33030
} | class ____(LookupError):
"""Could not return a requested fixture (missing or invalid)."""
def __init__(
self, argname: str | None, request: FixtureRequest, msg: str | None = None
) -> None:
self.argname = argname
self.request = request
self.fixturestack = request._get_fixtur... | FixtureLookupError |
python | matplotlib__matplotlib | lib/matplotlib/backend_tools.py | {
"start": 14230,
"end": 14524
} | class ____(AxisScaleBase):
"""Tool to toggle between linear and logarithmic scales on the X axis."""
description = 'Toggle scale X axis'
default_keymap = property(lambda self: mpl.rcParams['keymap.xscale'])
def set_scale(self, ax, scale):
ax.set_xscale(scale)
| ToolXScale |
python | ray-project__ray | rllib/core/rl_module/torch/torch_rl_module.py | {
"start": 8490,
"end": 12776
} | class ____(RLModule, nn.parallel.DistributedDataParallel):
def __init__(self, *args, **kwargs) -> None:
nn.parallel.DistributedDataParallel.__init__(self, *args, **kwargs)
# We do not want to call RLModule.__init__ here because all we need is
# the interface of that base-class not the actual... | TorchDDPRLModule |
python | ray-project__ray | python/ray/dag/tests/experimental/test_torch_tensor_transport.py | {
"start": 3632,
"end": 6200
} | class ____:
"""Tests driver to worker tensor transport with CPU device."""
def create_and_execute_dag(self, actor, device, tensor_input, is_dict=False):
"""Create a DAG with tensor transport and execute it."""
with InputNode() as inp:
method = actor.echo_dict_device if is_dict else ... | TestDriverToWorkerDeviceCPU |
python | django-extensions__django-extensions | django_extensions/management/commands/print_settings.py | {
"start": 310,
"end": 2704
} | class ____(BaseCommand):
help = "Print the active Django settings."
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
"setting", nargs="*", help="Specifies setting to be printed."
)
parser.add_argument(
"-f",
... | Command |
python | falconry__falcon | tests/test_recipes.py | {
"start": 1381,
"end": 2106
} | class ____:
@pytest.mark.parametrize(
'recipe,expected_head',
[
('output_csv_text', '"fruit","quantity"\r\n"apples",13\r\n'),
('output_csv_stream', '"n","Fibonacci Fn"\r\n0,0\r\n1,1\r\n'),
],
ids=['simple', 'stream'],
)
def test_csv_output(self, asgi, ... | TestOutputCSV |
python | modin-project__modin | modin/core/execution/ray/implementations/pandas_on_ray/partitioning/virtual_partition.py | {
"start": 9422,
"end": 12439
} | class ____(PandasOnRayDataframeVirtualPartition):
axis = 1
@ray.remote
def _deploy_ray_func(
deployer,
*positional_args,
axis,
f_to_deploy,
f_len_args,
f_kwargs,
extract_metadata=True,
**kwargs,
): # pragma: no cover
"""
Execute a function on an axis partition in a worker ... | PandasOnRayDataframeRowPartition |
python | apache__airflow | providers/amazon/docs/aws/links/ec2.py | {
"start": 1198,
"end": 1712
} | class ____(BaseAwsLink):
"""
Helper class for constructing Amazon EC2 console links.
This is useful for displaying the list of EC2 instances, rather
than a single instance.
"""
name = "EC2 Instances"
key = "_instance_dashboard"
format_str = BASE_AWS_CONSOLE_LINK + "/ec2/home?region={re... | EC2InstanceDashboardLink |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/tryceratops/TRY003.py | {
"start": 0,
"end": 464
} | class ____(Exception):
pass
def func():
a = 1
if a == 1:
raise CustomException("Long message")
elif a == 2:
raise CustomException("Short") # This is acceptable
elif a == 3:
raise CustomException("its_code_not_message") # This is acceptable
def ignore():
try:
... | CustomException |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/embedding_ops_test.py | {
"start": 9495,
"end": 27853
} | class ____(test.TestCase):
# This test looks up [0, 0] in a parameter matrix sharded 2 ways. Since
# both the ids are in the first shard, one of the resulting lookup
# vector is going to be empty. The subsequent DivOp fails because of that.
# TODO(keveman): Disabling the test until the underlying problem is fi... | EmbeddingLookupTest |
python | pandas-dev__pandas | pandas/core/indexing.py | {
"start": 89524,
"end": 91209
} | class ____(_ScalarAccessIndexer):
_takeable = False
def _convert_key(self, key):
"""
Require they keys to be the same type as the index. (so we don't
fallback)
"""
# GH 26989
# For series, unpacking key needs to result in the label.
# This is already the ... | _AtIndexer |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF023.py | {
"start": 1051,
"end": 1452
} | class ____:
__slots__ = (
"d0",
"c0", # a comment regarding 'c0'
"b0",
# a comment regarding 'a0':
"a0"
)
__slots__ = [
"d",
"c", # a comment regarding 'c'
"b",
# a comment regarding 'a':
"a"
]
###########################... | Klass3 |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 308896,
"end": 309599
} | class ____(sgqlc.types.Input):
"""Parameters to be used for the tag_name_pattern rule"""
__schema__ = github_schema
__field_names__ = ("name", "negate", "operator", "pattern")
name = sgqlc.types.Field(String, graphql_name="name")
"""How this rule will appear to users."""
negate = sgqlc.types.F... | TagNamePatternParametersInput |
python | doocs__leetcode | solution/0300-0399/0332.Reconstruct Itinerary/Solution.py | {
"start": 0,
"end": 361
} | class ____:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
def dfs(f: str):
while g[f]:
dfs(g[f].pop())
ans.append(f)
g = defaultdict(list)
for f, t in sorted(tickets, reverse=True):
g[f].append(t)
ans = []
... | Solution |
python | pypa__pipenv | pipenv/patched/pip/_vendor/distlib/metadata.py | {
"start": 958,
"end": 9087
} | class ____(DistlibException):
"""A metadata value is invalid"""
# public API of this module
__all__ = ['Metadata', 'PKG_INFO_ENCODING', 'PKG_INFO_PREFERRED_VERSION']
# Encoding used for the PKG-INFO files
PKG_INFO_ENCODING = 'utf-8'
# preferred version. Hopefully will be changed
# to 1.2 once PEP 345 is support... | MetadataInvalidError |
python | pytorch__pytorch | test/quantization/jit/test_quantize_jit.py | {
"start": 129821,
"end": 143773
} | class ____(QuantizationTestCase):
@override_qengines
def test_single_linear(self):
r"""Compare the result of quantizing single linear layer in
eager mode and graph mode
"""
# eager mode
annotated_linear_model = AnnotatedSingleLayerLinearModel(
torch.backends.q... | TestQuantizeJit |
python | pytorch__pytorch | test/distributions/test_distributions.py | {
"start": 265675,
"end": 274340
} | class ____(DistributionsTestCase):
def setUp(self):
super().setUp()
positive_var = torch.randn(20, dtype=torch.double).exp()
positive_var2 = torch.randn(20, dtype=torch.double).exp()
random_var = torch.randn(20, dtype=torch.double)
simplex_tensor = softmax(torch.randn(20, dty... | TestAgainstScipy |
python | pandas-dev__pandas | pandas/tests/apply/conftest.py | {
"start": 139,
"end": 1877
} | class ____(BaseExecutionEngine):
"""
Execution Engine to test if the execution engine interface receives and
uses all parameters provided by the user.
Making this engine work as the default Python engine by calling it, no extra
functionality is implemented here.
When testing, this will be call... | MockExecutionEngine |
python | pandas-dev__pandas | asv_bench/benchmarks/tslibs/timedelta.py | {
"start": 211,
"end": 1188
} | class ____:
def setup(self):
self.nptimedelta64 = np.timedelta64(3600)
self.dttimedelta = datetime.timedelta(seconds=3600)
self.td = Timedelta(3600, unit="s")
def time_from_int(self):
Timedelta(123456789)
def time_from_unit(self):
Timedelta(1, unit="D")
def tim... | TimedeltaConstructor |
python | huggingface__transformers | src/transformers/models/vitpose/image_processing_vitpose.py | {
"start": 13173,
"end": 29987
} | class ____(BaseImageProcessor):
r"""
Constructs a VitPose image processor.
Args:
do_affine_transform (`bool`, *optional*, defaults to `True`):
Whether to apply an affine transformation to the input images.
size (`dict[str, int]` *optional*, defaults to `{"height": 256, "width": ... | VitPoseImageProcessor |
python | huggingface__transformers | src/transformers/models/ernie/configuration_ernie.py | {
"start": 865,
"end": 6221
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`ErnieModel`]. It is used to
instantiate a ERNIE model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a similar configura... | ErnieConfig |
python | celery__celery | t/unit/app/test_routes.py | {
"start": 7502,
"end": 8026
} | class ____:
def test_prepare(self):
o = object()
R = [
{'foo': 'bar'},
qualname(TestRouter),
o,
]
p = routes.prepare(R)
assert isinstance(p[0], routes.MapRoute)
assert isinstance(maybe_evaluate(p[1]), TestRouter)
assert p[2... | test_prepare |
python | wandb__wandb | wandb/sdk/launch/runner/kubernetes_runner.py | {
"start": 2686,
"end": 8889
} | class ____(AbstractRun):
"""Wrapper for a launched run on Kubernetes."""
def __init__(
self,
batch_api: "BatchV1Api",
core_api: "CoreV1Api",
apps_api: "AppsV1Api",
network_api: "NetworkingV1Api",
name: str,
namespace: Optional[str] = "default",
se... | KubernetesSubmittedRun |
python | kamyu104__LeetCode-Solutions | Python/binary-tree-pruning.py | {
"start": 29,
"end": 409
} | class ____(object):
def pruneTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return None
root.left = self.pruneTree(root.left)
root.right = self.pruneTree(root.right)
if not root.left and not root.right and root... | Solution |
python | sphinx-doc__sphinx | sphinx/util/cfamily.py | {
"start": 3979,
"end": 4124
} | class ____(ASTBaseBase):
def describe_signature(self, signode: TextElement) -> None:
raise NotImplementedError(repr(self))
| ASTAttribute |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/streams/async_job_manager.py | {
"start": 2635,
"end": 7522
} | class ____:
"""
Minimal, state-agnostic manager:
- asks jobs to start when capacity allows (jobs decide if they can start)
- polls jobs in batch for status updates
- yields completed jobs
- accepts 'new_jobs' emitted by jobs (e.g., after split) and puts them into the running set
"""
... | InsightAsyncJobManager |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-braintree/source_braintree/schemas/cards.py | {
"start": 538,
"end": 1257
} | class ____(CatalogModel):
"""
https://developer.paypal.com/braintree/docs/reference/response/credit-card
"""
billing_address: Address
bin: str
card_type: str
cardholder_name: str
commercial: str
country_of_issuance: str
created_at: datetime
customer_id: str
customer_loca... | CreditCard |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/spacetobatch_op_test.py | {
"start": 11596,
"end": 12237
} | class ____(test.TestCase, PythonOpImpl):
# Verifies that: space_to_batch(x) = transpose(space_to_depth(transpose(x)))
@test_util.run_deprecated_v1
def testSpaceToDepthTranspose(self):
x = np.arange(5 * 10 * 16 * 7, dtype=np.float32).reshape([5, 10, 16, 7])
block_size = 2
paddings = np.zeros((2, 2), d... | SpaceToBatchSpaceToDepth |
python | jazzband__prettytable | src/prettytable/prettytable.py | {
"start": 5197,
"end": 106207
} | class ____:
_xhtml: bool
_align: dict[str, AlignType]
_valign: dict[str, VAlignType]
_min_width: dict[str, int]
_max_width: dict[str, int]
_min_table_width: int | None
_max_table_width: int | None
_fields: Sequence[str | None] | None
_title: str | None
_start: int
_end: int |... | PrettyTable |
python | ray-project__ray | doc/source/serve/doc_code/application_level_autoscaling.py | {
"start": 275,
"end": 501
} | class ____:
def __call__(self, preprocessed_data: str) -> str:
# Simulate model inference (takes longer than preprocessing)
time.sleep(0.1)
return f"result_{preprocessed_data}"
@serve.deployment
| Model |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/io_test.py | {
"start": 5840,
"end": 7610
} | class ____(IOTest, checkpoint_test_base.CheckpointTestBase):
@combinations.generate(test_base.eager_only_combinations())
def testSaveCheckpointingAPI(self):
dataset = dataset_ops.Dataset.range(40)
checkpoint_args = {"directory": self._checkpoint_prefix, "max_to_keep": 50}
io.save(dataset, self._save_di... | SaveCheckpointTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.