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
numpy__numpy
numpy/lib/tests/test_index_tricks.py
{ "start": 19552, "end": 24407 }
class ____: def test_diag_indices_from(self): x = np.random.random((4, 4)) r, c = diag_indices_from(x) assert_array_equal(r, np.arange(4)) assert_array_equal(c, np.arange(4)) def test_error_small_input(self): x = np.ones(7) with assert_raises_regex(ValueError, "...
TestDiagIndicesFrom
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/functions.py
{ "start": 56480, "end": 56602 }
class ____(ReturnTypeFromArgs[_T]): # noqa: A001 """The SQL MAX() aggregate function.""" inherit_cache = True
max
python
spack__spack
lib/spack/spack/resource.py
{ "start": 289, "end": 754 }
class ____: """Represents any resource to be fetched by a package. This includes the main tarball or source archive, as well as extra archives defined by the resource() directive. Aggregates a name, a fetcher, a destination and a placement. """ def __init__(self, name, fetcher, destination, p...
Resource
python
airbytehq__airbyte
airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/tests/test_core.py
{ "start": 33461, "end": 35216 }
class ____(BaseTest): async def test_check(self, connector_config, inputs: ConnectionTestConfig, docker_runner: ConnectorRunner): if inputs.status == ConnectionTestConfig.Status.Succeed: output = await docker_runner.call_check(config=connector_config) con_messages = filter_output(out...
TestConnection
python
huggingface__transformers
src/transformers/modeling_outputs.py
{ "start": 63928, "end": 68152 }
class ____(ModelOutput): """ Base class for outputs of sequence-to-sequence sentence classification models. Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `label` is provided): Classification (or regression if config.num_labels==1) loss. logits (`torc...
Seq2SeqSequenceClassifierOutput
python
huggingface__transformers
src/transformers/models/mask2former/modeling_mask2former.py
{ "start": 49367, "end": 53382 }
class ____(nn.Module): def __init__(self, config: Mask2FormerConfig): super().__init__() self.embed_dim = config.feature_size self.self_attn = Mask2FormerPixelDecoderEncoderMultiscaleDeformableAttention( embed_dim=self.embed_dim, num_heads=config.num_attention_heads, ...
Mask2FormerPixelDecoderEncoderLayer
python
getsentry__sentry
tests/sentry/integrations/api/endpoints/test_user_organizationintegration.py
{ "start": 951, "end": 2309 }
class ____(APITestCase): endpoint = "sentry-api-0-user-organization-integrations" method = "get" def setUp(self) -> None: super().setUp() self.login_as(self.user) def test_simple(self) -> None: integration = self.create_provider_integration(provider="github") self.crea...
UserOrganizationIntegationTest
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_remove_timezone.py
{ "start": 617, "end": 2382 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("remove_timezone01.xlsx") def test_remove_timezone_none(self): """Test write_datetime without timezones.""" workbook = Workbook(sel...
TestCompareXLSXFiles
python
huggingface__transformers
src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py
{ "start": 133920, "end": 134646 }
class ____(nn.Module): def __init__(self, dim): super().__init__() self.silu = nn.SiLU() self.linear = nn.Linear(dim, dim * 6) self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6) def forward(self, hidden_states, emb=None): emb = self.linear(self.silu(emb)...
Qwen2_5_OmniAdaLayerNormZero
python
PrefectHQ__prefect
src/prefect/utilities/importtools.py
{ "start": 9358, "end": 17760 }
class ____(Loader): def __init__( self, alias: str, callback: Optional[Callable[[str], None]], real_spec: ModuleSpec, ): self.alias = alias self.callback = callback self.real_spec = real_spec def exec_module(self, module: ModuleType) -> None: ...
AliasedModuleLoader
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-clarifai/llama_index/llms/clarifai/base.py
{ "start": 754, "end": 7799 }
class ____(LLM): """ Clarifai LLM. Examples: `pip install llama-index-llms-clarifai` ```python from llama_index.llms.clarifai import Clarifai llm = Clarifai( user_id="clarifai", app_id="ml", model_name="llama2-7b-alternative-4k", ...
Clarifai
python
kamyu104__LeetCode-Solutions
Python/checking-existence-of-edge-length-limited-paths-ii.py
{ "start": 5133, "end": 6378 }
class ____(object): # Time: O(n * α(n)), Space: O(n) def __init__(self, n): self.snap_id = 0 self.set = SnapshotArray(n) for i in xrange(n): self.set.set(i, i, self.snap_id) self.rank = SnapshotArray(n) def find_set(self, x, snap_id): stk = [] while...
VersionedUnionFind
python
django__django
django/db/migrations/questioner.py
{ "start": 303, "end": 3478 }
class ____: """ Give the autodetector responses to questions it might have. This base class has a built-in noninteractive mode, but the interactive subclass is what the command-line arguments will use. """ def __init__(self, defaults=None, specified_apps=None, dry_run=None): self.defaul...
MigrationQuestioner
python
PrefectHQ__prefect
src/integrations/prefect-kubernetes/prefect_kubernetes/worker.py
{ "start": 6723, "end": 6928 }
class ____(enum.Enum): """Enum representing the image pull policy options for a Kubernetes job.""" IF_NOT_PRESENT = "IfNotPresent" ALWAYS = "Always" NEVER = "Never"
KubernetesImagePullPolicy
python
ansible__ansible
test/lib/ansible_test/_internal/http.py
{ "start": 3041, "end": 3649 }
class ____: """HTTP response.""" def __init__(self, method: str, url: str, status_code: int, response: str) -> None: self.method = method self.url = url self.status_code = status_code self.response = response def json(self) -> t.Any: """Return the response parsed as...
HttpResponse
python
jazzband__django-formtools
formtools/wizard/storage/base.py
{ "start": 162, "end": 4998 }
class ____: step_key = 'step' step_data_key = 'step_data' step_files_key = 'step_files' extra_data_key = 'extra_data' def __init__(self, prefix, request=None, file_storage=None): self.prefix = 'wizard_%s' % prefix self.request = request self.file_storage = file_storage ...
BaseStorage
python
crytic__slither
slither/core/declarations/solidity_variables.py
{ "start": 5343, "end": 5923 }
class ____(SolidityVariable): def _check_name(self, name: str) -> None: assert name in SOLIDITY_VARIABLES_COMPOSED @property def name(self) -> str: return self._name @property def type(self) -> ElementaryType: return ElementaryType(SOLIDITY_VARIABLES_COMPOSED[self.name]) ...
SolidityVariableComposed
python
openai__openai-python
src/openai/types/responses/web_search_tool.py
{ "start": 525, "end": 1218 }
class ____(BaseModel): city: Optional[str] = None """Free text input for the city of the user, e.g. `San Francisco`.""" country: Optional[str] = None """ The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user, e.g. `US`. """ region: Optional[str] = None...
UserLocation
python
cython__cython
tests/run/py3k_super.py
{ "start": 2788, "end": 3073 }
class ____: """ >>> obj = D() >>> obj.method(1) 1 >>> obj.method(0) # doctest: +ELLIPSIS Traceback (most recent call last): ... UnboundLocalError: ... '__class__' ... """ def method(self, x): if x: __class__ = x print(__class__)
D
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-baseten/llama_index/llms/baseten/utils.py
{ "start": 648, "end": 4455 }
class ____(BaseModel): """ Model information for Baseten models. Args: id: unique identifier for the model, passed as model parameter for requests model_type: API type (defaults to "chat") client: client name """ id: str model_type: str = "chat" client: str = "Base...
Model
python
great-expectations__great_expectations
contrib/experimental/great_expectations_experimental/expectations/expect_column_values_to_not_be_outliers.py
{ "start": 747, "end": 2419 }
class ____(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. # Please see https://docs.greatexpectations.io/en/latest/reference/core_concepts/metrics.html#metrics # for information on how to choose an id string for your Metric. condition_metric_name = "column_...
ColumnValuesNotOutliers
python
doocs__leetcode
solution/1600-1699/1639.Number of Ways to Form a Target String Given a Dictionary/Solution.py
{ "start": 0, "end": 613 }
class ____: def numWays(self, words: List[str], target: str) -> int: @cache def dfs(i: int, j: int) -> int: if i >= m: return 1 if j >= n: return 0 ans = dfs(i + 1, j + 1) * cnt[j][ord(target[i]) - ord('a')] ans = (ans +...
Solution
python
spack__spack
var/spack/test_repos/spack_repo/tutorial/packages/hdf5/package.py
{ "start": 290, "end": 24954 }
class ____(CMakePackage): """HDF5 is a data model, library, and file format for storing and managing data. It supports an unlimited variety of datatypes, and is designed for flexible and efficient I/O and for high volume and complex data. """ homepage = "https://portal.hdfgroup.org" url = "http...
Hdf5
python
ray-project__ray
python/ray/data/_internal/execution/operators/base_physical_operator.py
{ "start": 9115, "end": 9817 }
class ____(PhysicalOperator): """An operator that has multiple input dependencies and one output. This operator serves as the base for union, zip, etc. """ def __init__( self, data_context: DataContext, *input_ops: LogicalOperator, ): """Create a OneToOneOperator. ...
NAryOperator
python
pytorch__pytorch
torch/testing/_internal/distributed/distributed_test.py
{ "start": 16361, "end": 18928 }
class ____(MultiProcessTestCase): @classmethod def setUpClass(cls): os.environ["MASTER_ADDR"] = str(MASTER_ADDR) # Not setting MASTER_PORT and get a random free port super().setUpClass() def setUp(self): super().setUp() # initialize temp directories initializ...
TestDistBackend
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_relationship.py
{ "start": 97077, "end": 100668 }
class ____( AssertsCompiledSQL, fixtures.DeclarativeMappedTest ): """test for #12843 / discussion #12842""" @classmethod def setup_classes(cls): Base = cls.DeclarativeBasic class LogEntry(ComparableEntity, Base): __tablename__ = "log_entry" id: Mapped[int] = map...
SingleSubclassInRelationship
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/selectable.py
{ "start": 150901, "end": 151103 }
class ____(Enum): UNION = "UNION" UNION_ALL = "UNION ALL" EXCEPT = "EXCEPT" EXCEPT_ALL = "EXCEPT ALL" INTERSECT = "INTERSECT" INTERSECT_ALL = "INTERSECT ALL"
_CompoundSelectKeyword
python
getsentry__sentry
src/sentry/models/releases/util.py
{ "start": 1074, "end": 9515 }
class ____(BaseQuerySet["Release"]): def annotate_prerelease_column(self): """ Adds a `prerelease_case` column to the queryset which is used to properly sort by prerelease. We treat an empty (but not null) prerelease as higher than any other value. """ return self.ann...
ReleaseQuerySet
python
keras-team__keras
keras/src/ops/node.py
{ "start": 154, "end": 4214 }
class ____: """A `Node` describes an operation `__call__()` event. A Keras Function is a DAG with `Node` instances as nodes, and `KerasTensor` instances as edges. Nodes aren't `Operation` instances, because a single operation could be called multiple times, which would result in graph cycles. ...
Node
python
allegroai__clearml
clearml/backend_api/services/v2_9/workers.py
{ "start": 43264, "end": 46023 }
class ____(Request): """ Returns count of active company workers in the selected time range. :param from_date: Starting time (in seconds from epoch) for collecting statistics :type from_date: float :param to_date: Ending time (in seconds from epoch) for collecting statistics :type to_da...
GetActivityReportRequest
python
dagster-io__dagster
python_modules/dagster/dagster_tests/storage_tests/test_event_log.py
{ "start": 1394, "end": 2201 }
class ____(TestEventLogStorage): __test__ = True @pytest.fixture(scope="function", name="storage") def event_log_storage(self, instance): yield instance.event_log_storage @pytest.fixture(name="instance", scope="function") def instance(self): with DagsterInstance.ephemeral() as the_...
TestInMemoryEventLogStorage
python
huggingface__transformers
src/transformers/models/t5/modeling_t5.py
{ "start": 3940, "end": 5230 }
class ____(nn.Module): def __init__(self, config: T5Config): super().__init__() self.wi_0 = nn.Linear(config.d_model, config.d_ff, bias=False) self.wi_1 = nn.Linear(config.d_model, config.d_ff, bias=False) self.wo = nn.Linear(config.d_ff, config.d_model, bias=False) self.drop...
T5DenseGatedActDense
python
cython__cython
Cython/Compiler/PyrexTypes.py
{ "start": 198292, "end": 223624 }
class ____(Exception): def __init__(self, errors, candidate_count): if len(errors) == 1 or len({msg for _, msg in errors}) == 1: _, errmsg = errors[0] elif candidate_count: errmsg = f"no suitable method found (candidates: {candidate_count})" else: # No can...
NoMatchFound
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_M.py
{ "start": 19766, "end": 20837 }
class ____(Benchmark): r""" MultiModal objective function. This class defines the MultiModal global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{MultiModal}}(x) = \left( \sum_{i=1}^n \lvert x_i \rvert \right) \left( \prod_{i...
MultiModal
python
scipy__scipy
scipy/optimize/tests/test_quadratic_assignment.py
{ "start": 7442, "end": 9909 }
class ____(QAPCommonTests): method = "faq" def test_options(self): # cost and distance matrices of QAPLIB instance chr12c rng = np.random.default_rng(4358764578823597324) A, B, opt_perm = chr12c() n = len(A) # check that max_iter is obeying with low input value ...
TestFAQ
python
django-import-export__django-import-export
tests/core/tests/test_widgets.py
{ "start": 24846, "end": 27254 }
class ____(TestCase, RowDeprecationTestMixin): def setUp(self): self.widget = widgets.ManyToManyWidget(Category) self.widget_name = widgets.ManyToManyWidget(Category, field="name") self.cat1 = Category.objects.create(name="Cat úňíčóďě") self.cat2 = Category.objects.create(name="Cat 2...
ManyToManyWidget
python
getsentry__sentry
src/sentry/api/bases/organization.py
{ "start": 6440, "end": 6583 }
class ____(OrganizationPermission): scope_map = {"GET": ["project:read", "project:write", "project:admin"]}
OrganizationUserReportsPermission
python
pypa__pip
src/pip/_vendor/resolvelib/resolvers/exceptions.py
{ "start": 817, "end": 1283 }
class ____(ResolverException, Generic[RT, CT]): def __init__(self, candidate: CT, criterion: Criterion[RT, CT]): super().__init__(candidate, criterion) self.candidate = candidate self.criterion = criterion def __str__(self) -> str: return "Provided candidate {!r} does not satisf...
InconsistentCandidate
python
getsentry__sentry
src/sentry/issues/endpoints/organization_group_search_view_details.py
{ "start": 1373, "end": 4939 }
class ____(OrganizationEndpoint): publish_status = { "GET": ApiPublishStatus.EXPERIMENTAL, "PUT": ApiPublishStatus.EXPERIMENTAL, "DELETE": ApiPublishStatus.EXPERIMENTAL, } owner = ApiOwner.ISSUES permission_classes = (GroupSearchViewPermission,) def get(self, request: Reques...
OrganizationGroupSearchViewDetailsEndpoint
python
pennersr__django-allauth
allauth/mfa/webauthn/views.py
{ "start": 2892, "end": 3616 }
class ____(NextRedirectMixin, DeleteView): object: Authenticator # https://github.com/typeddjango/django-stubs/issues/1227 template_name = ( "mfa/webauthn/authenticator_confirm_delete." + account_settings.TEMPLATE_EXTENSION ) success_url = reverse_lazy("mfa_list_webauthn") def get_...
RemoveWebAuthnView
python
PrefectHQ__prefect
tests/test_tasks.py
{ "start": 26881, "end": 27775 }
class ____: def test_task_version_defaults_to_null(self): @task def my_task(): pass assert my_task.version is None def test_task_version_can_be_provided(self): @task(version="test-dev-experimental") def my_task(): pass assert my_task.ver...
TestTaskVersion
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/json.py
{ "start": 2510, "end": 2942 }
class ____(JSONPathType): """JSON Path Type. This is usually required to cast literal values to json path when using json search like function, such as ``jsonb_path_query_array`` or ``jsonb_path_exists``:: stmt = sa.select( sa.func.jsonb_path_query_array( table.c.js...
JSONPATH
python
jazzband__django-model-utils
tests/test_managers/test_join_manager.py
{ "start": 130, "end": 1372 }
class ____(TestCase): def setUp(self) -> None: for i in range(20): BoxJoinModel.objects.create(name=f'name_{i}') JoinItemForeignKey.objects.create( weight=10, belonging=BoxJoinModel.objects.get(name='name_1') ) JoinItemForeignKey.objects.create(weight=20) ...
JoinManagerTest
python
eth-brownie__brownie
brownie/_gui/source.py
{ "start": 279, "end": 5615 }
class ____(ttk.Notebook): def __init__(self, parent): super().__init__(parent) self.root = self._root() self._scope = None self.configure(padding=0) self._frames = [] self.bind_count = 0 self.root.bind("<Left>", self.key_left) self.root.bind("<Right>",...
SourceNoteBook
python
ray-project__ray
rllib/utils/actor_manager.py
{ "start": 6188, "end": 46065 }
class ____: """A manager that is aware of the healthiness of remote actors. .. testcode:: import time import ray from ray.rllib.utils.actor_manager import FaultTolerantActorManager @ray.remote class MyActor: def apply(self, fn): return fn(se...
FaultTolerantActorManager
python
pydantic__pydantic
tests/mypy/outputs/mypy-plugin_ini/plugin_fail_baseConfig.py
{ "start": 5166, "end": 5449 }
class ____(BaseModel): x: str = Field(..., alias=x_alias) z: int class Config: validate_by_name = True DynamicAliasModel2(y='y', z=1) # MYPY: error: Missing named argument "x" for "DynamicAliasModel2" [call-arg] DynamicAliasModel2(x='y', z=1)
DynamicAliasModel2
python
pydata__xarray
xarray/coding/variables.py
{ "start": 24699, "end": 25102 }
class ____(VariableCoder): def encode(self): raise NotImplementedError def decode(self, variable: Variable, name: T_Name = None) -> Variable: if variable.dtype.kind == "O" and variable.encoding.get("dtype", False) is str: variable = variable.astype(variable.encoding["dtype"]) ...
ObjectVLenStringCoder
python
huggingface__transformers
tests/quantization/compressed_tensors_integration/test_compressed_tensors.py
{ "start": 368, "end": 4173 }
class ____(unittest.TestCase): tinyllama_w8a16 = "nm-testing/tinyllama-w8a16-dense" tinyllama_w4a16 = "nm-testing/tinyllama-w4a16-compressed" tinyllama_w8a8 = "nm-testing/tinyllama-w8a8-compressed" llama3_8b_fp8 = "nm-testing/Meta-Llama-3-8B-Instruct-fp8-hf_compat" prompt = "Paris is the capital of...
CompressedTensorsTest
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/cloud_memorystore.py
{ "start": 25184, "end": 29040 }
class ____(GoogleCloudBaseOperator): """ Lists all Redis instances owned by a project in either the specified location (region) or all locations. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudMemorystoreListInstancesOperat...
CloudMemorystoreListInstancesOperator
python
pypa__pip
src/pip/_vendor/distlib/util.py
{ "start": 51863, "end": 52967 }
class ____(xmlrpclib.Transport): def __init__(self, timeout, use_datetime=0): self.timeout = timeout xmlrpclib.Transport.__init__(self, use_datetime) def make_connection(self, host): h, eh, x509 = self.get_host_info(host) if not self._connection or host != self._connection[0]: ...
Transport
python
lepture__authlib
authlib/oidc/registration/claims.py
{ "start": 133, "end": 17264 }
class ____(BaseClaims): REGISTERED_CLAIMS = [ "token_endpoint_auth_signing_alg", "application_type", "sector_identifier_uri", "subject_type", "id_token_signed_response_alg", "id_token_encrypted_response_alg", "id_token_encrypted_response_enc", "userinf...
ClientMetadataClaims
python
sphinx-doc__sphinx
sphinx/ext/autosummary/__init__.py
{ "start": 5743, "end": 21388 }
class ____(SphinxDirective): """Pretty table containing short signatures and summaries of functions etc. autosummary can also optionally generate a hidden toctree:: node. """ required_arguments = 0 optional_arguments = 0 final_argument_whitespace = False has_content = True option_spec:...
Autosummary
python
apache__airflow
dev/breeze/src/airflow_breeze/utils/kubernetes_utils.py
{ "start": 17814, "end": 19043 }
class ____(NamedTuple): kubernetes_version: str python_version: str def _get_k8s_python_version( index: int, kubernetes_version_array: list[str], python_version_array: list[str] ) -> KubernetesPythonVersion: current_python = python_version_array[index % len(python_version_array)] current_kubernete...
KubernetesPythonVersion
python
getsentry__sentry
tests/sentry/api/test_authentication.py
{ "start": 29026, "end": 31439 }
class ____(TestCase): def test_generate_signature(self) -> None: url = "/test/endpoint" body = b'{"test": "data"}' shared_secrets = ["secret-key"] service_name = "TestService" signature = generate_service_request_signature(url, body, shared_secrets, service_name) as...
TestGenerateServiceRequestSignature
python
PyCQA__pylint
tests/config/test_argparse_config.py
{ "start": 764, "end": 2026 }
class ____: """Tests for the argparse implementation of OptionsProviderMixIn. The logger checker is used as an example checker for this implementation. """ @staticmethod def test_logger_without_options() -> None: """Check that we raise messages when we do not supply any options.""" ...
TestArgparseOptionsProviderMixin
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/declarative_automation/operands/run_operands.py
{ "start": 3795, "end": 6667 }
class ____(SubsetAutomationCondition[AssetKey]): tag_keys: Optional[Set[str]] = None tag_values: Optional[Mapping[str, str]] = None @property @abstractmethod def base_name(self) -> str: ... @property def name(self) -> str: return _get_run_tag_filter_name(self.base_name, self.tag_ke...
NewUpdatesWithRunTagsCondition
python
huggingface__transformers
src/transformers/models/auto/modeling_auto.py
{ "start": 81765, "end": 81877 }
class ____(_BaseAutoModelClass): _model_mapping = MODEL_FOR_MASK_GENERATION_MAPPING
AutoModelForMaskGeneration
python
hynek__structlog
src/structlog/_output.py
{ "start": 8617, "end": 9115 }
class ____: r""" Produce `BytesLogger`\ s. To be used with `structlog.configure`\ 's ``logger_factory``. Args: file: File to print to. (default: `sys.stdout`\ ``.buffer``) Positional arguments are silently ignored. .. versionadded:: 20.2.0 """ __slots__ = ("_file",) def...
BytesLoggerFactory
python
pytorch__pytorch
torch/_numpy/_ndarray.py
{ "start": 8339, "end": 21362 }
class ____: def __init__(self, t=None): if t is None: self.tensor = torch.Tensor() elif isinstance(t, torch.Tensor): self.tensor = t else: raise ValueError( "ndarray constructor is not recommended; prefer" "either array(...)...
ndarray
python
django__django
tests/admin_views/test_breadcrumbs.py
{ "start": 182, "end": 1041 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com", ) def setUp(self): self.client.force_login(self.superuser) def test_brea...
AdminBreadcrumbsTests
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1546058, "end": 1549769 }
class ____(VegaLiteSchema): """ UnitSpec schema wrapper. Base interface for a unit (single-view) specification. Parameters ---------- mark : dict, :class:`Mark`, :class:`AnyMark`, :class:`BoxPlot`, :class:`MarkDef`, :class:`ErrorBar`, :class:`ErrorBand`, :class:`BoxPlotDef`, :class:`ErrorBarDe...
UnitSpec
python
django__django
tests/delete_regress/models.py
{ "start": 636, "end": 768 }
class ____(models.Model): pagecount = models.IntegerField() owner = models.ForeignKey("Child", models.CASCADE, null=True)
Book
python
getsentry__sentry
src/sentry/api/endpoints/internal/mail.py
{ "start": 391, "end": 1917 }
class ____(Endpoint): owner = ApiOwner.HYBRID_CLOUD publish_status = { "GET": ApiPublishStatus.PRIVATE, "POST": ApiPublishStatus.PRIVATE, } permission_classes = (SuperuserPermission,) def get(self, request: Request) -> Response: assert request.user.is_authenticated d...
InternalMailEndpoint
python
pydantic__pydantic
pydantic-core/tests/validators/test_int.py
{ "start": 19265, "end": 21336 }
class ____(float): pass def test_float_subclass() -> None: v = SchemaValidator(cs.int_schema()) v_lax = v.validate_python(FloatSubclass(1)) assert v_lax == 1 assert type(v_lax) == int def test_int_subclass_plain_enum() -> None: v = SchemaValidator(cs.int_schema()) from enum import Enum ...
FloatSubclass
python
PrefectHQ__prefect
src/prefect/utilities/templating.py
{ "start": 992, "end": 16017 }
class ____(NamedTuple): full_match: str name: str type: PlaceholderType def determine_placeholder_type(name: str) -> PlaceholderType: """ Determines the type of a placeholder based on its name. Args: name: The name of the placeholder Returns: The type of the placeholder ...
Placeholder
python
pypa__pip
tests/unit/test_finder.py
{ "start": 4231, "end": 7204 }
class ____: def test_skip_invalid_wheel_link( self, caplog: pytest.LogCaptureFixture, data: TestData ) -> None: """ Test if PackageFinder skips invalid wheel filenames """ caplog.set_level(logging.DEBUG) req = install_req_from_line("invalid") # data.find_...
TestWheel
python
django__django
django/contrib/gis/db/models/lookups.py
{ "start": 3654, "end": 3894 }
class ____(GISLookup): """ The overlaps_left operator returns true if A's bounding box overlaps or is to the left of B's bounding box. """ lookup_name = "overlaps_left" @BaseSpatialField.register_lookup
OverlapsLeftLookup
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/cloud_composer.py
{ "start": 23678, "end": 26401 }
class ____(GoogleCloudBaseOperator): """ List ImageVersions for provided location. :param request: The request object. List ImageVersions in a project and location. :param retry: Designation of what errors, if any, should be retried. :param timeout: The timeout for this request. :param metadat...
CloudComposerListImageVersionsOperator
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-service-now/llama_index/readers/service_now/base.py
{ "start": 855, "end": 7984 }
class ____(BaseModel): """ Manager for custom file parsers with validation and file processing capabilities. Validates that custom parsers are provided for processing different file types. At minimum, an HTML parser must be provided for processing article bodies. """ custom_parsers: Dict[FileT...
CustomParserManager
python
doocs__leetcode
solution/1400-1499/1436.Destination City/Solution.py
{ "start": 0, "end": 160 }
class ____: def destCity(self, paths: List[List[str]]) -> str: s = {a for a, _ in paths} return next(b for _, b in paths if b not in s)
Solution
python
google__pytype
pytype/pyi/types.py
{ "start": 426, "end": 2008 }
class ____(Exception): """Exceptions raised by the parser.""" def __init__(self, msg, line=None, filename=None, column=None, text=None): super().__init__(msg) self._line = line self._filename = filename self._column = column self._text = text @classmethod def from_exc(cls, exc) -> "ParseEr...
ParseError
python
readthedocs__readthedocs.org
readthedocs/oauth/querysets.py
{ "start": 481, "end": 1826 }
class ____(NoReprQuerySet, models.QuerySet): """For models with relations through :py:class:`User`.""" def api(self, user=None): """Return objects for user.""" if not user.is_authenticated: return self.none() queryset = self.filter(users=user) # Exclude repositories...
RelatedUserQuerySet
python
automl__auto-sklearn
autosklearn/pipeline/components/regression/adaboost.py
{ "start": 452, "end": 3133 }
class ____(AutoSklearnRegressionAlgorithm): def __init__(self, n_estimators, learning_rate, loss, max_depth, random_state=None): self.n_estimators = n_estimators self.learning_rate = learning_rate self.loss = loss self.random_state = random_state self.max_depth = max_depth ...
AdaboostRegressor
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1046404, "end": 1047258 }
class ____(VegaLiteSchema): """ Resolve schema wrapper. Defines how scales, axes, and legends from different specs should be combined. Resolve is a mapping from ``scale``, ``axis``, and ``legend`` to a mapping from channels to resolutions. Scales and guides can be resolved to be ``"independent"`` o...
Resolve
python
TheAlgorithms__Python
data_structures/stacks/stack.py
{ "start": 188, "end": 4725 }
class ____[T]: """A stack is an abstract data type that serves as a collection of elements with two principal operations: push() and pop(). push() adds an element to the top of the stack, and pop() removes an element from the top of a stack. The order in which elements come off of a stack are Last I...
Stack
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_stateful.py
{ "start": 31964, "end": 33429 }
class ____(RuleBasedStateMachine): @initialize() def init_a(self): self.a = 0 @rule() def inc(self): self.a += 1 @invariant() def check_a_positive(self): # This will fail if run before the init_a method, but without # @invariant(check_during_init=True) it will o...
TrickyInitMachine
python
realpython__materials
arcade-platformer/arcade_platformer/04_define_player.py
{ "start": 575, "end": 6411 }
class ____(arcade.Window): def __init__(self) -> None: super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) # These lists will hold different sets of sprites self.coins = None self.background = None self.walls = None self.ladders = None self.goals = No...
Platformer
python
allegroai__clearml
clearml/model.py
{ "start": 76727, "end": 107380 }
class ____(BaseModel): """ Create an output model for a Task (experiment) to store the training results. The OutputModel object is always connected to a Task object, because it is instantiated with a Task object as an argument. It is, therefore, automatically registered as the Task's (experiment's) out...
OutputModel
python
mlflow__mlflow
mlflow/store/tracking/dbmodels/models.py
{ "start": 34746, "end": 38189 }
class ____(Base): __tablename__ = "logged_models" model_id = Column(String(36), nullable=False) """ Model ID: `String` (limit 36 characters). *Primary Key* for ``logged_models`` table. """ experiment_id = Column(Integer, nullable=False) """ Experiment ID to which this model belongs: *F...
SqlLoggedModel
python
sympy__sympy
sympy/functions/special/hyper.py
{ "start": 31740, "end": 32285 }
class ____(HyperRep): """ Represent hyper([1/2, 1/2], [3/2], z) == asin(sqrt(z))/sqrt(z). """ @classmethod def _expr_small(cls, z): return asin(sqrt(z))/sqrt(z) @classmethod def _expr_small_minus(cls, z): return asinh(sqrt(z))/sqrt(z) @classmethod def _expr_big(cls, z, n): ...
HyperRep_asin1
python
readthedocs__readthedocs.org
readthedocs/config/tests/test_validation.py
{ "start": 2219, "end": 3067 }
class ____: def test_it_accepts_relative_path(self, tmpdir): tmpdir.mkdir("a directory") validate_path("a directory", str(tmpdir)) def test_it_accepts_files(self, tmpdir): tmpdir.join("file").write("content") validate_path("file", str(tmpdir)) def test_it_accepts_absolute_p...
TestValidatePath
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol1.py
{ "start": 1684, "end": 1735 }
class ____(Protocol[T_co], Generic[T_co]): ...
Proto2
python
tiangolo__fastapi
tests/test_dependency_yield_scope.py
{ "start": 296, "end": 781 }
class ____: def __init__(self) -> None: self.open = True def dep_session() -> Any: s = Session() yield s s.open = False def raise_after_yield() -> Any: yield raise HTTPException(status_code=503, detail="Exception after yield") SessionFuncDep = Annotated[Session, Depends(dep_session...
Session
python
donnemartin__interactive-coding-challenges
recursion_dynamic/fibonacci/test_fibonacci.py
{ "start": 18, "end": 513 }
class ____(unittest.TestCase): def test_fib(self, func): result = [] expected = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] for i in range(len(expected)): result.append(func(i)) self.assertEqual(result, expected) print('Success: test_fib') def main(): test = TestFib(...
TestFib
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI059.py
{ "start": 1216, "end": 1349 }
class ____(Sized, Generic[T]): # Generic already in last place def __init__(self) -> None: self._items: List[T] = []
MyList
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_dlp.py
{ "start": 10557, "end": 11436 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.dlp.CloudDLPHook") def test_delete_inspect_template(self, mock_hook): mock_hook.return_value.delete_inspect_template.return_value = mock.MagicMock() operator = CloudDLPDeleteInspectTemplateOperator( template_id=TEMPLAT...
TestCloudDLPDeleteInspectTemplateOperator
python
scikit-learn__scikit-learn
sklearn/utils/_testing.py
{ "start": 40953, "end": 42609 }
class ____: """Minimal classifier implementation without inheriting from BaseEstimator. This estimator should be tested with: * `check_estimator` in `test_estimator_checks.py`; * within a `Pipeline` in `test_pipeline.py`; * within a `SearchCV` in `test_search.py`. """ def __init__(self, p...
MinimalClassifier
python
ray-project__ray
python/ray/_private/worker.py
{ "start": 48214, "end": 130585 }
class ____(BaseContext, Mapping): """ Context manager for attached drivers. """ dashboard_url: Optional[str] python_version: str ray_version: str ray_commit: str def __init__(self, address_info: Dict[str, Optional[str]]): super().__init__() self.dashboard_url = get_dash...
RayContext
python
allegroai__clearml
clearml/backend_api/services/v2_13/tasks.py
{ "start": 188639, "end": 191077 }
class ____(Request): """ Remove a task from its queue. Fails if task status is not queued. :param task: Task ID :type task: str :param status_reason: Reason for status change :type status_reason: str :param status_message: Extra information regarding status change :type stat...
DequeueRequest
python
google__pytype
build_scripts/build_utils.py
{ "start": 751, "end": 5329 }
class ____: """Utility class to create and manage the build config cache.""" BUILD_CONFIG_CACHE = os.path.join(OUT_DIR, ".build_config.json") def __init__(self, **kwargs): self.py_version = kwargs.get("py_version") self.build_type = kwargs.get("build_type") def save_to_cache_file(self): with open...
BuildConfig
python
lazyprogrammer__machine_learning_examples
rl3/a2c/atari_wrappers.py
{ "start": 1868, "end": 3335 }
class ____(gym.Wrapper): def __init__(self, env): """Make end-of-life == end-of-episode, but only reset on true game over. Done by DeepMind for the DQN and co. since it helps value estimation. """ gym.Wrapper.__init__(self, env) self.lives = 0 self.was_real_done = Tru...
EpisodicLifeEnv
python
SmileyChris__easy-thumbnails
easy_thumbnails/tests/test_files.py
{ "start": 17756, "end": 18916 }
class ____(TestCase): def setUp(self): self.source = BytesIO(b'file-contents') def test_single_fail(self): source_generators = [FakeSourceGenerator(fail=True)] self.assertRaises( ValueError, engine.generate_source_image, self.source, {}, source_generators, fail_...
EngineTest
python
apache__airflow
devel-common/src/tests_common/test_utils/terraform.py
{ "start": 889, "end": 1669 }
class ____(SystemTest): """Base class for Terraform tests.""" TERRAFORM_DIR: str def setup_method(self) -> None: self.execute_cmd(["terraform", "init", "-input=false", self.TERRAFORM_DIR]) self.execute_cmd(["terraform", "plan", "-input=false", self.TERRAFORM_DIR]) self.execute_cmd(...
Terraform
python
tensorflow__tensorflow
tensorflow/python/framework/ops_test.py
{ "start": 23857, "end": 43833 }
class ____(test_util.TensorFlowTestCase): def testTraceback(self): g = ops.Graph() op1 = ops.Operation.from_node_def( ops._NodeDef("None", "op1"), g, [], [dtypes.float32_ref, dtypes.float32] ) self.assertIn("testTraceback", op1.traceback[-2]) @test_util.run_deprecated_v1 def testNoInputs...
OperationTest
python
getsentry__sentry
src/sentry/api/serializers/models/organization.py
{ "start": 31098, "end": 31300 }
class ____( DetailedOrganizationSerializerResponse ): teams: list[TeamSerializerResponse] projects: list[OrganizationProjectResponse]
DetailedOrganizationSerializerWithProjectsAndTeamsResponse
python
kamyu104__LeetCode-Solutions
Python/find-the-k-th-character-in-string-game-ii.py
{ "start": 50, "end": 427 }
class ____(object): def kthCharacter(self, k, operations): """ :type k: int :type operations: List[int] :rtype: str """ result = 0 k -= 1 for i in xrange(min(len(operations), k.bit_length())): if k&(1<<i): result = (result+o...
Solution
python
pydantic__pydantic
pydantic/networks.py
{ "start": 1683, "end": 4147 }
class ____: """Url constraints. Attributes: max_length: The maximum length of the url. Defaults to `None`. allowed_schemes: The allowed schemes. Defaults to `None`. host_required: Whether the host is required. Defaults to `None`. default_host: The default host. Defaults to `None...
UrlConstraints
python
PrefectHQ__prefect
src/integrations/prefect-gcp/prefect_gcp/workers/vertex.py
{ "start": 1908, "end": 8693 }
class ____(BaseVariables): """ Default variables for the Vertex AI worker. The schema for this class is used to populate the `variables` section of the default base job template. """ region: str = Field( description="The region where the Vertex AI Job resides.", examples=["us-c...
VertexAIWorkerVariables
python
davidhalter__parso
parso/python/pep8.py
{ "start": 1143, "end": 1621 }
class ____(object): type = IndentationTypes.SUITE def __init__(self, config, indentation, parent=None): self.bracket_indentation = self.indentation = indentation self.parent = parent def __repr__(self): return '<%s>' % self.__class__.__name__ def get_latest_suite_node(self): ...
IndentationNode
python
kamyu104__LeetCode-Solutions
Python/parse-lisp-expression.py
{ "start": 33, "end": 1212 }
class ____(object): def evaluate(self, expression): """ :type expression: str :rtype: int """ def getval(lookup, x): return lookup.get(x, x) def evaluate(tokens, lookup): if tokens[0] in ('add', 'mult'): a, b = map(int, map(lam...
Solution