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 | great-expectations__great_expectations | great_expectations/core/expectation_diagnostics/supporting_types.py | {
"start": 3728,
"end": 4070
} | class ____(SerializableDictDot):
"""Captures which of the three Execution Engines are supported by an Expectation. Used within the ExpectationDiagnostic object.""" # noqa: E501 # FIXME CoP
PandasExecutionEngine: bool
SqlAlchemyExecutionEngine: bool
SparkDFExecutionEngine: bool
@dataclass
| ExpectationExecutionEngineDiagnostics |
python | run-llama__llama_index | docs/examples/output_parsing/directory.py | {
"start": 1112,
"end": 1414
} | class ____(BaseModel):
"""
Container class representing a directory tree.
Args:
root (Node): The root node of the tree.
"""
root: Node = Field(..., description="Root folder of the directory tree")
Node.update_forward_refs()
DirectoryTree.update_forward_refs()
| DirectoryTree |
python | pytorch__pytorch | torch/_functorch/pyfunctorch.py | {
"start": 6510,
"end": 7830
} | class ____(FuncTorchInterpreter):
def __init__(self, cdata: CInterpreter):
assert cdata.key() == TransformType.Jvp
# See NOTE: [Interpreter cdata vs cptr]
self._cdata = cdata
@cached_property
# pyrefly: ignore [bad-override]
def _cptr(self):
return CJvpInterpreterPtr(sel... | JvpInterpreter |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 384982,
"end": 388205
} | class ____(Request):
"""
Mark a task status as in_progress. Optionally allows to set the task's execution progress.
:param force: If not true, call fails if the task status is not 'not_started'
:type force: bool
:param task: Task ID
:type task: str
:param status_reason: Reason for status ch... | StartedRequest |
python | PrefectHQ__prefect | src/prefect/server/utilities/messaging/memory.py | {
"start": 10820,
"end": 13092
} | class ____(_Consumer):
def __init__(
self,
topic: str,
subscription: Optional[Subscription] = None,
concurrency: int = 2,
**kwargs: Any,
):
self.topic: Topic = Topic.by_name(topic)
if not subscription:
subscription = self.topic.subscribe()
... | Consumer |
python | kamyu104__LeetCode-Solutions | Python/paint-house.py | {
"start": 790,
"end": 1254
} | class ____(object):
def minCost(self, costs):
"""
:type costs: List[List[int]]
:rtype: int
"""
if not costs:
return 0
n = len(costs)
for i in xrange(1, n):
costs[i][0] += min(costs[i - 1][1], costs[i - 1][2])
costs[i][1] +=... | Solution2 |
python | coleifer__peewee | tests/sqlite.py | {
"start": 2702,
"end": 2894
} | class ____(FTSModel, TestModel):
c1 = SearchField()
c2 = SearchField()
c3 = SearchField()
c4 = IntegerField()
class Meta:
options = {'tokenize': 'porter'}
| MultiColumn |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 319063,
"end": 320412
} | class ____(StatNode):
# Generated in the optimization of an if-elif-else node
#
# conditions [ExprNode]
# body StatNode
child_attrs = ['conditions', 'body']
def generate_condition_evaluation_code(self, code):
for cond in self.conditions:
cond.generate_evaluation... | SwitchCaseNode |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1263518,
"end": 1263713
} | class ____(VegaLiteSchema):
"""StandardType schema wrapper."""
_schema = {"$ref": "#/definitions/StandardType"}
def __init__(self, *args):
super().__init__(*args)
| StandardType |
python | ansible__ansible | test/lib/ansible_test/_internal/bootstrap.py | {
"start": 1686,
"end": 2085
} | class ____(Bootstrap):
"""Bootstrap docker instances."""
def get_variables(self) -> dict[str, t.Union[str, list[str]]]:
"""The variables to template in the bootstrapping script."""
variables = super().get_variables()
variables.update(
platform='',
platform_versi... | BootstrapDocker |
python | sympy__sympy | sympy/physics/quantum/piab.py | {
"start": 671,
"end": 1016
} | class ____(HermitianOperator):
"""Particle in a box Hamiltonian operator."""
@classmethod
def _eval_hilbert_space(cls, label):
return L2(Interval(S.NegativeInfinity, S.Infinity))
def _apply_operator_PIABKet(self, ket, **options):
n = ket.label[0]
return (n**2*pi**2*hbar**2)/(2*... | PIABHamiltonian |
python | wandb__wandb | wandb/apis/public/registries/registries_search.py | {
"start": 1100,
"end": 4402
} | class ____(RelayPaginator["RegistryFragment", "Registry"]):
"""A lazy iterator of `Registry` objects."""
QUERY: ClassVar[Document | None] = None
last_response: RegistryConnection | None
def __init__(
self,
client: RetryingClient,
organization: str,
filter: dict[str, Any... | Registries |
python | joke2k__faker | faker/providers/internet/fr_CH/__init__.py | {
"start": 46,
"end": 754
} | class ____(InternetProvider):
safe_email_tlds = ("org", "com", "net", "ch")
free_email_domains = (
"gmail.com",
"hotmail.fr",
"yahoo.fr",
"bluewin.ch",
"romandie.com",
"hispeed.ch",
"sunrise.ch",
"vtxnet.ch",
)
tlds = ("com", "com", "com", ... | Provider |
python | PyCQA__pylint | tests/functional/u/unused/unused_import_everything_disabled.py | {
"start": 277,
"end": 444
} | class ____:
"""For the bug reported in #6089 it is important to use the same names for the class attributes as in the imports."""
e = float(e)
pi = pi
| MyClass |
python | fabric__fabric | tests/transfer.py | {
"start": 301,
"end": 12204
} | class ____:
class init:
"__init__"
def requires_connection(self):
# Transfer() -> explodes
try:
Transfer()
except TypeError:
pass
else:
assert False, "Did not raise ArgumentError"
# Transfer(... | Transfer_ |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 51209,
"end": 52025
} | class ____(CBaseTypeNode):
# For C++ classes that live inside other C++ classes.
# name string
# base_type CBaseTypeNode
child_attrs = ['base_type']
def analyse(self, env, could_be_name=None):
base_type = self.base_type.analyse(env)
if base_type is PyrexTypes.er... | CNestedBaseTypeNode |
python | facebookresearch__faiss | tests/test_rabitq.py | {
"start": 11582,
"end": 18789
} | class ____(unittest.TestCase):
def do_comparison_vs_pq_test(self, metric_type=faiss.METRIC_L2):
nlist = 64
nprobe = 8
nq = 1000
ds = datasets.SyntheticDataset(TEST_DIM, TEST_N, TEST_N, nq)
k = 10
d = ds.d
xb = ds.get_database()
xt = ds.get_train()
... | TestIVFRaBitQ |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/blur_on_disabled.py | {
"start": 79,
"end": 416
} | class ____(App):
BINDINGS = [("f3", "disable")]
def compose(self) -> ComposeResult:
yield Input()
def on_ready(self) -> None:
self.query_one(Input).focus()
def action_disable(self) -> None:
self.query_one(Input).disabled = True
if __name__ == "__main__":
app = BlurApp()
... | BlurApp |
python | django-haystack__django-haystack | haystack/utils/loading.py | {
"start": 4061,
"end": 5523
} | class ____:
def __init__(self):
self._routers = None
@property
def routers(self):
if self._routers is None:
default_routers = ["haystack.routers.DefaultRouter"]
router_list = getattr(settings, "HAYSTACK_ROUTERS", default_routers)
# in case HAYSTACK_ROUTER... | ConnectionRouter |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_qt.py | {
"start": 22222,
"end": 25996
} | class ____(FigureManagerBase):
"""
Attributes
----------
canvas : `FigureCanvas`
The FigureCanvas instance
num : int or str
The Figure number
toolbar : qt.QToolBar
The qt.QToolBar
window : qt.QMainWindow
The qt.QMainWindow
"""
def __init__(self, canva... | FigureManagerQT |
python | redis__redis-py | redis/multidb/database.py | {
"start": 991,
"end": 1629
} | class ____(AbstractDatabase):
def __init__(
self,
weight: float,
health_check_url: Optional[str] = None,
):
self._weight = weight
self._health_check_url = health_check_url
@property
def weight(self) -> float:
return self._weight
@weight.setter
de... | BaseDatabase |
python | networkx__networkx | networkx/algorithms/centrality/tests/test_current_flow_betweenness_centrality_subset.py | {
"start": 3314,
"end": 5839
} | class ____:
def test_K4_normalized(self):
"""Betweenness centrality: K4"""
G = nx.complete_graph(4)
b = edge_current_flow_subset(G, list(G), list(G), normalized=True)
b_answer = edge_current_flow(G, normalized=True)
for (s, t), v1 in b_answer.items():
v2 = b.get((... | TestEdgeFlowBetweennessCentrality |
python | pytorch__pytorch | torch/utils/data/datapipes/iter/routeddecoder.py | {
"start": 586,
"end": 2731
} | class ____(IterDataPipe[tuple[str, Any]]):
r"""
Decodes binary streams from input DataPipe, yields pathname and decoded data in a tuple.
(functional name: ``routed_decode``)
Args:
datapipe: Iterable datapipe that provides pathname and binary stream in tuples
handlers: Optional user def... | RoutedDecoderIterDataPipe |
python | matplotlib__matplotlib | lib/matplotlib/_type1font.py | {
"start": 2369,
"end": 2489
} | class ____(_Token):
kind = 'keyword'
def is_keyword(self, *names):
return self.raw in names
| _KeywordToken |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/pipes/utils.py | {
"start": 23662,
"end": 24627
} | class ____(ABC):
@abstractmethod
def start(self, params: PipesParams, is_session_closed: Event) -> None: ...
@abstractmethod
def stop(self) -> None: ...
@abstractmethod
def is_running(self) -> bool: ...
@abstractmethod
def target_is_readable(self, params: PipesParams) -> bool: ...
... | PipesLogReader |
python | PrefectHQ__prefect | src/prefect/runner/storage.py | {
"start": 2161,
"end": 3458
} | class ____(Protocol):
"""
Protocol for credential blocks that can format themselves for git URLs.
Implementing this protocol allows credential blocks to own their auth
formatting logic instead of having it centralized in core Prefect.
This enables proper separation of concerns where each git provi... | _GitCredentialsFormatter |
python | django__django | tests/template_tests/syntax_tests/test_resetcycle.py | {
"start": 116,
"end": 4329
} | class ____(SimpleTestCase):
@setup({"resetcycle01": "{% resetcycle %}"})
def test_resetcycle01(self):
with self.assertRaisesMessage(TemplateSyntaxError, "No cycles in template."):
self.engine.get_template("resetcycle01")
@setup({"resetcycle02": "{% resetcycle undefinedcycle %}"})
de... | ResetCycleTagTests |
python | walkccc__LeetCode | solutions/3433. Count Mentions Per User/3433.py | {
"start": 60,
"end": 202
} | class ____:
returnTimestamp: int
userId: int
def __lt__(self, other):
return self.returnTimestamp < other.returnTimestamp
| OfflineUser |
python | google__jax | jax/_src/state/types.py | {
"start": 19214,
"end": 19528
} | class ____(core.AbstractValue):
inner_aval: core.AbstractValue
memory_space: Any = None
shape = property(lambda self: self.inner_aval.shape) # type: ignore
dtype = property(lambda self: self.inner_aval.dtype) # type: ignore
ndim = property(lambda self: self.inner_aval.ndim) # type: ignore
| AbstractLinVal |
python | numpy__numpy | numpy/_core/tests/test_numerictypes.py | {
"start": 13361,
"end": 16023
} | class ____:
# scalar types can be promoted into dtypes
wrappers = [np.dtype, lambda x: x]
def test_both_abstract(self):
assert_(np.issubdtype(np.floating, np.inexact))
assert_(not np.issubdtype(np.inexact, np.floating))
def test_same(self):
for cls in (np.float32, np.int32):
... | TestIsSubDType |
python | fastapi__sqlmodel | docs_src/tutorial/relationship_attributes/back_populates/tutorial003.py | {
"start": 752,
"end": 1584
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
team_id: Optional[int] = Field(default=None, foreign_key="team.id")
team: Optional[Team] = Relationship... | Hero |
python | openai__openai-python | src/openai/resources/beta/realtime/realtime.py | {
"start": 32699,
"end": 32851
} | class ____:
def __init__(self, connection: AsyncRealtimeConnection) -> None:
self._connection = connection
| BaseAsyncRealtimeConnectionResource |
python | pytorch__pytorch | test/test_subclass.py | {
"start": 1239,
"end": 10879
} | class ____(TestCase):
def _create_tensor(self, tensor_cls):
return subclass_db[tensor_cls].create_fn(3)
@parametrize_tensor_cls
@parametrize("tensor_requires_grad", [False, True])
def test_param_invariants(self, tensor_cls, tensor_requires_grad):
x = self._create_tensor(tensor_cls).requ... | TestSubclass |
python | pyca__cryptography | tests/hazmat/primitives/decrepit/test_algorithms.py | {
"start": 2477,
"end": 3246
} | class ____:
@pytest.mark.parametrize(
("key", "keysize"),
[(b"0" * (keysize // 4), keysize) for keysize in range(32, 449, 8)],
)
def test_key_size(self, key, keysize):
cipher = Blowfish(binascii.unhexlify(key))
assert cipher.key_size == keysize
def test_invalid_key_size(... | TestBlowfish |
python | jackfrued__Python-100-Days | Day31-35/code/example16.py | {
"start": 631,
"end": 1437
} | class ____():
def __init__(self, name):
self.name = name
self.students = {}
def __setitem__(self, key, student):
self.students[key] = student
def __getitem__(self, key):
return self.students[key]
def main():
# students = set()
# students.add(Student(1001, '王大锤'))... | School |
python | pandas-dev__pandas | pandas/tests/arrays/test_datetimes.py | {
"start": 10227,
"end": 29394
} | class ____:
def test_astype_ns_to_ms_near_bounds(self):
# GH#55979
ts = pd.Timestamp("1677-09-21 00:12:43.145225")
target = ts.as_unit("ms")
dta = DatetimeArray._from_sequence([ts], dtype="M8[ns]")
assert (dta.view("i8") == ts.as_unit("ns").value).all()
result = dta... | TestDatetimeArray |
python | numpy__numpy | numpy/_utils/_pep440.py | {
"start": 2335,
"end": 3411
} | class ____:
def __repr__(self):
return "-Infinity"
def __hash__(self):
return hash(repr(self))
def __lt__(self, other):
return True
def __le__(self, other):
return True
def __eq__(self, other):
return isinstance(other, self.__class__)
def __ne__(self,... | NegativeInfinity |
python | doocs__leetcode | solution/0700-0799/0738.Monotone Increasing Digits/Solution.py | {
"start": 0,
"end": 443
} | class ____:
def monotoneIncreasingDigits(self, n: int) -> int:
s = list(str(n))
i = 1
while i < len(s) and s[i - 1] <= s[i]:
i += 1
if i < len(s):
while i and s[i - 1] > s[i]:
s[i - 1] = str(int(s[i - 1]) - 1)
i -= 1
... | Solution |
python | django-haystack__django-haystack | test_haystack/test_fields.py | {
"start": 8339,
"end": 9994
} | class ____(TestCase):
def test_init(self):
try:
foo = EdgeNgramField(model_attr="foo")
except:
self.fail()
self.assertRaises(SearchFieldError, EdgeNgramField, faceted=True)
def test_prepare(self):
mock = MockModel()
mock.user = "daniel"
a... | EdgeNgramFieldTestCase |
python | getsentry__sentry | src/sentry/api/serializers/release_details_types.py | {
"start": 1711,
"end": 1870
} | class ____(ProjectOptional):
id: int
slug: str
name: str
platform: str | None
platforms: list[str] | None
hasHealthData: bool
| BaseProject |
python | pytorch__pytorch | torch/_inductor/compile_fx_ext.py | {
"start": 3544,
"end": 4268
} | class ____:
"""
This handles the data for serializing lowering.lowering
"""
# A full implementation would make sure that all lowerings are copied over
# (or at least detected and raise a bypass when a non-standard lowering is
# used). For now we just handle tests by looking for lowerings that w... | _LoweringSerializer |
python | getsentry__sentry | src/sentry/api/serializers/models/rule.py | {
"start": 2557,
"end": 12172
} | class ____(Serializer):
def __init__(
self,
expand: list[str] | None = None,
prepare_component_fields: bool = False,
project_slug: str | None = None,
):
super().__init__()
self.expand = expand or []
self.prepare_component_fields = prepare_component_fields
... | RuleSerializer |
python | django__django | tests/admin_views/test_autocomplete_view.py | {
"start": 14744,
"end": 23706
} | class ____(AdminSeleniumTestCase):
available_apps = ["admin_views"] + AdminSeleniumTestCase.available_apps
def setUp(self):
self.superuser = User.objects.create_superuser(
username="super",
password="secret",
email="super@example.com",
)
self.admin_lo... | SeleniumTests |
python | run-llama__llama_index | llama-index-core/llama_index/core/callbacks/llama_debug.py | {
"start": 383,
"end": 7768
} | class ____(PythonicallyPrintingBaseHandler):
"""
Callback handler that keeps track of debug info.
NOTE: this is a beta feature. The usage within our codebase, and the interface
may change.
This handler simply keeps track of event starts/ends, separated by event types.
You can use this callback... | LlamaDebugHandler |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/model_query_parameters_where.py | {
"start": 1300,
"end": 1780
} | class ____:
def test5_alarm1(self, x: List[str]):
pass
def test5_alarm2(self, x: List[int]):
pass
def test5_alarm3(self, x: C):
pass
def test5_alarm4(self, x: str):
pass
def test5_noalarm1(self, x: int):
pass
def test6_alarm1(a, b, c, d):
_test_sink(... | Test5 |
python | pyqtgraph__pyqtgraph | pyqtgraph/examples/ColorBarItem.py | {
"start": 195,
"end": 3349
} | class ____(QtWidgets.QMainWindow):
""" example application main window """
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
gr_wid = pg.GraphicsLayoutWidget(show=True)
self.setCentralWidget(gr_wid)
self.setWindowTitle('pyqtgraph example: Inte... | MainWindow |
python | astropy__astropy | astropy/modeling/tests/test_parameters.py | {
"start": 5480,
"end": 26638
} | class ____:
def setup_class(self):
"""
Unit tests for parameters
Read an iraf database file created by onedspec.identify. Use the
information to create a 1D Chebyshev model and perform the same fit.
Create also a gaussian model.
"""
test_file = get_pkg_data... | TestParameters |
python | getsentry__sentry | src/sentry/notifications/notification_action/action_validation.py | {
"start": 4611,
"end": 4840
} | class ____(TicketingActionValidatorHandler):
provider = Action.Type.JIRA_SERVER
notify_action_form = JiraServerNotifyServiceForm
@action_validator_registry.register(Action.Type.AZURE_DEVOPS)
| JiraServerActionValidatorHandler |
python | PrefectHQ__prefect | src/prefect/task_runners.py | {
"start": 31629,
"end": 34524
} | class ____(TaskRunner[PrefectDistributedFuture[R]]):
def __init__(self):
super().__init__()
def duplicate(self) -> "PrefectTaskRunner[R]":
return type(self)()
@overload
def submit(
self,
task: "Task[P, CoroutineType[Any, Any, R]]",
parameters: dict[str, Any],
... | PrefectTaskRunner |
python | keras-team__keras | keras/src/ops/operation_test.py | {
"start": 571,
"end": 850
} | class ____(operation.Operation):
def call(self, x):
return (x, x + 1)
def compute_output_spec(self, x):
return (
keras_tensor.KerasTensor(x.shape, x.dtype),
keras_tensor.KerasTensor(x.shape, x.dtype),
)
| OpWithMultipleOutputs |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarTuple12.py | {
"start": 449,
"end": 793
} | class ____(Protocol[*Ts, T]):
def __call__(self, *args: *Ts, keyed: T) -> tuple[Unpack[Ts], T]: ...
def example(a: int, b: str, *, keyed: bool) -> tuple[int, str, bool]:
return (a, b, keyed)
a: CallbackA[int, str, bool] = example
reveal_type(
a, expected_text="(a: int, b: str, *, keyed: bool) -> tuple[... | CallbackA |
python | altair-viz__altair | altair/utils/data.py | {
"start": 2906,
"end": 3387
} | class ____(PluginRegistry[DataTransformerType, R]):
_global_settings = {"consolidate_datasets": True}
@property
def consolidate_datasets(self) -> bool:
return self._global_settings["consolidate_datasets"]
@consolidate_datasets.setter
def consolidate_datasets(self, value: bool) -> None:
... | DataTransformerRegistry |
python | huggingface__transformers | src/transformers/models/maskformer/modeling_maskformer_swin.py | {
"start": 10456,
"end": 12841
} | class ____(nn.Module):
"""
Patch Merging Layer.
Args:
input_resolution (`tuple[int]`):
Resolution of input feature.
dim (`int`):
Number of input channels.
norm_layer (`nn.Module`, *optional*, defaults to `nn.LayerNorm`):
Normalization layer class.... | MaskFormerSwinPatchMerging |
python | pallets__quart | src/quart/wrappers/request.py | {
"start": 933,
"end": 3955
} | class ____:
"""A request body container.
The request body can either be iterated over and consumed in parts
(without building up memory usage) or awaited.
.. code-block:: python
async for data in body:
...
# or simply
complete = await body
Note: It is not poss... | Body |
python | numpy__numpy | numpy/random/tests/test_randomstate.py | {
"start": 19526,
"end": 57838
} | class ____:
# Make sure the random distribution returns the correct value for a
# given seed
seed = 1234567890
def test_rand(self):
rng = random.RandomState(self.seed)
actual = rng.rand(3, 2)
desired = np.array([[0.61879477158567997, 0.59162362775974664],
... | TestRandomDist |
python | huggingface__transformers | src/transformers/models/upernet/modeling_upernet.py | {
"start": 9701,
"end": 10004
} | class ____(PreTrainedModel):
config: UperNetConfig
main_input_name = "pixel_values"
input_modalities = ("image",)
_no_split_modules = []
@auto_docstring(
custom_intro="""
UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes.
"""
)
| UperNetPreTrainedModel |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_basic.py | {
"start": 21948,
"end": 23178
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"a",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column(
"b_id",
Inte... | SortOnlyOnImportantFKsTest |
python | ansible__ansible | lib/ansible/_internal/_templating/_engine.py | {
"start": 1944,
"end": 2261
} | class ____(enum.Enum):
# DTFIX-FUTURE: this enum ideally wouldn't exist - revisit/rename before making public
DEFAULT = enum.auto()
STOP_ON_TEMPLATE = enum.auto()
STOP_ON_CONTAINER = enum.auto()
ALWAYS_FINALIZE = enum.auto()
@dataclasses.dataclass(kw_only=True, slots=True, frozen=True)
| TemplateMode |
python | tartley__colorama | colorama/tests/utils.py | {
"start": 160,
"end": 230
} | class ____(StringIO):
def isatty(self):
return True
| StreamTTY |
python | lepture__authlib | authlib/oauth2/rfc6749/hooks.py | {
"start": 38,
"end": 1004
} | class ____:
_hooks = None
def __init__(self):
self._hooks = defaultdict(set)
def register_hook(self, hook_type, hook):
self._hooks[hook_type].add(hook)
def execute_hook(self, hook_type, *args, **kwargs):
for hook in self._hooks[hook_type]:
hook(self, *args, **kwarg... | Hookable |
python | run-llama__llama_index | llama-index-core/llama_index/core/retrievers/transform_retriever.py | {
"start": 365,
"end": 1586
} | class ____(BaseRetriever):
"""
Transform Retriever.
Takes in an existing retriever and a query transform and runs the query transform
before running the retriever.
"""
def __init__(
self,
retriever: BaseRetriever,
query_transform: BaseQueryTransform,
transform_... | TransformRetriever |
python | scipy__scipy | scipy/interpolate/_fitpack2.py | {
"start": 52329,
"end": 56420
} | class ____(BivariateSpline):
"""
Weighted least-squares bivariate spline approximation.
Parameters
----------
x, y, z : array_like
1-D sequences of data points (order is not important).
tx, ty : array_like
Strictly ordered 1-D sequences of knots coordinates.
w : array_like, ... | LSQBivariateSpline |
python | skorch-dev__skorch | skorch/callbacks/logging.py | {
"start": 18792,
"end": 24094
} | class ____(Callback):
"""Display a progress bar for each epoch.
The progress bar includes elapsed and estimated remaining time for
the current epoch, the number of batches processed, and other
user-defined metrics. The progress bar is erased once the epoch is
completed.
``ProgressBar`` needs t... | ProgressBar |
python | huggingface__transformers | tests/models/bark/test_modeling_bark.py | {
"start": 22716,
"end": 26296
} | class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
all_model_classes = (BarkCoarseModel,) if is_torch_available() else ()
# `BarkCoarseModel` inherits from `BarkCausalModel`, but requires an advanced generation config.
# `BarkCausalModel` does not, so we run generation tests there.
... | BarkCoarseModelTest |
python | celery__celery | t/unit/backends/test_redis.py | {
"start": 5228,
"end": 5270
} | class ____:
Sentinel = Sentinel
| sentinel |
python | mamba-org__mamba | micromamba/tests/test_proxy.py | {
"start": 506,
"end": 3793
} | class ____:
def __init__(self, exe: Path, conf: Path, dump: Path):
self.exe = Path(exe).resolve()
self.conf = Path(conf).resolve()
self.dump = Path(dump).resolve()
self.process = None
def start_proxy(self, port, options=[]):
assert self.process is None
self.proce... | MitmProxy |
python | cython__cython | tests/run/cpdef_optargs_pure.py | {
"start": 105,
"end": 910
} | class ____(object):
a = 99
def pymethod(self, x, y=1, z=PyClass):
"""
>>> obj = PyClass99()
>>> obj.pymethod(0)
(0, 1, 2)
"""
return x, y, z.a
def func(x, y=1, z=PyClass):
"""
>>> func(0)
(0, 1, 2)
>>> func(0, 3)
(0, 3, 2)
>>> func(0, 3,... | PyClass99 |
python | TheAlgorithms__Python | strings/autocomplete_using_trie.py | {
"start": 48,
"end": 1489
} | class ____:
def __init__(self) -> None:
self._trie: dict = {}
def insert_word(self, text: str) -> None:
trie = self._trie
for char in text:
if char not in trie:
trie[char] = {}
trie = trie[char]
trie[END] = True
def find_word(self, pr... | Trie |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_with.py | {
"start": 13605,
"end": 21277
} | class ____(ContextmanagerAssertionMixin, __TestCase):
def testSingleResource(self):
cm = mock_contextmanager_generator()
def shouldThrow():
with cm as self.resource:
self.assertInWithManagerInvariants(cm)
self.assertInWithGeneratorInvariants(self.resource)... | ExceptionalTestCase |
python | pytorch__pytorch | torch/nn/modules/activation.py | {
"start": 57601,
"end": 59400
} | class ____(Module):
r"""Applies the Softmax function to an n-dimensional input Tensor.
Rescales them so that the elements of the n-dimensional output Tensor
lie in the range [0,1] and sum to 1.
Softmax is defined as:
.. math::
\text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}
... | Softmax |
python | django-mptt__django-mptt | tests/myapp/tests.py | {
"start": 76513,
"end": 77937
} | class ____(TreeTestCase):
"""
Regression tests for #176 and #424
"""
def setUp(self):
OrderedInsertion.objects.create(name="a")
def test_deferred_order_insertion_by(self):
qs = OrderedInsertion.objects.defer("name")
with self.assertNumQueries(1):
nodes = list(qs... | DeferredAttributeTests |
python | vyperlang__vyper | vyper/compiler/input_bundle.py | {
"start": 524,
"end": 1196
} | class ____:
# an input to the compiler, basically an abstraction for file contents
source_id: int
path: PathLike # the path that was asked for
# resolved_path is the real path that was resolved to.
# mainly handy for debugging at this point
resolved_path: PathLike
contents: str
@cach... | CompilerInput |
python | huggingface__transformers | src/transformers/models/pegasus/modeling_pegasus.py | {
"start": 55800,
"end": 61834
} | class ____(PegasusPreTrainedModel, GenerationMixin):
_tied_weights_keys = {
"lm_head.weight": "model.decoder.embed_tokens.weight",
}
def __init__(self, config):
config = copy.deepcopy(config)
config.is_decoder = True
config.is_encoder_decoder = False
super().__init__... | PegasusForCausalLM |
python | tensorflow__tensorflow | tensorflow/python/tpu/tpu_embedding_for_serving_test.py | {
"start": 1267,
"end": 16972
} | class ____(test.TestCase):
def setUp(self):
super(TPUEmbeddingForServingTest, self).setUp()
self.embedding_values = np.array(list(range(32)), dtype=np.float64)
self.initializer = init_ops_v2.Constant(self.embedding_values)
# Embedding for video initialized to
# 0 1 2 3
# 4 5 6 7
# ...
... | TPUEmbeddingForServingTest |
python | kamyu104__LeetCode-Solutions | Python/lowest-common-ancestor-of-a-binary-tree.py | {
"start": 29,
"end": 729
} | class ____(object):
# @param {TreeNode} root
# @param {TreeNode} p
# @param {TreeNode} q
# @return {TreeNode}
def lowestCommonAncestor(self, root, p, q):
if root in (None, p, q):
return root
left, right = [self.lowestCommonAncestor(child, p, q) \
... | Solution |
python | getsentry__sentry | src/sentry/integrations/mixins/issues.py | {
"start": 1748,
"end": 2528
} | class ____(enum.Enum):
"""
When an issue's state changes, we may have to sync the state based on the
"done" states we get from the API. This enum encapsulates the three options
we have: "resolve", "unresolve", or "do nothing".
"""
NOOP = 0
RESOLVE = 1
UNRESOLVE = 2
@classmethod
... | ResolveSyncAction |
python | huggingface__transformers | tests/models/mobilenet_v1/test_modeling_mobilenet_v1.py | {
"start": 4958,
"end": 8067
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as MobileNetV1 does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
all_model_classes = (MobileNetV1Model, MobileNetV1ForImageClassific... | MobileNetV1ModelTest |
python | getsentry__sentry | tests/sentry/tasks/test_activity.py | {
"start": 229,
"end": 411
} | class ____(NotificationPlugin):
def notify_about_activity(self, activity):
pass
def is_enabled(self, project=None) -> bool:
return True
| BasicPreprocessorPlugin |
python | django__django | django/db/models/functions/text.py | {
"start": 11465,
"end": 11538
} | class ____(Transform):
function = "UPPER"
lookup_name = "upper"
| Upper |
python | google__pytype | pytype/tests/test_match2.py | {
"start": 15488,
"end": 20454
} | class ____(test_base.BaseTest):
"""Tests for non-iterable string behavior."""
def test_add_string(self):
ty = self.Infer("""
a = []
a += list("foo")
a += "bar"
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import List
a = ... # type: List[str]
""... | NonIterableStringsTest |
python | scikit-learn__scikit-learn | sklearn/linear_model/_coordinate_descent.py | {
"start": 53226,
"end": 69338
} | class ____(MultiOutputMixin, LinearModel, ABC):
"""Base class for iterative model fitting along a regularization path."""
_parameter_constraints: dict = {
"eps": [Interval(Real, 0, None, closed="neither")],
"n_alphas": [
Interval(Integral, 1, None, closed="left"),
Hidden... | LinearModelCV |
python | walkccc__LeetCode | solutions/3378. Count Connected Components in LCM Graph/3378.py | {
"start": 0,
"end": 554
} | class ____:
def __init__(self):
self.id = {}
self.rank = collections.Counter()
def unionByRank(self, u: int, v: int) -> None:
i = self.find(u)
j = self.find(v)
if i == j:
return
if self.rank[i] < self.rank[j]:
self.id[i] = j
elif self.rank[i] > self.rank[j]:
self.id[j]... | UnionFind |
python | huggingface__transformers | src/transformers/models/deepseek_vl/image_processing_deepseek_vl.py | {
"start": 2232,
"end": 21447
} | class ____(BaseImageProcessor):
r"""
Constructs a DEEPSEEK_VL image processor.
Args:
do_resize (`bool`, *optional*, defaults to `True`):
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
`do_resize` parameter in the `p... | DeepseekVLImageProcessor |
python | tensorflow__tensorflow | tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py | {
"start": 73170,
"end": 74198
} | class ____(test.TestCase):
# Checks that executing the same rng_func multiple times rarely produces the
# same result.
def _testSingleSessionNotConstant(
self,
rng_func,
num,
dtype,
min_or_mean,
max_or_stddev,
use_gpu,
op_seed=None,
graph_seed=None,
):
... | RandomOpTestCommon |
python | lepture__mistune | src/mistune/directives/toc.py | {
"start": 646,
"end": 3916
} | class ____(DirectivePlugin):
def __init__(self, min_level: int = 1, max_level: int = 3) -> None:
self.min_level = min_level
self.max_level = max_level
def generate_heading_id(self, token: Dict[str, Any], index: int) -> str:
return "toc_" + str(index + 1)
def parse(self, block: "Blo... | TableOfContents |
python | astropy__astropy | astropy/io/fits/hdu/base.py | {
"start": 27274,
"end": 28436
} | class ____(_BaseHDU):
"""
A Corrupted HDU class.
This class is used when one or more mandatory `Card`s are
corrupted (unparsable), such as the ``BITPIX``, ``NAXIS``, or
``END`` cards. A corrupted HDU usually means that the data size
cannot be calculated or the ``END`` card is not found. In th... | _CorruptedHDU |
python | gevent__gevent | examples/webpy.py | {
"start": 450,
"end": 1182
} | class ____(object):
# Since gevent's WSGIServer executes each incoming connection in a separate greenlet
# long running requests such as this one don't block one another;
# and thanks to "monkey.patch_all()" statement at the top, thread-local storage used by web.ctx
# becomes greenlet-local storage thus... | long_polling |
python | pandas-dev__pandas | asv_bench/benchmarks/tslibs/period.py | {
"start": 1999,
"end": 2593
} | class ____:
params = [["D"], [True, False]]
param_names = ["freq", "is_offset"]
def setup(self, freq, is_offset):
if is_offset:
self.freq = to_offset(freq)
else:
self.freq = freq
def time_period_constructor(self, freq, is_offset):
Period("2012-06-01", fr... | PeriodConstructor |
python | sympy__sympy | sympy/physics/optics/gaussopt.py | {
"start": 5126,
"end": 5768
} | class ____(RayTransferMatrix):
"""
Ray Transfer Matrix for refraction.
Parameters
==========
n1 :
Refractive index of one medium.
n2 :
Refractive index of other medium.
See Also
========
RayTransferMatrix
Examples
========
>>> from sympy.physics.opti... | FlatRefraction |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 340850,
"end": 341498
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("ExternalIdentityEdge"), graphql_name="edges"
)
nodes = sg... | ExternalIdentityConnection |
python | pytorch__pytorch | torch/_inductor/codegen/common.py | {
"start": 4247,
"end": 4556
} | class ____(ABC):
"""
An IR object possibly corresponding to a variable in the wrapper code.
"""
@abstractmethod
def get_name(self) -> str:
pass
@abstractmethod
def get_example(self) -> Union[torch.Tensor, sympy.Symbol]:
pass
@ir_dataclass(frozen=True)
| CodegenSymbol |
python | mahmoud__boltons | boltons/urlutils.py | {
"start": 55909,
"end": 57489
} | class ____(OrderedMultiDict):
"""A subclass of :class:`~dictutils.OrderedMultiDict` specialized for
representing query string values. Everything is fully unquoted on
load and all parsed keys and values are strings by default.
As the name suggests, multiple values are supported and insertion
order i... | QueryParamDict |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_image03.py | {
"start": 315,
"end": 841
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("image03.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workbook(... | TestCompareXLSXFiles |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/filter_test.py | {
"start": 9264,
"end": 10285
} | class ____(
test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(test_base.default_test_combinations())
def testShuffleFilter(self):
dataset = dataset_ops.Dataset.range(100)
dataset = global_shuffle_op._global_shuffle(dataset)
dataset = dataset.filter(lambda x: math_ops.equal(... | FilterGlobalShuffleTest |
python | pytorch__pytorch | torch/_inductor/index_propagation.py | {
"start": 6386,
"end": 13345
} | class ____(DefaultHandler):
"""Ops wrapper that tries to propagate constant and index_expr values through the computation.
This aims to maximize the compile time simplification possible, and convert
indirect indexing from arange into normal static indexing.
"""
def __init__(
self,
... | IndexPropagation |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/quantization_test.py | {
"start": 9530,
"end": 12038
} | class ____(op_bench.TorchBenchmarkBase):
r"""Benchmarks 3 different fake quantize per channel operators."""
def init(self, N, C, H, W, zero_point_dtype, nbits, device, op_func):
self.quant_min = 0
self.quant_max = 2**nbits - 1
self.quant_range = 2**nbits
# Axis is chosen with re... | FakeQuantizePerChannelOpBenchmark |
python | pytorch__pytorch | torch/testing/_internal/common_distributed.py | {
"start": 58522,
"end": 59359
} | class ____(DistributedTestBase):
"""
Use this for tests that actually run on multiple GPUs.
Decorate tests with @skip_if_lt_x_gpu(ngpu)
Note: MultiProcTestCase spawns processes per test and is slow.
Prefer MultiThreadedTestCase for most tests. Perhaps use this one
sparingly for integration tes... | DynamoDistributedMultiProcTestCase |
python | django__django | django/db/models/fields/related_lookups.py | {
"start": 5740,
"end": 5804
} | class ____(RelatedLookupMixin, LessThan):
pass
| RelatedLessThan |
python | pytorch__pytorch | test/test_cuda.py | {
"start": 159240,
"end": 195708
} | class ____(TestCase):
@unittest.skipIf(
TEST_CUDAMALLOCASYNC, "setContextRecorder not supported by CUDAMallocAsync"
)
def test_memory_snapshot(self):
try:
torch.cuda.memory.empty_cache()
torch.cuda.memory._record_memory_history("state", stacks="python")
# ... | TestCudaMallocAsync |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 7009,
"end": 7158
} | class ____(models.Model):
relations = models.ManyToManyField("self")
history = HistoricalRecords(m2m_fields=[relations])
| PollWithSelfManyToMany |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.