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 | anthropics__anthropic-sdk-python | tests/test_response.py | {
"start": 8305,
"end": 9592
} | class ____(BaseModel):
a: str
@pytest.mark.parametrize("client", [False], indirect=True) # loose validation
def test_response_parse_expect_model_union_non_json_content(client: Anthropic) -> None:
response = APIResponse(
raw=httpx.Response(200, content=b"foo", headers={"Content-Type": "application/tex... | OtherModel |
python | allegroai__clearml | clearml/backend_api/services/v2_23/frames.py | {
"start": 109850,
"end": 111050
} | class ____(Request):
"""
Get an attachment containing the frames returned by the dataview specified in `prepare_download_for_dataview`
:param prepare_id: Call ID returned by a call to prepare_download_for_dataview
:type prepare_id: str
"""
_service = "frames"
_action = "download_for_datavi... | DownloadForDataviewRequest |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/triggers/dataflow.py | {
"start": 11342,
"end": 17794
} | class ____(BaseTrigger):
"""
Dataflow trigger that checks the state of a Dataflow YAML job.
:param job_id: Required. ID of the job.
:param project_id: Required. The Google Cloud project ID in which the job was started.
:param location: The location where job is executed. If set to None then
... | DataflowStartYamlJobTrigger |
python | ansible__ansible | test/lib/ansible_test/_internal/provisioning.py | {
"start": 920,
"end": 7508
} | class ____:
"""State of hosts and profiles to be passed to ansible-test during delegation."""
controller_profile: ControllerHostProfile
target_profiles: list[HostProfile]
@property
def profiles(self) -> list[HostProfile]:
"""Return all the profiles as a list."""
return [t.cast(Host... | HostState |
python | eventlet__eventlet | eventlet/hubs/asyncio.py | {
"start": 879,
"end": 5961
} | class ____(hub.BaseHub):
"""An Eventlet hub implementation on top of an asyncio event loop."""
def __init__(self):
super().__init__()
# Pre-emptively make sure we're using the right modules:
_unmonkey_patch_asyncio_all()
# The presumption is that eventlet is driving the event ... | Hub |
python | doocs__leetcode | solution/1300-1399/1354.Construct Target Array With Multiple Sums/Solution.py | {
"start": 0,
"end": 398
} | class ____:
def isPossible(self, target: List[int]) -> bool:
s = sum(target)
pq = [-x for x in target]
heapify(pq)
while -pq[0] > 1:
mx = -heappop(pq)
t = s - mx
if t == 0 or mx - t < 1:
return False
x = (mx % t) or t
... | Solution |
python | getsentry__sentry | src/sentry/tagstore/types.py | {
"start": 4984,
"end": 5659
} | class ____(Serializer):
def serialize(self, obj, attrs, user, **kwargs) -> TagValueSerializerResponse:
from sentry import tagstore
key = tagstore.backend.get_standardized_key(obj.key)
serialized: TagValueSerializerResponse = {
"key": key,
"name": tagstore.backend.get... | TagValueSerializer |
python | apache__airflow | providers/google/tests/unit/google/cloud/triggers/test_dataproc.py | {
"start": 13222,
"end": 17670
} | class ____:
def test_async_create_batch_trigger_serialization_should_execute_successfully(self, batch_trigger):
"""
Asserts that the DataprocBatchTrigger correctly serializes its arguments
and classpath.
"""
classpath, kwargs = batch_trigger.serialize()
assert classp... | TestDataprocBatchTrigger |
python | pandas-dev__pandas | pandas/tests/series/test_missing.py | {
"start": 230,
"end": 2593
} | class ____:
def test_categorical_nan_handling(self):
# NaNs are represented as -1 in labels
s = Series(Categorical(["a", "b", np.nan, "a"]))
tm.assert_index_equal(s.cat.categories, Index(["a", "b"]))
tm.assert_numpy_array_equal(
s.values.codes, np.array([0, 1, -1, 0], dty... | TestSeriesMissingData |
python | django__django | tests/aggregation_regress/tests.py | {
"start": 884,
"end": 70015
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.a1 = Author.objects.create(name="Adrian Holovaty", age=34)
cls.a2 = Author.objects.create(name="Jacob Kaplan-Moss", age=35)
cls.a3 = Author.objects.create(name="Brad Dayley", age=45)
cls.a4 = Author.objects.create(nam... | AggregationTests |
python | pdm-project__pdm | src/pdm/project/core.py | {
"start": 1988,
"end": 45321
} | class ____:
"""Core project class.
Args:
core: The core instance.
root_path: The root path of the project.
is_global: Whether the project is global.
global_config: The path to the global config file.
"""
PYPROJECT_FILENAME = "pyproject.toml"
DEPENDENCIES_RE = re.com... | Project |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 132408,
"end": 159525
} | class ____(FuncDefNode):
# A Python function definition.
#
# name string the Python name of the function
# lambda_name string the internal name of a lambda 'function'
# decorators [DecoratorNode] list of decorators
# args [CArgDeclNod... | DefNode |
python | facebook__pyre-check | scripts/pypi/build_pypi_package.py | {
"start": 814,
"end": 11919
} | class ____:
wheel_path: Path
source_distribution_path: Path
def get_source_distribution_and_wheel(artifact_directory: Path) -> BuildArtifacts:
wheel = list(artifact_directory.glob("**/*.whl"))
source_distribution = list(artifact_directory.glob("**/*.tar.gz"))
# make sure the appropriate numbers of... | BuildArtifacts |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 296107,
"end": 333032
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"admins",
"affiliated_users_with_two_factor_disabled",
"affiliated_users_with_two_factor_disabled_exist",
"allow_private_repository_forking_setting",
... | EnterpriseOwnerInfo |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 122238,
"end": 122365
} | class ____(BaseModel):
failed: "ShardCleanStatusFailedTelemetry" = Field(..., description="")
| ShardCleanStatusTelemetryOneOf2 |
python | readthedocs__readthedocs.org | readthedocs/api/v2/views/model_views.py | {
"start": 5452,
"end": 6948
} | class ____(viewsets.ReadOnlyModelViewSet):
"""
View set that varies serializer class based on request user credentials.
Viewsets using this class should have an attribute `admin_serializer_class`,
which is a serializer that might have more fields that only the builders
require. If the request is us... | UserSelectViewSet |
python | tensorflow__tensorflow | tensorflow/python/ops/summary_ops_v2.py | {
"start": 2351,
"end": 2689
} | class ____(threading.local):
def __init__(self):
super(_SummaryState, self).__init__()
self.is_recording = None
# TODO(slebedev): why a separate flag for DS and is it on by default?
self.is_recording_distribution_strategy = True
self.writer = None
self.step = None
_summary_state = _SummaryS... | _SummaryState |
python | astropy__astropy | astropy/visualization/wcsaxes/transforms.py | {
"start": 4895,
"end": 5661
} | class ____(CurvedTransform, metaclass=abc.ABCMeta):
"""
Base transformation from world to pixel coordinates.
"""
has_inverse = True
frame_in = None
@property
@abc.abstractmethod
def input_dims(self):
"""
The number of input world dimensions.
"""
@abc.abstra... | World2PixelTransform |
python | pytorch__pytorch | torch/_dynamo/types.py | {
"start": 3438,
"end": 3663
} | class ____(Protocol):
def __call__(
self,
guard_manager: GuardFn,
code: types.CodeType,
f_locals: dict[str, object],
index: int,
last: bool,
) -> None: ...
| DynamoGuardHook |
python | kamyu104__LeetCode-Solutions | Python/longest-cycle-in-a-graph.py | {
"start": 37,
"end": 654
} | class ____(object):
def longestCycle(self, edges):
"""
:type edges: List[int]
:rtype: int
"""
result = -1
lookup = [-1]*len(edges)
idx = 0
for i in xrange(len(edges)):
if lookup[i] != -1:
continue
start = idx
... | Solution |
python | apache__airflow | airflow-core/src/airflow/models/callback.py | {
"start": 9507,
"end": 10460
} | class ____(Callback):
"""Used to store Dag Processor's callback requests in the DB."""
__mapper_args__ = {"polymorphic_identity": CallbackType.DAG_PROCESSOR}
def __init__(self, priority_weight: int, callback: CallbackRequest):
"""Initialize a DagProcessorCallback from a callback request."""
... | DagProcessorCallback |
python | pytest-dev__pytest | src/_pytest/skipping.py | {
"start": 5670,
"end": 6734
} | class ____:
"""The result of evaluate_skip_marks()."""
reason: str = "unconditional skip"
def evaluate_skip_marks(item: Item) -> Skip | None:
"""Evaluate skip and skipif marks on item, returning Skip if triggered."""
for mark in item.iter_markers(name="skipif"):
if "condition" not in mark.kwa... | Skip |
python | Pylons__pyramid | src/pyramid/httpexceptions.py | {
"start": 14470,
"end": 14829
} | class ____(HTTPSuccessful):
"""
subclass of :class:`~HTTPSuccessful`
This indicates that the server has fulfilled the request and
the user agent SHOULD reset the document view which caused the
request to be sent.
code: 205, title: Reset Content
"""
code = 205
title = 'Reset Conten... | HTTPResetContent |
python | tensorflow__tensorflow | tensorflow/python/framework/python_api_parameter_converter_test.py | {
"start": 1698,
"end": 20188
} | class ____(test_util.TensorFlowTestCase,
parameterized.TestCase):
def setUp(self):
context.ensure_initialized()
super(PythonAPIWrapperTest, self).setUp()
def makeTensorConverter(self):
"""Returns a new PythonTensorConverter with the current context."""
return PythonTenso... | PythonAPIWrapperTest |
python | astropy__astropy | astropy/units/format/generic.py | {
"start": 12689,
"end": 16953
} | class ____(Base, _GenericParserMixin):
"""
A "generic" format.
The syntax of the format is based directly on the FITS standard,
but instead of only supporting the units that FITS knows about, it
supports any unit available in the `astropy.units` namespace.
"""
@classproperty
def _units... | Generic |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 4715,
"end": 5739
} | class ____:
def __deepcopy__(self, memo):
# Any references to objects further up the tree should not be deep-copied.
# However, if they're in memo (because they've already been deep-copied because
# we're copying from far enough up the tree) then they should be replaced
# with the me... | CopyWithUpTreeRefsMixin |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 3082,
"end": 3326
} | class ____(BaseModel, extra="forbid"):
ids: List["ExtendedPointId"] = Field(..., description="")
vectors: "BatchVectorStruct" = Field(..., description="")
payloads: Optional[List["Payload"]] = Field(default=None, description="")
| Batch |
python | pypa__warehouse | tests/unit/manage/test_forms.py | {
"start": 16323,
"end": 20541
} | class ____:
def test_validate(self):
user_service = pretend.stub(
verify_webauthn_credential=lambda *a, **kw: pretend.stub(),
get_webauthn_by_label=lambda *a: None,
)
user_id = pretend.stub()
challenge = pretend.stub()
rp_id = pretend.stub()
or... | TestProvisionWebAuthnForm |
python | joke2k__faker | faker/providers/date_time/sl_SI/__init__.py | {
"start": 46,
"end": 787
} | class ____(DateTimeProvider):
DAY_NAMES = {
"0": "Nedelja",
"1": "Ponedeljek",
"2": "Torek",
"3": "Sreda",
"4": "Četrtek",
"5": "Petek",
"6": "Sobota",
}
MONTH_NAMES = {
"01": "Januar",
"02": "Februar",
"03": "Marec",
"... | Provider |
python | apache__airflow | airflow-core/src/airflow/hooks/base.py | {
"start": 891,
"end": 4189
} | class ____(Protocol):
"""
Interface that providers *can* implement to be discovered by ProvidersManager.
It is not used by any of the Hooks, but simply methods and class fields described here are
implemented by those Hooks. Each method is optional -- only implement the ones you need.
The conn_name... | DiscoverableHook |
python | pypa__warehouse | warehouse/oidc/models/google.py | {
"start": 4296,
"end": 5462
} | class ____(GooglePublisherMixin, PendingOIDCPublisher):
__tablename__ = "pending_google_oidc_publishers"
__mapper_args__ = {"polymorphic_identity": "pending_google_oidc_publishers"}
__table_args__ = ( # type: ignore[assignment]
UniqueConstraint(
"email",
"sub",
n... | PendingGooglePublisher |
python | getsentry__sentry | tests/sentry/relocation/api/serializers/test_relocation.py | {
"start": 559,
"end": 10481
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.owner = self.create_user(
email="owner", is_superuser=False, is_staff=True, is_active=True
)
self.superuser = self.create_user(
"superuser", is_superuser=True, is_staff=True, is_active=True
... | RelocationSerializerTest |
python | joke2k__faker | tests/providers/test_color.py | {
"start": 18169,
"end": 18499
} | class ____:
"""Test cs_CZ color provider methods"""
def test_safe_color_name(self, faker, num_samples):
for _ in range(num_samples):
safe_color_name = faker.safe_color_name()
assert isinstance(safe_color_name, str)
assert safe_color_name in CsCzColorProvider.safe_col... | TestCsCz |
python | spack__spack | lib/spack/spack/util/environment.py | {
"start": 10795,
"end": 11206
} | class ____(NameValueModifier):
def execute(self, env: MutableMapping[str, str]):
tty.debug(f"RemoveFlagsEnv: {self.name}-{self.value}", level=3)
environment_value = env.get(self.name, "")
flags = environment_value.split(self.separator) if environment_value else []
flags = [f for f in... | RemoveFlagsEnv |
python | coleifer__peewee | playhouse/sqlite_ext.py | {
"start": 34204,
"end": 48525
} | class ____(SqliteDatabase):
def __init__(self, database, c_extensions=None, rank_functions=True,
hash_functions=False, regexp_function=False,
bloomfilter=False, json_contains=False, *args, **kwargs):
super(SqliteExtDatabase, self).__init__(database, *args, **kwargs)
... | SqliteExtDatabase |
python | pytorch__pytorch | torch/ao/quantization/fx/graph_module.py | {
"start": 4541,
"end": 6607
} | class ____(GraphModule):
"""This class is created to make sure PackedParams
(e.g. LinearPackedParams, Conv2dPackedParams) to appear in state_dict
so that we can serialize and deserialize quantized graph module with
torch.save(m.state_dict()) and m.load_state_dict(state_dict)
"""
def __init__(
... | QuantizedGraphModule |
python | ray-project__ray | python/ray/tests/test_autoscaler_gcp.py | {
"start": 114,
"end": 2084
} | class ____:
def __init__(self, errors: List[type]):
# List off errors to raise while retrying self.mock_method
self.errors = errors
# Incremented during each retry via self._construct_client
self.error_index = -1
# Mirrors the __init__ of GCPNodeProvider
# Also called... | MockGCPNodeProvider |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/connectors/asyncio.py | {
"start": 1782,
"end": 3042
} | class ____(Protocol):
"""protocol representing an async adapted version
of a :pep:`249` database cursor.
"""
def __aenter__(self) -> Any: ...
@property
def description(
self,
) -> _DBAPICursorDescription:
"""The description attribute of the Cursor."""
...
@pr... | AsyncIODBAPICursor |
python | pandas-dev__pandas | pandas/tests/plotting/test_hist_method.py | {
"start": 797,
"end": 8982
} | class ____:
@pytest.mark.parametrize("kwargs", [{}, {"grid": False}, {"figsize": (8, 10)}])
def test_hist_legacy_kwargs(self, ts, kwargs):
_check_plot_works(ts.hist, **kwargs)
@pytest.mark.parametrize("kwargs", [{}, {"bins": 5}])
def test_hist_legacy_kwargs_warning(self, ts, kwargs):
# ... | TestSeriesPlots |
python | getsentry__sentry | tests/acceptance/test_project_tags_settings.py | {
"start": 348,
"end": 1905
} | class ____(AcceptanceTestCase, SnubaTestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user("foo@example.com")
self.org = self.create_organization(name="Rowdy Tiger", owner=None)
self.team = self.create_team(organization=self.org, name="Mariachi Band")
... | ProjectTagsSettingsTest |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 16955,
"end": 17137
} | class ____(PydanticValueError):
code = 'discriminated_union.missing_discriminator'
msg_template = 'Discriminator {discriminator_key!r} is missing in value'
| MissingDiscriminator |
python | facebook__pyre-check | pyre_extensions/generic.py | {
"start": 303,
"end": 980
} | class ____(type):
def __getitem__(cls, *args) -> Any:
return cls.__class__(cls.__name__, cls.__bases__, dict(cls.__dict__))
if sys.version_info >= (3, 7):
class Generic:
"""Pyre's variadic-supporting substitute for `typing.Generic`.
By using `__class_getitem__`, this avoids a metacla... | GenericMeta |
python | getsentry__sentry | tests/sentry/rules/processing/test_delayed_processing.py | {
"start": 5449,
"end": 16952
} | class ____(CreateEventTestCase):
interval = "1h"
comparison_interval = "15m"
def create_events(self, comparison_type: ComparisonType) -> Event:
# Create current events for the first query
event = self.create_event(self.project.id, FROZEN_TIME, "group-1", self.environment.name)
self.... | GetConditionGroupResultsTest |
python | django__django | tests/migrations/test_writer.py | {
"start": 1826,
"end": 1895
} | class ____(enum.Enum):
A = b"a-value"
B = b"value-b"
| BinaryEnum |
python | pennersr__django-allauth | allauth/headless/mfa/views.py | {
"start": 8240,
"end": 9763
} | class ____(SignupView):
input_class = {
"POST": SignupWebAuthnInput,
"PUT": CreateWebAuthnInput,
}
by_passkey = True
def get(self, request, *args, **kwargs):
resp = self._require_stage()
if resp:
return resp
creation_options = webauthn_flows.begin_reg... | SignupWebAuthnView |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/translator.py | {
"start": 7131,
"end": 8364
} | class ____:
"""Translator class which converts a `AirbyteConnectionTableProps` object into AssetSpecs.
Subclass this class to implement custom logic how to translate Airbyte content into asset spec.
"""
def get_asset_spec(self, props: AirbyteConnectionTableProps) -> AssetSpec:
"""Get the AssetS... | DagsterAirbyteTranslator |
python | tensorflow__tensorflow | tensorflow/python/keras/utils/generic_utils.py | {
"start": 4491,
"end": 5175
} | class ____(object):
"""A context manager for disabling handling of shared objects.
Disables shared object handling for both saving and loading.
Created primarily for use with `clone_model`, which does extra surgery that
is incompatible with shared objects.
"""
def __enter__(self):
SHARED_OBJECT_DISAB... | DisableSharedObjectScope |
python | gevent__gevent | src/gevent/tests/test__greenlet.py | {
"start": 28065,
"end": 28218
} | class ____(greentest.TestCase):
def test_killall_raw(self):
g = gevent.spawn_raw(lambda: 1)
gevent.killall([g])
| TestKillallRawGreenlet |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/index_flat_map_test.py | {
"start": 7936,
"end": 11562
} | class ____(
checkpoint_test_base.CheckpointTestBase, parameterized.TestCase):
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
checkpoint_test_base.default_test_combinations(),
combinations.combine(
repetitions=[1, 3],
... | IndexFlatMapCheckpointTest |
python | dask__dask | dask/dataframe/io/parquet/core.py | {
"start": 620,
"end": 2739
} | class ____(DataFrameIOFunction):
"""
Parquet Function-Wrapper Class
Reads parquet data from disk to produce a partition
(given a `part` argument).
"""
def __init__(
self,
engine,
fs,
meta,
columns,
index,
dtype_backend,
kwargs,
... | ParquetFunctionWrapper |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1574435,
"end": 1574658
} | class ____(VegaLiteSchema):
"""Vector2Vector2number schema wrapper."""
_schema = {"$ref": "#/definitions/Vector2<Vector2<number>>"}
def __init__(self, *args):
super().__init__(*args)
| Vector2Vector2number |
python | kamyu104__LeetCode-Solutions | Python/collecting-chocolates.py | {
"start": 2475,
"end": 2901
} | class ____(object):
def minCost(self, nums, x):
"""
:type nums: List[int]
:type x: int
:rtype: int
"""
result = [x*k for k in xrange(len(nums)+1)]
for i in xrange(len(nums)):
curr = nums[i]
for k in xrange(len(result)):
... | Solution3 |
python | astropy__astropy | astropy/io/ascii/tdat.py | {
"start": 1546,
"end": 5364
} | class ____(core.BaseSplitter):
"""Splitter for tdat data.
Handles the (deprecated) cases of multiple data delimiters, record
delimiters, and multi-line records.
Multiple data delimiters - Multiple delimiters can be specified in the
header, e.g. field_delimiter = "|!" would treat both | and !
... | TdatDataSplitter |
python | spyder-ide__spyder | external-deps/qtconsole/qtconsole/tests/test_ansi_code_processor.py | {
"start": 143,
"end": 9930
} | class ____(unittest.TestCase):
def setUp(self):
self.processor = AnsiCodeProcessor()
self.qt_processor = QtAnsiCodeProcessor()
def test_clear(self):
""" Do control sequences for clearing the console work?
"""
string = '\x1b[2J\x1b[K'
i = -1
for i, substr... | TestAnsiCodeProcessor |
python | gevent__gevent | src/greentest/3.10/test_ssl.py | {
"start": 122671,
"end": 191852
} | class ____(unittest.TestCase):
def test_echo(self):
"""Basic test of an SSL client connecting to a server"""
if support.verbose:
sys.stdout.write("\n")
client_context, server_context, hostname = testing_context()
with self.subTest(client=ssl.PROTOCOL_TLS_CLIENT, server... | ThreadedTests |
python | matplotlib__matplotlib | lib/matplotlib/rcsetup.py | {
"start": 1210,
"end": 24686
} | class ____:
def __init__(self, key, valid, ignorecase=False, *,
_deprecated_since=None):
"""*valid* is a list of legal strings."""
self.key = key
self.ignorecase = ignorecase
self._deprecated_since = _deprecated_since
def func(s):
if ignorecase:
... | ValidateInStrings |
python | ray-project__ray | python/ray/llm/tests/serve/cpu/deployments/llm/multiplex/test_lora_model_loader.py | {
"start": 363,
"end": 7260
} | class ____:
"""Test suite for the LoraModelLoader class."""
@pytest.fixture
def model_loader(self):
"""Provides a LoraModelLoader instance for tests."""
return LoraModelLoader("/tmp/ray/lora/cache", max_tries=3)
@pytest.fixture
def llm_config(self, disable_placement_bundles):
... | TestLoRAModelLoader |
python | doocs__leetcode | solution/3000-3099/3071.Minimum Operations to Write the Letter Y on a Grid/Solution.py | {
"start": 0,
"end": 614
} | class ____:
def minimumOperationsToWriteY(self, grid: List[List[int]]) -> int:
n = len(grid)
cnt1 = Counter()
cnt2 = Counter()
for i, row in enumerate(grid):
for j, x in enumerate(row):
a = i == j and i <= n // 2
b = i + j == n - 1 and i <=... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/super1.py | {
"start": 1282,
"end": 1482
} | class ____(ClassA):
def method5(self):
class ClassDInner(super().method5()):
# This should generate an error.
x = super().method5()
return ClassDInner
| ClassE |
python | lepture__authlib | authlib/oidc/core/grants/hybrid.py | {
"start": 373,
"end": 3430
} | class ____(OpenIDImplicitGrant):
#: Generated "code" length
AUTHORIZATION_CODE_LENGTH = 48
RESPONSE_TYPES = {"code id_token", "code token", "code id_token token"}
GRANT_TYPE = "code"
DEFAULT_RESPONSE_MODE = "fragment"
def generate_authorization_code(self):
""" "The method to generate "... | OpenIDHybridGrant |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/instance/methods/scheduling_methods.py | {
"start": 922,
"end": 18251
} | class ____:
"""Mixin class containing scheduling-related functionality for DagsterInstance.
This class provides methods for schedule, sensor, and backfill management.
All methods are implemented as instance methods that DagsterInstance inherits.
"""
@property
def _instance(self) -> "DagsterIns... | SchedulingMethods |
python | huggingface__transformers | src/transformers/models/janus/image_processing_janus_fast.py | {
"start": 1224,
"end": 8818
} | class ____(BaseImageProcessorFast):
resample = PILImageResampling.BICUBIC
image_mean = OPENAI_CLIP_MEAN
image_std = OPENAI_CLIP_STD
size = {"height": 384, "width": 384}
min_size = 14
do_resize = True
do_rescale = True
do_normalize = True
do_pad = True
valid_kwargs = JanusImagePro... | JanusImageProcessorFast |
python | kamyu104__LeetCode-Solutions | Python/maximum-length-substring-with-two-occurrences.py | {
"start": 78,
"end": 754
} | class ____(object):
def maximumLengthSubstring(self, s):
"""
:type s: str
:rtype: int
"""
COUNT = 2
result = 0
cnt = [0]*26
left = invalid_cnt = 0
for right, x in enumerate(s):
if cnt[ord(x)-ord('a')] == COUNT:
inval... | Solution |
python | oauthlib__oauthlib | oauthlib/oauth1/rfc5849/endpoints/resource.py | {
"start": 323,
"end": 7374
} | class ____(BaseEndpoint):
"""An endpoint responsible for protecting resources.
Typical use is to instantiate with a request validator and invoke the
``validate_protected_resource_request`` in a decorator around a view
function. If the request is valid, invoke and return the response of the
view. I... | ResourceEndpoint |
python | skorch-dev__skorch | skorch/tests/test_regressor.py | {
"start": 247,
"end": 7390
} | class ____:
@pytest.fixture(scope='module')
def data(self, regression_data):
return regression_data
@pytest.fixture(scope='module')
def module_cls(self):
from skorch.toy import make_regressor
return make_regressor(dropout=0.5)
@pytest.fixture(scope='module')
def module_... | TestNeuralNetRegressor |
python | ray-project__ray | python/ray/train/xgboost/config.py | {
"start": 4334,
"end": 6980
} | class ____(Backend):
def __init__(self):
self._tracker: Optional[RabitTracker] = None
def _setup_xgboost_distributed_backend(self, worker_group: BaseWorkerGroup):
# Set up the rabit tracker on the Train driver.
num_workers = len(worker_group)
rabit_args = {"DMLC_NUM_WORKER": num... | _XGBoostRabitBackend_pre_xgb210 |
python | jazzband__django-waffle | waffle/apps.py | {
"start": 36,
"end": 258
} | class ____(AppConfig):
name = 'waffle'
verbose_name = 'django-waffle'
default_auto_field = 'django.db.models.AutoField'
def ready(self) -> None:
import waffle.signals # noqa: F401,PLC0415
| WaffleConfig |
python | sqlalchemy__sqlalchemy | test/orm/test_unitofwork.py | {
"start": 99346,
"end": 102709
} | class ____(fixtures.TestBase):
"""test #7594.
failure modes when INSERT doesn't actually insert a row.
s
"""
# the test manipulates INSERTS to become UPDATES to simulate
# "INSERT that returns no row" so both are needed; the manipulations
# are currently postgresql or SQLite specific
_... | NoRowInsertedTest |
python | django__django | tests/modeladmin/test_checks.py | {
"start": 37484,
"end": 37974
} | class ____(CheckTestCase):
def test_not_boolean(self):
class TestModelAdmin(ModelAdmin):
save_as = 1
self.assertIsInvalid(
TestModelAdmin,
ValidationTestModel,
"The value of 'save_as' must be a boolean.",
"admin.E101",
)
def t... | SaveAsCheckTests |
python | wandb__wandb | wandb/vendor/pygments/lexers/robotframework.py | {
"start": 6912,
"end": 8214
} | class ____(Tokenizer):
_tokens = (SETTING, ARGUMENT)
_keyword_settings = ('suitesetup', 'suiteprecondition', 'suiteteardown',
'suitepostcondition', 'testsetup', 'testprecondition',
'testteardown', 'testpostcondition', 'testtemplate')
_import_settings = ('lib... | Setting |
python | scrapy__scrapy | tests/mockserver/http.py | {
"start": 3149,
"end": 3293
} | class ____(BaseMockServer):
module_name = "tests.mockserver.http"
main = main_factory(Root)
if __name__ == "__main__":
main()
| MockServer |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 524527,
"end": 525186
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("duration", "id", "start_date", "title", "title_html")
duration = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="duration")
id = sgqlc.types.Field(sgqlc.types.non_... | ProjectV2IterationFieldIteration |
python | sympy__sympy | sympy/utilities/codegen.py | {
"start": 13006,
"end": 13048
} | class ____(Argument):
pass
| InputArgument |
python | simplejson__simplejson | simplejson/encoder.py | {
"start": 15003,
"end": 29093
} | class ____(JSONEncoder):
"""An encoder that produces JSON safe to embed in HTML.
To embed JSON content in, say, a script tag on a web page, the
characters &, < and > should be escaped. They cannot be escaped
with the usual entities (e.g. &) because they are not expanded
within <script> tags.
... | JSONEncoderForHTML |
python | pytorch__pytorch | torch/_dynamo/guards.py | {
"start": 36114,
"end": 36354
} | class ____(enum.Enum):
GUARD_MANAGER = 1
DICT_GUARD_MANAGER = 2
@functools.cache
def code_framelocals_names_reversed_cached(code: types.CodeType) -> list[str]:
return list(reversed(code_framelocals_names(code)))
| GuardManagerType |
python | walkccc__LeetCode | solutions/553. Optimal Division/553.py | {
"start": 0,
"end": 322
} | class ____:
def optimalDivision(self, nums: list[int]) -> str:
ans = str(nums[0])
if len(nums) == 1:
return ans
if len(nums) == 2:
return ans + '/' + str(nums[1])
ans += '/(' + str(nums[1])
for i in range(2, len(nums)):
ans += '/' + str(nums[i])
ans += ')'
return ans
| Solution |
python | walkccc__LeetCode | solutions/114. Flatten Binary Tree to Linked List/114-3.py | {
"start": 0,
"end": 464
} | class ____:
def flatten(self, root: TreeNode | None) -> None:
if not root:
return
while root:
if root.left:
# Find the rightmost root
rightmost = root.left
while rightmost.right:
rightmost = rightmost.right
# Rewire the connections
rightmost.right... | Solution |
python | kamyu104__LeetCode-Solutions | Python/prime-pairs-with-target-sum.py | {
"start": 45,
"end": 882
} | class ____(object):
def findPrimePairs(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
def linear_sieve_of_eratosthenes(n):
primes = []
spf = [-1]*(n+1) # the smallest prime factor
for i in xrange(2, n+1):
if spf[i] ... | Solution |
python | huggingface__transformers | src/transformers/models/blip/modeling_blip.py | {
"start": 4647,
"end": 5697
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss from the text decoder.
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_proje... | BlipTextVisionModelOutput |
python | nedbat__coveragepy | tests/test_api.py | {
"start": 45104,
"end": 50185
} | class ____(CoverageTest):
"""Tests of the relative_files setting."""
def test_moving_stuff(self) -> None:
# When using absolute file names, moving the source around results in
# "No source for code" errors while reporting.
self.make_file("foo.py", "a = 1")
cov = coverage.Coverag... | RelativePathTest |
python | readthedocs__readthedocs.org | readthedocs/organizations/models.py | {
"start": 11368,
"end": 13541
} | class ____(models.Model):
"""Model to keep track of invitations to an organization."""
# Auto fields
pub_date = models.DateTimeField(_("Publication date"), auto_now_add=True)
modified_date = models.DateTimeField(_("Modified date"), auto_now=True)
# Foreign
organization = models.ForeignKey(
... | TeamInvite |
python | bottlepy__bottle | test/test_mdict.py | {
"start": 58,
"end": 1975
} | class ____(unittest.TestCase):
def test_isadict(self):
""" MultiDict should behaves like a normal dict """
d, m = dict(a=5), MultiDict(a=5)
d['key'], m['key'] = 'value', 'value'
d['k2'], m['k2'] = 'v1', 'v1'
d['k2'], m['k2'] = 'v2', 'v2'
self.assertEqual(list(d.keys()... | TestMultiDict |
python | kamyu104__LeetCode-Solutions | Python/splitting-a-string-into-descending-consecutive-values.py | {
"start": 31,
"end": 636
} | class ____(object):
def splitString(self, s):
"""
:type s: str
:rtype: bool
"""
def backtracking(s, i, num, cnt):
if i == len(s):
return cnt >= 2
new_num = 0
for j in xrange(i, len(s)):
new_num = new_num*10 +... | Solution |
python | lepture__authlib | tests/flask/test_oauth2/test_code_challenge.py | {
"start": 824,
"end": 8600
} | class ____(_CodeChallenge):
SUPPORTED_CODE_CHALLENGE_METHOD = ["plain", "S256", "S128"]
@pytest.fixture(autouse=True)
def server(server):
server.register_grant(AuthorizationCodeGrant, [CodeChallenge(required=True)])
return server
@pytest.fixture(autouse=True)
def client(client, db):
client.set_clien... | CodeChallenge |
python | pytorch__pytorch | test/inductor/test_flex_attention.py | {
"start": 234712,
"end": 235705
} | class ____:
batch_size: int
num_heads: int
seq_length: int
head_dim: int
dtype: torch.dtype
config_str: Optional[str] = None
def __str__(self):
return f"batch:{self.batch_size}_head:{self.num_heads}_seq_len:{self.seq_length}_headdim:{self.head_dim}_dtype:{str(self.dtype).split('.')[... | Params |
python | apache__airflow | devel-common/src/tests_common/pytest_plugin.py | {
"start": 63041,
"end": 64646
} | class ____(Protocol):
"""Type stub for create_task_instance_of_operator and create_serialized_task_instance_of_operator."""
def __call__(
self,
operator_class: type[BaseOperator],
*,
dag_id: str,
logical_date: datetime = ...,
session: Session = ...,
**kwa... | CreateTaskInstanceOfOperator |
python | SmileyChris__easy-thumbnails | easy_thumbnails/tests/test_templatetags.py | {
"start": 11793,
"end": 13125
} | class ____(ThumbnailerBase):
def test_check_generate(self):
src = (
'{% with t=filename|thumbnailer_passive %}'
'{{ t.generate }}{% endwith %}'
)
output = self.render_template(src)
self.assertEqual(output, 'False')
def test_get_existing(self):
op... | ThumbnailerPassiveFilterTest |
python | gevent__gevent | src/greentest/3.13/test_subprocess.py | {
"start": 71300,
"end": 80433
} | class ____(BaseTestCase):
def run_python(self, code, **kwargs):
"""Run Python code in a subprocess using subprocess.run"""
argv = [sys.executable, "-c", code]
return subprocess.run(argv, **kwargs)
def test_returncode(self):
# call() function with sequence argument
cp = s... | RunFuncTestCase |
python | PrefectHQ__prefect | src/prefect/events/schemas/deployment_triggers.py | {
"start": 970,
"end": 2375
} | class ____(PrefectBaseModel, abc.ABC, extra="ignore"): # type: ignore[call-arg]
"""
Base class describing a set of criteria that must be satisfied in order to trigger
an automation.
"""
# Fields from Automation
name: Optional[str] = Field(
default=None,
description="The name t... | BaseDeploymentTrigger |
python | tiangolo__fastapi | docs_src/query_param_models/tutorial002_pv1_an.py | {
"start": 166,
"end": 522
} | class ____(BaseModel):
class Config:
extra = "forbid"
limit: int = Field(100, gt=0, le=100)
offset: int = Field(0, ge=0)
order_by: Literal["created_at", "updated_at"] = "created_at"
tags: List[str] = []
@app.get("/items/")
async def read_items(filter_query: Annotated[FilterParams, Query()... | FilterParams |
python | gevent__gevent | src/gevent/tests/test__pool.py | {
"start": 15851,
"end": 16054
} | class ____(greentest.TestCase):
switch_expected = False
def test(self):
p = gevent.pool.Pool()
res = p.join()
self.assertTrue(res, "empty should return true")
| TestJoinEmpty |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/partitions/mapping/static.py | {
"start": 1033,
"end": 7755
} | class ____(
PartitionMapping,
NamedTuple(
"_StaticPartitionMapping",
[
(
"downstream_partition_keys_by_upstream_partition_key",
PublicAttr[Mapping[str, Union[str, Collection[str]]]],
)
],
),
):
"""Define an explicit correspo... | StaticPartitionMapping |
python | mwaskom__seaborn | seaborn/_core/properties.py | {
"start": 19780,
"end": 20183
} | class ____(TextAlignment):
def _default_values(self, n: int) -> list:
vals = itertools.cycle(["top", "bottom"])
return [next(vals) for _ in range(n)]
# =================================================================================== #
# Properties with RGB(A) color values
# ==================... | VerticalAlignment |
python | pypa__warehouse | warehouse/integrations/vulnerabilities/osv/__init__.py | {
"start": 483,
"end": 3440
} | class ____(vulnerabilities.VulnerabilityVerifier):
def __init__(
self,
session,
metrics,
public_keys_api_url: str = OSV_PUBLIC_KEYS_URL,
public_keys_cache=DEFAULT_PUBLIC_KEYS_CACHE,
):
super().__init__(
metrics=metrics, source="osv", public_keys_cache=... | VulnerabilityReportVerifier |
python | huggingface__transformers | src/transformers/models/hiera/modeling_hiera.py | {
"start": 35252,
"end": 35913
} | class ____(nn.Module):
def __init__(self, config: HieraConfig):
super().__init__()
num_features = int(config.embed_dim * config.embed_dim_multiplier ** (len(config.depths) - 1))
self.layernorm = nn.LayerNorm(num_features, eps=config.layer_norm_eps)
self.pooler = nn.AdaptiveAvgPool1d(... | HieraPooler |
python | kamyu104__LeetCode-Solutions | Python/image-smoother.py | {
"start": 33,
"end": 762
} | class ____(object):
def imageSmoother(self, M):
"""
:type M: List[List[int]]
:rtype: List[List[int]]
"""
def getGray(M, i, j):
total, count = 0, 0.0
for r in xrange(-1, 2):
for c in xrange(-1, 2):
ii, jj = i + r, j +... | Solution |
python | django__django | tests/admin_filters/tests.py | {
"start": 83510,
"end": 83791
} | class ____(SimpleTestCase):
def test_get_facet_counts(self):
msg = "subclasses of FacetsMixin must provide a get_facet_counts() method."
with self.assertRaisesMessage(NotImplementedError, msg):
FacetsMixin().get_facet_counts(None, None)
| FacetsMixinTests |
python | keras-team__keras | keras/src/ops/numpy_test.py | {
"start": 18309,
"end": 37227
} | class ____(testing.TestCase):
def test_add(self):
x = KerasTensor((2, 3))
y = KerasTensor((2, 3))
self.assertEqual(knp.add(x, y).shape, (2, 3))
with self.assertRaises(ValueError):
x = KerasTensor((2, 3))
y = KerasTensor((2, 3, 4))
knp.add(x, y)
... | NumpyTwoInputOpsStaticShapeTest |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_usage.py | {
"start": 321,
"end": 1088
} | class ____(BaseModel):
cache_creation: Optional[BetaCacheCreation] = None
"""Breakdown of cached tokens by TTL"""
cache_creation_input_tokens: Optional[int] = None
"""The number of input tokens used to create the cache entry."""
cache_read_input_tokens: Optional[int] = None
"""The number of in... | BetaUsage |
python | automl__auto-sklearn | autosklearn/metalearning/metafeatures/metafeatures.py | {
"start": 24702,
"end": 26086
} | class ____(MetaFeature):
def _calculate(self, X, y, logger, feat_type):
labels = 1 if len(y.shape) == 1 else y.shape[1]
entropies = []
for i in range(labels):
occurence_dict = defaultdict(float)
for value in y if labels == 1 else y[:, i]:
occurence_di... | ClassEntropy |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.