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 | doocs__leetcode | solution/2900-2999/2927.Distribute Candies Among Children III/Solution.py | {
"start": 0,
"end": 316
} | class ____:
def distributeCandies(self, n: int, limit: int) -> int:
if n > 3 * limit:
return 0
ans = comb(n + 2, 2)
if n > limit:
ans -= 3 * comb(n - limit + 1, 2)
if n - 2 >= 2 * limit:
ans += 3 * comb(n - 2 * limit, 2)
return ans
| Solution |
python | doocs__leetcode | solution/0200-0299/0286.Walls and Gates/Solution.py | {
"start": 0,
"end": 692
} | class ____:
def wallsAndGates(self, rooms: List[List[int]]) -> None:
"""
Do not return anything, modify rooms in-place instead.
"""
m, n = len(rooms), len(rooms[0])
inf = 2**31 - 1
q = deque([(i, j) for i in range(m) for j in range(n) if rooms[i][j] == 0])
d =... | Solution |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/sensors/test_data_factory.py | {
"start": 5733,
"end": 7423
} | class ____:
RUN_ID = "7f8c6c72-c093-11ec-a83d-0242ac120007"
SENSOR = AzureDataFactoryPipelineRunStatusSensor(
task_id="pipeline_run_sensor_async",
run_id=RUN_ID,
resource_group_name="resource-group-name",
factory_name="factory-name",
deferrable=True,
)
@mock.patc... | TestAzureDataFactoryPipelineRunStatusSensorWithAsync |
python | ethereum__web3.py | web3/_utils/module_testing/go_ethereum_txpool_module.py | {
"start": 95,
"end": 760
} | class ____:
@pytest.mark.asyncio
async def test_async_geth_txpool_inspect(self, async_w3: "AsyncWeb3[Any]") -> None:
test_data = await async_w3.geth.txpool.inspect()
assert "pending" in test_data
@pytest.mark.asyncio
async def test_async_geth_txpool_content(self, async_w3: "AsyncWeb3[An... | GoEthereumAsyncTxPoolModuleTest |
python | scipy__scipy | scipy/integrate/_quadpack_py.py | {
"start": 52359,
"end": 52660
} | class ____:
def __init__(self, range_):
self.range_ = range_
def __call__(self, *args):
"""Return stored value.
*args needed because range_ can be float or func, and is called with
variable number of parameters.
"""
return self.range_
| _RangeFunc |
python | pydata__xarray | xarray/computation/weighted.py | {
"start": 18322,
"end": 18620
} | class ____(Weighted["DataArray"]):
def _implementation(self, func, dim, **kwargs) -> DataArray:
self._check_dim(dim)
dataset = self.obj._to_temp_dataset()
dataset = dataset.map(func, dim=dim, **kwargs)
return self.obj._from_temp_dataset(dataset)
| DataArrayWeighted |
python | kamyu104__LeetCode-Solutions | Python/majority-element-ii.py | {
"start": 50,
"end": 1460
} | class ____(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
k, n, cnts = 3, len(nums), collections.defaultdict(int)
for i in nums:
cnts[i] += 1
# Detecting k items in cnts, at least one of them must hav... | Solution |
python | redis__redis-py | tests/test_asyncio/test_encoding.py | {
"start": 135,
"end": 2470
} | class ____:
@pytest_asyncio.fixture()
async def r(self, create_redis):
redis = await create_redis(decode_responses=True)
yield redis
await redis.flushall()
@pytest_asyncio.fixture()
async def r_no_decode(self, create_redis):
redis = await create_redis(decode_responses=Fa... | TestEncoding |
python | mlflow__mlflow | dev/clint/tests/rules/test_redundant_test_docstring.py | {
"start": 2637,
"end": 3119
} | class ____:
"""Test class."""
pass
'''
config = Config(select={RedundantTestDocstring.name})
violations = lint_file(Path("module_test.py"), code, config, index_path)
assert len(violations) == 2
def test_multiline_docstrings_are_always_allowed(index_path: Path) -> None:
code = '''def test_with... | TestClassImplementation |
python | allegroai__clearml | clearml/logger.py | {
"start": 1141,
"end": 65092
} | class ____(object):
"""
The ``Logger`` class is the ClearML console log and metric statistics interface, and contains methods for explicit
reporting.
Explicit reporting extends ClearML automagical capturing of inputs and output. Explicit reporting
methods include scalar plots, line plots, histogram... | Logger |
python | PrefectHQ__prefect | src/prefect/_internal/concurrency/calls.py | {
"start": 7919,
"end": 17830
} | class ____(Generic[T]):
"""
A deferred function call.
"""
future: Future[T]
fn: "_SyncOrAsyncCallable[..., T]"
args: tuple[Any, ...]
kwargs: dict[str, Any]
context: contextvars.Context
timeout: Optional[float]
runner: Optional["Portal"] = None
def __eq__(self, other: object... | Call |
python | allegroai__clearml | clearml/backend_api/services/v2_23/events.py | {
"start": 34554,
"end": 36637
} | class ____(Response):
"""
:param scroll_id: Scroll ID for getting more results
:type scroll_id: str
:param metrics: Plot events grouped by tasks and iterations
:type metrics: Sequence[PlotsResponseTaskMetrics]
"""
_service = "events"
_action = "plots"
_version = "2.23"
_schema =... | PlotsResponse |
python | wandb__wandb | wandb/sdk/artifacts/_generated/enums.py | {
"start": 246,
"end": 356
} | class ____(str, Enum):
PENDING = "PENDING"
COMMITTED = "COMMITTED"
DELETED = "DELETED"
| ArtifactState |
python | pandas-dev__pandas | pandas/tests/series/methods/test_count.py | {
"start": 74,
"end": 567
} | class ____:
def test_count(self, datetime_series):
assert datetime_series.count() == len(datetime_series)
datetime_series[::2] = np.nan
assert datetime_series.count() == np.isfinite(datetime_series).sum()
def test_count_categorical(self):
ser = Series(
Categorical(... | TestSeriesCount |
python | keras-team__keras | keras/src/layers/pooling/average_pooling2d.py | {
"start": 185,
"end": 4121
} | class ____(BasePooling):
"""Average pooling operation for 2D spatial data.
Downsamples the input along its spatial dimensions (height and width)
by taking the average value over an input window
(of size defined by `pool_size`) for each channel of the input.
The window is shifted by `strides` along ... | AveragePooling2D |
python | Netflix__metaflow | metaflow/plugins/cards/exception.py | {
"start": 3699,
"end": 4122
} | class ____(MetaflowException):
headline = (
"`get_cards` function requires a `Task` object or pathspec as an argument"
)
def __init__(self, obj_type):
msg = (
"`get_cards` function requires a `Task` object or pathspec as an argument. `task` argument cannot be of type %s."
... | IncorrectArgumentException |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/spanner.py | {
"start": 17653,
"end": 22044
} | class ____(GoogleCloudBaseOperator):
"""
Updates a Cloud Spanner database with the specified DDL statement.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:SpannerUpdateDatabaseInstanceOperator`
:param instance_id: The Cloud... | SpannerUpdateDatabaseInstanceOperator |
python | cython__cython | Cython/TestUtils.py | {
"start": 7089,
"end": 15572
} | class ____(VisitorTransform):
# actually, a TreeVisitor would be enough, but this needs to run
# as part of the compiler pipeline
def __init__(self):
super().__init__()
self._module_pos = None
self._c_patterns = []
self._c_antipatterns = []
def create_c_file_validator(s... | TreeAssertVisitor |
python | google__pytype | pytype/pytd/printer.py | {
"start": 324,
"end": 1339
} | class ____:
"""Imports from the `typing` module."""
def __init__(self):
# Typing members that are imported via `from typing import ...`.
self._members: dict[_AliasType, _NameType] = {}
# The number of times that each typing member is used.
self._counts: dict[_NameType, int] = collections.defaultdic... | _TypingImports |
python | pytorch__pytorch | torch/distributed/nn/functional.py | {
"start": 15357,
"end": 15844
} | class ____(Function):
@staticmethod
# pyrefly: ignore [bad-override]
def forward(ctx, op, group, tensor):
ctx.group = group
ctx.op = op
tensor = tensor.clone(memory_format=torch.contiguous_format)
dist.all_reduce(tensor, op=op, group=group)
return tensor
@staticm... | _AllReduce |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/emr/types.py | {
"start": 194,
"end": 715
} | class ____(PyEnum):
"""Cluster state for EMR."""
Starting = "STARTING"
Bootstrapping = "BOOTSTRAPPING"
Running = "RUNNING"
Waiting = "WAITING"
Terminating = "TERMINATING"
Terminated = "TERMINATED"
TerminatedWithErrors = "TERMINATED_WITH_ERRORS"
EMR_CLUSTER_TERMINATED_STATES = [
Em... | EmrClusterState |
python | apache__airflow | providers/slack/src/airflow/providers/slack/operators/slack.py | {
"start": 1290,
"end": 3972
} | class ____(BaseOperator):
"""
Base Slack Operator class.
:param slack_conn_id: :ref:`Slack API Connection <howto/connection:slack>`
which its password is Slack API token.
:param method: The Slack API Method to Call (https://api.slack.com/methods).
:param api_params: API Method call paramete... | SlackAPIOperator |
python | tox-dev__tox | src/tox/config/loader/convert.py | {
"start": 537,
"end": 6901
} | class ____(ABC, Generic[T]):
"""A class that converts a raw type to a given tox (python) type."""
def to(self, raw: T, of_type: type[V] | UnionType, factory: Factory[V]) -> V: # noqa: PLR0911
"""
Convert given raw type to python type.
:param raw: the raw type
:param of_type: p... | Convert |
python | django__django | tests/logging_tests/tests.py | {
"start": 7738,
"end": 8291
} | class ____(SetupDefaultLoggingMixin, LoggingCaptureMixin, SimpleTestCase):
def test_i18n_page_found_no_warning(self):
self.client.get("/exists/")
self.client.get("/en/exists/")
self.assertEqual(self.logger_output.getvalue(), "")
def test_i18n_page_not_found_warning(self):
self.c... | I18nLoggingTests |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP008.py | {
"start": 3342,
"end": 3394
} | class ____:
def f(self):
print("D")
| ParentD |
python | pyinstaller__pyinstaller | bootloader/waflib/Tools/ccroot.py | {
"start": 16598,
"end": 16788
} | class ____(link_task):
def runnable_status(self):
for t in self.run_after:
if not t.hasrun:
return Task.ASK_LATER
return Task.SKIP_ME
| fake_shlib |
python | pydata__xarray | xarray/computation/arithmetic.py | {
"start": 3630,
"end": 3781
} | class ____(
ImplementsDatasetReduce,
SupportsArithmetic,
DatasetOpsMixin,
):
__slots__ = ()
__array_priority__ = 50
| DatasetArithmetic |
python | ray-project__ray | python/ray/serve/tests/unit/test_metrics_utils.py | {
"start": 9884,
"end": 30163
} | class ____:
"""Test the new instantaneous merge functionality."""
def test_merge_instantaneous_total_empty(self):
"""Test merge_instantaneous_total with empty input."""
result = merge_instantaneous_total([])
assert result == []
result = merge_instantaneous_total([[], []])
... | TestInstantaneousMerge |
python | tiangolo__fastapi | tests/test_generic_parameterless_depends.py | {
"start": 235,
"end": 1875
} | class ____:
pass
@app.get("/a")
async def a(dep: Dep[A]):
return {"cls": dep.__class__.__name__}
@app.get("/b")
async def b(dep: Dep[B]):
return {"cls": dep.__class__.__name__}
client = TestClient(app)
def test_generic_parameterless_depends():
response = client.get("/a")
assert response.stat... | B |
python | sympy__sympy | sympy/physics/quantum/tests/test_state.py | {
"start": 872,
"end": 966
} | class ____(Ket):
@classmethod
def default_args(self):
return ("test",)
| CustomKet |
python | plotly__plotly.py | plotly/basedatatypes.py | {
"start": 216282,
"end": 228101
} | class ____(BaseTraceHierarchyType):
"""
Base class for the all trace types.
Specific trace type classes (Scatter, Bar, etc.) are code generated as
subclasses of this class.
"""
def __init__(self, plotly_name, **kwargs):
super(BaseTraceHierarchyType, self).__init__(plotly_name, **kwargs... | BaseTraceType |
python | modin-project__modin | modin/core/execution/ray/common/engine_wrapper.py | {
"start": 7600,
"end": 8800
} | class ____: # pragma: no cover
"""
Help synchronize across tasks and actors on cluster.
For details see: https://docs.ray.io/en/latest/advanced.html?highlight=signalactor#multi-node-synchronization-using-an-actor
Parameters
----------
event_count : int
Number of events required for sy... | SignalActor |
python | ray-project__ray | rllib/examples/rl_modules/classes/rock_paper_scissors_heuristic_rlm.py | {
"start": 207,
"end": 1499
} | class ____(RLModule):
"""In rock-paper-scissors, always chooses the same action within an episode.
The first move is random, all the following moves are the same as the first one.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._actions_per_vector_idx = ... | AlwaysSameHeuristicRLM |
python | getsentry__sentry-python | tests/integrations/grpc/test_grpc.py | {
"start": 10919,
"end": 11675
} | class ____(gRPCTestServiceServicer):
events = []
@staticmethod
def TestServe(request, context): # noqa: N802
with start_span(
op="test",
name="test",
origin="auto.grpc.grpc.TestService",
):
pass
return gRPCTestMessage(text=request.te... | TestService |
python | tensorflow__tensorflow | tensorflow/python/ops/distributions/gamma.py | {
"start": 1620,
"end": 10078
} | class ____(distribution.Distribution):
"""Gamma distribution.
The Gamma distribution is defined over positive real numbers using
parameters `concentration` (aka "alpha") and `rate` (aka "beta").
#### Mathematical Details
The probability density function (pdf) is,
```none
pdf(x; alpha, beta, x > 0) = x... | Gamma |
python | getsentry__sentry | src/sentry/hybridcloud/rpc/__init__.py | {
"start": 892,
"end": 3253
} | class ____(pydantic.BaseModel):
"""A serializable object that may be part of an RPC schema."""
class Config:
orm_mode = True
use_enum_values = True
@classmethod
def get_field_names(cls) -> Iterable[str]:
return iter(cls.__fields__.keys())
@classmethod
def serialize_by_... | RpcModel |
python | getsentry__sentry | tests/sentry/workflow_engine/handlers/condition/test_issue_category_handler.py | {
"start": 462,
"end": 3996
} | class ____(ConditionTestCase):
condition = Condition.ISSUE_CATEGORY
payload = {
"id": IssueCategoryFilter.id,
"value": "1",
}
def setUp(self) -> None:
super().setUp()
self.event_data = WorkflowEventData(event=self.group_event, group=self.group_event.group)
self.d... | TestIssueCategoryCondition |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 80227,
"end": 80665
} | class ____(sgqlc.types.Enum):
"""The privacy of a repository
Enumeration Choices:
* `INTERNAL`: The repository is visible only to users in the same
business.
* `PRIVATE`: The repository is visible only to those with explicit
access.
* `PUBLIC`: The repository is visible to everyone.
... | RepoAccessAuditEntryVisibility |
python | ray-project__ray | python/ray/experimental/channel/shared_memory_channel.py | {
"start": 20624,
"end": 25385
} | class ____(ChannelInterface):
"""A channel that can be read and written by Ray processes.
It creates `num_shm_buffers` number of buffers and allows buffered read and
write APIs. I.e., read and write APIs are non-blocking as long as it can write to
next buffer or read from a next buffer. See `read` and ... | BufferedSharedMemoryChannel |
python | PyCQA__pylint | tests/functional/s/super/super_checks.py | {
"start": 1043,
"end": 1096
} | class ____:
""" crash """
name = NewAaaa
| Getattr |
python | plotly__plotly.py | tests/test_core/test_graph_objs/test_graph_objs.py | {
"start": 3273,
"end": 4545
} | class ____(TestCase):
def setUp(self):
self.layout = go.Layout(
width=1000,
title={"text": "the title", "font": {"size": 20}},
annotations=[{}, {}],
xaxis2={"range": [1, 2]},
)
def test_pop_valid_simple_prop(self):
self.assertEqual(self.la... | TestPop |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/execution_tests/execution_plan_tests/test_host_run_worker.py | {
"start": 1079,
"end": 4335
} | class ____(ReconstructableJob):
def __new__(
cls,
repository,
pipeline_name,
op_selection=None,
asset_selection=None,
):
return super().__new__(
cls,
repository,
pipeline_name,
op_selection,
asset_selecti... | ExplodingTestPipeline |
python | simonw__sqlite-utils | sqlite_utils/utils.py | {
"start": 4649,
"end": 5545
} | class ____:
def __init__(self, wrapped, update):
self._wrapped = wrapped
self._update = update
def __iter__(self):
for line in self._wrapped:
self._update(len(line))
yield line
def read(self, size=-1):
data = self._wrapped.read(size)
self._up... | UpdateWrapper |
python | django__django | tests/get_earliest_or_latest/models.py | {
"start": 233,
"end": 401
} | class ____(models.Model):
name = models.CharField(max_length=30)
birthday = models.DateField()
# Note that this model doesn't have "get_latest_by" set.
| Person |
python | sympy__sympy | sympy/core/assumptions.py | {
"start": 22761,
"end": 23402
} | class ____(type):
def __init__(cls, *args, **kwargs):
msg = ("The ManagedProperties metaclass. "
"Basic does not use metaclasses any more")
sympy_deprecation_warning(msg,
deprecated_since_version="1.12",
active_deprecations_target='managedproperties')
... | ManagedProperties |
python | catalyst-team__catalyst | catalyst/contrib/utils/thresholds.py | {
"start": 256,
"end": 17009
} | class ____(str, enum.Enum):
"""Available threshold search strategies types."""
NOOP = noop = "noop"
MULTILABEL = multilabel = "multilabel"
MULTICLASS = multiclass = "multiclass"
def get_baseline_thresholds(
scores: np.ndarray, labels: np.ndarray, objective: METRIC_FN
) -> Tuple[float, List[float]... | ThresholdMode |
python | wandb__wandb | wandb/sdk/artifacts/artifact_manifest.py | {
"start": 430,
"end": 2716
} | class ____(ArtifactsBase, ABC):
# Note: we can't name this "version" since it conflicts with the prior
# `version()` classmethod.
manifest_version: Annotated[Any, Field(repr=False)]
entries: Dict[str, ArtifactManifestEntry] = Field(default_factory=dict) # noqa: UP006
storage_policy: Annotated[Stor... | ArtifactManifest |
python | numba__numba | numba/tests/test_target_extension.py | {
"start": 23540,
"end": 28255
} | class ____(TestCase):
"""In this use case the CPU compilation pipeline is extended with a new
compilation pass that runs just prior to lowering. The pass looks for
function calls and when it finds one it sees if there's a DPU function
available that is a valid overload for the function call. If there... | TestTargetOffload |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/random_crop.py | {
"start": 584,
"end": 10553
} | class ____(BaseImagePreprocessingLayer):
"""A preprocessing layer which randomly crops images during training.
During training, this layer will randomly choose a location to crop images
down to a target size. The layer will crop all the images in the same batch
to the same cropping location.
At in... | RandomCrop |
python | pypa__warehouse | tests/unit/organizations/test_models.py | {
"start": 1352,
"end": 2032
} | class ____:
def test_traversal_finds(self, db_request):
organization_application = DBOrganizationApplicationFactory.create()
_organization_application = OrganizationApplicationFactory(db_request)
assert (
_organization_application[organization_application.id]
== organ... | TestOrganizationApplicationFactory |
python | huggingface__transformers | src/transformers/models/sam3_tracker/modeling_sam3_tracker.py | {
"start": 34745,
"end": 52750
} | class ____(Sam3TrackerPreTrainedModel):
input_modalities = ("image", "text")
_can_record_outputs = {"mask_decoder_attentions": OutputRecorder(Sam3TrackerTwoWayAttentionBlock, index=2)}
_keys_to_ignore_on_load_unexpected = [
r"^detector_model.",
r"^memory_.*",
r"^mask_downsample.*",
... | Sam3TrackerModel |
python | astropy__astropy | astropy/table/index.py | {
"start": 11051,
"end": 11166
} | class ____(ValueError):
"""
Indicates that a given index cannot handle the supplied query.
"""
| QueryError |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 1884,
"end": 1973
} | class ____(ModelShow1_plain):
field2 = models.CharField(max_length=30)
| ModelShow2_plain |
python | pyparsing__pyparsing | examples/adventureEngine.py | {
"start": 10782,
"end": 11069
} | class ____(Command):
def __init__(self, quals):
super().__init__("QUIT", "quitting")
@staticmethod
def help_description():
return "QUIT or Q - ends the game"
def _do_command(self, player):
print("Ok....")
player.gameOver = True
| QuitCommand |
python | cherrypy__cherrypy | cherrypy/lib/httputil.py | {
"start": 13649,
"end": 14572
} | class ____(jaraco.collections.KeyTransformingDict):
"""A case-insensitive dict subclass.
Each key is changed on entry to title case.
"""
@staticmethod
def transform_key(key):
"""Title-case an HTTP header name."""
if key is None:
# TODO(#1830): why?
return 'N... | CaseInsensitiveDict |
python | django__django | tests/delete_regress/models.py | {
"start": 971,
"end": 1157
} | class ____(models.Model):
child = models.ForeignKey(Child, models.CASCADE)
toy = models.ForeignKey(Toy, models.CASCADE)
date = models.DateField(db_column="date_col")
| PlayedWith |
python | spyder-ide__spyder | external-deps/qtconsole/qtconsole/comms.py | {
"start": 5768,
"end": 8848
} | class ____(MetaQObjectHasTraits(
'NewBase', (LoggingConfigurable, SuperQObject), {})):
"""
Comm base class
"""
sig_is_closing = QtCore.Signal(object)
def __init__(self, target_name, kernel_client, comm_id=None,
msg_callback=None, close_callback=None):
"""
Cr... | Comm |
python | neetcode-gh__leetcode | python/0080-remove-duplicates-from-sorted-array-ii.py | {
"start": 0,
"end": 407
} | class ____:
def removeDuplicates(self, nums: List[int]) -> int:
l, r = 0, 0
while r < len(nums):
count = 1
while r + 1 < len(nums) and nums[r] == nums[r + 1]:
r += 1
count += 1
for i in range(min(2, count)):
... | Solution |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_storage_transfer_service.py | {
"start": 21761,
"end": 24706
} | class ____(GoogleCloudBaseOperator):
"""
Gets the latest state of a long-running operation in Google Storage Transfer Service.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudDataTransferServiceGetOperationOperator`
:pa... | CloudDataTransferServiceGetOperationOperator |
python | kamyu104__LeetCode-Solutions | Python/longest-uncommon-subsequence-ii.py | {
"start": 35,
"end": 825
} | class ____(object):
def findLUSlength(self, strs):
"""
:type strs: List[str]
:rtype: int
"""
def isSubsequence(a, b):
i = 0
for j in xrange(len(b)):
if i >= len(a):
break
if a[i] == b[j]:
... | Solution |
python | ZoranPandovski__al-go-rithms | data_structures/Graphs/graph/Python/floyd_warshall.py | {
"start": 147,
"end": 1520
} | class ____:
# Constructor
def __init__(self, vertices, directed=True):
# default dictionary to store graph
self.graph = defaultdict(list)
# Number of vertices
self.V = vertices
# Is a directed graph?
self.directed = directed
# Initialize adjacency matr... | Graph |
python | jazzband__django-oauth-toolkit | tests/migrations/0003_basetestapplication_post_logout_redirect_uris_and_more.py | {
"start": 158,
"end": 853
} | class ____(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.OAUTH2_PROVIDER_ID_TOKEN_MODEL),
("tests", "0002_swapped_models"),
]
operations = [
migrations.AddField(
model_name="basetestapplication",
name="post_logout_redirect_... | Migration |
python | astropy__astropy | astropy/cosmology/_src/tests/flrw/test_parameters.py | {
"start": 4299,
"end": 7043
} | class ____(ParameterTestMixin):
"""Tests for `astropy.cosmology.Parameter` Ode0 on a Cosmology.
Ode0 is a descriptor, which are tested by mixin, here with ``TestFLRW``.
These tests expect dicts ``_cls_args`` and ``cls_kwargs`` which give the
args and kwargs for the cosmology class, respectively. See ``... | ParameterOde0TestMixin |
python | tensorflow__tensorflow | tensorflow/compiler/mlir/tensorflow/tests/tf_saved_model/dag_object_graph.py | {
"start": 895,
"end": 1176
} | class ____(tf.Module):
def __init__(self):
super(Child, self).__init__()
self.my_variable = tf.Variable(3.)
# Creates a dag object graph.
# There is only one instance of `Child`, but it is reachable via two names.
# Thus, self.my_variable is reachable via two paths.
| Child |
python | ray-project__ray | python/ray/tune/registry.py | {
"start": 8823,
"end": 9426
} | class ____:
def __init__(self):
self.to_flush = {}
self.references = {}
def put(self, k, v):
self.to_flush[k] = v
if ray.is_initialized():
self.flush()
def get(self, k):
if not ray.is_initialized():
return self.to_flush[k]
return ray.... | _ParameterRegistry |
python | encode__django-rest-framework | tests/test_generics.py | {
"start": 15538,
"end": 16199
} | class ____(generics.ListCreateAPIView):
queryset = TwoFieldModel.objects.all()
renderer_classes = (renderers.BrowsableAPIRenderer, renderers.JSONRenderer)
def get_serializer_class(self):
if self.request.method == 'POST':
class DynamicSerializer(serializers.ModelSerializer):
... | DynamicSerializerView |
python | zarr-developers__zarr-python | src/zarr/codecs/numcodecs/_codecs.py | {
"start": 11549,
"end": 11622
} | class ____(_NumcodecsChecksumCodec, codec_name="adler32"):
pass
| Adler32 |
python | numba__numba | numba/core/utils.py | {
"start": 22358,
"end": 22535
} | class ____(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, _lazy_pformat):
return str(obj)
return super().default(obj)
| _LazyJSONEncoder |
python | huggingface__transformers | src/transformers/models/d_fine/modular_d_fine.py | {
"start": 40754,
"end": 42128
} | class ____(RTDetrModel):
def __init__(self, config: DFineConfig):
super().__init__(config)
del self.decoder_input_proj
self.encoder = DFineHybridEncoder(config=config)
num_backbone_outs = len(config.decoder_in_channels)
decoder_input_proj = []
in_channels = config.dec... | DFineModel |
python | getsentry__sentry | src/sentry/backup/crypto.py | {
"start": 12167,
"end": 12438
} | class ____:
"""
An Encryptor and Decryptor that use paired public and private keys, respectively.
"""
def __init__(self, encryptor: Encryptor, decryptor: Decryptor):
self.encryptor = encryptor
self.decryptor = decryptor
| EncryptorDecryptorPair |
python | ipython__ipython | IPython/terminal/embed.py | {
"start": 651,
"end": 922
} | class ____(Exception):pass
# kept for backward compatibility as IPython 6 was released with
# the typo. See https://github.com/ipython/ipython/pull/10706
KillEmbeded = KillEmbedded
# This is an additional magic that is exposed in embedded shells.
@magics_class
| KillEmbedded |
python | Textualize__textual | src/textual/demo/widgets.py | {
"start": 1027,
"end": 2884
} | class ____(containers.VerticalGroup):
"""Buttons demo."""
ALLOW_MAXIMIZE = True
DEFAULT_CLASSES = "column"
DEFAULT_CSS = """
Buttons {
ItemGrid { margin-bottom: 1;}
Button { width: 1fr; }
}
"""
BUTTONS_MD = """\
## Buttons
A simple button, with a number of semantic sty... | Buttons |
python | pypa__hatch | tests/backend/builders/test_wheel.py | {
"start": 22601,
"end": 24284
} | class ____:
def test_default(self, isolation):
builder = WheelBuilder(str(isolation))
assert builder.config.strict_naming is builder.config.strict_naming is True
def test_target(self, isolation):
config = {"tool": {"hatch": {"build": {"targets": {"wheel": {"strict-naming": False}}}}}}
... | TestStrictNaming |
python | kamyu104__LeetCode-Solutions | Python/number-of-good-pairs.py | {
"start": 50,
"end": 266
} | class ____(object):
def numIdenticalPairs(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(c*(c-1)//2 for c in collections.Counter(nums).itervalues())
| Solution |
python | django-guardian__django-guardian | example_project/core/migrations/0002_auto_20190629_0848.py | {
"start": 130,
"end": 992
} | class ____(migrations.Migration):
dependencies = [
("core", "0001_initial"),
]
operations = [
migrations.AlterField(
model_name="customuser",
name="last_name",
field=models.CharField(blank=True, max_length=150, verbose_name="last name"),
),
... | Migration |
python | pytorch__pytorch | test/jit/test_dce.py | {
"start": 222,
"end": 2181
} | class ____(JitTestCase):
def test_setattr_no_aliasdb(self):
class Net(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.x = torch.empty([2, 2])
def forward(self):
x = torch.rand([3, 3])
self.x = x
... | TestDCE |
python | mlflow__mlflow | mlflow/store/model_registry/databricks_workspace_model_registry_rest_store.py | {
"start": 2634,
"end": 7111
} | class ____(RestStore):
def __init__(self, store_uri, tracking_uri):
super().__init__(get_host_creds=partial(get_databricks_host_creds, store_uri))
self.tracking_uri = tracking_uri
def set_registered_model_alias(self, name, alias, version):
_raise_unsupported_method(method="set_registere... | DatabricksWorkspaceModelRegistryRestStore |
python | scrapy__scrapy | tests/test_commands.py | {
"start": 704,
"end": 2037
} | class ____:
def setup_method(self):
self.command = EmptyCommand()
self.command.settings = Settings()
self.parser = argparse.ArgumentParser(
formatter_class=ScrapyHelpFormatter, conflict_handler="resolve"
)
self.command.add_options(self.parser)
def test_settin... | TestCommandSettings |
python | falconry__falcon | falcon/errors.py | {
"start": 4054,
"end": 4713
} | class ____(ConnectionError):
"""The websocket connection is lost.
This error is raised when attempting to perform an operation on the
WebSocket and it is determined that either the client has closed the
connection, the server closed the connection, or the socket has otherwise
been lost.
Keywor... | WebSocketDisconnected |
python | huggingface__transformers | src/transformers/models/granitemoeshared/modeling_granitemoeshared.py | {
"start": 30466,
"end": 35211
} | class ____(GraniteMoeSharedPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config: GraniteMoeSharedConfig):
super().__init__(c... | GraniteMoeSharedForCausalLM |
python | aimacode__aima-python | probability4e.py | {
"start": 13823,
"end": 18975
} | class ____:
""" A Bayesian network node with continuous distribution or with continuous distributed parents """
def __init__(self, name, d_parents, c_parents, parameters, type):
"""
A continuous Bayesian node has two types of parents: discrete and continuous.
:param d_parents: str, name... | ContinuousBayesNode |
python | numba__numba | numba/cpython/setobj.py | {
"start": 41796,
"end": 57246
} | class ____(object):
def __init__(self, context, builder, iter_type, iter_val):
self._context = context
self._builder = builder
self._ty = iter_type
self._iter = context.make_helper(builder, iter_type, iter_val)
ptr = self._context.nrt.meminfo_data(builder, self.meminfo)
... | SetIterInstance |
python | tensorflow__tensorflow | tensorflow/python/eager/polymorphic_function/concrete_function.py | {
"start": 75037,
"end": 75575
} | class ____:
"""Cleans up reference cycles when a `ConcreteFunction` goes out of scope."""
__slots__ = ["_func_graph"]
def __init__(self, func_graph):
self._func_graph = func_graph
def release(self):
"""Call off the FuncGraph deletion."""
self._func_graph = None
def __del__(self):
if func_g... | ConcreteFunctionGarbageCollector |
python | pytorch__pytorch | test/dynamo/test_subclasses.py | {
"start": 46082,
"end": 47872
} | class ____(torch.nn.Module):
def forward(self, L_x_: "f32[3, 4]"):
l_x_ = L_x_
add_: "f32[3, 4]" = l_x_.add_(1.0)
relu_: "f32[3, 4]" = torch.relu_(l_x_); l_x_ = None
add: "f32[3, 4]" = add_ + relu_; add_ = relu_ = None
return (add,)
""",
)
self.assertTrue(t... | GraphModule |
python | walkccc__LeetCode | solutions/1157. Online Majority Element In Subarray/1157.py | {
"start": 0,
"end": 617
} | class ____:
def __init__(self, arr: list[int]):
self.arr = arr
self.TIMES = 20 # 2^TIMES >> |arr|
self.numToIndices = collections.defaultdict(list)
for i, a in enumerate(self.arr):
self.numToIndices[a].append(i)
def query(self, left: int, right: int, threshold: int) -> int:
for _ in ran... | MajorityChecker |
python | Textualize__textual | src/textual/style.py | {
"start": 1666,
"end": 15922
} | class ____:
"""Represents a style in the Visual interface (color and other attributes).
Styles may be added together, which combines their style attributes.
"""
background: Color | None = None
foreground: Color | None = None
bold: bool | None = None
dim: bool | None = None
italic: boo... | Style |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/natural_language.py | {
"start": 1492,
"end": 4642
} | class ____(GoogleCloudBaseOperator):
"""
Finds named entities in the text along with various properties.
Examples properties: entity types, salience, mentions for each entity, and others.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`how... | CloudNaturalLanguageAnalyzeEntitiesOperator |
python | kamyu104__LeetCode-Solutions | Python/minimum-time-to-complete-all-deliveries.py | {
"start": 70,
"end": 838
} | class ____(object):
def minimumTime(self, d, r):
"""
:type d: List[int]
:type r: List[int]
:rtype: int
"""
def gcd(a, b):
while b:
a, b = b, a%b
return a
def lcm(a, b):
return a//gcd(a,b)*b
def bina... | Solution |
python | pypa__pip | src/pip/_internal/utils/temp_dir.py | {
"start": 2130,
"end": 6597
} | class ____:
"""Helper class that owns and cleans up a temporary directory.
This class can be used as a context manager or as an OO representation of a
temporary directory.
Attributes:
path
Location to the created temporary directory
delete
Whether the directory ... | TempDirectory |
python | pandas-dev__pandas | pandas/tests/indexing/test_chaining_and_caching.py | {
"start": 306,
"end": 2280
} | class ____:
@pytest.mark.parametrize("do_ref", [True, False])
def test_setitem_cache_updating(self, do_ref):
# GH 5424
cont = ["one", "two", "three", "four", "five", "six", "seven"]
df = DataFrame({"a": cont, "b": cont[3:] + cont[:3], "c": np.arange(7)})
# ref the cache
... | TestCaching |
python | scikit-learn__scikit-learn | sklearn/tests/metadata_routing_common.py | {
"start": 14929,
"end": 15492
} | class ____(_Scorer):
def __init__(self, registry=None):
super().__init__(
score_func=mean_squared_error, sign=1, kwargs={}, response_method="predict"
)
self.registry = registry
def _score(self, method_caller, clf, X, y, **kwargs):
if self.registry is not None:
... | ConsumingScorer |
python | ray-project__ray | rllib/examples/rl_modules/classes/modelv2_to_rlm.py | {
"start": 958,
"end": 9244
} | class ____(TorchRLModule, ValueFunctionAPI):
"""An RLModule containing a (old stack) ModelV2.
The `ModelV2` may be define either through
- an existing Policy checkpoint
- an existing Algorithm checkpoint (and a policy ID or "default_policy")
- or through an AlgorithmConfig object
The ModelV2 i... | ModelV2ToRLModule |
python | kamyu104__LeetCode-Solutions | Python/check-if-all-the-integers-in-a-range-are-covered.py | {
"start": 65,
"end": 662
} | class ____(object):
def isCovered(self, ranges, left, right):
"""
:type ranges: List[List[int]]
:type left: int
:type right: int
:rtype: bool
"""
RANGE_SIZE = 50
interval = [0]*(RANGE_SIZE+1)
for l, r in ranges:
interval[l-1] += 1
... | Solution |
python | fastapi__sqlmodel | docs_src/tutorial/relationship_attributes/read_relationships/tutorial002.py | {
"start": 338,
"end": 4085
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
team_id: Optional[int] = Field(default=None, foreign_key="team.id")
team: Optional[Team] = Relationship... | Hero |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/waiters/test_comprehend.py | {
"start": 1394,
"end": 1621
} | class ____:
@pytest.fixture(autouse=True)
def mock_conn(self, monkeypatch):
self.client = boto3.client("comprehend")
monkeypatch.setattr(ComprehendHook, "conn", self.client)
| TestComprehendCustomWaitersBase |
python | kamyu104__LeetCode-Solutions | Python/longest-semi-repeating-subarray.py | {
"start": 805,
"end": 1498
} | class ____(object):
def longestSubarray(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
cnt = collections.defaultdict(int)
result = left = repeat = 0
for right in xrange(len(nums)):
cnt[nums[right]] += 1
i... | Solution2 |
python | google__jax | jax/_src/hijax.py | {
"start": 10134,
"end": 16112
} | class ____:
in_avals: tuple[PyTreeOfAvals, ...]
out_aval: PyTreeOfAvals
params: dict[str, Hashable]
def __init__(self):
if not hasattr(self, 'in_avals'):
raise AttributeError("subclass __init__ should set `self.in_avals`")
if not hasattr(self, 'out_aval'):
raise AttributeError("subclass __i... | VJPHiPrimitive |
python | dagster-io__dagster | python_modules/libraries/dagster-snowflake-polars/dagster_snowflake_polars/snowflake_polars_type_handler.py | {
"start": 5628,
"end": 12518
} | class ____(SnowflakeIOManager):
"""An I/O manager definition that reads inputs from and writes Polars DataFrames to Snowflake. When
using the SnowflakePolarsIOManager, any inputs and outputs without type annotations will be loaded
as Polars DataFrames.
Returns:
IOManagerDefinition
Example... | SnowflakePolarsIOManager |
python | keras-team__keras | keras/src/ops/image.py | {
"start": 311,
"end": 2714
} | class ____(Operation):
def __init__(self, data_format=None, *, name=None):
super().__init__(name=name)
self.data_format = backend.standardize_data_format(data_format)
def call(self, images):
return backend.image.rgb_to_grayscale(
images, data_format=self.data_format
... | RGBToGrayscale |
python | FactoryBoy__factory_boy | tests/test_using.py | {
"start": 88979,
"end": 89565
} | class ____(unittest.TestCase):
def test_no_parent(self):
from .cyclic import self_ref
obj = self_ref.TreeElementFactory(parent__parent__parent=None)
self.assertIsNone(obj.parent.parent.parent)
def test_deep(self):
from .cyclic import self_ref
obj = self_ref.TreeElement... | SelfReferentialTests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.