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 | openai__openai-python | src/openai/types/responses/response_input_item_param.py | {
"start": 9919,
"end": 10615
} | class ____(TypedDict, total=False):
call_id: Required[str]
"""The unique ID of the apply patch tool call generated by the model."""
operation: Required[ApplyPatchCallOperation]
"""
The specific create, delete, or update instruction for the apply_patch tool
call.
"""
status: Required[Li... | ApplyPatchCall |
python | sanic-org__sanic | guide/webapp/display/plugins/tabs.py | {
"start": 288,
"end": 1562
} | class ____(DirectivePlugin):
def parse(
self, block: BlockParser, m: Match, state: BlockState
) -> dict[str, Any]:
info = m.groupdict()
new_state = block.state_cls()
new_state.process(dedent(info["text"]))
block.parse(new_state)
return {
"type": "tab... | Tabs |
python | pydata__xarray | xarray/core/parallel.py | {
"start": 654,
"end": 25062
} | class ____(TypedDict):
shapes: dict[Hashable, int]
coords: set[Hashable]
data_vars: set[Hashable]
def unzip(iterable):
return zip(*iterable, strict=True)
def assert_chunks_compatible(a: Dataset, b: Dataset):
a = a.unify_chunks()
b = b.unify_chunks()
for dim in set(a.chunks).intersection... | ExpectedDict |
python | django__django | tests/template_tests/test_custom.py | {
"start": 1032,
"end": 1437
} | class ____(SimpleTestCase):
@classmethod
def setUpClass(cls):
cls.engine = Engine(app_dirs=True, libraries=LIBRARIES)
super().setUpClass()
def verify_tag(self, tag, name):
self.assertEqual(tag.__name__, name)
self.assertEqual(tag.__doc__, "Expected %s __doc__" % name)
... | TagTestCase |
python | openai__openai-python | src/openai/_base_client.py | {
"start": 8889,
"end": 10410
} | class ____(BasePage[_T], Generic[_T]):
_client: AsyncAPIClient = pydantic.PrivateAttr()
def _set_private_attributes(
self,
model: Type[_T],
client: AsyncAPIClient,
options: FinalRequestOptions,
) -> None:
if (not PYDANTIC_V1) and getattr(self, "__pydantic_private__",... | BaseAsyncPage |
python | milvus-io__pymilvus | pymilvus/orm/index.py | {
"start": 829,
"end": 5183
} | class ____:
def __init__(
self,
collection: Collection,
field_name: str,
index_params: Dict,
**kwargs,
) -> Index:
"""Creates index on a specified field according to the index parameters.
Args:
collection(Collection): The collection in which t... | Index |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 186570,
"end": 188386
} | class ____(GeneratedAirbyteSource):
@public
def __init__(
self,
name: str,
host: str,
port: int,
database: str,
username: str,
password: str,
schemas: Optional[list[str]] = None,
jdbc_url_params: Optional[str] = None,
):
"""Airb... | RedshiftSource |
python | django__django | tests/utils_tests/test_module/__init__.py | {
"start": 0,
"end": 55
} | class ____:
_registry = {}
site = SiteMock()
| SiteMock |
python | PyCQA__pylint | tests/functional/a/access/access_attr_before_def_false_positive.py | {
"start": 1918,
"end": 2169
} | class ____:
"""blabla"""
_the_instance = None
def __new__(cls):
if cls._the_instance is None:
cls._the_instance = object.__new__(cls)
return cls._the_instance
def __init__(self):
pass
| QoSALConnection |
python | huggingface__transformers | tests/models/myt5/test_tokenization_myt5.py | {
"start": 2672,
"end": 6525
} | class ____(TokenizerTesterMixin, unittest.TestCase):
tokenizer_class = MyT5Tokenizer
from_pretrained_id = "Tomlim/myt5-base"
test_rust_tokenizer = False
def get_tokenizer(cls, **kwargs) -> MyT5Tokenizer:
return cls.tokenizer_class.from_pretrained("Tomlim/myt5-base", **kwargs)
@unittest.ski... | MyT5TokenizationTest |
python | getsentry__sentry | src/sentry/api/endpoints/chunk.py | {
"start": 2068,
"end": 3202
} | class ____(OrganizationReleasePermission):
"""
Allow OrganizationReleasePermission OR Launchpad service authentication
"""
def _is_launchpad_authenticated(self, request: Request) -> bool:
"""Check if the request is authenticated via Launchpad service."""
return isinstance(
g... | ChunkUploadPermission |
python | tornadoweb__tornado | tornado/queues.py | {
"start": 2153,
"end": 2328
} | class ____(Generic[_T]):
def __init__(self, q: "Queue[_T]") -> None:
self.q = q
def __anext__(self) -> Awaitable[_T]:
return self.q.get()
| _QueueIterator |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/asyncpg.py | {
"start": 16666,
"end": 17356
} | class ____(Protocol):
async def executemany(
self, operation: Any, seq_of_parameters: Sequence[Tuple[Any, ...]]
) -> Any: ...
async def reload_schema_state(self) -> None: ...
async def prepare(
self, operation: Any, *, name: Optional[str] = None
) -> Any: ...
def is_closed(sel... | _AsyncpgConnection |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/ui/config.py | {
"start": 908,
"end": 1320
} | class ____(BaseModel):
"""configuration serializer."""
page_size: int
auto_refresh_interval: int
hide_paused_dags_by_default: bool
instance_name: str
enable_swagger_ui: bool
require_confirmation_dag_change: bool
default_wrap: bool
test_connection: str
dashboard_alert: list[UIAle... | ConfigResponse |
python | huggingface__transformers | src/transformers/models/blip_2/modeling_blip_2.py | {
"start": 40780,
"end": 54469
} | class ____(Blip2PreTrainedModel):
config: Blip2Config
main_input_name = "pixel_values"
_keep_in_fp32_modules = ["query_tokens", "qformer"]
_supports_flash_attn = False # because self.qformer does not support FA2
def __init__(self, config: Blip2Config):
super().__init__(config)
sel... | Blip2Model |
python | apache__airflow | airflow-core/src/airflow/models/variable.py | {
"start": 2010,
"end": 20452
} | class ____(Base, LoggingMixin):
"""A generic way to store and retrieve arbitrary content or settings as a simple key/value store."""
__tablename__ = "variable"
__NO_DEFAULT_SENTINEL = object()
id: Mapped[int] = mapped_column(Integer, primary_key=True)
key: Mapped[str] = mapped_column(String(ID_LEN... | Variable |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1528593,
"end": 1529012
} | class ____(Transform):
"""
SampleTransform schema wrapper.
Parameters
----------
sample : float
The maximum number of data objects to include in the sample.
**Default value:** ``1000``
"""
_schema = {"$ref": "#/definitions/SampleTransform"}
def __init__(self, sample: ... | SampleTransform |
python | EpistasisLab__tpot | tpot/builtin_modules/nn.py | {
"start": 7626,
"end": 9516
} | class ____(PytorchClassifier):
"""Logistic Regression classifier, implemented in PyTorch, for use with
TPOT.
For examples on standalone use (i.e., non-TPOT) refer to:
https://github.com/trang1618/tpot-nn/blob/master/tpot_nn/estimator_sandbox.py
"""
def __init__(
self,
num_epoch... | PytorchLRClassifier |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py | {
"start": 114,
"end": 155
} | class ____(object):
__slots__ = ()
| Node |
python | scrapy__scrapy | tests/test_crawler.py | {
"start": 20638,
"end": 21129
} | class ____(TestBaseCrawler):
def test_crawler_process_accepts_dict(self):
runner = CrawlerProcess({"foo": "bar"}, install_root_handler=False)
assert runner.settings["foo"] == "bar"
self.assertOptionIsDefault(runner.settings, "RETRY_ENABLED")
def test_crawler_process_accepts_None(self):
... | TestCrawlerProcess |
python | mahmoud__boltons | boltons/queueutils.py | {
"start": 7205,
"end": 7650
} | class ____(BasePriorityQueue):
"""A priority queue inherited from :class:`BasePriorityQueue`, based
on the :func:`bisect.insort` approach for in-order insertion into
a sorted list.
"""
_backend_type = BList
@staticmethod
def _pop_entry(backend):
return backend.pop(0)
@staticmet... | SortedPriorityQueue |
python | mlflow__mlflow | dev/update_changelog.py | {
"start": 685,
"end": 1389
} | class ____(NamedTuple):
title: str
number: int
author: str
labels: list[str]
@property
def url(self):
return f"https://github.com/mlflow/mlflow/pull/{self.number}"
@property
def release_note_labels(self):
return [l for l in self.labels if l.startswith("rn/")]
def _... | PullRequest |
python | pypa__virtualenv | src/virtualenv/run/plugin/discovery.py | {
"start": 69,
"end": 1395
} | class ____(PluginLoader):
"""Discovery plugins."""
def get_discover(parser, args):
discover_types = Discovery.entry_points_for("virtualenv.discovery")
discovery_parser = parser.add_argument_group(
title="discovery",
description="discover and provide a target interpreter",
)
choices... | Discovery |
python | pytest-dev__pytest | testing/test_subtests.py | {
"start": 13049,
"end": 20393
} | class ____:
"""Test unittest.TestCase.subTest functionality."""
def test_failures(
self, pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setenv("COLUMNS", "120")
pytester.makepyfile(
"""
from unittest import TestCase
... | TestUnittestSubTest |
python | huggingface__transformers | tests/models/markuplm/test_feature_extraction_markuplm.py | {
"start": 859,
"end": 1792
} | class ____:
def __init__(self, parent):
self.parent = parent
def prepare_feat_extract_dict(self):
return {}
def get_html_strings():
html_string_1 = """<HTML>
<HEAD>
<TITLE>sample document</TITLE>
</HEAD>
<BODY BGCOLOR="FFFFFF">
<HR>
<a href="http://google.com">Go... | MarkupLMFeatureExtractionTester |
python | neetcode-gh__leetcode | python/1834-single-threaded-cpu.py | {
"start": 0,
"end": 822
} | class ____:
def getOrder(self, tasks: List[List[int]]) -> List[int]:
tasks = sorted([(t[0], t[1], i) for i, t in enumerate(tasks)])
result, heap = [], []
cur_task_index = 0
cur_time = tasks[0][0]
while len(result) < len(tasks):
while (cur_task_index < len... | Solution |
python | getsentry__sentry | tests/sentry/issues/test_issue_occurrence.py | {
"start": 2741,
"end": 3121
} | class ____(OccurrenceTestMixin, TestCase):
def test(self) -> None:
occurrence = self.build_occurrence()
occurrence.save()
fetched_occurrence = IssueOccurrence.fetch(occurrence.id, occurrence.project_id)
assert fetched_occurrence is not None
self.assert_occurrences_identical(o... | IssueOccurrenceSaveAndFetchTest |
python | pytorch__pytorch | test/dynamo/test_deque_reconstruct.py | {
"start": 118,
"end": 2607
} | class ____(torch._inductor.test_case.TestCase):
UNSET = object()
@contextlib.contextmanager
def set_deque_in_globals(self, value):
prev = globals().pop("deque", self.UNSET)
assert "deque" not in globals()
try:
if value is not self.UNSET:
globals()["deque... | TestDequeReconstruct |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/coercions.py | {
"start": 14850,
"end": 16526
} | class ____(RoleImpl):
__slots__ = ()
def _warn_for_scalar_subquery_coercion(self):
util.warn(
"implicitly coercing SELECT object to scalar subquery; "
"please use the .scalar_subquery() method to produce a scalar "
"subquery.",
)
def _implicit_coercions(... | _ColumnCoercions |
python | wandb__wandb | wandb/sdk/artifacts/_generated/fetch_org_info_from_entity.py | {
"start": 226,
"end": 320
} | class ____(GQLResult):
entity: Optional[FetchOrgInfoFromEntityEntity]
| FetchOrgInfoFromEntity |
python | scipy__scipy | scipy/sparse/_dok.py | {
"start": 416,
"end": 19799
} | class ____(_spbase, IndexMixin, dict):
_format = 'dok'
_allow_nd = (1, 2)
def __init__(self, arg1, shape=None, dtype=None, copy=False, *, maxprint=None):
_spbase.__init__(self, arg1, maxprint=maxprint)
if isinstance(arg1, tuple) and isshape(arg1, allow_nd=self._allow_nd):
self.... | _dok_base |
python | tensorflow__tensorflow | tensorflow/python/distribute/cross_device_ops.py | {
"start": 10105,
"end": 23882
} | class ____(object):
"""Base class for cross-device reduction and broadcasting algorithms.
The main purpose of this class is to be passed to
`tf.distribute.MirroredStrategy` in order to choose among different cross
device communication implementations. Prefer using the methods of
`tf.distribute.Strategy` inst... | CrossDeviceOps |
python | giampaolo__psutil | tests/__init__.py | {
"start": 21249,
"end": 27109
} | class ____:
"""A retry decorator."""
def __init__(
self,
exception=Exception,
timeout=None,
retries=None,
interval=0.001,
logfun=None,
):
if timeout and retries:
raise ValueError("timeout and retries args are mutually exclusive")
s... | retry |
python | doocs__leetcode | solution/2700-2799/2706.Buy Two Chocolates/Solution2.py | {
"start": 0,
"end": 295
} | class ____:
def buyChoco(self, prices: List[int], money: int) -> int:
a = b = inf
for x in prices:
if x < a:
a, b = x, a
elif x < b:
b = x
cost = a + b
return money if money < cost else money - cost
| Solution |
python | huggingface__transformers | src/transformers/models/canine/modeling_canine.py | {
"start": 24336,
"end": 26238
} | class ____(GradientCheckpointingLayer):
def __init__(
self,
config,
local,
always_attend_to_first_position,
first_position_attends_to_all,
attend_from_chunk_width,
attend_from_chunk_stride,
attend_to_chunk_width,
attend_to_chunk_stride,
):
... | CanineLayer |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/cloud_composer.py | {
"start": 2386,
"end": 21997
} | class ____(GoogleBaseHook, OperationHelper):
"""Hook for Google Cloud Composer APIs."""
client_options = ClientOptions(api_endpoint="composer.googleapis.com:443")
def get_environment_client(self) -> EnvironmentsClient:
"""Retrieve client library object that allow access Environments service."""
... | CloudComposerHook |
python | spack__spack | lib/spack/spack/database.py | {
"start": 73865,
"end": 74307
} | class ____(KeyError):
"""Raised when a spec is not found in the database."""
def __init__(self, spec):
self.spec = spec
super().__init__(spec)
def __str__(self):
# This exception is raised frequently, and almost always
# caught, so ensure we don't pay the cost of Spec.__str... | NoSuchSpecError |
python | tensorflow__tensorflow | tensorflow/python/ops/image_ops_impl.py | {
"start": 49783,
"end": 235119
} | class ____:
"""See `tf.image.resize` for details."""
BILINEAR = 'bilinear'
NEAREST_NEIGHBOR = 'nearest'
BICUBIC = 'bicubic'
AREA = 'area'
LANCZOS3 = 'lanczos3'
LANCZOS5 = 'lanczos5'
GAUSSIAN = 'gaussian'
MITCHELLCUBIC = 'mitchellcubic'
def _resize_images_common(images, resizer_fn, size, preserve_asp... | ResizeMethod |
python | kamyu104__LeetCode-Solutions | Python/the-number-of-the-smallest-unoccupied-chair.py | {
"start": 48,
"end": 762
} | class ____(object):
def smallestChair(self, times, targetFriend):
"""
:type times: List[List[int]]
:type targetFriend: int
:rtype: int
"""
events = []
for i, (s, e) in enumerate(times):
events.append((s, True, i))
events.append((e, Fal... | Solution |
python | openai__openai-python | src/openai/resources/responses/responses.py | {
"start": 155426,
"end": 156373
} | class ____:
def __init__(self, responses: Responses) -> None:
self._responses = responses
self.create = _legacy_response.to_raw_response_wrapper(
responses.create,
)
self.retrieve = _legacy_response.to_raw_response_wrapper(
responses.retrieve,
)
... | ResponsesWithRawResponse |
python | matplotlib__matplotlib | lib/matplotlib/contour.py | {
"start": 2158,
"end": 23794
} | class ____:
"""Mixin to provide labelling capability to `.ContourSet`."""
def clabel(self, levels=None, *,
fontsize=None, inline=True, inline_spacing=5, fmt=None,
colors=None, use_clabeltext=False, manual=False,
rightside_up=True, zorder=None):
"""
L... | ContourLabeler |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/owners.py | {
"start": 286,
"end": 443
} | class ____(graphene.ObjectType):
class Meta:
name = "TeamDefinitionOwner"
team = graphene.NonNull(graphene.String)
| GrapheneTeamDefinitionOwner |
python | kamyu104__LeetCode-Solutions | Python/partition-array-for-maximum-xor-and-and.py | {
"start": 60,
"end": 1532
} | class ____(object):
def maximizeXorAndXor(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def max_xor_subset(nums): # Time: O(nlogr)
base = [0]*l
for x in nums: # gaussian elimination over GF(2)
for i in reversed(xrange(len(ba... | Solution |
python | keras-team__keras | keras/src/ops/nn.py | {
"start": 49906,
"end": 52776
} | class ____(Operation):
def __init__(
self, num_classes, axis=-1, dtype=None, sparse=False, *, name=None
):
super().__init__(name=name)
self.num_classes = num_classes
self.axis = axis
self.dtype = backend.standardize_dtype(dtype)
self.sparse = sparse
def call(... | OneHot |
python | openai__openai-python | src/openai/types/responses/response_input_file_content.py | {
"start": 229,
"end": 743
} | class ____(BaseModel):
type: Literal["input_file"]
"""The type of the input item. Always `input_file`."""
file_data: Optional[str] = None
"""The base64-encoded data of the file to be sent to the model."""
file_id: Optional[str] = None
"""The ID of the file to be sent to the model."""
file... | ResponseInputFileContent |
python | pytorch__pytorch | torch/_inductor/codegen/rocm/ck_universal_gemm_template.py | {
"start": 1864,
"end": 39672
} | class ____(CKTemplate):
# the JINJA template for rendering CK Universal GEMMs
gemm_template = r"""{{version_comment}}
{{headers}}
{{globals}}
{{instance_definition}}
extern "C" {
PT_EXPORT {{kernel_definition}} {
auto gemm = {{instance_type}} {};
auto invoker = gemm.MakeInvok... | CKGemmTemplate |
python | django__django | tests/auth_tests/test_auth_backends.py | {
"start": 20639,
"end": 22915
} | class ____(BaseModelBackendTest, TestCase):
"""
Tests for the ModelBackend using the default User model.
"""
UserModel = User
user_credentials = {"username": "test", "password": "test"}
def create_users(self):
self.user = User.objects.create_user(
email="test@example.com", ... | ModelBackendTest |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 53925,
"end": 54977
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"path",
"body",
"pull_request_id",
"pull_request_review_id",
"line",
"side",
"start_line",
"start_side",
"cli... | AddPullRequestReviewThreadInput |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py | {
"start": 97233,
"end": 98599
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("endpoint_service.EndpointServiceHook"))
def test_execute(self, mock_hook):
page_token = "page_token"
page_size = 42
filter = "filter"
read_mask = "read_mask"
order_by = "order_by"
op = ListEndpointsOperator(
... | TestVertexAIListEndpointsOperator |
python | tiangolo__fastapi | fastapi/exceptions.py | {
"start": 4334,
"end": 4527
} | class ____(Exception):
def __init__(self, errors: Sequence[Any]) -> None:
self._errors = errors
def errors(self) -> Sequence[Any]:
return self._errors
| ValidationException |
python | python-pillow__Pillow | src/PIL/BufrStubImagePlugin.py | {
"start": 691,
"end": 1730
} | class ____(ImageFile.StubImageFile):
format = "BUFR"
format_description = "BUFR"
def _open(self) -> None:
if not _accept(self.fp.read(4)):
msg = "Not a BUFR file"
raise SyntaxError(msg)
self.fp.seek(-4, os.SEEK_CUR)
# make something up
self._mode = ... | BufrStubImageFile |
python | django__django | tests/view_tests/tests/test_debug.py | {
"start": 1800,
"end": 1887
} | class ____:
urlpatterns = [path("url/", index_page, name="url")]
| WithoutEmptyPathUrls |
python | pytorch__pytorch | torch/_inductor/codegen/multi_kernel.py | {
"start": 19961,
"end": 23403
} | class ____(MultiKernelCall):
"""
Runtime class for size-hint multi-kernels.
Instead of having a plain list of kernels to benchmark over, keys them by input & output shapes,
and optionally perform shape-based selection. The pre-generated kernel is chosen based on the shape keys,
with the heuristic be... | SizeHintMultiKernelCall |
python | getsentry__sentry | tests/sentry/utils/test_ratelimits.py | {
"start": 698,
"end": 2673
} | class ____(TestCase):
def test_by_email(self) -> None:
organization = Organization(id=1)
email = "foo@example.com"
for n in range(2):
assert not ratelimits.for_organization_member_invite(
organization, email, config=RELAXED_CONFIG
)
assert rat... | ForOrganizationMemberTestCase |
python | pytest-dev__pytest | doc/en/example/nonpython/conftest.py | {
"start": 257,
"end": 555
} | class ____(pytest.File):
def collect(self):
# We need a yaml parser, e.g. PyYAML.
import yaml
raw = yaml.safe_load(self.path.open(encoding="utf-8"))
for name, spec in sorted(raw.items()):
yield YamlItem.from_parent(self, name=name, spec=spec)
| YamlFile |
python | google__pytype | pytype_extensions/instrumentation_for_testing_test.py | {
"start": 685,
"end": 1045
} | class ____(i4t.ProductionType[NoCtor]):
def __init__(self, state):
self.state = state
def Mul100(self, i):
return self.state * i * 103
# When access to instrumented_type is needed and the fake __init__ signature is
# IDENTICAL to that of production_type (or __init__ has no arguments if
# production_type... | FakeNoCtorInitArgUnsealed |
python | plotly__plotly.py | plotly/graph_objs/histogram2d/_legendgrouptitle.py | {
"start": 233,
"end": 2967
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "histogram2d"
_path_str = "histogram2d.legendgrouptitle"
_valid_props = {"font", "text"}
@property
def font(self):
"""
Sets this legend group's title font.
The 'font' property is an instance of Font
that may be... | Legendgrouptitle |
python | huggingface__transformers | src/transformers/models/groupvit/modeling_groupvit.py | {
"start": 17597,
"end": 19186
} | class ____(nn.Module):
def __init__(self, config: GroupViTTextConfig):
super().__init__()
embed_dim = config.hidden_size
self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
# pos... | GroupViTTextEmbeddings |
python | scikit-learn__scikit-learn | sklearn/model_selection/_classification_threshold.py | {
"start": 6914,
"end": 17363
} | class ____(BaseThresholdClassifier):
"""Binary classifier that manually sets the decision threshold.
This classifier allows to change the default decision threshold used for
converting posterior probability estimates (i.e. output of `predict_proba`) or
decision scores (i.e. output of `decision_function... | FixedThresholdClassifier |
python | walkccc__LeetCode | solutions/2283. Check if Number Has Equal Digit Count and Digit Value/2283.py | {
"start": 0,
"end": 185
} | class ____:
def digitCount(self, num: str) -> bool:
count = collections.Counter(num)
return all(count[str(i)] == int(digit)
for i, digit in enumerate(num))
| Solution |
python | py-pdf__pypdf | pypdf/constants.py | {
"start": 9592,
"end": 9741
} | class ____:
"""Table 8.2 of the PDF 1.7 reference."""
LEFT = "/Left"
RIGHT = "/Right"
BOTTOM = "/Bottom"
TOP = "/Top"
| TypArguments |
python | keras-team__keras | keras/src/ops/core_test.py | {
"start": 5474,
"end": 12237
} | class ____(testing.TestCase):
def test_associative_scan(self):
xs = (KerasTensor((5, 10)), KerasTensor((5, 10)))
ys = core.associative_scan(
f=lambda x, y: (x[0] + y[0], x[1] + y[1]), elems=xs, axis=0
)
self.assertEqual(ys[0].shape, (5, 10))
# sum two tuples of u... | CoreOpsStaticShapeTest |
python | protocolbuffers__protobuf | python/google/protobuf/internal/thread_safe_test.py | {
"start": 1637,
"end": 3125
} | class ____(unittest.TestCase):
def RunThreads(self, thread_size, func):
threads = []
for i in range(0, thread_size):
threads.append(threading.Thread(target=func))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
def testDoNothing(self):
thread_size =... | FreeThreadingTest |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 91680,
"end": 91753
} | class ____(Binop):
operation = operator.le
_operator_repr = "<="
| LE |
python | spyder-ide__spyder | spyder/plugins/layout/layouts.py | {
"start": 343,
"end": 566
} | class ____:
SpyderLayout = "Spyder Default Layout"
HorizontalSplitLayout = "Horizontal split"
VerticalSplitLayout = "Vertical split"
RLayout = "Rstudio layout"
MatlabLayout = "Matlab layout"
| DefaultLayouts |
python | lxml__lxml | src/lxml/html/tests/test_html5parser.py | {
"start": 13577,
"end": 13707
} | class ____:
def __init__(self, root):
self.root = root
def getroot(self):
return self.root
| DummyElementTree |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_combined09.py | {
"start": 315,
"end": 1633
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_combined09.xlsx")
self.ignore_elements = {
"xl/charts/chart1.xml": ["<c:dispBlanksAs", "<c:tickLblPos"]
}
def te... | TestCompareXLSXFiles |
python | coleifer__peewee | tests/fields.py | {
"start": 1083,
"end": 1208
} | class ____(TestModel):
data = IntegerField(default=17)
data_callable = IntegerField(default=lambda: 1337)
| DefaultValues |
python | vyperlang__vyper | vyper/semantics/analysis/base.py | {
"start": 9311,
"end": 11172
} | class ____:
"""
Class which represents the analysis associated with an expression
"""
typ: VyperType
var_info: Optional[VarInfo] = None
module_info: Optional[ModuleInfo] = None
location: DataLocation = DataLocation.UNSET
modifiability: Modifiability = Modifiability.MODIFIABLE
attr: ... | ExprInfo |
python | django-guardian__django-guardian | guardian/migrations/0003_remove_groupobjectpermission_guardian_gr_content_ae6aec_idx_and_more.py | {
"start": 125,
"end": 1649
} | class ____(migrations.Migration):
dependencies = [
("auth", "0012_alter_user_first_name_max_length"),
("contenttypes", "0002_remove_content_type_name"),
("guardian", "0002_generic_permissions_index"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = ... | Migration |
python | pytorch__pytorch | test/higher_order_ops/test_local_map.py | {
"start": 6613,
"end": 8993
} | class ____(TestCase):
def setUp(self):
torch._dynamo.reset()
self.exit_stack = ExitStack()
self.exit_stack.enter_context(sdpa_kernel(backends=[SDPBackend.MATH]))
if torch.distributed.is_available():
from torch.testing._internal.distributed.fake_pg import FakeStore
... | TestLocalMap |
python | getsentry__sentry | src/sentry/status_checks/base.py | {
"start": 389,
"end": 1831
} | class ____:
# Used for issues that may render the system inoperable or have effects on
# data integrity (e.g. issues in the processing pipeline.)
SEVERITY_CRITICAL: Final = "critical"
# Used for issues that may cause the system to operate in a degraded (but
# still operational) state, as well as c... | Problem |
python | graphql-python__graphene | graphene/relay/tests/test_connection_async.py | {
"start": 448,
"end": 2754
} | class ____(ObjectType):
letters = ConnectionField(LetterConnection)
connection_letters = ConnectionField(LetterConnection)
async_letters = ConnectionField(LetterConnection)
node = Node.Field()
def resolve_letters(self, info, **args):
return list(letters.values())
async def resolve_asy... | Query |
python | davidhalter__jedi | test/completion/classes.py | {
"start": 10046,
"end": 10207
} | class ____:
class __init__:
def __init__(self, a):
self.a = a
def y(self):
return self.a
#?
WithWeirdInit(1).y()
| WithWeirdInit |
python | getsentry__sentry | src/sentry/models/grouprulestatus.py | {
"start": 219,
"end": 846
} | class ____(Model):
__relocation_scope__ = RelocationScope.Excluded
ACTIVE = 0
INACTIVE = 1
project = FlexibleForeignKey("sentry.Project")
rule = FlexibleForeignKey("sentry.Rule")
group = FlexibleForeignKey("sentry.Group")
status = models.PositiveSmallIntegerField(default=ACTIVE)
date_a... | GroupRuleStatus |
python | kamyu104__LeetCode-Solutions | Python/longest-common-prefix-of-k-strings-after-removal.py | {
"start": 2826,
"end": 4563
} | class ____(object):
def longestCommonPrefix(self, words, k):
"""
:type words: List[str]
:type k: int
:rtype: List[int]
"""
class Trie(object):
def __init__(self):
self.__nodes = []
self.__cnt = []
self.__mx =... | Solution_TLE |
python | pypa__pip | src/pip/_vendor/rich/prompt.py | {
"start": 10146,
"end": 10414
} | class ____(PromptBase[float]):
"""A prompt that returns a float.
Example:
>>> temperature = FloatPrompt.ask("Enter desired temperature")
"""
response_type = float
validate_error_message = "[prompt.invalid]Please enter a number"
| FloatPrompt |
python | wandb__wandb | tools/cloud_tool.py | {
"start": 3978,
"end": 10260
} | class ____:
def __init__(
self,
config: GCEConfig,
verbose: bool = False,
log_level: int = logging.INFO,
) -> None:
self.config = config
self.logger = Logger(__name__.lower(), verbose, log_level)
self.logger.print(f"Initialized {__name__} CLI")
se... | GCE |
python | oauthlib__oauthlib | oauthlib/oauth2/rfc6749/clients/base.py | {
"start": 802,
"end": 26368
} | class ____:
"""Base OAuth2 client responsible for access token management.
This class also acts as a generic interface providing methods common to all
client types such as ``prepare_authorization_request`` and
``prepare_token_revocation_request``. The ``prepare_x_request`` methods are
the recommend... | Client |
python | huggingface__transformers | src/transformers/models/phi4_multimodal/processing_phi4_multimodal.py | {
"start": 1036,
"end": 1196
} | class ____(ProcessingKwargs, total=False):
_defaults = {
"audio_kwargs": {
"device": "cpu",
},
}
| Phi4MultimodalProcessorKwargs |
python | tensorflow__tensorflow | tensorflow/core/function/runtime_client/runtime_client_test.py | {
"start": 7367,
"end": 9379
} | class ____(test.TestCase):
@test_util.run_v2_only
def setUp(self):
super().setUp()
workers, _ = test_util.create_local_cluster(2, 0)
remote.connect_to_remote_host(
[workers[0].target, workers[1].target])
self.device0 = "/job:worker/replica:0/task:0/device:CPU:0"
self.device1 = "/job:... | RuntimeClientMultiWorkersTest |
python | keras-team__keras | keras/src/utils/audio_dataset_utils_test.py | {
"start": 169,
"end": 16560
} | class ____(testing.TestCase):
def _get_audio_samples(self, count=16, different_sequence_lengths=False):
sequence_length = 30
num_channels = 1
audio_samples = []
for _ in range(count):
if different_sequence_lengths:
random_sequence_length = np.random.randin... | AudioDatasetFromDirectoryTest |
python | crytic__slither | slither/slithir/tmp_operations/tmp_call.py | {
"start": 750,
"end": 3455
} | class ____(OperationWithLValue): # pylint: disable=too-many-instance-attributes
def __init__(
self,
called: SourceMapping,
nbr_arguments: int,
result: Union[TupleVariable, TemporaryVariable],
type_call: str,
names: Optional[List[str]] = None,
) -> None:
#... | TmpCall |
python | google__python-fire | fire/test_components.py | {
"start": 7530,
"end": 8404
} | class ____:
"""Test class for testing help text output with multiline docstring.
This is a test class that has a long docstring description that spans across
multiple lines for testing line breaking in help text.
"""
@staticmethod
def example_generator(n):
"""Generators have a ``Yields`` section inste... | ClassWithMultilineDocstring |
python | kamyu104__LeetCode-Solutions | Python/count-good-triplets-in-an-array.py | {
"start": 540,
"end": 1093
} | class ____(object):
def goodTriplets(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: int
"""
lookup = [0]*len(nums1)
for i, x in enumerate(nums1):
lookup[x] = i
result = 0
bit = BIT(len(nums1))
... | Solution |
python | kamyu104__LeetCode-Solutions | Python/find-duplicate-file-in-system.py | {
"start": 99,
"end": 751
} | class ____(object):
def findDuplicate(self, paths):
"""
:type paths: List[str]
:rtype: List[List[str]]
"""
files = collections.defaultdict(list)
for path in paths:
s = path.split(" ")
for i in xrange(1,len(s)):
file_name = s[0] + "... | Solution |
python | ZoranPandovski__al-go-rithms | math/RunningMedian/python/runningMedian.py | {
"start": 0,
"end": 3582
} | class ____:
def __init__(self,key):
self.left=None
self.right=None
self.data=key
self.bf=0
self.count=1
self.parent=None
self.lkids=0
self.rkids=0
def rotateNBalance(node):
if node.bf < 0:
if node.right.bf <= 0:
rotateLeft(node... | Node |
python | pallets__werkzeug | tests/test_wrappers.py | {
"start": 41216,
"end": 43916
} | class ____:
def test_secure(self):
response = wrappers.Response()
response.set_cookie(
"foo",
value="bar",
max_age=60,
expires=0,
path="/blub",
domain="example.org",
secure=True,
samesite=None,
)
... | TestSetCookie |
python | ansible__ansible | lib/ansible/galaxy/api.py | {
"start": 7598,
"end": 9295
} | class ____(AnsibleError):
""" Error for bad Galaxy server responses. """
def __init__(self, http_error, message):
super(GalaxyError, self).__init__(message)
self.http_code = http_error.code
self.url = http_error.geturl()
try:
http_msg = to_text(http_error.read())
... | GalaxyError |
python | sympy__sympy | sympy/series/sequences.py | {
"start": 11521,
"end": 12320
} | class ____(SeqBase, metaclass=Singleton):
"""Represents an empty sequence.
The empty sequence is also available as a singleton as
``S.EmptySequence``.
Examples
========
>>> from sympy import EmptySequence, SeqPer
>>> from sympy.abc import x
>>> EmptySequence
EmptySequence
>>> ... | EmptySequence |
python | google__pytype | pytype/pyc/opcodes.py | {
"start": 13659,
"end": 13805
} | class ____(OpcodeWithArg): # Arg: Number of raise args (1, 2, or 3)
_FLAGS = HAS_ARGUMENT | HAS_JUNKNOWN | NO_NEXT
__slots__ = ()
| RAISE_VARARGS |
python | langchain-ai__langchain | libs/partners/exa/langchain_exa/retrievers.py | {
"start": 1205,
"end": 4341
} | class ____(BaseRetriever):
"""Exa Search retriever."""
k: int = 10 # num_results
"""The number of search results to return (1 to 100)."""
include_domains: list[str] | None = None
"""A list of domains to include in the search."""
exclude_domains: list[str] | None = None
"""A list of domains... | ExaSearchRetriever |
python | django__django | tests/distinct_on_fields/models.py | {
"start": 31,
"end": 346
} | class ____(models.Model):
name = models.CharField(max_length=10)
parent = models.ForeignKey(
"self",
models.SET_NULL,
blank=True,
null=True,
related_name="children",
)
class Meta:
ordering = ["name"]
def __str__(self):
return self.name
| Tag |
python | apache__airflow | providers/edge3/src/airflow/providers/edge3/cli/worker.py | {
"start": 2593,
"end": 17898
} | class ____:
"""Runner instance which executes the Edge Worker."""
jobs: list[Job] = []
"""List of jobs that the worker is running currently."""
last_hb: datetime | None = None
"""Timestamp of last heart beat sent to server."""
drain: bool = False
"""Flag if job processing should be complete... | EdgeWorker |
python | ansible__ansible | test/units/parsing/test_ajson.py | {
"start": 2915,
"end": 6946
} | class ____:
"""
Namespace for testing AnsibleJSONEncoder.
"""
@pytest.fixture(scope='class')
def mapping(self, request):
"""
Returns object of Mapping mock class.
The object is used for testing handling of Mapping objects
in AnsibleJSONEncoder.default().
Us... | TestAnsibleJSONEncoder |
python | facelessuser__pymdown-extensions | pymdownx/_bypassnorm.py | {
"start": 1018,
"end": 1368
} | class ____(Preprocessor):
"""Preprocessor to clean up normalization bypass hack."""
def run(self, lines):
"""Convert alternate placeholder symbols to actual placeholder symbols."""
source = '\n'.join(lines)
source = source.replace(SOH, STX).replace(EOT, ETX)
return source.split... | PostNormalizePreprocessor |
python | ZoranPandovski__al-go-rithms | data_structures/trie/Python/trie_word_search.py | {
"start": 0,
"end": 79
} | class ____:
def __init__(self):
self.ch=[None]*26
self.endofword=None
| Trienode |
python | scipy__scipy | benchmarks/benchmarks/fft_basic.py | {
"start": 651,
"end": 1682
} | class ____:
"""Backend for pyfftw"""
__ua_domain__ = 'numpy.scipy.fft'
@staticmethod
def __ua_function__(method, args, kwargs):
kwargs.pop('overwrite_x', None)
fn = getattr(pyfftw_fft, method.__name__, None)
return (NotImplemented if fn is None
else fn(*args, **... | PyfftwBackend |
python | run-llama__llama_index | llama-index-integrations/indices/llama-index-indices-managed-lancedb/llama_index/indices/managed/lancedb/retriever.py | {
"start": 622,
"end": 7088
} | class ____(BaseRetriever):
def __init__(
self, table: Union[AsyncTable, Table], multimodal: bool, **kwargs: Any
):
self.table = table
self.multimodal = multimodal
callback_manager = kwargs.get("callback_manager")
verbose = kwargs.get("verbose", False)
super().__in... | LanceDBRetriever |
python | tensorflow__tensorflow | tensorflow/python/data/ops/multi_device_iterator_ops.py | {
"start": 1690,
"end": 7199
} | class ____(dataset_ops.DatasetV2):
"""A `dummy` generator dataset."""
def __init__(self, shard_num, multi_device_iterator_resource, incarnation_id,
source_device, element_spec, iterator_is_anonymous):
self._element_spec = element_spec
self._name = f"device_generator_{shard_num}"
multi_d... | _PerDeviceGenerator |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.