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 | automl__auto-sklearn | autosklearn/experimental/askl2.py | {
"start": 711,
"end": 2356
} | class ____:
def __init__(self, portfolio):
self.portfolio = portfolio
def __call__(
self,
scenario_dict,
seed,
ta,
ta_kwargs,
metalearning_configurations,
n_jobs,
dask_client,
multi_objective_algorithm,
multi_objective_kwar... | SmacObjectCallback |
python | joke2k__faker | faker/providers/sbn/__init__.py | {
"start": 168,
"end": 1978
} | class ____(BaseProvider):
"""Generates fake SBNs. These are the precursor to the ISBN and are
largely similar to ISBN-10.
See https://www.isbn-international.org/content/what-isbn for the
format of ISBNs. SBNs have no EAN prefix or Registration Group.
"""
def _body(self) -> List[str]:
"... | Provider |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_textbox38.py | {
"start": 315,
"end": 1645
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("textbox38.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with textbox(s)."""
workbook = Workb... | TestCompareXLSXFiles |
python | kamyu104__LeetCode-Solutions | Python/number-of-ways-to-separate-numbers.py | {
"start": 33,
"end": 1728
} | class ____(object):
def numberOfCombinations(self, num):
"""
:type num: str
:rtype: int
"""
MOD = 10**9+7
def find_longest_common_prefix(num):
lcp = [[0]*(len(num)+1) for _ in xrange(len(num)+1)] # lcp[i][j]: longest length of the common prefix which star... | Solution |
python | tensorflow__tensorflow | tensorflow/python/debug/cli/cli_shared_test.py | {
"start": 1248,
"end": 2983
} | class ____(test_util.TensorFlowTestCase):
def testNoneSizeWorks(self):
self.assertEqual(str(None), cli_shared.bytes_to_readable_str(None))
def testSizesBelowOneKiloByteWorks(self):
self.assertEqual("0", cli_shared.bytes_to_readable_str(0))
self.assertEqual("500", cli_shared.bytes_to_readable_str(500))... | BytesToReadableStrTest |
python | PrefectHQ__prefect | src/prefect/client/schemas/objects.py | {
"start": 2840,
"end": 3115
} | class ____(AutoEnum):
"""Enumeration of work pool statuses."""
READY = AutoEnum.auto()
NOT_READY = AutoEnum.auto()
PAUSED = AutoEnum.auto()
@property
def display_name(self) -> str:
return self.name.replace("_", " ").capitalize()
| WorkPoolStatus |
python | dagster-io__dagster | python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/core/alert_types.py | {
"start": 102,
"end": 907
} | class ____(Enum):
"""Possible comparison operators for an insights alert type, used to
determine when to trigger an alert based on the value of the metric.
"""
LESS_THAN = "LESS_THAN"
GREATER_THAN = "GREATER_THAN"
def compare(self, computed_value: float, target_value: float) -> bool:
i... | InsightsAlertComparisonOperator |
python | getsentry__sentry | src/sentry/seer/breakpoints.py | {
"start": 1453,
"end": 1608
} | class ____(TypedDict):
data: "list[SnubaTSEntry]"
request_start: int
request_end: int
data_start: int
data_end: int
| BreakpointTransaction |
python | weaviate__weaviate-python-client | weaviate/groups/async_.py | {
"start": 312,
"end": 383
} | class ____(_GroupsOIDCExecutor[ConnectionAsync]):
pass
| _GroupsOIDCAsync |
python | jina-ai__jina | jina/enums.py | {
"start": 7286,
"end": 7422
} | class ____(str, Enum):
"""Subprotocol supported with Websocket Gateway"""
JSON = 'json'
BYTES = 'bytes'
| WebsocketSubProtocols |
python | ray-project__ray | release/benchmark-worker-startup/benchmark_worker_startup.py | {
"start": 3525,
"end": 7434
} | class ____:
"""
Actor which tests will report metrics to.
"""
def __init__(self, expected_measurements_per_test: int):
self.measurements = defaultdict(list)
self.expected_measurements_per_test = expected_measurements_per_test
def submit(self, test_name: str, latency: float):
... | MetricsActor |
python | pytorch__pytorch | torch/__init__.py | {
"start": 70306,
"end": 70529
} | class ____(_LegacyStorage):
@classproperty
def dtype(self):
_warn_typed_storage_removal(stacklevel=3)
return self._dtype
@classproperty
def _dtype(self):
return torch.uint8
| ByteStorage |
python | getsentry__sentry | src/sentry/sentry_apps/installations.py | {
"start": 4179,
"end": 7225
} | class ____:
organization_id: int
slug: str
notify: bool = True
def run(self, *, user: User | RpcUser, request: HttpRequest | None) -> SentryAppInstallation:
with SentryAppInteractionEvent(
operation_type=SentryAppInteractionType.MANAGEMENT,
event_type=SentryAppEventType.... | SentryAppInstallationCreator |
python | doocs__leetcode | solution/1000-1099/1036.Escape a Large Maze/Solution.py | {
"start": 0,
"end": 810
} | class ____:
def isEscapePossible(
self, blocked: List[List[int]], source: List[int], target: List[int]
) -> bool:
def dfs(source: List[int], target: List[int], vis: set) -> bool:
vis.add(tuple(source))
if len(vis) > m:
return True
for a, b in p... | Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/asset_backfill.py | {
"start": 28178,
"end": 95415
} | class ____(NamedTuple):
run_requests: Sequence[RunRequest]
backfill_data: AssetBackfillData
reserved_run_ids: Sequence[str]
def _get_requested_asset_graph_subset_from_run_requests(
run_requests: Sequence[RunRequest],
asset_graph_view: AssetGraphView,
) -> AssetGraphSubset:
asset_graph = asset_... | AssetBackfillIterationResult |
python | kamyu104__LeetCode-Solutions | Python/minimum-flips-to-make-a-or-b-equal-to-c.py | {
"start": 30,
"end": 450
} | class ____(object):
def minFlips(self, a, b, c):
"""
:type a: int
:type b: int
:type c: int
:rtype: int
"""
def number_of_1_bits(n):
result = 0
while n:
n &= n-1
result += 1
return result
... | Solution |
python | realpython__materials | flask-connexion-rest-part-4/models.py | {
"start": 1476,
"end": 1728
} | class ____(ma.ModelSchema):
def __init__(self, **kwargs):
super().__init__(strict=True, **kwargs)
class Meta:
model = Note
sqla_session = db.session
person = fields.Nested("NotePersonSchema", default=None)
| NoteSchema |
python | google__flatbuffers | python/flatbuffers/number_types.py | {
"start": 1846,
"end": 1997
} | class ____(object):
bytewidth = 2
min_val = -(2**15)
max_val = (2**15) - 1
py_type = int
name = "int16"
packer_type = packer.int16
| Int16Flags |
python | django__django | tests/expressions/models.py | {
"start": 2237,
"end": 2444
} | class ____(models.Model):
experiment = models.ForeignKey(Experiment, models.CASCADE)
result_time = models.DateTimeField()
def __str__(self):
return "Result at %s" % self.result_time
| Result |
python | getsentry__sentry | src/sentry/sentry_apps/models/sentry_app_component.py | {
"start": 428,
"end": 1438
} | class ____(Model):
__relocation_scope__ = RelocationScope.Global
uuid = UUIDField(unique=True, auto_add=True)
sentry_app = FlexibleForeignKey("sentry.SentryApp", related_name="components")
type = models.CharField(max_length=64)
schema = models.JSONField()
class Meta:
app_label = "sentr... | SentryAppComponent |
python | PyCQA__pyflakes | pyflakes/checker.py | {
"start": 7369,
"end": 7489
} | class ____:
"""
A dictionary key of a type that we cannot or do not check for duplicates.
"""
| UnhandledKeyType |
python | numpy__numpy | numpy/_core/tests/test_indexing.py | {
"start": 49672,
"end": 52190
} | class ____:
# Using a boolean as integer argument/indexing is an error.
def test_bool_as_int_argument_errors(self):
a = np.array([[[1]]])
assert_raises(TypeError, np.reshape, a, (True, -1))
assert_raises(TypeError, np.reshape, a, (np.bool(True), -1))
# Note that operator.index(n... | TestBooleanIndexing |
python | tensorflow__tensorflow | tensorflow/dtensor/python/tests/numpy_util_test.py | {
"start": 1100,
"end": 4903
} | class ____(test_util.DTensorBaseTest):
def setUp(self):
super().setUp()
global_ids = test_util.create_device_ids_array((2, 2))
local_ids = np.ravel(global_ids).tolist()
mesh_dict = {
device: layout.Mesh([_MESH_DIM_X, _MESH_DIM_Y], global_ids, local_ids,
test_util.c... | NumpyUtilTest |
python | great-expectations__great_expectations | contrib/experimental/great_expectations_experimental/expectations/expect_column_values_to_be_alphabetical.py | {
"start": 789,
"end": 2323
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
# Please see {some doc} for information on how to choose an id string for your Metric.
condition_metric_name = "column_values.are_alphabetical"
condition_value_keys = ("reverse",)
# This method ... | ColumnValuesAreAlphabetical |
python | doocs__leetcode | lcof2/剑指 Offer II 112. 最长递增路径/Solution.py | {
"start": 0,
"end": 500
} | class ____:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
@cache
def dfs(i, j):
ans = 1
for a, b in [[-1, 0], [1, 0], [0, 1], [0, -1]]:
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and matrix[x][y] > matrix[i][j]:
... | Solution |
python | doocs__leetcode | solution/0200-0299/0279.Perfect Squares/Solution.py | {
"start": 0,
"end": 379
} | class ____:
def numSquares(self, n: int) -> int:
m = int(sqrt(n))
f = [[inf] * (n + 1) for _ in range(m + 1)]
f[0][0] = 0
for i in range(1, m + 1):
for j in range(n + 1):
f[i][j] = f[i - 1][j]
if j >= i * i:
f[i][j] = mi... | Solution |
python | kamyu104__LeetCode-Solutions | Python/find-the-safest-path-in-a-grid.py | {
"start": 4425,
"end": 6245
} | class ____(object):
def maximumSafenessFactor(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1))
def bfs():
dist = [[0 if grid[r][c] == 1 else -1 for c in xrange(len(grid[0]))] for r in xrange(len(g... | Solution3 |
python | pandas-dev__pandas | pandas/core/arrays/integer.py | {
"start": 2016,
"end": 5130
} | class ____(NumericArray):
"""
Array of integer (optional missing) values.
Uses :attr:`pandas.NA` as the missing value.
.. warning::
IntegerArray is currently experimental, and its API or internal
implementation may change without warning.
We represent an IntegerArray with 2 numpy a... | IntegerArray |
python | neetcode-gh__leetcode | python/0658-find-k-closest-elements.py | {
"start": 49,
"end": 953
} | class ____:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
l, r = 0, len(arr) - 1
# Find index of x or the closest val to x
val, idx = arr[0], 0
while l <= r:
m = (l + r) // 2
curDiff, resDiff = abs(arr[m] - x), abs(val - x)
... | Solution |
python | chroma-core__chroma | chromadb/api/collection_configuration.py | {
"start": 401,
"end": 626
} | class ____(TypedDict, total=False):
space: Space
ef_construction: int
max_neighbors: int
ef_search: int
num_threads: int
batch_size: int
sync_threshold: int
resize_factor: float
| HNSWConfiguration |
python | huggingface__transformers | src/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py | {
"start": 120552,
"end": 121026
} | class ____(BigBirdPegasusPreTrainedModel):
"""
This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
used in combination with the [`EncoderDecoderModel`] framework.
"""
def __init__(self, config):
super().__init__(config)
sel... | BigBirdPegasusDecoderWrapper |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/list1.py | {
"start": 520,
"end": 668
} | class ____(Generic[_T]):
def __get__(self, instance: Any, owner: Any) -> _T: ...
def __set__(self, instance: Any, value: _T) -> None: ...
| Baz |
python | django-guardian__django-guardian | guardian/testapp/migrations/0004_childtestmodel_parenttestmodel.py | {
"start": 126,
"end": 1173
} | class ____(migrations.Migration):
dependencies = [
("testapp", "0003_auto_20190611_0440"),
]
operations = [
migrations.CreateModel(
name="ParentTestModel",
fields=[
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_... | Migration |
python | pytorch__pytorch | test/mobile/lightweight_dispatch/tests_setup.py | {
"start": 1129,
"end": 1438
} | class ____(torch.nn.Module):
def forward(self, index):
a = torch.zeros(2, 2)
a[0][1] = 1
a[1][0] = 2
a[1][1] = 3
return a[index]
# gradient.scalarrayint(Tensor self, *, Scalar[] spacing, int? dim=None, int edge_order=1) -> Tensor[]
@save_model
| ModelWithTensorOptional |
python | huggingface__transformers | tests/trainer/test_trainer.py | {
"start": 9531,
"end": 10177
} | class ____:
def __init__(self, length=64, seed=42, batch_size=8):
self.length = length
np.random.seed(seed)
sizes = np.random.randint(1, 20, (length // batch_size,))
# For easy batching, we make every batch_size consecutive samples the same size.
self.xs = [np.random.normal(s... | DynamicShapesDataset |
python | kubernetes-client__python | kubernetes/client/models/v1_git_repo_volume_source.py | {
"start": 383,
"end": 5828
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1GitRepoVolumeSource |
python | pypa__setuptools | pkg_resources/tests/test_pkg_resources.py | {
"start": 15221,
"end": 17108
} | class ____:
def fake_site_packages(self, tmp_path, monkeypatch, dist_files):
site_packages = tmp_path / "site-packages"
site_packages.mkdir()
for file, content in self.FILES.items():
path = site_packages / file
path.parent.mkdir(exist_ok=True, parents=True)
... | TestWorkdirRequire |
python | fsspec__filesystem_spec | fsspec/implementations/dbfs.py | {
"start": 255,
"end": 607
} | class ____(Exception):
"""
Helper class for exceptions raised in this module.
"""
def __init__(self, error_code, message, details=None):
"""Create a new DatabricksException"""
super().__init__(message)
self.error_code = error_code
self.message = message
self.det... | DatabricksException |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 15576,
"end": 15861
} | class ____:
xlBox = 0 # from enum XlBarShape
xlConeToMax = 5 # from enum XlBarShape
xlConeToPoint = 4 # from enum XlBarShape
xlCylinder = 3 # from enum XlBarShape
xlPyramidToMax = 2 # from enum XlBarShape
xlPyramidToPoint = 1 # from enum XlBarShape
| BarShape |
python | ipython__ipython | tests/test_zzz_autoreload.py | {
"start": 5387,
"end": 22933
} | class ____(Fixture):
def test_reload_enums(self):
mod_name, mod_fn = self.new_module(
textwrap.dedent(
"""
from enum import Enum
class MyEnum(Enum):
A = 'A'
... | TestAutoreload |
python | numba__numba | numba/tests/test_import.py | {
"start": 107,
"end": 4197
} | class ____(TestCase):
"""
Test behaviour of importing Numba.
"""
def test_laziness(self):
"""
Importing top-level numba features should not import too many modules.
"""
# A heuristic set of modules that shouldn't be imported immediately
banlist = ['cffi',
... | TestNumbaImport |
python | joblib__joblib | joblib/_parallel_backends.py | {
"start": 18068,
"end": 19655
} | class ____(PoolManagerMixin, ParallelBackendBase):
"""A ParallelBackend which will use a thread pool to execute batches in.
This is a low-overhead backend but it suffers from the Python Global
Interpreter Lock if the called function relies a lot on Python objects.
Mostly useful when the execution bottl... | ThreadingBackend |
python | google__jax | jax/_src/interpreters/pxla.py | {
"start": 51032,
"end": 52391
} | class ____:
# `out_avals` is the `Array` global avals when using pjit. It is the
# local one when using `pmap`.
__slots__ = ("handlers", "out_shardings", "out_avals")
def __init__(self, handlers, out_shardings, out_avals):
self.handlers = handlers
self.out_shardings = out_shardings
self.out_avals =... | ResultsHandler |
python | python-excel__xlwt | xlwt/antlr.py | {
"start": 27049,
"end": 27836
} | class ____(object):
def __init__(self,ibuf):
assert isinstance(ibuf,InputBuffer)
self.input = ibuf
self.column = 1
self.line = 1
self.tokenStartColumn = 1
self.tokenStartLine = 1
self.guessing = 0
self.filename = None
def reset(self):
self... | LexerSharedInputState |
python | pytorch__pytorch | torch/_inductor/fuzzer.py | {
"start": 1878,
"end": 2324
} | class ____(CustomPartitionerFn):
"""
A Dummy partitioner function to be used by ConfigFuzzer
"""
def __call__(
self, gm: torch.fx.GraphModule, joint_inputs: Sequence[object], **kwargs: Any
) -> tuple[torch.fx.GraphModule, torch.fx.GraphModule]:
return min_cut_rematerialization_parti... | DummyPartitionerFn |
python | huggingface__transformers | src/transformers/models/gemma3n/modeling_gemma3n.py | {
"start": 69064,
"end": 72702
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: Gemma3nConfig, layer_idx: int):
super().__init__()
self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
self.config = config
... | Gemma3nAttention |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/sort_by_all.py | {
"start": 122,
"end": 168
} | class ____:
pass
def foobar():
pass
| Quux |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/dialects/mysql/mysql_stuff.py | {
"start": 236,
"end": 509
} | class ____(Base):
__tablename__ = "test_table_json"
id = mapped_column(Integer, primary_key=True)
data: Mapped[str] = mapped_column()
insert(Test).on_duplicate_key_update(
{"id": 42, Test.data: 99}, [("foo", 44)], data=99, id="foo"
).inserted.foo.desc()
| Test |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/orchestrator/orchestrator/models/ci_report.py | {
"start": 1055,
"end": 1898
} | class ____(BaseModel):
file_path: str
connector_technical_name: Optional[str] = None
connector_version: Optional[str] = None
run_timestamp: Optional[str] = None
run_duration: Optional[float] = None
success: Optional[bool] = None
failed_steps: Optional[List[str]] = None
successful_steps: ... | ConnectorPipelineReport |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/too_many_arguments.py | {
"start": 1260,
"end": 1416
} | class ____:
# `__new__` counts args like a classmethod
# even though it is an implicit staticmethod
def __new__(cls,a,b,c,d,e): # Ok
...
| Foo |
python | hynek__structlog | src/structlog/_output.py | {
"start": 2939,
"end": 3395
} | class ____:
r"""
Produce `PrintLogger`\ s.
To be used with `structlog.configure`\ 's ``logger_factory``.
Args:
file: File to print to. (default: `sys.stdout`)
Positional arguments are silently ignored.
.. versionadded:: 0.4.0
"""
def __init__(self, file: TextIO | None = None... | PrintLoggerFactory |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/diag_test.py | {
"start": 434,
"end": 1253
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, dim, M, N, diagonal, out, device):
self.inputs = {
"input": torch.rand(M, N, device=device)
if dim == 2
else torch.rand(M, device=device),
"diagonal": diagonal,
"out": out,
"out_te... | DiagBenchmark |
python | facebook__pyre-check | stubs/integration_test/fixture_source/integration_test/constructor_tito.py | {
"start": 498,
"end": 890
} | class ____(ParentWithoutConstructor):
def __init__(self, arg):
super(ChildWithoutParentConstructor, self).__init__(arg)
def test1():
tainted = source()
child = ChildWithParentConstructor(tainted)
sink(child.arg) # Issue.
def test2():
tainted = source()
child = ChildWithoutParentCons... | ChildWithoutParentConstructor |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_sparkline03.py | {
"start": 345,
"end": 5501
} | class ____(unittest.TestCase):
"""
Test assembling a complete Worksheet file.
"""
def test_assemble_xml_file(self):
"""Test writing a worksheet with no cell data."""
self.maxDiff = None
fh = StringIO()
worksheet = Worksheet()
worksheet._set_filehandle(fh)
... | TestAssembleWorksheet |
python | ray-project__ray | python/ray/_private/test_utils.py | {
"start": 50851,
"end": 53466
} | class ____(NodeKillerBase):
def __init__(self, *args, grace_period_s: int = 30, **kwargs):
super().__init__(*args, **kwargs)
self._grace_period_s = grace_period_s
self._kill_threads: Set[threading.Thread] = set()
def _kill_resource(self, node_id, node_to_kill_ip, _):
assert nod... | EC2InstanceTerminatorWithGracePeriod |
python | ray-project__ray | rllib/connectors/agent/view_requirement.py | {
"start": 500,
"end": 5288
} | class ____(AgentConnector):
"""This connector does 2 things:
1. It filters data columns based on view_requirements for training and inference.
2. It buffers the right amount of history for computing the sample batch for
action computation.
The output of this connector is AgentConnectorsOut, which... | ViewRequirementAgentConnector |
python | celery__celery | t/unit/events/test_cursesmon.py | {
"start": 47,
"end": 122
} | class ____:
def getmaxyx(self):
return self.y, self.x
| MockWindow |
python | pydata__xarray | xarray/tests/test_parallelcompat.py | {
"start": 582,
"end": 1502
} | class ____(np.ndarray):
"""
Mock-up of a chunked array class.
Adds a (non-functional) .chunks attribute by following this example in the numpy docs
https://numpy.org/doc/stable/user/basics.subclassing.html#simple-example-adding-an-extra-attribute-to-ndarray
"""
chunks: T_NormalizedChunks
... | DummyChunkedArray |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-twilio/components.py | {
"start": 5922,
"end": 8131
} | class ____(StateMigration):
"""
Reshape Message Media state to include hierarchical parent slices back to the
Messages collection. Low-code derives `message_media` partitions from `messages`,
so the state must retain the media-level `subresource_uri` and also include
`parent_slice.subresource_uri` p... | TwilioMessageMediaStateMigration |
python | django-guardian__django-guardian | example_project/posts/models.py | {
"start": 63,
"end": 631
} | class ____(models.Model):
title = models.CharField("title", max_length=64)
slug = models.SlugField(max_length=64)
content = models.TextField("content")
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
class Meta:
default_permissions = ("add", "change", "delete")
p... | Post |
python | PyCQA__bandit | tests/unit/core/test_blacklisting.py | {
"start": 158,
"end": 1316
} | class ____(testtools.TestCase):
def test_report_issue(self):
data = {"level": "HIGH", "message": "test {name}", "id": "B000"}
issue = blacklisting.report_issue(data, "name")
issue_dict = issue.as_dict(with_code=False)
self.assertIsInstance(issue_dict, dict)
self.assertEqual(... | BlacklistingTests |
python | PyCQA__pylint | tests/functional/u/undefined/undefined_variable_py30.py | {
"start": 2172,
"end": 2500
} | class ____(metaclass=abc.Metaclass):
"""Metaclasses can come from imported modules."""
# The following used to raise used-before-assignment
# pylint: disable=missing-docstring, multiple-statements
def used_before_assignment(*, arg): return arg + 1
# Test for #4021
# https://github.com/pylint-dev/pylint/issues/40... | FifthGood |
python | cython__cython | Cython/Debugger/libpython.py | {
"start": 61655,
"end": 62318
} | class ____(gdb.Command):
'Display the current python frame and all the frames within its call stack (if any)'
def __init__(self):
gdb.Command.__init__ (self,
"py-bt-full",
gdb.COMMAND_STACK,
gdb.COMPLETE_NONE)
... | PyBacktraceFull |
python | pytorch__pytorch | torch/distributed/tensor/experimental/_context_parallel/_attention.py | {
"start": 7077,
"end": 7357
} | class ____(ABC):
@abstractmethod
def __init__(self, pg: dist.ProcessGroup, seq_dim: int) -> None: ...
@abstractmethod
def exchange_buffers(self, curr_buffer: torch.Tensor) -> None: ...
@abstractmethod
def next_buffer(self) -> torch.Tensor: ...
| _RingRotater |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_bool.py | {
"start": 568,
"end": 15812
} | class ____(__TestCase):
def test_subclass(self):
try:
with torch._dynamo.error_on_graph_break(False):
class C(bool):
pass
except TypeError:
pass
else:
self.fail("bool should not be subclassable")
self.assertRai... | BoolTest |
python | great-expectations__great_expectations | great_expectations/expectations/core/expect_column_value_lengths_to_equal.py | {
"start": 2205,
"end": 13982
} | class ____(ColumnMapExpectation):
__doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION}
This expectation only works for string-type values. Invoking it on ints or floats will raise a TypeError.
ExpectColumnValueLengthsToEqual is a \
Column Map Expectation.
Column Map Expectations are one of the most comm... | ExpectColumnValueLengthsToEqual |
python | numba__numba | numba/core/extending.py | {
"start": 17855,
"end": 18971
} | class ____(collections.namedtuple(
'_SentryLiteralArgs', ['literal_args'])):
"""
Parameters
----------
literal_args : Sequence[str]
A sequence of names for literal arguments
Examples
--------
The following line:
>>> SentryLiteralArgs(literal_args).for_pysig(pysig).bind... | SentryLiteralArgs |
python | ray-project__ray | rllib/evaluation/tests/test_rollout_worker.py | {
"start": 1372,
"end": 2055
} | class ____(RandomPolicy):
@override(RandomPolicy)
def compute_actions(
self,
obs_batch,
state_batches=None,
prev_action_batch=None,
prev_reward_batch=None,
episodes=None,
explore=None,
timestep=None,
**kwargs
):
return np.array(... | MockPolicy |
python | huggingface__transformers | src/transformers/models/maskformer/modeling_maskformer.py | {
"start": 61262,
"end": 62956
} | class ____(nn.Module):
def __init__(self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int = 3):
"""
A classic Multi Layer Perceptron (MLP).
Args:
input_dim (`int`):
The input dimensions.
hidden_dim (`int`):
The hidden... | MaskformerMLPPredictionHead |
python | PyCQA__pylint | tests/functional/m/missing/missing_docstring.py | {
"start": 258,
"end": 313
} | class ____:
"""It has a docstring."""
| ClassDocumented |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 105122,
"end": 105259
} | class ____(BaseModel, extra="forbid"):
shard_id: int = Field(..., description="")
peer_id: int = Field(..., description="")
| Replica |
python | tornadoweb__tornado | tornado/test/simple_httpclient_test.py | {
"start": 2423,
"end": 2571
} | class ____(RequestHandler):
def options(self):
self.set_header("Access-Control-Allow-Origin", "*")
self.write("ok")
| OptionsHandler |
python | django__django | tests/admin_inlines/models.py | {
"start": 7727,
"end": 7906
} | class ____(models.Model):
name = models.CharField(max_length=100)
parent = models.ForeignKey("self", models.SET_NULL, null=True, blank=True)
# Models for #19524
| BinaryTree |
python | django-debug-toolbar__django-debug-toolbar | tests/panels/test_alerts.py | {
"start": 141,
"end": 4452
} | class ____(BaseTestCase):
panel_id = "AlertsPanel"
def test_alert_warning_display(self):
"""
Test that the panel (does not) display[s] an alert when there are
(no) problems.
"""
self.panel.record_stats({"alerts": []})
self.assertNotIn("alerts", self.panel.nav_sub... | AlertsPanelTestCase |
python | google__pytype | pytype/pytd/optimize.py | {
"start": 3071,
"end": 3811
} | class ____:
"""Mutable class for collecting return types and exceptions of functions.
The collecting is stable: Items are kept in the order in which they were
encountered.
Attributes:
return_types: Return types seen so far.
exceptions: Exceptions seen so far.
"""
def __init__(self):
self.retu... | _ReturnsAndExceptions |
python | django__django | tests/staticfiles_tests/test_checks.py | {
"start": 464,
"end": 4725
} | class ____(CollectionTestCase):
run_collectstatic_in_setUp = False
def test_base_finder_check_not_implemented(self):
finder = BaseFinder()
msg = (
"subclasses may provide a check() method to verify the finder is "
"configured correctly."
)
with self.asser... | FindersCheckTests |
python | spack__spack | lib/spack/spack/test/oci/mock_registry.py | {
"start": 11805,
"end": 13044
} | class ____(InMemoryOCIRegistry):
"""This is another in-memory OCI registry requiring basic authentication."""
def __init__(
self, domain, username: str, password: str, realm: str, allow_single_post: bool = True
) -> None:
super().__init__(domain, allow_single_post)
self.username = u... | InMemoryOCIRegistryWithBasicAuth |
python | plotly__plotly.py | plotly/graph_objs/volume/_surface.py | {
"start": 233,
"end": 6688
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "volume"
_path_str = "volume.surface"
_valid_props = {"count", "fill", "pattern", "show"}
@property
def count(self):
"""
Sets the number of iso-surfaces between minimum and maximum
iso-values. By default this value is 2... | Surface |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 148908,
"end": 150090
} | class ____(TestCase):
def test_no_exceptions_pass(self):
iterable = '0123'
actual = list(mi.filter_except(int, iterable))
expected = ['0', '1', '2', '3']
self.assertEqual(actual, expected)
def test_no_exceptions_raise(self):
iterable = ['0', '1', 'two', '3']
with... | FilterExceptTests |
python | pypa__pipenv | pipenv/vendor/pipdeptree/_models/dag.py | {
"start": 820,
"end": 10056
} | class ____(Mapping[DistPackage, List[ReqPackage]]):
"""
Representation of Package dependencies as directed acyclic graph using a dict as the underlying datastructure.
The nodes and their relationships (edges) are internally stored using a map as follows,
{a: [b, c],
b: [d],
c: [d, e],
d... | PackageDAG |
python | tiangolo__fastapi | docs_src/app_testing/app_b_an/main.py | {
"start": 373,
"end": 1205
} | class ____(BaseModel):
id: str
title: str
description: Union[str, None] = None
@app.get("/items/{item_id}", response_model=Item)
async def read_main(item_id: str, x_token: Annotated[str, Header()]):
if x_token != fake_secret_token:
raise HTTPException(status_code=400, detail="Invalid X-Token h... | Item |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 273300,
"end": 274569
} | class ____(ConditionalValueDefstringExprRef):
"""
ConditionalPredicateValueDefstringExprRef schema wrapper.
Parameters
----------
test : str, dict, :class:`Predicate`, :class:`FieldGTPredicate`, :class:`FieldLTPredicate`, :class:`FieldGTEPredicate`, :class:`FieldLTEPredicate`, :class:`LogicalOrPred... | ConditionalPredicateValueDefstringExprRef |
python | cython__cython | Cython/Plex/Errors.py | {
"start": 566,
"end": 976
} | class ____(PlexError):
scanner = None
position = None
state_name = None
def __init__(self, scanner, state_name):
self.scanner = scanner
self.position = scanner.get_position()
self.state_name = state_name
def __str__(self):
return ("'%s', line %d, char %d: Token not ... | UnrecognizedInput |
python | apache__airflow | providers/fab/tests/unit/fab/www/views/test_views_custom_user_views.py | {
"start": 2969,
"end": 6454
} | class ____:
@pytest.fixture(autouse=True)
def app_context(self, app):
with app.app_context():
delete_roles(app)
yield
delete_user(app, "no_access")
delete_user(app, "has_access")
@pytest.mark.parametrize(("url", "_", "expected_text"), PERMISSIONS_TEST... | TestSecurity |
python | doocs__leetcode | lcof2/剑指 Offer II 095. 最长公共子序列/Solution.py | {
"start": 0,
"end": 453
} | class ____:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
m, n = len(text1), len(text2)
f = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if text1[i - 1] == text2[j - 1]:
f[i][j] ... | Solution |
python | pypa__pip | src/pip/_vendor/rich/progress.py | {
"start": 32381,
"end": 36471
} | class ____:
"""Information regarding a progress task.
This object should be considered read-only outside of the :class:`~Progress` class.
"""
id: TaskID
"""Task ID associated with this task (used in Progress methods)."""
description: str
"""str: Description of the task."""
total: Op... | Task |
python | jazzband__django-simple-history | simple_history/tests/tests/test_utils.py | {
"start": 23363,
"end": 23823
} | class ____(TestCase):
def test_update_change_reason_with_excluded_fields(self):
poll = PollWithExcludeFields(
question="what's up?", pub_date=timezone.now(), place="The Pub"
)
poll.save()
update_change_reason(poll, "Test change reason.")
most_recent = poll.history... | UpdateChangeReasonTestCase |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/visitors.py | {
"start": 12416,
"end": 14288
} | class ____:
"""base for classes that have a "traverse internals" element,
which defines all kinds of ways of traversing the elements of an object.
Compared to :class:`.Visitable`, which relies upon an external visitor to
define how the object is travered (i.e. the :class:`.SQLCompiler`), the
:class... | HasTraverseInternals |
python | getsentry__sentry | tests/sentry/middleware/test_subdomain.py | {
"start": 2919,
"end": 3401
} | class ____(Endpoint):
permission_classes = (AllowAny,)
def get(self, request):
# return HttpResponse(status=status.HTTP_200_OK)
return Response(
{
"subdomain": request.subdomain,
}
)
urlpatterns = [
re_path(
r"^api/0/test/$",
... | APITestEndpoint |
python | kamyu104__LeetCode-Solutions | Python/binary-searchable-numbers-in-an-unsorted-array.py | {
"start": 30,
"end": 546
} | class ____(object):
def binarySearchableNumbers(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
right = [float("inf")]*(len(nums)+1)
for i in reversed(xrange(1, len(nums)+1)):
right[i-1] = min(right[i], nums[i-1])
result, left = set(), float... | Solution |
python | huggingface__transformers | src/transformers/models/speecht5/modeling_speecht5.py | {
"start": 27904,
"end": 30075
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.layers = nn.ModuleList(
[
nn.Linear(
config.num_mel_bins if i == 0 else config.speech_decoder_prenet_units,
config.speech_decod... | SpeechT5SpeechDecoderPrenet |
python | numba__numba | numba/tests/test_array_constants.py | {
"start": 956,
"end": 4578
} | class ____(TestCase):
"""
Test array constants.
"""
def check_array_const(self, pyfunc):
cfunc = njit((types.int32,))(pyfunc)
for i in [0, 1, 2]:
np.testing.assert_array_equal(pyfunc(i), cfunc(i))
def test_array_const_0d(self):
self.check_array_const(getitem0)
... | TestConstantArray |
python | PrefectHQ__prefect | src/prefect/infrastructure/provisioners/modal.py | {
"start": 771,
"end": 9142
} | class ____:
"""
A infrastructure provisioner for Modal push work pools.
"""
def __init__(self, client: Optional["PrefectClient"] = None):
self._console: Console = Console()
@property
def console(self) -> Console:
return self._console
@console.setter
def console(self, v... | ModalPushProvisioner |
python | kamyu104__LeetCode-Solutions | Python/make-the-string-great.py | {
"start": 29,
"end": 400
} | class ____(object):
def makeGood(self, s):
"""
:type s: str
:rtype: str
"""
stk = []
for ch in s:
counter_ch = ch.upper() if ch.islower() else ch.lower()
if stk and stk[-1] == counter_ch:
stk.pop()
else:
... | Solution |
python | run-llama__llama_index | llama-index-finetuning/llama_index/finetuning/cross_encoders/dataset_gen.py | {
"start": 500,
"end": 9797
} | class ____:
"""Class for keeping track of each item of Cross-Encoder training Dataset."""
query: str
context: str
score: int
DEFAULT_QUERY_GEN_SYSTEM_PROMPT = """You are Albert a Professor proficient in {qa_topic}.
You are working on creating {num_questions_per_chunk} questions.
You provide the quest... | CrossEncoderFinetuningDatasetSample |
python | Netflix__metaflow | metaflow/plugins/azure/azure_secret_manager_secrets_provider.py | {
"start": 627,
"end": 762
} | class ____(MetaflowException):
"""Raised when the secret path does not match to expected length"""
| MetaflowAzureKeyVaultBadSecretPath |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/call_graph.py | {
"start": 925,
"end": 2052
} | class ____:
args: tuple[object, ...] | Mapping[str, object] | None = None
def __init__(self) -> None: ...
def is_dict(obj: object) -> TypeGuard[dict[object, object]]:
return isinstance(obj, dict)
def test_chained_assign_subscript(record: LogRecord):
if is_dict(record.args) and "headers" in record.a... | LogRecord |
python | ray-project__ray | doc/source/_ext/callouts.py | {
"start": 4254,
"end": 5307
} | class ____(SphinxDirective):
"""Annotations directive, which is only used nested within a Callout directive."""
has_content = True
def run(self):
content = self.content
content = _replace_numbers(content)
joined_content = "\n".join(content)
annotations_node = callout(joine... | AnnotationsDirective |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/bedrock.py | {
"start": 40185,
"end": 42318
} | class ____(AwsBaseOperator[BedrockAgentRuntimeHook]):
"""
Query a knowledge base and retrieve results with source citations.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:BedrockRetrieveOperator`
:param retrieval_query: Th... | BedrockRetrieveOperator |
python | spack__spack | var/spack/test_repos/spack_repo/tutorial/packages/elpa/package.py | {
"start": 228,
"end": 2753
} | class ____(AutotoolsPackage):
"""Eigenvalue solvers for Petaflop-Applications (ELPA)"""
homepage = "http://elpa.mpcdf.mpg.de/"
url = "http://elpa.mpcdf.mpg.de/elpa-2015.11.001.tar.gz"
version("2018.05.001.rc1", md5="ccd77bd8036988ee624f43c04992bcdd")
version("2017.11.001", md5="4a437be40cc966efb07... | Elpa |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.