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 | mlflow__mlflow | mlflow/models/evaluation/default_evaluator.py | {
"start": 10552,
"end": 41950
} | class ____(ModelEvaluator):
"""
The base class for all evaluators that are built-in to MLflow.
Each evaluator is responsible for implementing the `_evaluate()` method, which is called by
the `evaluate()` method of this base class. This class contains many helper methods used
across built-in evaluat... | BuiltInEvaluator |
python | pytorch__pytorch | torch/_dynamo/_trace_wrapped_higher_order_op.py | {
"start": 5070,
"end": 6127
} | class ____(TorchFunctionMode):
# This is needed since we want to support calling
# A[q_idx], where q_idx is a scalar tensor in score_mod.
# Today, when q_idx is a scalar tensor, we implicitly convert it to a python
# scalar and create a view. We do not want that behavior in this case, so we
# use th... | TransformGetItemToIndex |
python | PyCQA__pylint | tests/functional/n/no/no_member_dataclasses.py | {
"start": 2029,
"end": 2312
} | class ____:
attr1: str
attr2: str
dict_prop = field(default_factory=dict) # No type annotation, not treated as field
def some_func(self) -> None:
for key, value in self.dict_prop.items(): # [no-member]
print(key)
print(value)
| TestClass3 |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-firestore/destination_firestore/writer.py | {
"start": 193,
"end": 1182
} | class ____:
def __init__(self, project_id: str, credentials_json: Optional[str] = None):
connection = {}
connection["project"] = project_id
if credentials_json:
try:
json_account_info = json.loads(credentials_json)
except ValueError:
... | FirestoreWriter |
python | ApeWorX__ape | src/ape/utils/abi.py | {
"start": 20761,
"end": 21044
} | class ____(str, Enum):
"""
Control the display of calldata in Ape.
"""
abridged = "abridged"
"""
Show the first and last 4-bytes of the calldata, enough
to see the method ID.
"""
full = "full"
"""
Show the full calldata.
"""
| CalldataRepr |
python | python-pillow__Pillow | src/PIL/ImageTransform.py | {
"start": 3184,
"end": 3638
} | class ____(Transform):
"""
Define a quad image transform.
Maps a quadrilateral (a region defined by four corners) from the image to a
rectangle of the given size.
See :py:meth:`.Image.transform`
:param xy: An 8-tuple (x0, y0, x1, y1, x2, y2, x3, y3) which contain the
upper left, lower... | QuadTransform |
python | getsentry__sentry | src/sentry/analytics/events/relocation_organization_imported.py | {
"start": 89,
"end": 289
} | class ____(analytics.Event):
organization_id: int
relocation_uuid: str
owner_id: int
slug: str
analytics.register(RelocationOrganizationImportedEvent)
| RelocationOrganizationImportedEvent |
python | pydata__xarray | xarray/tests/test_backends.py | {
"start": 204740,
"end": 207863
} | class ____(TestH5NetCDFData, FileObjectNetCDF):
engine: T_NetcdfEngine = "h5netcdf"
def test_open_badbytes(self) -> None:
with pytest.raises(
ValueError, match=r"match in any of xarray's currently installed IO"
):
with open_dataset(b"garbage"):
pass
... | TestH5NetCDFFileObject |
python | sympy__sympy | sympy/functions/special/polynomials.py | {
"start": 39251,
"end": 42597
} | class ____(OrthogonalPolynomial):
r"""
Returns the $n$th Laguerre polynomial in $x$, $L_n(x)$.
Examples
========
>>> from sympy import laguerre, diff
>>> from sympy.abc import x, n
>>> laguerre(0, x)
1
>>> laguerre(1, x)
1 - x
>>> laguerre(2, x)
x**2/2 - 2*x + 1
>>>... | laguerre |
python | huggingface__transformers | src/transformers/generation/logits_process.py | {
"start": 105004,
"end": 107633
} | class ____(LogitsProcessor):
"""
This processor can be used to detect silence when using Whisper. It should take as input unprocessed logits
to follow the original implementation
"""
def __init__(self, no_speech_token: int, begin_index: int, scores_is_logprobs: bool = False):
self.no_speech... | WhisperNoSpeechDetection |
python | Lightning-AI__lightning | tests/tests_pytorch/checkpointing/test_model_checkpoint.py | {
"start": 38150,
"end": 38411
} | class ____(BoringModel):
def optimizer_step(self, epoch, batch_idx, optimizer, optimizer_closure=None):
optimizer.step(closure=optimizer_closure)
if self.current_epoch == 1:
raise RuntimeError("Trouble!")
| TroubledModelOptimizerStep |
python | huggingface__transformers | src/transformers/models/llava_onevision/image_processing_llava_onevision_fast.py | {
"start": 1886,
"end": 13931
} | class ____(BaseImageProcessorFast):
model_input_names = ["pixel_values", "image_sizes", "batch_num_images"]
resample = PILImageResampling.BICUBIC
image_mean = OPENAI_CLIP_MEAN
image_std = OPENAI_CLIP_STD
size = {"height": 384, "width": 384}
default_to_square = False
crop_size = None
do_r... | LlavaOnevisionImageProcessorFast |
python | conda__conda | conda/testing/solver_helpers.py | {
"start": 6080,
"end": 47104
} | class ____:
"""Tests for :py:class:`conda.core.solve.Solver` implementations."""
@property
def solver_class(self) -> type[Solver]:
"""Class under test."""
raise NotImplementedError
@property
def tests_to_skip(self):
return {} # skip reason -> list of tests to skip
@py... | SolverTests |
python | python-openxml__python-docx | src/docx/section.py | {
"start": 10254,
"end": 14443
} | class ____(BlockItemContainer):
"""Base class for header and footer classes."""
def __init__(
self,
sectPr: CT_SectPr,
document_part: DocumentPart,
header_footer_index: WD_HEADER_FOOTER,
):
self._sectPr = sectPr
self._document_part = document_part
sel... | _BaseHeaderFooter |
python | huggingface__transformers | src/transformers/models/sam3_tracker_video/modular_sam3_tracker_video.py | {
"start": 19782,
"end": 26280
} | class ____(Sam2VideoModel):
_checkpoint_conversion_mapping = {
r"tracker_model.(.+)": r"\1", # the regex allows to remove the prefix, and add it back in revert mode
"detector_model.vision_encoder.backbone.": "vision_encoder.backbone.",
"tracker_neck.": "vision_encoder.neck.",
}
_key... | Sam3TrackerVideoModel |
python | doocs__leetcode | solution/3100-3199/3153.Sum of Digit Differences of All Pairs/Solution.py | {
"start": 0,
"end": 398
} | class ____:
def sumDigitDifferences(self, nums: List[int]) -> int:
n = len(nums)
m = int(log10(nums[0])) + 1
ans = 0
for _ in range(m):
cnt = Counter()
for i, x in enumerate(nums):
nums[i], y = divmod(x, 10)
cnt[y] += 1
... | Solution |
python | readthedocs__readthedocs.org | readthedocs/api/v3/routers.py | {
"start": 162,
"end": 590
} | class ____(APIRootView):
# Overridden only to add documentation for BrowsableAPIRenderer.
# noqa
"""
Each request requires an `Authorization` HTTP header with `Token <your-token>`,
find the token in [your account](/accounts/tokens/).
Read the full documentation at <https://docs.readthedocs.io/... | DocsAPIRootView |
python | falconry__falcon | tests/test_httperror.py | {
"start": 5365,
"end": 5563
} | class ____:
def on_get(self, req, resp):
raise falcon.HTTPContentTooLarge(
title='Request Rejected', description='Request Body Too Large'
)
| RequestEntityTooLongResource |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_textbox34.py | {
"start": 315,
"end": 863
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("textbox34.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with textbox(s)."""
workbook = Workb... | TestCompareXLSXFiles |
python | mlflow__mlflow | mlflow/server/graphql/graphql_errors.py | {
"start": 221,
"end": 432
} | class ____(graphene.ObjectType):
code = graphene.String()
message = graphene.String()
help_url = graphene.String()
trace_id = graphene.String()
error_details = graphene.List(ErrorDetail)
| ApiError |
python | django-debug-toolbar__django-debug-toolbar | debug_toolbar/_stubs.py | {
"start": 378,
"end": 471
} | class ____(dj_template.context.RenderContext):
template: dj_template.Template
| RenderContext |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_S.py | {
"start": 15918,
"end": 17166
} | class ____(Benchmark):
r"""
Schwefel 22 objective function.
This class defines the Schwefel 22 [1]_ global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{Schwefel22}}(x) = \sum_{i=1}^n \lvert x_i \rvert
... | Schwefel22 |
python | keras-team__keras | keras/src/models/sequential_test.py | {
"start": 404,
"end": 12649
} | class ____(testing.TestCase):
def test_basic_flow_with_input(self):
model = Sequential(name="seq")
model.add(Input(shape=(2,), batch_size=3))
model.add(layers.Dense(4))
model.add(layers.Dense(5))
model.summary()
self.assertEqual(len(model.layers), 2)
self.ass... | SequentialTest |
python | doocs__leetcode | solution/0400-0499/0423.Reconstruct Original Digits from English/Solution.py | {
"start": 0,
"end": 557
} | class ____:
def originalDigits(self, s: str) -> str:
counter = Counter(s)
cnt = [0] * 10
cnt[0] = counter['z']
cnt[2] = counter['w']
cnt[4] = counter['u']
cnt[6] = counter['x']
cnt[8] = counter['g']
cnt[3] = counter['h'] - cnt[8]
cnt[5] = cou... | Solution |
python | getsentry__sentry | src/sentry/integrations/on_call/metrics.py | {
"start": 1820,
"end": 2068
} | class ____(StrEnum):
"""
Reasons why on on call integration method may halt without success/failure.
"""
INVALID_TEAM = "invalid_team"
INVALID_SERVICE = "invalid_service"
INVALID_KEY = "invalid_key"
| OnCallIntegrationsHaltReason |
python | getsentry__sentry | src/sentry/quotas/base.py | {
"start": 886,
"end": 1140
} | class ____(IntEnum):
ORGANIZATION = 1
PROJECT = 2
KEY = 3
GLOBAL = 4
def api_name(self):
return self.name.lower()
AbuseQuotaScope = Literal[QuotaScope.ORGANIZATION, QuotaScope.PROJECT, QuotaScope.GLOBAL]
@dataclass
| QuotaScope |
python | scipy__scipy | scipy/stats/_multivariate.py | {
"start": 254996,
"end": 258612
} | class ____(multi_rv_frozen):
def __init__(self, mu=None, kappa=1, seed=None):
"""Create a frozen von Mises-Fisher distribution.
Parameters
----------
mu : array_like, default: None
Mean direction of the distribution.
kappa : float, default: 1
Concentr... | vonmises_fisher_frozen |
python | pennersr__django-allauth | allauth/mfa/webauthn/stages.py | {
"start": 172,
"end": 507
} | class ____(LoginStage):
key = LoginStageKey.MFA_SIGNUP_WEBAUTHN.value
urlname = "mfa_signup_webauthn"
def handle(self):
response, cont = None, True
if self.login.state.get("passkey_signup"):
response = headed_redirect_response("mfa_signup_webauthn")
return response, cont... | PasskeySignupStage |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/elements.py | {
"start": 40515,
"end": 41111
} | class ____(
SQLCoreOperations[_T_co], roles.ExpressionElementRole[_T_co], TypingOnly
):
"""A type that may be used to indicate any SQL column element or object
that acts in place of one.
:class:`.SQLColumnExpression` is a base of
:class:`.ColumnElement`, as well as within the bases of ORM elements
... | SQLColumnExpression |
python | openai__openai-python | src/openai/types/responses/response_input_item.py | {
"start": 12271,
"end": 13282
} | class ____(BaseModel):
id: str
"""The unique ID of the tool call."""
arguments: str
"""A JSON string of the arguments passed to the tool."""
name: str
"""The name of the tool that was run."""
server_label: str
"""The label of the MCP server running the tool."""
type: Literal["mcp... | McpCall |
python | mlflow__mlflow | mlflow/types/llm.py | {
"start": 25094,
"end": 25905
} | class ____(_BaseDataclass):
"""
Stats about the number of tokens used during inference.
Args:
prompt_tokens (int): The number of tokens in the prompt.
**Optional**, defaults to ``None``
completion_tokens (int): The number of tokens in the generated completion.
**Opti... | TokenUsageStats |
python | google__jax | jax/_src/dtypes.py | {
"start": 23847,
"end": 40818
} | class ____(ValueError):
pass
# We don't use util.memoize because there is no implicit X64 dependence.
@functools.lru_cache(512)
def _least_upper_bound(jax_numpy_dtype_promotion: config.NumpyDtypePromotion,
x64: bool, *nodes: JAXType) -> JAXType:
"""Compute the least upper bound of a set of n... | TypePromotionError |
python | euske__pdfminer | pdfminer/pdffont.py | {
"start": 2413,
"end": 4888
} | class ____(PSStackParser):
KEYWORD_BEGIN = KWD(b'begin')
KEYWORD_END = KWD(b'end')
KEYWORD_DEF = KWD(b'def')
KEYWORD_PUT = KWD(b'put')
KEYWORD_DICT = KWD(b'dict')
KEYWORD_ARRAY = KWD(b'array')
KEYWORD_READONLY = KWD(b'readonly')
KEYWORD_FOR = KWD(b'for')
KEYWORD_FOR = KWD(b'for')
... | Type1FontHeaderParser |
python | django__django | tests/generic_views/test_base.py | {
"start": 23622,
"end": 24444
} | class ____(SimpleTestCase):
rf = RequestFactory()
def test_use_queryset_from_view(self):
test_view = views.CustomMultipleObjectMixinView()
test_view.get(self.rf.get("/"))
# Don't pass queryset as argument
context = test_view.get_context_data()
self.assertEqual(context["o... | UseMultipleObjectMixinTest |
python | jackfrued__Python-100-Days | Day31-35/code/example14.py | {
"start": 1222,
"end": 1940
} | class ____():
"""玩家"""
def __init__(self, name):
self.name = name
self.cards = []
def get_card(self, card):
"""摸牌"""
self.cards.append(card)
def arrange(self):
"""整理手上的牌"""
self.cards.sort(key=lambda card: (card.suite, card.face))
def main():
"""主... | Player |
python | huggingface__transformers | src/transformers/models/dinov3_vit/modular_dinov3_vit.py | {
"start": 11822,
"end": 11863
} | class ____(ArceeMLP):
pass
| DINOv3ViTMLP |
python | joke2k__faker | faker/providers/address/nl_BE/__init__.py | {
"start": 45,
"end": 64941
} | class ____(AddressProvider):
building_number_formats = ("#", "##", "###", "#", "##", "###")
street_suffixes = (
"baan",
"boulevard",
"dreef",
"hof",
"laan",
"lei",
"pad",
"ring",
"singel",
"steeg",
"straat",
"weg",
... | Provider |
python | readthedocs__readthedocs.org | readthedocs/core/settings.py | {
"start": 90,
"end": 804
} | class ____:
"""Class-based settings wrapper."""
@classmethod
def load_settings(cls, module_name):
"""
Export class variables and properties to module namespace.
This will export and class variable that is all upper case and doesn't
begin with ``_``. These members will be s... | Settings |
python | pytorch__pytorch | torch/_dynamo/debug_utils.py | {
"start": 22794,
"end": 32624
} | class ____:
def __init__(self, save_dir: Optional[str], *, stable_hash: bool = False) -> None:
self._lines: list[str] = []
# TODO: consider ensuring tensor and storage counters line up?
self.storage_counter = itertools.count()
self.save_dir = save_dir
self.store = (
... | InputWriter |
python | pennersr__django-allauth | allauth/headless/mfa/views.py | {
"start": 7613,
"end": 8240
} | class ____(APIView):
input_class = {
"POST": LoginWebAuthnInput,
}
def get(self, request, *args, **kwargs):
request_options = webauthn_auth.begin_authentication()
return response.WebAuthnRequestOptionsResponse(request, request_options)
def post(self, request, *args, **kwargs):
... | LoginWebAuthnView |
python | davidhalter__jedi | jedi/inference/value/dynamic_arrays.py | {
"start": 6991,
"end": 7312
} | class ____(_Modification):
def py__iter__(self, contextualized_node=None):
yield from self._wrapped_value.py__iter__(contextualized_node)
yield self._contextualized_key
def get_key_values(self):
return self._wrapped_value.get_key_values() | self._contextualized_key.infer()
| DictModification |
python | sqlalchemy__sqlalchemy | test/orm/declarative/test_tm_future_annotations_sync.py | {
"start": 135679,
"end": 148092
} | class ____(fixtures.TestBase, testing.AssertsCompiledSQL):
__dialect__ = "default"
@testing.fixture
def dataclass_point_fixture(self, decl_base):
@dataclasses.dataclass
class Point:
x: int
y: int
class Edge(decl_base):
__tablename__ = "edge"
... | CompositeTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/coercions.py | {
"start": 27211,
"end": 27285
} | class ____(_NoTextCoercion, RoleImpl):
__slots__ = ()
| ColumnArgumentImpl |
python | pypa__warehouse | warehouse/oidc/models/activestate.py | {
"start": 1552,
"end": 4949
} | class ____:
"""
Common functionality for both pending and concrete ActiveState OIDC publishers.
"""
organization: Mapped[str] = mapped_column(String, nullable=False)
activestate_project_name: Mapped[str] = mapped_column(String, nullable=False)
actor: Mapped[str] = mapped_column(String, nullable... | ActiveStatePublisherMixin |
python | ansible__ansible | lib/ansible/playbook/__init__.py | {
"start": 1206,
"end": 4766
} | class ____:
def __init__(self, loader):
# Entries in the datastructure of a playbook may
# be either a play or an include statement
self._entries = []
self._basedir = to_text(os.getcwd(), errors='surrogate_or_strict')
self._loader = loader
self._file_name = None
... | Playbook |
python | aimacode__aima-python | probability.py | {
"start": 7649,
"end": 9988
} | class ____(Agent):
"""
[Figure 16.9]
A simple information gathering agent. The agent works by repeatedly selecting
the observation with the highest information value, until the cost of the next
observation is greater than its expected benefit."""
def __init__(self, decnet, infer, initial_eviden... | InformationGatheringAgent |
python | jmcnamara__XlsxWriter | xlsxwriter/exceptions.py | {
"start": 525,
"end": 622
} | class ____(XlsxInputError):
"""Chart must contain at least one data series."""
| EmptyChartSeries |
python | pytorch__pytorch | test/mobile/test_upgraders.py | {
"start": 329,
"end": 2613
} | class ____(TestCase):
def _save_load_mobile_module(self, script_module: torch.jit.ScriptModule):
buffer = io.BytesIO(
script_module._save_to_buffer_for_lite_interpreter(
_save_mobile_debug_info=True
)
)
buffer.seek(0)
mobile_module = _load_for_... | TestLiteScriptModule |
python | pyca__cryptography | src/cryptography/hazmat/primitives/hashes.py | {
"start": 2378,
"end": 2493
} | class ____(HashAlgorithm): # noqa: N801
name = "sha512-256"
digest_size = 32
block_size = 128
| SHA512_256 |
python | scikit-learn__scikit-learn | sklearn/random_projection.py | {
"start": 16104,
"end": 20841
} | class ____(BaseRandomProjection):
"""Reduce dimensionality through Gaussian random projection.
The components of the random matrix are drawn from N(0, 1 / n_components).
Read more in the :ref:`User Guide <gaussian_random_matrix>`.
.. versionadded:: 0.13
Parameters
----------
n_components... | GaussianRandomProjection |
python | pypa__hatch | tests/cli/status/test_status.py | {
"start": 147,
"end": 1056
} | class ____:
def test_no_project(self, hatch, isolation, config_file, helpers):
result = hatch("status")
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
f"""
[Project] - <no project detected>
[Location] - {isolation}
... | TestModeLocalDefault |
python | huggingface__transformers | src/transformers/models/mimi/modeling_mimi.py | {
"start": 21253,
"end": 26115
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: MimiConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.co... | MimiRotaryEmbedding |
python | neetcode-gh__leetcode | python/0200-number-of-islands.py | {
"start": 0,
"end": 860
} | class ____:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid or not grid[0]:
return 0
islands = 0
visit = set()
rows, cols = len(grid), len(grid[0])
def dfs(r, c):
if (
r not in range(rows)
or c not in r... | Solution |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/sensors/emr.py | {
"start": 6796,
"end": 9125
} | class ____(AwsBaseSensor[EmrServerlessHook]):
"""
Poll the state of the application until it reaches a terminal state; fails if the application fails.
.. seealso::
For more information on how to use this sensor, take a look at the guide:
:ref:`howto/sensor:EmrServerlessApplicationSensor`
... | EmrServerlessApplicationSensor |
python | python-attrs__attrs | src/attr/exceptions.py | {
"start": 98,
"end": 456
} | class ____(AttributeError):
"""
A frozen/immutable instance or attribute have been attempted to be
modified.
It mirrors the behavior of ``namedtuples`` by using the same error message
and subclassing `AttributeError`.
.. versionadded:: 20.1.0
"""
msg = "can't set attribute"
args: ... | FrozenError |
python | euske__pdfminer | pdfminer/layout.py | {
"start": 3977,
"end": 4127
} | class ____(LTCurve):
def __init__(self, linewidth, p0, p1):
LTCurve.__init__(self, linewidth, [p0, p1])
return
## LTRect
##
| LTLine |
python | django__django | tests/model_options/models/tablespaces.py | {
"start": 1059,
"end": 1881
} | class ____(models.Model):
title = models.CharField(max_length=50, unique=True)
code = models.CharField(max_length=50, unique=True, db_tablespace="idx_tbsp")
authors = models.ManyToManyField(Scientist, related_name="articles_written_set")
reviewers = models.ManyToManyField(
Scientist, related_nam... | Article |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 15240,
"end": 15355
} | class ____(PydanticValueError):
msg_template = 'value is not a valid IPv4 or IPv6 interface'
| IPvAnyInterfaceError |
python | automl__auto-sklearn | test/test_util/test_backend.py | {
"start": 150,
"end": 2625
} | class ____(unittest.TestCase):
class BackendStub(Backend):
def __init__(self):
self.__class__ = Backend
def setUp(self):
self.backend = self.BackendStub()
self.backend.internals_directory = "/"
@unittest.mock.patch("pickle.load")
@unittest.mock.patch("os.path.exists... | BackendModelsTest |
python | pytorch__pytorch | test/distributed/test_store.py | {
"start": 30570,
"end": 31104
} | class ____(dist.Store):
def __init__(self) -> None:
self.appends = []
self.multi_sets = []
self.multi_gets = []
self.multi_get_res = []
super().__init__()
def append(self, key, value):
self.appends.append((key, value))
def multi_get(self, keys):
self... | DummyStore |
python | pytorch__pytorch | torch/utils/data/datapipes/dataframe/dataframe_wrapper.py | {
"start": 540,
"end": 3288
} | class ____:
@classmethod
def create_dataframe(cls, data, columns):
if not _with_pandas():
raise RuntimeError("DataFrames prototype requires pandas to function")
return _pandas.DataFrame(data, columns=columns) # type: ignore[union-attr]
@classmethod
def is_dataframe(cls, dat... | PandasWrapper |
python | huggingface__transformers | src/transformers/models/timesfm/modular_timesfm.py | {
"start": 3972,
"end": 5938
} | class ____(nn.Module):
"""Generates position embedding for a given 1-d sequence."""
def __init__(self, config: TimesFmConfig):
super().__init__()
min_timescale = config.min_timescale
max_timescale = config.max_timescale
self.embedding_dims = config.hidden_size
num_times... | TimesFmPositionalEmbedding |
python | kamyu104__LeetCode-Solutions | Python/equalize-strings-by-adding-or-removing-characters-at-ends.py | {
"start": 2056,
"end": 2611
} | class ____(object):
def minOperations(self, initial, target):
"""
:type initial: str
:type target: str
:rtype: int
"""
if len(initial) < len(target):
initial, target = target, initial
result = 0
dp = [0]*(len(target)+1)
for i in xra... | Solution3 |
python | huggingface__transformers | src/transformers/models/reformer/configuration_reformer.py | {
"start": 849,
"end": 13196
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`ReformerModel`]. It is used to instantiate a
Reformer model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar con... | ReformerConfig |
python | catalyst-team__catalyst | catalyst/contrib/losses/recsys.py | {
"start": 5748,
"end": 7269
} | class ____(PairwiseLoss):
"""Adaptive hinge loss function.
Takes a set of predictions for implicitly negative items, and selects those
that are highest, thus sampling those negatives that are closes to violating
the ranking implicit in the pattern of user interactions.
Example:
.. code-block:... | AdaptiveHingeLoss |
python | etianen__django-reversion | reversion/errors.py | {
"start": 0,
"end": 110
} | class ____(Exception):
"""Exception thrown when something goes wrong with reverting a model."""
| RevertError |
python | tensorflow__tensorflow | tensorflow/python/framework/convert_to_constants.py | {
"start": 24699,
"end": 27144
} | class ____(_Convertible):
"""A convertible GraphDef."""
def __init__(self, graph_def):
super(_GraphDef, self).__init__(enclosing_graph=None)
self._graph_def = graph_def
self._nodes = {
n.name: _Node.new(node=n, function=None, enclosing_graph=self)
for n in graph_def.node
}
self.... | _GraphDef |
python | getsentry__sentry | tests/sentry/sentry_apps/api/endpoints/test_sentry_app_rotate_secret.py | {
"start": 268,
"end": 4659
} | class ____(APITestCase):
def setUp(self) -> None:
self.application = ApiApplication.objects.create(owner=self.user)
self.sentry_app = SentryApp.objects.create(
application=self.application, owner_id=self.organization.id, name="a", slug="a"
)
self.url = reverse("sentry-api... | SentryAppRotateSecretTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-pgvector/destination_pgvector/pgvector_processor.py | {
"start": 2034,
"end": 9426
} | class ____(SqlProcessorBase):
"""A PGVector implementation of the SQL Processor."""
supports_merge_insert = False
"""We use the emulated merge code path because each primary key has multiple rows (chunks)."""
sql_config: PostgresConfig
"""The configuration for the PGVector processor, including the... | PGVectorProcessor |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vector_index.py | {
"start": 3693,
"end": 3901
} | class ____(_VectorIndexConfigCreate):
vectorCacheMaxObjects: Optional[int]
@staticmethod
def vector_index_type() -> VectorIndexType:
return VectorIndexType.FLAT
| _VectorIndexConfigFlatCreate |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 125955,
"end": 126219
} | class ____:
xlVAlignBottom = -4107 # from enum XlVAlign
xlVAlignCenter = -4108 # from enum XlVAlign
xlVAlignDistributed = -4117 # from enum XlVAlign
xlVAlignJustify = -4130 # from enum XlVAlign
xlVAlignTop = -4160 # from enum XlVAlign
| VAlign |
python | huggingface__transformers | tests/models/gemma3/test_processing_gemma3.py | {
"start": 880,
"end": 7801
} | class ____(ProcessorTesterMixin, unittest.TestCase):
processor_class = Gemma3Processor
@classmethod
def _setup_test_attributes(cls, processor):
cls.image_token = processor.boi_token
@classmethod
def _setup_image_processor(cls):
image_processor_class = cls._get_component_class_from_... | Gemma3ProcessorTest |
python | vyperlang__vyper | vyper/semantics/types/base.py | {
"start": 621,
"end": 1411
} | class ____:
def __repr__(self):
return f"GenericTypeAcceptor({self.type_})"
def __init__(self, type_):
self.type_ = type_
def compare_type(self, other):
if isinstance(other, self.type_):
return True
# compare two GenericTypeAcceptors -- they are the same if the ... | _GenericTypeAcceptor |
python | kamyu104__LeetCode-Solutions | Python/two-sum-iv-input-is-a-bst.py | {
"start": 29,
"end": 1392
} | class ____(object):
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
class BSTIterator(object):
def __init__(self, root, forward):
self.__node = root
self.__forward = forward
... | Solution |
python | keras-team__keras | keras/src/saving/saving_api_test.py | {
"start": 417,
"end": 4262
} | class ____(test_case.TestCase):
def get_model(self):
return Sequential(
[
layers.Dense(5, input_shape=(3,)),
layers.Softmax(),
]
)
def test_basic_saving(self):
"""Test basic model saving and loading."""
model = self.get_mod... | SaveModelTests |
python | django__django | django/http/response.py | {
"start": 23650,
"end": 24069
} | class ____(HttpResponse):
status_code = 304
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
del self["content-type"]
@HttpResponse.content.setter
def content(self, value):
if value:
raise AttributeError(
"You cannot set content... | HttpResponseNotModified |
python | allegroai__clearml | clearml/backend_interface/session.py | {
"start": 406,
"end": 816
} | class ____(object):
"""Session wrapper interface providing a session property and a send convenience method"""
@property
@abstractmethod
def session(self) -> Any:
pass
@abstractmethod
def send(
self,
req: Any,
ignore_errors: bool = False,
raise_on_errors... | SessionInterface |
python | spack__spack | lib/spack/spack/binary_distribution.py | {
"start": 109382,
"end": 109571
} | class ____(spack.error.SpackError):
"""
Raised if directory layout is different from buildcache.
"""
def __init__(self, msg):
super().__init__(msg)
| NewLayoutException |
python | Lightning-AI__lightning | tests/tests_pytorch/trainer/logging_/test_distributed_logging.py | {
"start": 905,
"end": 1515
} | class ____(Logger):
"""Logger to test all-rank logging (i.e. not just rank 0).
Logs are saved to local variable `logs`.
"""
def __init__(self):
super().__init__()
self.logs = {}
self.exp = object()
def experiment(self) -> Any:
return self.exp
def log_metrics(... | AllRankLogger |
python | automl__auto-sklearn | test/test_pipeline/components/classification/test_adaboost.py | {
"start": 170,
"end": 777
} | class ____(BaseClassificationComponentTest):
__test__ = True
res = dict()
res["default_iris"] = 0.93999999999999995
res["default_iris_iterative"] = -1
res["default_iris_proba"] = 0.22452300738472031
res["default_iris_sparse"] = 0.85999999999999999
res["default_digits"] = 0.6879174256223437... | AdaBoostComponentTest |
python | pytorch__pytorch | torch/_dynamo/variables/ctx_manager.py | {
"start": 37136,
"end": 38455
} | class ____(ContextWrappingVariable):
"""
This class represents a set of torch profiler context objects, where Dynamo
ignores all the side-effects in the __init__, __enter__ and __exit__ methods
by treating the object mostly as a `contextlib.nullcontext`, except for edge
cases like the `__enter__` me... | ProfilerContextVariable |
python | keras-team__keras | keras/src/backend/common/variables_test.py | {
"start": 46492,
"end": 47067
} | class ____(test_case.TestCase):
def test_standardize_shape_with_torch_size(self):
import torch
tensor = torch.randn(3, 4, 5)
shape = tensor.size()
standardized_shape = standardize_shape(shape)
self.assertEqual(standardized_shape, (3, 4, 5))
self.assertIs(type(standar... | TestStandardizeShapeWithTorch |
python | ray-project__ray | rllib/offline/estimators/fqe_torch_model.py | {
"start": 631,
"end": 11812
} | class ____:
"""Pytorch implementation of the Fitted Q-Evaluation (FQE) model from
https://arxiv.org/abs/1911.06854
"""
def __init__(
self,
policy: Policy,
gamma: float,
model_config: ModelConfigDict = None,
n_iters: int = 1,
lr: float = 1e-3,
min_... | FQETorchModel |
python | getsentry__sentry | src/sentry/api/bases/organization.py | {
"start": 8638,
"end": 8899
} | class ____(OrganizationPermission):
scope_map = {
"GET": ["org:read", "org:write", "org:admin"],
"POST": ["org:read", "org:write", "org:admin"],
"DELETE": ["org:write", "org:admin"],
}
| OrganizationFlagWebHookSigningSecretPermission |
python | uqfoundation__dill | dill/tests/test_recursive.py | {
"start": 1636,
"end": 1825
} | class ____(object):
def __init__(self):
self.child = Model()
self.trigger = partial(get_trigger, self)
self.child.trigger = partial(get_trigger, self.child)
| Machine |
python | tensorflow__tensorflow | tensorflow/python/distribute/checkpointing_test.py | {
"start": 1076,
"end": 2949
} | class ____(test.TestCase, parameterized.TestCase):
@combinations.generate(
combinations.combine(
distribution=[
strategy_combinations.mirrored_strategy_with_one_cpu,
strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
strategy_combinations.tpu_strategy,... | TrainingCheckpointTests |
python | tensorflow__tensorflow | tensorflow/compiler/tests/function_test.py | {
"start": 1044,
"end": 4818
} | class ____(xla_test.XLATestCase):
def testFunction(self):
"""Executes a simple TensorFlow function."""
def APlus2B(a, b):
return a + b * 2
aval = np.array([4, 3, 2, 1]).reshape([2, 2]).astype(np.float32)
bval = np.array([5, 6, 7, 8]).reshape([2, 2]).astype(np.float32)
expected = APlus2B(a... | FunctionTest |
python | spyder-ide__spyder | spyder/plugins/profiler/widgets/profiler_data_tree.py | {
"start": 7675,
"end": 14796
} | class ____(QTreeWidgetItem):
"""Item to show in the tree. It represent a function call."""
def __init__(self, parent, item_key, profile_data, compare_data, icon_list,
index_dict):
QTreeWidgetItem.__init__(self, parent)
self.item_key = item_key
self.index_dict = index_di... | TreeWidgetItem |
python | getsentry__sentry | src/sentry/testutils/helpers/notifications.py | {
"start": 2214,
"end": 11566
} | class ____(DummyNotification):
group: Group
def get_notification_title(
self, provider: ExternalProviders, context: Mapping[str, Any] | None = None
) -> str:
assert context is not None
some_value = context["some_field"]
return f"Notification Title with {some_value}"
def... | DummyNotificationWithMoreFields |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_variables.py | {
"start": 17791,
"end": 23890
} | class ____(TestVariableEndpoint):
@pytest.mark.enable_redact
@pytest.mark.parametrize(
("body", "expected_response"),
[
(
{
"key": "new variable key",
"value": "new variable value",
"description": "new variab... | TestPostVariable |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 94210,
"end": 96144
} | class ____(GeneratedAirbyteSource):
@public
def __init__(
self,
name: str,
client_id: str,
refresh_token: str,
developer_token: str,
reports_start_date: str,
auth_method: Optional[str] = None,
tenant_id: Optional[str] = None,
client_secret:... | BingAdsSource |
python | huggingface__transformers | src/transformers/models/xmod/modeling_xmod.py | {
"start": 14627,
"end": 15310
} | class ____(nn.Module):
# Copied from transformers.models.roberta.modeling_roberta.RobertaSelfOutput.__init__
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_no... | XmodSelfOutput |
python | tiangolo__fastapi | scripts/notify_translations.py | {
"start": 1770,
"end": 1861
} | class ____(BaseModel):
updateDiscussionComment: UpdateDiscussionComment
| UpdateCommentData |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 207832,
"end": 208319
} | class ____(TestCase):
def test_basic(self) -> None:
greetings = ['Hello', 'Goodbye']
names = ['Alice', 'Bob', 'Carol']
greet = lambda greeting, name: f'{greeting}, {name}!'
result = list(mi.outer_product(greet, greetings, names))
expected = [
('Hello, Alice!', 'He... | OuterProductTests |
python | huggingface__transformers | src/transformers/models/llava_next_video/modular_llava_next_video.py | {
"start": 12160,
"end": 12242
} | class ____(LlavaNextMultiModalProjector):
pass
| LlavaNextVideoMultiModalProjector |
python | pandas-dev__pandas | pandas/tests/arrays/sparse/test_libsparse.py | {
"start": 6480,
"end": 11877
} | class ____:
def test_int_internal(self):
idx = make_sparse_index(4, np.array([2, 3], dtype=np.int32), kind="integer")
assert isinstance(idx, IntIndex)
assert idx.npoints == 2
tm.assert_numpy_array_equal(idx.indices, np.array([2, 3], dtype=np.int32))
idx = make_sparse_index(4... | TestSparseIndexCommon |
python | pydantic__pydantic | pydantic/types.py | {
"start": 36970,
"end": 37190
} | class ____(BaseModel):
uuid8: UUID8
Model(uuid8=uuid.UUID('81a0b92e-6078-8551-9c81-8ccb666bdab8'))
```
"""
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PATH TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@_dataclasses.dataclass
| Model |
python | sqlalchemy__sqlalchemy | test/orm/test_query.py | {
"start": 91059,
"end": 91893
} | class ____(QueryTest):
def test_clause_element_query_resolve(self):
from sqlalchemy.orm.properties import ColumnProperty
User = self.classes.User
class Comparator(ColumnProperty.Comparator):
def __init__(self, expr):
self.expr = expr
def __clause_el... | ComparatorTest |
python | chroma-core__chroma | chromadb/telemetry/product/events.py | {
"start": 4242,
"end": 6750
} | class ____(ProductTelemetryEvent):
max_batch_size: ClassVar[int] = 3000
batch_size: int
collection_uuid: str
query_amount: int
filtered_ids_amount: int
with_metadata_filter: int
with_document_filter: int
n_results: int
include_metadatas: int
include_documents: int
include_uri... | CollectionQueryEvent |
python | getsentry__sentry | src/sentry/dynamic_sampling/rules/combinators/base.py | {
"start": 516,
"end": 1530
} | class ____(ABC):
"""
Base class representing a way to define total order between biases.
The need of this class arises as there is the need to be explicit w.r.t to the ordering semantics of the biases.
"""
def __init__(self) -> None:
self.biases: dict[RuleType, OrderedBias] = {}
def a... | BiasesCombinator |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.