language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | apache__airflow | providers/google/src/airflow/providers/google/marketing_platform/operators/analytics_admin.py | {
"start": 1667,
"end": 5130
} | class ____(GoogleCloudBaseOperator):
"""
Lists all accounts to which the user has access.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:GoogleAnalyticsAdminListAccountsOperator`
:param page_size: Optional, number of result... | GoogleAnalyticsAdminListAccountsOperator |
python | pandas-dev__pandas | pandas/tests/io/parser/conftest.py | {
"start": 2222,
"end": 2279
} | class ____(CParser):
low_memory = True
| CParserLowMemory |
python | django-extensions__django-extensions | tests/testapp/jobs/hourly/test_hourly_job.py | {
"start": 122,
"end": 229
} | class ____(HourlyJob):
help = "My sample hourly job."
def execute(self):
HOURLY_JOB_MOCK()
| Job |
python | pypa__pip | src/pip/_internal/cli/parser.py | {
"start": 4589,
"end": 5239
} | class ____(optparse.OptionParser):
def insert_option_group(
self, idx: int, *args: Any, **kwargs: Any
) -> optparse.OptionGroup:
"""Insert an OptionGroup at a given position."""
group = self.add_option_group(*args, **kwargs)
self.option_groups.pop()
self.option_groups.in... | CustomOptionParser |
python | great-expectations__great_expectations | tests/scripts/test_public_api_report.py | {
"start": 11670,
"end": 12835
} | class ____:
@public_api
def example_public_api_method():
pass
@staticmethod
@public_api
def example_public_api_staticmethod():
pass
@classmethod
@public_api
def example_public_api_classmethod(cls):
pass
@some_other_decorator
@public_api
@another_dec... | ExamplePublicAPIClass |
python | doocs__leetcode | solution/0100-0199/0102.Binary Tree Level Order Traversal/Solution.py | {
"start": 192,
"end": 699
} | class ____:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
ans = []
if root is None:
return ans
q = deque([root])
while q:
t = []
for _ in range(len(q)):
node = q.popleft()
t.append(node.val)
... | Solution |
python | falconry__falcon | falcon/bench/queues/queues.py | {
"start": 586,
"end": 820
} | class ____:
def on_put(self, req, resp, tenant_id, queue_name):
pass
def on_get(self, req, resp, tenant_id, queue_name):
pass
def on_delete(self, req, resp, tenant_id, queue_name):
pass
| ItemResource |
python | cython__cython | Cython/Debugger/libpython.py | {
"start": 38593,
"end": 38884
} | class ____(PyObjectPtr):
_typename = 'PyTypeObject'
def _unichr_is_printable(char):
# Logic adapted from Python 3's Tools/unicode/makeunicodedata.py
if char == " ":
return True
import unicodedata
return unicodedata.category(char) not in ("C", "Z")
| PyTypeObjectPtr |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/comms.py | {
"start": 25082,
"end": 25284
} | class ____(BaseModel):
key: str
dag_id: str
run_id: str
task_id: str
map_index: int | None = None
include_prior_dates: bool = False
type: Literal["GetXCom"] = "GetXCom"
| GetXCom |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-rki-covid/source_rki_covid/source.py | {
"start": 22383,
"end": 24291
} | class ____(AbstractSource):
def check_connection(self, logger, config) -> Tuple[bool, any]:
"""
Testing connection availability for the connector.
:param config: the user-input config object conforming to the connector's spec.json
:param logger: logger object
:return Tuple... | SourceRkiCovid |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_searchstrategy.py | {
"start": 3256,
"end": 4373
} | class ____:
x: defaultdict
def test_jsonable_defaultdict():
obj = HasDefaultDict(defaultdict(list))
obj.x["a"] = [42]
assert to_jsonable(obj, avoid_realization=False) == {"x": {"a": [42]}}
def test_jsonable_namedtuple():
Obj = namedtuple("Obj", ("x"))
obj = Obj(10)
assert to_jsonable(obj... | HasDefaultDict |
python | pytorch__pytorch | torch/distributed/algorithms/_comm_hooks/default_hooks.py | {
"start": 93,
"end": 1353
} | class ____:
r"""
Stores state needed to perform the default communication algorithm within a communication hook.
Args:
process_group (ProcessGroup): The process group to be used.
"""
__slots__ = [
"process_group",
"world_size",
"gradient_predivide_factor",
"... | DefaultState |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/modal_screen_bindings.py | {
"start": 557,
"end": 893
} | class ____(App):
BINDINGS = [("enter", "open_dialog", "Open Dialog")]
def compose(self) -> ComposeResult:
yield Header()
yield Label("Hello")
yield Footer()
def action_open_dialog(self) -> None:
self.push_screen(Dialog())
if __name__ == "__main__":
app = ModalApp()
... | ModalApp |
python | google__jax | jax/_src/numpy/error.py | {
"start": 5050,
"end": 6519
} | class ____:
"""A context manager to set the error checking behavior.
If both `all` and a category are provided, the category will override the
`all` setting.
When the error checking behavior is set to "ignore", all errors will be
ignored. When set to "raise", errors will be detected and recorded, but an
e... | error_checking_behavior |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/athena/resources.py | {
"start": 7973,
"end": 8093
} | class ____(FakeAthenaClient):
"""This class was used by the function-style fake Athena resource."""
| FakeAthenaResource |
python | kubernetes-client__python | kubernetes/client/models/v1_csi_driver_spec.py | {
"start": 383,
"end": 24338
} | 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... | V1CSIDriverSpec |
python | sqlalchemy__sqlalchemy | test/ext/test_horizontal_shard.py | {
"start": 36456,
"end": 39134
} | class ____(fixtures.DeclarativeMappedTest):
"""illustrate the test case for #4376"""
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
from sqlalchemy.ext.associationproxy import association_proxy
class Book(Base):
__tablename__ = "book"
id =... | UseAssocProxForM2MTest |
python | readthedocs__readthedocs.org | readthedocs/core/forms.py | {
"start": 1811,
"end": 2255
} | class ____(forms.ModelForm):
username = CharField(
label=_("Username"),
help_text=_("Please type your username to confirm."),
)
class Meta:
model = User
fields = ["username"]
def clean_username(self):
data = self.cleaned_data["username"]
if self.instanc... | UserDeleteForm |
python | getsentry__sentry | src/sentry/notifications/notification_action/group_type_notification_registry/handlers/issue_alert_registry_handler.py | {
"start": 570,
"end": 1330
} | class ____(LegacyRegistryHandler):
@staticmethod
def handle_workflow_action(job: WorkflowEventData, action: Action, detector: Detector) -> None:
try:
handler = issue_alert_handler_registry.get(action.type)
handler.invoke_legacy_registry(job, action, detector)
except NoReg... | IssueAlertRegistryHandler |
python | numpy__numpy | benchmarks/benchmarks/bench_io.py | {
"start": 5312,
"end": 6153
} | class ____(Benchmark):
# pandas has a similar CSV reading benchmark
# modified to suit np.loadtxt
params = [550, 1000, 10000]
param_names = ['size']
def setup(self, size):
arr = np.arange(size).astype('uint64') + 2**63
self.data1 = StringIO('\n'.join(arr.astype(str).tolist()))
... | LoadtxtReadUint64Integers |
python | scipy__scipy | scipy/spatial/tests/test_kdtree.py | {
"start": 7398,
"end": 9107
} | class ____:
def setup_method(self):
self.data = np.array([[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, ... | Test_vectorization_cKDTree |
python | matplotlib__matplotlib | lib/matplotlib/dates.py | {
"start": 59985,
"end": 62303
} | class ____(DateLocator):
"""
Make ticks on regular intervals of one or more microsecond(s).
.. note::
By default, Matplotlib uses a floating point representation of time in
days since the epoch, so plotting data with
microsecond time resolution does not work well for
dates ... | MicrosecondLocator |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli_tests/cli_tests/defs_state_tests/sample_state_backed_component.py | {
"start": 289,
"end": 1422
} | class ____(StateBackedComponent, dg.Model, dg.Resolvable):
fail_write: bool = False
defs_state_key_id: Optional[str] = None
defs_state: ResolvedDefsStateConfig = DefsStateConfigArgs.versioned_state_storage()
@property
def defs_state_config(self) -> DefsStateConfig:
default_key = self.__clas... | SampleStateBackedComponent |
python | getsentry__sentry | src/sentry/taskworker/registry.py | {
"start": 7877,
"end": 9996
} | class ____:
"""
Registry of all namespaces.
The TaskRegistry is responsible for handling namespace -> topic resolution
during startup.
"""
def __init__(self) -> None:
self._namespaces: dict[str, TaskNamespace] = {}
self._router = self._build_router()
def _build_router(self... | TaskRegistry |
python | facebook__pyre-check | client/commands/infer.py | {
"start": 14230,
"end": 14582
} | class ____:
name: str
annotation: TypeAnnotation
has_default: bool
def to_stub(self) -> str:
delimiter = "=" if self.annotation.missing else " = "
value = f"{delimiter}..." if self.has_default else ""
return f"{self.name}{self.annotation.to_stub(prefix=': ')}{value}"
@dataclas... | Parameter |
python | getsentry__sentry | src/sentry/hybridcloud/services/organizationmember_mapping/service.py | {
"start": 517,
"end": 1710
} | class ____(RpcService):
key = "organizationmember_mapping"
local_mode = SiloMode.CONTROL
@classmethod
def get_local_implementation(cls) -> RpcService:
from sentry.hybridcloud.services.organizationmember_mapping.impl import (
DatabaseBackedOrganizationMemberMappingService,
)
... | OrganizationMemberMappingService |
python | getsentry__sentry | tests/sentry/workflow_engine/endpoints/test_organization_workflow_details.py | {
"start": 1452,
"end": 2206
} | class ____(OrganizationWorkflowDetailsBaseTest):
def test_simple(self) -> None:
workflow = self.create_workflow(organization_id=self.organization.id)
response = self.get_success_response(self.organization.slug, workflow.id)
assert response.data == serialize(workflow)
def test_does_not_e... | OrganizationWorkflowIndexGetTest |
python | django__django | django/contrib/admindocs/views.py | {
"start": 2137,
"end": 3735
} | class ____(BaseAdminDocsView):
template_name = "admin_doc/template_tag_index.html"
def get_context_data(self, **kwargs):
tags = []
try:
engine = Engine.get_default()
except ImproperlyConfigured:
# Non-trivial TEMPLATES settings aren't supported (#24125).
... | TemplateTagIndexView |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/constructors.py | {
"start": 4546,
"end": 4639
} | class ____:
def __init__(self):
self.foo = _test_source()
| SanitizeSingleTraceSource |
python | getsentry__sentry | src/sentry/search/events/fields.py | {
"start": 81955,
"end": 83015
} | class ____(DiscoverFunction):
def __init__(self, *args, **kwargs) -> None:
self.snql_aggregate = kwargs.pop("snql_aggregate", None)
self.snql_column = kwargs.pop("snql_column", None)
self.requires_other_aggregates = kwargs.pop("requires_other_aggregates", False)
super().__init__(*arg... | SnQLFunction |
python | getsentry__sentry | tests/sentry/test_no_create_or_update_usage.py | {
"start": 1925,
"end": 2013
} | class ____:
file_path: str
line: int
col: int
qualified_context: str
| Usage |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 36627,
"end": 36834
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("RSA_SHA1", "RSA_SHA256", "RSA_SHA384", "RSA_SHA512")
| SamlSignatureAlgorithm |
python | readthedocs__readthedocs.org | readthedocs/core/migrations/0002_make_userprofile_user_a_onetoonefield.py | {
"start": 133,
"end": 614
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("core", "0001_initial"),
]
operations = [
migrations.AlterField(
model_name="userprofile",
name="user",
field=models.OneToOneField(
related_name="profile",
... | Migration |
python | google__jax | tests/array_test.py | {
"start": 1838,
"end": 34966
} | class ____(jtu.JaxTestCase):
def test_array_impl_name(self):
self.assertEqual(array.ArrayImpl.__name__, "ArrayImpl")
@parameterized.named_parameters(
("mesh_x_y", P("x", "y")),
("mesh_x", P("x")),
("mesh_y", P("y")),
("mesh_none_y", P(None, "y")),
("mesh_xy", P(("x", "y"))),
... | JaxArrayTest |
python | huggingface__transformers | src/transformers/models/sam_hq/modular_sam_hq.py | {
"start": 19997,
"end": 20223
} | class ____(SamVisionModel):
pass
@auto_docstring(
custom_intro="""
Segment Anything Model HQ (SAM-HQ) for generating masks, given an input image and optional 2D location and bounding boxes.
"""
)
| SamHQVisionModel |
python | bokeh__bokeh | src/bokeh/core/serialization.py | {
"start": 5437,
"end": 14973
} | class ____:
""" Convert built-in and custom types into serializable representations.
Not all built-in types are supported (e.g., decimal.Decimal due to
lacking support for fixed point arithmetic in JavaScript).
"""
_encoders: ClassVar[dict[type[Any], Encoder]] = {}
@classmethod
def ... | Serializer |
python | tensorflow__tensorflow | tensorflow/python/feature_column/feature_column_test.py | {
"start": 113823,
"end": 136179
} | class ____(test.TestCase):
def test_raises_if_empty_feature_columns(self):
with self.assertRaisesRegex(ValueError,
'feature_columns must not be empty'):
fc.input_layer(features={}, feature_columns=[])
def test_should_be_dense_column(self):
with self.assertRaisesRegex(... | FunctionalInputLayerTest |
python | lxml__lxml | src/lxml/tests/test_etree.py | {
"start": 203833,
"end": 209627
} | class ____(unittest.TestCase):
etree = etree
def assert_event_tags(self, events, expected):
self.assertEqual([(action, elem.tag) for action, elem in events],
expected)
def test_pull_from_simple_target(self):
class Target:
def start(self, tag, attrib):
... | XMLPullParserTest |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/language/lexer.py | {
"start": 1202,
"end": 11467
} | class ____(object):
EOF = 1
BANG = 2
DOLLAR = 3
PAREN_L = 4
PAREN_R = 5
SPREAD = 6
COLON = 7
EQUALS = 8
AT = 9
BRACKET_L = 10
BRACKET_R = 11
BRACE_L = 12
PIPE = 13
BRACE_R = 14
NAME = 15
VARIABLE = 16
INT = 17
FLOAT = 18
STRING = 19
def get_t... | TokenKind |
python | pytorch__pytorch | torch/_lobpcg.py | {
"start": 10492,
"end": 26514
} | class ____(torch.autograd.Function):
@staticmethod
def forward( # type: ignore[override]
ctx,
A: Tensor,
k: Optional[int] = None,
B: Optional[Tensor] = None,
X: Optional[Tensor] = None,
n: Optional[int] = None,
iK: Optional[Tensor] = None,
niter: ... | LOBPCGAutogradFunction |
python | keras-team__keras | keras/src/ops/math.py | {
"start": 11293,
"end": 13478
} | class ____(Operation):
def compute_output_spec(self, x):
if not isinstance(x, (tuple, list)) or len(x) != 2:
raise ValueError(
"Input `x` should be a tuple of two tensors - real and "
f"imaginary. Received: x={x}"
)
real, imag = x
# Bo... | FFT |
python | getsentry__sentry | src/sentry/uptime/migrations/0049_cleanup_failed_safe_deletes.py | {
"start": 207,
"end": 1704
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | numba__numba | numba/cuda/tests/cudadrv/test_context_stack.py | {
"start": 190,
"end": 679
} | class ____(CUDATestCase):
def setUp(self):
super().setUp()
# Reset before testing
cuda.close()
def test_gpus_current(self):
self.assertIs(cuda.gpus.current, None)
with cuda.gpus[0]:
self.assertEqual(int(cuda.gpus.current.id), 0)
def test_gpus_len(self):
... | TestContextStack |
python | run-llama__llama_index | llama-index-finetuning/llama_index/finetuning/types.py | {
"start": 614,
"end": 922
} | class ____(ABC):
"""Base Embedding finetuning engine."""
@abstractmethod
def finetune(self) -> None:
"""Goes off and does stuff."""
@abstractmethod
def get_finetuned_model(self, **model_kwargs: Any) -> BaseEmbedding:
"""Gets finetuned model."""
| BaseEmbeddingFinetuneEngine |
python | doocs__leetcode | solution/1500-1599/1535.Find the Winner of an Array Game/Solution.py | {
"start": 0,
"end": 312
} | class ____:
def getWinner(self, arr: List[int], k: int) -> int:
mx = arr[0]
cnt = 0
for x in arr[1:]:
if mx < x:
mx = x
cnt = 1
else:
cnt += 1
if cnt == k:
break
return mx
| Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_type_checking/runtime_evaluated_base_classes_5.py | {
"start": 133,
"end": 173
} | class ____(Parent):
baz: DataFrame
| Child |
python | django__django | tests/utils_tests/test_duration.py | {
"start": 196,
"end": 941
} | class ____(unittest.TestCase):
def test_simple(self):
duration = datetime.timedelta(hours=1, minutes=3, seconds=5)
self.assertEqual(duration_string(duration), "01:03:05")
def test_days(self):
duration = datetime.timedelta(days=1, hours=1, minutes=3, seconds=5)
self.assertEqual(d... | TestDurationString |
python | django__django | django/db/models/lookups.py | {
"start": 17132,
"end": 17312
} | class ____(
IntegerFieldOverflow, IntegerFieldFloatRounding, GreaterThanOrEqual
):
underflow_exception = FullResultSet
@IntegerField.register_lookup
| IntegerGreaterThanOrEqual |
python | giampaolo__psutil | tests/test_unicode.py | {
"start": 9388,
"end": 9755
} | class ____(TestFSAPIs):
"""Test FS APIs with a funky, invalid path name."""
funky_suffix = INVALID_UNICODE_SUFFIX
def expect_exact_path_match(self):
return not MACOS
# ===================================================================
# Non fs APIs
# ============================================... | TestFSAPIsWithInvalidPath |
python | tensorflow__tensorflow | tensorflow/tools/test/run_and_gather_logs_lib.py | {
"start": 1030,
"end": 6823
} | class ____(Exception):
pass
def get_git_commit_sha():
"""Get git commit SHA for this build.
Attempt to get the SHA from environment variable GIT_COMMIT, which should
be available on Jenkins build agents.
Returns:
SHA hash of the git commit used for the build, if available
"""
return os.getenv("GI... | MissingLogsError |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 202624,
"end": 202724
} | class ____(
_Int4MultiRangeTests, _MultiRangeTypeRoundTrip
):
pass
| Int4MultiRangeRoundTripTest |
python | huggingface__transformers | src/transformers/models/unispeech_sat/modeling_unispeech_sat.py | {
"start": 12114,
"end": 15492
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
embed_dim: int,
num_heads: int,
dropout: float = 0.0,
is_decoder: bool = False,
bias: bool = True,
is_causal: bool = False,
config: Opti... | UniSpeechSatAttention |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chartsheet02.py | {
"start": 315,
"end": 1507
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chartsheet02.xlsx")
def test_create_file(self):
"""Test the worksheet properties of an XlsxWriter chartsheet file."""
workbook = W... | TestCompareXLSXFiles |
python | PrefectHQ__prefect | src/prefect/workers/process.py | {
"start": 3527,
"end": 11902
} | class ____(
BaseWorker[ProcessJobConfiguration, ProcessVariables, ProcessWorkerResult]
):
type = "process"
job_configuration: type[ProcessJobConfiguration] = ProcessJobConfiguration
job_configuration_variables: type[ProcessVariables] | None = ProcessVariables
_description = (
"Execute flow ... | ProcessWorker |
python | getsentry__sentry | tests/sentry/uptime/endpoints/test_project_uptime_alert_details.py | {
"start": 1079,
"end": 9220
} | class ____(ProjectUptimeAlertDetailsBaseEndpointTest):
method = "put"
def test_all(self) -> None:
detector = self.create_uptime_detector()
uptime_sub = get_uptime_subscription(detector)
resp = self.get_success_response(
self.organization.slug,
detector.project.sl... | ProjectUptimeAlertDetailsPutEndpointTest |
python | getsentry__sentry | src/sentry/runner/commands/presenters/presenterdelegator.py | {
"start": 186,
"end": 1182
} | class ____:
def __init__(self, source: str, dry_run: bool, timestamp: float | None = None) -> None:
from sentry.runner.commands.presenters.audit_log_presenter import AuditLogPresenter
self._consolepresenter = ConsolePresenter()
self._slackpresenter = None
if WebhookPresenter.is_web... | PresenterDelegator |
python | pytorch__pytorch | torch/_export/serde/schema.py | {
"start": 6270,
"end": 6466
} | class ____:
# Argument name from the operator schema
name: Annotated[str, 10]
arg: Annotated[Argument, 20]
kind: Annotated[Optional[ArgumentKind], 30] = None
@dataclass
| NamedArgument |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/vk/tests.py | {
"start": 232,
"end": 1065
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = VKProvider.id
def get_mocked_response(self, verified_email=True):
return MockedResponse(
HTTPStatus.OK,
"""
{
"user": {
"user_id": "1234567890",
"first_name": "Ivan",
"last_name": "I.",
"ph... | VKTests |
python | google__jax | tests/pallas/pallas_test.py | {
"start": 72454,
"end": 76611
} | class ____(PallasBaseTest):
def setUp(self):
super().setUp()
if jtu.test_device_matches(["tpu"]):
# TODO: most tests fail on TPU in non-interpret mode
self.skipTest("On TPU the test works only in interpret mode")
# TODO: improve tolerance setting
self.tol = 1e-5
self.grad_tol = jtu.de... | PallasCallAutodifferentiationTest |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 242319,
"end": 247074
} | class ____:
# indices in order [alternative={two-sided, less, greater},
# equal_var={False, True}, trim={0, 0.2}]
# reference values in order `statistic, df, pvalue, low, high`
# equal_var=False reference values computed with R PairedData yuen.t.test:
#
# library(PairedData)
... | Test_ttest_CI |
python | openai__openai-python | src/openai/types/responses/response_input_item_param.py | {
"start": 14129,
"end": 15060
} | class ____(TypedDict, total=False):
id: Required[str]
"""The ID of the item to reference."""
type: Optional[Literal["item_reference"]]
"""The type of item to reference. Always `item_reference`."""
ResponseInputItemParam: TypeAlias = Union[
EasyInputMessageParam,
Message,
ResponseOutputMes... | ItemReference |
python | huggingface__transformers | src/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py | {
"start": 101101,
"end": 109586
} | class ____(BigBirdPegasusPreTrainedModel, GenerationMixin):
base_model_prefix = "model"
_tied_weights_keys = {
"lm_head.weight": "model.shared.weight",
}
_keys_to_ignore_on_load_missing = ["final_logits_bias"]
# Copied from transformers.models.bart.modeling_bart.BartForConditionalGeneration... | BigBirdPegasusForConditionalGeneration |
python | ansible__ansible | test/lib/ansible_test/_internal/commands/integration/coverage.py | {
"start": 9371,
"end": 12681
} | class ____(CoverageHandler[WindowsConfig]):
"""Configure integration test code coverage for Windows hosts."""
def __init__(self, args: IntegrationConfig, host_state: HostState, inventory_path: str) -> None:
super().__init__(args, host_state, inventory_path)
# Common temporary directory used on... | WindowsCoverageHandler |
python | scikit-learn__scikit-learn | sklearn/linear_model/_passive_aggressive.py | {
"start": 11969,
"end": 21162
} | class ____(BaseSGDRegressor):
"""Passive Aggressive Regressor.
.. deprecated:: 1.8
The whole class `PassiveAggressiveRegressor` was deprecated in version 1.8
and will be removed in 1.10. Instead use:
.. code-block:: python
reg = SGDRegressor(
loss="epsilon_... | PassiveAggressiveRegressor |
python | tensorflow__tensorflow | tensorflow/python/distribute/combinations.py | {
"start": 16212,
"end": 24737
} | class ____(object):
"""Holds the test environment information.
Tests should modify the attributes of the instance returned by `env()` in the
main process if needed, and it will be passed to the worker processes each
time a test case is run.
"""
def __init__(self):
self.tf_data_service_dispatcher = Non... | TestEnvironment |
python | apache__airflow | providers/standard/tests/unit/standard/operators/test_python.py | {
"start": 15951,
"end": 24744
} | class ____(BasePythonTest):
opcls = BranchPythonOperator
@pytest.fixture(autouse=True)
def setup_tests(self):
self.branch_1 = EmptyOperator(task_id="branch_1")
self.branch_2 = EmptyOperator(task_id="branch_2")
def test_with_dag_run(self):
clear_db_runs()
with self.dag_m... | TestBranchOperator |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py | {
"start": 163852,
"end": 166519
} | class ____(Qwen2_5OmniPreTrainedModel):
config: Qwen2_5OmniToken2WavConfig
base_model_prefix = "model"
input_modalities = "audio"
_no_split_modules = ["Qwen2_5OmniToken2WavDiTModel", "Qwen2_5OmniToken2WavBigVGANModel"]
def __init__(self, config: Qwen2_5OmniToken2WavConfig):
super().__init__... | Qwen2_5OmniToken2WavModel |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/guides/dagster/dagster_pipes/dagster_pipes_details_and_customization/custom_message_writer.py | {
"start": 615,
"end": 1055
} | class ____(PipesBlobStoreMessageWriterChannel):
def __init__(self, key_prefix: str):
super().__init__()
self.key_prefix = key_prefix
# This will be called periodically to upload any buffered messages
def upload_messages_chunk(self, payload: IO, index: int) -> None:
key = f"{self.key... | MyCustomCloudServiceMessageWriterChannel |
python | mlflow__mlflow | mlflow/store/model_registry/dbmodels/models.py | {
"start": 4811,
"end": 5738
} | class ____(Base):
__tablename__ = "model_version_tags"
name = Column(String(256))
version = Column(Integer)
key = Column(String(250), nullable=False)
value = Column(Text, nullable=True)
# linked entities
model_version = relationship(
"SqlModelVersion",
foreign_keys=[name... | SqlModelVersionTag |
python | weaviate__weaviate-python-client | weaviate/cluster/models.py | {
"start": 130,
"end": 241
} | class ____(str, Enum):
"""Enum for replication types."""
COPY = "COPY"
MOVE = "MOVE"
| ReplicationType |
python | joke2k__faker | faker/providers/automotive/bn_BD/__init__.py | {
"start": 118,
"end": 4701
} | class ____(AutomotiveProvider):
"""Implement automotive provider for ``bn_BD`` locale.
Sources:
- https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Bangladesh
"""
# noinspection DuplicatedCode
cities = (
"বরগুনা",
"বরিশাল",
"বরিশাল মেট্রো",
"ভোলা",
... | Provider |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/pool/base.py | {
"start": 4230,
"end": 4311
} | class ____(Protocol):
def __call__(self) -> DBAPIConnection: ...
| _CreatorFnType |
python | Farama-Foundation__Gymnasium | gymnasium/wrappers/vector/jax_to_torch.py | {
"start": 332,
"end": 1338
} | class ____(ArrayConversion):
"""Wraps a Jax-based vector environment so that it can be interacted with through PyTorch Tensors.
Actions must be provided as PyTorch Tensors and observations, rewards, terminations and truncations will be returned as PyTorch Tensors.
Example:
>>> import gymnasium as ... | JaxToTorch |
python | PrefectHQ__prefect | src/prefect/settings/models/cli.py | {
"start": 208,
"end": 1045
} | class ____(PrefectBaseSettings):
"""
Settings for controlling CLI behavior
"""
model_config: ClassVar[SettingsConfigDict] = build_settings_config(("cli",))
colors: bool = Field(
default=True,
description="If True, use colors in CLI output. If `False`, output will not include colors... | CLISettings |
python | scipy__scipy | scipy/cluster/tests/test_hierarchy.py | {
"start": 33963,
"end": 35532
} | class ____:
def test_maxinconsts_empty_linkage(self, xp):
# Tests maxinconsts(Z, R) on empty linkage. Expecting exception.
Z = xp.zeros((0, 4), dtype=xp.float64)
R = xp.zeros((0, 4), dtype=xp.float64)
assert_raises(ValueError, maxinconsts, Z, R)
def test_maxinconsts_difrow_link... | TestMaxInconsts |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_axis49.py | {
"start": 315,
"end": 1387
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_axis49.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
python | pandas-dev__pandas | pandas/core/dtypes/dtypes.py | {
"start": 49122,
"end": 51665
} | class ____(ExtensionDtype):
"""
A Pandas ExtensionDtype for NumPy dtypes.
This is mostly for internal compatibility, and is not especially
useful on its own.
Parameters
----------
dtype : object
Object to be converted to a NumPy data type object.
See Also
--------
nump... | NumpyEADtype |
python | astropy__astropy | astropy/tests/runner.py | {
"start": 1399,
"end": 11850
} | class ____:
"""
The base class for the TestRunner.
A test runner can be constructed by creating a subclass of this class and
defining 'keyword' methods. These are methods that have the
``astropy.tests.runner.keyword`` decorator, these methods are used to
construct allowed keyword arguments to t... | TestRunnerBase |
python | django__django | django/contrib/postgres/fields/citext.py | {
"start": 533,
"end": 948
} | class ____(EmailField):
system_check_removed_details = {
"msg": (
"django.contrib.postgres.fields.CIEmailField is removed except for support "
"in historical migrations."
),
"hint": (
'Use EmailField(db_collation="…") with a case-insensitive '
... | CIEmailField |
python | great-expectations__great_expectations | tests/datasource/fluent/test_invalid_datasource.py | {
"start": 3020,
"end": 5546
} | class ____(Protocol):
"""
Accept a datasource config and return an InvalidDatasource instance.
Raises an error if the config was valid.
"""
def __call__(
self, config: dict[Literal["name", "type", "assets"] | Any, Any]
) -> InvalidDatasource: ...
@pytest.fixture
def invalid_datasource... | InvalidDSFactory |
python | jupyterlab__jupyterlab | jupyterlab/handlers/plugin_manager_handler.py | {
"start": 316,
"end": 1915
} | class ____(APIHandler):
def initialize(self, manager: PluginManager):
super().initialize()
self.manager = manager
@web.authenticated
async def get(self):
"""GET query returns info on plugins locks"""
# note: this is informative only - validation is server-side
locks ... | PluginHandler |
python | django__django | tests/fixtures_regress/models.py | {
"start": 1039,
"end": 1147
} | class ____(Parent):
data = models.CharField(max_length=10)
# Models to regression test #7572, #20820
| Child |
python | neetcode-gh__leetcode | python/1985-find-the-kth-largest-integer-in-the-array.py | {
"start": 0,
"end": 256
} | class ____:
def kthLargestNumber(self, nums: List[str], k: int) -> str:
maxHeap = [-int(n) for n in nums]
heapq.heapify(maxHeap)
while k>1:
heapq.heappop(maxHeap)
k-=1
return str(-maxHeap[0])
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1026930,
"end": 1027407
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of UpdateEnterpriseProfile"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "enterprise")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing... | UpdateEnterpriseProfilePayload |
python | kubernetes-client__python | kubernetes/client/models/v1_pod_security_context.py | {
"start": 383,
"end": 23939
} | 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... | V1PodSecurityContext |
python | cherrypy__cherrypy | cherrypy/test/test_states.py | {
"start": 1724,
"end": 9358
} | class ____(helper.CPWebCase):
setup_server = staticmethod(setup_server)
def setUp(self):
cherrypy.server.socket_timeout = 0.1
self.do_gc_test = False
def test_0_NormalStateFlow(self):
engine.stop()
# Our db_connection should not be running
self.assertEqual(db_connec... | ServerStateTests |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/math_ops/reduction_ops_test.py | {
"start": 1822,
"end": 3209
} | class ____(test.TestCase):
def _check(self, shape, axes, result):
output = math_ops.reduced_shape(shape, axes=axes)
self.assertAllEqual(output, result)
@test_util.run_deprecated_v1
def testSimple(self):
with self.cached_session():
self._check([3], [], [3])
self._check([3], [0], [1])
... | ReducedShapeTest |
python | PyCQA__pylint | tests/functional/a/access/access_to_protected_members_typing.py | {
"start": 134,
"end": 912
} | class ____:
"""Class with protected members."""
class _Inner_Class:
"""Inner class with protected members."""
def __init__(self) -> None:
self.data = 1
def return_data(self) -> int:
"""Return data"""
return self.data
def return_private_class(se... | MyClass |
python | catalyst-team__catalyst | examples/detection/custom_runner.py | {
"start": 74,
"end": 666
} | class ____(ConfigRunner):
"""Runner for SSD models."""
def handle_batch(self, batch):
"""Do a forward pass and compute loss.
Args:
batch (Dict[str, Any]): batch of data.
"""
locs, confs = self.model(batch["image"])
regression_loss, classification_loss = sel... | SSDDetectionRunner |
python | sanic-org__sanic | sanic/request/parameters.py | {
"start": 71,
"end": 1130
} | class ____(dict):
"""Hosts a dict with lists as values where get returns the first value of the list and getlist returns the whole shebang""" # noqa: E501
def get(self, name: str, default: Optional[Any] = None) -> Optional[Any]:
"""Return the first value, either the default or actual
Args:
... | RequestParameters |
python | apache__airflow | providers/postgres/tests/unit/postgres/hooks/test_postgres.py | {
"start": 19836,
"end": 21916
} | class ____:
"""PostgresHookConn tests that are specific to psycopg2."""
def setup_method(self):
self.connection = Connection(login="login", password="password", host="host", schema="database")
class UnitTestPostgresHook(PostgresHook):
conn_name_attr = "test_conn_id"
self.d... | TestPostgresHookConnPPG2 |
python | mkdocs__mkdocs | mkdocs/contrib/search/__init__.py | {
"start": 2209,
"end": 5230
} | class ____(BasePlugin[_PluginConfig]):
"""Add a search feature to MkDocs."""
def on_config(self, config: MkDocsConfig, **kwargs) -> MkDocsConfig:
"""Add plugin templates and scripts to config."""
if config.theme.get('include_search_page'):
config.theme.static_templates.add('search.h... | SearchPlugin |
python | Textualize__rich | rich/json.py | {
"start": 189,
"end": 5019
} | class ____:
"""A renderable which pretty prints JSON.
Args:
json (str): JSON encoded data.
indent (Union[None, int, str], optional): Number of characters to indent by. Defaults to 2.
highlight (bool, optional): Enable highlighting. Defaults to True.
skip_keys (bool, optional): S... | JSON |
python | getsentry__sentry | src/sentry/api/serializers/models/team.py | {
"start": 12063,
"end": 12197
} | class ____(TypedDict):
schemas: list[str]
id: str
displayName: str
meta: SCIMMeta
| OrganizationTeamSCIMSerializerRequired |
python | dask__dask | dask/dataframe/dask_expr/_rolling.py | {
"start": 5701,
"end": 5755
} | class ____(RollingReduction):
how = "cov"
| RollingCov |
python | huggingface__transformers | src/transformers/models/canine/modeling_canine.py | {
"start": 31117,
"end": 43556
} | class ____(CaninePreTrainedModel):
def __init__(self, config, add_pooling_layer=True):
r"""
add_pooling_layer (bool, *optional*, defaults to `True`):
Whether to add a pooling layer
"""
super().__init__(config)
self.config = config
shallow_config = copy.dee... | CanineModel |
python | sqlalchemy__sqlalchemy | test/dialect/sqlite/test_dialect.py | {
"start": 22508,
"end": 26439
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
__only_on__ = "sqlite"
__skip_if__ = (full_text_search_missing,)
__backend__ = True
@classmethod
def setup_test_class(cls):
global metadata, cattable, matchtable
metadata = MetaData()
exec_sql(
testing.db,
... | MatchTest |
python | scrapy__scrapy | scrapy/pipelines/files.py | {
"start": 12131,
"end": 14283
} | class ____:
FTP_USERNAME: str | None = None
FTP_PASSWORD: str | None = None
USE_ACTIVE_MODE: bool | None = None
def __init__(self, uri: str):
if not uri.startswith("ftp://"):
raise ValueError(f"Incorrect URI scheme in {uri}, expected 'ftp'")
u = urlparse(uri)
assert ... | FTPFilesStore |
python | google__python-fire | fire/test_components.py | {
"start": 1975,
"end": 2490
} | class ____:
"""Class with functions that have default arguments."""
def double(self, count=0):
"""Returns the input multiplied by 2.
Args:
count: Input number that you want to double.
Returns:
A number that is the double of count.
"""
return 2 * count
def triple(self, count=0):... | WithDefaults |
python | langchain-ai__langchain | libs/partners/groq/tests/unit_tests/fake/callbacks.py | {
"start": 6590,
"end": 9227
} | class ____(AsyncCallbackHandler, BaseFakeCallbackHandlerMixin):
"""Fake async callback handler for testing."""
@property
def ignore_llm(self) -> bool:
"""Whether to ignore LLM callbacks."""
return self.ignore_llm_
@property
def ignore_chain(self) -> bool:
"""Whether to igno... | FakeAsyncCallbackHandler |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.