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 | apache__airflow | airflow-core/src/airflow/utils/types.py | {
"start": 1664,
"end": 2442
} | class ____(enum.Enum):
"""Class with TriggeredBy types for DagRun."""
CLI = "cli" # for the trigger subcommand of the CLI: airflow dags trigger
OPERATOR = "operator" # for the TriggerDagRunOperator
REST_API = "rest_api" # for triggering the DAG via RESTful API
UI = "ui" # for clicking the `Trig... | DagRunTriggeredByType |
python | huggingface__transformers | src/transformers/models/phimoe/modeling_phimoe.py | {
"start": 21782,
"end": 23475
} | class ____(nn.Module):
"""
This implementation is
strictly equivalent to standard MoE with full capacity (no
dropped tokens). It's faster since it formulates MoE operations
in terms of block-sparse operations to accommodate imbalanced
assignments of tokens to experts, whereas standard MoE either... | PhimoeSparseMoeBlock |
python | wntrblm__nox | nox/manifest.py | {
"start": 1305,
"end": 16153
} | class ____:
"""Session manifest.
The session manifest provides the source of truth for the sequence of
sessions that should be run by Nox.
It is possible for this to be mutated during execution. This allows for
useful use cases, such as for one session to "notify" another or
"chain" to another... | Manifest |
python | pytorch__pytorch | torch/autograd/profiler.py | {
"start": 44056,
"end": 47051
} | class ____:
"""Raises an error if a key is seen more than once."""
def __init__(self):
self.seen = set()
def see(self, *key):
r"""
Observe a key and raise an error if it is seen multiple times.
"""
if key in self.seen:
raise RuntimeError("duplicate key: ... | EnforceUnique |
python | realpython__materials | python-313/repl/power_factory.py | {
"start": 0,
"end": 255
} | class ____:
"""Create instances that can calculate powers."""
def __init__(self, exponent):
self.exponent = exponent
def __call__(self, number):
return number**self.exponent
cubed = PowerFactory(3)
print(cubed(13))
| PowerFactory |
python | jd__tenacity | tests/test_tenacity.py | {
"start": 2773,
"end": 3607
} | class ____(unittest.TestCase):
def test_retrying_repr(self):
class ConcreteRetrying(tenacity.BaseRetrying):
def __call__(self, fn, *args, **kwargs):
pass
repr(ConcreteRetrying())
def test_callstate_repr(self):
rs = RetryCallState(None, None, (), {})
... | TestBase |
python | spyder-ide__spyder | spyder/widgets/elementstable.py | {
"start": 8204,
"end": 24680
} | class ____(HoverRowsTableView):
def __init__(
self,
parent: Optional[QWidget],
highlight_hovered_row: bool = True,
add_padding_around_widgets: bool = False,
):
HoverRowsTableView.__init__(self, parent, custom_delegate=True)
# To highlight the hovered row
... | ElementsTable |
python | walkccc__LeetCode | solutions/2914. Minimum Number of Changes to Make Binary String Beautiful/2914.py | {
"start": 0,
"end": 111
} | class ____:
def minChanges(self, s: str) -> int:
return sum(a != b for a, b in zip(s[::2], s[1::2]))
| Solution |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_text_editor_code_execution_tool_result_error_param.py | {
"start": 275,
"end": 616
} | class ____(TypedDict, total=False):
error_code: Required[
Literal["invalid_tool_input", "unavailable", "too_many_requests", "execution_time_exceeded", "file_not_found"]
]
type: Required[Literal["text_editor_code_execution_tool_result_error"]]
error_message: Optional[str]
| BetaTextEditorCodeExecutionToolResultErrorParam |
python | oauthlib__oauthlib | examples/device_code_flow.py | {
"start": 7892,
"end": 9830
} | class ____(ServerSetupForTokenEndpoint):
def default_flow_token_response(self, request):
url, headers, body, status = self.server.create_token_response(request)
access_token = json.loads(body).get("access_token")
# return access_token in a http response
return access_token
@rat... | TokenEndpoint |
python | PyCQA__bandit | tests/unit/core/test_docs_util.py | {
"start": 147,
"end": 996
} | class ____(testtools.TestCase):
"""This set of tests exercises bandit.core.docs_util functions."""
BASE_URL = f"https://bandit.readthedocs.io/en/{bandit.__version__}/"
def test_overwrite_bib_info(self):
expected_url = self.BASE_URL + (
"blacklists/blacklist_calls.html" "#b304-b305-ciph... | DocsUtilTests |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/ROI.py | {
"start": 89654,
"end": 93389
} | class ____(ROI):
r"""
ROI subclass with two freely-moving handles defining a line.
============== =============================================================
**Arguments**
positions (list of two length-2 sequences) The endpoints of the line
segment. Note that, unlike the ... | LineSegmentROI |
python | django__django | tests/migrations/migrations_test_apps/unspecified_app_with_conflict/migrations/0002_conflicting_second.py | {
"start": 43,
"end": 335
} | class ____(migrations.Migration):
dependencies = [("unspecified_app_with_conflict", "0001_initial")]
operations = [
migrations.CreateModel(
"Something",
[
("id", models.AutoField(primary_key=True)),
],
)
]
| Migration |
python | google__jax | jax/_src/config.py | {
"start": 35309,
"end": 45321
} | class ____:
__slots__ = ["_config", "_new_value", "_prev_value"]
def __init__(self, config, new_value):
self._config = config
self._new_value = new_value
def __enter__(self):
self._prev_value = self._config.swap_local(self._new_value)
def __exit__(self, exc_type, exc_val, exc_tb):
self._confi... | UserContext |
python | psf__black | src/black/trans.py | {
"start": 6828,
"end": 11019
} | class ____(ABC):
"""
An implementation of the Transformer protocol that relies on its
subclasses overriding the template methods `do_match(...)` and
`do_transform(...)`.
This Transformer works exclusively on strings (for example, by merging
or splitting them).
The following sections can be... | StringTransformer |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-chatgpt-plugin/llama_index/readers/chatgpt_plugin/base.py | {
"start": 238,
"end": 2107
} | class ____(BaseReader):
"""ChatGPT Retrieval Plugin reader."""
def __init__(
self,
endpoint_url: str,
bearer_token: Optional[str] = None,
retries: Optional[Retry] = None,
batch_size: int = 100,
) -> None:
"""Chatgpt Retrieval Plugin."""
self._endpoint... | ChatGPTRetrievalPluginReader |
python | huggingface__transformers | src/transformers/pipelines/deprecated/text2text_generation.py | {
"start": 430,
"end": 556
} | class ____(enum.Enum):
TENSORS = 0
TEXT = 1
@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
| ReturnType |
python | pyca__cryptography | tests/hazmat/asn1/test_serialization.py | {
"start": 2753,
"end": 3217
} | class ____:
def test_string(self) -> None:
assert_roundtrips(
[
("", b"\x0c\x00"),
("hello", b"\x0c\x05hello"),
("Test User 1", b"\x0c\x0bTest User 1"),
(
"café",
b"\x0c\x05caf\xc3\xa9",
... | TestString |
python | has2k1__plotnine | plotnine/labels.py | {
"start": 366,
"end": 2125
} | class ____:
"""
Add labels for any aesthetics with a scale or title, subtitle & caption
"""
# Names of Scaled Aesthetics
x: str | None = None
"""
Name of the x-axis.
"""
y: str | None = None
"""
Name of the y-axis.
"""
alpha: str | None = None
"""
Name of t... | labs |
python | py-pdf__pypdf | pypdf/errors.py | {
"start": 1823,
"end": 1947
} | class ____(PyPdfError, RuntimeError):
"""Raised when the XMP XML document context is invalid or missing."""
| XmpDocumentError |
python | scipy__scipy | scipy/integrate/tests/test_integrate.py | {
"start": 16413,
"end": 18631
} | class ____:
"""Call an ode-class solver with several cases of parameter use."""
# solver_name must be set before tests can be run with this class.
# Set these in subclasses.
solver_name = ''
solver_uses_jac = False
def _get_solver(self, f, jac):
solver = ode(f, jac)
if self.so... | ODECheckParameterUse |
python | skorch-dev__skorch | skorch/helper.py | {
"start": 4359,
"end": 9153
} | class ____(Sequence):
# pylint: disable=anomalous-backslash-in-string
"""Helper class that wraps a torch dataset to make it work with
sklearn.
Sometimes, sklearn will touch the input data, e.g. when splitting
the data for a grid search. This will fail when the input data is
a torch dataset. To ... | SliceDataset |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess1.py | {
"start": 1665,
"end": 1787
} | class ____:
def __get__(self, instance: "type[ClassE] | None", owner: "MetaclassE"):
return None
| MetaDescriptorE |
python | numpy__numpy | numpy/polynomial/tests/test_hermite.py | {
"start": 11307,
"end": 12852
} | class ____:
# some random values in [-1, 1)
x = np.random.random((3, 5)) * 2 - 1
def test_hermvander(self):
# check for 1d x
x = np.arange(3)
v = herm.hermvander(x, 3)
assert_(v.shape == (3, 4))
for i in range(4):
coef = [0] * i + [1]
assert_a... | TestVander |
python | tensorflow__tensorflow | third_party/xla/build_tools/configure/configure.py | {
"start": 5631,
"end": 6565
} | class ____(enum.Enum):
"""Enum base class with helper methods for working with argparse.
Example usage:
```
class Fruit(ArgparseableEnum):
APPLE = enum.auto()
# argparse setup
parser.add_argument("--fruit", type=Fruit.from_str, choices=list(Fruit))
```
Users can pass strings like `--fruit=apple` w... | ArgparseableEnum |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/exc.py | {
"start": 939,
"end": 1910
} | class ____(sa_exc.SQLAlchemyError):
"""An operation encountered database state that is unaccounted for.
Conditions which cause this to happen include:
* A flush may have attempted to update or delete rows
and an unexpected number of rows were matched during
the UPDATE or DELETE statement. No... | StaleDataError |
python | pytorch__pytorch | torch/testing/_internal/distributed/ddp_under_dist_autograd_test.py | {
"start": 10665,
"end": 17267
} | class ____(RpcAgentTestFixture):
@property
def world_size(self) -> int:
return WORLD_SIZE
def remote_worker_name(self) -> str:
# The name has to be consistent with that in 'dist_init' decorator.
return f"worker{REMOTE_WORKER_RANK}"
def trainer_name(self, rank):
# The na... | DdpUnderDistAutogradTest |
python | buildout__buildout | zc.recipe.egg_/src/zc/recipe/egg/custom.py | {
"start": 777,
"end": 1069
} | class ____:
def __init__(self, buildout, name, options):
self.name, self.options = name, options
options['_d'] = buildout['buildout']['develop-eggs-directory']
self.build_ext = build_ext(buildout, options)
def update(self):
return self.install()
| Base |
python | eventlet__eventlet | eventlet/green/http/cookiejar.py | {
"start": 31542,
"end": 46022
} | class ____(CookiePolicy):
"""Implements the standard rules for accepting and returning cookies."""
DomainStrictNoDots = 1
DomainStrictNonDomain = 2
DomainRFC2965Match = 4
DomainLiberal = 0
DomainStrict = DomainStrictNoDots|DomainStrictNonDomain
def __init__(self,
blocked_... | DefaultCookiePolicy |
python | facebook__pyre-check | client/commands/tests/profile_test.py | {
"start": 238,
"end": 16574
} | class ____(testslide.TestCase):
def test_parse_event(self) -> None:
self.assertEqual(
profile.parse_event(
"""
{
"name": "Kara",
"worker_id": 579102694,
"pid": 400,
"event_type": [ "Duration",... | ProfileTest |
python | kamyu104__LeetCode-Solutions | Python/maximum-area-rectangle-with-point-constraints-ii.py | {
"start": 66,
"end": 1611
} | class ____(object):
def maxRectangleArea(self, xCoord, yCoord):
"""
:type xCoord: List[int]
:type yCoord: List[int]
:rtype: int
"""
class BIT(object): # 0-indexed.
def __init__(self, n):
self.__bit = [0]*(n+1) # Extra one for dummy node.
... | Solution |
python | scrapy__scrapy | tests/test_utils_asyncgen.py | {
"start": 127,
"end": 552
} | class ____:
@deferred_f_from_coro_f
async def test_as_async_generator(self):
ag = as_async_generator(range(42))
results = [i async for i in ag]
assert results == list(range(42))
@deferred_f_from_coro_f
async def test_collect_asyncgen(self):
ag = as_async_generator(range(... | TestAsyncgenUtils |
python | cython__cython | Cython/Compiler/Tests/TestCode.py | {
"start": 2290,
"end": 4273
} | class ____(TestCase):
def _process(self, code):
utility_code = UtilityCode()
formatted_code, is_module_specific = process_utility_ccode(utility_code, None, code)
self.assertFalse(is_module_specific) # cannot currently test this case
return formatted_code
def assert_formatted_co... | TestUtilityCodeProcessing |
python | coleifer__peewee | tests/keys.py | {
"start": 1312,
"end": 1486
} | class ____(TestModel):
thing = CharField()
user = ForeignKeyField(User, backref='things')
class Meta:
primary_key = CompositeKey('thing', 'user')
| UserThing |
python | pytorch__pytorch | torch/_library/opaque_object.py | {
"start": 173,
"end": 6542
} | class ____:
def __init__(self) -> None:
pass
@classmethod
def __obj_unflatten__(cls, flattened_ctx: dict[str, Any]) -> None:
raise RuntimeError(
"FakeOpaqueObject should not be created through __obj_unflatten__ "
"and should be special handled. Please file an issue t... | FakeOpaqueObject |
python | doocs__leetcode | solution/1100-1199/1184.Distance Between Bus Stops/Solution.py | {
"start": 0,
"end": 319
} | class ____:
def distanceBetweenBusStops(
self, distance: List[int], start: int, destination: int
) -> int:
s = sum(distance)
t, n = 0, len(distance)
while start != destination:
t += distance[start]
start = (start + 1) % n
return min(t, s - t)
| Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructorCallable2.py | {
"start": 696,
"end": 935
} | class ____:
def __new__(cls, *args, **kwargs) -> Self: ...
def __init__(self, x: int) -> None: ...
r3 = accepts_callable(Class3)
reveal_type(r3, expected_text="(x: int) -> Class3")
reveal_type(r3(3), expected_text="Class3")
| Class3 |
python | apache__airflow | dev/breeze/src/airflow_breeze/utils/custom_param_types.py | {
"start": 4638,
"end": 4730
} | class ____:
value: Any
def __repr__(self):
return self.value
| CacheableDefault |
python | django-guardian__django-guardian | example_project/articles/views.py | {
"start": 1259,
"end": 1450
} | class ____(PermissionRequiredMixin, DeleteView):
model = Article
success_url = reverse_lazy("articles:list")
permission_required = ["view_article", "delete_article"]
| ArticleDeleteView |
python | scikit-learn__scikit-learn | sklearn/neighbors/_base.py | {
"start": 38763,
"end": 52382
} | class ____:
"""Mixin for radius-based neighbors searches."""
def _radius_neighbors_reduce_func(self, dist, start, radius, return_distance):
"""Reduce a chunk of distances to the nearest neighbors.
Callback to :func:`sklearn.metrics.pairwise.pairwise_distances_chunked`
Parameters
... | RadiusNeighborsMixin |
python | walkccc__LeetCode | solutions/3317. Find the Number of Possible Ways for an Event/3317.py | {
"start": 0,
"end": 1178
} | class ____:
def numberOfWays(self, n: int, x: int, y: int) -> int:
MOD = 1_000_000_007
@functools.lru_cache(None)
def fact(i: int) -> int:
return 1 if i <= 1 else i * fact(i - 1) % MOD
@functools.lru_cache(None)
def inv(i: int) -> int:
return pow(i, MOD - 2, MOD)
@functools.lru_... | Solution |
python | redis__redis-py | redis/asyncio/connection.py | {
"start": 34809,
"end": 36884
} | class ____(AbstractConnection):
"Manages UDS communication to and from a Redis server"
def __init__(self, *, path: str = "", **kwargs):
self.path = path
super().__init__(**kwargs)
def repr_pieces(self) -> Iterable[Tuple[str, Union[str, int]]]:
pieces = [("path", self.path), ("db", ... | UnixDomainSocketConnection |
python | ray-project__ray | rllib/core/rl_module/torch/tests/test_torch_rl_module.py | {
"start": 3732,
"end": 5445
} | class ____(unittest.TestCase):
@unittest.skipIf(not _dynamo_is_available(), "torch._dynamo not available")
def test_torch_compile_no_memory_leak_gpu(self):
assert torch.cuda.is_available()
def get_memory_usage_cuda():
torch.cuda.empty_cache()
return torch.cuda.memory_all... | TestRLModuleGPU |
python | pallets__werkzeug | examples/simplewiki/database.py | {
"start": 2909,
"end": 3846
} | class ____(Page, Revision):
"""
Represents a wiki page with a revision. Thanks to multiple inheritance
and the ability of SQLAlchemy to map to joins we can combine `Page` and
`Revision` into one class here.
"""
query = session.query_property()
def __init__(self):
raise TypeError(
... | RevisionedPage |
python | gevent__gevent | src/gevent/tests/test__queue.py | {
"start": 15948,
"end": 16035
} | class ____(TestGetInterrupt):
kind = queue.PriorityQueue
| TestGetInterruptPriorityQueue |
python | pytorch__pytorch | torch/testing/_internal/common_quantization.py | {
"start": 99089,
"end": 100144
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
norm_layer = nn.BatchNorm2d
inplanes = 3
self.conv1 = nn.Conv2d(inplanes, inplanes, (1, 1), bias=False)
self.conv2 = nn.Conv2d(inplanes, inplanes, (1, 1), bias=False)
self.bn1 = norm_layer(inp... | ModelMultipleOpsNoAvgPool |
python | kamyu104__LeetCode-Solutions | Python/choose-numbers-from-two-arrays-in-range.py | {
"start": 116,
"end": 741
} | class ____(object):
def countSubranges(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: int
"""
MOD = 10**9+7
result = 0
dp = collections.Counter()
for x, y in itertools.izip(nums1, nums2):
new_dp = co... | Solution |
python | pytorch__pytorch | test/distributed/elastic/utils/logging_test.py | {
"start": 416,
"end": 1071
} | class ____(TestCase):
def setUp(self):
super().setUp()
self.clazz_log = logging.get_logger()
def test_logger_name(self):
local_log = logging.get_logger()
name_override_log = logging.get_logger("foobar")
self.assertEqual(__name__, log.name)
self.assertEqual(__nam... | LoggingTest |
python | tox-dev__tox | src/tox/session/env_select.py | {
"start": 4958,
"end": 5435
} | class ____:
"""tox environment information."""
env: PackageToxEnv | RunToxEnv #: the tox environment
is_active: bool #: a flag indicating if the environment is marked as active in the current run
package_skip: tuple[str, Skip] | None = None #: if set the creation of the packaging environment failed
... | _ToxEnvInfo |
python | facebook__pyre-check | tools/upgrade/commands/command.py | {
"start": 1553,
"end": 1817
} | class ____:
def __init__(self, repository: Repository) -> None:
self._repository: Repository = repository
@classmethod
def add_arguments(cls, parser: argparse.ArgumentParser) -> None:
pass
def run(self) -> None:
pass
| Command |
python | mwaskom__seaborn | seaborn/palettes.py | {
"start": 2246,
"end": 27857
} | class ____(list):
"""Set the color palette in a with statement, otherwise be a list."""
def __enter__(self):
"""Open the context."""
from .rcmod import set_palette
self._orig_palette = color_palette()
set_palette(self)
return self
def __exit__(self, *args):
"... | _ColorPalette |
python | tensorflow__tensorflow | tensorflow/python/data/util/structure_test.py | {
"start": 21245,
"end": 42415
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
# pylint: disable=g-long-lambda,protected-access
@combinations.generate(
combinations.times(test_base.default_test_combinations(),
_test_flat_structure_combinations()))
def testFlatStructure(self, value_fn, expected_str... | StructureTest |
python | pandas-dev__pandas | pandas/tests/extension/base/ops.py | {
"start": 7694,
"end": 9145
} | class ____(BaseOpsUtil):
"""Various Series and DataFrame comparison ops methods."""
def _compare_other(self, ser: pd.Series, data, op, other):
if op.__name__ in ["eq", "ne"]:
# comparison should match point-wise comparisons
result = op(ser, other)
expected = ser.comb... | BaseComparisonOpsTests |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/ext/hybrid/hybrid_four.py | {
"start": 1556,
"end": 1872
} | class ____(FirstNameOnly):
last_name: Mapped[str]
@FirstNameOnly.name.getter
def name(self) -> str:
return self.first_name + " " + self.last_name
@name.inplace.setter
def _name_setter(self, value: str) -> None:
self.first_name, self.last_name = value.split(" ", 1)
| FirstNameLastName |
python | pytorch__pytorch | test/quantization/pt2e/test_xnnpack_quantizer.py | {
"start": 1330,
"end": 43232
} | class ____(PT2EQuantizationTestCase):
def test_conv1d(self):
quantizer = XNNPACKQuantizer()
quantization_config = get_symmetric_quantization_config(is_per_channel=True)
quantizer.set_global(quantization_config)
example_inputs = (torch.randn(1, 3, 5),)
node_occurrence = {
... | TestXNNPACKQuantizer |
python | pytorch__pytorch | torch/_inductor/exc.py | {
"start": 658,
"end": 1030
} | class ____(RuntimeError):
@staticmethod
def operator_str(target: Any, args: list[Any], kwargs: dict[str, Any]) -> str:
lines = [f"target: {target}"] + [
f"args[{i}]: {arg}" for i, arg in enumerate(args)
]
if kwargs:
lines.append(f"kwargs: {kwargs}")
return... | OperatorIssue |
python | scipy__scipy | scipy/linalg/tests/test_decomp_update.py | {
"start": 24896,
"end": 24959
} | class ____(BaseQRdelete):
dtype = np.dtype('f')
| TestQRdelete_f |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0060_make_rank_not_null.py | {
"start": 179,
"end": 767
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0059_migrate_null_rank"),
]
operations = [
migrations.AlterField(
model_name="importedfile",
name="rank",
field=models.IntegerField(
default=0,... | Migration |
python | lxml__lxml | src/lxml/tests/test_etree.py | {
"start": 184808,
"end": 197325
} | class ____(HelperTestCase):
def test_c14n(self):
tree = self.parse(b'<a><b/></a>')
f = BytesIO()
tree.write_c14n(f)
s = f.getvalue()
self.assertEqual(b'<a><b></b></a>',
s)
def test_c14n_gzip(self):
tree = self.parse(b'<a>'+b'<b/>'*200+b'... | ETreeC14NTestCase |
python | graphql-python__graphene | graphene/types/tests/test_scalar.py | {
"start": 1198,
"end": 1512
} | class ____(ObjectType):
int = Int(input=Int(), resolver=return_input)
big_int = BigInt(input=BigInt(), resolver=return_input)
float = Float(input=Float(), resolver=return_input)
bool = Boolean(input=Boolean(), resolver=return_input)
string = String(input=String(), resolver=return_input)
| Optional |
python | openai__openai-python | src/openai/types/responses/response_computer_tool_call_param.py | {
"start": 2970,
"end": 3454
} | class ____(TypedDict, total=False):
scroll_x: Required[int]
"""The horizontal scroll distance."""
scroll_y: Required[int]
"""The vertical scroll distance."""
type: Required[Literal["scroll"]]
"""Specifies the event type.
For a scroll action, this property is always set to `scroll`.
""... | ActionScroll |
python | huggingface__transformers | tests/models/llava/test_processing_llava.py | {
"start": 822,
"end": 4912
} | class ____(ProcessorTesterMixin, unittest.TestCase):
processor_class = LlavaProcessor
@classmethod
def _setup_image_processor(cls):
image_processor_class = cls._get_component_class_from_processor("image_processor")
return image_processor_class(do_center_crop=False)
@classmethod
def... | LlavaProcessorTest |
python | getsentry__sentry | src/sentry/releases/endpoints/project_release_stats.py | {
"start": 1395,
"end": 4320
} | class ____(ProjectEndpoint):
publish_status = {
"GET": ApiPublishStatus.UNKNOWN,
}
permission_classes = (ProjectReleasePermission,)
def get(self, request: Request, project, version) -> Response:
"""
Get a Project Release's Stats
`````````````````````````````
Ret... | ProjectReleaseStatsEndpoint |
python | google__jax | tests/random_test.py | {
"start": 28322,
"end": 28730
} | class ____(jtu.JaxTestCase):
@parameterized.parameters([{'make_key': ctor} for ctor in [
partial(random.PRNGKey, impl='threefry2x32'),
partial(random.key, impl='threefry2x32')]])
def test_seed_no_implicit_transfers(self, make_key):
# See https://github.com/jax-ml/jax/issues/15613
with jax.transf... | ThreefryPrngTest |
python | huggingface__transformers | src/transformers/models/roformer/configuration_roformer.py | {
"start": 785,
"end": 6140
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`RoFormerModel`]. It is used to instantiate an
RoFormer model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar co... | RoFormerConfig |
python | PyCQA__pylint | tests/functional/a/abstract/abstract_method.py | {
"start": 1773,
"end": 1878
} | class ____(Structure):
__hash__ = 42
# +1: [abstract-method, abstract-method, abstract-method]
| Hashable |
python | realpython__materials | solid-principles-python/app_dip.py | {
"start": 634,
"end": 716
} | class ____(ABC):
@abstractmethod
def get_data(self):
pass
| DataSource |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/taint_in_taint_out.py | {
"start": 1457,
"end": 2689
} | class ____(FieldIsTITO):
pass
def adds_tito_inherited(x: InheritsFromTITO) -> int:
return x.add_tito
def adds_tito_with_indirect_sink(src: FieldIsTITO) -> None:
indirect_sink(src)
def indirect_sink(x: FieldIsTITO) -> None:
_test_sink(x.add_tito)
def issue_with_indirect_sink_tito():
x = _test... | InheritsFromTITO |
python | huggingface__transformers | src/transformers/models/idefics2/modeling_idefics2.py | {
"start": 29057,
"end": 31282
} | class ____(Idefics2PreTrainedModel):
config: Idefics2PerceiverConfig
input_modalities = ("image",)
_supports_sdpa = True
_supports_flash_attention_2 = True
_supports_flex_attn = True
def __init__(self, config) -> None:
super().__init__(config)
self.hidden_size = config.hidden_si... | Idefics2PerceiverResampler |
python | ApeWorX__ape | src/ape/api/projects.py | {
"start": 258,
"end": 1647
} | class ____(BaseInterfaceModel):
"""
An API for obtaining sources.
"""
name: str
"""
The package-name of the dependency.
"""
config_override: dict = Field(default_factory=dict, repr=False)
"""
Set different config than what Ape can deduce.
"""
@property
@abstractmet... | DependencyAPI |
python | pytorch__pytorch | torch/onnx/_internal/fx/passes/type_promotion.py | {
"start": 11193,
"end": 12361
} | class ____(ReductionTypePromotionRule):
"""Reference type promotion rule from torch.ops.aten.all or torch.ops.aten.any.
This is a special case where computation dtype is always torch.bool.
The result dtype is always uint8 if `dtype` kwarg is uint8, otherwise torch.bool.
"""
def __init__(self, op_n... | AllOrAnyReductionTypePromotionRule |
python | altair-viz__altair | altair/utils/schemapi.py | {
"start": 36861,
"end": 37831
} | class ____(Generic[_JSON_VT_co], Protocol): # type: ignore[misc]
"""
Represents ``altair`` classes which *may* not derive ``SchemaBase``.
Attributes
----------
_schema
A single item JSON Schema using the `type`_ keyword.
Notes
-----
Should be kept tightly defined to the **mini... | SchemaLike |
python | django__django | tests/gis_tests/test_data.py | {
"start": 895,
"end": 1204
} | class ____(TestObj):
"""
Object for testing GDAL data sources.
"""
def __init__(self, name, *, ext="shp", **kwargs):
# Shapefile is default extension, unless specified otherwise.
self.name = name
self.ds = get_ds_file(name, ext)
super().__init__(**kwargs)
| TestDS |
python | facelessuser__pymdown-extensions | pymdownx/emoji.py | {
"start": 11686,
"end": 13990
} | class ____(Extension):
"""Add emoji extension to Markdown class."""
def __init__(self, *args, **kwargs):
"""Initialize."""
self.config = {
'emoji_index': [
emojione,
"Function that returns the desired emoji index. - Default: 'pymdownx.emoji.emojione'... | EmojiExtension |
python | langchain-ai__langchain | libs/partners/nomic/langchain_nomic/embeddings.py | {
"start": 244,
"end": 4148
} | class ____(Embeddings):
"""`NomicEmbeddings` embedding model.
Example:
```python
from langchain_nomic import NomicEmbeddings
model = NomicEmbeddings()
```
"""
@overload
def __init__(
self,
*,
model: str,
nomic_api_key: str | None = .... | NomicEmbeddings |
python | pandas-dev__pandas | pandas/tests/arrays/categorical/test_operators.py | {
"start": 4553,
"end": 15909
} | class ____:
@pytest.mark.parametrize(
"categories",
[["a", "b"], [0, 1], [Timestamp("2019"), Timestamp("2020")]],
)
def test_not_equal_with_na(self, categories):
# https://github.com/pandas-dev/pandas/issues/32276
c1 = Categorical.from_codes([-1, 0], categories=categories)
... | TestCategoricalOps |
python | doocs__leetcode | solution/0600-0699/0658.Find K Closest Elements/Solution3.py | {
"start": 0,
"end": 362
} | class ____:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
left, right = 0, len(arr) - k
while left < right:
mid = (left + right) >> 1
if x - arr[mid] <= arr[mid + k] - x:
right = mid
else:
left = mid + ... | Solution |
python | langchain-ai__langchain | libs/langchain/tests/unit_tests/agents/test_agent.py | {
"start": 1258,
"end": 43655
} | class ____(LLM):
"""Fake LLM for testing that outputs elements of a list."""
responses: list[str]
i: int = -1
@override
def _call(
self,
prompt: str,
stop: list[str] | None = None,
run_manager: CallbackManagerForLLMRun | None = None,
**kwargs: Any,
) -> ... | FakeListLLM |
python | pydata__xarray | xarray/backends/lru_cache.py | {
"start": 221,
"end": 3661
} | class ____(MutableMapping[K, V]):
"""Thread-safe LRUCache based on an OrderedDict.
All dict operations (__getitem__, __setitem__, __contains__) update the
priority of the relevant key and take O(1) time. The dict is iterated over
in order from the oldest to newest key, which means that a complete pass
... | LRUCache |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/pandas_datasource.py | {
"start": 13193,
"end": 18408
} | class ____(_PandasDataAsset):
# instance attributes
type: Literal["dataframe"] = "dataframe"
class Config:
extra = pydantic.Extra.forbid
@override
def _get_reader_method(self) -> str:
raise NotImplementedError(
"""Pandas DataFrameAsset does not implement "_get_reader_me... | DataFrameAsset |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_core_utils.py | {
"start": 768,
"end": 8540
} | class ____(TestCase):
def setUp(self):
self.project = get(
Project, container_time_limit=None, main_language_project=None
)
self.version = get(Version, project=self.project)
@mock.patch("readthedocs.projects.tasks.builds.update_docs_task")
def test_trigger_skipped_projec... | CoreUtilTests |
python | python-poetry__poetry | src/poetry/utils/env/python/installer.py | {
"start": 1022,
"end": 1134
} | class ____(PythonInstallerError, ValueError):
pass
@dataclasses.dataclass(frozen=True)
| PythonInstallationError |
python | pytorch__pytorch | torch/_inductor/memory.py | {
"start": 15458,
"end": 38862
} | class ____:
size_alloc: int
size_free: int
def estimate_peak_memory_allocfree(
nodes: list[BaseSchedulerNode],
name_to_freeable_input_buf: dict[str, FreeableInputBuffer],
graph_outputs: OrderedSet[str],
) -> tuple[
int,
list[tuple[int, int]],
dict[BaseSchedulerNode, SNodeMemory],
d... | SNodeMemory |
python | allegroai__clearml | clearml/backend_api/services/v2_20/queues.py | {
"start": 29925,
"end": 31594
} | class ____(Request):
"""
Delete metadata from queue
:param queue: ID of the queue
:type queue: str
:param keys: The list of metadata keys to delete
:type keys: Sequence[str]
"""
_service = "queues"
_action = "delete_metadata"
_version = "2.20"
_schema = {
"definitio... | DeleteMetadataRequest |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_emoji.py | {
"start": 1895,
"end": 3241
} | class ____(util.MdCase):
"""Test strict mode."""
def test_strict(self):
"""Test strict mode."""
MD1 = ":apple:"
MD2 = ":apple:\n:bad:\n:whatever:\n\n:yep:\n"
extension_configs = {
'pymdownx.emoji': {
'strict': True
}
}
... | TestEmojiStrict |
python | doocs__leetcode | solution/0400-0499/0472.Concatenated Words/Solution.py | {
"start": 0,
"end": 356
} | class ____:
def __init__(self):
self.children = [None] * 26
self.is_end = False
def insert(self, w):
node = self
for c in w:
idx = ord(c) - ord('a')
if node.children[idx] is None:
node.children[idx] = Trie()
node = node.childre... | Trie |
python | getsentry__sentry | src/sentry/sentry_metrics/querying/units.py | {
"start": 2853,
"end": 3011
} | class ____:
"""
Represents a placeholder object for the unit metadata of a given QueryExpression.
"""
pass
@dataclass(frozen=True)
| UnitMetadata |
python | neetcode-gh__leetcode | python/0912-sort-an-array.py | {
"start": 0,
"end": 976
} | class ____:
def sortArray(self, nums: List[int]) -> List[int]:
def merge(arr, L, M, R):
left, right = arr[L:M+1], arr[M+1:R+1]
i, j, k = L, 0, 0
while j < len(left) and k < len(right):
if left[j] <= right[k]:
arr[i] = left[j]
... | Solution |
python | getsentry__sentry | tests/sentry/sentry_apps/api/parsers/test_video.py | {
"start": 142,
"end": 659
} | class ____(unittest.TestCase):
def setUp(self) -> None:
self.schema = {"type": "video", "url": "https://example.com/video.mov"}
def test_valid_schema(self) -> None:
validate_component(self.schema)
@invalid_schema
def test_missing_url(self) -> None:
del self.schema["url"]
... | TestVideoSchemaValidation |
python | getlogbook__logbook | src/logbook/handlers.py | {
"start": 3565,
"end": 11090
} | class ____(ContextObject, metaclass=_HandlerType):
"""Handler instances dispatch logging events to specific destinations.
The base handler class. Acts as a placeholder which defines the Handler
interface. Handlers can optionally use Formatter instances to format
records as desired. By default, no forma... | Handler |
python | TheAlgorithms__Python | data_structures/linked_list/print_reverse.py | {
"start": 192,
"end": 3611
} | class ____:
"""A class to represent a Linked List.
Use a tail pointer to speed up the append() operation.
"""
def __init__(self) -> None:
"""Initialize a LinkedList with the head node set to None.
>>> linked_list = LinkedList()
>>> (linked_list.head, linked_list.tail)
(N... | LinkedList |
python | getsentry__sentry | src/sentry/issues/endpoints/group_details.py | {
"start": 2467,
"end": 17874
} | class ____(GroupEndpoint):
publish_status = {
"DELETE": ApiPublishStatus.PRIVATE,
"GET": ApiPublishStatus.PRIVATE,
"PUT": ApiPublishStatus.PRIVATE,
}
enforce_rate_limit = True
rate_limits = RateLimitConfig(
limit_overrides={
"GET": {
RateLimitC... | GroupDetailsEndpoint |
python | django__django | django/forms/models.py | {
"start": 21125,
"end": 24405
} | class ____(BaseModelForm, metaclass=ModelFormMetaclass):
pass
def modelform_factory(
model,
form=ModelForm,
fields=None,
exclude=None,
formfield_callback=None,
widgets=None,
localized_fields=None,
labels=None,
help_texts=None,
error_messages=None,
field_classes=None,
):... | ModelForm |
python | kubernetes-client__python | kubernetes/client/models/v1beta1_cluster_trust_bundle_spec.py | {
"start": 383,
"end": 7385
} | 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... | V1beta1ClusterTrustBundleSpec |
python | wandb__wandb | tests/unit_tests/test_automations/test_automations.py | {
"start": 450,
"end": 9914
} | class ____:
"""Checks on the internal helper that prepares the GraphQL input for CreateFilterTrigger mutations."""
def test_same_results_from_equivalent_args(self, input_event, input_action):
"""Check that preparing the CreateFilterTrigger input object by passing the same values in different ways produ... | TestPrepareToCreate |
python | RaRe-Technologies__gensim | gensim/models/atmodel.py | {
"start": 3119,
"end": 5177
} | class ____(LdaState):
"""Encapsulate information for computation of :class:`~gensim.models.atmodel.AuthorTopicModel`."""
def __init__(self, eta, lambda_shape, gamma_shape):
"""
Parameters
----------
eta: numpy.ndarray
Dirichlet topic parameter for sparsity.
... | AuthorTopicState |
python | apache__airflow | providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/decorators/kubernetes.py | {
"start": 1923,
"end": 6203
} | class ____(DecoratedOperator, KubernetesPodOperator):
custom_operator_name = "@task.kubernetes"
# `cmds` and `arguments` are used internally by the operator
template_fields: Sequence[str] = tuple(
{"op_args", "op_kwargs", *KubernetesPodOperator.template_fields} - {"cmds", "arguments"}
)
# ... | _KubernetesDecoratedOperator |
python | streamlit__streamlit | lib/streamlit/runtime/state/query_params.py | {
"start": 1474,
"end": 9416
} | class ____(MutableMapping[str, str]):
"""A lightweight wrapper of a dict that sends forwardMsgs when state changes.
It stores str keys with str and List[str] values.
"""
_query_params: dict[str, list[str] | str] = field(default_factory=dict)
def __iter__(self) -> Iterator[str]:
self._ensur... | QueryParams |
python | buildout__buildout | src/zc/buildout/_package_index.py | {
"start": 42498,
"end": 46941
} | class ____(configparser.RawConfigParser):
def __init__(self):
"""
Load from ~/.pypirc
"""
defaults = dict.fromkeys(['username', 'password', 'repository'], '')
super().__init__(defaults)
rc = os.path.join(os.path.expanduser('~'), '.pypirc')
if os.path.exists(r... | PyPIConfig |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_image57.py | {
"start": 315,
"end": 842
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("image57.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workbook(... | TestCompareXLSXFiles |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.