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 | huggingface__transformers | tests/models/mobilenet_v2/test_image_processing_mobilenet_v2.py | {
"start": 1223,
"end": 3381
} | class ____:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
image_size=18,
min_resolution=30,
max_resolution=400,
do_resize=True,
size=None,
do_center_crop=True,
crop_size=None,
do_reduce_labels=False,
):
... | MobileNetV2ImageProcessingTester |
python | kubernetes-client__python | kubernetes/client/models/v1_object_reference.py | {
"start": 383,
"end": 10311
} | 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... | V1ObjectReference |
python | pypa__warehouse | warehouse/helpdesk/services.py | {
"start": 5598,
"end": 6632
} | class ____:
"""
An AdminNotificationService that sends notifications to a Slack webhook.
https://api.slack.com/messaging/webhooks
"""
def __init__(self, *, session: Session, webhook_url: str) -> None:
self.http = session
self.webhook_url = webhook_url
@classmethod
def crea... | SlackAdminNotificationService |
python | spyder-ide__spyder | spyder/plugins/completion/providers/snippets/conftabs.py | {
"start": 1009,
"end": 9372
} | class ____(SpyderPreferencesTab):
TITLE = _('Snippets')
def __init__(self, parent):
super().__init__(parent)
self.snippets_language = 'python'
grammar_url = (
"<a href=\"{0}/specifications/specification-current#snippet_syntax\">"
"{1}</a>".format(LSP_URL, _('the ... | SnippetsConfigTab |
python | doocs__leetcode | solution/1800-1899/1801.Number of Orders in the Backlog/Solution.py | {
"start": 0,
"end": 917
} | class ____:
def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int:
buy, sell = [], []
for p, a, t in orders:
if t == 0:
while a and sell and sell[0][0] <= p:
x, y = heappop(sell)
if a >= y:
a -= ... | Solution |
python | run-llama__llama_index | llama-index-core/llama_index/core/indices/list/base.py | {
"start": 838,
"end": 5113
} | class ____(BaseIndex[IndexList]):
"""
Summary Index.
The summary index is a simple data structure where nodes are stored in
a sequence. During index construction, the document texts are
chunked up, converted to nodes, and stored in a list.
During query time, the summary index iterates through ... | SummaryIndex |
python | google__pytype | pytype/pyc/opcodes.py | {
"start": 10228,
"end": 10313
} | class ____(OpcodeWithArg):
_FLAGS = HAS_JREL | HAS_ARGUMENT
__slots__ = ()
| FOR_ITER |
python | Pylons__pyramid | tests/test_scripts/dummy.py | {
"start": 84,
"end": 303
} | class ____:
def __init__(self, implicit, explicit):
self._implicit = implicit
self.explicit = explicit
self.name_to_alias = {}
def implicit(self):
return self._implicit
| DummyTweens |
python | Textualize__textual | examples/five_by_five.py | {
"start": 2083,
"end": 3320
} | class ____(Widget):
"""Header for the game.
Comprises of the title (``#app-title``), the number of moves ``#moves``
and the count of how many cells are turned on (``#progress``).
"""
moves = reactive(0)
"""int: Keep track of how many moves the player has made."""
filled = reactive(0)
... | GameHeader |
python | getsentry__sentry | src/sentry/api/serializers/models/discoversavedquery.py | {
"start": 1330,
"end": 6496
} | class ____(Serializer):
def partial_serialize_explore_query(self, query: ExploreSavedQuery) -> dict:
query_keys = [
"environment",
"query",
"range",
"start",
"end",
"interval",
]
data = {
"id": str(query.id),... | DiscoverSavedQueryModelSerializer |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/operator4.py | {
"start": 93,
"end": 279
} | class ____:
def __rmul__(self, a: A):
pass
def __rmatmul__(self, a: A):
pass
def __matmul__(self, a: A):
pass
a, b = A(), B()
v1 = a @ b
v2 = b @ a
| B |
python | django__django | django/db/migrations/state.py | {
"start": 25490,
"end": 30279
} | class ____(Apps):
"""
Subclass of the global Apps registry class to better handle dynamic model
additions and removals.
"""
def __init__(self, real_apps, models, ignore_swappable=False):
# Any apps in self.real_apps should have all their models included
# in the render. We don't use... | StateApps |
python | eventlet__eventlet | eventlet/pools.py | {
"start": 121,
"end": 5971
} | class ____:
"""
Pool class implements resource limitation and construction.
There are two ways of using Pool: passing a `create` argument or
subclassing. In either case you must provide a way to create
the resource.
When using `create` argument, pass a function with no arguments::
htt... | Pool |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 113845,
"end": 114955
} | class ____(SimpleHandlerTestCase):
class Handler(RequestHandler):
def get(self):
self.write(self.xsrf_token)
def get_app_kwargs(self):
return dict(
xsrf_cookies=True, xsrf_cookie_kwargs=dict(httponly=True, expires_days=2)
)
def test_xsrf_httponly(self):
... | XSRFCookieKwargsTest |
python | google__pytype | pytype/pytd/booleq.py | {
"start": 9738,
"end": 17698
} | class ____:
"""Solver for boolean equations.
This solver computes the union of all solutions. I.e. rather than assigning
exactly one value to each variable, it will create a list of values for each
variable: All the values this variable has in any of the solutions.
To accomplish this, we use the following r... | Solver |
python | pytest-dev__pytest | src/_pytest/cacheprovider.py | {
"start": 8630,
"end": 10546
} | class ____:
def __init__(self, lfplugin: LFPlugin) -> None:
self.lfplugin = lfplugin
self._collected_at_least_one_failure = False
@hookimpl(wrapper=True)
def pytest_make_collect_report(
self, collector: nodes.Collector
) -> Generator[None, CollectReport, CollectReport]:
... | LFPluginCollWrapper |
python | pandas-dev__pandas | pandas/tests/extension/base/printing.py | {
"start": 48,
"end": 1110
} | class ____:
"""Tests checking the formatting of your EA when printed."""
@pytest.mark.parametrize("size", ["big", "small"])
def test_array_repr(self, data, size):
if size == "small":
data = data[:5]
else:
data = type(data)._concat_same_type([data] * 20)
resu... | BasePrintingTests |
python | pytorch__pytorch | torch/ao/nn/quantized/modules/embedding_ops.py | {
"start": 3038,
"end": 8956
} | class ____(torch.nn.Module):
r"""
A quantized Embedding module with quantized packed weights as inputs.
We adopt the same interface as `torch.nn.Embedding`, please see
https://pytorch.org/docs/stable/generated/torch.nn.Embedding.html for documentation.
Similar to :class:`~torch.nn.Embedding`, attri... | Embedding |
python | ansible__ansible | lib/ansible/module_utils/facts/hardware/aix.py | {
"start": 843,
"end": 11817
} | class ____(Hardware):
"""
AIX-specific subclass of Hardware. Defines memory and CPU facts:
- memfree_mb
- memtotal_mb
- swapfree_mb
- swaptotal_mb
- processor (a list)
- processor_count
- processor_cores
- processor_threads_per_core
- processor_vcpus
"""
platform = '... | AIXHardware |
python | django__django | tests/admin_inlines/admin.py | {
"start": 6880,
"end": 6948
} | class ____(admin.TabularInline):
model = SottoCapo
| SottoCapoInline |
python | jina-ai__jina | jina/serve/runtimes/gateway/health_model.py | {
"start": 477,
"end": 732
} | class ____(BaseModel):
"""Pydantic BaseModel for Jina status, used as the response model in REST app."""
jina: Dict
envs: Dict
class Config:
alias_generator = _to_camel_case
allow_population_by_field_name = True
| JinaInfoModel |
python | run-llama__llama_index | llama-index-core/llama_index/core/instrumentation/events/agent.py | {
"start": 1049,
"end": 1342
} | class ____(BaseEvent):
"""
AgentChatWithStepStartEvent.
Args:
user_msg (str): User input message.
"""
user_msg: str
@classmethod
def class_name(cls) -> str:
"""Class name."""
return "AgentChatWithStepStartEvent"
| AgentChatWithStepStartEvent |
python | pytorch__pytorch | test/test_serialization.py | {
"start": 3772,
"end": 4256
} | class ____(torch.Tensor):
@staticmethod
def __new__(cls, elem, **kwargs):
assert elem.dtype is torch.uint8
assert not kwargs.get("requires_grad", False)
kwargs["requires_grad"] = False
return torch.Tensor._make_wrapper_subclass(cls, up_size(elem.shape), dtype=torch.uint4, **kwarg... | UInt4Tensor |
python | pydata__xarray | asv_bench/benchmarks/indexing.py | {
"start": 2306,
"end": 3071
} | class ____:
def setup(self, key):
self.ds = xr.Dataset(
{
"var1": (("x", "y"), randn((nx, ny), frac_nan=0.1)),
"var2": (("x", "t"), randn((nx, nt))),
"var3": (("t",), randn(nt)),
},
coords={
"x": np.arange(nx... | Base |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 117471,
"end": 117794
} | class ____(sgqlc.types.Enum):
"""Properties by which team member connections can be ordered.
Enumeration Choices:
* `CREATED_AT`: Order team members by creation time
* `LOGIN`: Order team members by login
"""
__schema__ = github_schema
__choices__ = ("CREATED_AT", "LOGIN")
| TeamMemberOrderField |
python | tensorflow__tensorflow | tensorflow/compiler/tests/runtime_shape_check_test.py | {
"start": 1118,
"end": 2624
} | class ____(xla_test.XLATestCase):
def testUniqueDifferentSizes(self):
"""Test that we correctly check for shape mismatches at runtime."""
if 'tpu' in self.device.lower():
self.skipTest('We do not check shapes on TPU')
with ops.device(f'device:{self.device}:0'):
@def_function.function(jit_co... | RuntimeShapeCheckTest |
python | chroma-core__chroma | chromadb/api/collection_configuration.py | {
"start": 626,
"end": 890
} | class ____(TypedDict, total=False):
search_nprobe: int
write_nprobe: int
space: Space
ef_construction: int
ef_search: int
max_neighbors: int
reassign_neighbor_count: int
split_threshold: int
merge_threshold: int
| SpannConfiguration |
python | sqlalchemy__sqlalchemy | test/orm/test_relationship_criteria.py | {
"start": 84336,
"end": 90461
} | class ____(fixtures.DeclarativeMappedTest):
"""test #10223"""
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class Temperature(Base):
__tablename__ = "temperature"
id: Mapped[int] = mapped_column(primary_key=True)
pointless_flag: Mapped... | SubqueryCriteriaTest |
python | sphinx-doc__sphinx | sphinx/search/__init__.py | {
"start": 5212,
"end": 6428
} | class ____:
"""The search index as JavaScript file that calls a function
on the documentation search object to register the index.
"""
PREFIX = 'Search.setIndex('
SUFFIX = ')'
def dumps(self, data: Any) -> str:
data_json = json.dumps(data, separators=(',', ':'), sort_keys=True)
... | _JavaScriptIndex |
python | apache__airflow | providers/fab/tests/unit/fab/auth_manager/api_endpoints/test_auth.py | {
"start": 1262,
"end": 1744
} | class ____:
@pytest.fixture(autouse=True)
def set_attrs(self, minimal_app_for_auth_api):
self.app = minimal_app_for_auth_api
sm = self.app.appbuilder.sm
delete_user(self.app, "test")
role_admin = sm.find_role("Admin")
sm.add_user(
username="test",
... | BaseTestAuth |
python | django__django | tests/select_for_update/models.py | {
"start": 138,
"end": 201
} | class ____(Country):
join_date = models.DateField()
| EUCountry |
python | doocs__leetcode | solution/1500-1599/1563.Stone Game V/Solution.py | {
"start": 63,
"end": 908
} | class ____:
def stoneGameV(self, stoneValue: List[int]) -> int:
@cache
def dfs(i: int, j: int) -> int:
if i >= j:
return 0
ans = l = 0
r = s[j + 1] - s[i]
for k in range(i, j):
l += stoneValue[k]
r -= sto... | Solution |
python | ray-project__ray | python/ray/dashboard/modules/job/job_agent.py | {
"start": 692,
"end": 7832
} | class ____(dashboard_utils.DashboardAgentModule):
def __init__(self, dashboard_agent):
super().__init__(dashboard_agent)
self._job_manager = None
@routes.post("/api/job_agent/jobs/")
@optional_utils.deny_browser_requests()
@optional_utils.init_ray_and_catch_exceptions()
async def su... | JobAgent |
python | Netflix__metaflow | metaflow/plugins/cards/card_modules/json_viewer.py | {
"start": 3478,
"end": 7113
} | class ____(MetaflowCardComponent):
"""
A component for displaying YAML data with syntax highlighting and collapsible sections.
This component provides a rich view of YAML data with proper formatting and syntax highlighting.
Example:
```python
from metaflow.cards import YAMLViewer
from meta... | YAMLViewer |
python | getsentry__sentry-python | tests/integrations/celery/integration_tests/__init__.py | {
"start": 143,
"end": 1499
} | class ____(Scheduler):
"""
A custom scheduler that starts tasks immediately after starting Celery beat.
"""
def setup_schedule(self):
super().setup_schedule()
for _, entry in self.schedule.items():
self.apply_entry(entry)
def tick(self):
# Override tick to preve... | ImmediateScheduler |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/hashability2.py | {
"start": 360,
"end": 397
} | class ____:
__hash__: None = None
| C |
python | wepe__MachineLearning | DeepLearning Tutorials/FaceRecognition_CNN(olivettifaces)/use_CNN_olivettifaces.py | {
"start": 2213,
"end": 2656
} | class ____(object):
def __init__(self, input, params_W,params_b, n_in, n_out,
activation=T.tanh):
self.input = input
self.W = params_W
self.b = params_b
lin_output = T.dot(input, self.W) + self.b
self.output = (
lin_output if activation is None
... | HiddenLayer |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 43058,
"end": 43559
} | class ____(DelegatingLexer):
"""
Subclass of the `DjangoLexer` that highlights unlexed data with the
`CssLexer`.
"""
name = 'CSS+Django/Jinja'
aliases = ['css+django', 'css+jinja']
alias_filenames = ['*.css']
mimetypes = ['text/css+django', 'text/css+jinja']
def __init__(self, **op... | CssDjangoLexer |
python | huggingface__transformers | src/transformers/models/dinov2/modeling_dinov2.py | {
"start": 13643,
"end": 14355
} | class ____(nn.Module):
def __init__(self, config) -> None:
super().__init__()
in_features = out_features = config.hidden_size
hidden_features = int(config.hidden_size * config.mlp_ratio)
hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
self.weights_in = nn.Linea... | Dinov2SwiGLUFFN |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 14416,
"end": 16114
} | class ____(themeable):
"""
Make themeable also accept a sequence to values
This makes it possible to apply a different style value similar artists.
e.g.
theme(axis_text_x=element_text(color=("red", "green", "blue")))
The number of values in the list must match the number of objects
t... | MixinSequenceOfValues |
python | matplotlib__matplotlib | lib/matplotlib/transforms.py | {
"start": 74154,
"end": 77453
} | class ____(_BlendedMixin, Transform):
"""
A "blended" transform uses one transform for the *x*-direction, and
another transform for the *y*-direction.
This "generic" version can handle any given child transform in the
*x*- and *y*-directions.
"""
input_dims = 2
output_dims = 2
is_se... | BlendedGenericTransform |
python | spack__spack | lib/spack/spack/solver/input_analysis.py | {
"start": 15142,
"end": 16107
} | class ____(Counter):
def _compute_cache_values(self) -> None:
self._possible_dependencies, virtuals, _ = self.possible_graph.possible_dependencies(
*self.specs, allowed_deps=self.all_types
)
self._possible_virtuals.update(virtuals)
def possible_packages_facts(self, gen: "spa... | NoDuplicatesCounter |
python | huggingface__transformers | src/transformers/models/blt/configuration_blt.py | {
"start": 2874,
"end": 4888
} | class ____(PreTrainedConfig):
"""
Configuration class for the Blt Local Decoder component.
"""
model_type = "blt_local_decoder"
default_theta = 500000.0
def __init__(
self,
vocab_size: Optional[int] = 260,
cross_attn_all_layers: Optional[bool] = True,
cross_attn... | BltLocalDecoderConfig |
python | pytest-dev__pytest | testing/test_cacheprovider.py | {
"start": 9385,
"end": 39068
} | class ____:
def test_lastfailed_usecase(
self, pytester: Pytester, monkeypatch: MonkeyPatch
) -> None:
monkeypatch.setattr("sys.dont_write_bytecode", True)
p = pytester.makepyfile(
"""
def test_1(): assert 0
def test_2(): assert 0
def test_... | TestLastFailed |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_getnewargs/invalid_getnewargs_returned.py | {
"start": 840,
"end": 999
} | class ____:
""" __getnewargs__ returns str """
def __getnewargs__(self): # [invalid-getnewargs-returned]
return "(1, 2, 3)"
| SecondBadGetNewArgs |
python | walkccc__LeetCode | solutions/2056. Number of Valid Move Combinations On Chessboard/2056.py | {
"start": 0,
"end": 1639
} | class ____:
def countCombinations(
self,
pieces: list[str],
positions: list[list[int]],
) -> int:
n = len(pieces)
moves = {"rook": [(1, 0), (-1, 0), (0, 1), (0, -1)],
"bishop": [(1, 1), (1, -1), (-1, 1), (-1, -1)],
"queen": [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1... | Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/asset_key.py | {
"start": 972,
"end": 7089
} | class ____(IHaveNew):
"""Object representing the structure of an asset key. Takes in a sanitized string, list of
strings, or tuple of strings.
Example usage:
.. code-block:: python
from dagster import AssetKey
AssetKey("asset1")
AssetKey(["asset1"]) # same as the above
... | AssetKey |
python | Netflix__metaflow | test/core/tests/switch_in_branch.py | {
"start": 63,
"end": 1018
} | class ____(MetaflowTest):
PRIORITY = 2
ONLY_GRAPHS = ["switch_in_branch"]
@steps(0, ["start-split"], required=True)
def step_start(self):
self.condition = "case1"
@steps(0, ["switch-a"], required=True)
def step_a(self):
pass
@steps(0, ["branch-b"], required=True)
def s... | SwitchInBranchTest |
python | django__django | tests/delete/models.py | {
"start": 6477,
"end": 6565
} | class ____(models.Model):
delete_top = models.ForeignKey(DeleteTop, models.CASCADE)
| B1 |
python | django__django | tests/auth_tests/test_remote_user.py | {
"start": 15051,
"end": 15191
} | class ____(RemoteUserBackend):
"""Backend that doesn't create unknown users."""
create_unknown_user = False
| RemoteUserNoCreateBackend |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarTuple2.py | {
"start": 331,
"end": 1166
} | class ____(Generic[_T, Unpack[_Xs]]):
def __init__(self, *shape: Unpack[_Xs]):
self.x: tuple[Unpack[_Xs]] = shape
# This should generate an error
self.y: _Xs = shape
# This should generate two errors
def func1(self) -> Union[Unpack[_Xs]]: ...
# This should generate an error
... | ClassA |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/initsubclass1.py | {
"start": 1279,
"end": 1311
} | class ____(a=3):
a: int
| ClassI |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/alloy_db.py | {
"start": 52623,
"end": 57876
} | class ____(AlloyDBWriteBaseOperator):
"""
Create a Backup in an Alloy DB cluster.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:AlloyDBCreateBackupOperator`
:param backup_id: Required. ID of the backup to create.
:para... | AlloyDBCreateBackupOperator |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/session.py | {
"start": 186465,
"end": 198921
} | class ____(_SessionClassMethods, Generic[_S]):
"""A configurable :class:`.Session` factory.
The :class:`.sessionmaker` factory generates new
:class:`.Session` objects when called, creating them given
the configurational arguments established here.
e.g.::
from sqlalchemy import create_engi... | sessionmaker |
python | numba__numba | numba/core/datamodel/models.py | {
"start": 22369,
"end": 22855
} | class ____(StructModel):
_element_type = NotImplemented
def __init__(self, dmm, fe_type):
members = [
('real', fe_type.underlying_float),
('imag', fe_type.underlying_float),
]
super(ComplexModel, self).__init__(dmm, fe_type, members)
@register_default(types.Lit... | ComplexModel |
python | simonw__datasette | datasette/database.py | {
"start": 25191,
"end": 25416
} | class ____(Exception):
def __init__(self, e, sql, params):
self.e = e
self.sql = sql
self.params = params
def __str__(self):
return "QueryInterrupted: {}".format(self.e)
| QueryInterrupted |
python | PyCQA__bandit | bandit/core/config.py | {
"start": 429,
"end": 9840
} | class ____:
def __init__(self, config_file=None):
"""Attempt to initialize a config dictionary from a yaml file.
Error out if loading the yaml file fails for any reason.
:param config_file: The Bandit yaml config file
:raises bandit.utils.ConfigError: If the config is invalid or
... | BanditConfig |
python | walkccc__LeetCode | solutions/1685. Sum of Absolute Differences in a Sorted Array/1685.py | {
"start": 0,
"end": 306
} | class ____:
def getSumAbsoluteDifferences(self, nums: list[int]) -> list[int]:
prefix = list(itertools.accumulate(nums))
suffix = list(itertools.accumulate(nums[::-1]))[::-1]
return [num * (i + 1) - prefix[i] + suffix[i] - num * (len(nums) - i)
for i, num in enumerate(nums)]
| Solution |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/core_tests/test_mask_user_code_errors.py | {
"start": 888,
"end": 9780
} | class ____:
pass
@pytest.fixture(scope="function")
def enable_masking_user_code_errors() -> Any:
with environ({"DAGSTER_REDACT_USER_CODE_ERRORS": "1"}):
yield
def test_masking_basic(enable_masking_user_code_errors):
try:
with user_code_error_boundary(
error_cls=DagsterUserCod... | hunter2 |
python | huggingface__transformers | tests/cli/test_serve.py | {
"start": 13939,
"end": 20723
} | class ____(unittest.TestCase):
def test_processor_inputs_from_inbound_messages_llm(self):
modality = Modality.LLM
messages = expected_outputs = [
{"role": "user", "content": "How are you doing?"},
{"role": "assistant", "content": "I'm doing great, thank you for asking! How ca... | ServeCompletionsGenerateMockTests |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 20639,
"end": 20810
} | class ____(str, Enum):
NAV = "nav"
DAG = "dag"
DAG_RUN = "dag_run"
TASK = "task"
TASK_INSTANCE = "task_instance"
DASHBOARD = "dashboard"
| Destination1 |
python | justquick__django-activity-stream | actstream/drf/views.py | {
"start": 1044,
"end": 2038
} | class ____(viewsets.ReadOnlyModelViewSet):
def get_permissions(self):
if isinstance(DRF_SETTINGS['PERMISSIONS'], (tuple, list)):
return [import_obj(permission)() for permission in DRF_SETTINGS['PERMISSIONS']]
if isinstance(DRF_SETTINGS['PERMISSIONS'], dict):
lookup = {key.lo... | DefaultModelViewSet |
python | django__django | django/core/exceptions.py | {
"start": 1361,
"end": 1536
} | class ____(SuspiciousOperation):
"""
The number of fields in a GET or POST request exceeded
settings.DATA_UPLOAD_MAX_NUMBER_FILES.
"""
pass
| TooManyFilesSent |
python | pytorch__pytorch | test/distributed/fsdp/test_wrap.py | {
"start": 1591,
"end": 1890
} | class ____(nn.Module):
def __init__(self) -> None:
super().__init__()
self.lin = nn.Linear(10, 10, bias=False)
self.bn1 = nn.BatchNorm1d(10)
self.bn2 = nn.BatchNorm2d(10)
self.bn3 = nn.BatchNorm3d(10)
self.sync_bn = nn.SyncBatchNorm(10)
| BatchNormNet |
python | doocs__leetcode | solution/0500-0599/0594.Longest Harmonious Subsequence/Solution.py | {
"start": 0,
"end": 177
} | class ____:
def findLHS(self, nums: List[int]) -> int:
cnt = Counter(nums)
return max((c + cnt[x + 1] for x, c in cnt.items() if cnt[x + 1]), default=0)
| Solution |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/owners.py | {
"start": 443,
"end": 1035
} | class ____(graphene.Union):
class Meta:
types = (
GrapheneUserDefinitionOwner,
GrapheneTeamDefinitionOwner,
)
name = "DefinitionOwner"
def definition_owner_from_owner_str(
owner_str: str,
) -> Union[GrapheneUserDefinitionOwner, GrapheneTeamDefinitionOwner]:
... | GrapheneDefinitionOwner |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_length/invalid_length_returned.py | {
"start": 424,
"end": 524
} | class ____(type):
def __len__(cls):
return 1
@six.add_metaclass(LenMetaclass)
| LenMetaclass |
python | pytorch__pytorch | test/test_cpp_extensions_aot.py | {
"start": 7034,
"end": 10719
} | class ____(common.TestCase):
"""Pybind tests for ahead-of-time cpp extensions
These tests verify the types returned from cpp code using custom type
casters. By exercising pybind, we also verify that the type casters work
properly.
For each type caster in `torch/csrc/utils/pybind.h` we create a pyb... | TestPybindTypeCasters |
python | allegroai__clearml | clearml/backend_api/session/jsonmodels/fields.py | {
"start": 10392,
"end": 11817
} | class ____(object):
def __init__(self, path: str) -> None:
self.path = path
def evaluate(self, base_cls: type) -> type:
module, type_name = _evaluate_path(self.path, base_cls)
return _import(module, type_name)
def _evaluate_path(relative_path: str, base_cls: type) -> Tuple[str, str]:
... | _LazyType |
python | openai__openai-python | src/openai/types/beta/chatkit/chatkit_thread_item_list.py | {
"start": 2702,
"end": 3538
} | class ____(BaseModel):
id: str
"""Identifier of the thread item."""
created_at: int
"""Unix timestamp (in seconds) for when the item was created."""
object: Literal["chatkit.thread_item"]
"""Type discriminator that is always `chatkit.thread_item`."""
tasks: List[DataChatKitTaskGroupTask]
... | DataChatKitTaskGroup |
python | scikit-learn__scikit-learn | sklearn/metrics/_plot/det_curve.py | {
"start": 281,
"end": 13298
} | class ____(_BinaryClassifierCurveDisplayMixin):
"""Detection Error Tradeoff (DET) curve visualization.
It is recommended to use :func:`~sklearn.metrics.DetCurveDisplay.from_estimator`
or :func:`~sklearn.metrics.DetCurveDisplay.from_predictions` to create a
visualizer. All parameters are stored as attri... | DetCurveDisplay |
python | SmileyChris__easy-thumbnails | easy_thumbnails/alias.py | {
"start": 44,
"end": 4000
} | class ____:
"""
A container which stores and retrieves named easy-thumbnail options
dictionaries.
"""
def __init__(self, populate_from_settings=True):
"""
Initialize the Aliases object.
:param populate_from_settings: If ``True`` (default) then populate the
initi... | Aliases |
python | openai__openai-python | src/openai/_extras/_common.py | {
"start": 312,
"end": 364
} | class ____(OpenAIError):
pass
| MissingDependencyError |
python | astropy__astropy | astropy/visualization/lupton_rgb.py | {
"start": 11805,
"end": 14582
} | class ____(BaseStretch):
r"""
A modified asinh stretch, with some changes to the constants
relative to `~astropy.visualization.AsinhStretch`.
The stretch is given by:
.. math::
& y = {\rm asinh}\left(\frac{Q * x}{stretch}\right) *
\frac{frac}{{\rm asinh}(frac * Q)} \\
& fra... | LuptonAsinhStretch |
python | huggingface__transformers | src/transformers/models/idefics3/image_processing_idefics3_fast.py | {
"start": 5690,
"end": 22643
} | class ____(BaseImageProcessorFast):
resample = PILImageResampling.LANCZOS
image_mean = IMAGENET_STANDARD_MEAN
image_std = IMAGENET_STANDARD_STD
size = {"longest_edge": 4 * 364}
max_image_size = {"longest_edge": 364}
do_resize = True
do_rescale = True
do_normalize = True
do_convert_rg... | Idefics3ImageProcessorFast |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/classGetItem1.py | {
"start": 456,
"end": 754
} | class ____(Generic[_T, _S]):
# Even though this class has a __class_getitem__ method,
# it will be assumed to follow normal generic class semantics.
def __class_getitem__(cls, args: tuple[int, ...]) -> None: ...
reveal_type(ClassB[int, str], expected_text="type[ClassB[int, str]]")
| ClassB |
python | sympy__sympy | sympy/physics/biomechanics/tests/test_curve.py | {
"start": 11136,
"end": 19043
} | class ____:
@pytest.fixture(autouse=True)
def _tendon_force_length_inverse_arguments_fixture(self):
self.fl_T = Symbol('fl_T')
self.c0 = Symbol('c_0')
self.c1 = Symbol('c_1')
self.c2 = Symbol('c_2')
self.c3 = Symbol('c_3')
self.constants = (self.c0, self.c1, self... | TestTendonForceLengthInverseDeGroote2016 |
python | pypa__pip | src/pip/_vendor/rich/progress.py | {
"start": 31745,
"end": 32176
} | class ____(ProgressColumn):
"""Renders human readable transfer speed."""
def render(self, task: "Task") -> Text:
"""Show data transfer speed."""
speed = task.finished_speed or task.speed
if speed is None:
return Text("?", style="progress.data.speed")
data_speed = fil... | TransferSpeedColumn |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-file/llama_index/readers/file/rtf/base.py | {
"start": 216,
"end": 1093
} | class ____(BaseReader):
"""RTF (Rich Text Format) Reader. Reads rtf file and convert to Document."""
def load_data(
self,
input_file: Union[Path, str],
extra_info: Optional[Dict[str, Any]] = None,
**load_kwargs: Any,
) -> List[Document]:
"""
Load data from RT... | RTFReader |
python | getsentry__sentry | src/sentry/interfaces/contexts.py | {
"start": 6978,
"end": 7081
} | class ____(ContextType):
type = "trace"
context_to_tag_mapping = {}
@contexttype
| TraceContextType |
python | huggingface__transformers | tests/models/dinov2/test_modeling_dinov2.py | {
"start": 10819,
"end": 11907
} | class ____(unittest.TestCase):
@cached_property
def default_image_processor(self):
return AutoImageProcessor.from_pretrained("facebook/dinov2-base") if is_vision_available() else None
@slow
def test_inference_no_head(self):
model = Dinov2Model.from_pretrained("facebook/dinov2-base").to(... | Dinov2ModelIntegrationTest |
python | lazyprogrammer__machine_learning_examples | svm_class/fake_neural_net.py | {
"start": 808,
"end": 4151
} | class ____:
def __init__(self, gamma=1.0, n_components=100, method='random'):
self.M = n_components
self.gamma = gamma
assert(method in ('normal', 'random', 'kmeans', 'gmm'))
self.method = method
def _subsample_data(self, X, Y, n=10000):
if Y is not None:
X, Y = shuffle(X, Y)
return... | SigmoidFeaturizer |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/math_ops/reduction_ops_test.py | {
"start": 7703,
"end": 18107
} | class ____(BaseReductionTest):
def _tf_reduce(self, x, reduction_axes, keepdims):
return math_ops.reduce_sum(x, reduction_axes, keepdims)
def _np_reduce(self, x, reduction_axes, keepdims):
if isinstance(reduction_axes, list) or isinstance(reduction_axes,
... | SumReductionTest |
python | PyCQA__pylint | tests/functional/u/undefined/undefined_variable_py30.py | {
"start": 1718,
"end": 1799
} | class ____(metaclass=ABCMet): # [undefined-variable]
""" Notice the typo """
| Bad |
python | tiangolo__fastapi | scripts/sponsors.py | {
"start": 1460,
"end": 1528
} | class ____(BaseModel):
data: SponsorsResponseData
| SponsorsResponse |
python | google__pytype | pytype/errors/error_printer.py | {
"start": 9435,
"end": 10024
} | class ____:
"""Pretty printer for attribute errors."""
def __init__(self, pp: pretty_printer_base.PrettyPrinterBase):
self._pp = pp
def print_receiver(self, obj: types.BaseValue, attr_name: str):
if attr_name in slots.SYMBOL_MAPPING:
obj_repr = self._pp.print_type(obj)
return BadAttr(obj_rep... | AttributeErrorPrinter |
python | huggingface__transformers | tests/models/qwen2_audio/test_modeling_qwen2_audio.py | {
"start": 8037,
"end": 16271
} | class ____(unittest.TestCase):
def setUp(self):
cleanup(torch_device, gc_collect=True)
self.processor = AutoProcessor.from_pretrained("Qwen/Qwen2-Audio-7B-Instruct")
def tearDown(self):
cleanup(torch_device, gc_collect=True)
@slow
def test_small_model_integration_test_single(se... | Qwen2AudioForConditionalGenerationIntegrationTest |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_table12.py | {
"start": 315,
"end": 999
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("table12.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with tables."""
workbook = Workbook(se... | TestCompareXLSXFiles |
python | scipy__scipy | scipy/sparse/linalg/tests/test_matfuncs.py | {
"start": 2496,
"end": 21072
} | class ____:
def test_zero_ndarray(self):
a = array([[0.,0],[0,0]])
assert_array_almost_equal(expm(a),[[1,0],[0,1]])
def test_zero_sparse(self):
a = csc_array([[0.,0],[0,0]])
assert_array_almost_equal(expm(a).toarray(),[[1,0],[0,1]])
def test_zero_matrix(self):
a = m... | TestExpM |
python | getsentry__sentry | src/sentry/integrations/slack/utils/rule_status.py | {
"start": 310,
"end": 1904
} | class ____:
def __init__(self, uuid: str | None = None) -> None:
self._uuid = uuid or self._generate_uuid()
cluster_id = getattr(settings, "SENTRY_RULE_TASK_REDIS_CLUSTER", "default")
self.client = redis_clusters.get(cluster_id)
self._set_initial_value()
@property
def uuid(... | RedisRuleStatus |
python | pypa__pip | src/pip/_vendor/pygments/scanner.py | {
"start": 535,
"end": 669
} | class ____(RuntimeError):
"""
Raise if end of text is reached and the user
tried to call a match function.
"""
| EndOfText |
python | jazzband__django-simple-history | simple_history/models.py | {
"start": 2365,
"end": 32624
} | class ____:
DEFAULT_MODEL_NAME_PREFIX = "Historical"
thread = context = LocalContext() # retain thread for backwards compatibility
m2m_models = {}
def __init__(
self,
verbose_name=None,
verbose_name_plural=None,
bases=(models.Model,),
user_related_name="+",
... | HistoricalRecords |
python | apache__airflow | airflow-core/tests/unit/serialization/test_dag_serialization.py | {
"start": 17093,
"end": 155758
} | class ____:
"""Unit tests for stringified DAGs."""
@pytest.fixture(autouse=True)
def setup_test_cases(self):
with mock.patch.object(BaseHook, "get_connection") as m:
m.return_value = Connection(
extra=(
"{"
'"project_id": "mock", '... | TestStringifiedDAGs |
python | scipy__scipy | scipy/linalg/tests/test_basic.py | {
"start": 7541,
"end": 18532
} | class ____:
def test_01_upper(self):
# Solve
# [ 4 1 2 0] [1]
# [ 1 4 1 2] X = [4]
# [ 2 1 4 1] [1]
# [ 0 2 1 4] [2]
# with the RHS as a 1D array.
ab = array([[0.0, 0.0, 2.0, 2.0],
[-99, 1.0, 1.0, 1.0],
[4.0... | TestSolveHBanded |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_gcs.py | {
"start": 2599,
"end": 5114
} | class ____:
def test_parse_gcs_url(self):
"""
Test GCS url parsing
"""
assert gcs._parse_gcs_url("gs://bucket/path/to/blob") == ("bucket", "path/to/blob")
# invalid URI
with pytest.raises(AirflowException):
gcs._parse_gcs_url("gs:/bucket/path/to/blob")
... | TestGCSHookHelperFunctions |
python | kamyu104__LeetCode-Solutions | Python/maximize-palindrome-length-from-subsequences.py | {
"start": 45,
"end": 751
} | class ____(object):
def longestPalindrome(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
s = word1+word2
dp = [[0]*len(s) for _ in xrange(len(s))]
result = 0
for j in xrange(len(s)):
dp[j][j] = 1
... | Solution |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/consts.py | {
"start": 82,
"end": 1677
} | class ____(str, Enum):
"""
An enum for the different step ids of the connector test pipeline.
"""
ACCEPTANCE = "acceptance"
INCREMENTAL_ACCEPTANCE = "incremental_acceptance"
BUILD_NORMALIZATION = "build_normalization"
BUILD_TAR = "build_tar"
BUILD = "build"
INTEGRATION = "integratio... | CONNECTOR_TEST_STEP_ID |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 199840,
"end": 203011
} | class ____(TestCase):
def test_basic(self):
zen = [
'Beautiful is better than ugly',
'Explicit is better than implicit',
'Simple is better than complex',
'Complex is better than complicated',
'Flat is better than nested',
'Sparse is bet... | ConstrainedBatchesTests |
python | facebookresearch__faiss | tests/test_fast_scan.py | {
"start": 19353,
"end": 21417
} | class ____(unittest.TestCase):
def subtest_accuracy(self, paq):
"""
Compare IndexPAQFastScan with IndexPAQ (qint8)
"""
d = 16
ds = datasets.SyntheticDataset(d, 1000, 1000, 500)
gt = ds.get_groundtruth(k=1)
index = faiss.index_factory(d, f'{paq}2x3x4_Nqint8')... | TestPAQFastScan |
python | openai__openai-python | src/openai/_types.py | {
"start": 6252,
"end": 7364
} | class ____(TypedDict, total=False):
auth: httpx.Auth
follow_redirects: bool
_T_co = TypeVar("_T_co", covariant=True)
if TYPE_CHECKING:
# This works because str.__contains__ does not accept object (either in typeshed or at runtime)
# https://github.com/hauntsaninja/useful_types/blob/5e9710f3875107d06... | HttpxSendArgs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.