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 | sympy__sympy | sympy/vector/orienters.py | {
"start": 7197,
"end": 9089
} | class ____(ThreeAngleOrienter):
"""
Class to denote a space-orienter.
"""
_in_order = False
def __new__(cls, angle1, angle2, angle3, rot_order):
obj = ThreeAngleOrienter.__new__(cls, angle1, angle2, angle3,
rot_order)
return obj
def __i... | SpaceOrienter |
python | allegroai__clearml | clearml/backend_api/services/v2_20/models.py | {
"start": 124808,
"end": 127662
} | class ____(Request):
"""
Set the model ready flag to True. If the model is an output model of a task then try to publish the task.
:param model: Model id
:type model: str
:param force_publish_task: Publish the associated task (if exists) even if it
is not in the 'stopped' state. Optional, t... | SetReadyRequest |
python | tiangolo__fastapi | docs_src/python_types/tutorial011_py39.py | {
"start": 89,
"end": 492
} | class ____(BaseModel):
id: int
name: str = "John Doe"
signup_ts: Union[datetime, None] = None
friends: list[int] = []
external_data = {
"id": "123",
"signup_ts": "2017-06-01 12:22",
"friends": [1, "2", b"3"],
}
user = User(**external_data)
print(user)
# > User id=123 name='John Doe' signup... | User |
python | tiangolo__fastapi | docs_src/sql_databases/tutorial001_an_py310.py | {
"start": 160,
"end": 1768
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str = Field(index=True)
age: int | None = Field(default=None, index=True)
secret_name: str
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
connect_args = {"check_same_thread": ... | Hero |
python | PrefectHQ__prefect | tests/server/models/test_flow_runs.py | {
"start": 7661,
"end": 12671
} | class ____:
async def test_update_flow_run_succeeds(
self,
flow,
session,
):
job_vars = {"foo": "bar"}
flow_run = await models.flow_runs.create_flow_run(
session=session,
flow_run=schemas.core.FlowRun(flow_id=flow.id, flow_version="1.0"),
)... | TestUpdateFlowRun |
python | getsentry__sentry | src/sentry/integrations/slack/analytics.py | {
"start": 162,
"end": 294
} | class ____(analytics.Event):
actor_id: int | None = None
@analytics.eventclass("integrations.slack.status")
| SlackIntegrationAssign |
python | Lightning-AI__lightning | tests/tests_pytorch/models/test_hparams.py | {
"start": 2603,
"end": 2805
} | class ____(BoringDataModule):
"""Tests that a model can take an object."""
def __init__(self, hparams):
super().__init__()
self.save_hyperparameters(hparams)
| SaveHparamsDataModule |
python | instagram__MonkeyType | monkeytype/tracing.py | {
"start": 6380,
"end": 10532
} | class ____:
"""CallTracer captures the concrete types involved in a function invocation.
On a per function call basis, CallTracer will record the types of arguments
supplied, the type of the function's return value (if any), and the types
of values yielded by the function (if any). It emits a CallTrace... | CallTracer |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/sensors/test_glue.py | {
"start": 1089,
"end": 8664
} | class ____:
@mock.patch.object(GlueJobHook, "print_job_logs")
@mock.patch.object(GlueJobHook, "get_conn")
@mock.patch.object(GlueJobHook, "get_job_state")
def test_poke(self, mock_get_job_state, mock_conn, mock_print_job_logs):
mock_conn.return_value.get_job_run()
mock_get_job_state.retu... | TestGlueJobSensor |
python | pallets__jinja | tests/test_ext.py | {
"start": 10520,
"end": 16845
} | class ____:
def test_trans(self):
tmpl = i18n_env.get_template("child.html")
assert tmpl.render(LANGUAGE="de") == "<title>fehlend</title>pass auf"
def test_trans_plural(self):
tmpl = i18n_env.get_template("plural.html")
assert tmpl.render(LANGUAGE="de", user_count=1) == "Ein Ben... | TestInternationalization |
python | pytorch__pytorch | torch/testing/_internal/distributed/nn/api/remote_module_test.py | {
"start": 18550,
"end": 23067
} | class ____(CommonRemoteModuleTest):
@property
def world_size(self): # Override setting in CommonRemoteModuleTest
return 3
@dist_utils.dist_init
def test_send_remote_module_over_the_wire(self):
if self.rank != 0:
return
dst_worker1_name = dist_utils.worker_name((self... | ThreeWorkersRemoteModuleTest |
python | falconry__falcon | examples/ws_tutorial/ws_tutorial/app.py | {
"start": 1331,
"end": 2052
} | class ____:
def __init__(self, protected_routes: list[str] | None = None):
if protected_routes is None:
protected_routes = []
self.protected_routes = protected_routes
async def process_request_ws(self, req: Request, ws: WebSocket):
# Opening a connection so we can receive t... | AuthMiddleware |
python | python__mypy | mypy/nodes.py | {
"start": 136393,
"end": 146168
} | class ____(SymbolNode):
"""
A symbol node representing a type alias.
Type alias is a static concept, in contrast to variables with types
like Type[...]. Namely:
* type aliases
- can be used in type context (annotations)
- cannot be re-assigned
* variables with ty... | TypeAlias |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/cli_utils.py | {
"start": 279,
"end": 660
} | class ____(argparse.Action):
"""
Internal custom Action to raise warning when argument is called.
"""
def __init__(self, nargs=0, **kwargs):
super().__init__(nargs=nargs, **kwargs)
def __call__(self, arg_parser, namespace, values, option_string=None):
logger.warning(f"The command l... | RaiseRemovedWarning |
python | huggingface__transformers | src/transformers/models/csm/modular_csm.py | {
"start": 6351,
"end": 10858
} | class ____(LlamaModel, CsmPreTrainedModel):
config: CsmDepthDecoderConfig
def __init__(self, config):
super().__init__(config)
self.embed_tokens = nn.Embedding((config.num_codebooks * config.vocab_size), config.backbone_hidden_size)
self.inputs_embeds_projector = nn.Linear(config.backbo... | CsmDepthDecoderModel |
python | Textualize__textual | src/textual/eta.py | {
"start": 149,
"end": 4645
} | class ____:
"""Calculate speed and estimate time to arrival."""
def __init__(
self, estimation_period: float = 60, extrapolate_period: float = 30
) -> None:
"""Create an ETA.
Args:
estimation_period: Period in seconds, used to calculate speed.
extrapolate_pe... | ETA |
python | google__pytype | pytype/abstract/_typing.py | {
"start": 21891,
"end": 22046
} | class ____(_TypeVariable):
"""Parameter of a callable type (typing.ParamSpec)."""
_INSTANCE_CLASS: type[ParamSpecInstance] = ParamSpecInstance
| ParamSpec |
python | spyder-ide__spyder | spyder/plugins/ipythonconsole/widgets/figurebrowser.py | {
"start": 470,
"end": 2611
} | class ____(RichJupyterWidget):
"""
Widget with the necessary attributes and methods to intercept the figures
sent by the kernel to the IPython Console and send it to the plots plugin.
This widget can also block the plotting of inline figures in the IPython
Console so that figures are only plotted in... | FigureBrowserWidget |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/comprehend.py | {
"start": 3470,
"end": 9825
} | class ____(ComprehendBaseOperator):
"""
Create a comprehend pii entities detection job for a collection of documents.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:ComprehendStartPiiEntitiesDetectionJobOperator`
:param inp... | ComprehendStartPiiEntitiesDetectionJobOperator |
python | Textualize__textual | docs/examples/how-to/layout.py | {
"start": 183,
"end": 299
} | class ____(Placeholder):
DEFAULT_CSS = """
Header {
height: 3;
dock: top;
}
"""
| Header |
python | falconry__falcon | tests/asgi/_asgi_test_app.py | {
"start": 4463,
"end": 7184
} | class ____:
async def on_get(self, req, resp):
async def emit():
s = 0
while s <= SSE_TEST_MAX_DELAY_SEC:
yield falcon.asgi.SSEvent(text='hello world')
await asyncio.sleep(s)
s += SSE_TEST_MAX_DELAY_SEC / 4
resp.sse = emit()
... | Events |
python | kamyu104__LeetCode-Solutions | Python/design-spreadsheet.py | {
"start": 149,
"end": 972
} | class ____(object):
def __init__(self, rows):
"""
:type rows: int
"""
self.__lookup = collections.defaultdict(int)
def setCell(self, cell, value):
"""
:type cell: str
:type value: int
:rtype: None
"""
self.__lookup[cell] = value
... | Spreadsheet |
python | numba__numba | numba/tests/test_parallel_backend.py | {
"start": 39187,
"end": 41581
} | class ____(TestCase):
_DEBUG = False
def run_cmd(self, cmdline):
popen = subprocess.Popen(cmdline,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,)
# finish in _TEST_TIMEOUT seconds or kill it
timeout = threading.Timer(_... | TestInitSafetyIssues |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/database.py | {
"start": 28278,
"end": 41324
} | class ____(ExampleDatabase):
"""
A file-based database loaded from a `GitHub Actions <https://docs.github.com/en/actions>`_ artifact.
You can use this for sharing example databases between CI runs and developers, allowing
the latter to get read-only access to the former. This is particularly useful for... | GitHubArtifactDatabase |
python | getsentry__sentry | tests/sentry/hybridcloud/test_organizationmembermapping.py | {
"start": 652,
"end": 6759
} | class ____(TransactionTestCase, HybridCloudTestMixin):
def test_upsert_stale_user_id(self) -> None:
organizationmember_mapping_service.upsert_mapping(
organization_id=self.organization.id,
organizationmember_id=111111,
mapping=RpcOrganizationMemberMappingUpdate(
... | OrganizationMappingTest |
python | ansible__ansible | lib/ansible/modules/hostname.py | {
"start": 25933,
"end": 26052
} | class ____(Hostname):
platform = 'SunOS'
distribution = None
strategy_class = SolarisStrategy
| SolarisHostname |
python | pyinstaller__pyinstaller | PyInstaller/building/build_main.py | {
"start": 14974,
"end": 17171
} | class ____(enum.IntFlag):
"""
Module collection mode flags.
"""
PYZ = enum.auto() # Collect byte-compiled .pyc into PYZ archive
PYC = enum.auto() # Collect byte-compiled .pyc as external data file
PY = enum.auto() # Collect source .py file as external data file
_MODULE_COLLECTION_MODES = {
... | _ModuleCollectionMode |
python | django__django | tests/migrations/test_migrations_no_ancestor/0002_conflicting_second.py | {
"start": 43,
"end": 618
} | class ____(migrations.Migration):
dependencies = []
operations = [
migrations.DeleteModel("Tribble"),
migrations.RemoveField("Author", "silly_field"),
migrations.AddField("Author", "rating", models.IntegerField(default=0)),
migrations.CreateModel(
"Book",
... | Migration |
python | numba__numba | numba/tests/test_unicode.py | {
"start": 92138,
"end": 93279
} | class ____(BaseTest):
def test_unicode_iter(self):
pyfunc = iter_usecase
cfunc = njit(pyfunc)
for a in UNICODE_EXAMPLES:
self.assertPreciseEqual(pyfunc(a), cfunc(a))
def test_unicode_literal_iter(self):
pyfunc = literal_iter_usecase
cfunc = njit(pyfunc)
... | TestUnicodeIteration |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol24.py | {
"start": 752,
"end": 808
} | class ____(Protocol):
def jump(self) -> int: ...
| Jumps |
python | allegroai__clearml | clearml/backend_api/services/v2_9/events.py | {
"start": 99006,
"end": 101007
} | class ____(Request):
"""
Get histogram data of all the scalar metrics and variants in the task
:param task: Task ID
:type task: str
:param metric:
:type metric: str
:param variant:
:type variant: str
"""
_service = "events"
_action = "vector_metrics_iter_histogram"
_ver... | VectorMetricsIterHistogramRequest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1236390,
"end": 1242161
} | class ____(sgqlc.types.Type, Node, Closable, UniformResourceLocatable):
"""Represents a Milestone object on a given repository."""
__schema__ = github_schema
__field_names__ = (
"created_at",
"creator",
"description",
"due_on",
"issues",
"number",
"pr... | Milestone |
python | django-crispy-forms__django-crispy-forms | crispy_forms/base.py | {
"start": 0,
"end": 744
} | class ____:
"""
Context manager that receives a `django.template.Context` instance and a list of keys
Once the context manager is exited, it removes `keys` from the context, to avoid
side effects in later layout objects that may use the same context variables.
Layout objects should use `extra_cont... | KeepContext |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/math_ops/reduction_ops_test.py | {
"start": 33892,
"end": 39383
} | class ____(test.TestCase):
def _compare(self, x, reduction_axes, keepdims, use_gpu=False):
np_ans = x
if reduction_axes is None:
np_ans = np.amax(np_ans, keepdims=keepdims)
else:
for ra in reduction_axes[::-1]:
np_ans = np.amax(np_ans, axis=ra, keepdims=keepdims)
with self.cached_... | MaxReductionTest |
python | getsentry__sentry | tests/sentry/issue_detection/test_n_plus_one_db_span_detector.py | {
"start": 12491,
"end": 13319
} | class ____(TestCase):
def test_respects_project_option(self) -> None:
project = self.create_project()
event = get_event("n-plus-one-db/n-plus-one-in-django-index-view-activerecord")
event["project_id"] = project.id
settings = get_detection_settings(project.id)
detector = NPl... | NPlusOneDbSettingTest |
python | pandas-dev__pandas | pandas/tests/indexing/interval/test_interval.py | {
"start": 5349,
"end": 7538
} | class ____:
def test_mi_intervalindex_slicing_with_scalar(self):
# GH#27456
ii = IntervalIndex.from_arrays(
[0, 1, 10, 11, 0, 1, 10, 11], [1, 2, 11, 12, 1, 2, 11, 12], name="MP"
)
idx = pd.MultiIndex.from_arrays(
[
pd.Index(["FC", "FC", "FC", "... | TestIntervalIndexInsideMultiIndex |
python | milvus-io__pymilvus | tests/test_grpc_handler_mutations.py | {
"start": 16023,
"end": 19312
} | class ____:
def test_get_query_segment_info(self, channel: Any, client_thread: Any) -> None:
handler = GrpcHandler(channel=channel)
info_future = client_thread.submit(
handler.get_query_segment_info,
collection_name="test_collection",
timeout=30
)
... | TestGrpcHandlerSegmentAndAliasOperations |
python | openai__openai-python | src/openai/types/batch_usage.py | {
"start": 192,
"end": 413
} | class ____(BaseModel):
cached_tokens: int
"""The number of tokens that were retrieved from the cache.
[More on prompt caching](https://platform.openai.com/docs/guides/prompt-caching).
"""
| InputTokensDetails |
python | django__django | tests/auth_tests/test_views.py | {
"start": 3560,
"end": 4578
} | class ____(AuthViewsTestCase):
def test_named_urls(self):
"Named URLs should be reversible"
expected_named_urls = [
("login", [], {}),
("logout", [], {}),
("password_change", [], {}),
("password_change_done", [], {}),
("password_reset", [],... | AuthViewNamedURLTests |
python | pydata__xarray | xarray/tests/test_backends.py | {
"start": 162176,
"end": 172422
} | class ____(ZarrBase):
@contextlib.contextmanager
def create_zarr_target(self):
if has_zarr_v3:
yield zarr.storage.MemoryStore({}, read_only=False)
else:
yield {}
def test_chunk_key_encoding_v2(self) -> None:
encoding = {"name": "v2", "configuration": {"separa... | TestZarrDictStore |
python | jazzband__django-waffle | test_app/models.py | {
"start": 631,
"end": 720
} | class ____(AbstractBaseSwitch):
"""Demonstrates custom switch behavior."""
| CustomSwitch |
python | cython__cython | docs/examples/tutorial/pure/A.py | {
"start": 94,
"end": 225
} | class ____:
def __init__(self, b=0):
self.a = 3
self.b = b
def foo(self, x):
print(x + _helper(1.0))
| A |
python | kubernetes-client__python | kubernetes/client/models/v1_validating_admission_policy.py | {
"start": 383,
"end": 7646
} | 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... | V1ValidatingAdmissionPolicy |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zoho-crm/source_zoho_crm/types.py | {
"start": 1873,
"end": 2507
} | class ____:
@classmethod
def _field_names(cls) -> Iterable[str]:
return [field.name for field in dataclasses.fields(cls)]
@classmethod
def _filter_by_names(cls, dct: Dict[Any, Any]) -> Dict[Any, Any]:
return {key: val for key, val in dct.items() if key in cls._field_names()}
@class... | FromDictMixin |
python | matplotlib__matplotlib | lib/matplotlib/tri/_triinterpolate.py | {
"start": 24071,
"end": 41335
} | class ____:
"""
Implementation of reduced HCT triangular element with explicit shape
functions.
Computes z, dz, d2z and the element stiffness matrix for bending energy:
E(f) = integral( (d2z/dx2 + d2z/dy2)**2 dA)
*** Reference for the shape functions: ***
[1] Basis functions for general Hs... | _ReducedHCT_Element |
python | ansible__ansible | packaging/release.py | {
"start": 9392,
"end": 9647
} | class ____:
"""Details required to create a pull request."""
upstream_user: str
upstream_repo: str
upstream_branch: str
user: str
repo: str
branch: str
title: str
body: str
@dataclasses.dataclass(frozen=True)
| PullRequest |
python | ZoranPandovski__al-go-rithms | machine_learning/Neural_Networks/Back Propogation/back_propagation_neural_network.py | {
"start": 3021,
"end": 5997
} | class ____:
"""
Back Propagation Neural Network model
"""
def __init__(self):
self.layers = []
self.train_mse = []
self.fig_loss = plt.figure()
self.ax_loss = self.fig_loss.add_subplot(1, 1, 1)
def add_layer(self, layer):
self.layers.append(layer)
def b... | BPNN |
python | django__django | tests/multiple_database/tests.py | {
"start": 97533,
"end": 97724
} | class ____:
"""Disallow all relations."""
def allow_relation(self, obj1, obj2, **hints):
return False
@override_settings(DATABASE_ROUTERS=[NoRelationRouter()])
| NoRelationRouter |
python | google__jax | jax/_src/pallas/mosaic/interpret/interpret_pallas_call.py | {
"start": 7482,
"end": 31506
} | class ____:
"""A simple counter that is thread-safe."""
def __init__(self, initial_value: int):
self.value = initial_value
self.lock = threading.Lock()
def get_next(self):
with self.lock:
result = self.value
self.value += 1
return result
# TODO(jburnim): Do we want to support multi... | Counter |
python | huggingface__transformers | src/transformers/integrations/ggml.py | {
"start": 24000,
"end": 24437
} | class ____(GPT2Converter):
def __init__(self, tokenizer_dict):
self.original_tokenizer = GGUFTokenizerSkeleton(tokenizer_dict)
self.additional_kwargs = {}
def converted(self) -> Tokenizer:
vocab = {word: i for i, word in enumerate(self.original_tokenizer.tokens)}
merges = self.o... | GGUFGPTConverter |
python | scrapy__scrapy | tests/test_downloader_handlers.py | {
"start": 4928,
"end": 10584
} | class ____:
download_handler_cls: type = S3DownloadHandler
# test use same example keys than amazon developer guide
# http://s3.amazonaws.com/awsdocs/S3/20060301/s3-dg-20060301.pdf
# and the tests described here are the examples from that manual
AWS_ACCESS_KEY_ID = "0PN5J17HBGZHT7JJ3X82"
AWS_S... | TestS3 |
python | kubernetes-client__python | kubernetes/client/models/v1_service_backend_port.py | {
"start": 383,
"end": 4495
} | 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... | V1ServiceBackendPort |
python | fluentpython__example-code-2e | 12-seq-hacking/vector_v2.py | {
"start": 2251,
"end": 3486
} | 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 | walkccc__LeetCode | solutions/1983. Widest Pair of Indices With Equal Range Sum/1983.py | {
"start": 0,
"end": 311
} | class ____:
def widestPairOfIndices(self, nums1: list[int], nums2: list[int]) -> int:
ans = 0
prefix = 0
prefixToIndex = {0: -1}
for i, (num1, num2) in enumerate(zip(nums1, nums2)):
prefix += num1 - num2
ans = max(ans, i - prefixToIndex.setdefault(prefix, i))
return ans
| Solution |
python | wandb__wandb | wandb/sdk/artifacts/_generated/project_artifact_type.py | {
"start": 253,
"end": 343
} | class ____(GQLResult):
project: Optional[ProjectArtifactTypeProject]
| ProjectArtifactType |
python | automl__auto-sklearn | autosklearn/metalearning/input/aslib_simple.py | {
"start": 183,
"end": 5965
} | class ____(object):
def __init__(self, directory: str, cs: ConfigurationSpace):
self.logger = logging.getLogger(__name__)
# Create data structures
self.cs = cs
self.dir_ = directory
self.algorithm_runs = None
self.configurations = None
self.metafeatures = Non... | AlgorithmSelectionProblem |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/class_interval.py | {
"start": 2087,
"end": 2242
} | class ____(B4):
def m0(self, x):
self.m1(x)
def source_two_hops(d: D4):
d.m0(_test_source())
"""
A5
/ \
B5 C5
|
D5
"""
| D4 |
python | scikit-learn__scikit-learn | sklearn/utils/tests/test_testing.py | {
"start": 8105,
"end": 8355
} | class ____:
def __init__(self):
"""MockEstimator"""
def fit(self, X, y):
return X
def predict(self, X):
return X
def predict_proba(self, X):
return X
def score(self, X):
return 1.0
| MockEst |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-tplcentral/source_tplcentral/streams.py | {
"start": 3051,
"end": 3445
} | class ____(TplcentralStream):
# https://api.3plcentral.com/rels/customers/customers
upstream_primary_key = "ReadOnly.CustomerId"
collection_field = "ResourceList"
page_size = 100
def path(
self, stream_state: Mapping[str, Any] = None, stream_slice: Mapping[str, Any] = None, next_page_token:... | Customers |
python | Lightning-AI__lightning | src/lightning/pytorch/trainer/connectors/data_connector.py | {
"start": 12317,
"end": 15268
} | class ____:
"""Stores the information where the dataloaders come from.
The source can be
1. from a ``*_dataloader()`` method on the :class:`~lightning.pytorch.core.LightningModule`,
2. from a ``*_dataloader()`` method on the :class:`~lightning.pytorch.core.datamodule.LightningDataModule`,
3. a dir... | _DataLoaderSource |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 199107,
"end": 199281
} | class ____(VegaLiteSchema):
"""Blend schema wrapper."""
_schema = {"$ref": "#/definitions/Blend"}
def __init__(self, *args):
super().__init__(*args)
| Blend |
python | has2k1__plotnine | tests/test_geom_boxplot.py | {
"start": 688,
"end": 2865
} | class ____:
p = (
ggplot(data, aes("x"))
+ geom_boxplot(aes(y="y"), size=2)
+ geom_boxplot(data[: 2 * m], aes(y="y+25", fill="x"), size=2)
+ geom_boxplot(data[2 * m :], aes(y="y+30", color="x"), size=2)
+ geom_boxplot(data[2 * m :], aes(y="y+55", linetype="x"), size=2)
)
... | TestAesthetics |
python | numpy__numpy | numpy/_core/tests/test_records.py | {
"start": 307,
"end": 13344
} | class ____:
def test_fromrecords(self):
r = np.rec.fromrecords([[456, 'dbe', 1.2], [2, 'de', 1.3]],
names='col1,col2,col3')
assert_equal(r[0].item(), (456, 'dbe', 1.2))
assert_equal(r['col1'].dtype.kind, 'i')
assert_equal(r['col2'].dtype.kind, 'U')
... | TestFromrecords |
python | Textualize__textual | src/textual/widgets/_markdown.py | {
"start": 22497,
"end": 22573
} | class ____(MarkdownBlock):
"""A table header Markdown block."""
| MarkdownTH |
python | google__jax | tests/tree_util_test.py | {
"start": 4606,
"end": 4668
} | class ____(tuple):
pass
@tree_util.register_static
| StaticTuple |
python | EpistasisLab__tpot | tpot/builtin_modules/nn.py | {
"start": 2859,
"end": 3542
} | class ____(BaseEstimator):
"""Base class for Pytorch-based estimators (currently only classifiers) for
use in TPOT.
In the future, these will be merged into TPOT's main code base.
"""
@abstractmethod
def fit(self, X, y): # pragma: no cover
pass
@abstractmethod
def transform(se... | PytorchEstimator |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/distributions/util_test.py | {
"start": 18991,
"end": 19681
} | class ____(test.TestCase):
@test_util.run_deprecated_v1
def testCorrectlyPicksVector(self):
with self.cached_session():
x = np.arange(10, 12)
y = np.arange(15, 18)
self.assertAllEqual(
x, self.evaluate(du.pick_vector(math_ops.less(0, 5), x, y)))
self.assertAllEqual(
... | PickVectorTest |
python | run-llama__llama_index | llama-index-integrations/retrievers/llama-index-retrievers-tldw/llama_index/retrievers/tldw/base.py | {
"start": 405,
"end": 594
} | class ____(BaseModel):
"""Represents a fragment of a video scene with metadata."""
uuid: str
start_ms: float
end_ms: float
similarity: float
description: str
| Fragment |
python | matplotlib__matplotlib | lib/matplotlib/collections.py | {
"start": 65099,
"end": 65285
} | class ____(RegularPolyCollection):
"""Draw a collection of regular asterisks with *numsides* points."""
_path_generator = mpath.Path.unit_regular_asterisk
| AsteriskPolygonCollection |
python | pypa__setuptools | setuptools/command/build_ext.py | {
"start": 2879,
"end": 18505
} | class ____(_build_ext):
distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
editable_mode = False
inplace = False
def run(self) -> None:
"""Build extensions in build directory, then copy if --inplace"""
old_inplace, self.inplace = self.in... | build_ext |
python | joke2k__faker | faker/providers/automotive/ar_BH/__init__.py | {
"start": 48,
"end": 275
} | class ____(AutomotiveProvider):
"""Implement automotive provider for ``ar_BH`` locale.
Source:
- https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Bahrain
"""
license_formats = ("######",)
| Provider |
python | gevent__gevent | src/greentest/3.10/test_signal.py | {
"start": 28080,
"end": 40369
} | class ____(unittest.TestCase):
"""
Test pthread_sigmask(), pthread_kill(), sigpending() and sigwait()
functions.
"""
@unittest.skipUnless(hasattr(signal, 'sigpending'),
'need signal.sigpending()')
def test_sigpending_empty(self):
self.assertEqual(signal.sigpendin... | PendingSignalsTests |
python | getsentry__sentry | src/sentry_plugins/bitbucket/endpoints/webhook.py | {
"start": 1105,
"end": 3317
} | class ____(Webhook):
# https://confluence.atlassian.com/bitbucket/event-payloads-740262817.html#EventPayloads-Push
def __call__(self, organization_id: int, event):
authors = {}
try:
repo = Repository.objects.get(
organization_id=organization_id,
provi... | PushEventWebhook |
python | streamlit__streamlit | lib/tests/streamlit/runtime/caching/cache_data_api_test.py | {
"start": 20069,
"end": 20979
} | class ____(DeltaGeneratorTestCase):
"""st.cache_data disk persistence tests"""
def setUp(self) -> None:
super().setUp()
mock_runtime = MagicMock(spec=Runtime)
mock_runtime.cache_storage_manager = AlwaysFailingTestCacheStorageManager()
Runtime._instance = mock_runtime
def te... | CacheDataValidateParamsTest |
python | Pylons__pyramid | src/pyramid/exceptions.py | {
"start": 2361,
"end": 2802
} | class ____(UnicodeDecodeError):
"""
This exception is raised when :app:`Pyramid` cannot
successfully decode a URL or a URL path segment. This exception
behaves just like the Python builtin
:exc:`UnicodeDecodeError`. It is a subclass of the builtin
:exc:`UnicodeDecodeError` exception only for id... | URLDecodeError |
python | sympy__sympy | sympy/printing/theanocode.py | {
"start": 2621,
"end": 19094
} | class ____(Printer):
""" Code printer which creates Theano symbolic expression graphs.
Parameters
==========
cache : dict
Cache dictionary to use. If None (default) will use
the global cache. To create a printer which does not depend on or alter
global state pass an empty dicti... | TheanoPrinter |
python | Lightning-AI__lightning | src/lightning/pytorch/_graveyard/tpu.py | {
"start": 2427,
"end": 2866
} | class ____(XLAPrecision):
"""Legacy class.
Use :class:`~lightning.pytorch.plugins.precision.xla.XLAPrecision` instead.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
rank_zero_deprecation(
"The `TPUPrecisionPlugin` class is deprecated. Use `lightning.pytorch.plugins.pr... | TPUPrecisionPlugin |
python | huggingface__transformers | src/transformers/models/kosmos2/modeling_kosmos2.py | {
"start": 7475,
"end": 12132
} | class ____(nn.Module):
def __init__(self, config: Kosmos2VisionConfig):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.image_size = config.image_size
self.patch_size = config.patch_size
self.class_embedding = nn.Parameter(torch.randn... | Kosmos2VisionEmbeddings |
python | facebookresearch__faiss | tests/test_fast_scan.py | {
"start": 21417,
"end": 21862
} | class ____(unittest.TestCase):
def test_issue_2739(self):
ds = datasets.SyntheticDataset(960, 200, 1, 0)
M = 32
index = faiss.index_factory(ds.d, f"PQ{M}x4fs")
index.train(ds.get_train())
index.add(ds.get_database())
np.testing.assert_array_equal(
index.... | TestBlockDecode |
python | wireservice__csvkit | tests/utils.py | {
"start": 2587,
"end": 2805
} | class ____:
def test_empty(self):
with open('examples/empty.csv', 'rb') as f, stdin_as_string(f):
utility = self.Utility(getattr(self, 'default_args', []))
utility.run()
| EmptyFileTests |
python | django__django | django/contrib/contenttypes/admin.py | {
"start": 4996,
"end": 5099
} | class ____(GenericInlineModelAdmin):
template = "admin/edit_inline/stacked.html"
| GenericStackedInline |
python | PrefectHQ__prefect | tests/test_flows.py | {
"start": 172837,
"end": 178575
} | class ____:
def test_load_flow_name_from_entrypoint(self, tmp_path: Path):
flow_source = dedent(
"""
from prefect import flow
@flow(name="My custom name")
def flow_function(name: str) -> str:
return name
"""
)
tmp_path.joinpath("flow... | TestLoadFlowArgumentFromEntrypoint |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/util/typing.py | {
"start": 2471,
"end": 3030
} | class ____(Protocol[_T]):
"""protocol for generic types.
this since Python.typing _GenericAlias is private
"""
__args__: Tuple[_AnnotationScanType, ...]
__origin__: Type[_T]
# Python's builtin _GenericAlias has this method, however builtins like
# list, dict, etc. do not, even though the... | GenericProtocol |
python | encode__starlette | starlette/convertors.py | {
"start": 388,
"end": 715
} | class ____(Convertor[str]):
regex = "[^/]+"
def convert(self, value: str) -> str:
return value
def to_string(self, value: str) -> str:
value = str(value)
assert "/" not in value, "May not contain path separators"
assert value, "Must not be empty"
return value
| StringConvertor |
python | huggingface__transformers | src/transformers/models/dac/modeling_dac.py | {
"start": 3273,
"end": 3544
} | class ____(ModelOutput):
r"""
audio_values (`torch.FloatTensor` of shape `(batch_size, input_length)`, *optional*):
Decoded audio values, obtained using the decoder part of Dac.
"""
audio_values: Optional[torch.FloatTensor] = None
| DacDecoderOutput |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_highlight.py | {
"start": 6985,
"end": 7654
} | class ____(util.MdCase):
"""Test no class."""
extension = ['pymdownx.highlight', 'pymdownx.superfences']
extension_configs = {
'pymdownx.highlight': {
'css_class': '',
'use_pygments': False
}
}
def test_no_class_no_pygments(self):
"""Test with no cla... | TestNoClassNoPygments |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType28.py | {
"start": 1692,
"end": 1818
} | class ____(Class6[T_co, T_co]): ...
# This should generate an error because T_contra isn't
# compatible with T_co.
| Class6_Child2 |
python | jschneier__django-storages | storages/compress.py | {
"start": 1133,
"end": 1295
} | class ____:
def _compress_content(self, content):
"""Gzip a given string content."""
return GzipCompressionWrapper(content)
| CompressStorageMixin |
python | modin-project__modin | stress_tests/kaggle/kaggle4.py | {
"start": 9412,
"end": 10067
} | class ____(BaseEstimator, RegressorMixin, TransformerMixin):
def __init__(self, models):
self.models = models
def fit(self, X, y):
self.models_ = [clone(x) for x in self.models]
for model in self.models_:
model.fit(X, y)
return self
def predict(self, X):
... | AveragingModels |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_contextlib.py | {
"start": 15315,
"end": 15574
} | class ____(__TestCase):
def test_nullcontext(self):
with torch._dynamo.error_on_graph_break(False):
class C:
pass
c = C()
with nullcontext(c) as c_in:
self.assertIs(c_in, c)
| NullcontextTestCase |
python | doocs__leetcode | solution/1700-1799/1711.Count Good Meals/Solution2.py | {
"start": 0,
"end": 377
} | class ____:
def countPairs(self, deliciousness: List[int]) -> int:
mod = 10**9 + 7
cnt = Counter(deliciousness)
ans = 0
for i in range(22):
s = 1 << i
for a, m in cnt.items():
if (b := s - a) in cnt:
ans += m * (m - 1) if a ... | Solution |
python | apache__airflow | providers/standard/src/airflow/providers/standard/sensors/time_delta.py | {
"start": 6183,
"end": 7449
} | class ____(BaseSensorOperator):
"""
A sensor that waits a specified period of time before completing.
This differs from TimeDeltaSensor because the time to wait is measured from the start of the task, not
the data_interval_end of the DAG run.
:param time_to_wait: time length to wait after the task... | WaitSensor |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/emr.py | {
"start": 49345,
"end": 64274
} | class ____(AwsBaseOperator[EmrServerlessHook]):
"""
Operator to start EMR Serverless job.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:EmrServerlessStartJobOperator`
:param application_id: ID of the EMR Serverless applica... | EmrServerlessStartJobOperator |
python | pytorch__pytorch | torch/testing/_internal/common_quantization.py | {
"start": 70349,
"end": 70885
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.fc1 = torch.nn.Linear(5, 5).to(dtype=torch.float)
self.relu = torch.nn.ReLU()
self.fc2 = torch.nn.Linear(5, 5).to(dtype=torch.float)
def forward(self, x):
x = self.fc1(x)
x = self.re... | LinearReluAddModel |
python | apache__airflow | providers/hashicorp/tests/unit/hashicorp/hooks/test_vault.py | {
"start": 58178,
"end": 61389
} | class ____:
@mock.patch("airflow.providers.hashicorp._internal_client.vault_client.hvac")
@conf_vars(
{
("secrets", "backend"): "airflow.providers.hashicorp.secrets.vault.VaultBackend",
("secrets", "backend_kwargs"): '{"url": "http://127.0.0.1:8200", "token": "token"}',
}... | TestConfigurationFromSecrets |
python | ansible__ansible | test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/lookup/mylookup.py | {
"start": 84,
"end": 207
} | class ____(LookupBase):
def run(self, terms, variables, **kwargs):
return ['mylookup_from_user_dir']
| LookupModule |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 9782,
"end": 10171
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = (
"COMMUNITY_BRIDGE",
"CUSTOM",
"GITHUB",
"ISSUEHUNT",
"KO_FI",
"LFX_CROWDFUNDING",
"LIBERAPAY",
"OPEN_COLLECTIVE",
... | FundingPlatform |
python | matplotlib__matplotlib | lib/matplotlib/category.py | {
"start": 3675,
"end": 4196
} | class ____(ticker.Locator):
"""Tick at every integer mapping of the string data."""
def __init__(self, units_mapping):
"""
Parameters
----------
units_mapping : dict
Mapping of category names (str) to indices (int).
"""
self._units = units_mapping
... | StrCategoryLocator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-microsoft-sharepoint/source_microsoft_sharepoint/spec.py | {
"start": 1424,
"end": 2624
} | class ____(BaseModel):
"""
ServiceCredentials class for service key authentication.
This class is structured similarly to OAuthCredentials but for a different authentication method.
"""
class Config:
title = "Service Key Authentication"
# Fields for the Service authentication, similar ... | ServiceCredentials |
python | viewflow__viewflow | viewflow/workflow/migrations/0005_merge.py | {
"start": 108,
"end": 288
} | class ____(migrations.Migration):
dependencies = [
("viewflow", "0004_subprocess"),
("viewflow", "0004_extend_fields_length"),
]
operations = []
| Migration |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.