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 | getsentry__sentry | src/sentry/api/endpoints/project_commits.py | {
"start": 477,
"end": 1888
} | class ____(ProjectEndpoint):
owner = ApiOwner.ISSUES
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
permission_classes = (ProjectReleasePermission,)
def get(self, request: Request, project) -> Response:
"""
List a Project's Commits
`````````````````````````
... | ProjectCommitsEndpoint |
python | openai__openai-python | src/openai/types/beta/thread_create_params.py | {
"start": 5803,
"end": 6423
} | class ____(TypedDict, total=False):
vector_store_ids: SequenceNotStr[str]
"""
The
[vector store](https://platform.openai.com/docs/api-reference/vector-stores/object)
attached to this thread. There can be a maximum of 1 vector store attached to
the thread.
"""
vector_stores: Iterable[Too... | ToolResourcesFileSearch |
python | huggingface__transformers | src/transformers/models/apertus/modular_apertus.py | {
"start": 9285,
"end": 11500
} | class ____(LlamaAttention):
def __init__(self, config: ApertusConfig, layer_idx: Optional[int] = None):
super().__init__(config, layer_idx)
self.q_norm = ApertusRMSNorm(self.head_dim, config.rms_norm_eps)
self.k_norm = ApertusRMSNorm(self.head_dim, config.rms_norm_eps)
def forward(
... | ApertusAttention |
python | keras-team__keras | keras/src/losses/losses_test.py | {
"start": 7404,
"end": 10711
} | class ____(testing.TestCase):
def test_config(self):
self.run_class_serialization_test(
losses.MeanAbsolutePercentageError(name="mymape")
)
def test_all_correct_unweighted(self):
mape_obj = losses.MeanAbsolutePercentageError()
y_true = np.array([[4, 8, 12], [8, 1, 3]... | MeanAbsolutePercentageErrorTest |
python | keras-team__keras | keras/src/backend/common/backend_utils_test.py | {
"start": 2702,
"end": 3682
} | class ____(test_case.TestCase):
def test_valid_padding_without_output_padding(self):
"""Test computation with 'valid' padding and no output padding"""
jax_padding = compute_conv_transpose_padding_args_for_jax(
input_shape=(1, 5, 5, 3),
kernel_shape=(3, 3, 3, 3),
s... | ComputeConvTransposePaddingArgsForJAXTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py | {
"start": 2276,
"end": 3161
} | class ____(IncrementalShopifyStreamWithDeletedEvents):
data_field = "orders"
deleted_events_api_name = "Order"
initial_limit = 250
def __init__(self, config: Mapping[str, Any]):
self._error_handler = LimitReducingErrorHandler(
max_retries=5,
error_mapping=DEFAULT_ERROR_M... | Orders |
python | celery__celery | celery/concurrency/thread.py | {
"start": 521,
"end": 738
} | class ____:
def __init__(self, future: Future) -> None:
self.f = future
self.get = self.f.result
def wait(self, timeout: float | None = None) -> None:
wait([self.f], timeout)
| ApplyResult |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-hubspot/unit_tests/integrations/test_engagements_calls.py | {
"start": 373,
"end": 5585
} | class ____(HubspotCRMSearchStream):
SCOPES = ["crm.objects.contacts.read"]
CURSOR_FIELD = "updatedAt"
STREAM_NAME = "engagements_calls"
OBJECT_TYPE = "calls"
ASSOCIATIONS = ["companies", "contacts", "deals", "tickets"]
OBJECT_ID = "12345"
@HttpMocker()
def test_given_records_when_read_e... | TestEngagementCallsStream |
python | google__jax | jax/_src/pallas/mosaic_gpu/core.py | {
"start": 39567,
"end": 39650
} | class ____(dtypes.extended):
pass
@dataclasses.dataclass(frozen=True)
| barrier_dtype |
python | huggingface__transformers | src/transformers/quantizers/quantizer_quanto.py | {
"start": 1057,
"end": 6147
} | class ____(HfQuantizer):
"""
Quantizer for the quanto library
"""
required_packages = ["quanto", "accelerate"]
requires_parameters_quantization = True
requires_calibration = False
def __init__(self, quantization_config: QuantoConfig, **kwargs):
super().__init__(quantization_config,... | QuantoHfQuantizer |
python | streamlit__streamlit | lib/tests/streamlit/elements/markdown_test.py | {
"start": 14068,
"end": 15669
} | class ____(DeltaGeneratorTestCase):
"""Test st.caption text_alignment parameter."""
@parameterized.expand(
[
("left", 1),
("center", 2),
("right", 3),
("justify", 4),
(None, 1), # Default case
]
)
def test_st_caption_text_alig... | StCaptionTextAlignmentTest |
python | pytorch__pytorch | torch/ao/quantization/pt2e/representation/rewrite.py | {
"start": 19365,
"end": 28387
} | class ____:
"""Data needed for rewrite, this includes example inputs, pattern and replacement functions
and post transformation functions for the exported pattern and replacement GraphModule
"""
# example inputs used for exporting the pattern into GraphModule
example_inputs: tuple[Any, ...]
pat... | _RewriteInfo |
python | Textualize__textual | src/textual/demo/game.py | {
"start": 9725,
"end": 17007
} | class ____(containers.Vertical, can_focus=True):
"""Widget for the game board."""
ALLOW_MAXIMIZE = False
DEFAULT_CSS = """
Game {
visibility: hidden;
align: center middle;
hatch: right $panel;
border: heavy transparent;
&:focus {
border: heavy $succes... | Game |
python | pytorch__pytorch | test/test_throughput_benchmark.py | {
"start": 180,
"end": 654
} | class ____(torch.jit.ScriptModule):
def __init__(self, D_in, H, D_out):
super().__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(2 * H, D_out)
@torch.jit.script_method
def forward(self, x1, x2):
h1_relu = self.linear1(x1).clamp(min=0)
... | TwoLayerNet |
python | google__pytype | pytype/pytd/pytd.py | {
"start": 18317,
"end": 18523
} | class ____(GenericType):
"""Concatenate params and ParamSpec."""
@property
def args(self):
return self.parameters[:-1]
@property
def paramspec(self):
return self.parameters[-1]
| Concatenate |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli/api_layer/schemas/sensor.py | {
"start": 868,
"end": 984
} | class ____(BaseModel):
"""GET /api/sensors response."""
items: list[DgApiSensor]
total: int
| DgApiSensorList |
python | dask__distributed | distributed/core.py | {
"start": 1682,
"end": 2380
} | class ____(Enum):
"""
This Enum contains the various states a cluster, worker, scheduler and nanny can be
in. Some of the status can only be observed in one of cluster, nanny, scheduler or
worker but we put them in the same Enum as they are compared with each
other.
"""
undefined = "undefin... | Status |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pycodestyle/W29.py | {
"start": 43,
"end": 392
} | class ____(object):
bang = 12
#: W291:2:35
'''multiline
string with trailing whitespace'''
#: W291 W292 noeol
x = 1
#: W191 W292 noeol
if False:
pass # indented with tabs
#: W292:1:36 noeol
# This line doesn't have a linefeed
#: W292:1:5 E225:1:2 noeol
1+ 1
#: W292:1:27 E261:1:12 noeol
import this # no... | Foo |
python | getsentry__sentry | tests/sentry/issues/endpoints/test_organization_group_search_view_details.py | {
"start": 5514,
"end": 11164
} | class ____(BaseGSVTestCase):
endpoint = "sentry-api-0-organization-group-search-view-details"
method = "delete"
def setUp(self) -> None:
self.base_data = self.create_base_data()
# For most tests, we'll be deleting views from user_2 (no special permissions)
self.login_as(user=self.u... | OrganizationGroupSearchViewsDeleteTest |
python | great-expectations__great_expectations | great_expectations/checkpoint/actions.py | {
"start": 17954,
"end": 20481
} | class ____(ValidationAction):
"""Sends a PagerDuty event.
```yaml
- name: send_pagerduty_alert_on_validation_result
action:
class_name: PagerdutyAlertAction
api_key: ${pagerduty_api_key}
routing_key: ${pagerduty_routing_key}
notify_on: failure
severity: critical
```
... | PagerdutyAlertAction |
python | spyder-ide__spyder | spyder/api/asyncdispatcher.py | {
"start": 17655,
"end": 17837
} | class ____(QObject):
"""Executor to run callbacks in the main Qt loop."""
def customEvent(self, e: _QCallbackEvent): # noqa: N802, PLR6301
e.func()
| _QCallbackExecutor |
python | pytorch__pytorch | torch/testing/_internal/common_quantization.py | {
"start": 90519,
"end": 90838
} | class ____(nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv = nn.Conv2d(2, 2, 1, bias=None).to(dtype=torch.float)
self.bn = nn.BatchNorm2d(2).to(dtype=torch.float)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
return x
| SubModelForFusion |
python | getsentry__sentry | src/sentry/notifications/platform/target.py | {
"start": 4305,
"end": 5598
} | class ____:
"""
A wrapper class that handles serialization/deserialization of NotificationTargets.
"""
target: NotificationTarget
@property
def notification_type(self) -> NotificationTargetType:
if isinstance(self.target, IntegrationNotificationTarget):
return NotificationT... | NotificationTargetDto |
python | docker__docker-py | tests/integration/api_client_test.py | {
"start": 144,
"end": 478
} | class ____(BaseAPIIntegrationTest):
def test_version(self):
res = self.client.version()
assert 'GoVersion' in res
assert 'Version' in res
def test_info(self):
res = self.client.info()
assert 'Containers' in res
assert 'Images' in res
assert 'Debug' in res... | InformationTest |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP049_1.py | {
"start": 121,
"end": 164
} | class ____[_T = int]:
var: _T
# tuple
| Foo |
python | dagster-io__dagster | python_modules/dagster/dagster/components/core/component_tree.py | {
"start": 20458,
"end": 21781
} | class ____(ComponentTree):
"""Variant of ComponentTree that is used for testing purposes. Mocks out the
definitions module name and path.
"""
@staticmethod
def for_test() -> "TestComponentTree":
"""Convenience method for creating a ComponentTree for testing purposes."""
return TestC... | TestComponentTree |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 76103,
"end": 78823
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
cran: Optional[RCranLibrary] = Field(
None, description="If cran, specification of a CRAN library to be installed."
)
egg: Optional[str] = Field(
... | Library |
python | tensorflow__tensorflow | tensorflow/python/ops/linalg/linear_operator.py | {
"start": 52139,
"end": 62340
} | class ____(type_spec.BatchableTypeSpec):
"""A tf.TypeSpec for `LinearOperator` objects."""
__slots__ = ("_param_specs", "_non_tensor_params", "_prefer_static_fields")
def __init__(self, param_specs, non_tensor_params, prefer_static_fields):
"""Initializes a new `_LinearOperatorSpec`.
Args:
param_... | _LinearOperatorSpec |
python | keras-team__keras | keras/src/ops/core_test.py | {
"start": 49222,
"end": 56070
} | class ____(testing.TestCase):
def test_associative_scan_invalid_arguments(self):
# varying dimension at scan axis
x = (np.array([1, 2]), np.array([3, 4]), np.array([5, 6, 7]))
with self.assertRaisesRegex(ValueError, " first dimension"):
core.associative_scan(lambda x, y: (x[0] + ... | CoreOpsBehaviorTests |
python | doocs__leetcode | solution/1400-1499/1434.Number of Ways to Wear Different Hats to Each Other/Solution.py | {
"start": 0,
"end": 622
} | class ____:
def numberWays(self, hats: List[List[int]]) -> int:
g = defaultdict(list)
for i, h in enumerate(hats):
for v in h:
g[v].append(i)
mod = 10**9 + 7
n = len(hats)
m = max(max(h) for h in hats)
f = [[0] * (1 << n) for _ in range(m +... | Solution |
python | walkccc__LeetCode | solutions/2249. Count Lattice Points Inside a Circle/2249.py | {
"start": 0,
"end": 231
} | class ____:
def countLatticePoints(self, circles: list[list[int]]) -> int:
return sum(any((xc - x)**2 + (yc - y)**2 <= r**2 for xc, yc, r in circles)
for x in range(201)
for y in range(201))
| Solution |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_searchstrategy.py | {
"start": 5239,
"end": 5956
} | class ____:
a: Any
b: Any
@pytest.mark.parametrize(
"obj, value",
[
(recursive_list, ["[...]"]),
(recursive_dict, {"a": "{...}"}),
(mutual1, [["[...]"]]),
(mutual2, [["[...]"]]),
# same id object in different fields. no cycle
(A(a=shared, b=shared), {"a"... | A |
python | getsentry__sentry | tests/sentry/api/bases/test_organization.py | {
"start": 14835,
"end": 23156
} | class ____(BaseOrganizationEndpointTest):
def setUp(self) -> None:
self.team_1 = self.create_team(organization=self.org)
self.team_2 = self.create_team(organization=self.org)
self.team_3 = self.create_team(organization=self.org)
self.create_team_membership(user=self.member, team=self... | GetProjectIdsTest |
python | sympy__sympy | sympy/combinatorics/perm_groups.py | {
"start": 983,
"end": 179285
} | class ____(Basic):
r"""The class defining a Permutation group.
Explanation
===========
``PermutationGroup([p1, p2, ..., pn])`` returns the permutation group
generated by the list of permutations. This group can be supplied
to Polyhedron if one desires to decorate the elements to which the
... | PermutationGroup |
python | ray-project__ray | python/ray/tune/logger/logger.py | {
"start": 7290,
"end": 8122
} | class ____(yaml.SafeDumper):
def represent_sequence(self, tag, sequence, flow_style=None):
if len(sequence) > _SEQUENCE_LEN_FLOW_STYLE:
return super().represent_sequence(tag, sequence, flow_style=True)
return super().represent_sequence(tag, sequence, flow_style=flow_style)
@DeveloperAP... | _RayDumper |
python | PrefectHQ__prefect | src/prefect/server/schemas/schedules.py | {
"start": 18254,
"end": 27126
} | class ____(PrefectBaseModel):
"""
RRule schedule, based on the iCalendar standard
([RFC 5545](https://datatracker.ietf.org/doc/html/rfc5545)) as
implemented in `dateutils.rrule`.
RRules are appropriate for any kind of calendar-date manipulation, including
irregular intervals, repetition, exclus... | RRuleSchedule |
python | graphql-python__graphene | graphene/types/datetime.py | {
"start": 1327,
"end": 2450
} | class ____(Scalar):
"""
The `DateTime` scalar type represents a DateTime
value as specified by
[iso8601](https://en.wikipedia.org/wiki/ISO_8601).
"""
@staticmethod
def serialize(dt):
if not isinstance(dt, (datetime.datetime, datetime.date)):
raise GraphQLError(f"DateTime... | DateTime |
python | pdm-project__pdm | src/pdm/models/specifiers.py | {
"start": 2196,
"end": 9836
} | class ____(SpecifierSet):
"""A custom SpecifierSet that supports merging with logic operators (&, |)."""
PY_MAX_MINOR_VERSION = _read_max_versions()
MAX_MAJOR_VERSION = max(PY_MAX_MINOR_VERSION)[:1].bump()
__slots__ = ("_logic", "_prereleases", "_specs")
def __init__(self, spec: str | VersionSpec... | PySpecSet |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess1.py | {
"start": 1839,
"end": 1930
} | class ____(metaclass=MetaclassE):
x = DescriptorE()
ClassE.x
ClassE().x
ClassE.y
| ClassE |
python | huggingface__transformers | src/transformers/models/aria/modeling_aria.py | {
"start": 18408,
"end": 21562
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: AriaTextConfig, layer_idx: int):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.head_dim = getattr(config, "head_dim", config.hidden_siz... | AriaTextAttention |
python | pandas-dev__pandas | asv_bench/benchmarks/frame_methods.py | {
"start": 9246,
"end": 9951
} | class ____:
def setup(self):
nrows = 10000
data = np.random.randn(nrows, 10)
arrays = np.tile(np.random.randn(3, nrows // 100), 100)
idx = MultiIndex.from_arrays(arrays)
self.df3 = DataFrame(data, index=idx)
self.df4 = DataFrame(data, index=np.random.randn(nrows))
... | Repr |
python | tiangolo__fastapi | tests/test_response_code_no_body.py | {
"start": 318,
"end": 3315
} | class ____(BaseModel):
errors: typing.List[Error]
@app.get(
"/a",
status_code=204,
response_class=JsonApiResponse,
responses={500: {"description": "Error", "model": JsonApiError}},
)
async def a():
pass
@app.get("/b", responses={204: {"description": "No Content"}})
async def b():
pass #... | JsonApiError |
python | modin-project__modin | modin/core/dataframe/algebra/default2pandas/groupby.py | {
"start": 22811,
"end": 25296
} | class ____(DefaultMethod):
"""Builder for default-to-pandas GroupBy aggregation functions."""
_groupby_cls = GroupBy
OBJECT_TYPE = "GroupBy"
@classmethod
def register(cls, func, **kwargs):
"""
Build default-to-pandas GroupBy aggregation function.
Parameters
------... | GroupByDefault |
python | Lightning-AI__lightning | src/lightning/pytorch/demos/transformer.py | {
"start": 843,
"end": 2901
} | class ____(nn.Module):
def __init__(
self,
vocab_size: int = 33278, # default for WikiText2
ninp: int = 200,
nhead: int = 2,
nhid: int = 200,
nlayers: int = 2,
dropout: float = 0.2,
) -> None:
super().__init__()
self.pos_encoder = Position... | Transformer |
python | huggingface__transformers | src/transformers/models/roformer/modeling_roformer.py | {
"start": 29224,
"end": 34846
} | class ____(RoFormerPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.config = config
self.embeddings = RoFormerEmbeddings(config)
if config.embedding_size != config.hidden_size:
self.embeddings_project = nn.Linear(config.embedding_size, config.h... | RoFormerModel |
python | pytorch__pytorch | .ci/lumen_cli/tests/test_vllm.py | {
"start": 217,
"end": 3763
} | class ____(unittest.TestCase):
@patch(f"{_VLLM_BUILD_MODULE}.local_image_exists", return_value=True)
@patch(f"{_VLLM_BUILD_MODULE}.is_path_exist", return_value=True)
@patch(
"cli.lib.common.envs_helper.env_path_optional",
side_effect=lambda name, default=None, resolve=True: {
"DO... | TestVllmBuildParameters |
python | yaml__pyyaml | lib/yaml/__init__.py | {
"start": 11507,
"end": 12316
} | class ____(metaclass=YAMLObjectMetaclass):
"""
An object that can dump itself to a YAML stream
and load itself from a YAML stream.
"""
__slots__ = () # no direct instantiation, so allow immutable subclasses
yaml_loader = [Loader, FullLoader, UnsafeLoader]
yaml_dumper = Dumper
yaml_ta... | YAMLObject |
python | python-attrs__attrs | src/attr/_version_info.py | {
"start": 205,
"end": 2222
} | class ____:
"""
A version object that can be compared to tuple of length 1--4:
>>> attr.VersionInfo(19, 1, 0, "final") <= (19, 2)
True
>>> attr.VersionInfo(19, 1, 0, "final") < (19, 1, 1)
True
>>> vi = attr.VersionInfo(19, 2, 0, "final")
>>> vi < (19, 1, 1)
False
>>> vi < (19,)... | VersionInfo |
python | huggingface__transformers | src/transformers/models/lightglue/modular_lightglue.py | {
"start": 1726,
"end": 8814
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`LightGlueForKeypointMatching`]. It is used to
instantiate a LightGlue model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yie... | LightGlueConfig |
python | huggingface__transformers | src/transformers/models/smollm3/modeling_smollm3.py | {
"start": 15814,
"end": 19657
} | class ____(SmolLM3PreTrainedModel):
def __init__(self, config: SmolLM3Config):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.l... | SmolLM3Model |
python | doocs__leetcode | solution/2000-2099/2088.Count Fertile Pyramids in a Land/Solution.py | {
"start": 0,
"end": 865
} | class ____:
def countPyramids(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
f = [[0] * n for _ in range(m)]
ans = 0
for i in range(m - 1, -1, -1):
for j in range(n):
if grid[i][j] == 0:
f[i][j] = -1
... | Solution |
python | ray-project__ray | rllib/core/rl_module/apis/q_net_api.py | {
"start": 157,
"end": 2045
} | class ____(abc.ABC):
"""An API to be implemented by RLModules used for (distributional) Q-learning.
RLModules implementing this API must override the `compute_q_values` and the
`compute_advantage_distribution` methods.
"""
@abc.abstractmethod
def compute_q_values(
self,
batch: ... | QNetAPI |
python | walkccc__LeetCode | solutions/1151. Minimum Swaps to Group All 1's Together/1151.py | {
"start": 0,
"end": 371
} | class ____:
def minSwaps(self, data: list[int]) -> int:
k = data.count(1)
ones = 0 # the number of ones in the window
maxOnes = 0 # the maximum number of ones in the window
for i, num in enumerate(data):
if i >= k and data[i - k]:
ones -= 1
if num:
ones += 1
maxOne... | Solution |
python | lepture__mistune | src/mistune/directives/include.py | {
"start": 273,
"end": 2343
} | class ____(DirectivePlugin):
def parse(
self, block: "BlockParser", m: Match[str], state: "BlockState"
) -> Union[Dict[str, Any], List[Dict[str, Any]]]:
source_file = state.env.get("__file__")
if not source_file:
return {"type": "block_error", "raw": "Missing source file"}
... | Include |
python | langchain-ai__langchain | libs/core/langchain_core/runnables/configurable.py | {
"start": 15079,
"end": 15347
} | class ____(str, enum.Enum):
"""String enum."""
_enums_for_spec: WeakValueDictionary[
ConfigurableFieldSingleOption | ConfigurableFieldMultiOption | ConfigurableField,
type[StrEnum],
] = WeakValueDictionary()
_enums_for_spec_lock = threading.Lock()
| StrEnum |
python | huggingface__transformers | src/transformers/models/mra/modeling_mra.py | {
"start": 27642,
"end": 28790
} | class ____(GradientCheckpointingLayer):
def __init__(self, config):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = MraAttention(config)
self.add_cross_attention = config.add_cross_attention
self.i... | MraLayer |
python | walkccc__LeetCode | solutions/2980. Check if Bitwise OR Has Trailing Zeros/2980.py | {
"start": 0,
"end": 121
} | class ____:
def hasTrailingZeros(self, nums: list[int]) -> bool:
return sum(num % 2 == 0 for num in nums) >= 2
| Solution |
python | walkccc__LeetCode | solutions/473. Matchsticks to Square/473.py | {
"start": 0,
"end": 648
} | class ____:
def makesquare(self, matchsticks: list[int]) -> bool:
if len(matchsticks) < 4:
return False
perimeter = sum(matchsticks)
if perimeter % 4 != 0:
return False
A = sorted(matchsticks)[::-1]
def dfs(selected: int, edges: list[int]) -> bool:
if selected == len(A):
... | Solution |
python | doocs__leetcode | solution/1100-1199/1140.Stone Game II/Solution.py | {
"start": 0,
"end": 388
} | class ____:
def stoneGameII(self, piles: List[int]) -> int:
@cache
def dfs(i, m):
if m * 2 >= n - i:
return s[n] - s[i]
return max(
s[n] - s[i] - dfs(i + x, max(m, x)) for x in range(1, m << 1 | 1)
)
n = len(piles)
... | Solution |
python | jina-ai__jina | tests/unit/serve/runtimes/worker/test_worker_runtime.py | {
"start": 5790,
"end": 11851
} | class ____(Executor):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
time.sleep(5.0)
@requests
def foo(self, docs, **kwargs):
return docs
@pytest.mark.timeout(10)
@pytest.mark.asyncio
@pytest.mark.skip
async def test_worker_runtime_slow_init_exec():
arg... | SlowInitExecutor |
python | dagster-io__dagster | python_modules/libraries/dagster-omni/dagster_omni/objects.py | {
"start": 4444,
"end": 4960
} | class ____:
"""Serializable container object for recording the state of the Omni API at a given point in time.
Properties:
documents: list[OmniDocument]
users: list[OmniUser]
"""
documents: list[OmniDocument]
users: list[OmniUser]
@cached_property
def _users_by_id(self) ->... | OmniWorkspaceData |
python | pytest-dev__pytest | testing/test_unittest.py | {
"start": 45688,
"end": 50745
} | class ____:
"""
Make sure to show exceptions raised during class cleanup function (those registered
via addClassCleanup()).
See #11728.
"""
def test_class_cleanups_failure_in_setup(self, pytester: Pytester) -> None:
testpath = pytester.makepyfile(
"""
import uni... | TestClassCleanupErrors |
python | kamyu104__LeetCode-Solutions | Python/maximum-nesting-depth-of-two-valid-parentheses-strings.py | {
"start": 265,
"end": 739
} | class ____(object):
def maxDepthAfterSplit(self, seq):
"""
:type seq: str
:rtype: List[int]
"""
A, B = 0, 0
result = [0]*len(seq)
for i, c in enumerate(seq):
point = 1 if c == '(' else -1
if (point == 1 and A <= B) or \
(... | Solution2 |
python | python__mypy | mypy/types.py | {
"start": 16962,
"end": 17523
} | class ____(Type):
"""Required[T] or NotRequired[T]. Only usable at top-level of a TypedDict definition."""
def __init__(self, item: Type, *, required: bool) -> None:
super().__init__(line=item.line, column=item.column)
self.item = item
self.required = required
def __repr__(self) ->... | RequiredType |
python | pypa__setuptools | setuptools/_vendor/tomli/_parser.py | {
"start": 6204,
"end": 7220
} | class ____:
def __init__(self) -> None:
# The parsed content of the TOML document
self.dict: dict[str, Any] = {}
def get_or_create_nest(
self,
key: Key,
*,
access_lists: bool = True,
) -> dict:
cont: Any = self.dict
for k in key:
i... | NestedDict |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_roman_numeral.py | {
"start": 525,
"end": 1661
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_roman_numeral"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pan... | ColumnValuesToBeValidRomanNumeral |
python | pandas-dev__pandas | pandas/tests/arrays/sparse/test_libsparse.py | {
"start": 17476,
"end": 19043
} | class ____:
@pytest.mark.parametrize("opname", ["add", "sub", "mul", "truediv", "floordiv"])
def test_op(self, opname, cases, test_length):
xloc, xlen, yloc, ylen, _, _ = cases
sparse_op = getattr(splib, f"sparse_{opname}_float64")
python_op = getattr(operator, opname)
xindex = ... | TestSparseOperators |
python | django-extensions__django-extensions | django_extensions/db/models.py | {
"start": 246,
"end": 789
} | class ____(models.Model):
"""
TimeStampedModel
An abstract base class model that provides self-managed "created" and
"modified" fields.
"""
created = CreationDateTimeField(_("created"))
modified = ModificationDateTimeField(_("modified"))
def save(self, **kwargs):
self.update_m... | TimeStampedModel |
python | aio-libs__aiohttp | tests/test_web_exceptions.py | {
"start": 10398,
"end": 11572
} | class ____:
def test_ctor(self) -> None:
resp = web.HTTPRequestEntityTooLarge(
max_size=100,
actual_size=123,
headers={"X-Custom": "value"},
reason="Too large",
)
assert resp.text == (
"Maximum request body size 100 exceeded, actual... | TestHTTPRequestEntityTooLarge |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-klaviyo/components.py | {
"start": 1823,
"end": 4328
} | class ____(StateMigration, ABC):
"""
Updates old format state to new per partitioned format.
Partitions: [{archived: True}, {archived: False}]
Default built in airbyte cdk migration will recognise only top-level field cursor value(updated_at),
but for partition {archived: True} source should use cur... | ArchivedToPerPartitionStateMigration |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0071_add_env_var_privacy.py | {
"start": 100,
"end": 617
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0070_make_md5_field_nullable"),
]
operations = [
migrations.AddField(
model_name="environmentvariable",
name="public",
field=models.BooleanField(
... | Migration |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/linear_unpack_fp16_test.py | {
"start": 585,
"end": 1508
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, M, N, K, device):
# input to unpack operator must be what the output is for prepack operator
self.inputs = {
"input_one": torch.ops.quantized.linear_prepack_fp16(
torch.rand(
M, N, K, device=devic... | LinearUnpackFP16Benchmark |
python | dask__dask | dask/dataframe/tseries/resample.py | {
"start": 6604,
"end": 6670
} | class ____(ResampleReduction):
how = "quantile"
| ResampleQuantile |
python | pytorch__pytorch | test/quantization/fx/test_numeric_suite_fx.py | {
"start": 9862,
"end": 30867
} | class ____(QuantizationTestCase):
@skipIfNoFBGEMM
def test_simple_mod(self):
m = nn.Sequential(nn.Conv2d(1, 1, 1)).eval()
mp = prepare_fx(m, {'': torch.ao.quantization.default_qconfig}, example_inputs=(torch.randn(1, 1, 1, 1),))
mp_copy = copy.deepcopy(mp)
mq = convert_fx(mp_cop... | TestFXGraphMatcher |
python | catalyst-team__catalyst | catalyst/contrib/data/dataset.py | {
"start": 4149,
"end": 6032
} | class ____(ListDataset):
"""
Dataset that derives features and targets from samples filesystem paths.
Examples:
>>> label_fn = lambda x: x.split("_")[0]
>>> dataset = PathsDataset(
>>> filenames=Path("/path/to/images/").glob("*.jpg"),
>>> label_fn=label_fn,
>... | PathsDataset |
python | pypa__warehouse | warehouse/manage/views/organizations.py | {
"start": 62433,
"end": 73882
} | class ____:
def __init__(self, organization, request):
self.organization = organization
self.request = request
self.metrics = self.request.metrics
self.project_service = self.request.find_service(IProjectService)
self.pending_github_publisher_form = PendingGitHubPublisherForm... | ManageOrganizationPublishingViews |
python | gevent__gevent | src/gevent/tests/test__pywsgi.py | {
"start": 14912,
"end": 17036
} | class ____(CommonTestMixin, TestCase):
# when returning a list of strings a shortcut is employed by the server:
# it calculates the content-length and joins all the chunks before sending
validator = None
last_environ = None
def _check_environ(self, input_terminated=True):
if input_terminate... | TestNoChunks |
python | huggingface__transformers | src/transformers/models/gemma3/image_processing_gemma3_fast.py | {
"start": 1295,
"end": 10268
} | class ____(BaseImageProcessorFast):
resample = PILImageResampling.BILINEAR
image_mean = IMAGENET_STANDARD_MEAN
image_std = IMAGENET_STANDARD_STD
size = {"height": 224, "width": 224}
default_to_square = True
do_convert_rgb = True
do_resize = True
do_rescale = True
do_normalize = True
... | Gemma3ImageProcessorFast |
python | sympy__sympy | sympy/functions/special/bessel.py | {
"start": 32635,
"end": 34488
} | class ____(SphericalBesselBase):
r"""
Spherical Bessel function of the second kind.
Explanation
===========
This function is another solution to the spherical Bessel equation, and
linearly independent from $j_n$. It can be defined as
.. math ::
y_\nu(z) = \sqrt{\frac{\pi}{2z}} Y_{... | yn |
python | python-attrs__attrs | src/attr/validators.py | {
"start": 10714,
"end": 13203
} | class ____:
key_validator = attrib(validator=optional(is_callable()))
value_validator = attrib(validator=optional(is_callable()))
mapping_validator = attrib(validator=optional(is_callable()))
def __call__(self, inst, attr, value):
"""
We use a callable class to be able to change the ``_... | _DeepMapping |
python | skorch-dev__skorch | skorch/utils.py | {
"start": 22350,
"end": 23635
} | class ____(pickle.Unpickler):
"""
Subclass of pickle.Unpickler that intercepts 'torch.storage._load_from_bytes' calls
and uses `torch.load(..., map_location=..., torch_load_kwargs=...)`.
This way, we can use normal pickle when unpickling a skorch net but still benefit
from torch.load to handle the ... | _TorchLoadUnpickler |
python | kamyu104__LeetCode-Solutions | Python/last-stone-weight-ii.py | {
"start": 33,
"end": 329
} | class ____(object):
def lastStoneWeightII(self, stones):
"""
:type stones: List[int]
:rtype: int
"""
dp = {0}
for stone in stones:
dp |= {stone+i for i in dp}
S = sum(stones)
return min(abs(i-(S-i)) for i in dp)
| Solution |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/mariadbconnector.py | {
"start": 2988,
"end": 3778
} | class ____(MySQLExecutionContext):
_lastrowid: Optional[int] = None
def create_server_side_cursor(self) -> DBAPICursor:
return self._dbapi_connection.cursor(buffered=False)
def create_default_cursor(self) -> DBAPICursor:
return self._dbapi_connection.cursor(buffered=True)
def post_exe... | MySQLExecutionContext_mariadbconnector |
python | doocs__leetcode | solution/0300-0399/0325.Maximum Size Subarray Sum Equals k/Solution.py | {
"start": 0,
"end": 317
} | class ____:
def maxSubArrayLen(self, nums: List[int], k: int) -> int:
d = {0: -1}
ans = s = 0
for i, x in enumerate(nums):
s += x
if s - k in d:
ans = max(ans, i - d[s - k])
if s not in d:
d[s] = i
return ans
| Solution |
python | doocs__leetcode | lcp/LCP 39. 无人机方阵/Solution.py | {
"start": 0,
"end": 364
} | class ____:
def minimumSwitchingTimes(
self, source: List[List[int]], target: List[List[int]]
) -> int:
cnt = Counter()
for row in source:
for x in row:
cnt[x] += 1
for row in target:
for x in row:
cnt[x] -= 1
return... | Solution |
python | django__django | tests/queries/tests.py | {
"start": 116747,
"end": 119649
} | class ____(TestCase):
def test_in_query(self):
apple = Food.objects.create(name="apple")
pear = Food.objects.create(name="pear")
lunch = Eaten.objects.create(food=apple, meal="lunch")
dinner = Eaten.objects.create(food=pear, meal="dinner")
self.assertEqual(
set(E... | ToFieldTests |
python | openai__openai-python | src/openai/types/responses/response_input_audio.py | {
"start": 415,
"end": 574
} | class ____(BaseModel):
input_audio: InputAudio
type: Literal["input_audio"]
"""The type of the input item. Always `input_audio`."""
| ResponseInputAudio |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/codeFlow4.py | {
"start": 692,
"end": 1989
} | class ____(Enum):
RED = 1
BLUE = 2
GREEN = 3
PERIWINKLE = 4
def func4(x: Color):
if x == Color.RED:
return
if x == Color.GREEN or (x == Color.PERIWINKLE and True):
y = 2
else:
if x == Color.BLUE:
y = 3
print(y)
def func5():
if True:
y... | Color |
python | mitsuhiko__rye | rye-devtools/src/rye_devtools/find_downloads.py | {
"start": 780,
"end": 946
} | class ____:
implementation: PythonImplementation
@abc.abstractmethod
async def find(self) -> list[PythonDownload]:
raise NotImplementedError
| Finder |
python | encode__django-rest-framework | rest_framework/generics.py | {
"start": 8447,
"end": 8987
} | class ____(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
GenericAPIView):
"""
Concrete view for retrieving, updating a model instance.
"""
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
de... | RetrieveUpdateAPIView |
python | donnemartin__interactive-coding-challenges | graphs_trees/tree_bfs/test_bfs.py | {
"start": 18,
"end": 545
} | class ____(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestBfs, self).__init__()
self.results = Results()
def test_bfs(self):
bst = BstBfs(Node(5))
bst.insert(2)
bst.insert(8)
bst.insert(1)
bst.insert(3)
bst.bfs(self.results.ad... | TestBfs |
python | kamyu104__LeetCode-Solutions | Python/smallest-k-length-subsequence-with-occurrences-of-a-letter.py | {
"start": 29,
"end": 781
} | class ____(object):
def smallestSubsequence(self, s, k, letter, repetition):
"""
:type s: str
:type k: int
:type letter: str
:type repetition: int
:rtype: str
"""
stk = []
suffix = [0]*(len(s)+1)
for i in reversed(xrange(len(suffix)-1))... | Solution |
python | matplotlib__matplotlib | galleries/examples/user_interfaces/embedding_in_wx4_sgskip.py | {
"start": 2229,
"end": 2475
} | class ____(wx.App):
def OnInit(self):
"""Create the main window and insert the custom frame."""
frame = CanvasFrame()
frame.Show(True)
return True
if __name__ == "__main__":
app = App()
app.MainLoop()
| App |
python | numpy__numpy | numpy/lib/tests/test_function_base.py | {
"start": 16037,
"end": 18308
} | class ____:
choices = [np.array([1, 2, 3]),
np.array([4, 5, 6]),
np.array([7, 8, 9])]
conditions = [np.array([False, False, False]),
np.array([False, True, False]),
np.array([False, False, True])]
def _select(self, cond, values, default=0):
... | TestSelect |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_comment08.py | {
"start": 315,
"end": 1154
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("comment08.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with comments."""
workbook = Workboo... | TestCompareXLSXFiles |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/vendorsb/package.py | {
"start": 217,
"end": 589
} | class ____(Package):
"""A package that vendors another, and thus conflicts with it"""
homepage = "http://www.example.com"
url = "http://www.example.com/b-1.0.tar.gz"
version("1.1", md5="0123456789abcdef0123456789abcdef")
version("1.0", md5="0123456789abcdef0123456789abcdef")
# pkg-b is not a ... | Vendorsb |
python | kubernetes-client__python | kubernetes/client/models/v1_host_path_volume_source.py | {
"start": 383,
"end": 4785
} | 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... | V1HostPathVolumeSource |
python | doocs__leetcode | solution/0100-0199/0188.Best Time to Buy and Sell Stock IV/Solution2.py | {
"start": 0,
"end": 489
} | class ____:
def maxProfit(self, k: int, prices: List[int]) -> int:
n = len(prices)
f = [[[0] * 2 for _ in range(k + 1)] for _ in range(n)]
for j in range(1, k + 1):
f[0][j][1] = -prices[0]
for i, x in enumerate(prices[1:], 1):
for j in range(1, k + 1):
... | Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_print_area03.py | {
"start": 315,
"end": 1190
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("print_area03.xlsx")
self.ignore_files = [
"xl/printerSettings/printerSettings1.bin",
"xl/worksheets/_rels/sheet1.xml.re... | TestCompareXLSXFiles |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 85734,
"end": 111436
} | class ____(NonStrictDataModel):
"""
:param id: Task id
:type id: str
:param name: Task Name
:type name: str
:param user: Associated user id
:type user: str
:param company: Company ID
:type company: str
:param type: Type of task. Values: 'dataset_import', 'annotation', 'training',... | Task |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.