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 | keras-team__keras | keras/src/ops/nn.py | {
"start": 52776,
"end": 55218
} | class ____(Operation):
def __init__(self, from_logits=False, *, name=None):
super().__init__(name=name)
self.from_logits = from_logits
def call(self, target, output):
return backend.nn.binary_crossentropy(
target, output, from_logits=self.from_logits
)
def compu... | BinaryCrossentropy |
python | docker__docker-py | docker/types/services.py | {
"start": 226,
"end": 2574
} | class ____(dict):
"""
Describe the task specification to be used when creating or updating a
service.
Args:
container_spec (ContainerSpec): Container settings for containers
started as part of this task.
log_driver (DriverConfig): Log configuration for containers created as
... | TaskTemplate |
python | pypa__setuptools | setuptools/_vendor/jaraco/functools/__init__.py | {
"start": 8022,
"end": 16642
} | class ____:
"""Rate-limit a function (or other callable)."""
def __init__(self, func, max_rate=float('Inf')):
if isinstance(func, Throttler):
func = func.func
self.func = func
self.max_rate = max_rate
self.reset()
def reset(self):
self.last_called = 0
... | Throttler |
python | django__django | django/db/models/deletion.py | {
"start": 277,
"end": 465
} | class ____(IntegrityError):
def __init__(self, msg, protected_objects):
self.protected_objects = protected_objects
super().__init__(msg, protected_objects)
| ProtectedError |
python | walkccc__LeetCode | solutions/1798. Maximum Number of Consecutive Values You Can Make/1798.py | {
"start": 0,
"end": 228
} | class ____:
def getMaximumConsecutive(self, coins: list[int]) -> int:
ans = 1 # the next value we want to make
for coin in sorted(coins):
if coin > ans:
return ans
ans += coin
return ans
| Solution |
python | sympy__sympy | sympy/polys/matrices/exceptions.py | {
"start": 492,
"end": 564
} | class ____(DMError):
"""domains do not match"""
pass
| DMDomainError |
python | kamyu104__LeetCode-Solutions | Python/all-oone-data-structure.py | {
"start": 941,
"end": 3109
} | class ____(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.bucket_of_key = {}
self.buckets = LinkedList()
def inc(self, key):
"""
Inserts a new key <Key> with value 1. Or increments an existing key by 1.
:type key: ... | AllOne |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/links/test_emr.py | {
"start": 9230,
"end": 10340
} | class ____(BaseAwsLinksTestCase):
link_class = EmrServerlessS3LogsLink
def test_extra_link(self, mock_supervisor_comms):
if AIRFLOW_V_3_0_PLUS and mock_supervisor_comms:
mock_supervisor_comms.send.return_value = XComResult(
key=self.link_class.key,
value={
... | TestEmrServerlessS3LogsLink |
python | optuna__optuna | optuna/terminator/erroreval.py | {
"start": 3536,
"end": 4145
} | class ____(BaseErrorEvaluator):
"""An error evaluator that always returns a constant value.
This evaluator can be used to terminate the optimization when the evaluated improvement
potential is below the fixed threshold.
Args:
constant:
A user-specified constant value to always retu... | StaticErrorEvaluator |
python | allegroai__clearml | clearml/backend_api/services/v2_9/queues.py | {
"start": 30449,
"end": 33852
} | class ____(Response):
"""
Response of queues.get_all endpoint.
:param queues: Queues list
:type queues: Sequence[Queue]
"""
_service = "queues"
_action = "get_all"
_version = "2.9"
_schema = {
"definitions": {
"entry": {
"properties": {
... | GetAllResponse |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 140168,
"end": 140922
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
cluster_id: str = Field(
..., description="Canonical identifier for the cluster. This field is required."
)
details: EventDetails = Field(
..., ... | ClusterEvent |
python | explosion__spaCy | website/setup/jinja_to_js.py | {
"start": 2394,
"end": 4061
} | class ____(Exception):
"""
Raised when an {% extends %} is encountered. At this point the parent template is
loaded and all blocks defined in the current template passed to it.
"""
pass
@contextlib.contextmanager
def option(current_kwargs, **kwargs):
"""
Context manager for temporarily se... | ExtendsException |
python | ansible__ansible | lib/ansible/cli/playbook.py | {
"start": 1066,
"end": 10480
} | class ____(CLI):
""" the tool to run *Ansible playbooks*, which are a configuration and multinode deployment system.
See the project home page (https://docs.ansible.com) for more information. """
name = 'ansible-playbook'
USES_CONNECTION = True
def init_parser(self):
# create parser ... | PlaybookCLI |
python | TheAlgorithms__Python | data_structures/linked_list/__init__.py | {
"start": 299,
"end": 431
} | class ____:
def __init__(self, item: Any, next: Any) -> None: # noqa: A002
self.item = item
self.next = next
| Node |
python | lazyprogrammer__machine_learning_examples | rl2/cartpole/dqn_tf.py | {
"start": 1277,
"end": 7001
} | class ____:
def __init__(self, D, K, hidden_layer_sizes, gamma, max_experiences=10000, min_experiences=100, batch_sz=32):
self.K = K
# create the graph
self.layers = []
M1 = D
for M2 in hidden_layer_sizes:
layer = HiddenLayer(M1, M2)
self.layers.append(layer)
M1 = M2
# fina... | DQN |
python | kamyu104__LeetCode-Solutions | Python/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n.py | {
"start": 29,
"end": 551
} | class ____(object):
def getHappyString(self, n, k):
"""
:type n: int
:type k: int
:rtype: str
"""
base = 2**(n-1)
if k > 3*base:
return ""
result = [chr(ord('a')+(k-1)//base)]
while base > 1:
k -= (k-1)//base*base
... | Solution |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 1066432,
"end": 1066891
} | class ____(sgqlc.types.Union):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__types__ = (Enterprise, Organization)
########################################################################
# Schema Entry Points
#################################################################... | VerifiableDomainOwner |
python | tiangolo__fastapi | docs_src/dependencies/tutorial008d.py | {
"start": 71,
"end": 691
} | class ____(Exception):
pass
def get_username():
try:
yield "Rick"
except InternalError:
print("We don't swallow the internal error here, we raise again 😎")
raise
@app.get("/items/{item_id}")
def get_item(item_id: str, username: str = Depends(get_username)):
if item_id == "po... | InternalError |
python | ray-project__ray | rllib/connectors/common/add_time_dim_to_batch_and_zero_pad.py | {
"start": 741,
"end": 12363
} | class ____(ConnectorV2):
"""Adds an extra time dim (axis=1) to all data currently in the batch.
Note: This is one of the default env-to-module or Learner ConnectorV2 pieces that
are added automatically by RLlib into every env-to-module/Learner connector
pipeline, unless `config.add_default_connectors_t... | AddTimeDimToBatchAndZeroPad |
python | google__jax | tests/nn_test.py | {
"start": 3305,
"end": 31473
} | class ____(jtu.JaxTestCase):
@parameterized.product(
contract=[160, 96],
lhs_non_contract=[240, 100],
dtype=[jnp.float16, jnp.bfloat16, jnp.float32],
)
def testScaledMatmul(self, contract, lhs_non_contract, dtype):
if not jtu.is_cuda_compute_capability_at_least("10.0"):
raise unittest.... | NNFunctionsTest |
python | PyCQA__pylint | tests/functional/r/regression/regression_property_no_member_2641.py | {
"start": 168,
"end": 441
} | class ____(metaclass=ABCMeta):
@abstractmethod
def __init__(self, name, age):
self.name = name
self.age = age
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
self.__name = value
| Person |
python | kamyu104__LeetCode-Solutions | Python/peaks-in-array.py | {
"start": 57,
"end": 1790
} | class ____(object):
def countOfPeaks(self, nums, queries):
"""
:type nums: List[int]
:type queries: List[List[int]]
:rtype: List[int]
"""
class BIT(object): # 0-indexed.
def __init__(self, nums):
self.__bit = [0]*(len(nums)+1) # Extra one... | Solution |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/missing_type.py | {
"start": 228,
"end": 499
} | class ____:
def source(self) -> None:
pass
unknown = source # revealed type is `unknown`
def test_unknown_source_def(x: UnknownSourceDef) -> None:
# TODO(T90322028): we don't find the flow here.
y = x.unknown()
_test_sink(y)
| UnknownSourceDef |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/atrous_conv2d_test.py | {
"start": 2226,
"end": 7413
} | class ____(test.TestCase):
@test_util.run_deprecated_v1
def testAtrousConv2DForward(self):
with self.session():
# Input: [batch, height, width, input_depth]
height = 9
for width in [9, 10]: # Test both odd and even width.
x_shape = [2, height, width, 2]
x = np.arange(np.prod(... | AtrousConv2DTest |
python | django__django | tests/flatpages_tests/test_middleware.py | {
"start": 5830,
"end": 8243
} | class ____(TestDataMixin, TestCase):
def test_redirect_view_flatpage(self):
"A flatpage can be served through a view and should add a slash"
response = self.client.get("/flatpage_root/flatpage")
self.assertRedirects(response, "/flatpage_root/flatpage/", status_code=301)
def test_redirec... | FlatpageMiddlewareAppendSlashTests |
python | gevent__gevent | src/greentest/3.9/test_socket.py | {
"start": 198815,
"end": 201321
} | class ____(unittest.TestCase):
class MockSocket(socket.socket):
def connect(self, *args):
raise socket.timeout('timed out')
@contextlib.contextmanager
def mocked_socket_module(self):
"""Return a socket which times out on connect"""
old_socket = socket.socket
soc... | NetworkConnectionNoServer |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/strategies/_internal/recursive.py | {
"start": 2059,
"end": 3784
} | class ____(SearchStrategy):
def __init__(self, base, extend, max_leaves):
super().__init__()
self.max_leaves = max_leaves
self.base = base
self.limited_base = LimitedStrategy(base)
self.extend = extend
strategies = [self.limited_base, self.extend(self.limited_base)]
... | RecursiveStrategy |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/mvdefaults/package.py | {
"start": 216,
"end": 637
} | class ____(Package):
homepage = "http://www.example.com"
url = "http://www.example.com/mvdefaults-1.0.tar.gz"
version("1.0", md5="abcdef1234567890abcdef1234567890")
version("0.9", md5="abcdef1234567890abcdef1234567890")
variant("foo", values=("a", "b", "c"), default=("a", "b", "c"), multi=True, de... | Mvdefaults |
python | apache__avro | lang/py/avro/schema.py | {
"start": 20022,
"end": 21049
} | class ____(FixedSchema, DecimalLogicalSchema):
def __init__(
self,
size,
name,
precision,
scale=0,
namespace=None,
names=None,
other_props=None,
validate_names: bool = True,
):
max_precision = int(math.floor(math.log10(2) * (8 * siz... | FixedDecimalSchema |
python | sympy__sympy | sympy/core/facts.py | {
"start": 17328,
"end": 17479
} | class ____(ValueError):
def __str__(self):
kb, fact, value = self.args
return "%s, %s=%s" % (kb, fact, value)
| InconsistentAssumptions |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/collective_ops_test.py | {
"start": 18384,
"end": 20718
} | class ____(test.TestCase, parameterized.TestCase):
def setUp(self):
_setup_context()
super().setUp()
def testReduce(self, collective_ops, device, communication,
max_subdivs_per_device):
dev0 = '/device:%s:0' % device
dev1 = '/device:%s:1' % device
tokens = {}
for dev in [... | AllReduceWithSubdivisionsTest |
python | ray-project__ray | python/ray/dag/compiled_dag_node.py | {
"start": 12867,
"end": 15138
} | class ____:
"""Wraps the normal Ray DAGNode with some metadata."""
def __init__(self, idx: int, dag_node: "ray.dag.DAGNode"):
"""
Args:
idx: A unique index into the original DAG.
dag_node: The original DAG node created by the user.
"""
self.idx = idx
... | CompiledTask |
python | huggingface__transformers | src/transformers/models/recurrent_gemma/modeling_recurrent_gemma.py | {
"start": 34060,
"end": 38020
} | class ____(RecurrentGemmaPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
def __init__(self, config):
super().__init__(config)
self.model = RecurrentGemmaModel(config)
self.vocab_size = config.vocab_size
self.lm_head = nn.Li... | RecurrentGemmaForCausalLM |
python | yaml__pyyaml | lib/yaml/events.py | {
"start": 2281,
"end": 2335
} | class ____(CollectionEndEvent):
pass
| SequenceEndEvent |
python | pytorch__pytorch | benchmarks/functional_autograd_benchmark/torchaudio_models.py | {
"start": 25344,
"end": 26386
} | class ____(torch.nn.Module):
def __init__(self, query_proj, key_proj, value_proj):
r"""A in-proj container to process inputs.
Args:
query_proj: a proj layer for query.
key_proj: a proj layer for key.
value_proj: a proj layer for value.
"""
super()... | InProjContainer |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/automap.py | {
"start": 51788,
"end": 61724
} | class ____:
__slots__ = ("table_keys",)
table_keys: Set[str]
def automap_base(
declarative_base: Optional[Type[Any]] = None, **kw: Any
) -> Any:
r"""Produce a declarative automap base.
This function produces a new base class that is a product of the
:class:`.AutomapBase` class as well a decl... | _Bookkeeping |
python | falconry__falcon | falcon/media/msgpack.py | {
"start": 3857,
"end": 3952
} | class ____(Protocol):
def __call__(self, data: bytes, raw: bool = ...) -> Any: ...
| UnpackMethod |
python | tiangolo__fastapi | docs_src/response_model/tutorial004_py39.py | {
"start": 104,
"end": 627
} | class ____(BaseModel):
name: str
description: Union[str, None] = None
price: float
tax: float = 10.5
tags: list[str] = []
items = {
"foo": {"name": "Foo", "price": 50.2},
"bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
"baz": {"name": "Baz", "descript... | Item |
python | optuna__optuna | optuna/storages/_cached_storage.py | {
"start": 1251,
"end": 12261
} | class ____(BaseStorage, BaseHeartbeat):
"""A wrapper class of storage backends.
This class is used in :func:`~optuna.get_storage` function and automatically
wraps :class:`~optuna.storages.RDBStorage` class.
:class:`~optuna.storages._CachedStorage` meets the following **Data persistence** requirements.... | _CachedStorage |
python | readthedocs__readthedocs.org | readthedocs/builds/apps.py | {
"start": 211,
"end": 450
} | class ____(AppConfig):
name = "readthedocs.builds"
label = "builds"
verbose_name = _("Builds")
def ready(self):
import readthedocs.builds.tasks # noqa
import readthedocs.builds.signals_receivers # noqa
| Config |
python | numba__numba | numba/tests/test_objects.py | {
"start": 158,
"end": 265
} | class ____(object):
pass
def setattr_usecase(o, v):
o.x = v
def delattr_usecase(o):
del o.x
| C |
python | pytorch__pytorch | test/test_transformers.py | {
"start": 115101,
"end": 207107
} | class ____(NNTestCase):
""" Used to test CUDA only functionality of scaled_dot_product_attention
Quarks:
There is some trickiness with this function. Its runtime behavior
is dependent on the CUDA architecture you are testing it on. See
`PLATFORM_SUPPORTS_FUSED_ATTENTION` at the top of th... | TestSDPACudaOnly |
python | pyparsing__pyparsing | examples/statemachine/statemachine.py | {
"start": 8863,
"end": 11532
} | class ____:
"""An importer designed using the mechanism defined in :pep:`302`. I read
the PEP, and also used Doug Hellmann's PyMOTW article `Modules and
Imports`_, as a pattern.
.. _`Modules and Imports`: http://www.doughellmann.com/PyMOTW/sys/imports.html
Define a subclass that specifies a :attr:... | SuffixImporter |
python | apache__airflow | airflow-ctl/src/airflowctl/ctl/cli_config.py | {
"start": 6172,
"end": 9224
} | class ____(argparse.Action):
"""Custom action to prompt for password input."""
def __call__(self, parser, namespace, values, option_string=None):
if values is None:
values = getpass.getpass()
setattr(namespace, self.dest, values)
# Common Positional Arguments
ARG_FILE = Arg(
f... | Password |
python | Textualize__textual | tests/test_content_switcher.py | {
"start": 214,
"end": 5202
} | class ____(App[None]):
def __init__(self, initial: str | None = None) -> None:
super().__init__()
self._initial = initial
def compose(self) -> ComposeResult:
with ContentSwitcher(initial=self._initial):
for n in range(5):
yield Widget(id=f"w{n}")
async def ... | SwitcherApp |
python | jina-ai__jina | tests/unit/orchestrate/flow/flow-construct/test_flow_yaml_parser.py | {
"start": 4949,
"end": 6038
} | class ____(Executor):
pass
def test_flow_yaml_override_with_protocol():
from jina.enums import ProtocolType
path = os.path.join(
cur_dir.parent.parent.parent, 'yaml/examples/faiss/flow-index.yml'
)
f1 = Flow.load_config(path)
assert f1.protocol == ProtocolType.GRPC
f2 = Flow.load_... | DummyEncoder |
python | pytorch__pytorch | torch/_inductor/codegen/cpp.py | {
"start": 140649,
"end": 150918
} | class ____:
"""
Implement the heuristic to select the tiling factors and tiling indices.
In the future, we can implement advanced heuristic in a subclass.
"""
def select_tiling(
self,
fn_list,
var_sizes_list,
) -> tuple[list[int], list[int]]:
# TODO(jgong5): supp... | TilingSelect |
python | kamyu104__LeetCode-Solutions | Python/regular-expression-matching.py | {
"start": 853,
"end": 1553
} | class ____(object):
# @return a boolean
def isMatch(self, s, p):
result = [[False for j in xrange(len(p) + 1)] for i in xrange(len(s) + 1)]
result[0][0] = True
for i in xrange(2, len(p) + 1):
if p[i-1] == '*':
result[0][i] = result[0][i-2]
for i in x... | Solution2 |
python | getsentry__sentry | tests/sentry/notifications/notification_action/test_issue_alert_registry_handlers.py | {
"start": 17310,
"end": 18716
} | class ____(BaseWorkflowTest):
def setUp(self) -> None:
super().setUp()
self.handler = OpsgenieIssueAlertHandler()
self.detector = self.create_detector(project=self.project)
self.action = self.create_action(
type=Action.Type.OPSGENIE,
integration_id="1234567890... | TestOpsgenieIssueAlertHandler |
python | spyder-ide__spyder | spyder/plugins/profiler/widgets/main_widget.py | {
"start": 1966,
"end": 24025
} | class ____(ShellConnectMainWidget):
"""Profiler widget."""
# PluginMainWidget API
ENABLE_SPINNER = True
SHOW_MESSAGE_WHEN_EMPTY = True
IMAGE_WHEN_EMPTY = "code-profiler"
MESSAGE_WHEN_EMPTY = _("Code not profiled yet")
DESCRIPTION_WHEN_EMPTY = _(
"Profile your code to explore which f... | ProfilerWidget |
python | sympy__sympy | sympy/physics/quantum/tests/test_anticommutator.py | {
"start": 947,
"end": 1304
} | class ____(Operator):
def _eval_anticommutator_Foo(self, foo):
return Integer(1)
def test_eval_commutator():
F = Foo('F')
B = Bar('B')
T = Tam('T')
assert AComm(F, B).doit() == 0
assert AComm(B, F).doit() == 0
assert AComm(F, T).doit() == 1
assert AComm(T, F).doit() == 1
a... | Tam |
python | ray-project__ray | python/ray/llm/tests/serve/cpu/deployments/test_prefix_tree.py | {
"start": 1025,
"end": 4569
} | class ____:
"""Tests for the PrefixTree class initialization and basic tenant management."""
def test_initial_state(self, tree: PrefixTree) -> None:
"""Test the initial state of a new PrefixTree."""
assert tree.tenant_to_char_count == {}
assert tree.tenant_to_lru_tail == {}
asse... | TestPrefixTreeInitialization |
python | kamyu104__LeetCode-Solutions | Python/reconstruct-itinerary.py | {
"start": 960,
"end": 1927
} | class ____(object):
def findItinerary(self, tickets):
"""
:type tickets: List[List[str]]
:rtype: List[str]
"""
def route_helper(origin, ticket_cnt, graph, ans):
if ticket_cnt == 0:
return True
for i, (dest, valid) in enumerate(graph[o... | Solution2 |
python | scipy__scipy | scipy/stats/_multivariate.py | {
"start": 3538,
"end": 6839
} | class ____:
"""
Compute coordinated functions of a symmetric positive semidefinite matrix.
This class addresses two issues. Firstly it allows the pseudoinverse,
the logarithm of the pseudo-determinant, and the rank of the matrix
to be computed using one call to eigh instead of three.
Secondly ... | _PSD |
python | Textualize__textual | src/textual/scrollbar.py | {
"start": 7234,
"end": 13249
} | class ____(Widget):
renderer: ClassVar[Type[ScrollBarRender]] = ScrollBarRender
"""The class used for rendering scrollbars.
This can be overridden and set to a ScrollBarRender-derived class
in order to delegate all scrollbar rendering to that class. E.g.:
```
class MyScrollBarRender(ScrollBarRe... | ScrollBar |
python | facebook__pyre-check | api/connection.py | {
"start": 973,
"end": 1106
} | class ____(NamedTuple):
exit_code: int
errors: Optional[List[str]]
# pyre-ignore[33]: We don't have GADT's yet.
| PyreCheckResult |
python | neetcode-gh__leetcode | python/0347-top-k-frequent-elements.py | {
"start": 0,
"end": 464
} | class ____:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
count = {}
freq = [[] for i in range(len(nums) + 1)]
for n in nums:
count[n] = 1 + count.get(n, 0)
for n, c in count.items():
freq[c].append(n)
res = []
for i in range(... | Solution |
python | getsentry__sentry | src/flagpole/conditions.py | {
"start": 6162,
"end": 7453
} | class ____(ConditionBase):
value: EqualsOperatorValueTypes
operator: str = dataclasses.field(default="not_equals")
def _operator_match(self, condition_property: Any, segment_name: str):
return not self._evaluate_equals(
condition_property=condition_property,
segment_name=seg... | NotEqualsCondition |
python | huggingface__transformers | src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py | {
"start": 29593,
"end": 29675
} | class ____(Qwen2VLCausalLMOutputWithPast):
pass
| Qwen2_5_VLCausalLMOutputWithPast |
python | getsentry__sentry | src/sentry/data_secrecy/types.py | {
"start": 381,
"end": 567
} | class ____(StrEnum):
CACHE_MISS = "cache_miss"
NEGATIVE_CACHE = "negative_cache"
VALID_WINDOW = "valid_window"
EXPIRED_WINDOW = "expired_window"
@dataclass
| GrantCacheStatus |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 165831,
"end": 167052
} | class ____(GeneratedAirbyteSource):
@public
def __init__(
self,
name: str,
token: str,
key: str,
start_date: str,
board_ids: Optional[list[str]] = None,
):
"""Airbyte Source for Trello.
Documentation can be found at https://docs.airbyte.com/in... | TrelloSource |
python | python__mypy | mypy/test/data.py | {
"start": 26955,
"end": 27091
} | class ____(NamedTuple):
lineno: int # 1-offset, inclusive
end_lineno: int # 1-offset, exclusive
lines: list[str]
| DataFileFix |
python | getsentry__sentry | src/sentry/tasks/llm_issue_detection/detection.py | {
"start": 1601,
"end": 1676
} | class ____(BaseModel):
issues: list[DetectedIssue]
| IssueDetectionResponse |
python | tensorflow__tensorflow | tensorflow/compiler/mlir/tensorflow/tests/tf_saved_model/structured_input.py | {
"start": 895,
"end": 5807
} | class ____(tf.Module):
# The fNNNN name prefixes in this file are such that the sorted order of the
# functions in the resulting MLIR output match the order in the source file,
# allowing us to conveniently co-locate the CHECK's with the code they are
# checking.
#
# Note: CHECK-DAG doesn't work with CHECK-... | TestModule |
python | google__pytype | pytype/rewrite/overlays/enum_overlay_test.py | {
"start": 182,
"end": 997
} | class ____(test_utils.ContextfulTestBase):
def test_call(self):
# Simulate:
# class E(enum.Enum):
# X = 42
metaclass = cast(abstract.SimpleClass,
self.ctx.abstract_loader.load_value('enum', 'EnumMeta'))
base = cast(abstract.SimpleClass,
self.ctx.abstract... | EnumMetaNewTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/classes11.py | {
"start": 648,
"end": 735
} | class ____(Mapping[int, int], Sequence[float]): ...
T = TypeVar("T")
S = TypeVar("S")
| F |
python | python__mypy | mypy/metastore.py | {
"start": 4492,
"end": 6598
} | class ____(MetadataStore):
def __init__(self, cache_dir_prefix: str) -> None:
# We check startswith instead of equality because the version
# will have already been appended by the time the cache dir is
# passed here.
if cache_dir_prefix.startswith(os.devnull):
self.db = ... | SqliteMetadataStore |
python | scipy__scipy | scipy/special/tests/test_spherical_bessel.py | {
"start": 5434,
"end": 7313
} | class ____:
def test_spherical_in_exact(self):
# https://dlmf.nist.gov/10.49.E9
x = np.array([0.12, 1.23, 12.34, 123.45])
assert_allclose(spherical_in(2, x),
(1/x + 3/x**3)*sinh(x) - 3/x**2*cosh(x))
def test_spherical_in_recurrence_real(self):
# https://d... | TestSphericalIn |
python | readthedocs__readthedocs.org | readthedocs/doc_builder/exceptions.py | {
"start": 705,
"end": 1112
} | class ____(BuildBaseException):
default_message = _("Build application exception")
GENERIC_WITH_BUILD_ID = "build:app:generic-with-build-id"
UPLOAD_FAILED = "build:app:upload-failed"
BUILDS_DISABLED = "build:app:project-builds-disabled"
BUILD_DOCKER_UNKNOWN_ERROR = "build:app:docker:unknown-error"
... | BuildAppError |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDict23.py | {
"start": 128,
"end": 197
} | class ____(TypedDict):
a: Required[int]
b: NotRequired[str]
| TD1 |
python | walkccc__LeetCode | solutions/1191. K-Concatenation Maximum Sum/1191.py | {
"start": 0,
"end": 695
} | class ____:
def kConcatenationMaxSum(self, arr: list[int], k: int) -> int:
MOD = 1_000_000_007
sz = len(arr) * (1 if k == 1 else 2)
summ = sum(arr)
# The concatenated array will be [arr1, arr2, ..., arrk].
# If sum(arr) > 0 and k > 2, then arr2, ..., arr(k - 1) should be included.
# Equivalent... | Solution |
python | Lightning-AI__lightning | src/lightning/pytorch/utilities/types.py | {
"start": 3509,
"end": 4018
} | class ____(TypedDict):
optimizer: Optimizer
lr_scheduler: Union[LRSchedulerTypeUnion, LRSchedulerConfigType]
monitor: NotRequired[str]
OptimizerLRScheduler = Optional[
Union[
Optimizer,
Sequence[Optimizer],
tuple[Sequence[Optimizer], Sequence[Union[LRSchedulerTypeUnion, LRSched... | OptimizerLRSchedulerConfig |
python | wandb__wandb | tests/unit_tests/test_step_prepare.py | {
"start": 3928,
"end": 7170
} | class ____:
def test_smoke(self):
q = Mock(
get=Mock(
side_effect=[
simple_request_prepare("a"),
simple_request_prepare("b"),
simple_request_prepare("c"),
RequestFinish(),
]
... | TestGatherBatch |
python | django-import-export__django-import-export | tests/core/tests/test_results.py | {
"start": 1159,
"end": 1574
} | class ____(SimpleTestCase):
def test_repr(self):
try:
raise ValidationError(message="invalid row")
except ValidationError as exc:
error = InvalidRow(validation_error=exc, number=1, values={})
self.assertEqual(
repr(error),
"<InvalidRow(row=1, ... | InvalidRowTest |
python | getsentry__sentry | tests/sentry/migrations/test_0002_backfill_insights_team_starred_segments.py | {
"start": 378,
"end": 2087
} | class ____(TestMigrations):
migrate_from = "0001_squashed_0001_add_starred_transactions_model"
migrate_to = "0002_backfill_team_starred"
app = "insights"
def setup_before_migration(self, apps):
self.organization: Organization = self.create_organization(name="test", slug="test")
self.pro... | BackfillUserStarredSegmentsTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/mysqlconnector.py | {
"start": 9855,
"end": 10154
} | class ____(
MariaDBDialect, MySQLDialect_mysqlconnector
):
supports_statement_cache = True
_allows_uuid_binds = False
preparer = MariaDBIdentifierPreparer_mysqlconnector
dialect = MySQLDialect_mysqlconnector
mariadb_dialect = MariaDBDialect_mysqlconnector
| MariaDBDialect_mysqlconnector |
python | Lightning-AI__lightning | tests/tests_pytorch/checkpointing/test_model_checkpoint.py | {
"start": 41253,
"end": 41440
} | class ____(Callback):
def on_train_epoch_end(self, trainer, pl_module):
if trainer.current_epoch == 1:
raise RuntimeError("Trouble!")
| TroubledCallbackOnTrainEpochEnd |
python | walkccc__LeetCode | solutions/2387. Median of a Row Wise Sorted Matrix/2387.py | {
"start": 0,
"end": 367
} | class ____:
def matrixMedian(self, grid: list[list[int]]) -> int:
noGreaterThanMedianCount = len(grid) * len(grid[0]) // 2 + 1
l = 1
r = 1_000_000
while l < r:
m = (l + r) // 2
if (sum(bisect.bisect_right(row, m) for row in grid) >=
noGreaterThanMedianCount):
r = m
... | Solution |
python | google__pytype | pytype/ast/visitor_test.py | {
"start": 365,
"end": 674
} | class ____(visitor.BaseVisitor):
"""Tests visit()'s node replacement functionality."""
def visit_Name(self, node):
if node.id == "x":
return True # should replace
elif node.id == "y":
return False # should replace
else:
return None # should not replace
| _VisitReplaceVisitor |
python | doocs__leetcode | solution/1500-1599/1579.Remove Max Number of Edges to Keep Graph Fully Traversable/Solution.py | {
"start": 0,
"end": 614
} | class ____:
def __init__(self, n):
self.p = list(range(n))
self.size = [1] * n
self.cnt = n
def find(self, x):
if self.p[x] != x:
self.p[x] = self.find(self.p[x])
return self.p[x]
def union(self, a, b):
pa, pb = self.find(a - 1), self.find(b - 1)... | UnionFind |
python | pytorch__pytorch | torch/utils/_cxx_pytree.py | {
"start": 33942,
"end": 34207
} | class ____:
def __repr__(self) -> str:
return "*"
def treespec_pprint(treespec: TreeSpec) -> str:
dummy_tree = tree_unflatten(
[_DummyLeaf() for _ in range(treespec.num_leaves)],
treespec,
)
return repr(dummy_tree)
| _DummyLeaf |
python | allegroai__clearml | clearml/backend_api/services/v2_13/models.py | {
"start": 133152,
"end": 137000
} | class ____(Response):
"""
Response of models.update_for_task endpoint.
:param id: ID of the model
:type id: str
:param created: Was the model created
:type created: bool
:param updated: Number of models updated (0 or 1)
:type updated: int
:param fields: Updated fields names and valu... | UpdateForTaskResponse |
python | cython__cython | Cython/Compiler/TypeSlots.py | {
"start": 21630,
"end": 21940
} | class ____(SlotDescriptor):
# Descriptor for the docstring slot.
def slot_code(self, scope):
doc = scope.doc
if doc is None:
return "0"
if doc.is_unicode:
doc = doc.as_utf8_string()
return "PyDoc_STR(%s)" % doc.as_c_string_literal()
| DocStringSlot |
python | huggingface__transformers | src/transformers/models/vit/image_processing_vit.py | {
"start": 1389,
"end": 14196
} | class ____(BaseImageProcessor):
r"""
Constructs a ViT image processor.
Args:
do_resize (`bool`, *optional*, defaults to `True`):
Whether to resize the image's (height, width) dimensions to the specified `(size["height"],
size["width"])`. Can be overridden by the `do_resize` ... | ViTImageProcessor |
python | numba__numba | numba/tests/npyufunc/test_gufunc.py | {
"start": 11613,
"end": 14666
} | class ____(MemoryLeakMixin, TestCase):
"""
Nothing keeps user from out-of-bound memory access
"""
target = 'cpu'
def test_scalar_output(self):
"""
Note that scalar output is a 0-dimension array that acts as
a pointer to the output location.
"""
@guvectorize(... | TestGUVectorizeScalar |
python | doocs__leetcode | lcof2/剑指 Offer II 003. 前 n 个数字二进制中 1 的个数/Solution.py | {
"start": 0,
"end": 177
} | class ____:
def countBits(self, n: int) -> List[int]:
f = [0] * (n + 1)
for i in range(1, n + 1):
f[i] = f[i & (i - 1)] + 1
return f
| Solution |
python | wandb__wandb | wandb/vendor/pygments/lexers/lisp.py | {
"start": 122449,
"end": 129602
} | class ____(RegexLexer):
"""
Lexer for `Shen <http://shenlanguage.org/>`_ source code.
.. versionadded:: 2.1
"""
name = 'Shen'
aliases = ['shen']
filenames = ['*.shen']
mimetypes = ['text/x-shen', 'application/x-shen']
DECLARATIONS = (
'datatype', 'define', 'defmacro', 'defp... | ShenLexer |
python | getsentry__sentry | tests/sentry/web/frontend/test_project_event.py | {
"start": 210,
"end": 2320
} | class ____(SnubaTestCase, TestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user()
self.login_as(self.user)
self.org = self.create_organization()
self.team = self.create_team(organization=self.org, name="Mariachi Band")
self.create_member(use... | ProjectEventTest |
python | doocs__leetcode | solution/3400-3499/3406.Find the Lexicographically Largest String From the Box II/Solution.py | {
"start": 0,
"end": 608
} | class ____:
def answerString(self, word: str, numFriends: int) -> str:
if numFriends == 1:
return word
s = self.lastSubstring(word)
return s[: len(word) - numFriends + 1]
def lastSubstring(self, s: str) -> str:
i, j, k = 0, 1, 0
while j + k < len(s):
... | Solution |
python | realpython__materials | python-serialize/executable-code/digital-signature/safe_unpickler.py | {
"start": 43,
"end": 630
} | class ____(pickle.Unpickler):
ALLOWED = {
"builtins": ["print"],
"sysconfig": ["get_python_version"],
}
@classmethod
def safe_loads(cls, serialized_data):
file = io.BytesIO(serialized_data)
return cls(file).load()
def find_class(self, module_name, name):
if ... | SafeUnpickler |
python | spack__spack | lib/spack/spack/package_base.py | {
"start": 11069,
"end": 12924
} | class ____(
spack.phase_callbacks.PhaseCallbacksMeta,
DetectablePackageMeta,
spack.directives_meta.DirectiveMeta,
spack.multimethod.MultiMethodMeta,
):
"""
Package metaclass for supporting directives (e.g., depends_on) and phases
"""
def __new__(cls, name, bases, attr_dict):
"""... | PackageMeta |
python | huggingface__transformers | src/transformers/models/diffllama/modeling_diffllama.py | {
"start": 32087,
"end": 35061
} | class ____(DiffLlamaPreTrainedModel, 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):
super().__init__(config)
self.model = Dif... | DiffLlamaForCausalLM |
python | walkccc__LeetCode | solutions/1244. Design A Leaderboard/1244.py | {
"start": 0,
"end": 357
} | class ____:
def __init__(self):
self.idToScore = collections.Counter()
def addScore(self, playerId: int, score: int) -> None:
self.idToScore[playerId] += score
def top(self, K: int) -> int:
return sum(score for _, score in self.idToScore.most_common(K))
def reset(self, playerId: int) -> None:
... | Leaderboard |
python | sqlalchemy__sqlalchemy | examples/adjacency_list/adjacency_list.py | {
"start": 570,
"end": 3338
} | class ____(MappedAsDataclass, Base):
__tablename__ = "tree"
id: Mapped[int] = mapped_column(primary_key=True, init=False)
parent_id: Mapped[Optional[int]] = mapped_column(
ForeignKey("tree.id"), init=False
)
name: Mapped[str]
children: Mapped[Dict[str, TreeNode]] = relationship(
... | TreeNode |
python | run-llama__llama_index | llama-index-integrations/postprocessor/llama-index-postprocessor-colbert-rerank/llama_index/postprocessor/colbert_rerank/base.py | {
"start": 675,
"end": 4796
} | class ____(BaseNodePostprocessor):
model: str = Field(description="Colbert model name.")
top_n: int = Field(description="Number of nodes to return sorted by score.")
device: str = Field(
default="cpu",
description="Device to use for sentence transformer.",
)
keep_retrieval_score: boo... | ColbertRerank |
python | sqlalchemy__sqlalchemy | test/aaa_profiling/test_misc.py | {
"start": 654,
"end": 1672
} | class ____(fixtures.TestBase):
__requires__ = ("cpython", "python_profiling_backend")
def setup_test(self):
class SomeEnum:
# Implements PEP 435 in the minimal fashion needed by SQLAlchemy
_members = {}
@classproperty
def __members__(cls):
... | EnumTest |
python | encode__django-rest-framework | tests/schemas/test_coreapi.py | {
"start": 29351,
"end": 29656
} | class ____(generics.CreateAPIView):
queryset = ForeignKeySource.objects.all()
serializer_class = ForeignKeySourceSerializer
@unittest.skipUnless(coreapi, 'coreapi is not installed')
@override_settings(REST_FRAMEWORK={'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.AutoSchema'})
| ForeignKeySourceView |
python | pytorch__pytorch | torch/_inductor/codegen/wrapper.py | {
"start": 22660,
"end": 24211
} | class ____:
def __init__(self):
from ..memory import estimate_peak_memory, get_freeable_input_buf
scheduler_nodes = V.graph.scheduler.nodes
graph_inputs = OrderedSet(V.graph.graph_inputs.keys())
graph_outputs = OrderedSet(V.graph.get_output_names())
names_to_freeable_bufs = ... | EfficientPeakEstimate |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 952413,
"end": 952893
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of RetireSponsorsTier"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "sponsors_tier")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing t... | RetireSponsorsTierPayload |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/orm/composite_dc.py | {
"start": 268,
"end": 331
} | class ____(DeclarativeBase):
pass
@dataclasses.dataclass
| Base |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.