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 | walkccc__LeetCode | solutions/930. Binary Subarrays With Sum/930-2.py | {
"start": 0,
"end": 517
} | class ____:
def numSubarraysWithSum(self, nums: list[int], goal: int) -> int:
def numSubarraysWithSumAtMost(goal: int) -> int:
res = 0
count = 0
l = 0
r = 0
while r < len(nums):
count += nums[r]
r += 1
while l < r and count > goal:
count -= nums[l]
... | Solution |
python | pypa__warehouse | tests/unit/organizations/test_models.py | {
"start": 3480,
"end": 10803
} | class ____:
def test_customer_name(self, db_session):
organization = DBOrganizationFactory.create(
name="pypi", display_name="The Python Package Index"
)
assert (
organization.customer_name()
== "PyPI Organization - The Python Package Index (pypi)"
... | TestOrganization |
python | ApeWorX__ape | src/ape/api/explorers.py | {
"start": 275,
"end": 2207
} | class ____(BaseInterfaceModel):
"""
An API class representing a blockchain explorer for a particular network
in a particular ecosystem.
"""
name: str # Plugin name
network: NetworkAPI
@abstractmethod
def get_address_url(self, address: "AddressType") -> str:
"""
Get an ... | ExplorerAPI |
python | walkccc__LeetCode | solutions/150. Evaluate Reverse Polish Notation/150.py | {
"start": 0,
"end": 435
} | class ____:
def evalRPN(self, tokens: list[str]) -> int:
stack = []
op = {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
'*': lambda a, b: a * b,
'/': lambda a, b: int(a / b),
}
for token in tokens:
if token in op:
b = stack.pop()
a = stack.po... | Solution |
python | walkccc__LeetCode | solutions/1977. Number of Ways to Separate Numbers/1977.py | {
"start": 0,
"end": 1532
} | class ____:
def numberOfCombinations(self, num: str) -> int:
if num[0] == '0':
return 0
MOD = 1_000_000_007
n = len(num)
# dp[i][k] := the number of possible lists of integers ending in num[i]
# with the length of the last number being 1..k
dp = [[0] * (n + 1) for _ in range(n)]
# l... | Solution |
python | huggingface__transformers | src/transformers/models/owlvit/modeling_owlvit.py | {
"start": 6806,
"end": 9683
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
bounding box loss. The latter is defined as a linear combination of... | OwlViTObjectDetectionOutput |
python | ansible__ansible | packaging/release.py | {
"start": 3036,
"end": 3636
} | class ____(Exception):
"""Results from a failed process."""
def __init__(self, message: str, cmd: tuple[str, ...], status: int, stdout: str | None, stderr: str | None) -> None:
if stdout and (stdout := stdout.strip()):
message += f"\n>>> Standard Output\n{stdout}"
if stderr and (st... | CalledProcessError |
python | google__pytype | pytype/abstract/function.py | {
"start": 23020,
"end": 33296
} | class ____:
"""Represents the parameters of a function call.
Attributes:
posargs: The positional arguments. A tuple of cfg.Variable.
namedargs: The keyword arguments. A dictionary, mapping strings to
cfg.Variable.
starargs: The *args parameter, or None.
starstarargs: The **kwargs parameter, o... | Args |
python | Pylons__pyramid | tests/test_scripts/test_pshell.py | {
"start": 13862,
"end": 14055
} | class ____:
def __init__(self, entry_points):
self._entry_points = entry_points
def entry_points(self):
return DummyEntryPoints(self._entry_points)
| DummyImportlibMetadata |
python | realpython__materials | django-gunicorn-nginx/myapp/apps.py | {
"start": 36,
"end": 142
} | class ____(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "myapp"
| MyappConfig |
python | doocs__leetcode | solution/1200-1299/1274.Number of Ships in a Rectangle/Solution.py | {
"start": 286,
"end": 1088
} | class ____:
def countShips(self, sea: "Sea", topRight: "Point", bottomLeft: "Point") -> int:
def dfs(topRight, bottomLeft):
x1, y1 = bottomLeft.x, bottomLeft.y
x2, y2 = topRight.x, topRight.y
if x1 > x2 or y1 > y2:
return 0
if not sea.hasShips(... | Solution |
python | mozilla__bleach | bleach/_vendor/html5lib/treewalkers/etree_lxml.py | {
"start": 2980,
"end": 6357
} | class ____(base.NonRecursiveTreeWalker):
def __init__(self, tree):
# pylint:disable=redefined-variable-type
if isinstance(tree, list):
self.fragmentChildren = set(tree)
tree = FragmentRoot(tree)
else:
self.fragmentChildren = set()
tree = Root(t... | TreeWalker |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/autograd_cache.py | {
"start": 20784,
"end": 42640
} | class ____(GuardedCache[GenericAOTAutogradResult]):
"""
Caches the results of running AOTAutograd. This class mostly handles the save and load logic, whereas
AOTAutogradResult handles the wrapping/unwrapping logic.
Cache Inputs (AOTAutogradCacheDetails)
- AOTAutogradCache takes in the following inp... | AOTAutogradCache |
python | apache__airflow | providers/apache/spark/tests/unit/apache/spark/hooks/test_spark_jdbc_script.py | {
"start": 1332,
"end": 7454
} | class ____:
jdbc_arguments = [
"-cmdType",
"spark_to_jdbc",
"-url",
"jdbc:postgresql://localhost:5432/default",
"-user",
"user",
"-password",
"supersecret",
"-metastoreTable",
"hiveMcHiveFace",
"-jdbcTable",
"tableMcTabl... | TestSparkJDBCScrip |
python | tiangolo__fastapi | docs_src/header_param_models/tutorial003_py310.py | {
"start": 86,
"end": 377
} | class ____(BaseModel):
host: str
save_data: bool
if_modified_since: str | None = None
traceparent: str | None = None
x_tag: list[str] = []
@app.get("/items/")
async def read_items(headers: CommonHeaders = Header(convert_underscores=False)):
return headers
| CommonHeaders |
python | falconry__falcon | tests/test_middleware.py | {
"start": 302,
"end": 529
} | class ____:
def process_response(self, req, resp, resource, req_succeeded):
self.req = req
self.resp = resp
self.resource = resource
self.req_succeeded = req_succeeded
| CaptureResponseMiddleware |
python | numba__numba | numba/tests/test_gdb_bindings.py | {
"start": 7737,
"end": 8317
} | class ____(TestCase):
def test_call_gdb(self):
def nop_compiler(x):
return x
for compiler in [nop_compiler, jit(forceobj=True), njit]:
for meth in [gdb, gdb_init]:
def python_func():
meth()
with self.assertRaises(errors.Typ... | TestGdbExceptions |
python | google__flatbuffers | tests/py_test.py | {
"start": 5193,
"end": 13736
} | class ____(unittest.TestCase):
"""Tests the generated object based API."""
def test_consistency_with_repeated_pack_and_unpack(self):
"""Checks the serialization and deserialization between a buffer and
its python object. It tests in the same way as the C++ object API test,
ObjectFlatBuffersTest in tes... | TestObjectBasedAPI |
python | huggingface__transformers | src/transformers/pipelines/text_classification.py | {
"start": 591,
"end": 1638
} | class ____(ExplicitEnum):
SIGMOID = "sigmoid"
SOFTMAX = "softmax"
NONE = "none"
@add_end_docstrings(
build_pipeline_init_args(has_tokenizer=True),
r"""
return_all_scores (`bool`, *optional*, defaults to `False`):
Whether to return all prediction scores or just the one of the pr... | ClassificationFunction |
python | pypa__pip | src/pip/_vendor/pygments/formatters/__init__.py | {
"start": 4847,
"end": 5385
} | class ____(types.ModuleType):
"""Automatically import formatters."""
def __getattr__(self, name):
info = FORMATTERS.get(name)
if info:
_load_formatters(info[0])
cls = _formatter_cache[info[1]]
setattr(self, name, cls)
return cls
raise Attr... | _automodule |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 96067,
"end": 96520
} | class ____(str, Enum):
"""
* `majority` - send N/2+1 random request and return points, which present on all of them * `quorum` - send requests to all nodes and return points which present on majority of nodes * `all` - send requests to all nodes and return points which present on all nodes
"""
def __... | ReadConsistencyType |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/recursiveTypeAlias16.py | {
"start": 213,
"end": 315
} | class ____(Generic[T]):
pass
TA1 = A["TA2[U]"] | B["TA2[U]"]
TA2 = TA1[U] | C[TA1[U]]
TA3 = TA2[U]
| C |
python | simonw__datasette | datasette/filters.py | {
"start": 6627,
"end": 6949
} | class ____:
def __init__(
self, where_clauses, params=None, human_descriptions=None, extra_context=None
):
self.where_clauses = where_clauses
self.params = params or {}
self.human_descriptions = human_descriptions or []
self.extra_context = extra_context or {}
| FilterArguments |
python | PyCQA__pylint | tests/functional/u/unused/unused_private_member.py | {
"start": 3603,
"end": 4506
} | class ____:
# pylint: disable=protected-access, no-member, unreachable
def __new__(cls, func, *args):
if args:
true_obj = super(FalsePositive4668, cls).__new__(cls)
true_obj.func = func
true_obj.__args = args # Do not emit message here
return true_obj
... | FalsePositive4668 |
python | tiangolo__fastapi | fastapi/openapi/models.py | {
"start": 2557,
"end": 2726
} | class ____(BaseModelWithConfig):
enum: Annotated[Optional[List[str]], Field(min_length=1)] = None
default: str
description: Optional[str] = None
| ServerVariable |
python | getsentry__sentry | src/sentry/integrations/messaging/linkage.py | {
"start": 11391,
"end": 12880
} | class ____(IdentityLinkageView, ABC):
@property
def confirmation_template(self) -> str:
return "sentry/auth-unlink-identity.html"
@property
def no_identity_template(self) -> str | None:
"""Optional page to show if identities were not found."""
return None
@property
def ... | UnlinkIdentityView |
python | sqlalchemy__sqlalchemy | test/orm/test_backref_mutations.py | {
"start": 16745,
"end": 18110
} | class ____(_fixtures.FixtureTest):
run_inserts = None
@classmethod
def setup_mappers(cls):
Address, addresses, users, User = (
cls.classes.Address,
cls.tables.addresses,
cls.tables.users,
cls.classes.User,
)
cls.mapper_registry.map_im... | O2OScalarOrphanTest |
python | networkx__networkx | networkx/generators/tests/test_atlas.py | {
"start": 229,
"end": 698
} | class ____:
"""Unit tests for the :func:`~networkx.graph_atlas` function."""
def test_index_too_small(self):
with pytest.raises(ValueError):
graph_atlas(-1)
def test_index_too_large(self):
with pytest.raises(ValueError):
graph_atlas(NUM_GRAPHS)
def test_graph(s... | TestAtlasGraph |
python | tensorflow__tensorflow | tensorflow/python/tools/api/generator2/extractor/extractor_test.py | {
"start": 2746,
"end": 7114
} | class ____(): # 14
pass # 15
@api_export.tf_export("e", "e_v2", v1=[]) # 16
def _e(): # 17
pass # 18
tf_export(v1=["f", "f_alias"])( # 19
dispatch.dispatch(deprecation(_f)) # 20
) # 21
@other_export("not-exported") # 22
def _not_exported(): # 23
pass # 24
""",
)
self.assertEqual(
... | _D |
python | kamyu104__LeetCode-Solutions | Python/number-of-divisible-triplet-sums.py | {
"start": 591,
"end": 1089
} | class ____(object):
def divisibleTripletCount(self, nums, d):
"""
:type nums: List[int]
:type d: int
:rtype: int
"""
result = 0
cnt = collections.Counter()
for i in xrange(len(nums)):
if nums[i]%d in cnt:
result += cnt[nums[... | Solution2 |
python | python-pillow__Pillow | Tests/test_image_resample.py | {
"start": 10004,
"end": 14223
} | class ____:
def make_levels_case(self, mode: str) -> Image.Image:
i = Image.new(mode, (256, 16))
px = i.load()
assert px is not None
for y in range(i.size[1]):
for x in range(i.size[0]):
pix = [x] * len(mode)
pix[-1] = 255 - y * 16
... | TestCoreResampleAlphaCorrect |
python | walkccc__LeetCode | solutions/1243. Array Transformation/1243.py | {
"start": 0,
"end": 358
} | class ____:
def transformArray(self, arr: list[int]) -> list[int]:
if len(arr) < 3:
return arr
ans = []
while ans != arr:
ans = arr[:]
for i in range(1, len(arr) - 1):
if ans[i - 1] > ans[i] < ans[i + 1]:
arr[i] += 1
elif ans[i - 1] < ans[i] > ans[i + 1]:
... | Solution |
python | getsentry__sentry | tests/sentry/tasks/test_llm_issue_detection.py | {
"start": 10693,
"end": 13564
} | class ____(APITransactionTestCase, SnubaTestCase, SpanTestCase):
def setUp(self) -> None:
super().setUp()
self.ten_mins_ago = before_now(minutes=10)
def test_get_evidence_trace_for_llm_detection(self) -> None:
transaction_name = "api/users/profile"
# Create multiple traces with... | TestGetEvidenceTraceForLLMDetection |
python | realpython__materials | python-selenium/src/bandcamp/web/locators.py | {
"start": 370,
"end": 653
} | class ____:
PLAY_BUTTON = (By.CSS_SELECTOR, "button.play-pause-button")
URL = (By.CSS_SELECTOR, "div.meta p a")
ALBUM = (By.CSS_SELECTOR, "div.meta p a strong")
GENRE = (By.CSS_SELECTOR, "div.meta p.genre")
ARTIST = (By.CSS_SELECTOR, "div.meta p a span")
| TrackLocator |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/embedding_ops_test.py | {
"start": 27853,
"end": 39957
} | class ____(test.TestCase, parameterized.TestCase):
def _RandomIdsAndWeights(self, batch_size, vocab_size, ragged=False):
max_val_per_entry = 6
vals_per_batch_entry = np.random.randint(
1, max_val_per_entry, size=batch_size)
num_vals = np.sum(vals_per_batch_entry)
ids = np.random.randint(voca... | EmbeddingLookupSparseTest |
python | readthedocs__readthedocs.org | readthedocs/builds/migrations/0047_build_default_triggered.py | {
"start": 149,
"end": 979
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("builds", "0046_identifier_null"),
]
operations = [
migrations.AlterField(
model_name="build",
name="state",
field=models.CharField(
choices=[
... | Migration |
python | doocs__leetcode | solution/1300-1399/1374.Generate a String With Characters That Have Odd Counts/Solution.py | {
"start": 0,
"end": 121
} | class ____:
def generateTheString(self, n: int) -> str:
return 'a' * n if n & 1 else 'a' * (n - 1) + 'b'
| Solution |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 186116,
"end": 188354
} | class ____(Request):
"""
Delete models from task
:param task: ID of the task
:type task: str
:param models: The list of models to delete
:type models: Sequence[dict]
"""
_service = "tasks"
_action = "delete_models"
_version = "2.20"
_schema = {
"definitions": {"mode... | DeleteModelsRequest |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/fastapi/FAST001.py | {
"start": 141,
"end": 2421
} | class ____(BaseModel):
name: str
# Errors
@app.post("/items/", response_model=Item)
async def create_item(item: Item) -> Item:
return item
@app.post("/items/", response_model=list[Item])
async def create_item(item: Item) -> list[Item]:
return item
@app.post("/items/", response_model=List[Item])
asyn... | Item |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/streams/streams.py | {
"start": 13471,
"end": 13637
} | class ____(AdsInsights):
breakdowns = ["publisher_platform", "device_platform"]
action_breakdowns = ["action_type"]
| AdsInsightsDeliveryPlatformAndDevicePlatform |
python | tensorflow__tensorflow | tensorflow/lite/testing/generate_examples_lib.py | {
"start": 14881,
"end": 15902
} | class ____:
"""State of multiple set generation process.
This state class stores the information needed when generating the examples
for multiple test set. The stored informations are open archive object to be
shared, information on test target for current iteration of generation,
accumulated generation resu... | MultiGenState |
python | PyCQA__pylint | tests/functional/m/membership_protocol.py | {
"start": 987,
"end": 1270
} | class ____:
def __getitem__(self, key):
if key < 10:
return 2 ** key
else:
raise IndexError("bad index")
64 in OldStyleIterable()
# do not emit warning if class has unknown bases
from some_missing_module import ImportedClass
| OldStyleIterable |
python | pytorch__pytorch | torch/backends/_nnapi/serializer.py | {
"start": 3626,
"end": 3903
} | class ____(NamedTuple):
"""Configuration arguments for a convolution."""
kernel_h: int
kernel_w: int
stride_h: int
stride_w: int
pad_t: int
pad_b: int
pad_l: int
pad_r: int
dilation_h: int
dilation_w: int
group: int
| ConvPoolArgs2d |
python | sanic-org__sanic | guide/webapp/display/page/page.py | {
"start": 772,
"end": 5170
} | class ____:
path: Path
content: str
meta: PageMeta = field(default_factory=PageMeta)
_relative_path: Path | None = None
next_page: Page | None = None
previous_page: Page | None = None
anchors: list[str] = field(default_factory=list)
DEFAULT_LANGUAGE = _DEFAULT
def get_layout(self) ... | Page |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1158807,
"end": 1162146
} | class ____(sgqlc.types.Type, Node):
"""An identity provider configured to provision identities for an
enterprise. Visible to enterprise owners or enterprise owners'
personal access tokens (classic) with read:enterprise or
admin:enterprise scope.
"""
__schema__ = github_schema
__field_names_... | EnterpriseIdentityProvider |
python | pytorch__pytorch | torch/_inductor/shape_propagation.py | {
"start": 232,
"end": 2241
} | class ____(Protocol):
@property
def shape(self) -> BlockShapeType: ...
ShapeArg = Union[ShapeVar, torch.types.Number, str, OpsValue, torch.dtype]
# Inputs need to be cacheable (e.g., not a CSEVar) in order for the cache to be effective
# So first decompose CSEVars -> tuple before calling this
@functools.lr... | ShapeVar |
python | walkccc__LeetCode | solutions/407. Trapping Rain Water II/407.py | {
"start": 0,
"end": 1111
} | class ____:
def trapRainWater(self, heightMap: list[list[int]]) -> int:
DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))
m = len(heightMap)
n = len(heightMap[0])
ans = 0
minHeap = []
seen = set()
for i in range(m):
heapq.heappush(minHeap, (heightMap[i][0], i, 0))
heapq.heappush(minHe... | Solution |
python | kamyu104__LeetCode-Solutions | Python/closest-node-to-path-in-tree.py | {
"start": 6115,
"end": 7194
} | class ____(object): # Time: O(N), Space: O(N), N is the number of nodes
def __init__(self, children): # modified
def preprocess(curr, parent):
# depth of the node i
D[curr] = 1 if parent == -1 else D[parent]+1
# ancestors of the node i
P[curr] = parent
... | TreeInfos3 |
python | python-markdown__markdown | markdown/extensions/fenced_code.py | {
"start": 1642,
"end": 8300
} | class ____(Preprocessor):
""" Find and extract fenced code blocks. """
FENCED_BLOCK_RE = re.compile(
dedent(r'''
(?P<fence>^(?:~{3,}|`{3,}))[ ]* # opening fence
((\{(?P<attrs>[^\n]*)\})| # (optional {attrs} or
(... | FencedBlockPreprocessor |
python | google__flatbuffers | tests/py_flexbuffers_test.py | {
"start": 8749,
"end": 36735
} | class ____(unittest.TestCase):
"""Tests to check FlexBuffer decoding functions.
Common variable names used in the tests for compactness:
bw: byte_width
ebw: element_byte_width
kbw: key_byte_width
vbw: value_byte_width
tbw: type_byte_width
Having '_ignored' suffix means that variable doesn't ... | DecoderTest |
python | pytest-dev__pytest-xdist | src/xdist/workermanage.py | {
"start": 950,
"end": 7402
} | class ____:
EXIT_TIMEOUT = 10
DEFAULT_IGNORES = [".*", "*.pyc", "*.pyo", "*~"]
def __init__(
self,
config: pytest.Config,
specs: Sequence[execnet.XSpec | str] | None = None,
defaultchdir: str = "pyexecnetcache",
) -> None:
self.config = config
self.trace ... | NodeManager |
python | sympy__sympy | sympy/physics/quantum/gate.py | {
"start": 25805,
"end": 26743
} | class ____(OneQubitGate):
"""The single qubit pi/8 gate.
This gate rotates the phase of the state by pi/4 if the state is ``|1>`` and
does nothing if the state is ``|0>``.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
"""
... | TGate |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/choose_from_datasets_test.py | {
"start": 6136,
"end": 7515
} | class ____(checkpoint_test_base.CheckpointTestBase,
parameterized.TestCase):
def _build_dataset(self,
num_datasets,
num_elements_per_dataset,
options=None):
datasets = [
dataset_ops.Dataset.range(num_ele... | ChooseFromDatasetsCheckpointTest |
python | spyder-ide__spyder | spyder/api/widgets/comboboxes.py | {
"start": 1247,
"end": 2410
} | class ____(QStyledItemDelegate):
"""
Delegate to make separators color follow our theme.
Adapted from https://stackoverflow.com/a/33464045/438386
"""
def __init__(self, parent, elide_mode=None):
super().__init__(parent)
self._elide_mode = elide_mode
def paint(self, painter, op... | _SpyderComboBoxDelegate |
python | huggingface__transformers | tests/utils/test_generic.py | {
"start": 5707,
"end": 8104
} | class ____(unittest.TestCase):
def test_cases_no_warning(self):
with warnings.catch_warnings(record=True) as raised_warnings:
warnings.simplefilter("always")
# basic test
@filter_out_non_signature_kwargs()
def func1(a):
return a
r... | ValidationDecoratorTester |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_north_dakota_zip.py | {
"start": 767,
"end": 1782
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_north_dakota_zip"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _... | ColumnValuesToBeValidNorthDakotaZip |
python | doocs__leetcode | solution/0100-0199/0137.Single Number II/Solution.py | {
"start": 0,
"end": 325
} | class ____:
def singleNumber(self, nums: List[int]) -> int:
ans = 0
for i in range(32):
cnt = sum(num >> i & 1 for num in nums)
if cnt % 3:
if i == 31:
ans -= 1 << i
else:
ans |= 1 << i
return ans... | Solution |
python | wandb__wandb | wandb/sdk/artifacts/_generated/artifact_collection_membership_files.py | {
"start": 1569,
"end": 2191
} | class ____(
GQLResult
):
node: Optional[FileFragment]
ArtifactCollectionMembershipFiles.model_rebuild()
ArtifactCollectionMembershipFilesProject.model_rebuild()
ArtifactCollectionMembershipFilesProjectArtifactCollection.model_rebuild()
ArtifactCollectionMembershipFilesProjectArtifactCollectionArtifactMembersh... | ArtifactCollectionMembershipFilesProjectArtifactCollectionArtifactMembershipFilesEdges |
python | django-compressor__django-compressor | compressor/tests/test_templatetags.py | {
"start": 719,
"end": 7873
} | class ____(TestCase):
def setUp(self):
self.context = {"STATIC_URL": settings.COMPRESS_URL}
def test_empty_tag(self):
template = """{% load compress %}{% compress js %}{% block js %}
{% endblock %}{% endcompress %}"""
self.assertEqual("", render(template, self.context))
def... | TemplatetagTestCase |
python | explosion__spaCy | spacy/lang/uk/lemmatizer.py | {
"start": 195,
"end": 1716
} | class ____(RussianLemmatizer):
def __init__(
self,
vocab: Vocab,
model: Optional[Model],
name: str = "lemmatizer",
*,
mode: str = "pymorphy3",
overwrite: bool = False,
scorer: Optional[Callable] = lemmatizer_score,
) -> None:
if mode in {"p... | UkrainianLemmatizer |
python | getsentry__sentry | src/sentry/sentry_apps/services/app_request/model.py | {
"start": 184,
"end": 525
} | class ____(RpcModel):
date: str
response_code: int
webhook_url: str
organization_id: int | None
event_type: str
error_id: str | None = None
project_id: int | None = None
request_body: str | None = None
request_headers: Mapping[str, str] | None = None
response_body: str | None = N... | RpcSentryAppRequest |
python | streamlit__streamlit | lib/tests/streamlit/connections/snowflake_connection_test.py | {
"start": 1199,
"end": 8533
} | class ____(unittest.TestCase):
def tearDown(self) -> None:
st.cache_data.clear()
@patch(
"snowflake.snowpark.context.get_active_session",
)
@patch(
"streamlit.connections.snowflake_connection.running_in_sis",
MagicMock(return_value=True),
)
def test_uses_active_s... | SnowflakeConnectionTest |
python | scikit-learn__scikit-learn | asv_benchmarks/benchmarks/ensemble.py | {
"start": 358,
"end": 1365
} | class ____(Predictor, Estimator, Benchmark):
"""
Benchmarks for RandomForestClassifier.
"""
param_names = ["representation", "n_jobs"]
params = (["dense", "sparse"], Benchmark.n_jobs_vals)
def setup_cache(self):
super().setup_cache()
def make_data(self, params):
representa... | RandomForestClassifierBenchmark |
python | kamyu104__LeetCode-Solutions | Python/make-two-arrays-equal-by-reversing-sub-arrays.py | {
"start": 324,
"end": 557
} | class ____(object):
def canBeEqual(self, target, arr):
"""
:type target: List[int]
:type arr: List[int]
:rtype: bool
"""
target.sort(), arr.sort()
return target == arr
| Solution2 |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 78751,
"end": 78854
} | class ____:
xlDownThenOver = 1 # from enum XlOrder
xlOverThenDown = 2 # from enum XlOrder
| Order |
python | getsentry__sentry | src/sentry/notifications/api/endpoints/user_notification_settings_options.py | {
"start": 839,
"end": 2842
} | class ____(UserEndpoint):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
"PUT": ApiPublishStatus.PRIVATE,
}
owner = ApiOwner.ALERTS_NOTIFICATIONS
def get(self, request: Request, user: User) -> Response:
"""
Retrieve the notification preferences for a user.
R... | UserNotificationSettingsOptionsEndpoint |
python | huggingface__transformers | src/transformers/models/colpali/processing_colpali.py | {
"start": 1547,
"end": 2775
} | class ____(ProcessingKwargs, total=False):
_defaults = {
"text_kwargs": {
"padding": "longest",
},
"images_kwargs": {
"data_format": "channels_first",
"do_convert_rgb": True,
},
"common_kwargs": {"return_tensors": "pt"},
}
IMAGE_TOKEN... | ColPaliProcessorKwargs |
python | ray-project__ray | python/ray/tune/tests/test_tuner.py | {
"start": 2648,
"end": 17997
} | class ____(unittest.TestCase):
"""The e2e test for hparam tuning using Tuner API."""
@pytest.fixture(autouse=True)
def tmp_path(self, tmp_path):
self.tmp_path = tmp_path
def setUp(self):
ray.init()
def tearDown(self):
ray.shutdown()
def test_tuner_with_xgboost_trainer... | TunerTest |
python | apache__airflow | devel-common/src/sphinx_exts/operators_and_hooks_ref.py | {
"start": 15604,
"end": 15987
} | class ____(BaseJinjaReferenceDirective):
"""Generate list of logging handlers"""
def render_content(
self, *, tags: set[str] | None, header_separator: str = DEFAULT_HEADER_SEPARATOR
) -> str:
return _common_render_list_content(
header_separator=header_separator, resource_type="l... | LoggingDirective |
python | fastapi__sqlmodel | docs_src/tutorial/fastapi/relationships/tutorial001.py | {
"start": 179,
"end": 263
} | class ____(SQLModel):
name: str = Field(index=True)
headquarters: str
| TeamBase |
python | fastapi__sqlmodel | docs_src/tutorial/indexes/tutorial001.py | {
"start": 100,
"end": 1219
} | 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)
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_u... | Hero |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 128834,
"end": 129121
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
repair_history: Optional[List[RepairHistoryItem]] = Field(
None, description="The repair history of the run."
)
| RepairHistory |
python | getsentry__sentry | src/sentry/sentry_metrics/indexer/limiters/writes.py | {
"start": 3039,
"end": 7700
} | class ____:
def __init__(self, namespace: str, **options: Mapping[str, str]) -> None:
self.namespace = namespace
self.rate_limiter: RedisSlidingWindowRateLimiter = RedisSlidingWindowRateLimiter(**options)
def _build_quota_key(self, use_case_id: UseCaseID, org_id: OrgId | None = None) -> str:
... | WritesLimiter |
python | mwaskom__seaborn | doc/sphinxext/gallery_generator.py | {
"start": 3296,
"end": 10739
} | class ____:
"""Tools for generating an example page from a file"""
def __init__(self, filename, target_dir):
self.filename = filename
self.target_dir = target_dir
self.thumbloc = .5, .5
self.extract_docstring()
with open(filename) as fid:
self.filetext = fid.r... | ExampleGenerator |
python | huggingface__transformers | src/transformers/models/mra/configuration_mra.py | {
"start": 780,
"end": 6240
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`MraModel`]. It is used to instantiate an MRA
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuratio... | MraConfig |
python | pytorch__pytorch | torch/ao/nn/quantized/modules/functional_modules.py | {
"start": 4551,
"end": 9222
} | class ____(torch.nn.Module):
r"""Wrapper class for quantized operations.
The instance of this class can be used instead of the
``torch.ops.quantized`` prefix. See example usage below.
.. note::
This class does not provide a ``forward`` hook. Instead, you must use
one of the underlying... | QFunctional |
python | getsentry__sentry | src/sentry/api/serializers/models/team.py | {
"start": 11988,
"end": 12063
} | class ____(TypedDict):
value: str
display: str
| SCIMTeamMemberListItem |
python | apache__airflow | providers/fab/src/airflow/providers/fab/www/extensions/init_views.py | {
"start": 2370,
"end": 2924
} | class ____(Resolver):
"""
OpenAPI endpoint resolver that loads lazily on first use.
This re-implements ``connexion.Resolver.resolve()`` to not eagerly resolve
the endpoint function (and thus avoid importing it in the process), but only
return a placeholder that will be actually resolved when the co... | _LazyResolver |
python | great-expectations__great_expectations | tests/expectations/test_conditions.py | {
"start": 12604,
"end": 19395
} | class ____:
"""Tests for deserialization (converting dicts back to Condition objects)."""
def test_deserialize_comparison_condition(self):
"""Test deserializing a ComparisonCondition from a dict."""
cond_dict = {
"type": "comparison",
"column": {"name": "age"},
... | TestConditionDeserialization |
python | dask__dask | dask/tests/test_task_spec.py | {
"start": 17946,
"end": 18368
} | class ____:
def __getstate__(self):
return "Nope"
def __setstate__(self, state):
raise ValueError(state)
def __call__(self):
return 1
# This is duplicated from distributed/utils_test.py
def _get_gc_overhead():
class _CustomObject:
def __sizeof__(self):
ret... | RaiseOnDeSerialization |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 370577,
"end": 380931
} | class ____:
def setup_method(self):
self.rng = np.random.default_rng(1808365978)
# expected statistic and p-values generated using R at
# https://rdrr.io/cran/cultevo/, e.g.
# library(cultevo)
# data = rbind(c(72, 47, 73, 35, 47, 96, 30, 59, 41, 36, 56, 49, 81, 43,
# 7... | TestPageTrendTest |
python | ray-project__ray | python/ray/dashboard/modules/metrics/dashboards/common.py | {
"start": 11708,
"end": 11966
} | class ____(Enum):
GRAPH = GRAPH_PANEL_TEMPLATE
HEATMAP = HEATMAP_TEMPLATE
PIE_CHART = PIE_CHART_TEMPLATE
STAT = STAT_PANEL_TEMPLATE
GAUGE = GAUGE_PANEL_TEMPLATE
BAR_CHART = BAR_CHART_PANEL_TEMPLATE
@DeveloperAPI
@dataclass
| PanelTemplate |
python | google__flatbuffers | grpc/examples/python/greeter/models/HelloRequest.py | {
"start": 175,
"end": 1372
} | class ____(object):
__slots__ = ['_tab']
@classmethod
def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = HelloRequest()
x.Init(buf, n + offset)
return x
@classmethod
def GetRootAsHelloRequest(cls, buf, offset=0... | HelloRequest |
python | huggingface__transformers | src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py | {
"start": 27860,
"end": 31734
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
embed_dim = config.hidden_size
dropout = config.adaptor_dropout
self.kernel_size = config.adaptor_kernel_size
self.stride = config.adaptor_stride
# 1. residual convolution
self.residual_la... | SeamlessM4Tv2ConformerAdapterLayer |
python | walkccc__LeetCode | solutions/2042. Check if Numbers Are Ascending in a Sentence/2042.py | {
"start": 0,
"end": 241
} | class ____:
def areNumbersAscending(self, s: str) -> bool:
prev = 0
for token in s.split():
if token.isdigit():
num = int(token)
if num <= prev:
return False
prev = num
return True
| Solution |
python | pytorch__pytorch | test/distributed/test_composability.py | {
"start": 1155,
"end": 1896
} | class ____(torch.nn.Module):
def __init__(self, d_hid: int):
super().__init__()
self.net1 = torch.nn.Linear(d_hid, d_hid)
self.relu = torch.nn.ReLU()
self.net2 = torch.nn.Linear(d_hid, d_hid)
self.init_weights()
def init_weights(self):
# ensure a proper init othe... | MLPModule |
python | sympy__sympy | sympy/physics/optics/gaussopt.py | {
"start": 6556,
"end": 6920
} | class ____(RayTransferMatrix):
"""
Ray Transfer Matrix for reflection.
See Also
========
RayTransferMatrix
Examples
========
>>> from sympy.physics.optics import FlatMirror
>>> FlatMirror()
Matrix([
[1, 0],
[0, 1]])
"""
def __new__(cls):
return RayTran... | FlatMirror |
python | pypa__pip | src/pip/_vendor/urllib3/util/url.py | {
"start": 3003,
"end": 14296
} | class ____(namedtuple("Url", url_attrs)):
"""
Data structure for representing an HTTP URL. Used as a return value for
:func:`parse_url`. Both the scheme and host are normalized as they are
both case-insensitive according to RFC 3986.
"""
__slots__ = ()
def __new__(
cls,
sch... | Url |
python | arrow-py__arrow | tests/test_parser.py | {
"start": 58763,
"end": 61283
} | class ____:
def test_parse_search(self):
assert self.parser.parse(
"Today is 25 of September of 2003", "DD of MMMM of YYYY"
) == datetime(2003, 9, 25)
def test_parse_search_with_numbers(self):
assert self.parser.parse(
"2000 people met the 2012-01-01 12:05:10", "... | TestDateTimeParserSearchDate |
python | langchain-ai__langchain | libs/langchain/langchain_classic/retrievers/ensemble.py | {
"start": 1413,
"end": 10863
} | class ____(BaseRetriever):
"""Retriever that ensembles the multiple retrievers.
It uses a rank fusion.
Args:
retrievers: A list of retrievers to ensemble.
weights: A list of weights corresponding to the retrievers. Defaults to equal
weighting for all retrievers.
c: A co... | EnsembleRetriever |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/selectable.py | {
"start": 35407,
"end": 36707
} | class ____(FromClause):
"""A :class:`.FromClause` that has a name.
Examples include tables, subqueries, CTEs, aliased tables.
.. versionadded:: 2.0
"""
named_with_column = True
name: str
@util.preload_module("sqlalchemy.sql.sqltypes")
def table_valued(self) -> TableValuedColumn[Any... | NamedFromClause |
python | pytorch__pytorch | torch/_inductor/graph.py | {
"start": 9533,
"end": 107259
} | class ____(torch.fx.Interpreter):
graph_outputs: list[ir.IRNode]
def __init__(
self,
gm: torch.fx.GraphModule,
example_inputs: Optional[Sequence[object]] = None,
shape_env: Optional[ShapeEnv] = None,
graph_id: Optional[int] = None,
cpp_wrapper: bool = False,
... | GraphLowering |
python | pytest-dev__pytest | src/_pytest/mark/expression.py | {
"start": 8049,
"end": 9041
} | class ____(Protocol):
"""A callable which, given an identifier and optional kwargs, should return
whether it matches in an :class:`Expression` evaluation.
Should be prepared to handle arbitrary strings as input.
If no kwargs are provided, the expression of the form `foo`.
If kwargs are provided, t... | ExpressionMatcher |
python | walkccc__LeetCode | solutions/1409. Queries on a Permutation With Key/1409.py | {
"start": 421,
"end": 1039
} | class ____:
def processQueries(self, queries: list[int], m: int) -> list[int]:
ans = []
# Map [-m, m] to [0, 2 * m].
tree = FenwickTree(2 * m + 1)
numToIndex = {num: num + m for num in range(1, m + 1)}
for num in range(1, m + 1):
tree.add(num + m, 1)
nextEmptyIndex = m # Map 0 to m.
... | Solution |
python | ray-project__ray | release/benchmark-worker-startup/benchmark_worker_startup.py | {
"start": 7434,
"end": 13114
} | class ____:
num_jobs: int
num_runs_per_job: int
num_tasks_or_actors_per_run: int
with_gpu: bool
with_tasks: bool
with_runtime_env: bool
import_to_try: str
num_cpus_in_cluster: int
num_gpus_in_cluster: int
num_nodes_in_cluster: int
def __repr__(self):
with_gpu_str = "... | TestConfiguration |
python | doocs__leetcode | solution/1600-1699/1634.Add Two Polynomials Represented as Linked Lists/Solution.py | {
"start": 198,
"end": 950
} | class ____:
def addPoly(self, poly1: "PolyNode", poly2: "PolyNode") -> "PolyNode":
dummy = curr = PolyNode()
while poly1 and poly2:
if poly1.power > poly2.power:
curr.next = poly1
poly1 = poly1.next
curr = curr.next
elif poly1.p... | Solution |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/backfills.py | {
"start": 1840,
"end": 2009
} | class ____(BaseModel):
"""Backfill Collection serializer for responses."""
backfills: Iterable[BackfillResponse]
total_entries: int
| BackfillCollectionResponse |
python | django-guardian__django-guardian | guardian/exceptions.py | {
"start": 123,
"end": 226
} | class ____(Exception):
"""Base class for all guardian-specific exceptions."""
pass
| GuardianError |
python | realpython__materials | python-protocol/shapes_v1.py | {
"start": 452,
"end": 884
} | class ____(Shape):
def __init__(self, side) -> None:
self.side = side
def get_area(self) -> float:
return self.side**2
def get_perimeter(self) -> float:
return 4 * self.side
def print_shape_info(shape: Shape):
print(f"Area: {shape.get_area()}")
print(f"Perimeter: {shape.g... | Square |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_selection.py | {
"start": 16555,
"end": 20531
} | class ____:
"""Test handling of duplicate and invalid tool selections."""
def test_duplicate_tool_selection_deduplicated(self) -> None:
"""Test that duplicate tool selections are deduplicated."""
model_requests = []
@wrap_model_call
def trace_model_requests(request, handler):
... | TestDuplicateAndInvalidTools |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.