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 | bokeh__bokeh | src/bokeh/util/browser.py | {
"start": 1776,
"end": 4694
} | class ____:
''' A "no-op" web-browser controller.
'''
def open(self, url: str, new: TargetCode = 0, autoraise: bool = True) -> bool:
''' Receive standard arguments and take no action. '''
return True
def get_browser_controller(browser: str | None = None) -> BrowserLike:
''' Return a br... | DummyWebBrowser |
python | django-compressor__django-compressor | compressor/tests/test_filters.py | {
"start": 8939,
"end": 9320
} | class ____(TestCase):
def test_jsmin_filter(self):
content = """/*!
* django-compressor
* Copyright (c) 2009-2014 Django Compressor authors
*/
var foo = "bar";"""
output = """/*!
* django-compressor
* Copyright (c) 2009-2014 Django Compressor authors
*/var foo="bar";"""
self.as... | JsMinTestCase |
python | neetcode-gh__leetcode | python/1721-swapping-nodes-in-a-linked-list.py | {
"start": 151,
"end": 703
} | class ____:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
right_pointer = head
for _ in range(1, k):
right_pointer = right_pointer.next
left_kth_node = right_pointer
left_pointer = head
while right_pointer is not None:
r... | Solution |
python | tensorflow__tensorflow | tensorflow/python/client/session.py | {
"start": 14695,
"end": 15800
} | class ____(_FetchMapper):
"""Fetch mapper for lists, tuples, and namedtuples."""
def __init__(self, fetches):
"""Creates a _ListFetchMapper.
Args:
fetches: List, tuple, or namedtuple of fetches.
"""
if isinstance(fetches, wrapt.ObjectProxy):
self._fetch_type = type(fetches.__wrapped__)... | _ListFetchMapper |
python | getsentry__sentry | src/sentry/hybridcloud/rpc/service.py | {
"start": 1682,
"end": 4362
} | class ____(SerializableFunctionSignature):
"""Represent the contract for an RPC method.
This class is responsible for serializing and deserializing arguments. If the
base service runs in the region silo, this class is also responsible for
resolving the arguments to the correct region for a remote call.... | RpcMethodSignature |
python | pytorch__pytorch | torch/onnx/_internal/exporter/_errors.py | {
"start": 440,
"end": 535
} | class ____(ConversionError):
"""Error during ONNX graph construction."""
| GraphConstructionError |
python | Textualize__rich | tests/test_inspect.py | {
"start": 2155,
"end": 18850
} | class ____(Foo):
pass
def test_render():
console = Console(width=100, file=io.StringIO(), legacy_windows=False)
foo = Foo("hello")
inspect(foo, console=console, all=True, value=False)
result = console.file.getvalue()
print(repr(result))
expected = "โญโโโโโโโโโโโโโโ <class 'tests.test_inspe... | FooSubclass |
python | huggingface__transformers | src/transformers/models/bert/modeling_bert.py | {
"start": 21239,
"end": 21849
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.transform = BertPredictionHeadTransform(config)
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
self.decoder = nn.Linear(config.hidden_siz... | BertLMPredictionHead |
python | django__django | tests/auth_tests/test_decorators.py | {
"start": 4206,
"end": 9682
} | class ____(TestCase):
"""
Tests for the permission_required decorator
"""
factory = RequestFactory()
@classmethod
def setUpTestData(cls):
cls.user = models.User.objects.create(username="joe", password="qwerty")
# Add permissions auth.add_customuser and auth.change_customuser
... | PermissionsRequiredDecoratorTest |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/metadata/external_metadata.py | {
"start": 739,
"end": 5040
} | class ____(TypedDict):
type: "ExternalMetadataType"
raw_value: InferrableExternalMetadataValue
# Infer the type from the raw value on the orchestration end
EXTERNAL_METADATA_TYPE_INFER = "__infer__"
ExternalMetadataType = Literal[
"__infer__",
"text",
"url",
"path",
"notebook",
"json"... | ExternalMetadataValue |
python | openai__openai-python | src/openai/types/upload.py | {
"start": 246,
"end": 1207
} | class ____(BaseModel):
id: str
"""The Upload unique identifier, which can be referenced in API endpoints."""
bytes: int
"""The intended number of bytes to be uploaded."""
created_at: int
"""The Unix timestamp (in seconds) for when the Upload was created."""
expires_at: int
"""The Unix... | Upload |
python | pytorch__pytorch | torch/utils/data/datapipes/map/combining.py | {
"start": 2252,
"end": 3903
} | class ____(MapDataPipe[tuple[_T_co, ...]]):
r"""
Aggregates elements into a tuple from each of the input DataPipes (functional name: ``zip``).
This MataPipe is out of bound as soon as the shortest input DataPipe is exhausted.
Args:
*datapipes: Map DataPipes being aggregated
Example:
... | ZipperMapDataPipe |
python | getsentry__sentry | tests/sentry/issues/endpoints/test_project_stacktrace_link.py | {
"start": 8444,
"end": 14809
} | class ____(BaseProjectStacktraceLink):
def setUp(self) -> None:
BaseProjectStacktraceLink.setUp(self)
self.android_code_mapping = self._create_code_mapping(
stack_root="usr/src/getsentry/",
source_root="src/getsentry/",
)
self.flutter_code_mapping = self._crea... | ProjectStacktraceLinkTestMobile |
python | numpy__numpy | numpy/_core/tests/test_deprecations.py | {
"start": 6693,
"end": 7535
} | class ____(_DeprecationTestCase):
# NumPy 1.20, 2020-09-03
message = "concatenate with `axis=None` will use same-kind casting"
def test_deprecated(self):
self.assert_deprecated(np.concatenate,
args=(([0.], [1.]),),
kwargs={'axis': None, 'out': np.empty(2, dtype=np.in... | FlatteningConcatenateUnsafeCast |
python | streamlit__streamlit | lib/tests/streamlit/web/server/upload_file_request_handler_test.py | {
"start": 7010,
"end": 8791
} | class ____(tornado.testing.AsyncHTTPTestCase):
"""Tests the /upload_file endpoint."""
def get_app(self):
self.file_mgr = MemoryUploadedFileManager(upload_endpoint=UPLOAD_FILE_ENDPOINT)
return tornado.web.Application(
[
(
f"{UPLOAD_FILE_ENDPOINT}/(... | UploadFileRequestHandlerInvalidSessionTest |
python | pytorch__pytorch | test/dynamo/cpython/3_13/list_tests.py | {
"start": 667,
"end": 1654
} | class ____(importlib.abc.MetaPathFinder):
def find_spec(self, fullname, path, target=None):
# Check if the import is the problematic one
if fullname in redirect_imports:
try:
# Attempt to import the standalone module
name = fullname.removeprefix("test.")
... | RedirectImportFinder |
python | joke2k__faker | tests/providers/test_python.py | {
"start": 4710,
"end": 5556
} | class ____(unittest.TestCase):
def setUp(self):
self.fake = Faker()
Faker.seed(0)
def test_pyint(self):
self.assertIsInstance(self.fake.pyint(), int)
def test_pyint_bounds(self):
self.assertTrue(0 <= self.fake.pyint() <= 9999)
def test_pyint_step(self):
random_... | TestPyint |
python | Lightning-AI__lightning | src/lightning/pytorch/callbacks/finetuning.py | {
"start": 1462,
"end": 13988
} | class ____(Callback):
r"""This class implements the base logic for writing your own Finetuning Callback.
.. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature.
Override ``freeze_before_training`` and ``finetune_function`` methods with your own logic.
``freeze_before_train... | BaseFinetuning |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/vertex_ai/test_dataset.py | {
"start": 1934,
"end": 10752
} | class ____:
def setup_method(self):
with mock.patch(
BASE_STRING.format("GoogleBaseHook.__init__"), new=mock_base_gcp_hook_default_project_id
):
self.hook = DatasetHook(gcp_conn_id=TEST_GCP_CONN_ID)
@mock.patch(DATASET_STRING.format("DatasetHook.get_dataset_service_clien... | TestVertexAIWithDefaultProjectIdHook |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_datacatalog.py | {
"start": 5691,
"end": 9679
} | class ____:
@mock.patch(
"airflow.providers.google.cloud.operators.datacatalog.CloudDataCatalogHook",
**{"return_value.create_entry.return_value": TEST_ENTRY},
)
def test_assert_valid_hook_call(self, mock_hook) -> None:
with pytest.warns(AirflowProviderDeprecationWarning):
... | TestCloudDataCatalogCreateEntryOperator |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 995249,
"end": 1004980
} | class ____(FieldChannelMixin, core.SecondaryFieldDef):
r"""
XError schema wrapper.
A field definition of a secondary channel that shares a scale with another primary channel.
For example, ``x2``, ``xError`` and ``xError2`` share the same scale with ``x``.
Parameters
----------
shorthand : ... | XError |
python | numba__numba | numba/core/compiler_machinery.py | {
"start": 477,
"end": 731
} | class ____(object):
"""
A simple context managed timer
"""
def __enter__(self):
self.ts = timeit.default_timer()
return self
def __exit__(self, *exc):
self.elapsed = timeit.default_timer() - self.ts
| SimpleTimer |
python | miyuchina__mistletoe | mistletoe/span_token.py | {
"start": 3884,
"end": 4111
} | class ____(SpanToken):
"""
Strikethrough token. ("~~some text~~")
This is an inline token. Its children are inline (span) tokens.
"""
pattern = re.compile(r"(?<!\\)(?:\\\\)*~~(.+?)~~", re.DOTALL)
| Strikethrough |
python | huggingface__transformers | src/transformers/models/grounding_dino/modeling_grounding_dino.py | {
"start": 67148,
"end": 71099
} | class ____(PreTrainedModel):
config: GroundingDinoConfig
base_model_prefix = "model"
main_input_name = "pixel_values"
input_modalities = ("image", "text")
@torch.no_grad()
def _init_weights(self, module):
std = self.config.init_std
if isinstance(module, GroundingDinoLearnedPosi... | GroundingDinoPreTrainedModel |
python | pallets__jinja | src/jinja2/exceptions.py | {
"start": 4458,
"end": 4625
} | class ____(TemplateError):
"""A generic runtime error in the template engine. Under some situations
Jinja may raise this exception.
"""
| TemplateRuntimeError |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_with_poly.py | {
"start": 5132,
"end": 5202
} | class ____(_WithPolymorphicBase, _Polymorphic):
pass
| PolymorphicTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 24922,
"end": 25291
} | class ____(sgqlc.types.Enum):
"""Properties by which gist connections can be ordered.
Enumeration Choices:
* `CREATED_AT`: Order gists by creation time
* `PUSHED_AT`: Order gists by push time
* `UPDATED_AT`: Order gists by update time
"""
__schema__ = github_schema
__choices__ = ("CRE... | GistOrderField |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/sensors/emr.py | {
"start": 20421,
"end": 25270
} | class ____(EmrBaseSensor):
"""
Poll the state of the step until it reaches any of the target states; raise AirflowException on failure.
With the default target states, sensor waits step to be completed.
.. seealso::
For more information on how to use this sensor, take a look at the guide:
... | EmrStepSensor |
python | chroma-core__chroma | chromadb/test/api/test_schema_e2e.py | {
"start": 2106,
"end": 9477
} | class ____(EmbeddingFunction[List[str]]):
"""Embedding function that records inputs for search embedding tests."""
def __init__(self, label: str = "default") -> None:
self._label = label
self.call_inputs: List[List[str]] = []
self.query_inputs: List[List[str]] = []
def __call__(sel... | RecordingSearchEmbeddingFunction |
python | chardet__chardet | chardet/enums.py | {
"start": 1370,
"end": 1683
} | class ____:
"""
This enum represents the different categories language models for
``SingleByteCharsetProber`` put characters into.
Anything less than CONTROL is considered a letter.
"""
UNDEFINED = 255
LINE_BREAK = 254
SYMBOL = 253
DIGIT = 252
CONTROL = 251
| CharacterCategory |
python | getsentry__sentry | tests/sentry/relocation/api/endpoints/artifacts/test_details.py | {
"start": 1010,
"end": 1953
} | class ____(APITestCase):
endpoint = "sentry-api-0-relocations-artifacts-details"
method = "GET"
def setUp(self) -> None:
super().setUp()
self.owner = self.create_user(email="owner@example.com", is_superuser=False, is_staff=False)
self.superuser = self.create_user(is_superuser=True)
... | GetRelocationArtifactDetailsTest |
python | tiangolo__fastapi | tests/test_no_schema_split.py | {
"start": 701,
"end": 7800
} | class ____(BaseModel):
input: str
output: MessageOutput
app = FastAPI(title="Minimal FastAPI App", version="1.0.0")
@app.post("/messages", response_model=Message)
async def create_message(input_message: str) -> Message:
return Message(
input=input_message,
output=MessageOutput(body=f"Pro... | Message |
python | wandb__wandb | wandb/sdk/artifacts/storage_policy.py | {
"start": 671,
"end": 2546
} | class ____(ABC):
_api: InternalApi | None = None
def __init_subclass__(cls, **kwargs: Any) -> None:
super().__init_subclass__(**kwargs)
_POLICY_REGISTRY[cls.name()] = cls
@classmethod
def lookup_by_name(cls, name: str) -> type[StoragePolicy]:
if policy := _POLICY_REGISTRY.get(n... | StoragePolicy |
python | getsentry__sentry | tests/sentry/relocation/tasks/test_process.py | {
"start": 76821,
"end": 84051
} | class ____(RelocationTaskTestCase, TransactionTestCase):
def setUp(self) -> None:
RelocationTaskTestCase.setUp(self)
TransactionTestCase.setUp(self)
self.relocation.step = Relocation.Step.VALIDATING.value
self.relocation.latest_task = OrderedTask.VALIDATING_COMPLETE.name
self... | ImportingTest |
python | ray-project__ray | python/ray/data/tests/unit/test_datatype.py | {
"start": 2489,
"end": 3607
} | class ____:
"""Test DataType validation and initialization."""
@pytest.mark.parametrize(
"valid_type",
[
pa.int64(),
pa.string(),
pa.timestamp("s"),
np.dtype("int32"),
np.dtype("float64"),
int,
str,
... | TestDataTypeValidation |
python | lepture__authlib | tests/flask/test_oauth2/test_client_registration_endpoint_oidc.py | {
"start": 404,
"end": 21030
} | class ____(_ClientRegistrationEndpoint):
software_statement_alg_values_supported = ["RS256"]
def authenticate_token(self, request):
auth_header = request.headers.get("Authorization")
if auth_header:
request.user_id = 1
return auth_header
def resolve_public_key(self,... | ClientRegistrationEndpoint |
python | huggingface__transformers | tests/models/depth_anything/test_modeling_depth_anything.py | {
"start": 9270,
"end": 12815
} | class ____(unittest.TestCase):
def test_inference(self):
# -- `relative` depth model --
image_processor = DPTImageProcessor.from_pretrained("LiheYoung/depth-anything-small-hf")
model = DepthAnythingForDepthEstimation.from_pretrained("LiheYoung/depth-anything-small-hf").to(torch_device)
... | DepthAnythingModelIntegrationTest |
python | django__django | tests/test_runner_apps/failures/tests_failures.py | {
"start": 142,
"end": 234
} | class ____(TestCase):
def test_sample(self):
raise Exception("test")
| ErrorTestCase |
python | eth-brownie__brownie | brownie/typing.py | {
"start": 666,
"end": 1001
} | class ____(TypedDict):
name: str | Literal["(anonymous)", "(unknown)"]
data: List[EventData]
decoded: bool
address: ChecksumAddress
# Transactions
TransactionReceiptType = TypeVar("TransactionReceiptType", bound="TransactionReceipt")
# PROJECT
Start = int
Stop = int
Offset = Tuple[Start, Stop]
# B... | FormattedEvent |
python | fluentpython__example-code-2e | 12-seq-hacking/vector_v5.py | {
"start": 4479,
"end": 7051
} | class ____:
typecode = 'd'
def __init__(self, components):
self._components = array(self.typecode, components)
def __iter__(self):
return iter(self._components)
def __repr__(self):
components = reprlib.repr(self._components)
components = components[components.find('[')... | Vector |
python | falconry__falcon | examples/asgilook/asgilook/images.py | {
"start": 910,
"end": 1368
} | class ____:
def __init__(self, store):
self._store = store
async def on_get(self, req, resp, image_id, width, height):
image = self._store.get(str(image_id))
if not image:
raise falcon.HTTPNotFound
if req.path not in image.thumbnails():
raise falcon.HTTPN... | Thumbnails |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/events.py | {
"start": 4427,
"end": 4722
} | class ____(NodeEvent):
__slots__ = 'style'
def __init__(self, anchor, start_mark=None, end_mark=None, style=None, comment=None):
# type: (Any, Any, Any, Any, Any) -> None
NodeEvent.__init__(self, anchor, start_mark, end_mark, comment)
self.style = style
| AliasEvent |
python | openai__openai-python | src/openai/types/beta/threads/run_create_params.py | {
"start": 1078,
"end": 7801
} | class ____(TypedDict, total=False):
assistant_id: Required[str]
"""
The ID of the
[assistant](https://platform.openai.com/docs/api-reference/assistants) to use to
execute this run.
"""
include: List[RunStepInclude]
"""A list of additional fields to include in the response.
Currentl... | RunCreateParamsBase |
python | kamyu104__LeetCode-Solutions | Python/robot-bounded-in-circle.py | {
"start": 29,
"end": 568
} | class ____(object):
def isRobotBounded(self, instructions):
"""
:type instructions: str
:rtype: bool
"""
directions = [[ 1, 0], [0, -1], [-1, 0], [0, 1]]
x, y, i = 0, 0, 0
for instruction in instructions:
if instruction == 'R':
i = ... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-recharge/source_recharge/source.py | {
"start": 504,
"end": 913
} | class ____(YamlDeclarativeSource):
def __init__(self) -> None:
super().__init__(**{"path_to_yaml": "manifest.yaml"})
def streams(self, config: Mapping[str, Any]) -> List[Stream]:
auth = RechargeTokenAuthenticator(token=config["access_token"])
streams = super().streams(config=config)
... | SourceRecharge |
python | kamyu104__LeetCode-Solutions | Python/find-unique-binary-string.py | {
"start": 29,
"end": 361
} | class ____(object):
def findDifferentBinaryString(self, nums):
"""
:type nums: List[str]
:rtype: str
"""
return "".join("01"[nums[i][i] == '0'] for i in xrange(len(nums)))
# Time: O(k * n) = O(n^2), k is len(nums)
# , n is len(nums[0])
# Space: O(k)... | Solution |
python | allegroai__clearml | clearml/backend_api/services/v2_23/datasets.py | {
"start": 352,
"end": 497
} | class ____(StringEnum):
draft = "draft"
committing = "committing"
committed = "committed"
published = "published"
| VersionStatusEnum |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 601,
"end": 4486
} | class ____(Operation):
def __init__(self, k=1, axes=(0, 1), *, name=None):
super().__init__(name=name)
self.k = k
self.axes = axes
def call(self, array):
return backend.numpy.rot90(array, k=self.k, axes=self.axes)
def compute_output_spec(self, array):
array_shape = ... | Rot90 |
python | getsentry__sentry | tests/sentry/core/endpoints/test_team_release_count.py | {
"start": 148,
"end": 6388
} | class ____(APITestCase):
endpoint = "sentry-api-0-team-release-count"
def test_simple(self) -> None:
user = self.create_user(is_staff=False, is_superuser=False)
org = self.organization
org2 = self.create_organization()
org.flags.allow_joinleave = False
org.save()
... | TeamReleaseCountTest |
python | dask__dask | dask/dataframe/dask_expr/_shuffle.py | {
"start": 37630,
"end": 38004
} | class ____(Blockwise):
_parameters = ["frame", "new_divisions", "ascending", "na_position"]
_defaults = {"ascending": True, "na_position": "last"}
operation = staticmethod(set_partitions_pre)
_is_length_preserving = True
@functools.cached_property
def _meta(self):
return make_meta(self.... | _SetPartitionsPreSetIndex |
python | huggingface__transformers | src/transformers/models/vit/modeling_vit.py | {
"start": 12720,
"end": 13946
} | class ____(GradientCheckpointingLayer):
"""This corresponds to the Block class in the timm implementation."""
def __init__(self, config: ViTConfig):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = ViTAttentio... | ViTLayer |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mssql/information_schema.py | {
"start": 672,
"end": 832
} | class ____(TypeDecorator):
impl = Unicode
cache_ok = True
def bind_expression(self, bindvalue):
return _cast_on_2005(bindvalue)
| CoerceUnicode |
python | tensorflow__tensorflow | tensorflow/python/ops/summary_ops_v2.py | {
"start": 2689,
"end": 9227
} | class ____:
"""Context manager to implement SummaryWriter.as_default()."""
# Note: this is a class so that it's possible to implement `set_as_default()`
# simply via `as_default().__enter__()`. We can't do that with @contextmanager
# because the `finally` block will be executed when the generator is GCed.
de... | _SummaryContextManager |
python | PyCQA__pylint | tests/functional/t/type/typedDict.py | {
"start": 148,
"end": 190
} | class ____(TypedDict):
var: int
| CustomTD |
python | sympy__sympy | sympy/core/expr.py | {
"start": 141444,
"end": 142807
} | class ____(Expr):
"""
Expression that is not evaluated unless released.
Examples
========
>>> from sympy import UnevaluatedExpr
>>> from sympy.abc import x
>>> x*(1/x)
1
>>> x*UnevaluatedExpr(1/x)
x*1/x
"""
def __new__(cls, arg, **kwargs):
arg = _sympify(arg)
... | UnevaluatedExpr |
python | ray-project__ray | python/ray/tests/test_runtime_env_plugin.py | {
"start": 7101,
"end": 11308
} | class ____(DummyPlugin):
name = FAULT_PLUGIN_NAME
async def create(
self,
uri: str,
runtime_env: "RuntimeEnv",
ctx: RuntimeEnvContext,
logger: logging.Logger, # noqa: F821
) -> float:
action = os.environ.get(FAULT_PLUGIN_KEY, "raise")
if action == "r... | FaultPlugin |
python | fsspec__filesystem_spec | fsspec/caching.py | {
"start": 25592,
"end": 34260
} | class ____(BaseCache):
"""
Cache holding memory as a set of blocks with pre-loading of
the next block in the background.
Requests are only ever made ``blocksize`` at a time, and are
stored in an LRU cache. The least recently accessed block is
discarded when more than ``maxblocks`` are stored. I... | BackgroundBlockCache |
python | Textualize__textual | tests/command_palette/test_no_results.py | {
"start": 112,
"end": 1066
} | class ____(App[None]):
COMMANDS = set()
def on_mount(self) -> None:
self.action_command_palette()
async def test_no_results() -> None:
"""Receiving no results from a search for a command should not be a problem."""
async with CommandPaletteApp().run_test() as pilot:
assert CommandPale... | CommandPaletteApp |
python | celery__celery | t/unit/worker/test_consumer.py | {
"start": 883,
"end": 1580
} | class ____:
def get_consumer(self, no_hub=False, **kwargs):
consumer = Consumer(
on_task_request=Mock(),
init_callback=Mock(),
pool=Mock(),
app=self.app,
timer=Mock(),
controller=Mock(),
hub=None if no_hub else Mock(),
... | ConsumerTestCase |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0006_add_domain_models.py | {
"start": 100,
"end": 1998
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0005_sync_project_model"),
]
operations = [
migrations.CreateModel(
name="Domain",
fields=[
(
"id",
models.AutoFiel... | Migration |
python | ray-project__ray | rllib/examples/algorithms/dqn/benchmark_dqn_atari.py | {
"start": 9976,
"end": 13227
} | class ____(Stopper):
def __init__(self, benchmark_envs):
self.benchmark_envs = benchmark_envs
def __call__(self, trial_id, result):
# Stop training if the mean reward is reached.
if (
result[ENV_RUNNER_RESULTS][EPISODE_RETURN_MEAN]
>= self.benchmark_envs[result["... | BenchmarkStopper |
python | PrefectHQ__prefect | src/prefect/server/utilities/messaging/memory.py | {
"start": 6513,
"end": 8143
} | class ____:
_topics: dict[str, "Topic"] = {}
name: str
_subscriptions: list[Subscription]
def __init__(self, name: str) -> None:
self.name = name
self._subscriptions = []
@classmethod
def by_name(cls, name: str) -> "Topic":
try:
return cls._topics[name]
... | Topic |
python | pytorch__pytorch | torch/_inductor/output_code.py | {
"start": 13070,
"end": 14111
} | class ____:
"""Wrapper class that unwraps constants from a compiled fx graph. This
version of the class only supports directly grabbing the saved constants off of
a CompiledFxGraph.
With freezing, FxGraphCache doesn't store the constants of the input
GraphModule it gets from AOTAutograd. Instead, i... | CompiledFxGraphConstants |
python | django__django | tests/postgres_tests/models.py | {
"start": 4367,
"end": 4957
} | class ____(PostgreSQLModel):
parent = models.ForeignKey(RangesModel, models.SET_NULL, blank=True, null=True)
integer = models.IntegerField(blank=True, null=True)
big_integer = models.BigIntegerField(blank=True, null=True)
float = models.FloatField(blank=True, null=True)
timestamp = models.DateTimeFi... | RangeLookupsModel |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 687624,
"end": 688122
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of LinkProjectV2ToRepository"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "repository")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performi... | LinkProjectV2ToRepositoryPayload |
python | django__django | tests/select_related/tests.py | {
"start": 9144,
"end": 11805
} | class ____(SimpleTestCase):
"""
select_related() should thrown an error on fields that do not exist and
non-relational fields.
"""
non_relational_error = (
"Non-relational field given in select_related: '%s'. Choices are: %s"
)
invalid_error = (
"Invalid field name(s) given ... | SelectRelatedValidationTests |
python | numba__numba | numba/core/errors.py | {
"start": 20561,
"end": 20808
} | class ____(NumbaError):
"""
For wrapping internal error occurred within the compiler
"""
def __init__(self, exception):
super(InternalError, self).__init__(str(exception))
self.old_exception = exception
| InternalError |
python | huggingface__transformers | src/transformers/models/auto/modeling_auto.py | {
"start": 86760,
"end": 86992
} | class ____(_BaseAutoModelClass):
_model_mapping = MODEL_FOR_IMAGE_SEGMENTATION_MAPPING
AutoModelForImageSegmentation = auto_class_update(AutoModelForImageSegmentation, head_doc="image segmentation")
| AutoModelForImageSegmentation |
python | dagster-io__dagster | python_modules/dagster/dagster/components/scaffold/scaffold.py | {
"start": 2678,
"end": 3317
} | class ____(Generic[TModel]):
"""Details about the current scaffolding operation.
This is passed to the :py:class:`Scaffolder` class when scaffolding a target.
"""
# fully qualified class name of the decorated object
type_name: str
# target path for the scaffold request. Typically used to const... | ScaffoldRequest |
python | weaviate__weaviate-python-client | weaviate/exceptions.py | {
"start": 12298,
"end": 12638
} | class ____(WeaviateBaseError):
"""Is raised when a request to Weaviate times out."""
def __init__(self, message: str = "") -> None:
msg = f"""The request to Weaviate timed out while awaiting a response. Try adjusting the timeout config for your client. Details: {message}"""
super().__init__(msg... | WeaviateTimeoutError |
python | pytorch__pytorch | scripts/release_notes/categorize.py | {
"start": 366,
"end": 7143
} | class ____:
def __init__(self, path, category="Uncategorized", use_classifier: bool = False):
self.cache = get_commit_data_cache()
self.commits = CommitList.from_existing(path)
if use_classifier:
print("Using a classifier to aid with categorization.")
device = "cuda" ... | Categorizer |
python | pytest-dev__pytest-xdist | testing/test_newhooks.py | {
"start": 2553,
"end": 4463
} | class ____:
@pytest.fixture(autouse=True)
def create_test_file(self, pytester: pytest.Pytester) -> None:
pytester.makepyfile(
"""
import os
def test_a(): pass
def test_b(): os._exit(1)
def test_c(): pass
def test_d(): pass
"... | TestCrashItem |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 403130,
"end": 403835
} | class ____(sgqlc.types.Interface):
"""Metadata for an audit entry with action oauth_application.*"""
__schema__ = github_schema
__field_names__ = ("oauth_application_name", "oauth_application_resource_path", "oauth_application_url")
oauth_application_name = sgqlc.types.Field(String, graphql_name="oauth... | OauthApplicationAuditEntryData |
python | pypa__pip | src/pip/_vendor/rich/align.py | {
"start": 7781,
"end": 10324
} | class ____(JupyterMixin):
"""Vertically aligns a renderable.
Warn:
This class is deprecated and may be removed in a future version. Use Align class with
`vertical="middle"`.
Args:
renderable (RenderableType): A renderable object.
style (StyleType, optional): An optional sty... | VerticalCenter |
python | kubernetes-client__python | kubernetes/client/models/v1beta2_device_class.py | {
"start": 383,
"end": 6826
} | 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... | V1beta2DeviceClass |
python | sphinx-doc__sphinx | sphinx/transforms/__init__.py | {
"start": 5759,
"end": 6712
} | class ____(SphinxTransform):
"""Several code block related transformations."""
default_priority = 210
def apply(self, **kwargs: Any) -> None:
# move doctest blocks out of blockquotes
for node in self.document.findall(nodes.block_quote):
if all(isinstance(child, nodes.doctest_bl... | HandleCodeBlocks |
python | Netflix__metaflow | metaflow/user_decorators/common.py | {
"start": 822,
"end": 5362
} | class ____:
def __init__(self):
self.root = _TrieNode(None, None)
self.inited = False
self._value_to_node = {} # type: Dict[type, _TrieNode]
def init(self, initial_nodes: Optional[List[Tuple[str, type]]] = None):
# We need to do this so we can delay import of STEP_DECORATORS
... | ClassPath_Trie |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/graph_compile.py | {
"start": 20862,
"end": 90895
} | class ____:
"""
A data structure to hold all the information needed to partition the
`joint_hop_gm` and joint graph and the restitch the `new_fw_hop_gm` and
`new_bw_hop_gm` into the bigger `joint_gm`.
"""
# To avoid re-partitioning subgraphs
partitioning_done: bool = False
old_num_fw_ou... | InvokeSubgraphHopGraphs |
python | numpy__numpy | numpy/lib/tests/test_nanfunctions.py | {
"start": 19832,
"end": 21842
} | class ____(SharedNanFunctionsTestsMixin):
nanfuncs = [np.nansum, np.nanprod]
stdfuncs = [np.sum, np.prod]
@pytest.mark.parametrize("axis", [None, 0, 1])
@pytest.mark.parametrize("dtype", np.typecodes["AllFloat"])
@pytest.mark.parametrize("array", [
np.array(np.nan),
np.full((3, 3),... | TestNanFunctions_SumProd |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 579454,
"end": 579819
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("assignable", "client_mutation_id")
assignable = sgqlc.types.Field(Assignable, graphql_name="assignable")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMu... | RemoveAssigneesFromAssignablePayload |
python | streamlit__streamlit | lib/streamlit/errors.py | {
"start": 9698,
"end": 10856
} | class ____(LocalizableStreamlitException):
"""Exception raised when there are more default selections specified than the max allowable selections."""
def __init__(
self, current_selections_count: int, max_selections_count: int
) -> None:
super().__init__(
"Multiselect has {curre... | StreamlitSelectionCountExceedsMaxError |
python | ray-project__ray | rllib/env/external_env.py | {
"start": 8606,
"end": 12465
} | class ____:
"""Tracked state for each active episode."""
def __init__(
self,
episode_id: str,
results_avail_condition: threading.Condition,
training_enabled: bool,
multiagent: bool = False,
):
self.episode_id = episode_id
self.results_avail_condition ... | _ExternalEnvEpisode |
python | Lightning-AI__lightning | src/lightning/fabric/utilities/distributed.py | {
"start": 14273,
"end": 16023
} | class ____(DistributedSampler):
"""Wrapper over ``Sampler`` for distributed training.
Allows you to use any sampler in distributed mode. It will be automatically used by Lightning in distributed mode if
sampler replacement is enabled.
Note:
The purpose of this wrapper is to take care of shardi... | DistributedSamplerWrapper |
python | mkdocs__mkdocs | mkdocs/config/config_options.py | {
"start": 25853,
"end": 27218
} | class ____(Dir):
"""
SiteDir Config Option.
Validates the site_dir and docs_dir directories do not contain each other.
"""
def post_validation(self, config: Config, key_name: str):
super().post_validation(config, key_name)
docs_dir = config['docs_dir']
site_dir = config['si... | SiteDir |
python | gevent__gevent | src/gevent/tests/test__socket_dns.py | {
"start": 33362,
"end": 33435
} | class ____(TestCase):
pass
add(TestBadName, 'xxxxxxxxxxxx')
| TestBadName |
python | scikit-learn__scikit-learn | sklearn/multioutput.py | {
"start": 15021,
"end": 21695
} | class ____(ClassifierMixin, _MultiOutputEstimator):
"""Multi target classification.
This strategy consists of fitting one classifier per target. This is a
simple strategy for extending classifiers that do not natively support
multi-target classification.
Parameters
----------
estimator : e... | MultiOutputClassifier |
python | ijl__orjson | test/test_subclass.py | {
"start": 2422,
"end": 3126
} | class ____:
def test_subclass_str(self):
with pytest.raises(orjson.JSONEncodeError):
orjson.dumps(SubStr("zxc"), option=orjson.OPT_PASSTHROUGH_SUBCLASS)
def test_subclass_int(self):
with pytest.raises(orjson.JSONEncodeError):
orjson.dumps(SubInt(1), option=orjson.OPT_PAS... | TestSubclassPassthrough |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/endpoints-frameworks-v2/echo/main.py | {
"start": 883,
"end": 960
} | class ____(messages.Message):
message = messages.StringField(1)
| EchoRequest |
python | Netflix__metaflow | metaflow/plugins/env_escape/client_modules.py | {
"start": 4304,
"end": 10580
} | class ____(object):
"""
A custom import hook that proxies module imports to a different Python environment.
This class implements the MetaPathFinder and Loader protocols (PEP 451) to enable
"environment escape" - allowing the current Python process to import and use modules
from a different Python ... | ModuleImporter |
python | walkccc__LeetCode | solutions/2094. Finding 3-Digit Even Numbers/2094.py | {
"start": 0,
"end": 454
} | class ____:
def findEvenNumbers(self, digits: list[int]) -> list[int]:
ans = []
count = collections.Counter(digits)
# Try to construct `abc`.
for a in range(1, 10):
for b in range(0, 10):
for c in range(0, 9, 2):
if count[a] > 0 and count[b] > (
b == a) and c... | Solution |
python | pytorch__pytorch | test/dynamo/test_export.py | {
"start": 116364,
"end": 116746
} | class ____(torch.nn.Module):
def forward(self, pred, x):
arg0: "Sym(Eq(s26, {size}))"; arg1: "f32[s77, s27]";
arg0, arg1, = fx_pytree.tree_flatten_spec(([pred, x], {{}}), self._in_spec)
l_x_ = arg1
sin: "f32[s77, s27]" = l_x_.sin(); l_x_ = None
return pytree.tree_unflatten... | GraphModule |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/hashability2.py | {
"start": 668,
"end": 716
} | class ____(E, D): ...
s5 = {G()}
d5 = {G(): 100}
| G |
python | django__django | tests/contenttypes_tests/models.py | {
"start": 2088,
"end": 2461
} | class ____(models.Model):
"""An ordered tag on an item."""
title = models.CharField(max_length=200)
content_type = models.ForeignKey(ContentType, models.CASCADE, null=True)
object_id = models.PositiveIntegerField(null=True)
parent = GenericForeignKey()
children = GenericRelation("Post")
cl... | Post |
python | django__django | tests/utils_tests/test_autoreload.py | {
"start": 24457,
"end": 29134
} | class ____:
@mock.patch("django.utils.autoreload.BaseReloader.notify_file_changed")
@mock.patch(
"django.utils.autoreload.iter_all_python_module_files", return_value=frozenset()
)
def test_glob(self, mocked_modules, notify_mock):
non_py_file = self.ensure_file(self.tempdir / "non_py_file... | IntegrationTests |
python | dagster-io__dagster | python_modules/libraries/dagster-looker/dagster_looker/api/components/looker_component.py | {
"start": 1547,
"end": 2212
} | class ____(Model, Resolvable):
"""Arguments for filtering which Looker content to load."""
dashboard_folders: Optional[list[list[str]]] = Field(
default=None,
description=(
"A list of folder paths to load dashboards from. Each folder path is a list of "
"folder names, st... | LookerFilterArgs |
python | apache__airflow | providers/microsoft/azure/src/airflow/providers/microsoft/azure/operators/data_factory.py | {
"start": 1615,
"end": 3092
} | class ____(LoggingMixin, BaseOperatorLink):
"""Construct a link to monitor a pipeline run in Azure Data Factory."""
name = "Monitor Pipeline Run"
def get_link(
self,
operator: BaseOperator,
*,
ti_key: TaskInstanceKey,
) -> str:
run_id = XCom.get_value(key="run_i... | AzureDataFactoryPipelineRunLink |
python | apache__airflow | providers/apache/hdfs/tests/unit/apache/hdfs/sensors/test_web_hdfs.py | {
"start": 1222,
"end": 2329
} | class ____:
@mock.patch("airflow.providers.apache.hdfs.hooks.webhdfs.WebHDFSHook")
def test_poke(self, mock_hook):
sensor = WebHdfsSensor(
task_id="test_task",
webhdfs_conn_id=TEST_HDFS_CONN,
filepath=TEST_HDFS_PATH,
)
exists = sensor.poke(dict())
... | TestWebHdfsSensor |
python | instagram__MonkeyType | monkeytype/typing.py | {
"start": 16385,
"end": 18594
} | class ____(TypeRewriter):
"""
Relace a union of classes by the most specific
common base of its members (while avoiding multiple
inheritance), i.e.,
Union[Derived1, Derived2] -> Base
"""
def _compute_bases(self, klass):
"""
Return list of bases of a given class,
goi... | RewriteMostSpecificCommonBase |
python | optuna__optuna | optuna/_gp/acqf.py | {
"start": 8390,
"end": 11389
} | class ____(BaseAcquisitionFunc):
def __init__(
self,
gpr_list: list[GPRegressor],
search_space: SearchSpace,
Y_train: torch.Tensor,
n_qmc_samples: int,
qmc_seed: int | None,
stabilizing_noise: float = 1e-12,
) -> None:
def _get_non_dominated_box_bo... | LogEHVI |
python | pydantic__pydantic | pydantic-core/python/pydantic_core/core_schema.py | {
"start": 51489,
"end": 52083
} | class ____(TypedDict, total=False):
type: Required[Literal['uuid']]
version: Literal[1, 3, 4, 5, 7]
strict: bool
ref: str
metadata: dict[str, Any]
serialization: SerSchema
def uuid_schema(
*,
version: Literal[1, 3, 4, 5, 6, 7, 8] | None = None,
strict: bool | None = None,
ref: ... | UuidSchema |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.