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 | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1031723,
"end": 1032197
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of UpdateIssueComment"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "issue_comment")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing t... | UpdateIssueCommentPayload |
python | mitmproxy__pdoc | pdoc/doc.py | {
"start": 45221,
"end": 50372
} | class ____(inspect.Signature):
"""
A subclass of `inspect.Signature` that pads __str__ over several lines
for complex signatures.
"""
MULTILINE_CUTOFF = 70
def _params(self) -> list[str]:
# redeclared here to keep code snipped below as-is.
_POSITIONAL_ONLY = inspect.Parameter.P... | _PrettySignature |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_views.py | {
"start": 7585,
"end": 10919
} | class ____(TestCase):
"""Tests for search analytics page."""
fixtures = ["eric", "test_data", "test_search_queries"]
def setUp(self):
self.client.login(username="eric", password="test")
self.pip = Project.objects.get(slug="pip")
self.version = self.pip.versions.order_by("id").firs... | TestSearchAnalyticsView |
python | django__django | tests/fixtures_model_package/tests.py | {
"start": 654,
"end": 2148
} | class ____(TestCase):
def test_loaddata(self):
"Fixtures can load data into models defined in packages"
# Load fixture 1. Single JSON file, with two objects
management.call_command("loaddata", "model_package_fixture1.json", verbosity=0)
self.assertQuerySetEqual(
Article.o... | FixtureTestCase |
python | scikit-learn__scikit-learn | sklearn/tests/metadata_routing_common.py | {
"start": 11436,
"end": 11833
} | class ____(ConsumingClassifier):
"""ConsumingClassifier without a predict_log_proba method, but with predict_proba.
Used to mimic dynamic method selection such as in
`BaggingClassifier.predict_log_proba()`.
"""
@property
def predict_log_proba(self):
raise AttributeError("This estimator... | ConsumingClassifierWithoutPredictLogProba |
python | tensorflow__tensorflow | tensorflow/python/compiler/tensorrt/test/topk_test.py | {
"start": 1066,
"end": 1778
} | class ____(trt_test.TfTrtIntegrationTestBase):
"""Testing Top-K in TF-TRT conversion."""
def GraphFn(self, x):
k = 5
k_tensor = constant_op.constant(k, dtype=dtypes.int32, name="Const")
values, indices = nn_ops.top_k(x, k_tensor, name="TopK")
values = array_ops.identity(values, name="output_0")
... | TopKTest |
python | facebook__pyre-check | client/language_server/protocol.py | {
"start": 9460,
"end": 9729
} | class ____(json_mixins.CamlCaseAndExcludeJsonMixin):
synchronization: Optional[TextDocumentSyncClientCapabilities] = None
publish_diagnostics: Optional[PublishDiagnosticsClientCapabilities] = None
@dataclasses.dataclass(frozen=True)
| TextDocumentClientCapabilities |
python | pytorch__pytorch | .github/scripts/filter_test_configs.py | {
"start": 1625,
"end": 23203
} | class ____(Enum):
DISABLED = "disabled"
UNSTABLE = "unstable"
def parse_args() -> Any:
from argparse import ArgumentParser
parser = ArgumentParser(
"Filter all test configurations and keep only requested ones"
)
parser.add_argument(
"--test-matrix", type=str, required=True, he... | IssueType |
python | walkccc__LeetCode | solutions/3341. Find Minimum Time to Reach Last Room I/3341.py | {
"start": 0,
"end": 971
} | class ____:
def minTimeToReach(self, moveTime: list[list[int]]) -> int:
return self._dijkstra(moveTime,
(0, 0), (len(moveTime) - 1, len(moveTime[0]) - 1))
def _dijkstra(
self,
moveTime: list[list[int]],
src: tuple[int, int],
dst: tuple[int, int]
) -> int:
... | Solution |
python | pypa__pip | src/pip/_internal/exceptions.py | {
"start": 9504,
"end": 9614
} | class ____(PipError):
"""Raised when there's a previous conflicting build directory"""
| PreviousBuildDirError |
python | tornadoweb__tornado | tornado/test/httpclient_test.py | {
"start": 29644,
"end": 30791
} | class ____(unittest.TestCase):
def test_request_set(self):
proxy = _RequestProxy(
HTTPRequest("http://example.com/", user_agent="foo"), dict()
)
self.assertEqual(proxy.user_agent, "foo")
def test_default_set(self):
proxy = _RequestProxy(
HTTPRequest("http... | RequestProxyTest |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_textbox03.py | {
"start": 315,
"end": 997
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("textbox03.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with textbox(s)."""
workbook = Workb... | TestCompareXLSXFiles |
python | networkx__networkx | networkx/generators/degree_seq.py | {
"start": 25991,
"end": 30491
} | class ____:
# class to generate random graphs with a given degree sequence
# use random_degree_sequence_graph()
def __init__(self, degree, rng):
self.rng = rng
self.degree = list(degree)
if not nx.is_graphical(self.degree):
raise nx.NetworkXUnfeasible("degree sequence is ... | DegreeSequenceRandomGraph |
python | getsentry__sentry | src/sentry/attachments/default.py | {
"start": 80,
"end": 217
} | class ____(BaseAttachmentCache):
def __init__(self, **options):
super().__init__(default_cache, **options)
| DefaultAttachmentCache |
python | openai__openai-python | src/openai/types/beta/thread.py | {
"start": 332,
"end": 633
} | class ____(BaseModel):
file_ids: Optional[List[str]] = None
"""
A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made
available to the `code_interpreter` tool. There can be a maximum of 20 files
associated with the tool.
"""
| ToolResourcesCodeInterpreter |
python | sqlalchemy__sqlalchemy | test/sql/test_metadata.py | {
"start": 102012,
"end": 114083
} | class ____(testing.AssertsCompiledSQL, fixtures.TablesTest):
@classmethod
def define_tables(cls, metadata):
Table(
"users",
metadata,
Column("id", Integer, primary_key=True),
Column("name", String(30)),
)
@testing.fixture
def existing_meta... | UseExistingTest |
python | jazzband__django-oauth-toolkit | tests/test_token_revocation.py | {
"start": 1239,
"end": 7586
} | class ____(BaseTest):
def test_revoke_access_token(self):
tok = AccessToken.objects.create(
user=self.test_user,
token="1234567890",
application=self.application,
expires=timezone.now() + datetime.timedelta(days=1),
scope="read write",
)
... | TestRevocationView |
python | euske__pdfminer | pdfminer/pdfdocument.py | {
"start": 8398,
"end": 12552
} | class ____:
PASSWORD_PADDING = (b'(\xbfN^Nu\x8aAd\x00NV\xff\xfa\x01\x08'
b'..\x00\xb6\xd0h>\x80/\x0c\xa9\xfedSiz')
supported_revisions = (2, 3)
def __init__(self, docid, param, password=b''):
self.docid = docid
self.param = param
self.password = password
... | PDFStandardSecurityHandler |
python | MongoEngine__mongoengine | mongoengine/queryset/visitor.py | {
"start": 2505,
"end": 3502
} | class ____:
"""Base class for nodes in query trees."""
AND = 0
OR = 1
def to_query(self, document):
query = self.accept(SimplificationVisitor())
query = query.accept(QueryCompilerVisitor(document))
return query
def accept(self, visitor):
raise NotImplementedError
... | QNode |
python | tiangolo__fastapi | docs_src/schema_extra_example/tutorial005_py310.py | {
"start": 84,
"end": 1348
} | class ____(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
@app.put("/items/{item_id}")
async def update_item(
*,
item_id: int,
item: Item = Body(
openapi_examples={
"normal": {
"summary": "A normal example",
... | Item |
python | Pylons__pyramid | src/pyramid/config/predicates.py | {
"start": 1699,
"end": 2704
} | class ____:
"""
You can invert the meaning of any predicate value by wrapping it in a call
to :class:`pyramid.config.not_`.
.. code-block:: python
:linenos:
from pyramid.config import not_
config.add_view(
'mypackage.views.my_view',
route_name='ok',
... | not_ |
python | Textualize__textual | docs/examples/tutorial/stopwatch04.py | {
"start": 883,
"end": 1521
} | class ____(App):
"""A Textual app to manage stopwatches."""
CSS_PATH = "stopwatch04.tcss"
BINDINGS = [("d", "toggle_dark", "Toggle dark mode")]
def compose(self) -> ComposeResult:
"""Create child widgets for the app."""
yield Header()
yield Footer()
yield VerticalScroll... | StopwatchApp |
python | realpython__materials | django-view-auth/Blog/core/models.py | {
"start": 31,
"end": 134
} | class ____(models.Model):
title = models.CharField(max_length=50)
content = models.TextField()
| Blog |
python | scipy__scipy | scipy/spatial/tests/test_kdtree.py | {
"start": 12673,
"end": 12814
} | class ____(_Test_random_ball):
def setup_method(self):
super().setup_method()
self.d = 2.
@KDTreeTest
| _Test_random_ball_far |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP044.py | {
"start": 126,
"end": 545
} | class ____(Generic[Unpack[Shape]]):
pass
def f(*args: Unpack[tuple[int, ...]]):
pass
def f(*args: Unpack[other.Type]):
pass
def f(*args: Generic[int, Unpack[int]]):
pass
# Valid syntax, but can't be unpacked.
def f(*args: Unpack[int | str]) -> None:
pass
def f(*args: Unpack[int and str]) -... | D |
python | docker__docker-py | tests/unit/models_resources_test.py | {
"start": 105,
"end": 873
} | class ____(unittest.TestCase):
def test_reload(self):
client = make_fake_client()
container = client.containers.get(FAKE_CONTAINER_ID)
container.attrs['Name'] = "oldname"
container.reload()
assert client.api.inspect_container.call_count == 2
assert container.attrs['Na... | ModelTest |
python | pypa__pipenv | pipenv/patched/pip/_vendor/distlib/locators.py | {
"start": 17308,
"end": 20110
} | class ____(Locator):
"""
This locator uses PyPI's JSON interface. It's very limited in functionality
and probably not worth using.
"""
def __init__(self, url, **kwargs):
super(PyPIJSONLocator, self).__init__(**kwargs)
self.base_url = ensure_slash(url)
def get_distribution_names... | PyPIJSONLocator |
python | realpython__materials | python-sqlite-sqlalchemy/project/examples/example_3/config.py | {
"start": 251,
"end": 712
} | class ____:
base_path = Path(__file__).resolve().parent.parent.parent
db_path = base_path / "data" / "chinook.db"
SECRET_KEY = os.getenv("SECRET_KEY")
SQLALCHEMY_DATABASE_URI = f"sqlite:///{str(db_path)}"
SQLALCHEMY_TRACK_MODIFICATIONS = json.loads(
os.getenv("SQLALCHEMY_TRACK_MODIFICATIONS... | Config |
python | google__jax | jax/_src/custom_partitioning.py | {
"start": 9247,
"end": 28452
} | class ____:
"""Inserts a CustomCallOp into the XLA graph with custom SPMD lowering rules.
.. code-block:: python
@custom_partitioning
def f(*args):
return ...
def propagate_user_sharding(mesh, user_shape):
'''Update the sharding of the op from a user's shape.sharding.'''
user_shardi... | custom_partitioning |
python | ray-project__ray | release/nightly_tests/multimodal_inference_benchmarks/video_object_detection/daft_main.py | {
"start": 922,
"end": 2202
} | class ____:
def __init__(self):
self.model = YOLO(YOLO_MODEL)
if torch.cuda.is_available():
self.model.to("cuda")
def to_features(self, res):
return [
{
"label": label,
"confidence": confidence.item(),
"bbox": bbox.... | ExtractImageFeatures |
python | pytorch__pytorch | test/distributed/launcher/launch_test.py | {
"start": 651,
"end": 2892
} | class ____(unittest.TestCase):
def setUp(self):
self.test_dir = tempfile.mkdtemp()
# set a sentinel env var on the parent proc
# this should be present on the child and gets
# asserted in ``bin/test_script.py``
os.environ["TEST_SENTINEL_PARENT"] = "FOOBAR"
def tearDown(s... | LaunchTest |
python | sympy__sympy | sympy/physics/biomechanics/activation.py | {
"start": 7011,
"end": 14269
} | class ____(ActivationBase):
"""Simple zeroth-order activation dynamics mapping excitation to
activation.
Explanation
===========
Zeroth-order activation dynamics are useful in instances where you want to
reduce the complexity of your musculotendon dynamics as they simple map
exictation to ... | ZerothOrderActivation |
python | apache__airflow | providers/openlineage/src/airflow/providers/openlineage/utils/utils.py | {
"start": 29744,
"end": 30340
} | class ____(InfoJsonEncodable):
"""Defines encoding TaskInstance object to JSON."""
includes = ["duration", "try_number", "pool", "queued_dttm", "log_url"]
casts = {
"log_url": lambda ti: getattr(ti, "log_url", None),
"map_index": lambda ti: ti.map_index if getattr(ti, "map_index", -1) != -1... | TaskInstanceInfo |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/elements.py | {
"start": 120031,
"end": 120717
} | class ____(ColumnElement[int]):
"""Represent a SQL EXTRACT clause, ``extract(field FROM expr)``."""
__visit_name__ = "extract"
_traverse_internals: _TraverseInternalsType = [
("expr", InternalTraversal.dp_clauseelement),
("field", InternalTraversal.dp_string),
]
expr: ColumnElemen... | Extract |
python | walkccc__LeetCode | solutions/1040. Moving Stones Until Consecutive II/1040.py | {
"start": 0,
"end": 521
} | class ____:
def numMovesStonesII(self, stones: list[int]) -> list[int]:
n = len(stones)
minMoves = n
stones.sort()
l = 0
for r, stone in enumerate(stones):
while stone - stones[l] + 1 > n:
l += 1
alreadyStored = r - l + 1
if alreadyStored == n - 1 and stone - stones[l] ... | Solution |
python | sympy__sympy | sympy/codegen/fnodes.py | {
"start": 17784,
"end": 18205
} | class ____(Function):
_required_standard = 77
def _fcode(self, printer):
name = self.__class__.__name__
if printer._settings['standard'] < self._required_standard:
raise NotImplementedError("%s requires Fortran %d or newer" %
(name, self._requir... | FFunction |
python | paramiko__paramiko | demos/forward.py | {
"start": 1394,
"end": 1507
} | class ____(SocketServer.ThreadingTCPServer):
daemon_threads = True
allow_reuse_address = True
| ForwardServer |
python | tqdm__tqdm | tqdm/contrib/telegram.py | {
"start": 544,
"end": 2815
} | class ____(MonoWorker):
"""Non-blocking file-like IO using a Telegram Bot."""
API = 'https://api.telegram.org/bot'
def __init__(self, token, chat_id):
"""Creates a new message in the given `chat_id`."""
super().__init__()
self.token = token
self.chat_id = chat_id
sel... | TelegramIO |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/pipes/utils.py | {
"start": 10154,
"end": 21442
} | class ____(PipesMessageReader):
"""A base class for message readers that read messages and logs in background threads.
Args:
interval (float): The interval in seconds at which to poll for messages.
log_readers (Optional[Sequence[PipesLogReader]]): A set of log readers to use to read logs.
"... | PipesThreadedMessageReader |
python | pydantic__pydantic | tests/test_docs.py | {
"start": 1580,
"end": 10409
} | class ____(datetime):
@classmethod
def now(cls, *args, tz=None, **kwargs):
return datetime(2032, 1, 2, 3, 4, 5, 6, tzinfo=tz)
skip_reason = skip_docs_tests()
LINE_LENGTH = 80
TARGET_VERSION = 'py39'
def print_callback(print_statement: str) -> str:
return re.sub(r'(https://errors.pydantic.dev)/.+... | MockedDatetime |
python | davidhalter__parso | parso/python/tree.py | {
"start": 5846,
"end": 7496
} | class ____(_LeafWithoutNewlines):
"""
A string. Sometimes it is important to know if the string belongs to a name
or not.
"""
type = 'name'
__slots__ = ()
def __repr__(self):
return "<%s: %s@%s,%s>" % (type(self).__name__, self.value,
self.line, se... | Name |
python | getsentry__sentry | src/sentry/analytics/events/first_insight_span_sent.py | {
"start": 80,
"end": 295
} | class ____(analytics.Event):
organization_id: int
user_id: int | None
project_id: int
module: str
platform: str | None = None
analytics.register(FirstInsightSpanSentEvent)
| FirstInsightSpanSentEvent |
python | apache__airflow | airflow-core/src/airflow/models/callback.py | {
"start": 2974,
"end": 3230
} | class ____(ImportPathCallbackDefProtocol, Protocol):
"""Protocol for callbacks that use the import path fetch method and have an executor attribute to specify the executor to run them on."""
executor: str | None
| ImportPathExecutorCallbackDefProtocol |
python | getsentry__sentry | src/sentry/integrations/api/endpoints/organization_integration_channels.py | {
"start": 6135,
"end": 7724
} | class ____(OrganizationIntegrationBaseEndpoint):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
owner = ApiOwner.TELEMETRY_EXPERIENCE
def get(
self,
request: Request,
organization_context: RpcUserOrganizationContext,
integration_id: int,
**kwargs: ... | OrganizationIntegrationChannelsEndpoint |
python | django__django | tests/generic_views/views.py | {
"start": 6900,
"end": 7029
} | class ____(generic.detail.SingleObjectMixin, generic.View):
model = Book
object = Book(name="dummy")
| CustomSingleObjectView |
python | milvus-io__pymilvus | pymilvus/milvus_client/index.py | {
"start": 2086,
"end": 2448
} | class ____(list):
"""List of indexs of a collection"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def add_index(self, field_name: str, index_type: str = "", index_name: str = "", **kwargs):
index_param = IndexParam(field_name, index_type, index_name, **kwargs)
... | IndexParams |
python | numpy__numpy | numpy/distutils/_shell_utils.py | {
"start": 812,
"end": 2130
} | class ____:
"""
The parsing behavior used by `subprocess.call("string")` on Windows, which
matches the Microsoft C/C++ runtime.
Note that this is _not_ the behavior of cmd.
"""
@staticmethod
def join(argv):
# note that list2cmdline is specific to the windows syntax
return su... | WindowsParser |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py | {
"start": 5487,
"end": 5576
} | class ____(IncrementalShopifyStream):
data_field = "smart_collections"
| SmartCollections |
python | Delgan__loguru | tests/test_pickling.py | {
"start": 1009,
"end": 10653
} | class ____(logging.Handler):
def __init__(self, level):
super().__init__(level)
self.written = ""
def emit(self, record):
self.written += record.getMessage()
def acquire(self):
pass
def release(self):
pass
def createLock(self): # noqa: N802
self.l... | StandardHandler |
python | ray-project__ray | python/ray/air/execution/_internal/tracked_actor_task.py | {
"start": 113,
"end": 1261
} | class ____:
"""Actor task tracked by a Ray event manager.
This container class is used to define callbacks to be invoked when
the task resolves, errors, or times out.
Note:
Objects of this class are returned by the :class:`RayActorManager`.
This class should not be instantiated manuall... | TrackedActorTask |
python | pytorch__pytorch | test/test_mps.py | {
"start": 360432,
"end": 362029
} | class ____(TestCaseMPS):
@serialTest()
def test_64bit_binops(self):
if torch.mps.recommended_max_memory() < 16_000_000_000:
raise unittest.SkipTest("Needs at least 16Gb of RAM")
a = torch.rand(1, 1024, 1024, dtype=torch.float16, device='mps')
b = torch.rand(5000, 1, 1, dtype=... | TestLargeTensors |
python | astropy__astropy | astropy/visualization/wcsaxes/frame.py | {
"start": 11324,
"end": 13052
} | class ____(BaseFrame):
"""
An elliptical frame.
"""
spine_names = "chv"
_spine_auto_position_order = "chv"
def update_spines(self):
xmin, xmax = self.parent_axes.get_xlim()
ymin, ymax = self.parent_axes.get_ylim()
xmid = 0.5 * (xmax + xmin)
ymid = 0.5 * (ymax +... | EllipticalFrame |
python | apache__airflow | providers/google/src/airflow/providers/google/marketing_platform/hooks/campaign_manager.py | {
"start": 1195,
"end": 11578
} | class ____(GoogleBaseHook):
"""Hook for Google Campaign Manager."""
_conn: Resource | None = None
def __init__(
self,
api_version: str = "v4",
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
) -> None:
super()._... | GoogleCampaignManagerHook |
python | mlflow__mlflow | mlflow/entities/span.py | {
"start": 18480,
"end": 30525
} | class ____(Span):
"""
A "live" version of the :py:class:`Span <mlflow.entities.Span>` class.
The live spans are those being created and updated during the application runtime.
When users start a new span using the tracing APIs within their code, this live span
object is returned to get and set the ... | LiveSpan |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/type_api.py | {
"start": 2409,
"end": 2618
} | class ____(Enum):
NO_VALUE_IN_LIST = 0
"""indicates we are trying to determine the type of an expression
against an empty list."""
_NO_VALUE_IN_LIST = _NoValueInList.NO_VALUE_IN_LIST
| _NoValueInList |
python | openai__openai-python | src/openai/resources/embeddings.py | {
"start": 11651,
"end": 11902
} | class ____:
def __init__(self, embeddings: AsyncEmbeddings) -> None:
self._embeddings = embeddings
self.create = _legacy_response.async_to_raw_response_wrapper(
embeddings.create,
)
| AsyncEmbeddingsWithRawResponse |
python | ansible__ansible | test/integration/targets/error_from_connection/connection_plugins/dummy.py | {
"start": 356,
"end": 918
} | class ____(ConnectionBase):
transport = 'dummy'
has_pipelining = True
def __init__(self, play_context, new_stdin, *args, **kwargs):
super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs)
raise AnsibleError('an error with {{ some Jinja }}')
def _connect(self):
... | Connection |
python | skorch-dev__skorch | skorch/tests/test_probabilistic.py | {
"start": 4684,
"end": 18060
} | class ____:
"""Base class for all GP estimators.
This class defined all fixtures, most of which need to be implemented by the
respective subclass, as well as all the tests. The tests take care of using
attributes and properties that are true for all sorts of GPs (e.g. only
using parameters shared b... | BaseProbabilisticTests |
python | jmcnamara__XlsxWriter | xlsxwriter/test/workbook/test_custom_sheet.py | {
"start": 363,
"end": 404
} | class ____(Worksheet):
pass
| MyWorksheet |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_pretty.py | {
"start": 4853,
"end": 5002
} | class ____(dict):
def __repr__(self):
return "hi"
def test_dict_with_custom_repr():
assert pretty.pretty(ReprDict()) == "hi"
| ReprDict |
python | google__jax | tests/debugging_primitives_test.py | {
"start": 28133,
"end": 35738
} | class ____(jtu.JaxTestCase):
def _create_devices(self, shape):
num_devices = np.prod(shape)
devices = [DummyDevice("CPU", i) for i in range(num_devices)]
return np.array(devices).reshape(shape)
def test_trivial_sharding(self):
mesh = jax.sharding.Mesh(self._create_devices(1), ['x'])
pspec = ja... | VisualizeShardingTest |
python | huggingface__transformers | src/transformers/models/flaubert/modeling_flaubert.py | {
"start": 2906,
"end": 6623
} | class ____(nn.Module):
def __init__(self, n_heads, dim, config, layer_idx: int = 0):
super().__init__()
self.layer_id = layer_idx
self.dim = dim
self.n_heads = n_heads
self.head_dim = dim // n_heads
self.dropout = config.attention_dropout
assert self.dim % sel... | MultiHeadAttention |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyflakes/F821_19.py | {
"start": 170,
"end": 427
} | class ____:
# OK: Allow list comprehensions in annotations (i.e., treat `qux` as a valid
# load in the scope of the annotation).
baz: Annotated[
str,
[qux for qux in foo],
]
# Error: `y` is not defined.
x: (y := 1)
print(y)
| Bar |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 118040,
"end": 118191
} | class ____:
xlStandardSummary = 1 # from enum XlSummaryReportType
xlSummaryPivotTable = -4148 # from enum XlSummaryReportType
| SummaryReportType |
python | jazzband__django-oauth-toolkit | oauth2_provider/models.py | {
"start": 2184,
"end": 11067
} | class ____(models.Model):
"""
An Application instance represents a Client on the Authorization server.
Usually an Application is created manually by client's developers after
logging in on an Authorization Server.
Fields:
* :attr:`client_id` The client identifier issued to the client during th... | AbstractApplication |
python | Textualize__textual | docs/examples/how-to/layout04.py | {
"start": 402,
"end": 580
} | class ____(Screen):
def compose(self) -> ComposeResult:
yield Header(id="Header")
yield Footer(id="Footer")
yield HorizontalScroll() # (1)!
| TweetScreen |
python | python__mypy | mypy/nodes.py | {
"start": 99430,
"end": 100165
} | class ____(Expression):
"""NewType expression NewType(...)."""
__slots__ = ("name", "old_type", "info")
__match_args__ = ("name", "old_type", "info")
name: str
# The base type (the second argument to NewType)
old_type: mypy.types.Type | None
# The synthesized class representing the new ty... | NewTypeExpr |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/static_analysis/type_inference.py | {
"start": 16435,
"end": 18706
} | class ____(cfg.GraphVisitor):
"""CFG visitor that propagates type information across statements."""
def __init__(self, graph, resolver, namespace, scope, closure_types):
"""Creates a new analyzer.
Args:
graph: cfg.Graph
resolver: Resolver
namespace: Dict[str, Any]
scope: activity.S... | Analyzer |
python | tiangolo__fastapi | tests/test_default_response_class.py | {
"start": 358,
"end": 5365
} | class ____(JSONResponse):
media_type = "application/x-override"
app = FastAPI(default_response_class=ORJSONResponse)
router_a = APIRouter()
router_a_a = APIRouter()
router_a_b_override = APIRouter() # Overrides default class
router_b_override = APIRouter() # Overrides default class
router_b_a = APIRouter()
rout... | OverrideResponse |
python | ray-project__ray | python/ray/autoscaler/v2/tests/test_sdk.py | {
"start": 2919,
"end": 3938
} | class ____:
node_id: str
node_status: NodeStatus
idle_time_check_cb: Optional[Callable] = None
labels: Optional[dict] = None
def assert_node_states(
state: ClusterResourceState, expected_nodes: List[ExpectedNodeState]
):
"""
Assert a GetClusterResourceStateReply has node states that
ma... | ExpectedNodeState |
python | pytest-dev__pytest-asyncio | docs/reference/markers/class_scoped_loop_custom_policies_strict_mode_example.py | {
"start": 334,
"end": 453
} | class ____:
@pytest.mark.asyncio
async def test_parametrized_loop(self):
pass
| TestWithDifferentLoopPolicies |
python | pyca__cryptography | tests/hazmat/primitives/test_ssh.py | {
"start": 26222,
"end": 31537
} | class ____:
def test_load_ssh_public_key_unsupported(self, backend):
ssh_key = b"ecdsa-sha2-junk AAAAE2VjZHNhLXNoYTItbmlzdHAyNTY="
with raises_unsupported_algorithm(None):
load_ssh_public_key(ssh_key, backend)
def test_load_ssh_public_key_bad_format(self, backend):
ssh_key ... | TestRSASSHSerialization |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py | {
"start": 104927,
"end": 105474
} | class ____(nn.Module):
def __init__(self, config: Qwen3OmniMoeTalkerConfig):
super().__init__()
self.linear_fc1 = nn.Linear(config.thinker_hidden_size, config.text_config.intermediate_size, bias=True)
self.linear_fc2 = nn.Linear(config.text_config.intermediate_size, config.text_config.hidden... | Qwen3OmniMoeTalkerResizeMLP |
python | pypa__pip | src/pip/_internal/exceptions.py | {
"start": 5316,
"end": 5399
} | class ____(PipError):
"""General exception in configuration"""
| ConfigurationError |
python | getsentry__sentry | src/sentry/dynamic_sampling/rules/utils.py | {
"start": 3480,
"end": 5947
} | class ____(Rule):
timeRange: TimeRange
decayingFn: NotRequired[DecayingFn] # const decaying doesn't require a decayingFn
# Type defining the all the possible rules types that can exist.
PolymorphicRule = Union[Rule, DecayingRule]
def get_rule_hash(rule: PolymorphicRule) -> int:
# We want to be explicit... | DecayingRule |
python | pytorch__pytorch | torch/backends/quantized/__init__.py | {
"start": 825,
"end": 1047
} | class ____:
def __get__(self, obj, objtype) -> str:
return _get_qengine_str(torch._C._get_qengine())
def __set__(self, obj, val: str) -> None:
torch._C._set_qengine(_get_qengine_id(val))
| _QEngineProp |
python | pytorch__pytorch | test/test_tensorboard.py | {
"start": 10243,
"end": 12899
} | class ____(BaseTestCase):
@unittest.skipIf(
sys.version_info >= (3, 13),
"numpy failure, likely caused by old tensorboard version",
)
def test_writer(self):
with self.createSummaryWriter() as writer:
sample_rate = 44100
n_iter = 0
writer.add_hpara... | TestTensorBoardWriter |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI026.py | {
"start": 459,
"end": 485
} | class ____(Enum): ...
| FooEnum |
python | gevent__gevent | src/greentest/3.14/test_ssl.py | {
"start": 66293,
"end": 68716
} | class ____(unittest.TestCase):
def test_str(self):
# The str() of a SSLError doesn't include the errno
e = ssl.SSLError(1, "foo")
self.assertEqual(str(e), "foo")
self.assertEqual(e.errno, 1)
# Same for a subclass
e = ssl.SSLZeroReturnError(1, "foo")
self.asse... | SSLErrorTests |
python | numba__numba | numba/tests/test_conversion.py | {
"start": 343,
"end": 6900
} | class ____(TestCase):
"""
Testing Python to Native conversion
"""
def test_complex_identity(self):
pyfunc = identity
cfunc = njit(types.complex64(types.complex64))(pyfunc)
xs = [1.0j, (1+1j), (-1-1j), (1+0j)]
for x in xs:
self.assertEqual(cfunc(x), x)
... | TestConversion |
python | pytorch__pytorch | torch/testing/_internal/autograd_function_db.py | {
"start": 3214,
"end": 4850
} | class ____(torch.autograd.Function):
@staticmethod
def forward(x, y):
return torch.tensor(to_numpy(x) * to_numpy(y), device=x.device)
@staticmethod
def setup_context(ctx, inputs, output):
ctx.save_for_backward(*inputs)
ctx.save_for_forward(*inputs)
@staticmethod
def bac... | NumpyMul |
python | nedbat__coveragepy | tests/test_testing.py | {
"start": 1040,
"end": 8326
} | class ____(CoverageTest):
"""Test the methods in `CoverageTest`."""
def test_file_exists(self) -> None:
self.make_file("whoville.txt", "We are here!")
self.assert_exists("whoville.txt")
self.assert_doesnt_exist("shadow.txt")
msg = "File 'whoville.txt' shouldn't exist"
wi... | CoverageTestTest |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 8842,
"end": 8952
} | class ____(ProxyBase):
name = models.CharField(max_length=30)
# base -> proxy -> real models
| NonProxyChild |
python | ray-project__ray | python/ray/autoscaler/v2/instance_manager/node_provider.py | {
"start": 9198,
"end": 18610
} | class ____(ICloudInstanceProvider):
"""
Warps a NodeProviderV1 to a ICloudInstanceProvider.
TODO(rickyx):
The current adapter right now consists of two sets of APIs:
- v1: the old APIs that are used by the autoscaler, where
we forward the calls to the NodeProviderV1.
- v2: the new APIs that... | NodeProviderAdapter |
python | catalyst-team__catalyst | catalyst/core/callback.py | {
"start": 5014,
"end": 5230
} | class ____(Callback):
"""Checkpoint callback interface, abstraction over checkpoint step."""
def __init__(self):
"""Init."""
super().__init__(order=CallbackOrder.Checkpoint)
| ICheckpointCallback |
python | pyca__cryptography | tests/x509/test_x509.py | {
"start": 259851,
"end": 262217
} | class ____:
def test_no_attributes(self):
attrs = x509.Attributes([])
assert len(attrs) == 0
def test_get_attribute_for_oid(self):
attr_list = [
x509.Attribute(
x509.oid.AttributeOID.CHALLENGE_PASSWORD,
b"nonsense",
),
... | TestAttributes |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 103003,
"end": 103768
} | class ____(Structure):
_fields_ = [("count", c_uint),
("sensor", c_nvmlGpuThermalSensor_t * NVML_MAX_THERMAL_SENSORS_PER_GPU)]
_nvmlCoolerControl_t = c_uint
NVML_THERMAL_COOLER_SIGNAL_NONE = 0
NVML_THERMAL_COOLER_SIGNAL_TOGGLE = 1
NVML_THERMAL_COOLER_SIGNAL_VARIABLE = 2
NVML_THERMAL_... | c_nvmlGpuThermalSettings_t |
python | django__django | tests/forms_tests/widget_tests/test_radioselect.py | {
"start": 275,
"end": 16967
} | class ____(ChoiceWidgetTest):
widget = RadioSelect
def test_render(self):
html = """
<div>
<div>
<label><input type="radio" name="beatle" value="">------</label>
</div>
<div>
<label><input checked type="radio" name="beatle" value="J">John</l... | RadioSelectTest |
python | kamyu104__LeetCode-Solutions | Python/score-after-flipping-matrix.py | {
"start": 34,
"end": 412
} | class ____(object):
def matrixScore(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
R, C = len(A), len(A[0])
result = 0
for c in xrange(C):
col = 0
for r in xrange(R):
col += A[r][c] ^ A[r][0]
result +... | Solution |
python | eth-brownie__brownie | brownie/network/multicall.py | {
"start": 925,
"end": 1095
} | class ____(ObjectProxy):
"""A proxy object to be updated with the result of a multicall."""
def __repr__(self) -> str:
return repr(self.__wrapped__)
| Result |
python | great-expectations__great_expectations | great_expectations/render/components.py | {
"start": 2907,
"end": 4559
} | class ____(str, Enum):
"""Available legacy descriptive renderer names"""
COLUMN_PROPERTIES_TABLE_DISTINCT_COUNT_ROW = ".".join(
[
LegacyRendererType.DESCRIPTIVE,
"column_properties_table",
"distinct_count_row",
]
)
COLUMN_PROPERTIES_TABLE_DISTINCT_PER... | LegacyDescriptiveRendererType |
python | kamyu104__LeetCode-Solutions | Python/numbers-with-repeated-digits.py | {
"start": 35,
"end": 1032
} | class ____(object):
def numDupDigitsAtMostN(self, N):
"""
:type N: int
:rtype: int
"""
def P(m, n):
result = 1
for _ in xrange(n):
result *= m
m -= 1
return result
digits = map(int, str(N+1))
... | Solution |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_primitive.py | {
"start": 1562,
"end": 3782
} | class ____:
def test_valid(self) -> None:
prop = bcpp.Bool()
assert prop.is_valid(False)
assert prop.is_valid(True)
assert prop.is_valid(np.bool_(False))
assert prop.is_valid(np.bool_(True))
def test_invalid(self) -> None:
prop = bcpp.Bool()
assert no... | Test_Bool |
python | pyqtgraph__pyqtgraph | pyqtgraph/imageview/ImageViewTemplate_generic.py | {
"start": 341,
"end": 8375
} | class ____(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(726, 588)
self.gridLayout_3 = QtWidgets.QGridLayout(Form)
self.gridLayout_3.setContentsMargins(0, 0, 0, 0)
self.gridLayout_3.setSpacing(0)
self.gridLayout_3.setObjectName("gridLayout_3... | Ui_Form |
python | wandb__wandb | wandb/sdk/data_types/saved_model.py | {
"start": 15574,
"end": 16224
} | class ____(_SavedModel["tensorflow.keras.Model"]):
_log_type = "tfkeras-model-file"
_path_extension = ""
@staticmethod
def _deserialize(
dir_or_file_path: str,
) -> tensorflow.keras.Model:
return _get_tf_keras().models.load_model(dir_or_file_path)
@staticmethod
def _validat... | _TensorflowKerasSavedModel |
python | bokeh__bokeh | src/bokeh/models/graphs.py | {
"start": 4158,
"end": 4514
} | class ____(GraphHitTestPolicy):
'''
With the ``EdgesOnly`` policy, only graph edges are able to be selected and
inspected. There is no selection or inspection of graph nodes.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super... | EdgesOnly |
python | huggingface__transformers | src/transformers/models/hgnet_v2/modeling_hgnet_v2.py | {
"start": 2318,
"end": 3477
} | class ____(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int = 1,
groups: int = 1,
activation: str = "relu",
use_learnable_affine_block: bool = False,
):
super().__init__()
self.convo... | HGNetV2ConvLayer |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/errors.py | {
"start": 15406,
"end": 16092
} | class ____(graphene.ObjectType):
class Meta:
interfaces = (GrapheneError,)
name = "RepositoryNotFoundError"
repository_name = graphene.NonNull(graphene.String)
repository_location_name = graphene.NonNull(graphene.String)
def __init__(self, repository_location_name, repository_name):
... | GrapheneRepositoryNotFoundError |
python | falconry__falcon | falcon/errors.py | {
"start": 4713,
"end": 4983
} | class ____(WebSocketDisconnected):
"""No route could be found for the requested path.
A simulated WebSocket connection was attempted but the path specified in
the handshake request did not match any of the app's routes.
"""
pass
| WebSocketPathNotFound |
python | urllib3__urllib3 | test/test_response.py | {
"start": 53630,
"end": 56196
} | class ____:
def __init__(self, content: list[bytes]) -> None:
"""
content: collection of str, each str is a chunk in response
"""
self.content = content
self.index = 0 # This class iterates over self.content.
self.closed = False
self.cur_chunk = b""
s... | MockChunkedEncodingResponse |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.