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 | networkx__networkx | networkx/algorithms/flow/utils.py | {
"start": 281,
"end": 1084
} | class ____:
"""Mechanism for iterating over out-edges incident to a node in a circular
manner. StopIteration exception is raised when wraparound occurs.
"""
__slots__ = ("_edges", "_it", "_curr")
def __init__(self, edges):
self._edges = edges
if self._edges:
self._rewin... | CurrentEdge |
python | tensorflow__tensorflow | tensorflow/python/keras/legacy_tf_layers/convolutional.py | {
"start": 9906,
"end": 19421
} | class ____(keras_layers.Conv2D, base.Layer):
"""2D convolution layer (e.g. spatial convolution over images).
This layer creates a convolution kernel that is convolved
(actually cross-correlated) with the layer input to produce a tensor of
outputs. If `use_bias` is True (and a `bias_initializer` is provided),
... | Conv2D |
python | ijl__orjson | test/test_enum.py | {
"start": 249,
"end": 296
} | class ____(enum.IntFlag):
ONE = 1
| IntFlagEnum |
python | langchain-ai__langchain | libs/core/langchain_core/load/load.py | {
"start": 1110,
"end": 9295
} | class ____:
"""Reviver for JSON objects."""
def __init__(
self,
secrets_map: dict[str, str] | None = None,
valid_namespaces: list[str] | None = None,
secrets_from_env: bool = True, # noqa: FBT001,FBT002
additional_import_mappings: dict[tuple[str, ...], tuple[str, ...]]
... | Reviver |
python | urllib3__urllib3 | src/urllib3/http2/connection.py | {
"start": 11712,
"end": 12674
} | class ____(BaseHTTPResponse):
# TODO: This is a woefully incomplete response object, but works for non-streaming.
def __init__(
self,
status: int,
headers: HTTPHeaderDict,
request_url: str,
data: bytes,
decode_content: bool = False, # TODO: support decoding
)... | HTTP2Response |
python | ansible__ansible | lib/ansible/playbook/attribute.py | {
"start": 5611,
"end": 5668
} | class ____(Attribute):
...
| NonInheritableFieldAttribute |
python | huggingface__transformers | tests/models/sam2_video/test_processor_sam2_video.py | {
"start": 1039,
"end": 5191
} | class ____(ProcessorTesterMixin, unittest.TestCase):
processor_class = Sam2VideoProcessor
@unittest.skip("Sam2VideoProcessor call take in images only")
def test_processor_with_multiple_inputs(self):
pass
def prepare_image_inputs(self):
"""This function prepares a list of PIL images, or... | Sam2VideoProcessorTest |
python | apache__airflow | dev/breeze/src/airflow_breeze/utils/release_validator.py | {
"start": 1395,
"end": 5492
} | class ____(ABC):
def __init__(
self,
version: str,
svn_path: Path,
airflow_repo_root: Path,
):
self.version = version
self.svn_path = svn_path
self.airflow_repo_root = airflow_repo_root
self.results: list[ValidationResult] = []
@abstractmethod... | ReleaseValidator |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 187320,
"end": 187397
} | class ____(_NumRangeTests, _RangeTypeRoundTrip):
pass
| NumRangeRoundTripTest |
python | pallets__werkzeug | src/werkzeug/datastructures/structures.py | {
"start": 18773,
"end": 19922
} | class ____(t.Generic[K, V]):
"""Wraps values in the :class:`OrderedMultiDict`. This makes it
possible to keep an order over multiple different keys. It requires
a lot of extra memory and slows down access a lot, but makes it
possible to access elements in O(1) and iterate in O(n).
"""
__slots... | _omd_bucket |
python | huggingface__transformers | src/transformers/models/bros/modeling_bros.py | {
"start": 4377,
"end": 6956
} | class ____(nn.Module):
"""Construct the embeddings from word, position and token_type embeddings."""
def __init__(self, config):
super().__init__()
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
self.position_embeddings = nn.... | BrosTextEmbeddings |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 46155,
"end": 46532
} | class ____(VOWarning, ValueError):
"""All ``COOSYS`` elements must have an ``ID`` attribute.
Note that the VOTable 1.1 specification says this attribute is
optional, but its corresponding schema indicates it is required.
In VOTable 1.2, the ``COOSYS`` element is deprecated.
"""
message_templa... | E15 |
python | sympy__sympy | sympy/physics/optics/gaussopt.py | {
"start": 4657,
"end": 5126
} | class ____(RayTransferMatrix):
"""
Ray Transfer Matrix for free space.
Parameters
==========
distance
See Also
========
RayTransferMatrix
Examples
========
>>> from sympy.physics.optics import FreeSpace
>>> from sympy import symbols
>>> d = symbols('d')
>>> ... | FreeSpace |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/declarative_automation/operators/since_operator.py | {
"start": 3386,
"end": 9079
} | class ____(BuiltinAutomationCondition[T_EntityKey]):
trigger_condition: AutomationCondition[T_EntityKey]
reset_condition: AutomationCondition[T_EntityKey]
@property
def name(self) -> str:
return "SINCE"
@property
def children(self) -> Sequence[AutomationCondition[T_EntityKey]]:
... | SinceCondition |
python | ray-project__ray | rllib/examples/multi_agent/utils/self_play_league_based_callback.py | {
"start": 266,
"end": 13494
} | class ____(RLlibCallback):
def __init__(self, win_rate_threshold):
super().__init__()
# All policies in the league.
self.main_policies = {"main", "main_0"}
self.main_exploiters = {"main_exploiter_0", "main_exploiter_1"}
self.league_exploiters = {"league_exploiter_0", "league_... | SelfPlayLeagueBasedCallback |
python | keras-team__keras | keras/src/ops/nn_test.py | {
"start": 3403,
"end": 28015
} | class ____(testing.TestCase):
def test_relu(self):
x = KerasTensor([None, 2, 3])
self.assertEqual(knn.relu(x).shape, (None, 2, 3))
def test_relu6(self):
x = KerasTensor([None, 2, 3])
self.assertEqual(knn.relu6(x).shape, (None, 2, 3))
def test_sigmoid(self):
x = Kera... | NNOpsDynamicShapeTest |
python | walkccc__LeetCode | solutions/92. Reverse Linked List II/92.py | {
"start": 0,
"end": 533
} | class ____:
def reverseBetween(
self,
head: ListNode | None,
left: int,
right: int,
) -> ListNode | None:
if left == 1:
return self.reverseN(head, right)
head.next = self.reverseBetween(head.next, left - 1, right - 1)
return head
def reverseN(self, head: ListNode | None... | Solution |
python | allegroai__clearml | clearml/backend_api/services/v2_13/queues.py | {
"start": 75503,
"end": 76686
} | class ____(Response):
"""
Response of queues.remove_task endpoint.
:param removed: Number of tasks removed (0 or 1)
:type removed: int
"""
_service = "queues"
_action = "remove_task"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"remov... | RemoveTaskResponse |
python | networkx__networkx | networkx/exception.py | {
"start": 2136,
"end": 2317
} | class ____(NetworkXAlgorithmError):
"""Exception raised by algorithms trying to solve a maximization
or a minimization problem instance that is unbounded."""
| NetworkXUnbounded |
python | pytorch__pytorch | torch/_dynamo/variables/streams.py | {
"start": 4586,
"end": 5793
} | class ____:
"""Track the currently entered stream if any"""
def __init__(self) -> None:
from ..source import CurrentStreamSource
cur_stack: list[StreamVariable] = []
if torch.accelerator.is_available():
stream_var = LazyVariableTracker.create(
torch.accelera... | SymbolicStreamState |
python | sphinx-doc__sphinx | sphinx/ext/doctest.py | {
"start": 5934,
"end": 6255
} | class ____(TestDirective):
option_spec: ClassVar[OptionSpec] = {
'hide': directives.flag,
'no-trim-doctest-flags': directives.flag,
'pyversion': directives.unchanged_required,
'skipif': directives.unchanged_required,
'trim-doctest-flags': directives.flag,
}
| TestcodeDirective |
python | automl__auto-sklearn | autosklearn/ensembles/multiobjective_dummy_ensemble.py | {
"start": 726,
"end": 7582
} | class ____(AbstractMultiObjectiveEnsemble):
def __init__(
self,
task_type: int,
metrics: Sequence[Scorer] | Scorer,
backend: Backend,
random_state: int | np.random.RandomState | None = None,
) -> None:
"""A dummy implementation of a multi-objective ensemble.
... | MultiObjectiveDummyEnsemble |
python | pytorch__pytorch | torch/distributed/algorithms/join.py | {
"start": 2842,
"end": 3433
} | class ____(NamedTuple):
r"""This includes all fields needed from a :class:`Joinable` instance for the join context manager side."""
enable: bool
throw_on_early_termination: bool
is_first_joinable: bool
@staticmethod
def construct_disabled_join_config():
r"""Return a :class:`_JoinConfig... | _JoinConfig |
python | streamlit__streamlit | lib/tests/streamlit/user_info_test.py | {
"start": 2041,
"end": 6184
} | class ____(DeltaGeneratorTestCase):
"""Test UserInfoProxy."""
def test_user_email_attr(self):
"""Test that `st.user.email` returns user info from ScriptRunContext"""
assert st.user.email == "test@example.com"
def test_user_email_key(self):
assert st.user["email"] == "test@example.c... | UserInfoProxyTest |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_lambda_function.py | {
"start": 6222,
"end": 10855
} | class ____:
@pytest.mark.parametrize("payload", PAYLOADS)
def test_init(self, payload):
lambda_operator = LambdaInvokeFunctionOperator(
task_id="test",
function_name="test",
payload=payload,
log_type="None",
aws_conn_id="aws_conn_test",
... | TestLambdaInvokeFunctionOperator |
python | huggingface__transformers | src/transformers/models/aria/processing_aria.py | {
"start": 2070,
"end": 8999
} | class ____(ProcessorMixin):
"""
AriaProcessor is a processor for the Aria model which wraps the Aria image preprocessor and the LLama slow tokenizer.
Args:
image_processor (`AriaImageProcessor`, *optional*):
The AriaImageProcessor to use for image preprocessing.
tokenizer (`PreT... | AriaProcessor |
python | huggingface__transformers | src/transformers/models/groupvit/modeling_groupvit.py | {
"start": 12934,
"end": 14353
} | class ____(nn.Module):
"""
Image to Patch Embedding.
"""
def __init__(
self,
image_size: int = 224,
patch_size: Union[int, tuple[int, int]] = 16,
num_channels: int = 3,
embed_dim: int = 768,
):
super().__init__()
image_size = image_size if isi... | GroupViTPatchEmbeddings |
python | spack__spack | lib/spack/spack/spec.py | {
"start": 220174,
"end": 220297
} | class ____(spack.error.SpecError):
"""Raised when the same dependency occurs in a spec twice."""
| DuplicateDependencyError |
python | wandb__wandb | wandb/vendor/pygments/lexers/javascript.py | {
"start": 41335,
"end": 45696
} | class ____(RegexLexer):
"""
For `CoffeeScript`_ source code.
.. _CoffeeScript: http://coffeescript.org
.. versionadded:: 1.3
"""
name = 'CoffeeScript'
aliases = ['coffee-script', 'coffeescript', 'coffee']
filenames = ['*.coffee']
mimetypes = ['text/coffeescript']
_operator_r... | CoffeeScriptLexer |
python | tensorflow__tensorflow | tensorflow/python/distribute/multi_process_lib.py | {
"start": 1418,
"end": 5886
} | class ____:
"""A process that runs using absl.app.run."""
def __init__(self, *args, **kwargs):
super(_AbslProcess, self).__init__(*args, **kwargs)
# Monkey-patch that is carried over into the spawned process by pickle.
self._run_impl = getattr(self, 'run')
self.run = self._run_with_absl
def _run... | _AbslProcess |
python | allegroai__clearml | clearml/backend_api/services/v2_13/workers.py | {
"start": 49047,
"end": 50444
} | class ____(Request):
"""
Returns information on all registered workers.
:param last_seen: Filter out workers not active for more than last_seen
seconds. A value or 0 or 'none' will disable the filter.
:type last_seen: int
"""
_service = "workers"
_action = "get_all"
_version = ... | GetAllRequest |
python | PyCQA__pyflakes | pyflakes/messages.py | {
"start": 6745,
"end": 6933
} | class ____(Message):
"""
Assertion test is a non-empty tuple literal, which are always True.
"""
message = 'assertion is always true, perhaps remove parentheses?'
| AssertTuple |
python | cython__cython | Doc/s5/ep2008/worker.py | {
"start": 1,
"end": 184
} | class ____(object):
u"Almost Sisyphus"
def __init__(self, task):
self.task = task
def work_hard(self):
for i in range(100):
self.task()
| HardWorker |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/data_asset/path/file_asset.py | {
"start": 2271,
"end": 2518
} | class ____(ValueError):
def __init__(self, path: PathStr):
message = f"Provided path matched multiple targets, and must match exactly one: {path} "
super().__init__(message)
self.path = path
@public_api
| AmbiguousPathError |
python | dagster-io__dagster | python_modules/dagster-pipes/dagster_pipes/__init__.py | {
"start": 16082,
"end": 16273
} | class ____(ABC):
@contextmanager
@abstractmethod
def capture(self) -> Iterator[None]: ...
T_LogChannel = TypeVar("T_LogChannel", bound=PipesLogWriterChannel)
| PipesLogWriterChannel |
python | ray-project__ray | python/ray/dashboard/modules/job/job_head.py | {
"start": 3333,
"end": 6548
} | class ____:
"""A local client for submitting and interacting with jobs on a specific node
in the remote cluster.
Submits requests over HTTP to the job agent on the specific node using the REST API.
"""
def __init__(
self,
dashboard_agent_address: str,
):
self._agent_addr... | JobAgentSubmissionClient |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 78754,
"end": 80202
} | class ____(PrefectFilterBaseModel):
"""Filter by `ArtifactCollection.key`."""
any_: Optional[list[str]] = Field(
default=None, description="A list of artifact keys to include"
)
like_: Optional[str] = Field(
default=None,
description=(
"A string to match artifact ke... | ArtifactCollectionFilterKey |
python | sanic-org__sanic | sanic/exceptions.py | {
"start": 8176,
"end": 9285
} | class ____(HTTPException):
"""500 Internal Server Error
A general server-side error has occurred. If no other HTTP exception is
appropriate, then this should be used
Args:
message (Optional[Union[str, bytes]], optional): The message to be sent to the client. If `None`
then the HTTP... | ServerError |
python | kamyu104__LeetCode-Solutions | Python/divisor-game.py | {
"start": 1234,
"end": 1892
} | class ____(object):
def divisorGame(self, n):
"""
:type n: int
:rtype: bool
"""
def factors(n):
result = [[] for _ in xrange(n+1)]
for i in xrange(1, n+1):
for j in range(i, n+1, i):
result[j].append(i)
r... | Solution3 |
python | getsentry__sentry | tests/sentry/utils/test_registry.py | {
"start": 193,
"end": 1978
} | class ____(TestCase):
def test(self) -> None:
test_registry = Registry[Callable]()
@test_registry.register("something")
def registered_func():
raise NotImplementedError
def unregistered_func():
raise NotImplementedError
assert test_registry.get("som... | RegistryTest |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/hooks/sts.py | {
"start": 891,
"end": 1827
} | class ____(AwsBaseHook):
"""
Interact with AWS Security Token Service (STS).
Provide thin wrapper around :external+boto3:py:class:`boto3.client("sts") <STS.Client>`.
Additional arguments (such as ``aws_conn_id``) may be specified and
are passed down to the underlying AwsBaseHook.
.. seealso::... | StsHook |
python | pytorch__pytorch | torch/testing/_internal/common_pruning.py | {
"start": 2800,
"end": 3735
} | class ____(nn.Module):
r"""Model with only Linear layers, some with bias, some in a Sequential and some following.
Activation functions modules in between each Linear in the Sequential, and each outside layer.
Used to test pruned Linear(Bias)-Activation-Linear fusion."""
def __init__(self) -> None:
... | LinearActivation |
python | huggingface__transformers | src/transformers/models/dots1/modular_dots1.py | {
"start": 1261,
"end": 1322
} | class ____(Qwen3RotaryEmbedding):
pass
| Dots1RotaryEmbedding |
python | coleifer__peewee | playhouse/migrate.py | {
"start": 5156,
"end": 15145
} | class ____(object):
explicit_create_foreign_key = False
explicit_delete_foreign_key = False
def __init__(self, database):
self.database = database
def make_context(self):
return self.database.get_sql_context()
@classmethod
def from_database(cls, database):
if Cockroach... | SchemaMigrator |
python | mlflow__mlflow | mlflow/types/chat.py | {
"start": 1133,
"end": 1443
} | class ____(BaseModel):
type: Literal["input_audio"]
input_audio: InputAudio
ContentPartsList = list[
Annotated[TextContentPart | ImageContentPart | AudioContentPart, Field(discriminator="type")]
]
ContentType = Annotated[str | ContentPartsList, Field(union_mode="left_to_right")]
| AudioContentPart |
python | rapidsai__cudf | python/cudf/cudf/core/dtypes.py | {
"start": 5169,
"end": 5273
} | class ____(ExtensionDtype, Serializable):
# Base type for all cudf-specific dtypes
pass
| _BaseDtype |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/triggers/bedrock.py | {
"start": 8900,
"end": 9827
} | class ____(BedrockBaseBatchInferenceTrigger):
"""
Trigger when a batch inference job is complete.
:param job_arn: The Amazon Resource Name (ARN) of the batch inference job.
:param waiter_delay: The amount of time in seconds to wait between attempts. (default: 120)
:param waiter_max_attempts: The m... | BedrockBatchInferenceCompletedTrigger |
python | kamyu104__LeetCode-Solutions | Python/maximum-white-tiles-covered-by-a-carpet.py | {
"start": 2244,
"end": 2941
} | class ____(object):
def maximumWhiteTiles(self, tiles, carpetLen):
"""
:type tiles: List[List[int]]
:type carpetLen: int
:rtype: int
"""
tiles.sort()
prefix = [0]*(len(tiles)+1)
for i, (l, r) in enumerate(tiles):
prefix[i+1] = prefix[i]+(r-... | Solution4 |
python | huggingface__transformers | src/transformers/models/beit/modeling_beit.py | {
"start": 17170,
"end": 17759
} | class ____(nn.Module):
def __init__(self, config: BeitConfig) -> None:
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
sel... | BeitIntermediate |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py | {
"start": 127654,
"end": 128881
} | class ____(nn.Module):
"""An implementation of building block in ECAPA-TDNN, i.e.,
TDNN-Res2Net-TDNN-SqueezeExcitationBlock.
"""
def __init__(
self,
in_channels,
out_channels,
res2net_scale=8,
se_channels=128,
kernel_size=1,
dilation=1,
):
... | SqueezeExcitationRes2NetBlock |
python | vyperlang__vyper | vyper/exceptions.py | {
"start": 12016,
"end": 12118
} | class ____(VyperInternalException):
"""General unexpected error during compilation."""
| CompilerPanic |
python | pennersr__django-allauth | allauth/socialaccount/providers/wahoo/provider.py | {
"start": 312,
"end": 434
} | class ____(ProviderAccount):
def get_profile_url(self):
return "https://api.wahooligan.com/v1/user"
| WahooAccount |
python | apache__thrift | lib/py/src/Thrift.py | {
"start": 1357,
"end": 1447
} | class ____(object):
CALL = 1
REPLY = 2
EXCEPTION = 3
ONEWAY = 4
| TMessageType |
python | pytest-dev__pytest | src/_pytest/config/argparsing.py | {
"start": 9810,
"end": 10698
} | class ____:
"""An option defined in an OptionGroup."""
def __init__(self, action: argparse.Action) -> None:
self._action = action
def attrs(self) -> dict[str, Any]:
return self._action.__dict__
def names(self) -> Sequence[str]:
return self._action.option_strings
@property... | Argument |
python | conda__conda | conda/exceptions.py | {
"start": 39954,
"end": 40153
} | class ____(CondaError):
def __init__(self, caused_by: Any, **kwargs):
message = "No space left on devices."
super().__init__(message, caused_by=caused_by, **kwargs)
| NoSpaceLeftError |
python | numba__numba | numba/cuda/cudadrv/driver.py | {
"start": 62795,
"end": 67066
} | class ____(object):
"""A memory pointer that owns a buffer, with an optional finalizer. Memory
pointers provide reference counting, and instances are initialized with a
reference count of 1.
The base ``MemoryPointer`` class does not use the
reference count for managing the buffer lifetime. Instead,... | MemoryPointer |
python | jmcnamara__XlsxWriter | xlsxwriter/test/app/test_app03.py | {
"start": 333,
"end": 2627
} | class ____(unittest.TestCase):
"""
Test assembling a complete App file.
"""
def test_assemble_xml_file(self):
"""Test writing an App file."""
self.maxDiff = None
fh = StringIO()
app = App()
app._set_filehandle(fh)
app._add_part_name("Sheet1")
a... | TestAssembleApp |
python | matplotlib__matplotlib | lib/matplotlib/_mathtext.py | {
"start": 35484,
"end": 35546
} | class ____(FontConstantsBase):
pass
| DejaVuSerifFontConstants |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/circularBaseClass.py | {
"start": 170,
"end": 260
} | class ____(Bar):
pass
# This should generate an error because 'ClassB' is not bound.
| Bar |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 179795,
"end": 180845
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of CreateCommitOnBranch"""
__schema__ = github_schema
__field_names__ = ("branch", "file_changes", "message", "expected_head_oid", "client_mutation_id")
branch = sgqlc.types.Field(sgqlc.types.non_null(CommittableBranch), graphql_name="branch")
... | CreateCommitOnBranchInput |
python | dask__dask | dask/tests/test_multiprocessing.py | {
"start": 2556,
"end": 5098
} | class ____:
def __getstate__(self):
return ()
def __setstate__(self, state):
raise ValueError("Can't unpickle me")
def test_unpicklable_args_generate_errors():
a = NotUnpickleable()
dsk = {"x": (bool, a)}
with pytest.raises(ValueError):
get(dsk, "x")
dsk = {"x": (bo... | NotUnpickleable |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 73777,
"end": 77572
} | class ____(unittest.TestCase):
def testCrucialConstants(self):
socket.AF_CAN
socket.PF_CAN
socket.CAN_RAW
@unittest.skipUnless(hasattr(socket, "CAN_BCM"),
'socket.CAN_BCM required for this test.')
def testBCMConstants(self):
socket.CAN_BCM
... | BasicCANTest |
python | conda__conda | conda/models/version.py | {
"start": 18819,
"end": 23727
} | class ____(BaseSpec, metaclass=SingleStrArgCachingType):
_cache_ = {}
def __init__(self, vspec):
vspec_str, matcher, is_exact = self.get_matcher(vspec)
super().__init__(vspec_str, matcher, is_exact)
def get_matcher(self, vspec):
if isinstance(vspec, str) and regex_split_re.match(vs... | VersionSpec |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-weaviate/llama_index/vector_stores/weaviate/base.py | {
"start": 3394,
"end": 19123
} | class ____(BasePydanticVectorStore):
"""
Weaviate vector store.
In this vector store, embeddings and docs are stored within a
Weaviate collection.
During query time, the index uses Weaviate to query for the top
k most similar nodes.
Args:
weaviate_client (Optional[Any]): Either a ... | WeaviateVectorStore |
python | PyCQA__pylint | tests/functional/n/no/no_member.py | {
"start": 1025,
"end": 1054
} | class ____:
label: str
| Base |
python | pyparsing__pyparsing | pyparsing/core.py | {
"start": 222278,
"end": 233669
} | class ____(ParseElementEnhance):
"""
Forward declaration of an expression to be defined later -
used for recursive grammars, such as algebraic infix notation.
When the expression is known, it is assigned to the ``Forward``
instance using the ``'<<'`` operator.
.. Note::
Take care when a... | Forward |
python | django__django | tests/backends/oracle/test_operations.py | {
"start": 256,
"end": 5715
} | class ____(TransactionTestCase):
available_apps = ["backends"]
def test_sequence_name_truncation(self):
seq_name = connection.ops._get_no_autofield_sequence_name(
"schema_authorwithevenlongee869"
)
self.assertEqual(seq_name, "SCHEMA_AUTHORWITHEVENLOB0B8_SQ")
def test_bu... | OperationsTests |
python | airbytehq__airbyte | airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/config.py | {
"start": 1738,
"end": 2219
} | class ____(BaseConfig):
oauth = Field(True, description="Allow source to have another default method that OAuth.")
bypass_reason: Optional[str] = Field(description="Reason why OAuth is not default method.")
@validator("oauth", always=True)
def validate_oauth(cls, oauth, values):
if oauth is Fal... | OAuthTestConfig |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/generative_model.py | {
"start": 16476,
"end": 21226
} | class ____(GoogleCloudBaseOperator):
"""
Use the Rapid Evaluation API to evaluate a model.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param location: Required. The ID of the Google Cloud location that the service belongs to.
:param pretrained_model... | RunEvaluationOperator |
python | facebookresearch__faiss | tests/test_index.py | {
"start": 25587,
"end": 26092
} | class ____(unittest.TestCase):
def test_random(self):
""" just check if several runs of search retrieve the
same results """
index = faiss.IndexRandom(32, 1000000000)
(xt, xb, xq) = get_dataset_2(32, 0, 0, 10)
Dref, Iref = index.search(xq, 10)
self.assertTrue(np.all... | TestRandomIndex |
python | getsentry__sentry | src/sentry/integrations/middleware/metrics.py | {
"start": 1479,
"end": 1676
} | class ____(StrEnum):
"""
Reasons why a middleware operation may halt without success/failure.
"""
ORG_INTEGRATION_DOES_NOT_EXIST = "org_integration_does_not_exist"
| MiddlewareHaltReason |
python | kamyu104__LeetCode-Solutions | Python/minimum-costs-using-the-train-line.py | {
"start": 53,
"end": 628
} | class ____(object):
def minimumCosts(self, regular, express, expressCost):
"""
:type regular: List[int]
:type express: List[int]
:type expressCost: int
:rtype: List[int]
"""
result = []
dp = [0, expressCost] # dp[0]: min cost of regular route to curr ... | Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_axis51.py | {
"start": 315,
"end": 1539
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_axis51.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
python | realpython__materials | arcade-platformer/arcade_platformer/03_read_level_one.py | {
"start": 575,
"end": 4372
} | class ____(arcade.Window):
def __init__(self) -> None:
super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
# These lists will hold different sets of sprites
self.coins = None
self.background = None
self.walls = None
self.ladders = None
self.goals = No... | Platformer |
python | encode__django-rest-framework | tests/test_generics.py | {
"start": 1013,
"end": 1148
} | class ____(serializers.ModelSerializer):
class Meta:
model = ForeignKeySource
fields = '__all__'
| ForeignKeySerializer |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclassFrozen1.py | {
"start": 150,
"end": 205
} | class ____:
val1: int = 6
@dataclass(frozen=True)
| DC1 |
python | doocs__leetcode | solution/2300-2399/2386.Find the K-Sum of an Array/Solution.py | {
"start": 0,
"end": 513
} | class ____:
def kSum(self, nums: List[int], k: int) -> int:
mx = 0
for i, x in enumerate(nums):
if x > 0:
mx += x
else:
nums[i] = -x
nums.sort()
h = [(0, 0)]
for _ in range(k - 1):
s, i = heappop(h)
... | Solution |
python | encode__django-rest-framework | tests/test_relations.py | {
"start": 5133,
"end": 6412
} | class ____(APISimpleTestCase):
def setUp(self):
self.queryset = MockQueryset([
MockObject(pk=uuid.UUID(int=0), name='foo'),
MockObject(pk=uuid.UUID(int=1), name='bar'),
MockObject(pk=uuid.UUID(int=2), name='baz')
])
self.instance = self.queryset.items[2]
... | TestProxiedPrimaryKeyRelatedField |
python | mlflow__mlflow | mlflow/telemetry/events.py | {
"start": 9982,
"end": 10148
} | class ____(str, Enum):
"""Source of a trace received by the MLflow server."""
MLFLOW_PYTHON_CLIENT = "MLFLOW_PYTHON_CLIENT"
UNKNOWN = "UNKNOWN"
| TraceSource |
python | tiangolo__fastapi | docs_src/schema_extra_example/tutorial004_an_py310.py | {
"start": 114,
"end": 917
} | class ____(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
@app.put("/items/{item_id}")
async def update_item(
*,
item_id: int,
item: Annotated[
Item,
Body(
examples=[
{
"name": "Foo"... | Item |
python | sympy__sympy | sympy/plotting/pygletplot/managed_window.py | {
"start": 120,
"end": 3072
} | class ____(Window):
"""
A pyglet window with an event loop which executes automatically
in a separate thread. Behavior is added by creating a subclass
which overrides setup, update, and/or draw.
"""
fps_limit = 30
default_win_args = {"width": 600,
"height": 500,
... | ManagedWindow |
python | getsentry__sentry-python | sentry_sdk/integrations/celery/__init__.py | {
"start": 8109,
"end": 18699
} | class ____:
def __enter__(self):
# type: () -> None
return None
def __exit__(self, exc_type, exc_value, traceback):
# type: (Any, Any, Any) -> None
return None
def _wrap_task_run(f):
# type: (F) -> F
@wraps(f)
def apply_async(*args, **kwargs):
# type: (*Any... | NoOpMgr |
python | pytorch__pytorch | test/distributed/checkpoint/test_nested_dict.py | {
"start": 229,
"end": 2065
} | class ____(TestCase):
def test_flattening_round_trip(self) -> None:
state_dict = {
"key0": 1,
"key1": [1, 2],
"key2": {"1": 2, "2": 3},
"key3": torch.tensor([1]),
"key4": [[torch.tensor(2), "x"], [1, 2, 3], {"key6": [44]}],
}
flatt... | TestFlattening |
python | getsentry__sentry | src/sentry/grouping/strategies/base.py | {
"start": 1451,
"end": 1685
} | class ____(Protocol[ConcreteInterface]):
def __call__(
self,
interface: ConcreteInterface,
event: Event,
context: GroupingContext,
**kwargs: Any,
) -> ComponentsByVariant: ...
| StrategyFunc |
python | apache__airflow | providers/hashicorp/tests/unit/hashicorp/hooks/test_vault.py | {
"start": 1206,
"end": 58178
} | class ____:
@staticmethod
def get_mock_connection(
conn_type="vault", schema="secret", host="localhost", port=8180, user="user", password="pass"
):
mock_connection = mock.MagicMock()
type(mock_connection).conn_type = PropertyMock(return_value=conn_type)
type(mock_connection).... | TestVaultHook |
python | docker__docker-py | tests/unit/utils_config_test.py | {
"start": 163,
"end": 2143
} | class ____(unittest.TestCase):
@fixture(autouse=True)
def tmpdir(self, tmpdir):
self.mkdir = tmpdir.mkdir
def test_find_config_fallback(self):
tmpdir = self.mkdir('test_find_config_fallback')
with mock.patch.dict(os.environ, {'HOME': str(tmpdir)}):
assert config.find_c... | FindConfigFileTest |
python | python-openxml__python-docx | tests/oxml/test_xmlchemy.py | {
"start": 14474,
"end": 15657
} | class ____:
def it_adds_a_getter_property_for_the_attr_value(self, getter_fixture):
parent, optAttr_python_value = getter_fixture
assert parent.optAttr == optAttr_python_value
def it_adds_a_setter_property_for_the_attr(self, setter_fixture):
parent, value, expected_xml = setter_fixture
... | DescribeOptionalAttribute |
python | PrefectHQ__prefect | tests/server/models/test_workers.py | {
"start": 23796,
"end": 31602
} | class ____:
@pytest.fixture(autouse=True)
async def setup(self, session, flow):
"""
Creates:
- Three different work pools ("A", "B", "C")
- Three different queues in each pool ("AA", "AB", "AC", "BA", "BB", "BC", "CA", "CB", "CC")
- One pending run, one running run, and 5... | TestGetScheduledRuns |
python | keras-team__keras | keras/src/metrics/confusion_metrics.py | {
"start": 26341,
"end": 30012
} | class ____(SensitivitySpecificityBase):
"""Computes best sensitivity where specificity is >= specified value.
`Sensitivity` measures the proportion of actual positives that are correctly
identified as such `(tp / (tp + fn))`.
`Specificity` measures the proportion of actual negatives that are correctly
... | SensitivityAtSpecificity |
python | doocs__leetcode | solution/0300-0399/0373.Find K Pairs with Smallest Sums/Solution.py | {
"start": 0,
"end": 470
} | class ____:
def kSmallestPairs(
self, nums1: List[int], nums2: List[int], k: int
) -> List[List[int]]:
q = [[u + nums2[0], i, 0] for i, u in enumerate(nums1[:k])]
heapify(q)
ans = []
while q and k > 0:
_, i, j = heappop(q)
ans.append([nums1[i], num... | Solution |
python | pandas-dev__pandas | pandas/io/excel/_calamine.py | {
"start": 733,
"end": 3524
} | class ____(BaseExcelReader["CalamineWorkbook"]):
@doc(storage_options=_shared_docs["storage_options"])
def __init__(
self,
filepath_or_buffer: FilePath | ReadBuffer[bytes],
storage_options: StorageOptions | None = None,
engine_kwargs: dict | None = None,
) -> None:
""... | CalamineReader |
python | scipy__scipy | scipy/linalg/tests/test_fblas.py | {
"start": 14525,
"end": 14755
} | class ____(BaseGemv):
blas_func = fblas.dgemv
dtype = float64
try:
class TestCgemv(BaseGemv):
blas_func = fblas.cgemv
dtype = complex64
except AttributeError:
class TestCgemv:
pass
| TestDgemv |
python | openai__openai-python | src/openai/types/beta/realtime/session_create_params.py | {
"start": 8738,
"end": 10251
} | class ____(TypedDict, total=False):
create_response: bool
"""
Whether or not to automatically generate a response when a VAD stop event
occurs.
"""
eagerness: Literal["low", "medium", "high", "auto"]
"""Used only for `semantic_vad` mode.
The eagerness of the model to respond. `low` wil... | TurnDetection |
python | pytorch__pytorch | test/torch_np/test_basic.py | {
"start": 9060,
"end": 9713
} | class ____(TestCase):
"""Smoke test (sequence of arrays) -> (array)."""
@parametrize("func", seq_to_single_funcs)
def test_several(self, func):
arys = (
torch.Tensor([[1, 2, 3], [4, 5, 6]]),
w.asarray([[1, 2, 3], [4, 5, 6]]),
[[1, 2, 3], [4, 5, 6]],
)
... | TestSequenceOfArraysToSingle |
python | optuna__optuna | tests/artifacts_tests/stubs.py | {
"start": 589,
"end": 1609
} | class ____:
def __init__(self) -> None:
self._data: dict[str, io.BytesIO] = {}
self._lock = threading.Lock()
def open_reader(self, artifact_id: str) -> BinaryIO:
with self._lock:
data = self._data.get(artifact_id)
if data is None:
raise ArtifactNo... | InMemoryArtifactStore |
python | tensorflow__tensorflow | tensorflow/python/keras/optimizer_v1.py | {
"start": 7999,
"end": 10384
} | class ____(Optimizer):
"""RMSProp optimizer.
It is recommended to leave the parameters of this optimizer
at their default values
(except the learning rate, which can be freely tuned).
Args:
lr: float >= 0. Learning rate.
rho: float >= 0.
epsilon: float >= 0. Fuzz factor.
If `None`, default... | RMSprop |
python | pytorch__pytorch | test/dynamo/test_guard_serialization.py | {
"start": 2145,
"end": 2278
} | class ____:
def __getstate__(self):
raise RuntimeError("Cannot pickle")
def add(self, x):
return x + 1
| MyClass |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 774383,
"end": 775114
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"actor",
"created_at",
"head_ref",
"head_ref_name",
"pull_request",
)
actor = sgqlc.types.Field(Actor, graphql_name="actor")
... | HeadRefDeletedEvent |
python | django-haystack__django-haystack | test_haystack/elasticsearch5_tests/test_backend.py | {
"start": 58220,
"end": 60925
} | class ____(TestCase):
def setUp(self):
super().setUp()
# Wipe it clean.
self.raw_es = elasticsearch.Elasticsearch(
settings.HAYSTACK_CONNECTIONS["elasticsearch"]["URL"]
)
clear_elasticsearch_index()
# Stow.
self.old_ui = connections["elasticsearc... | Elasticsearch5BoostBackendTestCase |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_length.py | {
"start": 706,
"end": 763
} | class ____:
def __len__(self):
return 42
| Length |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.