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 | pola-rs__polars | py-polars/src/polars/io/csv/batched_reader.py | {
"start": 712,
"end": 5018
} | class ____:
"""Read a CSV file in batches."""
def __init__(
self,
source: str | Path,
*,
has_header: bool = True,
columns: Sequence[int] | Sequence[str] | None = None,
separator: str = ",",
comment_prefix: str | None = None,
quote_char: str | None... | BatchedCsvReader |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py | {
"start": 21015,
"end": 22014
} | class ____(TypeSystemDefinition):
__slots__ = ('loc', 'directives', 'operation_types',)
_fields = ('operation_types',)
def __init__(self, operation_types, loc=None, directives=None):
self.operation_types = operation_types
self.loc = loc
self.directives = directives
def __eq__(s... | SchemaDefinition |
python | ray-project__ray | rllib/utils/exploration/parameter_noise.py | {
"start": 1000,
"end": 17226
} | class ____(Exploration):
"""An exploration that changes a Model's parameters.
Implemented based on:
[1] https://openai.com/research/better-exploration-with-parameter-noise
[2] https://arxiv.org/pdf/1706.01905.pdf
At the beginning of an episode, Gaussian noise is added to all weights
of the mod... | ParameterNoise |
python | kamyu104__LeetCode-Solutions | Python/maximize-active-section-with-trade-ii.py | {
"start": 56,
"end": 2798
} | class ____(object):
def maxActiveSectionsAfterTrade(self, s, queries):
"""
:type s: str
:type queries: List[List[int]]
:rtype: List[int]
"""
# RMQ - Sparse Table
# Template: https://github.com/kamyu104/GoogleCodeJam-Farewell-Rounds/blob/main/Round%20D/genetic_... | Solution |
python | getsentry__sentry | tests/sentry/core/endpoints/test_project_details.py | {
"start": 72228,
"end": 90101
} | class ____(TestProjectDetailsBase):
endpoint = "sentry-api-0-project-details"
def setUp(self) -> None:
super().setUp()
self.new_ds_flag = "organizations:dynamic-sampling"
self.url = reverse(
"sentry-api-0-project-details",
kwargs={
"organization_i... | TestProjectDetailsDynamicSamplingBiases |
python | tensorflow__tensorflow | tensorflow/python/distribute/input_lib_type_spec_test.py | {
"start": 13029,
"end": 20873
} | class ____(test.TestCase, parameterized.TestCase):
@combinations.generate(
combinations.combine(
mode=["eager"],
tf_api_version=2,
distribution=[
strategy_combinations.mirrored_strategy_with_two_gpus,
strategy_combinations.mirrored_strategy_with_cpu_1_a... | DistributedDatasetTypeSpecTest |
python | pydantic__pydantic | tests/typechecking/base_model.py | {
"start": 720,
"end": 1350
} | class ____(BaseModel):
title: str = Field(default='Sir Lancelot') # this is okay
age: int = Field(23) # this works fine at runtime but will case an error for pyright
k = Knight() # type: ignore[call-arg] # pyright: ignore[reportCallIssue]
assert_type(Knight.model_fields, dict[str, FieldInfo])
assert_type... | Knight |
python | altair-viz__altair | tools/generate_schema_wrapper.py | {
"start": 3033,
"end": 6056
} | class ____:
_encoding_name: str
def to_dict(
self,
validate: bool = True,
ignore: list[str] | None = None,
context: dict[str, Any] | None = None,
) -> dict | list[dict]:
context = context or {}
ignore = ignore or []
shorthand = self._get("shorthand") ... | FieldChannelMixin |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/unsat_provider/package.py | {
"start": 216,
"end": 583
} | class ____(Package):
"""This package has a dependency on a virtual that cannot be provided"""
homepage = "http://www.example.com"
url = "http://www.example.com/v1.0.tgz"
version("1.0", sha256="0123456789abcdef0123456789abcdef")
variant("foo", default=True, description="")
provides("unsatvdep... | UnsatProvider |
python | ray-project__ray | doc/source/ray-core/doc_code/ray-dag.py | {
"start": 513,
"end": 3463
} | class ____:
def __init__(self, init_value):
self.i = init_value
def inc(self, x):
self.i += x
def get(self):
return self.i
a1 = Actor.bind(10) # Instantiate Actor with init_value 10.
val = a1.get.bind() # ClassMethod that returns value from get() from
# the ... | Actor |
python | mlflow__mlflow | examples/auth/auth.py | {
"start": 46,
"end": 1878
} | class ____:
MLFLOW_TRACKING_USERNAME = "MLFLOW_TRACKING_USERNAME"
MLFLOW_TRACKING_PASSWORD = "MLFLOW_TRACKING_PASSWORD"
def __init__(self, username, password) -> None:
self.username = username
self.password = password
self.env = {}
def _record_env_var(self, key):
if key... | User |
python | django__django | tests/model_fields/test_uuid.py | {
"start": 479,
"end": 2362
} | class ____(TestCase):
def test_uuid_instance(self):
instance = UUIDModel.objects.create(field=uuid.uuid4())
loaded = UUIDModel.objects.get()
self.assertEqual(loaded.field, instance.field)
def test_str_instance_no_hyphens(self):
UUIDModel.objects.create(field="550e8400e29b41d4a71... | TestSaveLoad |
python | apache__airflow | providers/apache/hive/tests/unit/apache/hive/__init__.py | {
"start": 5551,
"end": 5765
} | class ____:
PIPE = -1
STDOUT = -2
returncode: int | None = None
def __init__(self, *args, **kwargs):
self.stdout = MockStdOut(*args, **kwargs)
def wait(self):
return
| MockSubProcess |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeAlias11.py | {
"start": 200,
"end": 573
} | class ____(Generic[_T]):
def __init__(self, x: _T):
pass
A = ClassA
reveal_type(A(3), expected_text="ClassA[int]")
TA1 = collections.OrderedDict
TA2 = OrderedDict
TA1[int, int]
TA2[int, int]
TA3 = TA1
TA3[int, int]
TA4 = dict | OrderedDict
# This should generate two errors because the two types i... | ClassA |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/connectors/aioodbc.py | {
"start": 3045,
"end": 4331
} | class ____(AsyncAdapt_dbapi_module):
def __init__(self, aioodbc, pyodbc):
super().__init__(aioodbc, dbapi_module=pyodbc)
self.aioodbc = aioodbc
self.pyodbc = pyodbc
self.paramstyle = pyodbc.paramstyle
self._init_dbapi_attributes()
self.Cursor = AsyncAdapt_dbapi_cursor... | AsyncAdapt_aioodbc_dbapi |
python | huggingface__transformers | tests/models/reformer/test_tokenization_reformer.py | {
"start": 301,
"end": 2703
} | class ____(TokenizerTesterMixin, unittest.TestCase):
from_pretrained_id = ["google/reformer-crime-and-punishment"]
tokenizer_class = ReformerTokenizer
test_tokenizer_from_extractor = False # no Tokenizer Backend yet
from_pretrained_kwargs = {}
integration_expected_tokens = ['▁T', 'h', 'is', '▁is',... | ReformerTokenizationTest |
python | readthedocs__readthedocs.org | readthedocs/builds/migrations/0064_healthcheck.py | {
"start": 149,
"end": 522
} | class ____(migrations.Migration):
safe = Safe.before_deploy()
dependencies = [
("builds", "0063_alter_buildcommandresult"),
]
operations = [
migrations.AddField(
model_name="build",
name="healthcheck",
field=models.DateTimeField(blank=True, null=True... | Migration |
python | pypa__pip | src/pip/_internal/commands/search.py | {
"start": 828,
"end": 957
} | class ____(TypedDict):
name: str
summary: str
versions: list[str]
logger = logging.getLogger(__name__)
| TransformedHit |
python | numpy__numpy | numpy/random/tests/test_generator_mt19937.py | {
"start": 4209,
"end": 6415
} | class ____:
def test_basic(self):
random.multinomial(100, [0.2, 0.8])
def test_zero_probability(self):
random.multinomial(100, [0.2, 0.8, 0.0, 0.0, 0.0])
def test_int_negative_interval(self):
assert_(-5 <= random.integers(-5, -1) < -1)
x = random.integers(-5, -1, 5)
... | TestMultinomial |
python | weaviate__weaviate-python-client | weaviate/backup/backup_location.py | {
"start": 286,
"end": 418
} | class ____(_BackupLocationConfig):
"""The dynamic location of a backup for filesystem."""
path: str
| _BackupLocationFilesystem |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/base.py | {
"start": 23415,
"end": 24310
} | class ____(Mapped[_T_co], _MappedAttribute[_T_co]):
"""Mixin for :class:`.MapperProperty` subclasses that allows them to
be compatible with ORM-annotated declarative mappings.
"""
__slots__ = ()
# MappedSQLExpression, Relationship, Composite etc. dont actually do
# SQL expression behavior. y... | _DeclarativeMapped |
python | huggingface__transformers | src/transformers/models/deepseek_v3/modeling_deepseek_v3.py | {
"start": 6790,
"end": 8697
} | class ____(nn.Module):
"""Collection of expert weights stored as 3D tensors."""
def __init__(self, config):
super().__init__()
self.num_experts = config.num_local_experts
self.hidden_dim = config.hidden_size
self.intermediate_dim = config.intermediate_size
self.gate_up_p... | DeepseekV3NaiveMoe |
python | ray-project__ray | ci/ray_ci/builder_container.py | {
"start": 125,
"end": 1539
} | class ____(LinuxContainer):
def __init__(
self,
python_version: str,
build_type: str,
architecture: str,
upload: bool = False,
) -> None:
super().__init__(
"manylinux" if architecture == "x86_64" else f"manylinux-{architecture}",
volumes=[f... | BuilderContainer |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 58911,
"end": 60748
} | class ____(BaseModel):
"""
TaskInstanceHistory serializer for responses.
"""
task_id: Annotated[str, Field(title="Task Id")]
dag_id: Annotated[str, Field(title="Dag Id")]
dag_run_id: Annotated[str, Field(title="Dag Run Id")]
map_index: Annotated[int, Field(title="Map Index")]
start_date... | TaskInstanceHistoryResponse |
python | encode__starlette | starlette/endpoints.py | {
"start": 2153,
"end": 5099
} | class ____:
encoding: Literal["text", "bytes", "json"] | None = None
def __init__(self, scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] == "websocket"
self.scope = scope
self.receive = receive
self.send = send
def __await__(self) -> Generator[Any, ... | WebSocketEndpoint |
python | huggingface__transformers | tests/models/canine/test_modeling_canine.py | {
"start": 8533,
"end": 20795
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(
CanineModel,
CanineForMultipleChoice,
CanineForQuestionAnswering,
CanineForSequenceClassification,
CanineForTokenClassification,
)
if is_t... | CanineModelTest |
python | astropy__astropy | astropy/time/formats.py | {
"start": 81946,
"end": 90558
} | class ____(TimeDeltaFormat, TimeUnique):
"""Time delta as a string with one or more Quantity components.
This format provides a human-readable multi-scale string representation of a time
delta. It is convenient for applications like a configuration file or a command line
option.
The format is spec... | TimeDeltaQuantityString |
python | encode__httpx | httpx/_client.py | {
"start": 5330,
"end": 19412
} | class ____:
def __init__(
self,
*,
auth: AuthTypes | None = None,
params: QueryParamTypes | None = None,
headers: HeaderTypes | None = None,
cookies: CookieTypes | None = None,
timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,
follow_redirects: bool = Fa... | BaseClient |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_exceptions/invalid_exceptions_raised.py | {
"start": 215,
"end": 2167
} | class ____:
"""Not an exception."""
def good_case():
"""raise"""
raise ValidException('hop')
def good_case1():
"""zlib.error is defined in C module."""
import zlib
raise zlib.error(4)
def good_case2():
"""decimal.DivisionByZero is defined in C on Python 3."""
import decimal
raise ... | NewStyleClass |
python | hyperopt__hyperopt | hyperopt/tests/unit/test_domains.py | {
"start": 5912,
"end": 7246
} | class ____:
def test_basic(self):
domain = self._domain_cls()
# print 'domain params', domain.params, domain
# print 'algo params', algo.vh.params
trials = Trials()
fmin(
lambda x: x,
domain.expr,
trials=trials,
algo=suggest,
... | DomainExperimentMixin |
python | bokeh__bokeh | src/bokeh/models/widgets/groups.py | {
"start": 2007,
"end": 2444
} | class ____(AbstractGroup, ButtonLike):
''' Abstract base class for groups with items rendered as buttons.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
orientation = Enum("horizontal", "vertical"... | ToggleButtonGroup |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 628460,
"end": 629103
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("SponsorableItemEdge"), graphql_name="edges"
)
nodes = sgq... | SponsorableItemConnection |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-oci-genai/tests/test_oci_genai.py | {
"start": 386,
"end": 18641
} | class ____(dict):
def __getattr__(self, val) -> Any: # type: ignore[no-untyped-def]
return self[val]
@pytest.mark.parametrize("test_model_id", [])
def test_llm_complete(monkeypatch: MonkeyPatch, test_model_id: str) -> None:
"""Test valid completion call to OCI Generative AI LLM service."""
oci_ge... | MockResponseDict |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 33292,
"end": 33471
} | class ____:
xlAutomaticScale = -4105 # from enum XlCategoryType
xlCategoryScale = 2 # from enum XlCategoryType
xlTimeScale = 3 # from enum XlCategoryType
| CategoryType |
python | PyCQA__pylint | tests/functional/u/useless/useless_parent_delegation.py | {
"start": 11926,
"end": 12098
} | class ____(Base):
@trigger_something("value1")
def method_decorated(self):
super(NotUselessSuperDecorators, self).method_decorated()
| NotUselessSuperDecorators |
python | sympy__sympy | sympy/codegen/pynodes.py | {
"start": 74,
"end": 111
} | class ____(AbstractList):
pass
| List |
python | getsentry__sentry | tests/sentry/db/models/fields/test_encryption.py | {
"start": 15832,
"end": 18897
} | class ____(models.Model):
id = models.AutoField(primary_key=True)
data = EncryptedCharField(null=True, blank=True)
class Meta:
app_label = "fixtures"
@pytest.mark.django_db
def test_encrypted_char_field_fernet_end_to_end(fernet_keys_store):
"""Test complete save/retrieve cycle with EncryptedF... | EncryptedFieldModel |
python | encode__starlette | starlette/middleware/base.py | {
"start": 8877,
"end": 10333
} | class ____(Response):
def __init__(
self,
content: AsyncContentStream,
status_code: int = 200,
headers: Mapping[str, str] | None = None,
media_type: str | None = None,
info: Mapping[str, Any] | None = None,
) -> None:
self.info = info
self.body_ite... | _StreamingResponse |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/hooks/test_glacier.py | {
"start": 1130,
"end": 4494
} | class ____:
def setup_method(self):
with mock.patch("airflow.providers.amazon.aws.hooks.glacier.GlacierHook.__init__", return_value=None):
self.hook = GlacierHook(aws_conn_id="aws_default")
@mock.patch("airflow.providers.amazon.aws.hooks.glacier.GlacierHook.get_conn")
def test_retrieve_... | TestAmazonGlacierHook |
python | doocs__leetcode | lcp/LCP 19. 秋叶收藏集/Solution.py | {
"start": 0,
"end": 595
} | class ____:
def minimumOperations(self, leaves: str) -> int:
n = len(leaves)
f = [[inf] * 3 for _ in range(n)]
f[0][0] = int(leaves[0] == "y")
for i in range(1, n):
if leaves[i] == "r":
f[i][0] = f[i - 1][0]
f[i][1] = min(f[i - 1][0], f[i -... | Solution |
python | tornadoweb__tornado | tornado/test/websocket_test.py | {
"start": 6879,
"end": 20904
} | class ____(WebSocketBaseTestCase):
def get_app(self):
self.close_future = Future() # type: Future[None]
return Application(
[
("/echo", EchoHandler, dict(close_future=self.close_future)),
("/non_ws", NonWebSocketHandler),
("/redirect", Red... | WebSocketTest |
python | google__pytype | pytype/tests/test_type_comments1.py | {
"start": 8405,
"end": 20212
} | class ____(test_base.BaseTest):
"""Tests for type comments applied to assignments."""
def test_class_attribute_comment(self):
ty = self.Infer("""
class Foo:
s = None # type: str
""")
self.assertTypesMatchPytd(
ty,
"""
class Foo:
s = ... # type: str
""",... | AssignmentCommentTest |
python | realpython__materials | wordcount/tests/task_04.py | {
"start": 505,
"end": 1764
} | class ____:
def test_long_word_without_trailing_newline(self, wc):
assert b" 0 1 29\n" == wc(stdin=b"floccinaucinihilipilification")
def test_long_word_with_trailing_newline(self, wc):
assert b" 1 1 30\n" == wc(stdin=b"floccinaucinihilipilification\n")
def test_multiple_words_without_tra... | Test |
python | PrefectHQ__prefect | tests/cli/test_api_command.py | {
"start": 10195,
"end": 11006
} | class ____:
"""Test different input sources for request body."""
def test_data_from_file(self, respx_mock: MockRouter, tmp_path) -> None:
"""Test reading data from file with @filename syntax."""
route = respx_mock.post("http://localhost:4200/api/flows/filter").mock(
return_value=htt... | TestInputSources |
python | xlwings__xlwings | tests/test_app.py | {
"start": 119,
"end": 769
} | class ____(TestBase):
def test_active(self):
self.assertTrue(xw.apps.active in [self.app1, self.app2])
def test_len(self):
n_original = len(xw.apps)
app = xw.App(spec=SPEC)
app.books.add()
self.assertEqual(n_original + 1, len(xw.apps))
app.quit()
def test_co... | TestApps |
python | bokeh__bokeh | src/bokeh/models/comparisons.py | {
"start": 3566,
"end": 4530
} | class ____(Comparison):
''' A client-side comparison that can sort NaN values first or last. This
comparison can be useful for DataTable columns.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
... | NanCompare |
python | walkccc__LeetCode | solutions/2293. Min Max Game/2293.py | {
"start": 0,
"end": 332
} | class ____:
def minMaxGame(self, nums: list[int]) -> int:
if len(nums) == 1:
return nums[0]
nextNums = []
for i in range(len(nums) // 2):
nextNums.append(min(nums[2 * i], nums[2 * i + 1]) if i % 2 == 0 else
max(nums[2 * i], nums[2 * i + 1]))
return self.minMaxGame(ne... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVar7.py | {
"start": 723,
"end": 2526
} | class ____(Generic[_T1, _T2]):
async def func1(self, a: _T1) -> _T1:
_ = a.var1
# This should generate an error.
_ = a.var2
# This should generate an error.
_ = a(3.3)
# This should generate two errors.
_ = a[0]
# This should generate an error.
... | ClassA |
python | openai__openai-python | tests/test_transform.py | {
"start": 4022,
"end": 4323
} | class ____(TypedDict):
foo: str
@parametrize
@pytest.mark.asyncio
async def test_ignores_invalid_input(use_async: bool) -> None:
assert await transform({"bar": "<foo>"}, Foo7, use_async) == {"bAr": "<foo>"}
assert await transform({"foo": "<foo>"}, Foo7, use_async) == {"foo": "<foo>"}
| Bar7 |
python | spyder-ide__spyder | spyder/api/widgets/dialogs.py | {
"start": 1182,
"end": 2786
} | class ____(QDialogButtonBox):
"""QDialogButtonBox widget for Spyder."""
def __init__(self, buttons=None, orientation=Qt.Horizontal, parent=None):
if buttons:
super().__init__(buttons, orientation, parent)
elif orientation:
super().__init__(orientation=orientation, parent... | SpyderDialogButtonBox |
python | getsentry__sentry-python | tests/test_basics.py | {
"start": 28645,
"end": 29903
} | class ____:
def __init__(self, word):
self.word = word
def greet(self, new_word=None):
return "Hello, {}".format(new_word if new_word else self.word)
def test_functions_to_trace_with_class(sentry_init, capture_events):
functions_to_trace = [
{"qualified_name": "tests.test_basics.W... | WorldGreeter |
python | graphql-python__graphene | graphene/types/datetime.py | {
"start": 181,
"end": 1327
} | class ____(Scalar):
"""
The `Date` scalar type represents a Date
value as specified by
[iso8601](https://en.wikipedia.org/wiki/ISO_8601).
"""
@staticmethod
def serialize(date):
if isinstance(date, datetime.datetime):
date = date.date()
if not isinstance(date, dat... | Date |
python | cherrypy__cherrypy | cherrypy/lib/locking.py | {
"start": 239,
"end": 926
} | class ____(object):
"""A simple timer that will indicate when an expiration time has passed."""
def __init__(self, expiration):
"""Create a timer that expires at `expiration` (UTC datetime)."""
self.expiration = expiration
@classmethod
def after(cls, elapsed):
"""Return a timer... | Timer |
python | pytorch__pytorch | test/test_cuda_sanitizer.py | {
"start": 5076,
"end": 16552
} | class ____(TestCase):
def setUp(self):
super().setUp()
self.handler = csan.EventHandler()
def kernel_launch(
self,
stream: StreamId,
read_only: Optional[list[DataPtr]] = None,
read_write: Optional[list[DataPtr]] = None,
) -> list[csan.SynchronizationError]:
... | TestEventHandler |
python | great-expectations__great_expectations | great_expectations/execution_engine/sqlalchemy_execution_engine.py | {
"start": 5664,
"end": 7253
} | class ____(ValueError):
def __init__(self, filter_clause: Any) -> None:
super().__init__(f"Invalid filter clause: {type(filter_clause)}")
def _dialect_requires_persisted_connection(
connection_string: str | None = None,
credentials: dict | None = None,
url: str | None = None,
) -> bool:
""... | InvalidFilterClause |
python | huggingface__transformers | examples/pytorch/text-classification/run_xnli.py | {
"start": 2035,
"end": 3935
} | class ____:
"""
Arguments pertaining to what data we are going to input our model for training and eval.
Using `HfArgumentParser` we can turn this class
into argparse arguments to be able to specify them on
the command line.
"""
max_seq_length: Optional[int] = field(
default=128,
... | DataTrainingArguments |
python | ray-project__ray | python/ray/util/dask/callbacks.py | {
"start": 7732,
"end": 10511
} | class ____(RayDaskCallback):
def __init__(self):
@ray.remote
class ProgressBarActor:
def __init__(self):
self._init()
def submit(self, key, deps, now):
for dep in deps.keys():
self.deps[key].add(dep)
self.su... | ProgressBarCallback |
python | readthedocs__readthedocs.org | readthedocs/oauth/admin.py | {
"start": 1200,
"end": 1702
} | class ____(admin.ModelAdmin):
"""Admin configuration for the RemoteOrganization model."""
readonly_fields = (
"created",
"modified",
)
search_fields = (
"name",
"slug",
"email",
"url",
"remote_id",
)
list_filter = ("vcs_provider",)
lis... | RemoteOrganizationAdmin |
python | getsentry__sentry | tests/sentry/web/frontend/test_oauth_token.py | {
"start": 17600,
"end": 21097
} | class ____(TestCase):
@cached_property
def path(self) -> str:
return "/oauth/token/"
def setUp(self) -> None:
super().setUp()
self.application = ApiApplication.objects.create(
owner=self.user, redirect_uris="https://example.com"
)
self.client_secret = sel... | OAuthTokenRefreshTokenTest |
python | gevent__gevent | src/greentest/3.14/test_urllib2_localnet.py | {
"start": 644,
"end": 1544
} | class ____(http.server.HTTPServer):
"""HTTP server w/ a few modifications that make it useful for
loopback testing purposes.
"""
def __init__(self, server_address, RequestHandlerClass):
http.server.HTTPServer.__init__(self,
server_address,
... | LoopbackHttpServer |
python | scrapy__scrapy | scrapy/crawler.py | {
"start": 13854,
"end": 17082
} | class ____(CrawlerRunnerBase):
"""
This is a convenient helper class that keeps track of, manages and runs
crawlers inside an already setup :mod:`~twisted.internet.reactor`.
The CrawlerRunner object must be instantiated with a
:class:`~scrapy.settings.Settings` object.
This class shouldn't be ... | CrawlerRunner |
python | PrefectHQ__prefect | src/integrations/prefect-azure/prefect_azure/container_instance.py | {
"start": 2921,
"end": 3074
} | class ____(str, Enum):
"""
Terminal run states for ACI containers.
"""
RUNNING = "Running"
TERMINATED = "Terminated"
| ContainerRunState |
python | getsentry__sentry | src/sentry/api/endpoints/organization_profiling_functions.py | {
"start": 2098,
"end": 2407
} | class ____(serializers.Serializer):
function = serializers.CharField(max_length=10)
trend = TrendTypeField()
query = serializers.CharField(required=False)
threshold = serializers.IntegerField(min_value=0, max_value=1000, default=16, required=False)
@region_silo_endpoint
| FunctionTrendsSerializer |
python | astropy__astropy | astropy/utils/metadata/tests/test_metadata.py | {
"start": 2101,
"end": 2221
} | class ____(MetaBaseTest):
test_class = ExampleDataclass
args = ()
@dataclass(frozen=True)
| TestMetaExampleDataclass |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-markitdown/llama_index/readers/markitdown/base.py | {
"start": 3110,
"end": 4572
} | class ____(BaseReader):
"""
MarkItDownReader is a document reader that utilizes the MarkItDown parser to convert files or collections of files into Document objects.
Methods
-------
load_data(file_path: str | Path | Iterable[str] | Iterable[Path]) -> List[Document]
Loads and parses a direct... | MarkItDownReader |
python | pola-rs__polars | py-polars/src/polars/datatypes/classes.py | {
"start": 9470,
"end": 9542
} | class ____(SignedIntegerType):
"""16-bit signed integer type."""
| Int16 |
python | Netflix__metaflow | metaflow/plugins/cards/card_modules/json_viewer.py | {
"start": 303,
"end": 3478
} | class ____(MetaflowCardComponent):
"""
A component for displaying JSON data with syntax highlighting and collapsible sections.
This component provides a rich view of JSON data with proper formatting, syntax highlighting,
and the ability to collapse/expand sections for better readability.
Example:
... | JSONViewer |
python | pytorch__pytorch | test/dynamo/cpython/3_13/typinganndata/_typed_dict_helper.py | {
"start": 684,
"end": 745
} | class ____(TypedDict, Generic[T]):
a: Optional[T]
| FooGeneric |
python | django__django | django/db/models/functions/text.py | {
"start": 9973,
"end": 10418
} | class ____(Func):
"""
Return a positive integer corresponding to the 1-indexed position of the
first occurrence of a substring inside another string, or 0 if the
substring is not found.
"""
function = "INSTR"
arity = 2
output_field = IntegerField()
def as_postgresql(self, compiler,... | StrIndex |
python | PyCQA__pylint | pylint/typing.py | {
"start": 3205,
"end": 3374
} | class ____(Protocol):
def __call__(
self, config: PyreverseConfig | None = None, args: Sequence[str] | None = None
) -> DiaDefGenerator: ...
| GeneratorFactory |
python | celery__celery | t/unit/worker/test_components.py | {
"start": 2257,
"end": 2461
} | class ____:
def test_create__green(self):
w = Mock(name='w')
w.pool_cls.__module__ = 'foo_gevent'
with pytest.raises(ImproperlyConfigured):
Beat(w).create(w)
| test_Beat |
python | streamlit__streamlit | lib/streamlit/elements/plotly_chart.py | {
"start": 2847,
"end": 5497
} | class ____(TypedDict, total=False):
"""
The schema for the Plotly chart selection state.
The selection state is stored in a dictionary-like object that supports both
key and attribute notation. Selection states cannot be programmatically
changed or set through Session State.
Attributes
---... | PlotlySelectionState |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0042_increase_env_variable_value_max_length.py | {
"start": 150,
"end": 534
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0041_index-repo-field"),
]
operations = [
migrations.AlterField(
model_name="environmentvariable",
name="value",
field=models.CharField(help_text="Value of the... | Migration |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-dashscope/llama_index/readers/dashscope/domain/lease_domains.py | {
"start": 10013,
"end": 10375
} | class ____(Enum):
INIT = "INIT"
PARSING = "PARSING"
PARSE_SUCCESS = "PARSE_SUCCESS"
PARSE_FAILED = "PARSE_FAILED"
@classmethod
def from_value(cls, value):
for member in cls:
if member.value == value:
return member
raise ValueError(f"No enum member fou... | DatahubDataStatusEnum |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_relationship.py | {
"start": 64263,
"end": 66310
} | class ____(
fixtures.DeclarativeMappedTest, testing.AssertsCompiledSQL
):
"""exercise issue #3611, using the test from dupe issue 3614"""
run_define_tables = None
__dialect__ = "default"
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class User(Base):
... | JoinedloadSinglePolysubSingle |
python | astropy__astropy | astropy/cosmology/_src/tests/flrw/test_wpwazpcdm.py | {
"start": 996,
"end": 2424
} | class ____(ParameterTestMixin):
"""Tests for `astropy.cosmology.Parameter` wp on a Cosmology.
wp is a descriptor, which are tested by mixin, here with ``TestFLRW``.
These tests expect dicts ``_cls_args`` and ``cls_kwargs`` which give the
args and kwargs for the cosmology class, respectively. See ``Test... | ParameterwpTestMixin |
python | tensorflow__tensorflow | tensorflow/python/tools/api/generator/create_python_api.py | {
"start": 2210,
"end": 3355
} | class ____(Exception):
"""Raised when different symbols are exported with the same name."""
pass
def get_canonical_import(import_set):
"""Obtain one single import from a set of possible sources of a symbol.
One symbol might come from multiple places as it is being imported and
reexported. To simplify API c... | SymbolExposedTwiceError |
python | kubernetes-client__python | kubernetes/client/models/v1_env_var.py | {
"start": 383,
"end": 5972
} | 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... | V1EnvVar |
python | huggingface__transformers | tests/models/gpt_oss/test_modeling_gpt_oss.py | {
"start": 6699,
"end": 21037
} | class ____(unittest.TestCase):
input_text = [
"Roses are red, violets",
"How are you? Tell me the name of the president of",
]
@staticmethod
def generate_config_key(quantized, model, kernels, attn_impl, mode):
"""Generate a key for the restructured integration test results."""
... | GptOssIntegrationTest |
python | numba__numba | numba/core/ir.py | {
"start": 22196,
"end": 22553
} | class ____(Terminator):
is_exit = True
def __init__(self, exception, loc):
assert exception is None or isinstance(exception, Var)
assert isinstance(loc, Loc)
self.exception = exception
self.loc = loc
def __str__(self):
return "raise %s" % self.exception
def get... | Raise |
python | cython__cython | Cython/Debugger/libcython.py | {
"start": 8693,
"end": 16673
} | class ____:
@default_selected_gdb_frame(err=False)
def is_cython_function(self, frame):
return frame.name() in self.cy.functions_by_cname
@default_selected_gdb_frame(err=False)
def is_python_function(self, frame):
"""
Tells if a frame is associated with a Python function.
... | CythonBase |
python | huggingface__transformers | src/transformers/models/pvt_v2/modeling_pvt_v2.py | {
"start": 21125,
"end": 23568
} | class ____(PvtV2Model, BackboneMixin):
def __init__(self, config: PvtV2Config):
super().__init__(config)
super()._init_backbone(config)
self.num_features = config.hidden_sizes
@auto_docstring
def forward(
self,
pixel_values: torch.FloatTensor,
output_attentio... | PvtV2Backbone |
python | huggingface__transformers | src/transformers/models/dinov2_with_registers/modular_dinov2_with_registers.py | {
"start": 14113,
"end": 15660
} | class ____(Dinov2ForImageClassification):
def forward(
self,
pixel_values: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> ImageClassifierOutput:
r"""
labels (`torch.LongTensor` of shape `(batch_size... | Dinov2WithRegistersForImageClassification |
python | dask__distributed | distributed/client.py | {
"start": 197629,
"end": 201169
} | class ____(WorkerPlugin):
"""This is used to support older setup functions as callbacks"""
def __init__(self, setup):
self._setup = setup
def setup(self, worker):
if has_keyword(self._setup, "dask_worker"):
return self._setup(dask_worker=worker)
else:
return... | _WorkerSetupPlugin |
python | ray-project__ray | python/ray/llm/_internal/serve/core/configs/llm_config.py | {
"start": 19350,
"end": 19554
} | class ____(BaseModelExtended):
model_id: str
max_total_tokens: Optional[int]
local_path: str
# this is a per process id assigned to the model
lora_assigned_int_id: int
| DiskMultiplexConfig |
python | keras-team__keras | keras/src/metrics/accuracy_metrics.py | {
"start": 8482,
"end": 11338
} | class ____(reduction_metrics.MeanMetricWrapper):
"""Calculates how often predictions match integer labels.
```python
acc = np.dot(sample_weight, np.equal(y_true, np.argmax(y_pred, axis=1))
```
You can provide logits of classes as `y_pred`, since argmax of
logits and probabilities are same.
... | SparseCategoricalAccuracy |
python | wandb__wandb | wandb/_pydantic/pagination.py | {
"start": 1261,
"end": 1355
} | class ____(Connection[NodeT], Generic[NodeT]):
total_count: NonNegativeInt
| ConnectionWithTotal |
python | great-expectations__great_expectations | tests/integration/fixtures/partition_and_sample_data/partitioner_test_cases_and_fixtures.py | {
"start": 8980,
"end": 9546
} | class ____(TaxiPartitioningTestCasesBase):
@override
def test_cases(self) -> List[TaxiPartitioningTestCase]:
return [
TaxiPartitioningTestCase(
table_domain_test_case=True,
num_expected_batch_definitions=1,
num_expected_rows_in_first_batch_defi... | TaxiPartitioningTestCasesWholeTable |
python | kamyu104__LeetCode-Solutions | Python/beautiful-arrangement-ii.py | {
"start": 29,
"end": 491
} | class ____(object):
def constructArray(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[int]
"""
result = []
left, right = 1, n
while left <= right:
if k % 2:
result.append(left)
left += 1
... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramSpec42.py | {
"start": 466,
"end": 1286
} | class ____(Generic[P, R]):
def __init__(self, func: Callable[P, R]):
self._func = func
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:
return self._func(*args, **kwargs)
def other(self, val: int, *args: P.args, **kwargs: P.kwargs) -> R: ...
decorated_func1 = DecoratorClass1(f... | DecoratorClass1 |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/guides/dagster/dagster_pipes/dagster_pipes_details_and_customization/custom_context_loader.py | {
"start": 225,
"end": 582
} | class ____(PipesContextLoader):
@contextmanager
def load_context(self, params: PipesParams) -> Iterator[PipesContextData]:
# params were yielded by the above context injector and sourced from the bootstrap payload
key = params["key"]
data = cloud_service.read(key)
yield json.load... | MyCustomCloudServiceContextLoader |
python | pytorch__pytorch | test/distributed/pipelining/schedule_registry.py | {
"start": 4983,
"end": 6239
} | class ____(_PipelineScheduleRuntime):
n_stages = 2
num_microbatches = 2
rank_stages = {
0: [0],
1: [1],
}
def __init__(
self,
stages: list[_PipelineStageBase],
n_microbatches: int,
loss_fn: Optional[Callable] = None,
scale_grads: bool = True,
... | ScheduleWithReorderedB |
python | realpython__materials | django-migrations/bitcoin_tracker/historical_data/models.py | {
"start": 31,
"end": 245
} | class ____(models.Model):
date = models.DateTimeField(auto_now_add=True)
price = models.DecimalField(max_digits=7, decimal_places=2)
volume = models.DecimalField(max_digits=7, decimal_places=3)
| PriceHistory |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1020946,
"end": 1021697
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of
UpdateEnterpriseMembersCanDeleteIssuesSetting
"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "enterprise", "message")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A u... | UpdateEnterpriseMembersCanDeleteIssuesSettingPayload |
python | pytorch__pytorch | test/dynamo/test_list.py | {
"start": 229,
"end": 5248
} | class ____(torch._dynamo.test_case.TestCase):
# Tuple methods
# + count
# + index
# BinOps:
# +, <, >, <=, >=, ==, !=
# Dunder methods:
# + __getitem__
# + __contains__
# + __delitem__
thetype = tuple
def setUp(self):
self.old = torch._dynamo.config.enable_trace_uni... | TupleTests |
python | ray-project__ray | rllib/examples/envs/classes/windy_maze_env.py | {
"start": 463,
"end": 2699
} | class ____(gym.Env):
def __init__(self, env_config):
self.map = [m for m in MAP_DATA.split("\n") if m]
self.x_dim = len(self.map)
self.y_dim = len(self.map[0])
logger.info("Loaded map {} {}".format(self.x_dim, self.y_dim))
for x in range(self.x_dim):
for y in rang... | WindyMazeEnv |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_compute.py | {
"start": 21994,
"end": 25518
} | class ____:
@mock.patch(COMPUTE_ENGINE_HOOK_PATH)
def test_instance_stop_should_execute_successfully(self, mock_hook):
op = ComputeEngineStopInstanceOperator(
project_id=GCP_PROJECT_ID,
zone=GCE_ZONE,
resource_id=GCE_RESOURCE_ID,
task_id=TASK_ID,
... | TestGceInstanceStop |
python | pandas-dev__pandas | pandas/plotting/_matplotlib/converter.py | {
"start": 5696,
"end": 8336
} | class ____(mdates.DateConverter):
@staticmethod
def convert(values, unit, axis: Axis):
# Reached via e.g. `ax.set_xlim`
# In tests as of 2025-09-24, unit is always None except for 3 tests
# that directly call this with unit="";
# axis is always specifically a matplotlib.axis.X... | PeriodConverter |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_axis25.py | {
"start": 314,
"end": 1456
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_axis25.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
python | huggingface__transformers | tests/quantization/autoawq/test_awq.py | {
"start": 22450,
"end": 23086
} | class ____(unittest.TestCase):
model_name = "TechxGenus/starcoder2-3b-AWQ"
def test_load_quantized_model(self):
from awq.modules.act import ScaledActivation
"""
Simple test that checks if the scales have been replaced in the quantized model
"""
quantized_model = AutoMod... | AwqScaleTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.