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 | encode__django-rest-framework | tests/test_validators.py | {
"start": 815,
"end": 983
} | class ____(models.Model):
user = models.OneToOneField(UniquenessModel, on_delete=models.CASCADE)
email = models.CharField(unique=True, max_length=80)
| RelatedModel |
python | optuna__optuna | tests/artifacts_tests/stubs.py | {
"start": 234,
"end": 589
} | class ____:
def open_reader(self, artifact_id: str) -> BinaryIO:
raise Exception("something error raised")
def write(self, artifact_id: str, content_body: BinaryIO) -> None:
raise Exception("something error raised")
def remove(self, artifact_id: str) -> None:
raise Exception("somet... | FailArtifactStore |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/tokens.py | {
"start": 8620,
"end": 8711
} | class ____(Token):
__slots__ = ()
id = '<block mapping start>'
| BlockMappingStartToken |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_numeric.py | {
"start": 102865,
"end": 103267
} | class ____(TestCase):
def test_outer_out_param(self):
arr1 = np.ones((5,))
arr2 = np.ones((2,))
arr3 = np.linspace(-2, 2, 5)
out1 = np.empty(shape=(5, 5))
out2 = np.empty(shape=(2, 5))
res1 = np.outer(arr1, arr3, out1)
assert_equal(res1, out1)
assert_e... | TestOuterMisc |
python | astropy__astropy | astropy/units/format/vounit.py | {
"start": 694,
"end": 8093
} | class ____(Base, _GenericParserMixin):
"""
The IVOA standard for units used by the VO.
This is an implementation of `Units in the VO 1.0
<https://www.ivoa.net/documents/VOUnits/20140523/index.html>`_.
"""
_explicit_custom_unit_regex: ClassVar[Pattern[str]] = re.compile(
r"^[YZEPTGMkhdc... | VOUnit |
python | allegroai__clearml | clearml/backend_api/services/v2_23/workers.py | {
"start": 64045,
"end": 70435
} | class ____(Request):
"""
Returns statistics for the selected workers and time range aggregated by date intervals.
:param worker_ids: List of worker ids to collect metrics for. If not provided
or empty then all the company workers metrics are analyzed.
:type worker_ids: Sequence[str]
:param ... | GetStatsRequest |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py | {
"start": 10569,
"end": 12335
} | class ____:
assetKey = graphene.Field(GrapheneAssetKey)
runOrError = graphene.NonNull("dagster_graphql.schema.pipelines.pipeline.GrapheneRunOrError")
stepStats = graphene.NonNull(lambda: GrapheneRunStepStats)
partition = graphene.Field(graphene.String)
tags = non_null_list(GrapheneEventTag)
def... | AssetEventMixin |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_bigquery.py | {
"start": 15183,
"end": 17776
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.bigquery.BigQueryHook")
def test_execute(self, mock_hook):
table_resource = {"friendlyName": "Test TB"}
operator = BigQueryUpdateTableOperator(
table_resource=table_resource,
task_id=TASK_ID,
da... | TestBigQueryUpdateTableOperator |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/lambda13.py | {
"start": 527,
"end": 940
} | class ____(Generic[T]):
def __init__(self, value: T) -> None:
self.value = value
def func2(callable: Callable[[type[A[T]]], A[T]]) -> T:
return callable(A).value
v3 = func2(lambda A: A(0))
reveal_type(v3, expected_text="int")
v4 = func2(lambda A: A(""))
reveal_type(v4, expected_text="str")
def te... | A |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/pg8000.py | {
"start": 4746,
"end": 4843
} | class ____(_PGNumeric):
def bind_processor(self, dialect):
return None
| _PGNumericNoBind |
python | huggingface__transformers | src/transformers/models/udop/modeling_udop.py | {
"start": 10828,
"end": 15716
} | class ____(PreTrainedModel):
config: UdopConfig
base_model_prefix = "transformer"
input_modalities = ("image", "text")
supports_gradient_checkpointing = True
_can_compile_fullgraph = False
_keep_in_fp32_modules = ["wo"]
@torch.no_grad()
def _init_weights(self, module):
"""Initi... | UdopPreTrainedModel |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/partitions/snap/snap.py | {
"start": 7993,
"end": 9263
} | class ____(PartitionsSnap):
partition_dimensions: Sequence[PartitionDimensionSnap]
@classmethod
def from_def(cls, partitions_def: "MultiPartitionsDefinition") -> Self: # pyright: ignore[reportIncompatibleMethodOverride]
from dagster._core.definitions.partitions.definition import MultiPartitionsDef... | MultiPartitionsSnap |
python | tensorflow__tensorflow | tensorflow/python/distribute/mirrored_strategy_test.py | {
"start": 55072,
"end": 57780
} | class ____(
multi_worker_test_base.MultiWorkerTestBase,
strategy_test_lib.DistributionTestBase):
@classmethod
def setUpClass(cls):
"""Create a local cluster with 2 workers and 1 chief."""
cls._cluster_spec = multi_worker_test_base.create_in_process_cluster(
num_workers=2, num_ps=0, has_chie... | MultiWorkerMirroredStrategyTestWithChief |
python | Netflix__metaflow | metaflow/plugins/debug_logger.py | {
"start": 265,
"end": 879
} | class ____(object):
def __init__(self):
pass
def process_message(self, msg):
# type: (Message) -> None
if msg.msg_type == MessageTypes.SHUTDOWN:
print("Debug[shutdown]: got shutdown!", file=sys.stderr)
self._shutdown()
elif msg.msg_type == MessageTypes.BE... | DebugEventLoggerSidecar |
python | huggingface__transformers | src/transformers/models/dpr/modeling_dpr.py | {
"start": 17736,
"end": 21934
} | class ____(DPRPretrainedReader):
def __init__(self, config: DPRConfig):
super().__init__(config)
self.config = config
self.span_predictor = DPRSpanPredictor(config)
# Initialize weights and apply final processing
self.post_init()
@auto_docstring
def forward(
... | DPRReader |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_notifications.py | {
"start": 581,
"end": 2536
} | class ____(TestCase):
def test_notification_custom(self, send, render_to_string):
render_to_string.return_value = "Test"
class TestNotification(EmailNotification):
name = "foo"
subject = "This is {{ foo.id }}"
context_object_name = "foo"
user = fixture.g... | NotificationTests |
python | walkccc__LeetCode | solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041.py | {
"start": 0,
"end": 338
} | class ____:
def maxSelectedElements(self, nums: list[int]) -> int:
ans = 0
# {num: the length of the longest consecutive elements ending in num}
dp = {}
for num in sorted(nums):
dp[num + 1] = dp.get(num, 0) + 1
dp[num] = dp.get(num - 1, 0) + 1
ans = max(ans, dp[num], dp[num + 1])
... | Solution |
python | scikit-learn__scikit-learn | sklearn/cross_decomposition/_pls.py | {
"start": 22499,
"end": 27018
} | class ____(_PLS):
"""Partial Least Squares transformer and regressor.
For a comparison between other cross decomposition algorithms, see
:ref:`sphx_glr_auto_examples_cross_decomposition_plot_compare_cross_decomposition.py`.
Read more in the :ref:`User Guide <cross_decomposition>`.
.. versionadded... | PLSCanonical |
python | pytorch__pytorch | torch/distributed/tensor/examples/comm_mode_features_example.py | {
"start": 1082,
"end": 31125
} | class ____:
"""
Checks if the set of keys in ground truth dictionary and the set
produced in advanced_module_tracker are in the same order
"""
def __init__(self, world_size: int, rank: int) -> None:
self.world_size = world_size
self.rank = rank
self.device_type = get_device_... | CommDebugModeExample |
python | celery__celery | t/unit/worker/test_control.py | {
"start": 908,
"end": 1501
} | class ____(consumer.Consumer):
def __init__(self, app):
self.app = app
self.buffer = FastQueue()
self.timer = Timer()
self.event_dispatcher = Mock()
self.controller = WorkController()
self.task_consumer = Mock()
self.prefetch_multiplier = 1
self.initi... | Consumer |
python | tensorflow__tensorflow | tensorflow/python/framework/indexed_slices.py | {
"start": 2069,
"end": 6944
} | class ____(
internal.IndexedSlices,
internal.NativeObject,
composite_tensor.CompositeTensor):
"""A sparse representation of a set of tensor slices at given indices.
This class is a simple wrapper for a pair of `Tensor` objects:
* `values`: A `Tensor` of any dtype with shape `[D0, D1, ..., Dn]`.
* ... | IndexedSlices |
python | cython__cython | tests/run/pep3135_class_cell.py | {
"start": 3182,
"end": 3453
} | class ____:
"""
>>> obj = I()
>>> obj.method()()().__name__
'J'
"""
def method(self):
def inner():
class J:
def inner(self):
return __class__
return J().inner
return inner
| I |
python | redis__redis-py | redis/commands/search/aggregation.py | {
"start": 10829,
"end": 11185
} | class ____:
def __init__(self, cid: int) -> None:
self.cid = cid
self.max_idle = 0
self.count = 0
def build_args(self):
args = [str(self.cid)]
if self.max_idle:
args += ["MAXIDLE", str(self.max_idle)]
if self.count:
args += ["COUNT", str(s... | Cursor |
python | jazzband__django-redis | tests/conftest.py | {
"start": 254,
"end": 1750
} | class ____(LoadScopeScheduling):
"""Split by [] value. This is very hackish and might blow up any time!"""
def _split_scope(self, nodeid):
if "[sqlite" in nodeid:
return nodeid.rsplit("[")[-1].replace("]", "")
return None
def pytest_xdist_make_scheduler(log, config):
return Fi... | FixtureScheduling |
python | getsentry__sentry | src/sentry/auth/services/auth/service.py | {
"start": 503,
"end": 3227
} | class ____(RpcService):
key = "auth"
local_mode = SiloMode.CONTROL
@classmethod
def get_local_implementation(cls) -> RpcService:
from sentry.auth.services.auth.impl import DatabaseBackedAuthService
return DatabaseBackedAuthService()
@rpc_method
@abc.abstractmethod
def get_... | AuthService |
python | pydata__xarray | asv_bench/benchmarks/dataset_io.py | {
"start": 18628,
"end": 19246
} | class ____(IONestedDataTree):
def setup(self):
# TODO: Lazily skipped in CI as it is very demanding and slow.
# Improve times and remove errors.
_skip_slow()
requires_dask()
self.make_datatree()
self.format = "NETCDF4"
self.filepath = "datatree.nc4.nc"
... | IOReadDataTreeNetCDF4 |
python | charliermarsh__ruff | crates/ruff_python_parser/resources/valid/statement/class.py | {
"start": 22,
"end": 83
} | class ____():
def __init__(self):
pass
| Test |
python | getsentry__sentry | tests/sentry/snuba/test_metrics_performance.py | {
"start": 540,
"end": 5067
} | class ____(MetricsEnhancedPerformanceTestCase):
def setUp(self) -> None:
super().setUp()
# We want to always consider 7 days for simplicity.
self.start = datetime.datetime.now(tz=timezone.utc).replace(
hour=10, minute=0, second=0, microsecond=0
) - datetime.timedelta(days... | TimeseriesQueryTest |
python | h5py__h5py | h5py/tests/test_dataset.py | {
"start": 10935,
"end": 12576
} | class ____:
"""
Feature: Write Numpy array directly into Dataset
"""
@pytest.mark.parametrize(
'source_shape,dest_shape,source_sel,dest_sel',
[
((100,), (100,), np.s_[0:10], np.s_[50:60]),
((70,), (100,), np.s_[50:60], np.s_[90:]),
((30, 10), (20... | TestWriteDirectly |
python | PrefectHQ__prefect | tests/test_task_worker.py | {
"start": 17066,
"end": 18884
} | class ____:
async def test_task_run_via_task_worker_runs_on_completion_hook(
self, async_foo_task, prefect_client, events_pipeline, capsys
):
async_foo_task_with_on_completion_hook = async_foo_task.with_options(
on_completion=[
lambda task, task_run, state: print("Run... | TestTaskWorkerTaskStateHooks |
python | huggingface__transformers | src/transformers/models/altclip/modeling_altclip.py | {
"start": 29098,
"end": 32945
} | class ____(nn.Module):
def __init__(self, config: AltCLIPVisionConfig):
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... | AltCLIPVisionEmbeddings |
python | scipy__scipy | scipy/signal/tests/test_bsplines.py | {
"start": 12820,
"end": 19116
} | class ____:
def test_sepfir2d_invalid_filter(self, xp):
filt = xp.asarray([1.0, 2.0, 4.0, 2.0, 1.0])
image = np.random.rand(7, 9)
image = xp.asarray(image)
# No error for odd lengths
signal.sepfir2d(image, filt, filt[2:])
# Row or column filter must be odd
wi... | TestSepfir2d |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 3940,
"end": 4052
} | class ____(PydanticTypeError):
code = 'none.allowed'
msg_template = 'value is not none'
| NoneIsAllowedError |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/initsubclass1.py | {
"start": 1459,
"end": 1574
} | class ____(ClassJ):
def __init__(self):
reveal_type(self.custom_attribute, expected_text="int")
| ClassJChild |
python | openai__openai-python | src/openai/lib/streaming/responses/_events.py | {
"start": 2713,
"end": 2847
} | class ____(RawResponseTextDoneEvent, GenericModel, Generic[TextFormatT]):
parsed: Optional[TextFormatT] = None
| ResponseTextDoneEvent |
python | tiangolo__fastapi | docs_src/security/tutorial004.py | {
"start": 897,
"end": 965
} | class ____(BaseModel):
username: Union[str, None] = None
| TokenData |
python | matplotlib__matplotlib | lib/mpl_toolkits/axisartist/angle_helper.py | {
"start": 4103,
"end": 4348
} | class ____:
def __init__(self, nbins, include_last=True):
self.nbins = nbins
self._include_last = include_last
def set_params(self, nbins=None):
if nbins is not None:
self.nbins = int(nbins)
| LocatorBase |
python | mlflow__mlflow | mlflow/utils/timeout.py | {
"start": 197,
"end": 1214
} | class ____(Exception):
pass
@contextmanager
def run_with_timeout(seconds):
"""
Context manager to runs a block of code with a timeout. If the block of code takes longer
than `seconds` to execute, a `TimeoutError` is raised.
NB: This function uses Unix signals to implement the timeout, so it is not... | MlflowTimeoutError |
python | lepture__authlib | authlib/jose/errors.py | {
"start": 1654,
"end": 1780
} | class ____(JoseError):
error = "key_mismatch_error"
description = "Key does not match to any recipient"
| KeyMismatchError |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/concepts/io_management/input_managers.py | {
"start": 4264,
"end": 4573
} | class ____(TableIOManager):
def load_input(self, context: dg.InputContext):
return read_dataframe_from_table(name="table_1")
@dg.job(resource_defs={"load_input_manager": Table1IOManager()})
def io_load_table_job():
my_op()
# end_load_unconnected_io
# start_load_input_subset
| Table1IOManager |
python | jupyterlab__jupyterlab | jupyterlab/labextensions.py | {
"start": 17020,
"end": 18331
} | class ____(BaseExtensionApp):
description = "Check labextension(s) by name"
flags = check_flags
should_check_installed_only = Bool(
False,
config=True,
help="Whether it should check only if the extensions is installed",
)
def run_task(self):
app_options = AppOptions... | CheckLabExtensionsApp |
python | redis__redis-py | redis/commands/core.py | {
"start": 131723,
"end": 157146
} | class ____(CommandsProtocol):
"""
Redis commands for Stream data type.
see: https://redis.io/topics/streams-intro
"""
def xack(self, name: KeyT, groupname: GroupT, *ids: StreamIdT) -> ResponseT:
"""
Acknowledges the successful processing of one or more messages.
Args:
... | StreamCommands |
python | getsentry__sentry | src/sentry/releases/endpoints/project_release_repositories.py | {
"start": 544,
"end": 2004
} | class ____(ProjectEndpoint):
publish_status = {
"GET": ApiPublishStatus.UNKNOWN,
}
permission_classes = (ProjectReleasePermission,)
def get(self, request: Request, project, version) -> Response:
"""
Retrieve Project Repositories from a Release
``````````````````````````... | ProjectReleaseRepositories |
python | doocs__leetcode | solution/2800-2899/2861.Maximum Number of Alloys/Solution.py | {
"start": 0,
"end": 610
} | class ____:
def maxNumberOfAlloys(
self,
n: int,
k: int,
budget: int,
composition: List[List[int]],
stock: List[int],
cost: List[int],
) -> int:
ans = 0
for c in composition:
l, r = 0, budget + stock[0]
while l < r:
... | Solution |
python | pallets__werkzeug | src/werkzeug/exceptions.py | {
"start": 11360,
"end": 12662
} | class ____(HTTPException):
"""*405* `Method Not Allowed`
Raise if the server used a method the resource does not handle. For
example `POST` if the resource is view only. Especially useful for REST.
The first argument for this exception should be a list of allowed methods.
Strictly speaking the r... | MethodNotAllowed |
python | pyparsing__pyparsing | examples/btpyparse.py | {
"start": 377,
"end": 4129
} | class ____:
"""Class to encapsulate undefined macro references"""
def __init__(self, name):
self.name = name
def __repr__(self):
return f'Macro("{self.name}")'
def __eq__(self, other):
return self.name == other.name
# Character literals
LCURLY, RCURLY, LPAREN, RPAREN, QUOTE,... | Macro |
python | plotly__plotly.py | plotly/io/_base_renderers.py | {
"start": 1420,
"end": 1595
} | class ____(BaseRenderer):
"""
Base class for all mime type renderers
"""
def to_mimebundle(self, fig_dict):
raise NotImplementedError()
| MimetypeRenderer |
python | pytorch__pytorch | test/test_serialization.py | {
"start": 4738,
"end": 39405
} | class ____:
def _test_serialization_data(self):
a = [torch.randn(5, 5).float() for i in range(2)]
b = [a[i % 2] for i in range(4)] # 0-3
b += [a[0].storage()] # 4
b += [a[0].reshape(-1)[1:4].storage()] # 5
b += [torch.arange(1, 11).int()] # 6
t1 = torch.FloatTenso... | SerializationMixin |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/type_api.py | {
"start": 55830,
"end": 86057
} | class ____(SchemaEventTarget, ExternalType, TypeEngine[_T]):
'''Allows the creation of types which add additional functionality
to an existing type.
This method is preferred to direct subclassing of SQLAlchemy's
built-in types as it ensures that all required functionality of
the underlying type is ... | TypeDecorator |
python | ray-project__ray | doc/source/ray-core/doc_code/pattern_tree_of_actors.py | {
"start": 317,
"end": 899
} | class ____:
def __init__(self, hyperparameter, data):
self.trainers = [Trainer.remote(hyperparameter, d) for d in data]
def fit(self):
# Train with different data shard in parallel.
return ray.get([trainer.fit.remote() for trainer in self.trainers])
data = [1, 2, 3]
supervisor1 = Supe... | Supervisor |
python | tensorflow__tensorflow | tensorflow/dtensor/python/tests/collective_test.py | {
"start": 1654,
"end": 13481
} | class ____(test_util.DTensorBaseTest):
def setUp(self):
super(CollectiveTest, self).setUp()
global_ids = test_util.create_device_ids_array((2, 1))
local_ids = np.ravel(global_ids).tolist()
mesh_dict = {
device: layout_lib.Mesh(_MESH_DIMS, global_ids, local_ids,
... | CollectiveTest |
python | pyparsing__pyparsing | pyparsing/core.py | {
"start": 215999,
"end": 222278
} | class ____(ParseElementEnhance):
"""
Token for skipping over all undefined text until the matched
expression is found.
:param expr: target expression marking the end of the data to be skipped
:param include: if ``True``, the target expression is also parsed
(the skipped text and... | SkipTo |
python | gabrielfalcao__HTTPretty | httpretty/core.py | {
"start": 14323,
"end": 30862
} | class ____(object):
"""
fake :py:mod:`socket`
"""
class socket(object):
"""drop-in replacement for :py:class:`socket.socket`
"""
_entry = None
_read_buf = None
debuglevel = 0
_sent_data = []
is_secure = False
def __init__(
self... | fakesock |
python | PrefectHQ__prefect | src/prefect/server/schemas/actions.py | {
"start": 14837,
"end": 16347
} | class ____(ActionBaseModel):
"""Data used by the Prefect REST API to create a new state."""
type: schemas.states.StateType = Field(
default=..., description="The type of the state to create"
)
name: Optional[str] = Field(
default=None, description="The name of the state to create"
)... | StateCreate |
python | run-llama__llama_index | llama-index-core/llama_index/core/output_parsers/selection.py | {
"start": 740,
"end": 808
} | class ____(DataClassJsonMixin):
choice: int
reason: str
| Answer |
python | altair-viz__altair | altair/vegalite/v6/schema/_config.py | {
"start": 303753,
"end": 310625
} | class ____(TypedDict, total=False):
"""
Top-Level Configuration ``TypedDict`` for creating a consistent theme.
Parameters
----------
align
The alignment to apply to grid rows and columns. The supported string values are
``"all"``, ``"each"``, and ``"none"``.
* For ``"none"`... | ThemeConfig |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_image48.py | {
"start": 315,
"end": 955
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("image48.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workbook(... | TestCompareXLSXFiles |
python | walkccc__LeetCode | solutions/782. Transform to Chessboard/782.py | {
"start": 0,
"end": 843
} | class ____:
def movesToChessboard(self, board: list[list[int]]) -> int:
n = len(board)
if any(board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j]
for i in range(n) for j in range(n)):
return -1
rowSum = sum(board[0])
colSum = sum(board[i][0] for i in range(n))
if rowSum != n ... | Solution |
python | pytorch__pytorch | torch/fx/graph_module.py | {
"start": 15931,
"end": 45812
} | class ____(torch.nn.Module):
"""
GraphModule is an nn.Module generated from an fx.Graph. Graphmodule has a
``graph`` attribute, as well as ``code`` and ``forward`` attributes generated
from that ``graph``.
.. warning::
When ``graph`` is reassigned, ``code`` and ``forward`` will be automati... | GraphModule |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/functions.py | {
"start": 64173,
"end": 64538
} | class ____(GenericFunction[int]):
"""Implement the ``rank`` hypothetical-set aggregate function.
This function must be used with the :meth:`.FunctionElement.within_group`
modifier to supply a sort expression to operate upon.
The return type of this function is :class:`.Integer`.
"""
type = s... | rank |
python | PyCQA__pylint | tests/functional/g/globals.py | {
"start": 376,
"end": 2871
} | class ____:
pass
def fix_contant(value):
"""all this is ok, but try not using global ;)"""
global CONSTANT # [global-statement]
print(CONSTANT)
CONSTANT = value
def other():
"""global behaviour test"""
global HOP # [global-variable-not-assigned]
print(HOP) # [undefined-variable]
... | CLASS |
python | pypa__hatch | src/hatch/template/files_feature_cli.py | {
"start": 480,
"end": 1092
} | class ____(File):
TEMPLATE = """\
import click
from {package_name}.__about__ import __version__
@click.group(context_settings={{"help_option_names": ["-h", "--help"]}}, invoke_without_command=True)
@click.version_option(version=__version__, prog_name="{project_name}")
def {package_name}():
click.echo("Hello ... | CommandLinePackage |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/annotation.py | {
"start": 2989,
"end": 4504
} | class ____(SupportsAnnotations):
__slots__ = ()
_constructor: Callable[..., SupportsWrappingAnnotations]
if TYPE_CHECKING:
@util.ro_non_memoized_property
def entity_namespace(self) -> _EntityNamespace: ...
def _annotate(self, values: _AnnotationDict) -> Self:
"""return a copy... | SupportsWrappingAnnotations |
python | django__django | tests/test_client_regress/tests.py | {
"start": 44174,
"end": 47737
} | class ____(SimpleTestCase):
def test_post(self):
"Request a view with string data via request method POST"
# Regression test for #11371
data = '{"test": "json"}'
response = self.client.post(
"/request_methods/", data=data, content_type="application/json"
)
... | RequestMethodStringDataTests |
python | tensorflow__tensorflow | tensorflow/python/keras/engine/data_adapter.py | {
"start": 47274,
"end": 59083
} | class ____(DataHandler):
"""A `DataHandler` that is compatible with `ClusterCoordinator`."""
def __init__(self, x, y=None, **kwargs):
if not isinstance(x, dataset_creator.DatasetCreator):
x = self._convert_to_dataset_creator(x, y, **kwargs)
super().__init__(x=x, **kwargs)
def _convert_to_dataset_... | _ClusterCoordinatorDataHandler |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 1231,
"end": 1556
} | class ____(Interface):
"""An event type that is emitted whenever any :app:`Pyramid`
view returns a response. See the
documentation attached to :class:`pyramid.events.NewResponse`
for more information."""
request = Attribute('The request object')
response = Attribute('The response object')
| INewResponse |
python | huggingface__transformers | src/transformers/models/levit/modeling_levit.py | {
"start": 20250,
"end": 22699
} | class ____(LevitPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.config = config
self.num_labels = config.num_labels
self.levit = LevitModel(config)
# Classifier head
self.classifier = (
LevitClassificationLayer(config.hidden_si... | LevitForImageClassification |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_S.py | {
"start": 29712,
"end": 31120
} | class ____(Benchmark):
r"""
SineEnvelope objective function.
This class defines the SineEnvelope [1]_ global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{SineEnvelope}}(x) = -\sum_{i=1}^{n-1}\left[\frac{\sin^2(
... | SineEnvelope |
python | sqlalchemy__sqlalchemy | test/sql/test_from_linter.py | {
"start": 14108,
"end": 18077
} | class ____(fixtures.TablesTest):
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"table_a",
metadata,
Column("col_a", Integer, primary_key=True, autoincrement=False),
)
Table(
"table_b",
... | TestLinterRoundTrip |
python | pandas-dev__pandas | asv_bench/benchmarks/io/csv.py | {
"start": 9425,
"end": 10146
} | class ____(StringIORewind):
def setup(self):
self.na_values = [2**63 + 500]
arr = np.arange(10000).astype("uint64") + 2**63
self.data1 = StringIO("\n".join(arr.astype(str).tolist()))
arr = arr.astype(object)
arr[500] = -1
self.data2 = StringIO("\n".join(arr.astype(str... | ReadUint64Integers |
python | doocs__leetcode | solution/2500-2599/2542.Maximum Subsequence Score/Solution.py | {
"start": 0,
"end": 370
} | class ____:
def maxScore(self, nums1: List[int], nums2: List[int], k: int) -> int:
nums = sorted(zip(nums2, nums1), reverse=True)
q = []
ans = s = 0
for a, b in nums:
s += b
heappush(q, b)
if len(q) == k:
ans = max(ans, s * a)
... | Solution |
python | ipython__ipython | IPython/core/magic_arguments.py | {
"start": 4488,
"end": 7066
} | class ____(argparse.ArgumentParser):
""" An ArgumentParser tweaked for use by IPython magics.
"""
def __init__(self,
prog=None,
usage=None,
description=None,
epilog=None,
parents=None,
formatter_class=Magic... | MagicArgumentParser |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 612835,
"end": 613481
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("SecurityAdvisoryEdge"), graphql_name="edges"
)
nodes = sg... | SecurityAdvisoryConnection |
python | pydata__xarray | asv_bench/benchmarks/rolling.py | {
"start": 320,
"end": 2590
} | class ____:
def setup(self, *args, **kwargs):
self.ds = xr.Dataset(
{
"var1": (("x", "y"), randn_xy),
"var2": (("x", "t"), randn_xt),
"var3": (("t",), randn_t),
},
coords={
"x": np.arange(nx),
... | Rolling |
python | mlflow__mlflow | tests/tensorflow/test_tensorflow2_autolog.py | {
"start": 14514,
"end": 15247
} | class ____(tf.keras.utils.Sequence):
def __init__(self, batch_size, with_sample_weights=False):
self.batch_size = batch_size
self.with_sample_weights = with_sample_weights
def __len__(self):
return 10
def __getitem__(self, idx):
x = np.array([idx] * self.batch_size)
... | __ExampleSequence |
python | jazzband__django-model-utils | tests/models.py | {
"start": 8598,
"end": 9010
} | class ____(models.Model):
fk = models.ForeignKey('Tracked', on_delete=models.PROTECT)
self_ref = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True)
tracker = LoopDetectionFieldTracker()
custom_tracker = LoopDetectionFieldTracker(fields=['fk_id', 'self_ref_id'])
custom_track... | TrackedProtectedSelfRefFK |
python | dagster-io__dagster | python_modules/dagster-pipes/dagster_pipes/__init__.py | {
"start": 16733,
"end": 18315
} | class ____(ABC, Generic[T_MessageChannel]):
@abstractmethod
@contextmanager
def open(self, params: PipesParams) -> Iterator[T_MessageChannel]:
"""A `@contextmanager` that initializes a channel for writing messages back to Dagster.
This method should takes the params passed by the orchestrat... | PipesMessageWriter |
python | ray-project__ray | python/ray/serve/tests/unit/test_config.py | {
"start": 4428,
"end": 9121
} | class ____:
def test_deployment_config_validation(self):
# Test config ignoring unknown keys (required for forward-compatibility)
DeploymentConfig(new_version_key=-1)
# Test num_replicas validation.
DeploymentConfig(num_replicas=1)
with pytest.raises(ValidationError, match="... | TestDeploymentConfig |
python | getsentry__sentry | src/sentry/api/helpers/group_index/types.py | {
"start": 451,
"end": 1005
} | class ____(TypedDict):
assignedTo: NotRequired[ActorSerializerResponse]
discard: NotRequired[bool]
hasSeen: NotRequired[bool]
inbox: NotRequired[bool]
isBookmarked: NotRequired[bool]
isPublic: NotRequired[bool]
isSubscribed: NotRequired[bool]
merge: NotRequired[MergedGroup]
priority:... | MutateIssueResponse |
python | django__django | tests/queries/tests.py | {
"start": 120477,
"end": 123452
} | class ____(TestCase):
"""Tests whose execution depend on different environment conditions like
Python version or DB backend features"""
@classmethod
def setUpTestData(cls):
generic = NamedCategory.objects.create(name="Generic")
t1 = Tag.objects.create(name="t1", category=generic)
... | ConditionalTests |
python | huggingface__transformers | src/transformers/models/videomae/modeling_videomae.py | {
"start": 12277,
"end": 12940
} | class ____(nn.Module):
def __init__(self, config: VideoMAEConfig):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.in... | VideoMAEIntermediate |
python | walkccc__LeetCode | solutions/949. Largest Time for Given Digits/949.py | {
"start": 0,
"end": 233
} | class ____:
def largestTimeFromDigits(self, arr: list[int]) -> str:
for time in itertools.permutations(sorted(arr, reverse=True)):
if time[:2] < (2, 4) and time[2] < 6:
return '%d%d:%d%d' % time
return ''
| Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/_config/pythonic_config/resource.py | {
"start": 24202,
"end": 27138
} | class ____(ConfigurableResourceFactory[TResValue]):
"""Base class for Dagster resources that utilize structured config.
This class is a subclass of both :py:class:`ResourceDefinition` and :py:class:`Config`.
Example definition:
.. code-block:: python
class WriterResource(ConfigurableResource... | ConfigurableResource |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 497096,
"end": 497530
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of CloseIssue"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "issue")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
... | CloseIssuePayload |
python | run-llama__llama_index | llama-index-integrations/response_synthesizers/llama-index-response-synthesizers-google/llama_index/response_synthesizers/google/base.py | {
"start": 1639,
"end": 8725
} | class ____(BaseSynthesizer):
"""
Google's Attributed Question and Answering service.
Given a user's query and a list of passages, Google's server will return
a response that is grounded to the provided list of passages. It will not
base the response on parametric memory.
"""
_client: Any
... | GoogleTextSynthesizer |
python | django__django | django/forms/fields.py | {
"start": 46291,
"end": 46614
} | class ____(CharField):
default_validators = [validators.validate_slug]
def __init__(self, *, allow_unicode=False, **kwargs):
self.allow_unicode = allow_unicode
if self.allow_unicode:
self.default_validators = [validators.validate_unicode_slug]
super().__init__(**kwargs)
| SlugField |
python | google__jax | tests/pallas/pallas_jumble_test.py | {
"start": 2508,
"end": 10803
} | class ____(PallasBaseTest):
def test_vmap_jumble_over_sin_kernel(self):
if not jtu.test_device_matches(["tpu"]):
self.skipTest("Only tested on TPU")
row_count = 8
col_grid_size = 5
ragged_shape = [3, 1, 4]
sizes = lax.convert_element_type(
jnp.array([128 * x for x in ragged_shape])... | PallasCallRaggedVmapTest |
python | pytorch__pytorch | test/test_legacy_vmap.py | {
"start": 447,
"end": 770
} | class ____:
def __enter__(self):
self.prev_state = torch._C._debug_only_are_vmap_fallback_warnings_enabled()
torch._C._debug_only_display_vmap_fallback_warnings(True)
def __exit__(self, *ignored):
torch._C._debug_only_display_vmap_fallback_warnings(self.prev_state)
| EnableVmapFallbackWarnings |
python | ray-project__ray | rllib/core/models/configs.py | {
"start": 13019,
"end": 16291
} | class ____(_MLPConfig):
"""Configuration for an MLPHead with a floating second half of outputs.
This model can be useful together with Gaussian Distributions.
This gaussian distribution would be conditioned as follows:
- The first half of outputs from this model can be used as
state-depende... | FreeLogStdMLPHeadConfig |
python | huggingface__transformers | src/transformers/models/falcon_mamba/modeling_falcon_mamba.py | {
"start": 2393,
"end": 7618
} | class ____:
"""
Cache for falcon_mamba model which does not have attention mechanism and key value states.
Arguments:
config (`PreTrainedConfig):
The configuration file defining the shape-related attributes required to initialize the static cache.
max_batch_size (`int`):
... | FalconMambaCache |
python | PyCQA__pylint | tests/functional/ext/docparams/return/missing_return_doc_Google.py | {
"start": 2492,
"end": 2818
} | class ____:
"""test_ignores_return_in_abstract_method_google_2
Example of a method documenting the return type that an
implementation should return.
"""
def foo_method(self, arg):
"""docstring ...
Args:
arg (int): An argument.
"""
raise NotImplementedErr... | Foo |
python | euske__pdfminer | pdfminer/lzw.py | {
"start": 47,
"end": 111
} | class ____(Exception):
pass
## LZWDecoder
##
| CorruptDataError |
python | celery__celery | t/unit/app/test_beat.py | {
"start": 5115,
"end": 22906
} | class ____:
def test_custom_schedule_dict(self):
custom = {'foo': 'bar'}
scheduler = mScheduler(app=self.app, schedule=custom, lazy=True)
assert scheduler.data is custom
def test_apply_async_uses_registered_task_instances(self):
@self.app.task(shared=False)
def foo():
... | test_Scheduler |
python | tornadoweb__tornado | tornado/web.py | {
"start": 131688,
"end": 133957
} | class ____:
"""A re-usable, modular UI unit on a page.
UI modules often execute additional queries, and they can include
additional CSS and JavaScript that will be included in the output
page, which is automatically inserted on page render.
Subclasses of UIModule must override the `render` method.... | UIModule |
python | PyCQA__pylint | tests/test_self.py | {
"start": 2101,
"end": 3307
} | class ____(BaseReporter):
def __init__(self, reporters: list[BaseReporter]) -> None:
# pylint: disable=super-init-not-called
# We don't call it because there is an attribute "linter" that is set inside the base class,
# and we have another setter here using yet undefined attribute.
#... | MultiReporter |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/constructors.py | {
"start": 4869,
"end": 4959
} | class ____:
def __init__(self, foo, baz):
self.foo = foo
| SanitizeTaintInTaintOut |
python | ray-project__ray | python/ray/tune/experimental/output.py | {
"start": 6615,
"end": 16696
} | class ____:
header: List[str]
data: List[_PerStatusTrialTableData]
def _max_len(value: Any, max_len: int = 20, wrap: bool = False) -> Any:
"""Abbreviate a string representation of an object to `max_len` characters.
For numbers, booleans and None, the original value will be returned for
correct re... | _TrialTableData |
python | davidhalter__jedi | test/run.py | {
"start": 9732,
"end": 18071
} | class ____(BaseTestCase):
"""
Static Analysis cases lie in the static_analysis folder.
The tests also start with `#!`, like the inference tests.
"""
def __init__(self, path):
self._path = path
self.name = os.path.basename(path)
with open(path) as f:
self._source =... | StaticAnalysisCase |
python | huggingface__transformers | src/transformers/models/vivit/modeling_vivit.py | {
"start": 1338,
"end": 3295
} | class ____(nn.Module):
"""
Construct Vivit Tubelet embeddings.
This module turns a batch of videos of shape (batch_size, num_frames, num_channels, height, width) into a tensor of
shape (batch_size, seq_len, hidden_size) to be consumed by a Transformer encoder.
The seq_len (the number of patches) e... | VivitTubeletEmbeddings |
python | jazzband__prettytable | src/prettytable/colortable.py | {
"start": 1161,
"end": 2477
} | class ____:
DEFAULT = Theme()
DYSLEXIA_FRIENDLY = Theme(
default_color="38;5;223",
vertical_color="38;5;22",
horizontal_color="38;5;22",
junction_color="38;5;58",
)
EARTH = Theme(
default_color="33",
vertical_color="38;5;94",
horizontal_color="38;5... | Themes |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.