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 | ray-project__ray | python/ray/serve/tests/test_model_composition.py | {
"start": 1429,
"end": 2030
} | class ____:
def __init__(self, val):
self.val = val
def get(self):
return self.val
def inc(self, inc):
self.val += inc
@serve.deployment
def fn_hello():
return "hello"
@serve.deployment
def combine(m1_output, m2_output, kwargs_output=0):
return m1_output + m2_output + k... | Counter |
python | PrefectHQ__prefect | tests/cli/transfer/test_dag.py | {
"start": 327,
"end": 1706
} | class ____:
"""Mock migratable resource for testing DAG functionality."""
def __init__(
self,
resource_id: uuid.UUID,
name: str,
migrate_success: bool = True,
dependencies: Optional[list[uuid.UUID]] = None,
):
self.id = resource_id
self.source_id = re... | MockMigratableResource |
python | spack__spack | lib/spack/spack/util/crypto.py | {
"start": 3541,
"end": 5668
} | class ____:
"""A checker checks files against one particular hex digest.
It will automatically determine what hashing algorithm
to used based on the length of the digest it's initialized
with. e.g., if the digest is 32 hex characters long this will
use md5.
Example: know your tarball should ha... | Checker |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/lib/metadata_service/models/generated/ConnectorBreakingChanges.py | {
"start": 785,
"end": 1791
} | class ____(BaseModel):
class Config:
extra = Extra.forbid
upgradeDeadline: date = Field(
...,
description="The deadline by which to upgrade before the breaking change takes effect.",
)
message: str = Field(
..., description="Descriptive message detailing the breaking cha... | VersionBreakingChange |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/queues/sqs.py | {
"start": 1476,
"end": 2870
} | class ____(BaseMessageQueueProvider):
"""
Configuration for SQS integration with common-messaging.
[START sqs_message_queue_provider_description]
* It uses ``sqs`` as scheme for identifying SQS queues.
* For parameter definitions take a look at :class:`~airflow.providers.amazon.aws.triggers.sqs.Sq... | SqsMessageQueueProvider |
python | pydantic__pydantic | pydantic/functional_serializers.py | {
"start": 3489,
"end": 18117
} | class ____:
"""Wrap serializers receive the raw inputs along with a handler function that applies the standard serialization
logic, and can modify the resulting value before returning it as the final output of serialization.
For example, here's a scenario in which a wrap serializer transforms timezones to ... | WrapSerializer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 565011,
"end": 565745
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for Deployment."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("DeploymentEdge"), graphql_name="edges")
"""A list of edges."""
nodes = ... | DeploymentConnection |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 3464,
"end": 3531
} | class ____(PydanticErrorMixin, TypeError):
pass
| PydanticTypeError |
python | streamlit__streamlit | lib/tests/streamlit/elements/heading_test.py | {
"start": 18540,
"end": 19749
} | class ____(DeltaGeneratorTestCase):
"""Test st.subheader text_alignment parameter."""
@parameterized.expand(
[
("left", 1),
("center", 2),
("right", 3),
("justify", 4),
(None, 1), # Default case
]
)
def test_st_subheader_text_... | StSubheaderTextAlignmentTest |
python | gwtw__py-sorting | test/quicksort_test.py | {
"start": 404,
"end": 728
} | class ____(unittest.TestCase,
BaseCustomComparisonSortTest,
BasePositiveIntegerSortTest,
BaseNegativeIntegerSortTest,
BaseStringSortTest):
def setUp(self):
self.sort = quicksort.sort
if __name__ == '__main__':
unittest.main()
| QuicksortTest |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/too_many_public_methods.py | {
"start": 44,
"end": 485
} | class ____:
foo = 1
def __init__(self):
pass
def _private(self):
pass
def method1(self):
pass
def method2(self):
pass
def method3(self):
pass
def method4(self):
pass
def method5(self):
pass
def method6(self):
pas... | Everything |
python | keras-team__keras | keras/src/distribution/distribution_lib.py | {
"start": 8490,
"end": 10763
} | class ____:
"""A layout to apply to a tensor.
This API is aligned with `jax.sharding.NamedSharding`
and `tf.dtensor.Layout`.
See more details in [jax.sharding.NamedSharding](
https://jax.readthedocs.io/en/latest/jax.sharding.html#jax.sharding.NamedSharding)
and [tf.dtensor.Layout](
... | TensorLayout |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-ragie/unit_tests/test_ragie_client.py | {
"start": 162,
"end": 1144
} | class ____(unittest.TestCase):
def setUp(self):
# Setup mock client
self.mock_client = MagicMock(RagieClient)
def test_find_ids_by_metadata(self):
# Test finding IDs by metadata
self.mock_client.find_ids_by_metadata.return_value = [1, 2, 3]
result = self.mock_client.find... | TestRagieClient |
python | huggingface__transformers | src/transformers/models/ernie4_5/modular_ernie4_5.py | {
"start": 1046,
"end": 3826
} | class ____(OlmoRotaryEmbedding):
@torch.no_grad()
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
def forward(self, x, position_ids):
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
position_ids_... | Ernie4_5RotaryEmbedding |
python | coleifer__peewee | tests/sql.py | {
"start": 83384,
"end": 84177
} | class ____(BaseTestCase):
database = SqliteDatabase(None)
def test_replace(self):
query = Person.insert(name='huey').on_conflict('replace')
self.assertSQL(query, (
'INSERT OR REPLACE INTO "person" ("name") VALUES (?)'), ['huey'])
def test_ignore(self):
query = Person.in... | TestOnConflictSqlite |
python | django__django | tests/postgres_tests/test_functions.py | {
"start": 223,
"end": 874
} | class ____(PostgreSQLTestCase):
def test_transaction_now(self):
"""
The test case puts everything under a transaction, so two models
updated with a short gap should have the same time.
"""
m1 = NowTestModel.objects.create()
m2 = NowTestModel.objects.create()
... | TestTransactionNow |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_indexing.py | {
"start": 43284,
"end": 45044
} | class ____(TestCase):
"""
These test that ``TypeError`` is raised when you try to use
non-integers as arguments to for indexing and slicing e.g. ``a[0.0:5]``
and ``a[0.5]``, or other functions like ``array.reshape(1., -1)``.
"""
def test_valid_indexing(self):
# These should raise no er... | TestFloatNonIntegerArgument |
python | ray-project__ray | rllib/examples/_old_api_stack/models/autoregressive_action_dist.py | {
"start": 338,
"end": 2632
} | class ____(ActionDistribution):
"""Action distribution P(a1, a2) = P(a1) * P(a2 | a1)"""
def deterministic_sample(self):
# First, sample a1.
a1_dist = self._a1_distribution()
a1 = a1_dist.deterministic_sample()
# Sample a2 conditioned on a1.
a2_dist = self._a2_distribut... | BinaryAutoregressiveDistribution |
python | airbytehq__airbyte | airbyte-ci/connectors/live-tests/src/live_tests/commons/models.py | {
"start": 4049,
"end": 4218
} | class ____(UserDict):
def __str__(self) -> str:
return f"{self.__class__.__name__}(******)"
def __repr__(self) -> str:
return str(self)
| SecretDict |
python | openai__openai-python | src/openai/types/realtime/realtime_conversation_item_function_call_param.py | {
"start": 241,
"end": 1182
} | class ____(TypedDict, total=False):
arguments: Required[str]
"""The arguments of the function call.
This is a JSON-encoded string representing the arguments passed to the function,
for example `{"arg1": "value1", "arg2": 42}`.
"""
name: Required[str]
"""The name of the function being calle... | RealtimeConversationItemFunctionCallParam |
python | milvus-io__pymilvus | tests/test_grpc_handler.py | {
"start": 5327,
"end": 8141
} | class ____:
def test_init_with_uri(self) -> None:
with patch('pymilvus.client.grpc_handler.grpc.insecure_channel') as mock_channel:
mock_channel.return_value = MagicMock()
handler = GrpcHandler(uri="http://localhost:19530")
assert handler.server_address == "localhost:1953... | TestGrpcHandlerInitialization |
python | ansible__ansible | lib/ansible/plugins/filter/encryption.py | {
"start": 2237,
"end": 2450
} | class ____(object):
""" Ansible vault jinja2 filters """
def filters(self):
filters = {
'vault': do_vault,
'unvault': do_unvault,
}
return filters
| FilterModule |
python | joblib__joblib | joblib/test/test_parallel.py | {
"start": 28651,
"end": 31119
} | class ____(SequentialBackend):
"""Pretends to run conncurrently while running sequentially."""
def __init__(self, param=None):
if param is None:
raise ValueError("param should not be None")
self.param = param
@parametrize("context", [parallel_config, parallel_backend])
def test_pa... | ParameterizedParallelBackend |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 91557,
"end": 95370
} | class ____(SocketConnectedTest):
def __init__(self, methodName='runTest'):
SocketConnectedTest.__init__(self, methodName=methodName)
def testRecv(self):
# Testing large receive over TCP
msg = self.cli_conn.recv(1024)
self.assertEqual(msg, MSG)
def _testRecv(self):
... | BasicTCPTest |
python | PyCQA__pylint | tests/functional/a/arguments_differ.py | {
"start": 2151,
"end": 2217
} | class ____:
@property
def close(self):
pass
| Property |
python | django__django | tests/admin_registration/tests.py | {
"start": 4347,
"end": 6255
} | class ____(SimpleTestCase):
"""
Tests the register decorator in admin.decorators
For clarity:
@register(Person)
class AuthorAdmin(ModelAdmin):
pass
is functionally equal to (the way it is written in these tests):
AuthorAdmin = register(Person)(AuthorAdmin)
"""... | TestRegistrationDecorator |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/dag_run.py | {
"start": 2202,
"end": 3031
} | class ____(BaseModel):
"""DAG Run serializer for responses."""
dag_run_id: str = Field(validation_alias="run_id")
dag_id: str
logical_date: datetime | None
queued_at: datetime | None
start_date: datetime | None
end_date: datetime | None
duration: float | None
data_interval_start: da... | DAGRunResponse |
python | huggingface__transformers | src/transformers/models/llava_onevision/modeling_llava_onevision.py | {
"start": 11808,
"end": 32119
} | class ____(LlavaOnevisionPreTrainedModel):
_checkpoint_conversion_mapping = {
r"^language_model.model": "language_model",
}
base_model_prefix = "model"
def __init__(self, config):
super().__init__(config)
self.vision_tower = AutoModel.from_config(config.vision_config)
s... | LlavaOnevisionModel |
python | scipy__scipy | scipy/special/tests/test_basic.py | {
"start": 55807,
"end": 58556
} | class ____:
def test_comb(self):
assert_allclose(special.comb([10, 10], [3, 4]), [120., 210.])
assert_allclose(special.comb(10, 3), 120.)
assert_equal(special.comb(10, 3, exact=True), 120)
assert_equal(special.comb(10, 3, exact=True, repetition=True), 220)
assert_allclose([s... | TestCombinatorics |
python | pyodide__pyodide | src/py/_pyodide/_importhook.py | {
"start": 281,
"end": 3812
} | class ____(MetaPathFinder):
def __init__(self) -> None:
self.jsproxies: dict[str, Any] = {}
self.hook: Callable[[JsProxy], None] = lambda _: None
def find_spec(
self,
fullname: str,
path: Sequence[bytes | str] | None,
target: ModuleType | None = None,
) -> Mo... | JsFinder |
python | charliermarsh__ruff | python/ruff-ecosystem/ruff_ecosystem/types.py | {
"start": 2336,
"end": 2502
} | class ____(Serializable):
"""
The result of a completed ecosystem comparison for a single project.
"""
diff: Diff
repo: ClonedRepository
| Comparison |
python | cython__cython | Cython/Compiler/Symtab.py | {
"start": 14148,
"end": 54683
} | class ____:
# name string Unqualified name
# outer_scope Scope or None Enclosing scope
# entries {string : Entry} Python name to entry, non-types
# const_entries [Entry] Constant entries
# type_entries [Entry] Struct/unio... | Scope |
python | euske__pdfminer | pdfminer/ccitt.py | {
"start": 1271,
"end": 18771
} | class ____(BitParser):
MODE = [None, None]
BitParser.add(MODE, 0, '1')
BitParser.add(MODE, +1, '011')
BitParser.add(MODE, -1, '010')
BitParser.add(MODE, 'h', '001')
BitParser.add(MODE, 'p', '0001')
BitParser.add(MODE, +2, '000011')
BitParser.add(MODE, -2, '000010')
BitParser.a... | CCITTG4Parser |
python | walkccc__LeetCode | solutions/215. Kth Largest Element in an Array/215-2.py | {
"start": 0,
"end": 672
} | class ____:
def findKthLargest(self, nums: list[int], k: int) -> int:
def quickSelect(l: int, r: int, k: int) -> int:
pivot = nums[r]
nextSwapped = l
for i in range(l, r):
if nums[i] >= pivot:
nums[nextSwapped], nums[i] = nums[i], nums[nextSwapped]
nextSwapped += 1
... | Solution |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_automation_rule_views.py | {
"start": 12111,
"end": 12450
} | class ____(TestAutomationRulesViews):
@pytest.fixture(autouse=True)
def setup_organization(self, settings):
settings.RTD_ALLOW_ORGANIZATIONS = True
self.organization = get(
Organization,
owners=[self.user],
projects=[self.project],
)
| TestAutomationRulesViewsWithOrganizations |
python | keras-team__keras | keras/src/ops/core.py | {
"start": 16457,
"end": 18298
} | class ____(Operation):
def call(self, inputs, start_indices, updates):
return backend.core.slice_update(inputs, start_indices, updates)
def compute_output_spec(self, inputs, start_indices, updates):
return KerasTensor(inputs.shape, dtype=inputs.dtype)
@keras_export("keras.ops.slice_update")
d... | SliceUpdate |
python | getsentry__sentry | src/sentry/db/postgres/schema.py | {
"start": 4781,
"end": 6227
} | class ____:
"""
Wrapper that allows us to use either the `SafePostgresDatabaseSchemaEditor` or
`PostgresDatabaseSchemaEditor`. Can be configured by setting the `safe` property
before using to edit the schema. If already in use, attempts to modify `safe` will
fail.
"""
class AlreadyInUse(Exc... | DatabaseSchemaEditorProxy |
python | conda__conda | conda/core/prefix_data.py | {
"start": 2112,
"end": 3063
} | class ____(type):
"""Basic caching of PrefixData instance objects."""
@deprecated.argument(
"25.9", "26.3", "pip_interop_enabled", rename="interoperability"
)
def __call__(
cls,
prefix_path: PathType,
interoperability: bool | None = None,
) -> PrefixData:
if ... | PrefixDataType |
python | getsentry__sentry | src/sentry/integrations/github/integration.py | {
"start": 41063,
"end": 45943
} | class ____:
client: GithubSetupApiClient
def dispatch(self, request: HttpRequest, pipeline: IntegrationPipeline) -> HttpResponseBase:
with record_event(IntegrationPipelineViewType.OAUTH_LOGIN).capture() as lifecycle:
self.active_user_organization = determine_active_organization(request)
... | OAuthLoginView |
python | apache__airflow | providers/apache/hive/tests/unit/apache/hive/macros/test_hive.py | {
"start": 910,
"end": 1901
} | class ____:
def test_closest_ds_partition(self):
date1 = datetime.strptime("2017-04-24", "%Y-%m-%d")
date2 = datetime.strptime("2017-04-25", "%Y-%m-%d")
date3 = datetime.strptime("2017-04-26", "%Y-%m-%d")
date4 = datetime.strptime("2017-04-28", "%Y-%m-%d")
date5 = datetime.st... | TestHive |
python | simonw__sqlite-utils | sqlite_utils/db.py | {
"start": 158595,
"end": 160696
} | class ____(Queryable):
def exists(self):
return True
def __repr__(self) -> str:
return "<View {} ({})>".format(
self.name, ", ".join(c.name for c in self.columns)
)
def drop(self, ignore=False):
"""
Drop this view.
:param ignore: Set to ``True``... | View |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/assets/graph/asset_graph_differ.py | {
"start": 1223,
"end": 1832
} | class ____:
"""Represents the diff information for changes between assets.
Change types in change_types should have diff info for their corresponding fields
if diff info is requested.
"NEW" and "REMOVED" change types do not have diff info.
"""
change_types: Set[AssetDefinitionChangeType]
... | AssetDefinitionDiffDetails |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/vertex_ai/test_batch_prediction_job.py | {
"start": 6725,
"end": 10643
} | class ____:
def setup_method(self):
with mock.patch(
BASE_STRING.format("GoogleBaseHook.__init__"), new=mock_base_gcp_hook_no_default_project_id
):
self.hook = BatchPredictionJobHook(gcp_conn_id=TEST_GCP_CONN_ID)
@mock.patch(BATCH_PREDICTION_JOB_STRING.format("BatchPredi... | TestBatchPredictionJobWithoutDefaultProjectIdHook |
python | mkdocstrings__mkdocstrings | src/mkdocstrings/_internal/handlers/base.py | {
"start": 2099,
"end": 2729
} | class ____(Exception): # noqa: N818
"""An exception raised to tell a theme is not supported."""
def do_any(seq: Sequence, attribute: str | None = None) -> bool:
"""Check if at least one of the item in the sequence evaluates to true.
The `any` builtin as a filter for Jinja templates.
Arguments:
... | ThemeNotSupported |
python | huggingface__transformers | src/transformers/models/mllama/modeling_mllama.py | {
"start": 70975,
"end": 79957
} | class ____(MllamaPreTrainedModel, GenerationMixin):
_checkpoint_conversion_mapping = {
r"^language_model.model": "model.language_model",
r"^vision_model": "model.vision_model",
r"^multi_modal_projector": "model.multi_modal_projector",
r"^language_model.lm_head": "lm_head",
}
... | MllamaForConditionalGeneration |
python | faif__python-patterns | patterns/creational/builder.py | {
"start": 1279,
"end": 1622
} | class ____:
def __init__(self) -> None:
self.build_floor()
self.build_size()
def build_floor(self):
raise NotImplementedError
def build_size(self):
raise NotImplementedError
def __repr__(self) -> str:
return "Floor: {0.floor} | Size: {0.size}".format(self)
# ... | Building |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/operators/test_asb.py | {
"start": 5208,
"end": 8804
} | class ____:
@pytest.mark.parametrize(
("mock_message", "mock_batch_flag", "mock_message_id", "mock_reply_to", "mock_headers"),
[
(MESSAGE, True, None, None, None),
(MESSAGE, False, "test_message_id", "test_reply_to", {"test_header": "test_value"}),
(MESSAGE_LIST, ... | TestAzureServiceBusSendMessageOperator |
python | coleifer__peewee | peewee.py | {
"start": 176039,
"end": 179666
} | class ____(BigIntegerField):
# Support second -> microsecond resolution.
valid_resolutions = [10**i for i in range(7)]
def __init__(self, *args, **kwargs):
self.resolution = kwargs.pop('resolution', None)
if not self.resolution:
self.resolution = 1
elif self.resolution ... | TimestampField |
python | django__django | django/contrib/admin/exceptions.py | {
"start": 426,
"end": 507
} | class ____(Exception):
"""The model is not registered."""
pass
| NotRegistered |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/unit_tests/integration/config.py | {
"start": 125,
"end": 1186
} | class ____:
def __init__(self) -> None:
self._config: Dict[str, Any] = {
"credentials": {"option_title": "PAT Credentials", "personal_access_token": "GITHUB_TEST_TOKEN"},
"start_date": "2020-05-01T00:00:00Z",
}
def with_repositories(self, repositories: List[str]) -> "Con... | ConfigBuilder |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 112646,
"end": 116073
} | class ____(GeneratedAirbyteSource):
class GoogleCredentials:
@public
def __init__(
self,
developer_token: str,
client_id: str,
client_secret: str,
refresh_token: str,
access_token: Optional[str] = None,
):
se... | GoogleAdsSource |
python | yaml__pyyaml | lib/yaml/tokens.py | {
"start": 865,
"end": 1109
} | class ____(Token):
id = '<stream start>'
def __init__(self, start_mark=None, end_mark=None,
encoding=None):
self.start_mark = start_mark
self.end_mark = end_mark
self.encoding = encoding
| StreamStartToken |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 18101,
"end": 18612
} | class ____(sgqlc.types.Enum):
"""The possible values for an enabled/disabled enterprise setting.
Enumeration Choices:
* `DISABLED`: The setting is disabled for organizations in the
enterprise.
* `ENABLED`: The setting is enabled for organizations in the
enterprise.
* `NO_POLICY`: There... | EnterpriseEnabledDisabledSettingValue |
python | google__jax | jax/_src/errors.py | {
"start": 717,
"end": 1197
} | class ____:
"""Mixin for JAX-specific errors"""
_error_page = 'https://docs.jax.dev/en/latest/errors.html'
_module_name = "jax.errors"
def __init__(self, message: str):
error_page = self._error_page
module_name = self._module_name
class_name = self.__class__.__name__
error_msg = f'{message}\nSe... | _JAXErrorMixin |
python | python-excel__xlwt | tests/test_unicode1.py | {
"start": 1190,
"end": 1502
} | class ____(unittest.TestCase):
def test_example_xls(self):
create_example_xls(in_tst_output_dir(EXAMPLE_XLS))
self.assertTrue(filecmp.cmp(in_tst_dir(EXAMPLE_XLS),
in_tst_output_dir(EXAMPLE_XLS),
shallow=False))
| TestUnicode1 |
python | pypa__pip | tests/lib/__init__.py | {
"start": 5952,
"end": 6084
} | class ____(AssertionError):
"""
An "assertion" failed during testing.
"""
StrPath = Union[str, pathlib.Path]
| TestFailure |
python | numpy__numpy | numpy/distutils/tests/test_system_info.py | {
"start": 2614,
"end": 3582
} | class ____(system_info):
def __init__(self,
default_lib_dirs=default_lib_dirs,
default_include_dirs=default_include_dirs,
verbosity=1,
):
self.__class__.info = {}
self.local_prefixes = []
defaults = {'library_dirs': '',
... | _system_info |
python | astropy__astropy | astropy/modeling/polynomial.py | {
"start": 715,
"end": 1769
} | class ____(FittableModel):
"""
Base class for all polynomial-like models with an arbitrary number of
parameters in the form of coefficients.
In this case Parameter instances are returned through the class's
``__getattr__`` rather than through class descriptors.
"""
# Default _param_names l... | PolynomialBase |
python | walkccc__LeetCode | solutions/3351. Sum of Good Subsequences/3351.py | {
"start": 0,
"end": 544
} | class ____:
def sumOfGoodSubsequences(self, nums: list[int]) -> int:
MOD = 10**9 + 7
maxNum = max(nums)
# endsIn[i] := the number of good subsequences ending in i
endsIn = [0] * (maxNum + 2)
# dp[i] := the sum of good subsequences ending in i
dp = [0] * (maxNum + 2)
for num in nums:
... | Solution |
python | scipy__scipy | scipy/odr/_odrpack.py | {
"start": 22508,
"end": 42707
} | class ____:
"""
The ODR class gathers all information and coordinates the running of the
main fitting routine.
Members of instances of the ODR class have the same names as the arguments
to the initialization routine.
Parameters
----------
data : Data class instance
instance of ... | ODR |
python | apache__airflow | airflow-core/tests/unit/models/test_taskinstance.py | {
"start": 114641,
"end": 117716
} | class ____:
"""Test TI.xcom_push() correctly records return values for task-mapping."""
def setup_class(self):
"""Ensure we start fresh."""
with create_session() as session:
session.query(TaskMap).delete()
@pytest.mark.parametrize("xcom_value", [[1, 2, 3], {"a": 1, "b": 2}, "ab... | TestTaskInstanceRecordTaskMapXComPush |
python | google__flatbuffers | tests/monster_test_generated.py | {
"start": 2252,
"end": 3170
} | class ____(object):
__slots__ = ['_tab']
@classmethod
def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = InParentNamespace()
x.Init(buf, n + offset)
return x
@classmethod
def GetRootAsInParentNamespace(cls, buf... | InParentNamespace |
python | zarr-developers__zarr-python | src/zarr/errors.py | {
"start": 3502,
"end": 3555
} | class ____(IndexError): ...
| VindexInvalidSelectionError |
python | crytic__slither | slither/solc_parsing/declarations/modifier.py | {
"start": 614,
"end": 3897
} | class ____(FunctionSolc):
def __init__(
self,
modifier: Modifier,
function_data: Dict,
contract_parser: "ContractSolc",
slither_parser: "SlitherCompilationUnitSolc",
) -> None:
super().__init__(modifier, function_data, contract_parser, slither_parser)
# _m... | ModifierSolc |
python | pytorch__pytorch | torch/_inductor/codecache.py | {
"start": 36942,
"end": 41956
} | class ____(Generic[T]):
"""
Mixin for caches that have guards associated with their entries.
"""
@classmethod
def _get_tmp_dir_for_key(cls: type[GuardedCache[T]], _key: str) -> str:
raise NotImplementedError("Implement _get_tmp_dir_for_key on parent class")
@classmethod
def iterate... | GuardedCache |
python | encode__httpx | httpx/_content.py | {
"start": 1681,
"end": 2543
} | class ____(AsyncByteStream):
CHUNK_SIZE = 65_536
def __init__(self, stream: AsyncIterable[bytes]) -> None:
self._stream = stream
self._is_stream_consumed = False
self._is_generator = inspect.isasyncgen(stream)
async def __aiter__(self) -> AsyncIterator[bytes]:
if self._is_s... | AsyncIteratorByteStream |
python | apache__airflow | providers/microsoft/azure/src/airflow/providers/microsoft/azure/hooks/cosmos.py | {
"start": 1901,
"end": 17486
} | class ____(BaseHook):
"""
Interact with Azure CosmosDB.
login should be the endpoint uri, password should be the master key
optionally, you can use the following extras to default these values
{"database_name": "<DATABASE_NAME>", "collection_name": "COLLECTION_NAME"}.
:param azure_cosmos_conn_... | AzureCosmosDBHook |
python | google__flatbuffers | python/flatbuffers/number_types.py | {
"start": 1259,
"end": 1406
} | class ____(object):
bytewidth = 2
min_val = 0
max_val = (2**16) - 1
py_type = int
name = "uint16"
packer_type = packer.uint16
| Uint16Flags |
python | bokeh__bokeh | src/bokeh/models/renderers/glyph_renderer.py | {
"start": 2075,
"end": 8942
} | class ____(DataRenderer):
'''
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@error(CDSVIEW_FILTERS_WITH_CONNECTED)
def _check_cdsview_filters_with_connected(self):
if isinstance(self.... | GlyphRenderer |
python | scipy__scipy | scipy/_build_utils/tempita/_looper.py | {
"start": 1338,
"end": 4011
} | class ____:
def __init__(self, seq, pos):
self.seq = seq
self.pos = pos
def __repr__(self):
return '<loop pos=%r at %r>' % (
self.seq[self.pos], self.pos)
def index(self):
return self.pos
index = property(index)
def number(self):
return self.po... | loop_pos |
python | tensorflow__tensorflow | tensorflow/python/tpu/tpu_hardware_feature.py | {
"start": 892,
"end": 3041
} | class ____(object):
"""class holds all the feature info about the TPU."""
def __init__(self, tpu_hardware_feature_proto):
"""Store TPU hardware feature info.
Args:
tpu_hardware_feature_proto: protobuf which describe the tpu hardware
feature.
"""
self.tpu_hardware_feature_proto = tpu_... | HardwareFeature |
python | kubernetes-client__python | kubernetes/client/models/v1_pod_ip.py | {
"start": 383,
"end": 3466
} | 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... | V1PodIP |
python | sympy__sympy | sympy/matrices/repmatrix.py | {
"start": 1100,
"end": 18762
} | class ____(MatrixBase):
"""Matrix implementation based on DomainMatrix as an internal representation.
The RepMatrix class is a superclass for Matrix, ImmutableMatrix,
SparseMatrix and ImmutableSparseMatrix which are the main usable matrix
classes in SymPy. Most methods on this class are simply forwarde... | RepMatrix |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1400409,
"end": 1402259
} | class ____(VegaLiteSchema):
"""
TimeLocale schema wrapper.
Locale definition for formatting dates and times.
Parameters
----------
date : str
The date (%x) format specifier (e.g., "%m/%d/%Y").
dateTime : str
The date and time (%c) format specifier (e.g., "%a %b %e %X %Y").
... | TimeLocale |
python | ansible__ansible | lib/ansible/_internal/ansible_collections/ansible/_protomatter/plugins/test/tagged_with.py | {
"start": 330,
"end": 453
} | class ____:
@staticmethod
def tests() -> dict[str, t.Callable]:
return dict(tagged_with=tagged_with)
| TestModule |
python | cookiecutter__cookiecutter | cookiecutter/exceptions.py | {
"start": 3899,
"end": 4064
} | class ____(CookiecutterException):
"""
Exception for un-cloneable repo.
Raised when a cookiecutter template can't be cloned.
"""
| RepositoryCloneFailed |
python | pytest-dev__pytest | testing/test_config.py | {
"start": 63080,
"end": 71855
} | class ____:
def test_simple_noini(self, tmp_path: Path, monkeypatch: MonkeyPatch) -> None:
assert get_common_ancestor(Path.cwd(), [tmp_path]) == tmp_path
a = tmp_path / "a"
a.mkdir()
assert get_common_ancestor(Path.cwd(), [a, tmp_path]) == tmp_path
assert get_common_ancestor(... | TestRootdir |
python | doocs__leetcode | solution/1000-1099/1071.Greatest Common Divisor of Strings/Solution2.py | {
"start": 0,
"end": 196
} | class ____:
def gcdOfStrings(self, str1: str, str2: str) -> str:
if str1 + str2 != str2 + str1:
return ''
n = gcd(len(str1), len(str2))
return str1[:n]
| Solution |
python | walkccc__LeetCode | solutions/2215. Find the Difference of Two Arrays/2215.py | {
"start": 0,
"end": 202
} | class ____:
def findDifference(self, nums1: list[int],
nums2: list[int]) -> list[list[int]]:
set1 = set(nums1)
set2 = set(nums2)
return [set1 - set2, set2 - set1]
| Solution |
python | openai__openai-python | tests/test_transform.py | {
"start": 4323,
"end": 4755
} | class ____(TypedDict, total=False):
foo: Annotated[datetime, PropertyInfo(format="iso8601")]
bar: Annotated[Optional[datetime], PropertyInfo(format="iso8601")]
required: Required[Annotated[Optional[datetime], PropertyInfo(format="iso8601")]]
list_: Required[Annotated[Optional[List[datetime]], Propert... | DatetimeDict |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/orchestrator/orchestrator/models/metadata.py | {
"start": 1136,
"end": 1319
} | class ____:
def __getitem__(self, key: str):
return self.__dict__[key]
def __setitem__(self, key: str, value: Any):
self.__dict__[key] = value
| PydanticDictMixin |
python | scipy__scipy | scipy/signal/tests/test_filter_design.py | {
"start": 44831,
"end": 55165
} | class ____:
def test_freqz_sos_basic(self, xp):
# Compare the results of freqz and freqz_sos for a low order
# Butterworth filter.
N = 500
b, a = butter(4, 0.2)
sos = butter(4, 0.2, output='sos')
w, h = freqz(b, a, worN=N)
w, h, sos = map(xp.asarray, (w, h... | TestFreqz_sos |
python | doocs__leetcode | solution/0300-0399/0355.Design Twitter/Solution.py | {
"start": 0,
"end": 1833
} | class ____:
def __init__(self):
"""
Initialize your data structure here.
"""
self.user_tweets = defaultdict(list)
self.user_following = defaultdict(set)
self.tweets = defaultdict()
self.time = 0
def postTweet(self, userId: int, tweetId: int) -> None:
... | Twitter |
python | spack__spack | lib/spack/spack/package_base.py | {
"start": 107139,
"end": 107251
} | class ____(PackageError):
"""Superclass for all errors having to do with extension packages."""
| ExtensionError |
python | pyparsing__pyparsing | examples/simpleBool.py | {
"start": 983,
"end": 1225
} | class ____:
def __init__(self, t):
self.arg = t[0][1]
def __bool__(self) -> bool:
v = bool(self.arg)
return not v
def __str__(self) -> str:
return "~" + str(self.arg)
__repr__ = __str__
| BoolNot |
python | django__django | django/forms/fields.py | {
"start": 19459,
"end": 20476
} | class ____(Field):
default_error_messages = {
"invalid": _("Enter a valid duration."),
"overflow": _("The number of days must be between {min_days} and {max_days}."),
}
def prepare_value(self, value):
if isinstance(value, datetime.timedelta):
return duration_string(value... | DurationField |
python | PyCQA__bandit | bandit/core/utils.py | {
"start": 2644,
"end": 2909
} | class ____(Exception):
"""Raised when the config file fails validation."""
def __init__(self, message, config_file):
self.config_file = config_file
self.message = f"{config_file} : {message}"
super().__init__(self.message)
| ConfigError |
python | Textualize__textual | src/textual/widgets/_key_panel.py | {
"start": 3771,
"end": 5569
} | class ____(VerticalScroll, can_focus=False):
"""
Shows bindings for currently focused widget.
"""
DEFAULT_CSS = """
KeyPanel {
split: right;
width: 33%;
min-width: 30;
max-width: 60;
border-left: vkey $foreground 30%;
padding: 0 1;
height: 1fr... | KeyPanel |
python | kamyu104__LeetCode-Solutions | Python/check-if-two-expression-trees-are-equivalent.py | {
"start": 214,
"end": 1560
} | class ____(object):
def checkEquivalence(self, root1, root2):
"""
:type root1: Node
:type root2: Node
:rtype: bool
"""
def add_counter(counter, prev, d, val):
if val.isalpha():
counter[ord(val)-ord('a')] += d if prev[0] == '+' else -d
... | Solution |
python | pytorch__pytorch | torch/fx/graph_module.py | {
"start": 5385,
"end": 13310
} | class ____(torch.nn.Module):
def __init__(self, body):
super().__init__()
self.__dict__ = body
def _deserialize_graph_module(
forward, body: dict[Any, Any], graph_module_cls=None
) -> torch.nn.Module:
"""
Deserialize a GraphModule given the dictionary of the original module,
using ... | _CodeOnlyModule |
python | Pylons__pyramid | docs/quick_tutorial/forms/tutorial/tests.py | {
"start": 431,
"end": 1800
} | class ____(unittest.TestCase):
def setUp(self):
from tutorial import main
app = main({})
from webtest import TestApp
self.testapp = TestApp(app)
def tearDown(self):
testing.tearDown()
def test_home(self):
res = self.testapp.get('/', status=200)
sel... | TutorialFunctionalTests |
python | django__django | django/template/exceptions.py | {
"start": 1208,
"end": 1342
} | class ____(Exception):
"""
The exception used for syntax errors during parsing or rendering.
"""
pass
| TemplateSyntaxError |
python | numpy__numpy | numpy/lib/tests/test_io.py | {
"start": 1002,
"end": 1948
} | class ____(BytesIO):
"""Helper IO class.
Writes encode strings to bytes if needed, reads return bytes.
This makes it easier to emulate files opened in binary mode
without needing to explicitly convert strings to bytes in
setting up the test data.
"""
def __init__(self, s=""):
Bytes... | TextIO |
python | getsentry__sentry | src/sentry/api/endpoints/organization_onboarding_continuation_email.py | {
"start": 794,
"end": 1762
} | class ____(CamelSnakeSerializer):
platforms = serializers.ListField(
child=serializers.CharField(max_length=255),
)
def get_request_builder_args(user: User, organization: Organization, platforms: list[str]):
num_platforms = len(platforms)
context = {
"recipient_name": user.get_display_... | OnboardingContinuationSerializer |
python | automl__auto-sklearn | test/test_pipeline/components/regression/test_k_nearest_neighbors.py | {
"start": 191,
"end": 793
} | class ____(BaseRegressionComponentTest):
__test__ = True
res = dict()
res["default_boston"] = 0.18393287980040374
res["default_boston_iterative"] = None
res["default_boston_sparse"] = -0.23029229186279609
res["default_boston_iterative_sparse"] = None
res["default_diabetes"] = 0.06860045634... | KNearestNeighborsComponentTest |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/compute.py | {
"start": 1954,
"end": 3228
} | class ____(GoogleCloudBaseOperator):
"""Abstract base operator for Google Compute Engine operators to inherit from."""
def __init__(
self,
*,
zone: str,
resource_id: str | None = None,
project_id: str = PROVIDE_PROJECT_ID,
gcp_conn_id: str = "google_cloud_default... | ComputeEngineBaseOperator |
python | psf__black | tests/data/cases/preview_long_strings__regression.py | {
"start": 20,
"end": 691
} | class ____:
def foo():
result = type(message)("")
# Don't merge multiline (e.g. triple-quoted) strings.
def foo():
query = (
"""SELECT xxxxxxxxxxxxxxxxxxxx(xxx)"""
""" FROM xxxxxxxxxxxxxxxx WHERE xxxxxxxxxx AND xxx <> xxxxxxxxxxxxxx()""")
# There was a bug where tuples were being iden... | A |
python | rapidsai__cudf | python/cudf/cudf/pandas/module_accelerator.py | {
"start": 11089,
"end": 23140
} | class ____(ModuleAcceleratorBase):
"""
A finder and loader that produces "accelerated" modules.
When someone attempts to import the specified slow library with
this finder enabled, we intercept the import and deliver an
equivalent, accelerated, version of the module. This provides
attributes an... | ModuleAccelerator |
python | huggingface__transformers | tests/models/clipseg/test_modeling_clipseg.py | {
"start": 12092,
"end": 15171
} | class ____:
def __init__(
self,
parent,
text_kwargs=None,
vision_kwargs=None,
is_training=True,
# This should respect the `num_hidden_layers` in `CLIPSegVisionModelTester`
extract_layers=(1,),
):
if text_kwargs is None:
text_kwargs = {}... | CLIPSegModelTester |
python | huggingface__transformers | src/transformers/models/fnet/modeling_fnet.py | {
"start": 7303,
"end": 7634
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
def forward(self, hidden_states, input_tensor):
hidden_states = self.LayerNorm(input_tensor + hidden_states)
return hidden_states
| FNetBasicOutput |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.