language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-firestore/llama_index/vector_stores/firestore/base.py | {
"start": 2708,
"end": 8515
} | class ____(BasePydanticVectorStore):
"""Firestore Vector Store."""
stores_text: bool = True
flat_metadata: bool = True
collection_name: str
batch_size: Optional[int] = DEFAULT_BATCH_SIZE
embedding_key: str = "embedding"
text_key: str = "text"
metadata_key: str = "metadata"
distance... | FirestoreVectorStore |
python | pytorch__pytorch | test/distributed/_composable/fsdp/test_fully_shard_comm.py | {
"start": 2434,
"end": 11777
} | class ____(FSDPTestMultiThread):
@property
def world_size(self) -> int:
return 128
@property
def device(self) -> torch.device:
return torch.device(device_type.type, 0)
def _get_param_sizes(self) -> list[torch.Size]:
# For world size 128, the fp32 all-gather and reduce-scatt... | TestFullyShardCollectiveOps |
python | sympy__sympy | sympy/stats/rv.py | {
"start": 10350,
"end": 16619
} | class ____(ProductPSpace):
"""
A probability space resulting from the merger of two independent probability
spaces.
Often created using the function, pspace.
"""
def __new__(cls, *spaces):
rs_space_dict = {}
for space in spaces:
for value in space.values:
... | IndependentProductPSpace |
python | kamyu104__LeetCode-Solutions | Python/maximum-value-after-insertion.py | {
"start": 29,
"end": 412
} | class ____(object):
def maxValue(self, n, x):
"""
:type n: str
:type x: int
:rtype: str
"""
check = (lambda i: str(x) > n[i]) if n[0] != '-' else (lambda i: str(x) < n[i])
for i in xrange(len(n)):
if check(i):
break
else:
... | Solution |
python | lepture__authlib | authlib/oauth2/rfc6749/models.py | {
"start": 5684,
"end": 7773
} | class ____:
def check_client(self, client):
"""A method to check if this token is issued to the given client.
For instance, ``client_id`` is saved on token table::
def check_client(self, client):
return self.client_id == client.client_id
:return: bool
""... | TokenMixin |
python | django__django | tests/servers/tests.py | {
"start": 4972,
"end": 5773
} | class ____(LiveServerBase):
server_thread_class = FailingLiveServerThread
@classmethod
def check_allowed_hosts(cls, expected):
if settings.ALLOWED_HOSTS != expected:
raise RuntimeError(f"{settings.ALLOWED_HOSTS} != {expected}")
@classmethod
def setUpClass(cls):
cls.chec... | LiveServerTestCaseSetupTest |
python | mlflow__mlflow | mlflow/server/auth/entities.py | {
"start": 3856,
"end": 4753
} | class ____:
def __init__(
self,
name,
user_id,
permission,
):
self._name = name
self._user_id = user_id
self._permission = permission
@property
def name(self):
return self._name
@property
def user_id(self):
return self._us... | RegisteredModelPermission |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/licenses_1/package.py | {
"start": 217,
"end": 566
} | class ____(Package):
"""Package with a licenses field."""
homepage = "https://www.example.com"
url = "https://www.example.com/license"
license("MIT", when="+foo")
license("Apache-2.0", when="~foo")
version("1.0", md5="0123456789abcdef0123456789abcdef")
variant("foo", default=True, descri... | Licenses1 |
python | getsentry__sentry | tests/sentry_plugins/twilio/test_plugin.py | {
"start": 4068,
"end": 5759
} | class ____(PluginTestCase):
@cached_property
def plugin(self) -> TwilioPlugin:
return TwilioPlugin()
def test_is_configured(self) -> None:
for o in ("account_sid", "auth_token", "sms_from", "sms_to"):
assert self.plugin.is_configured(self.project) is False
self.plugi... | TwilioPluginTest |
python | kubernetes-client__python | kubernetes/client/models/v1beta1_variable.py | {
"start": 383,
"end": 5269
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1beta1Variable |
python | pdm-project__pdm | src/pdm/cli/commands/venv/activate.py | {
"start": 312,
"end": 2796
} | class ____(BaseCommand):
"""Print the command to activate the virtualenv with the given name"""
arguments = (verbose_option,)
def add_arguments(self, parser: argparse.ArgumentParser) -> None:
parser.add_argument("env", nargs="?", help="The key of the virtualenv")
def handle(self, project: Pro... | ActivateCommand |
python | tensorflow__tensorflow | tensorflow/python/ops/gradients_test.py | {
"start": 26707,
"end": 26996
} | class ____(test_util.TensorFlowTestCase):
def testStopGradient(self):
with ops.Graph().as_default():
inp = constant(1.0, shape=[100, 32], name="in")
out = array_ops.stop_gradient(inp)
igrad = gradients.gradients(out, inp)[0]
assert igrad is None
| StopGradientTest |
python | scipy__scipy | scipy/optimize/tests/test_quadratic_assignment.py | {
"start": 9909,
"end": 13698
} | class ____(QAPCommonTests):
method = "2opt"
def test_deterministic(self):
n = 20
rng = default_rng(51982908)
A = rng.random(size=(n, n))
B = rng.random(size=(n, n))
res1 = quadratic_assignment(A, B, method=self.method, options={'rng': rng})
rng = default_rng(519... | Test2opt |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 180564,
"end": 181175
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"project_id",
"item_id",
"field_id",
"value",
"client_mutation_id",
)
project_id = sgqlc.types.Field(ID, graphql_name="projectId")
... | UpdateProjectNextItemFieldInput |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 151544,
"end": 151888
} | class ____(BaseModel):
wal_capacity_mb: int = Field(..., description="Size of a single WAL segment in MB")
wal_segments_ahead: int = Field(..., description="Number of WAL segments to create ahead of actually used ones")
wal_retain_closed: Optional[int] = Field(default=1, description="Number of closed WAL se... | WalConfig |
python | TheAlgorithms__Python | ciphers/hill_cipher.py | {
"start": 1593,
"end": 7301
} | class ____:
key_string = string.ascii_uppercase + string.digits
# This cipher takes alphanumerics into account
# i.e. a total of 36 characters
# take x and return x % len(key_string)
modulus = np.vectorize(lambda x: x % 36)
to_int = np.vectorize(round)
def __init__(self, encrypt_key: np.n... | HillCipher |
python | ray-project__ray | python/ray/actor.py | {
"start": 74951,
"end": 102296
} | class ____(Generic[T]):
"""A handle to an actor.
The fields in this class are prefixed with _ray_ to hide them from the user
and to avoid collision with actor method names.
An ActorHandle can be created in three ways. First, by calling .remote() on
an ActorClass. Second, by passing an actor handle... | ActorHandle |
python | ray-project__ray | python/ray/exceptions.py | {
"start": 28702,
"end": 28953
} | class ____(RayError):
"""Raised when the pending actor calls exceeds `max_pending_calls` option.
This exception could happen probably because the caller calls the callee
too frequently.
"""
pass
@PublicAPI
| PendingCallsLimitExceeded |
python | facebook__pyre-check | tools/typeshed_patcher/patch_specs.py | {
"start": 2255,
"end": 2566
} | class ____:
ACTION_NAME: ClassVar[str] = "delete"
name: str
@staticmethod
def from_json(input_dictionary: Mapping[str, object]) -> "DeleteAction":
name = _ensure_string_value(input_dictionary, "name")
return DeleteAction(name=name)
@dataclasses.dataclass(frozen=True)
| DeleteAction |
python | pypa__hatch | backend/src/hatchling/builders/config.py | {
"start": 640,
"end": 35662
} | class ____:
def __init__(
self,
builder: BuilderInterface,
root: str,
plugin_name: str,
build_config: dict[str, Any],
target_config: dict[str, Any],
) -> None:
self.__builder = builder
self.__root = root
self.__plugin_name = plugin_name
... | BuilderConfig |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/events.py | {
"start": 4140,
"end": 4427
} | class ____(Event):
__slots__ = ('explicit',)
def __init__(self, start_mark=None, end_mark=None, explicit=None, comment=None):
# type: (Any, Any, Any, Any) -> None
Event.__init__(self, start_mark, end_mark, comment)
self.explicit = explicit
| DocumentEndEvent |
python | prabhupant__python-ds | data_structures/graphs/dag_longest_path.py | {
"start": 122,
"end": 1560
} | class ____:
def __init__(self, vertices):
self.graph = defaultdict(list)
self.vertices = vertices
def add_edge(self, u, v, w):
self.graph[u].append((v, w))
def topological_sort_util(self, vertex, visited, stack):
visited[vertex] = True
for v, weight in self.gra... | Graph |
python | Textualize__textual | tests/command_palette/test_declare_sources.py | {
"start": 2178,
"end": 2669
} | class ____(ScreenWithNoSources):
COMMANDS = {ExampleCommandSource}
async def test_screen_command_sources() -> None:
"""Command sources declared on a screen should be in the command palette."""
async with AppWithInitialScreen(ScreenWithSources()).run_test() as pilot:
assert isinstance(pilot.app.scr... | ScreenWithSources |
python | getsentry__sentry | src/sentry/monitors/serializers.py | {
"start": 1224,
"end": 1540
} | class ____(Serializer):
def serialize(self, obj, attrs, user, **kwargs) -> MonitorEnvBrokenDetectionSerializerResponse:
return {
"userNotifiedTimestamp": obj.user_notified_timestamp,
"environmentMutedTimestamp": obj.env_muted_timestamp,
}
| MonitorEnvBrokenDetectionSerializer |
python | ray-project__ray | doc/source/serve/doc_code/grpc_proxy/grpc_guide.py | {
"start": 5101,
"end": 6908
} | class ____:
def __init__(
self,
_image_downloader: DeploymentHandle,
_data_preprocessor: DeploymentHandle,
):
self._image_downloader = _image_downloader
self._data_preprocessor = _data_preprocessor
self.model = torch.hub.load(
"pytorch/vision:v0.10.0",... | ImageClassifier |
python | FactoryBoy__factory_boy | factory/declarations.py | {
"start": 7312,
"end": 8569
} | class ____(BaseDeclaration):
"""Fill this value using the values returned by an iterator.
Warning: the iterator should not end !
Attributes:
iterator (iterable): the iterator whose value should be used.
getter (callable or None): a function to parse returned values
"""
def __init_... | Iterator |
python | huggingface__transformers | src/transformers/models/cwm/modeling_cwm.py | {
"start": 8390,
"end": 11703
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: CwmConfig, layer_idx: int):
super().__init__()
self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
self.config = config
s... | CwmAttention |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-weaviate/llama_index/vector_stores/weaviate/_exceptions.py | {
"start": 551,
"end": 1012
} | class ____(Exception):
"""Exception raised when the async weaviate client was not provided via the `weaviate_client` parameter."""
def __init__(
self,
message="Async method called without WeaviateAsyncClient provided. Pass the async weaviate client to be used via `weaviate_client` to the const... | AsyncClientNotProvidedError |
python | streamlit__streamlit | lib/tests/streamlit/elements/slider_test.py | {
"start": 13375,
"end": 15412
} | class ____(DeltaGeneratorTestCase):
def test_slider_with_width_pixels(self):
"""Test that slider can be displayed with a specific width in pixels."""
st.slider("Label", min_value=0, max_value=10, width=500)
element = self.get_delta_from_queue().new_element
assert (
elemen... | SliderWidthTest |
python | getsentry__sentry | src/sentry/uptime/types.py | {
"start": 2578,
"end": 2761
} | class ____(IntEnum):
"""
Used to identify what the current status of a uptime monitor is.
"""
NO_INCIDENT = 0
IN_INCIDENT = 1
@dataclass(frozen=True)
| IncidentStatus |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_cond_format09.py | {
"start": 345,
"end": 3720
} | class ____(unittest.TestCase):
"""
Test assembling a complete Worksheet file.
"""
def test_assemble_xml_file(self):
"""Test writing a worksheet with conditional formatting."""
self.maxDiff = None
fh = StringIO()
worksheet = Worksheet()
worksheet._set_filehandle... | TestAssembleWorksheet |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/docstring.py | {
"start": 1392,
"end": 1859
} | class ____:
"""""" ""
def docstring_that_ends_with_quote_and_a_line_break1():
"""
he said "the news of my death have been greatly exaggerated"
"""
def docstring_that_ends_with_quote_and_a_line_break2():
"""he said "the news of my death have been greatly exaggerated"
"""
def docstring_that_... | IgnoreImplicitlyConcatenatedStrings |
python | getsentry__sentry | tests/sentry/runner/commands/test_cleanup.py | {
"start": 5062,
"end": 6974
} | class ____(TestCase):
def test_run_bulk_query_deletes_by_project(self) -> None:
"""Test that the function runs bulk query deletes by project as expected."""
days = 30
# Creating the groups in out of order to test that the chunks are created in the correct order.
self.create_group(las... | RunBulkQueryDeletesByProjectTest |
python | scipy__scipy | scipy/integrate/_rules/_base.py | {
"start": 100,
"end": 5977
} | class ____:
"""
Base class for numerical integration algorithms (cubatures).
Finds an estimate for the integral of ``f`` over the region described by two arrays
``a`` and ``b`` via `estimate`, and find an estimate for the error of this
approximation via `estimate_error`.
If a subclass does not... | Rule |
python | walkccc__LeetCode | solutions/1081. Smallest Subsequence of Distinct Characters/1081.py | {
"start": 0,
"end": 441
} | class ____:
def smallestSubsequence(self, text: str) -> str:
ans = []
count = collections.Counter(text)
used = [False] * 26
for c in text:
count[c] -= 1
if used[ord(c) - ord('a')]:
continue
while ans and ans[-1] > c and count[ans[-1]] > 0:
used[ord(ans[-1]) - ord('a'... | Solution |
python | pytorch__pytorch | torch/distributed/_local_tensor/__init__.py | {
"start": 32601,
"end": 42242
} | class ____(torch.Tensor):
"""
LocalTensor is a Tensor subclass that simulates a tensor distributed across multiple SPMD
(Single Program, Multiple Data) ranks. Each LocalTensor instance internally holds a mapping from
global rank ids to their corresponding local Tensor shards.Operations performed on a Lo... | LocalTensor |
python | Textualize__textual | src/textual/_markup_playground.py | {
"start": 236,
"end": 4957
} | class ____(App):
TITLE = "Markup Playground"
CSS = """
Screen {
layout: vertical;
#editor {
width: 1fr;
height: 1fr;
border: tab $foreground 50%;
padding: 1;
margin: 1 0 0 0;
&:focus {
... | MarkupPlayground |
python | readthedocs__readthedocs.org | readthedocs/search/api/v3/tests/test_api.py | {
"start": 2655,
"end": 13365
} | class ____(SearchTestBase):
def setUp(self):
super().setUp()
self.user = get(User)
self.another_user = get(User)
self.project = get(
Project, slug="project", users=[self.user], privacy_level=PUBLIC
)
self.another_project = get(
Project,
... | SearchAPITest |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 258694,
"end": 259558
} | class ____:
def test_docstrings(self):
# See ticket #761
if stats.rayleigh.__doc__ is not None:
assert_("rayleigh" in stats.rayleigh.__doc__.lower())
if stats.bernoulli.__doc__ is not None:
assert_("bernoulli" in stats.bernoulli.__doc__.lower())
def test_no_name_... | TestDocstring |
python | pytorch__pytorch | torch/distributed/tensor/examples/torchrec_sharding_example.py | {
"start": 1000,
"end": 16727
} | class ____(torch.Tensor):
local_shards: list[torch.Tensor]
storage_meta: TensorStorageMetadata
@staticmethod
def __new__(
cls, local_shards: list[torch.Tensor], offsets: list[torch.Size]
) -> "LocalShardsWrapper":
assert len(local_shards) > 0
assert len(local_shards) == len(... | LocalShardsWrapper |
python | sympy__sympy | sympy/integrals/manualintegrate.py | {
"start": 7930,
"end": 8081
} | class ____(HyperbolicRule):
"""integrate(sinh(x), x) -> cosh(x)"""
def eval(self) -> Expr:
return cosh(self.variable)
@dataclass
| SinhRule |
python | astropy__astropy | astropy/coordinates/tests/test_masked.py | {
"start": 12338,
"end": 13202
} | class ____(TestFrame):
"""Tests that mask is calculated properly for SkyCoord.
Note that this does all the tests from TestFrame, as well as a few
specific to SkyCoord, i.e., that use attributes the frame does not have.
"""
@classmethod
def setup_class(cls):
super().setup_class()
... | TestSkyCoord |
python | kamyu104__LeetCode-Solutions | Python/subrectangle-queries.py | {
"start": 109,
"end": 1044
} | class ____(object):
def __init__(self, rectangle):
"""
:type rectangle: List[List[int]]
"""
self.__rectangle = rectangle
self.__updates = []
def updateSubrectangle(self, row1, col1, row2, col2, newValue):
"""
:type row1: int
:type col1: ... | SubrectangleQueries |
python | pytorch__pytorch | torch/_ops.py | {
"start": 31576,
"end": 42312
} | class ____(OperatorBase, Generic[_P, _T]):
def __init__(
self,
overloadpacket: "OpOverloadPacket",
op: Callable[_P, _T],
op_dk: Callable[Concatenate[DispatchKey, _P], _T],
schema: torch._C.FunctionSchema,
tags: list[Any],
) -> None:
super().__init__()
... | OpOverload |
python | optuna__optuna | optuna/_gp/gp.py | {
"start": 2275,
"end": 3545
} | class ____(torch.autograd.Function):
@staticmethod
def forward(ctx: Any, squared_distance: torch.Tensor) -> torch.Tensor:
"""
This method calculates `exp(-sqrt5d) * (1/3 * sqrt5d ** 2 + sqrt5d + 1)` where
`sqrt5d = sqrt(5 * squared_distance)`.
Please note that automatic differen... | Matern52Kernel |
python | numpy__numpy | numpy/_core/tests/test_records.py | {
"start": 13344,
"end": 13858
} | class ____:
# Test that pathlib.Path can be used
def test_tofile_fromfile(self):
with temppath(suffix='.bin') as path:
path = Path(path)
np.random.seed(123)
a = np.random.rand(10).astype('f8,i4,S5')
a[5] = (0.5, 10, 'abcde')
with path.open("wb"... | TestPathUsage |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/row_partition.py | {
"start": 2597,
"end": 49804
} | class ____(composite_tensor.CompositeTensor):
"""Partitioning of a sequence of values into contiguous subsequences ("rows").
A `RowPartition` describes how a sequence with `nvals` items should be
divided into `nrows` contiguous subsequences ("rows"). For example, a
`RowPartition` could be used to partition th... | RowPartition |
python | ray-project__ray | rllib/env/tests/test_single_agent_env_runner.py | {
"start": 570,
"end": 17270
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
ray.init()
tune.register_env(
"tune-registered",
lambda cfg: SimpleCorridor({"corridor_length": 10} | cfg),
)
tune.register_env(
"tune-registered-vector",
la... | TestSingleAgentEnvRunner |
python | django-extensions__django-extensions | tests/test_shortuuid_field.py | {
"start": 191,
"end": 1207
} | class ____(TestCase):
def test_UUID_field_create(self):
j = ShortUUIDTestModel_field.objects.create(
a=6, uuid_field="vytxeTZskVKR7C7WgdSP3d"
)
self.assertEqual(j.uuid_field, "vytxeTZskVKR7C7WgdSP3d")
def test_UUID_field_pk_create(self):
j = ShortUUIDTestModel_pk.obj... | ShortUUIDFieldTest |
python | matplotlib__matplotlib | lib/matplotlib/_mathtext.py | {
"start": 27849,
"end": 28315
} | class ____(DejaVuFonts):
"""
A font handling class for the DejaVu Sans fonts
If a glyph is not found it will fallback to Stix Sans
"""
_fontmap = {
'rm': 'DejaVu Sans',
'it': 'DejaVu Sans:italic',
'bf': 'DejaVu Sans:weight=bold',
'bfit': 'DejaVu Sans:italic:bold',
... | DejaVuSansFonts |
python | huggingface__transformers | src/transformers/models/blip/modeling_blip.py | {
"start": 38337,
"end": 46840
} | class ____(BlipPreTrainedModel, GenerationMixin):
config: BlipConfig
_tied_weights_keys = {
"text_decoder.cls.predictions.decoder.bias": "text_decoder.cls.predictions.bias",
"text_decoder.cls.predictions.decoder.weight": "text_decoder.bert.embeddings.word_embeddings.weight",
}
def __ini... | BlipForQuestionAnswering |
python | Textualize__textual | docs/examples/guide/styles/padding01.py | {
"start": 401,
"end": 750
} | class ____(App):
def compose(self) -> ComposeResult:
self.widget = Static(TEXT)
yield self.widget
def on_mount(self) -> None:
self.widget.styles.background = "purple"
self.widget.styles.width = 30
self.widget.styles.padding = 2
if __name__ == "__main__":
app = Padd... | PaddingApp |
python | jazzband__django-model-utils | model_utils/tracker.py | {
"start": 15859,
"end": 16654
} | class ____(FieldInstanceTracker):
def has_changed(self, field: str) -> bool:
"""Returns ``True`` if field has changed from currently saved value"""
if not self.instance.pk:
return True
elif field in self.saved_data:
prev: object = self.previous(field)
cur... | ModelInstanceTracker |
python | pyodide__pyodide | src/py/pyodide/console.py | {
"start": 20665,
"end": 24703
} | class ____(Console):
# TODO: Figure out proper SKIPIF syntax for Firefox and Safari
"""
A subclass of :py:class:`Console` that uses :js:func:`pyodide.loadPackagesFromImports`
before running the code.
Example:
>>> from pyodide.console import PyodideConsole # doctest: +SKIP
>>> conso... | PyodideConsole |
python | allegroai__clearml | clearml/backend_api/services/v2_9/auth.py | {
"start": 15037,
"end": 16137
} | class ____(Request):
"""
Revokes (and deletes) a set (key, secret) of credentials for
the authenticated user.
:param access_key: Credentials key
:type access_key: str
"""
_service = "auth"
_action = "revoke_credentials"
_version = "2.9"
_schema = {
"definitions"... | RevokeCredentialsRequest |
python | great-expectations__great_expectations | great_expectations/execution_engine/partition_and_sample/data_partitioner.py | {
"start": 1325,
"end": 2463
} | class ____(enum.Enum):
"""The names of available partitioner_methods."""
PARTITION_ON_YEAR = "partition_on_year"
PARTITION_ON_YEAR_AND_MONTH = "partition_on_year_and_month"
PARTITION_ON_YEAR_AND_MONTH_AND_DAY = "partition_on_year_and_month_and_day"
PARTITION_ON_DATE_PARTS = "partition_on_date_parts... | PartitionerMethod |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/table.py | {
"start": 1373,
"end": 1577
} | class ____(graphene.ObjectType):
constraints = graphene.Field(GrapheneTableConstraints)
columns = non_null_list(GrapheneTableColumn)
class Meta:
name = "TableSchema"
| GrapheneTableSchema |
python | google__pytype | pytype/pretty_printer_base.py | {
"start": 328,
"end": 4564
} | class ____(abc.ABC):
"""Pretty printer methods depending only on pytd types.
Subclasses are expected to handle abstract->pytd conversion.
"""
def __init__(self, ctx):
self.ctx = ctx
@staticmethod
def show_constant(val: types.BaseValue) -> str:
"""Pretty-print a value if it is a constant.
Rec... | PrettyPrinterBase |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/configuration_qwen3_omni_moe.py | {
"start": 39116,
"end": 46110
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Qwen3OmniMoeTalker`]. It is used to instantiate a
Qwen3-Omni multi-modal talker model capable of handling text, audio, and vision modalities in a unified architecture.
The model integrates a text decoder... | Qwen3OmniMoeTalkerConfig |
python | openai__openai-python | src/openai/types/beta/realtime/response_content_part_added_event.py | {
"start": 635,
"end": 1232
} | class ____(BaseModel):
content_index: int
"""The index of the content part in the item's content array."""
event_id: str
"""The unique ID of the server event."""
item_id: str
"""The ID of the item to which the content part was added."""
output_index: int
"""The index of the output ite... | ResponseContentPartAddedEvent |
python | openai__openai-python | src/openai/types/graders/label_model_grader.py | {
"start": 1145,
"end": 1533
} | class ____(BaseModel):
content: InputContent
"""Inputs to the model - can contain template strings."""
role: Literal["user", "assistant", "system", "developer"]
"""The role of the message input.
One of `user`, `assistant`, `system`, or `developer`.
"""
type: Optional[Literal["message"]] =... | Input |
python | kamyu104__LeetCode-Solutions | Python/minimum-time-for-k-virus-variants-to-spread.py | {
"start": 109,
"end": 2560
} | class ____(object): # 0-based index
def __init__(self, N,
build_fn=lambda x, y: [y]*(2*x),
query_fn=lambda x, y: y if x is None else max(x, y),
update_fn=lambda x, y: y if x is None else x+y,
default_val=0):
self.N = N
self.H = (N-... | SegmentTree |
python | doocs__leetcode | solution/0900-0999/0912.Sort an Array/Solution2.py | {
"start": 0,
"end": 800
} | class ____:
def sortArray(self, nums: List[int]) -> List[int]:
def merge_sort(l, r):
if l >= r:
return
mid = (l + r) >> 1
merge_sort(l, mid)
merge_sort(mid + 1, r)
i, j = l, mid + 1
tmp = []
while i <= mid an... | Solution |
python | django-crispy-forms__django-crispy-forms | tests/forms.py | {
"start": 4600,
"end": 4952
} | class ____(BaseModelForm):
is_company = forms.CharField(label="company", required=False, widget=forms.CheckboxInput())
password2 = forms.CharField(label="re-enter password", max_length=30, required=True, widget=forms.PasswordInput())
class Meta:
model = CrispyTestModel
fields = ("email", "p... | SampleForm7 |
python | huggingface__transformers | tests/models/vit/test_image_processing_vit.py | {
"start": 2697,
"end": 4199
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = ViTImageProcessor if is_vision_available() else None
fast_image_processing_class = ViTImageProcessorFast if is_torchvision_available() else None
def setUp(self):
super().setUp()
self.image_processor_tester = V... | ViTImageProcessingTest |
python | wandb__wandb | tests/unit_tests/test_wandb_summary.py | {
"start": 194,
"end": 3154
} | class ____:
# current_dict: t.Dict
# summary_record: t.Optional[SummaryRecord]
def __init__(self, current_dict: Dict) -> None:
self.reset(current_dict)
def reset(self, current_dict: Dict) -> None:
self.summary_record = None
self.current_dict = current_dict
def update_callb... | MockCallback |
python | getsentry__sentry | tests/sentry/preprod/pull_request/test_comment_types.py | {
"start": 143,
"end": 22341
} | class ____:
def test_parse_github_issue_comments_real_data(self):
"""Test parsing real GitHub issue comments from actual PR data."""
raw_comments = [
{
"url": "https://api.github.com/repos/test-org/test-repo/issues/comments/1111111111",
"html_url": "https:... | TestPullRequestCommentTypes |
python | python-jsonschema__jsonschema | jsonschema/tests/test_exceptions.py | {
"start": 22465,
"end": 22604
} | class ____(TestCase):
def test_hashable(self):
{exceptions.ValidationError("")}
{exceptions.SchemaError("")}
| TestHashable |
python | getsentry__sentry | tests/sentry/issues/endpoints/test_group_similar_issues_embeddings.py | {
"start": 1682,
"end": 31616
} | class ____(APITestCase):
def setUp(self) -> None:
super().setUp()
self.login_as(self.user)
self.org = self.create_organization(owner=self.user)
self.project = self.create_project(organization=self.org)
self.base_error_trace = {
"fingerprint": ["my-route", "{{ defa... | GroupSimilarIssuesEmbeddingsTest |
python | numpy__numpy | numpy/_core/tests/test_dtype.py | {
"start": 77388,
"end": 79124
} | class ____:
@pytest.mark.leaks_references(reason="dynamically creates custom dtype.")
@pytest.mark.thread_unsafe(reason="crashes when GIL disabled, dtype setup is thread-unsafe")
def test_custom_structured_dtype(self):
class mytype:
pass
blueprint = np.dtype([("field", object)])... | TestUserDType |
python | vyperlang__vyper | vyper/semantics/analysis/imports.py | {
"start": 976,
"end": 2430
} | class ____:
# the current path in the import graph traversal
_path: list[vy_ast.Module] = dc.field(default_factory=list)
# stack of dicts, each item in the stack is a dict keeping
# track of imports in the current module
_imports: list[dict] = dc.field(default_factory=list)
@property
def i... | _ImportGraph |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/guides/observe/alerts/generate_alerts_config_code_snippets.py | {
"start": 602,
"end": 6104
} | class ____(NamedTuple):
condition_description: str
alert_name: str
event_types: Sequence[str]
config_snippet: Optional[Mapping[str, Any]]
NOTIFICATION_SERVICES = sorted(
[
NotificationService(
name="email",
label="Email",
effect_description="an email",
... | AlertType |
python | google__jax | jax/_src/export/shape_poly.py | {
"start": 3045,
"end": 9152
} | class ____:
"""Represents a factor in a symbolic dimension expression.
Factors are either variables, or expressions of the form floordiv(E1, E2) or
mod(E1, E2), or max(E1, E2), or min(E1, E2).
Factors are multiplied to form terms (see _DimTerm), and
terms are added to form symbolic expressions (see _DimExpr)... | _DimFactor |
python | django-crispy-forms__django-crispy-forms | tests/forms.py | {
"start": 252,
"end": 414
} | class ____(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper(self)
| BaseModelForm |
python | jina-ai__jina | jina/serve/networking/sse.py | {
"start": 6554,
"end": 13446
} | class ____(Response):
"""Implements the ServerSentEvent Protocol:
https://www.w3.org/TR/2009/WD-eventsource-20090421/
Responses must not be compressed by middleware in order to work.
implementation based on Starlette StreamingResponse
"""
DEFAULT_PING_INTERVAL = 15
# noinspection PyMissin... | EventSourceResponse |
python | python-openxml__python-docx | src/docx/image/jpeg.py | {
"start": 8194,
"end": 9503
} | class ____:
"""Base class for JFIF marker classes.
Represents a marker and its segment occuring in a JPEG byte stream.
"""
def __init__(self, marker_code, offset, segment_length):
super(_Marker, self).__init__()
self._marker_code = marker_code
self._offset = offset
self... | _Marker |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_B.py | {
"start": 7260,
"end": 8649
} | class ____(Benchmark):
r"""
Bird objective function.
The Bird global optimization problem is a multimodal minimization
problem defined as follows
.. math::
f_{\text{Bird}}(x) = \left(x_1 - x_2\right)^{2} + e^{\left[1 -
\sin\left(x_1\right) \right]^{2}} \cos\left(x_2\right) + e^{... | Bird |
python | ray-project__ray | python/ray/tests/test_autoscaler_azure.py | {
"start": 5698,
"end": 16561
} | class ____(unittest.TestCase):
"""Test cases for Azure availability zone precedence logic."""
def setUp(self):
"""Set up test fixtures."""
self.base_provider_config = {
"resource_group": "test-rg",
"location": "westus2",
"subscription_id": "test-sub-id",
... | TestAzureAvailabilityZonePrecedence |
python | celery__celery | t/unit/worker/test_request.py | {
"start": 2977,
"end": 3199
} | class ____:
def test_retry_semipredicate(self):
try:
raise Exception('foo')
except Exception as exc:
ret = Retry('Retrying task', exc)
assert ret.exc == exc
| test_Retry |
python | kamyu104__LeetCode-Solutions | Python/neither-minimum-nor-maximum.py | {
"start": 47,
"end": 559
} | class ____(object):
def findNonMinOrMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
mx, mn = float("-inf"), float("inf")
result = -1
for x in nums:
if mn < x < mx:
return x
if x < mn:
result = ... | Solution |
python | pytransitions__transitions | transitions/extensions/asyncio.py | {
"start": 25847,
"end": 31533
} | class ____(HierarchicalMachine, AsyncMachine):
"""Asynchronous variant of transitions.extensions.nesting.HierarchicalMachine.
An asynchronous hierarchical machine REQUIRES AsyncNestedStates, AsyncNestedEvent and AsyncNestedTransitions
(or any subclass of it) to operate.
"""
state_cls = Nest... | HierarchicalAsyncMachine |
python | aio-libs__aiohttp | aiohttp/abc.py | {
"start": 6305,
"end": 6814
} | class ____(ABC):
"""Abstract writer to access log."""
__slots__ = ("logger", "log_format")
def __init__(self, logger: logging.Logger, log_format: str) -> None:
self.logger = logger
self.log_format = log_format
@abstractmethod
def log(self, request: BaseRequest, response: StreamRes... | AbstractAccessLogger |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/util/typing.py | {
"start": 2282,
"end": 2471
} | class ____(Protocol):
"""protocol for types that have ``__args__``
there's no public interface for this AFAIK
"""
__args__: Tuple[_AnnotationScanType, ...]
| ArgsTypeProtocol |
python | pytorch__pytorch | torch/testing/_internal/distributed/multi_threaded_pg.py | {
"start": 6565,
"end": 7264
} | class ____:
def __init__(self, src):
self.src = src
@torch.no_grad()
def work(self, data):
src_in_tensor_list = data[self.src][1]
# Can't handle scatter with multiple input tensor list
assert len(src_in_tensor_list) == 1
src_in_tensors = src_in_tensor_list[0]
... | Scatter |
python | apache__airflow | providers/common/sql/tests/unit/common/sql/operators/test_sql_execute.py | {
"start": 1497,
"end": 1549
} | class ____(NamedTuple):
id: str
value: str
| Row |
python | ApeWorX__ape | src/ape/exceptions.py | {
"start": 5007,
"end": 8581
} | class ____(ApeException):
"""
Raised when issues occur related to transactions.
"""
DEFAULT_MESSAGE = "Transaction failed."
def __init__(
self,
message: Optional[str] = None,
base_err: Optional[Exception] = None,
code: Optional[int] = None,
txn: Optional[Fai... | TransactionError |
python | django__django | tests/forms_tests/tests/test_widgets.py | {
"start": 219,
"end": 922
} | class ____(AdminSeleniumTestCase):
available_apps = ["forms_tests"] + AdminSeleniumTestCase.available_apps
def test_textarea_trailing_newlines(self):
"""
A roundtrip on a ModelForm doesn't alter the TextField value
"""
from selenium.webdriver.common.by import By
article... | LiveWidgetTests |
python | giampaolo__psutil | tests/test_aix.py | {
"start": 417,
"end": 4358
} | class ____(PsutilTestCase):
def test_virtual_memory(self):
out = sh('/usr/bin/svmon -O unit=KB')
re_pattern = r"memory\s*"
for field in [
"size",
"inuse",
"free",
"pin",
"virtual",
"available",
"mmode",
... | AIXSpecificTestCase |
python | dask__dask | dask/dataframe/dask_expr/_concat.py | {
"start": 11133,
"end": 11807
} | class ____(StackPartition):
def _divisions(self):
return self._frames[0].divisions
def _layer(self):
dsk, i = {}, 0
kwargs = self._kwargs.copy()
kwargs["ignore_order"] = self.ignore_order
dfs = self._frames
for i in range(self.npartitions):
dsk[(self... | StackPartitionInterleaved |
python | docker__docker-py | tests/integration/api_image_test.py | {
"start": 12227,
"end": 12533
} | class ____(BaseAPIIntegrationTest):
def test_inspect_distribution(self):
data = self.client.inspect_distribution('busybox:latest')
assert data is not None
assert 'Platforms' in data
assert {'os': 'linux', 'architecture': 'amd64'} in data['Platforms']
| InspectDistributionTest |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 32603,
"end": 33402
} | class ____(DelegatingLexer):
"""
A lexer that highlights `genshi <http://genshi.edgewall.org/>`_ and
`kid <http://kid-templating.org/>`_ kid XML templates.
"""
name = 'Genshi'
aliases = ['genshi', 'kid', 'xml+genshi', 'xml+kid']
filenames = ['*.kid']
alias_filenames = ['*.xml']
mime... | GenshiLexer |
python | walkccc__LeetCode | solutions/860. Lemonade Change/860.py | {
"start": 0,
"end": 401
} | class ____:
def lemonadeChange(self, bills: list[int]) -> bool:
fives = 0
tens = 0
for bill in bills:
if bill == 5:
fives += 1
elif bill == 10:
fives -= 1
tens += 1
else: # bill == 20
if tens > 0:
tens -= 1
fives -= 1
else:
... | Solution |
python | huggingface__transformers | src/transformers/models/m2m_100/modeling_m2m_100.py | {
"start": 22192,
"end": 22622
} | class ____(PreTrainedModel):
config: M2M100Config
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["M2M100EncoderLayer", "M2M100DecoderLayer"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
# Doesn't support `compile` (... | M2M100PreTrainedModel |
python | huggingface__transformers | src/transformers/models/patchtst/modeling_patchtst.py | {
"start": 78193,
"end": 84726
} | class ____(PatchTSTPreTrainedModel):
def __init__(self, config: PatchTSTConfig):
super().__init__(config)
# Turn off masking
if config.do_mask_input:
logger.warning("Setting `do_mask_input` parameter to False.")
config.do_mask_input = False
self.model = Patc... | PatchTSTForRegression |
python | python-poetry__poetry | tests/types.py | {
"start": 3983,
"end": 4084
} | class ____(Protocol):
def __call__(self, name: str) -> DistributionHash: ...
| DistributionHashGetter |
python | pytorch__pytorch | torch/fx/graph.py | {
"start": 43846,
"end": 44970
} | class ____:
"""
Side table for the graph for the purpose of doing fast queries
"""
def __init__(self):
self.table: dict[tuple[str, Optional[Target]], dict[Node, None]] = defaultdict(
dict
)
def _key(self, node) -> tuple[str, Optional[Target]]:
return (node.op, n... | _FindNodesLookupTable |
python | scipy__scipy | benchmarks/benchmarks/fft_basic.py | {
"start": 1682,
"end": 2405
} | class ____(Benchmark):
params = [
[100, 256, 313, 512, 1000, 1024, 2048, 2048*2, 2048*4],
['real', 'cmplx'],
['scipy.fftpack', 'scipy.fft', 'numpy.fft']
]
param_names = ['size', 'type', 'module']
def setup(self, size, cmplx, module):
if cmplx == 'cmplx':
self... | Fft |
python | python-openxml__python-docx | src/docx/oxml/table.py | {
"start": 9686,
"end": 12568
} | class ____(BaseOxmlElement):
"""``<w:tblPr>`` element, child of ``<w:tbl>``, holds child elements that define
table properties such as style and borders."""
get_or_add_bidiVisual: Callable[[], CT_OnOff]
get_or_add_jc: Callable[[], CT_Jc]
get_or_add_tblLayout: Callable[[], CT_TblLayoutType]
_add... | CT_TblPr |
python | ansible__ansible | lib/ansible/plugins/lookup/csvfile.py | {
"start": 4488,
"end": 6487
} | class ____(LookupBase):
def read_csv(self, filename, key, delimiter, encoding='utf-8', dflt=None, col=1, keycol=0):
with open(filename, encoding=encoding) as f:
for row in csv.reader(f, dialect=csv.excel, delimiter=delimiter):
if row and row[keycol] == key:
r... | LookupModule |
python | pytorch__pytorch | torch/_higher_order_ops/base_hop.py | {
"start": 10525,
"end": 10686
} | class ____:
def __init__(self, fn):
self.fn = fn
def __call__(self, *args, **kwargs):
return self.fn(*args, **kwargs)
| FunctionWithNoFreeVars |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.