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 | ray-project__ray | python/ray/exceptions.py | {
"start": 19592,
"end": 20300
} | class ____(RayError):
"""Indicates that the local disk is full.
This is raised if the attempt to store the object fails
because both the object store and disk are full.
"""
def __str__(self):
# TODO(scv119): expose more disk usage information and link to a doc.
return super(OutOfDi... | OutOfDiskError |
python | spyder-ide__spyder | spyder/plugins/run/api.py | {
"start": 5488,
"end": 5934
} | class ____(TypedDict):
"""Supported file extension and contexts schema."""
# File extension or identifier of the input context.
input_extension: str
# The supported contexts for the given input extension, e.g. file,
# selection, cell or others.
# The context can be compared against the values ... | SupportedExtensionContexts |
python | pytorch__pytorch | torch/_inductor/runtime/caching/interfaces.py | {
"start": 861,
"end": 956
} | class ____(Enum):
RECORD = "record"
GET = "get"
INSERT = "insert"
| _IntfCallbackOrigin |
python | tensorflow__tensorflow | tensorflow/core/function/trace_type/default_types_test.py | {
"start": 2227,
"end": 2549
} | class ____:
"""Helps test attrs collections."""
__attrs_attrs__ = (TestAttr('a'), TestAttr('b'))
def __init__(self, a, b):
self.a = a
self.b = b
def __eq__(self, other):
return (
isinstance(other, TestAttrsClass)
and self.a == other.a
and self.b == other.b
)
| TestAttrsClass |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor11.py | {
"start": 533,
"end": 800
} | class ____(Generic[K, V]):
def __init__(self, g: MyFuncType[K, V]) -> None:
self.g = g
MyFuncMapping = Mapping[K, Optional[MyFunc[K, V]]]
my_func_defaultdict: MyFuncMapping[str, int] = defaultdict(
lambda: None, {"x": MyFunc(lambda f: f("a"))}
)
| MyFunc |
python | ansible__ansible | lib/ansible/plugins/__init__.py | {
"start": 1723,
"end": 1944
} | class ____(t.Protocol):
"""Protocol to provide type-safe access to config for plugin-related mixins."""
def get_option(self, option: str, hostvars: dict[str, object] | None = None) -> t.Any: ...
| _ConfigurablePlugin |
python | google__jax | tests/tree_util_test.py | {
"start": 50669,
"end": 56459
} | class ____(jtu.JaxTestCase):
"""Simple smoke-tests for tree_util aliases under jax.tree"""
def test_tree_all(self):
obj = [True, True, (True, False)]
self.assertEqual(
jax.tree.all(obj),
tree_util.tree_all(obj),
)
def test_tree_all_is_leaf(self):
obj = [True, True, (True, False)]
... | TreeAliasTest |
python | tensorflow__tensorflow | tensorflow/python/tools/api/generator2/extractor/extractor.py | {
"start": 1391,
"end": 1461
} | class ____(Exception):
"""Exception for bad exports."""
| BadExportError |
python | pandas-dev__pandas | pandas/tests/tseries/offsets/test_offsets.py | {
"start": 26683,
"end": 28057
} | class ____:
def test_get_offset_name(self):
assert BDay().freqstr == "B"
assert BDay(2).freqstr == "2B"
assert BMonthEnd().freqstr == "BME"
assert Week(weekday=0).freqstr == "W-MON"
assert Week(weekday=1).freqstr == "W-TUE"
assert Week(weekday=2).freqstr == "W-WED"
... | TestOffsetNames |
python | sqlalchemy__sqlalchemy | test/sql/test_syntax_extensions.py | {
"start": 2215,
"end": 2476
} | class ____(SyntaxExtension, ClauseElement):
_traverse_internals = []
def apply_to_select(self, select_stmt):
select_stmt.apply_syntax_extension_point(
lambda existing: [self],
"post_criteria",
)
| PostCriteriaClause3 |
python | plotly__plotly.py | plotly/graph_objs/layout/polar/_domain.py | {
"start": 235,
"end": 5045
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.polar"
_path_str = "layout.polar.domain"
_valid_props = {"column", "row", "x", "y"}
@property
def column(self):
"""
If there is a layout grid, use the domain for this column in
the grid for this polar subplot .... | Domain |
python | optuna__optuna | optuna/artifacts/_protocol.py | {
"start": 151,
"end": 1803
} | class ____(Protocol):
"""A protocol defining the interface for an artifact backend.
The methods defined in this protocol are not supposed to be directly called by library users.
An artifact backend is responsible for managing the storage and retrieval
of artifact data. The backend should provide metho... | ArtifactStore |
python | walkccc__LeetCode | solutions/1927. Sum Game/1927.py | {
"start": 0,
"end": 325
} | class ____:
def sumGame(self, num: str) -> bool:
n = len(num)
ans = 0.0
def getExpectation(c: str) -> float:
return 4.5 if c == '?' else int(c)
for i in range(n // 2):
ans += getExpectation(num[i])
for i in range(n // 2, n):
ans -= getExpectation(num[i])
return ans != 0.0... | Solution |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 104541,
"end": 105038
} | class ____(Structure):
_fields_ = [("multiprocessorCount", c_uint),
("sharedCopyEngineCount", c_uint),
("sharedDecoderCount", c_uint),
("sharedEncoderCount", c_uint),
("sharedJpegCount", c_uint),
("sharedOfaCount", c_uint),
... | c_nvmlDeviceAttributes |
python | django__django | tests/staticfiles_tests/storage.py | {
"start": 594,
"end": 1441
} | class ____(storage.Storage):
def _save(self, name, content):
return "dummy"
def _path(self, name):
return os.path.join(settings.STATIC_ROOT, name)
def exists(self, name):
return os.path.exists(self._path(name))
def listdir(self, path):
path = self._path(path)
d... | PathNotImplementedStorage |
python | doocs__leetcode | solution/1600-1699/1676.Lowest Common Ancestor of a Binary Tree IV/Solution.py | {
"start": 164,
"end": 601
} | class ____:
def lowestCommonAncestor(
self, root: 'TreeNode', nodes: 'List[TreeNode]'
) -> 'TreeNode':
def dfs(root):
if root is None or root.val in s:
return root
left, right = dfs(root.left), dfs(root.right)
if left and right:
... | Solution |
python | scrapy__scrapy | scrapy/commands/__init__.py | {
"start": 534,
"end": 4465
} | class ____(ABC):
requires_project: bool = False
requires_crawler_process: bool = True
crawler_process: CrawlerProcessBase | None = None # set in scrapy.cmdline
# default settings to be used for this command instead of global defaults
default_settings: dict[str, Any] = {}
exitcode: int = 0
... | ScrapyCommand |
python | plotly__plotly.py | tests/test_optional/test_figure_factory/test_figure_factory.py | {
"start": 51608,
"end": 64259
} | class ____(NumpyTestUtilsMixin, TestCaseNoTemplate):
def test_dataframe_input(self):
# check: dataframe is imported
df = "foo"
pattern = (
"Dataframe not inputed. Please use a pandas dataframe to produce "
"a scatterplot matrix."
)
self.assertRaisesR... | TestScatterPlotMatrix |
python | pytorch__pytorch | test/test_overrides.py | {
"start": 50790,
"end": 51138
} | class ____(TestCase):
def test_resolve_name(self):
for cs in get_overridable_functions().values():
for c in cs:
self.assertEqual(
eval(torch.overrides.resolve_name(c)),
c,
msg=f"{c}, {torch.overrides.resolve_name(c)}"
... | TestResolveName |
python | joke2k__faker | faker/providers/internet/hr_HR/__init__.py | {
"start": 46,
"end": 654
} | class ____(InternetProvider):
free_email_domains = (
"gmail.com",
"hotmail.com",
"yahoo.com",
"net.hr",
"zg.t-com.hr",
"inet.hr",
"t.ht.hr",
"vip.hr",
"globalnet.hr",
"xnet.hr",
"yahoo.hr",
"zagreb.hr",
)
tlds =... | Provider |
python | bokeh__bokeh | src/bokeh/models/tools.py | {
"start": 8780,
"end": 9042
} | class ____(GestureTool):
''' A base class for tools that respond to scroll events.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@abstract
| Scroll |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/dev_build_test_install/package.py | {
"start": 225,
"end": 898
} | class ____(MakefilePackage):
homepage = "example.com"
url = "fake.com"
version("0.0.0", sha256="0123456789abcdef0123456789abcdef")
filename = "dev-build-test-file.txt"
original_string = "This file should be edited"
replacement_string = "This file has been edited"
def edit(self, spec, pref... | DevBuildTestInstall |
python | vyperlang__vyper | vyper/semantics/analysis/base.py | {
"start": 5198,
"end": 5355
} | class ____(AnalysisResult):
used_modules: list[ModuleInfo]
node: Optional[vy_ast.VyperNode] = None
# analysis result of ExportsDecl
@dataclass
| UsesInfo |
python | doocs__leetcode | solution/2000-2099/2040.Kth Smallest Product of Two Sorted Arrays/Solution.py | {
"start": 0,
"end": 615
} | class ____:
def kthSmallestProduct(self, nums1: List[int], nums2: List[int], k: int) -> int:
def count(p: int) -> int:
cnt = 0
n = len(nums2)
for x in nums1:
if x > 0:
cnt += bisect_right(nums2, p / x)
elif x < 0:
... | Solution |
python | plotly__plotly.py | plotly/graph_objs/scattergl/_error_y.py | {
"start": 233,
"end": 14397
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattergl"
_path_str = "scattergl.error_y"
_valid_props = {
"array",
"arrayminus",
"arrayminussrc",
"arraysrc",
"color",
"symmetric",
"thickness",
"traceref",
"tracerefminus",
... | ErrorY |
python | google__flatbuffers | tests/MyGame/Example/StructOfStructs.py | {
"start": 176,
"end": 1284
} | class ____(object):
__slots__ = ['_tab']
@classmethod
def SizeOf(cls):
return 20
# StructOfStructs
def Init(self, buf, pos):
self._tab = flatbuffers.table.Table(buf, pos)
# StructOfStructs
def A(self, obj):
obj.Init(self._tab.Bytes, self._tab.Pos + 0)
retur... | StructOfStructs |
python | spack__spack | lib/spack/spack/vendor/jinja2/nodes.py | {
"start": 11677,
"end": 11993
} | class ____(Stmt):
"""Like a macro without a name but a call instead. `call` is called with
the unnamed macro as `caller` argument this node holds.
"""
fields = ("call", "args", "defaults", "body")
call: "Call"
args: t.List["Name"]
defaults: t.List["Expr"]
body: t.List[Node]
| CallBlock |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_bigtable.py | {
"start": 6920,
"end": 26705
} | class ____:
def setup_method(self):
with mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__",
new=mock_base_gcp_hook_default_project_id,
):
self.bigtable_hook_default_project_id = BigtableHook(gcp_conn_id="test")
@mock.patc... | TestBigtableHookDefaultProjectId |
python | pytorch__pytorch | benchmarks/gpt_fast/quantize.py | {
"start": 2775,
"end": 3565
} | class ____(torch.nn.Module):
__constants__ = ["in_features", "out_features"]
in_features: int
out_features: int
weight: torch.Tensor
def __init__(
self,
in_features: int,
out_features: int,
bias: bool = True,
device=None,
dtype=None,
) -> None:
... | WeightOnlyInt8Linear |
python | plotly__plotly.py | _plotly_utils/basevalidators.py | {
"start": 71883,
"end": 73769
} | class ____(BaseValidator):
_PIL = None
try:
_PIL = import_module("PIL")
except ImportError:
pass
def __init__(self, plotly_name, parent_name, **kwargs):
super(ImageUriValidator, self).__init__(
plotly_name=plotly_name, parent_name=parent_name, **kwargs
)
... | ImageUriValidator |
python | pytorch__pytorch | torch/serialization.py | {
"start": 2938,
"end": 3226
} | class ____(threading.local):
def __init__(self):
super().__init__()
self.map_location: Optional[MAP_LOCATION] = None
self.skip_data: bool = False
self.materialize_fake_tensors: bool = False
_serialization_tls = _SerializationLocal()
| _SerializationLocal |
python | anthropics__anthropic-sdk-python | src/anthropic/_base_client.py | {
"start": 47993,
"end": 51396
} | class ____(httpx.AsyncClient):
def __init__(self, **kwargs: Any) -> None:
kwargs.setdefault("timeout", DEFAULT_TIMEOUT)
kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS)
kwargs.setdefault("follow_redirects", True)
if "transport" not in kwargs:
socket_options: List[T... | _DefaultAsyncHttpxClient |
python | google__jax | jax/_src/pallas/pipelining/internal.py | {
"start": 1739,
"end": 2501
} | class ____:
"""An internal representation of a pipeline stage."""
jaxpr: jax_core.ClosedJaxpr
effects: set[RefEffect]
properties: SchedulingProperties
name: str
def get_read_idxs(self) -> set[BufferIndex]:
"""Returns the buffer indices that this stage reads from."""
return {
effect.input_in... | PipelineStage |
python | scipy__scipy | benchmarks/benchmarks/sparse_linalg_spsolve_triangular.py | {
"start": 766,
"end": 1298
} | class ____(Benchmark):
params = [
[100,1000],
["spsolve", "spsolve_triangular"],
]
param_names = ['(n,n)',"method"]
def setup(self, n, method):
self.b = np.ones(n*n)
self.P_sparse = _create_sparse_poisson2d_half(n)
def time_solve(self, n, method):
if method ... | Bench |
python | fluentpython__example-code | 13-op-overloading/vector_v6.py | {
"start": 5678,
"end": 8834
} | class ____:
typecode = 'd'
def __init__(self, components):
self._components = array(self.typecode, components)
def __iter__(self):
return iter(self._components)
def __repr__(self):
components = reprlib.repr(self._components)
components = components[components.find('[')... | Vector |
python | tensorflow__tensorflow | tensorflow/python/keras/legacy_tf_layers/pooling.py | {
"start": 939,
"end": 3663
} | class ____(keras_layers.AveragePooling1D, base.Layer):
"""Average Pooling layer for 1D inputs.
Args:
pool_size: An integer or tuple/list of a single integer,
representing the size of the pooling window.
strides: An integer or tuple/list of a single integer, specifying the
strides of the pooling... | AveragePooling1D |
python | realpython__materials | python-built-in-exceptions/square.py | {
"start": 0,
"end": 343
} | class ____:
def __init__(self, values):
self.values = values
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index >= len(self.values):
raise StopIteration
square = self.values[self.index] ** 2
self.index += 1
r... | SquareIterator |
python | python-markdown__markdown | tests/test_syntax/extensions/test_admonition.py | {
"start": 781,
"end": 6873
} | class ____(TestCase):
def test_with_lists(self):
self.assertMarkdownRenders(
self.dedent(
'''
- List
!!! note "Admontion"
- Paragraph
Paragraph
'''
),
... | TestAdmonition |
python | pytorch__pytorch | benchmarks/fastrnns/custom_lstms.py | {
"start": 6928,
"end": 7486
} | class ____(jit.ScriptModule):
def __init__(self, cell, *cell_args):
super().__init__()
self.cell = cell(*cell_args)
@jit.script_method
def forward(
self, input: Tensor, state: tuple[Tensor, Tensor]
) -> tuple[Tensor, tuple[Tensor, Tensor]]:
inputs = reverse(input.unbind(... | ReverseLSTMLayer |
python | MongoEngine__mongoengine | mongoengine/queryset/field_list.py | {
"start": 32,
"end": 2964
} | class ____:
"""Object that handles combinations of .only() and .exclude() calls"""
ONLY = 1
EXCLUDE = 0
def __init__(
self, fields=None, value=ONLY, always_include=None, _only_called=False
):
"""The QueryFieldList builder
:param fields: A list of fields used in `.only()` o... | QueryFieldList |
python | doocs__leetcode | solution/0200-0299/0247.Strobogrammatic Number II/Solution.py | {
"start": 0,
"end": 474
} | class ____:
def findStrobogrammatic(self, n: int) -> List[str]:
def dfs(u):
if u == 0:
return ['']
if u == 1:
return ['0', '1', '8']
ans = []
for v in dfs(u - 2):
for l, r in ('11', '88', '69', '96'):
... | Solution |
python | django__django | tests/generic_relations_regress/models.py | {
"start": 3735,
"end": 3982
} | class ____(models.Model):
flag = models.BooleanField(null=True)
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey("content_type", "object_id")
| A |
python | aimacode__aima-python | probability.py | {
"start": 5226,
"end": 6556
} | class ____:
"""Bayesian network containing only boolean-variable nodes."""
def __init__(self, node_specs=None):
"""Nodes must be ordered with parents before children."""
self.nodes = []
self.variables = []
node_specs = node_specs or []
for node_spec in node_specs:
... | BayesNet |
python | streamlit__streamlit | lib/streamlit/elements/lib/column_types.py | {
"start": 5135,
"end": 5388
} | class ____(TypedDict):
type: Literal["time"]
format: NotRequired[str | Literal["localized", "iso8601"] | None]
min_value: NotRequired[str | None]
max_value: NotRequired[str | None]
step: NotRequired[int | float | None]
| TimeColumnConfig |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataflow.py | {
"start": 2180,
"end": 8066
} | class ____:
"""
Dataflow configuration for BeamRunJavaPipelineOperator and BeamRunPythonPipelineOperator.
.. seealso::
:class:`~airflow.providers.apache.beam.operators.beam.BeamRunJavaPipelineOperator`
and :class:`~airflow.providers.apache.beam.operators.beam.BeamRunPythonPipelineOperator`.... | DataflowConfiguration |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/plan/handle.py | {
"start": 2406,
"end": 3532
} | class ____(
NamedTuple(
"_ResolvedFromDynamicStepHandle",
[("node_handle", NodeHandle), ("mapping_key", str), ("key", str)],
)
):
"""A reference to an ExecutionStep that came from resolving an UnresolvedMappedExecutionStep
(and associated UnresolvedStepHandle) downstream of a dynamic out... | ResolvedFromDynamicStepHandle |
python | pypa__pipenv | pipenv/patched/pip/_vendor/distlib/database.py | {
"start": 11313,
"end": 16293
} | class ____(object):
"""
A base class for distributions, whether installed or from indexes.
Either way, it must have some metadata, so that's all that's needed
for construction.
"""
build_time_dependency = False
"""
Set to True if it's known to be only a build-time dependency (i.e.
n... | Distribution |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 61690,
"end": 64639
} | class ____(rv_continuous):
r"""An exponential continuous random variable.
%(before_notes)s
Notes
-----
The probability density function for `expon` is:
.. math::
f(x) = \exp(-x)
for :math:`x \ge 0`.
%(after_notes)s
A common parameterization for `expon` is in terms of t... | expon_gen |
python | ray-project__ray | python/ray/dashboard/modules/job/tests/test_job_manager_standalone.py | {
"start": 321,
"end": 2600
} | class ____:
"""NOTE: PLEASE READ CAREFULLY BEFORE MODIFYING
This test is extracted into a standalone module such that it can bootstrap its own
(standalone) Ray cluster while avoiding affecting the shared one used by other
JobManager tests
"""
@pytest.mark.parametrize(
"tracing_enabled",... | TestRuntimeEnvStandalone |
python | cython__cython | Cython/Compiler/Tests/TestTreeFragment.py | {
"start": 160,
"end": 2155
} | class ____(CythonTest):
def test_basic(self):
F = self.fragment("x = 4")
T = F.copy()
self.assertCode("x = 4", T)
def test_copy_is_taken(self):
F = self.fragment("if True: x = 4")
T1 = F.root
T2 = F.copy()
self.assertEqual("x", T2.stats[0].if_clauses[0].... | TestTreeFragments |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-oci-data-science/tests/test_oci_data_science_utils.py | {
"start": 5322,
"end": 6916
} | class ____:
"""Unit tests for _from_token_logprob_dicts function."""
def test_conversion(self):
"""Ensures multiple token logprobs are converted correctly."""
token_logprob_dicts = [
{
"token": "Hello",
"logprob": -0.1,
"top_logprobs"... | TestFromTokenLogprobs |
python | PrefectHQ__prefect | src/integrations/prefect-gitlab/prefect_gitlab/credentials.py | {
"start": 248,
"end": 3167
} | class ____(Block):
"""
Store a GitLab personal access token to interact with private GitLab
repositories.
Attributes:
token: The personal access token to authenticate with GitLab.
url: URL to self-hosted GitLab instances.
Examples:
Load stored GitLab credentials:
``... | GitLabCredentials |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/comments.py | {
"start": 22457,
"end": 22722
} | class ____(Sized):
__slots__ = ('_mapping',)
def __init__(self, mapping):
# type: (Any) -> None
self._mapping = mapping
def __len__(self):
# type: () -> int
count = len(self._mapping)
return count
| CommentedMapView |
python | readthedocs__readthedocs.org | readthedocs/builds/migrations/0023_add_status_code.py | {
"start": 149,
"end": 565
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("builds", "0022_migrate_protected_versions"),
]
operations = [
migrations.AddField(
model_name="build",
name="status_code",
field=models.BooleanField(
blank... | Migration |
python | tqdm__tqdm | tqdm/dask.py | {
"start": 178,
"end": 1319
} | class ____(Callback):
"""Dask callback for task progress."""
def __init__(self, start=None, pretask=None, tqdm_class=tqdm_auto,
**tqdm_kwargs):
"""
Parameters
----------
tqdm_class : optional
`tqdm` class to use for bars [default: `tqdm.auto.tqdm`].
... | TqdmCallback |
python | ansible__ansible | lib/ansible/galaxy/dependency_resolution/providers.py | {
"start": 1515,
"end": 19310
} | class ____(AbstractProvider):
"""Delegate providing a requirement interface for the resolver."""
def __init__(
self,
apis: MultiGalaxyAPIProxy,
concrete_artifacts_manager: ConcreteArtifactsManager,
preferred_candidates: _c.Iterable[Candidate] | None = None,
... | CollectionDependencyProvider |
python | pytest-dev__pytest | testing/example_scripts/unittest/test_setup_skip_module.py | {
"start": 229,
"end": 297
} | class ____(unittest.TestCase):
def test(self):
assert 0
| Base |
python | apache__airflow | providers/edge3/tests/unit/edge3/cli/test_dataclasses.py | {
"start": 1031,
"end": 1255
} | class ____:
def test_maintenance_marker_json(self):
marker = MaintenanceMarker(maintenance="maintenance", comments="comments")
assert marker == MaintenanceMarker.from_json(marker.json)
| TestMaintenanceMarker |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/class_interval.py | {
"start": 3642,
"end": 3725
} | class ____:
def foo(self, x):
return _test_source() # Interval: [3,4]
| B8 |
python | huggingface__transformers | src/transformers/models/maskformer/modeling_maskformer_swin.py | {
"start": 13421,
"end": 18071
} | class ____(nn.Module):
def __init__(self, config, dim, num_heads, window_size):
super().__init__()
if dim % num_heads != 0:
raise ValueError(
f"The hidden size ({dim}) is not a multiple of the number of attention heads ({num_heads})"
)
self.num_attent... | MaskFormerSwinSelfAttention |
python | pytorch__pytorch | torch/cuda/memory.py | {
"start": 1079,
"end": 1238
} | class ____(TypedDict):
"""Memory block information."""
size: int
requested_size: int
address: int
state: str
frames: list[_Frame]
| _Block |
python | realpython__materials | pyqt-calculator-tutorial/pycalc/pycalc.py | {
"start": 2262,
"end": 3588
} | class ____:
"""PyCalc's controller class."""
def __init__(self, model, view):
self._evaluate = model
self._view = view
self._connectSignalsAndSlots()
def _calculateResult(self):
result = self._evaluate(expression=self._view.displayText())
self._view.setDisplayText(r... | PyCalc |
python | chroma-core__chroma | chromadb/segment/impl/vector/hnsw_params.py | {
"start": 2485,
"end": 3162
} | class ____(HnswParams):
batch_size: int
sync_threshold: int
def __init__(self, metadata: Metadata):
super().__init__(metadata)
self.batch_size = int(metadata.get("hnsw:batch_size", 100))
self.sync_threshold = int(metadata.get("hnsw:sync_threshold", 1000))
@staticmethod
def ... | PersistentHnswParams |
python | numba__numba | numba/tests/test_dictobject.py | {
"start": 34652,
"end": 35488
} | class ____(TestCase, DictIterableCtor):
def setUp(self):
self.jit_enabled = True
def test_exception_no_iterable_arg(self):
@njit
def ctor():
return Dict(3)
msg = ".*No implementation of function.*"
with self.assertRaisesRegex(TypingError, msg):
... | TestDictIterableCtorJit |
python | nryoung__algorithms | tests/test_sorting.py | {
"start": 4176,
"end": 4423
} | class ____(SortingAlgorithmTestCase):
"""
Tests Strand sort on a small range from 0-9
"""
def test_strandsort(self):
self.output = strand_sort.sort(self.input)
self.assertEqual(self.correct, self.output)
| TestStrandSort |
python | ray-project__ray | python/ray/tests/conftest_docker.py | {
"start": 7631,
"end": 8566
} | class ____:
def __call__(self):
with open("file.txt") as f:
return f.read().strip()
app = Model.bind()
"""
run_in_container(
[
["bash", "-c", "echo helloworldalice >> /tmp/file.txt"],
["bash", "-c", f"echo '{serve_app}' >> /tmp/serve_application.py"],
... | Model |
python | modin-project__modin | modin/core/storage_formats/base/query_compiler.py | {
"start": 3351,
"end": 5125
} | class ____(IntEnum): # noqa: PR01
"""
Coercion costs between different Query Compiler backends.
Coercion costs between query compilers can be expressed
as integers in the range 0 to 1000, where 1000 is
considered impossible. Since coercion costs can be a
function of many variables ( dataset si... | QCCoercionCost |
python | tensorflow__tensorflow | tensorflow/python/feature_column/feature_column_v2_test.py | {
"start": 40246,
"end": 56560
} | class ____(test.TestCase):
def test_keys_empty(self):
with self.assertRaisesRegex(ValueError,
'keys must be a list with length > 1'):
fc.crossed_column([], 10)
def test_keys_length_one(self):
with self.assertRaisesRegex(ValueError,
'key... | CrossedColumnTest |
python | coleifer__peewee | tests/prefetch_tests.py | {
"start": 808,
"end": 928
} | class ____(TestModel):
name = TextField()
parent = ForeignKeyField('self', backref='children', null=True)
| Category |
python | django__django | tests/admin_views/admin.py | {
"start": 28695,
"end": 29027
} | class ____(admin.ModelAdmin):
inlines = [RestaurantInlineAdmin]
view_on_site = True
def get_formset_kwargs(self, request, obj, inline, prefix):
return {
**super().get_formset_kwargs(request, obj, inline, prefix),
"form_kwargs": {"initial": {"name": "overridden_name"}},
... | CityAdmin |
python | python__mypy | mypyc/irbuild/match.py | {
"start": 1324,
"end": 12246
} | class ____(TraverserVisitor):
builder: IRBuilder
code_block: BasicBlock
next_block: BasicBlock
final_block: BasicBlock
subject: Value
match: MatchStmt
as_pattern: AsPattern | None = None
def __init__(self, builder: IRBuilder, match_node: MatchStmt) -> None:
self.builder = build... | MatchVisitor |
python | ApeWorX__ape | src/ape/types/coverage.py | {
"start": 6912,
"end": 9675
} | class ____(BaseModel):
"""
An individual contract's coverage.
"""
name: str
"""
The name of the contract.
"""
functions: list[FunctionCoverage] = []
"""
The coverage of each function individually.
"""
@property
def statements(self) -> list[CoverageStatement]:
... | ContractCoverage |
python | xlwings__xlwings | tests/test_conversion.py | {
"start": 682,
"end": 4764
} | class ____(TestBase):
def test_transpose(self):
self.wb1.sheets[0].range("A1").options(transpose=True).value = [
[1.0, 2.0],
[3.0, 4.0],
]
self.assertEqual(
self.wb1.sheets[0].range("A1:B2").value, [[1.0, 3.0], [2.0, 4.0]]
)
def test_dictionar... | TestConverter |
python | getsentry__sentry | fixtures/page_objects/explore_logs.py | {
"start": 124,
"end": 1871
} | class ____(BasePage):
def __init__(self, browser, client):
super().__init__(browser)
self.client = client
self.global_selection = GlobalSelectionPage(browser)
def visit_explore_logs(self, org):
self.browser.get(f"/organizations/{org}/explore/logs/")
self.wait_until_loade... | ExploreLogsPage |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-hubspot/llama_index/readers/hubspot/base.py | {
"start": 148,
"end": 1399
} | class ____(BaseReader):
"""
Hubspot reader. Reads data from a Hubspot account.
Args:
access_token(str): Hubspot API key.
"""
def __init__(self, access_token: str) -> None:
"""Initialize Hubspot reader."""
self.access_token = access_token
def load_data(self) -> List[Do... | HubspotReader |
python | sqlalchemy__sqlalchemy | examples/asyncio/async_orm.py | {
"start": 731,
"end": 1000
} | class ____(Base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
data: Mapped[Optional[str]]
create_date: Mapped[datetime.datetime] = mapped_column(
server_default=func.now()
)
bs: Mapped[List[B]] = relationship()
| A |
python | scrapy__scrapy | tests/test_spidermiddleware_referer.py | {
"start": 32529,
"end": 32856
} | class ____(
MixinNoReferrerWhenDowngrade, TestRefererMiddleware
):
"""
The empty string means "no-referrer-when-downgrade"
"""
settings = {
"REFERRER_POLICY": "scrapy.spidermiddlewares.referer.OriginWhenCrossOriginPolicy"
}
resp_headers = {"Referrer-Policy": ""}
| TestPolicyHeaderPrecedence004 |
python | mlflow__mlflow | mlflow/types/responses_helpers.py | {
"start": 4127,
"end": 5132
} | class ____(BaseModel):
model_config = ConfigDict(extra="allow")
type: str
@model_validator(mode="after")
def check_type(self) -> "OutputItem":
if self.type == "message":
ResponseOutputMessage(**self.model_dump())
elif self.type == "function_call":
ResponseFunctio... | OutputItem |
python | mahmoud__glom | glom/streaming.py | {
"start": 12926,
"end": 14099
} | class ____:
"""Get the first element of an iterable which matches *key*, if there
is one, otherwise return *default* (``None`` if unset).
>>> is_odd = lambda x: x % 2
>>> glom([0, 1, 2, 3], First(is_odd))
1
>>> glom([0, 2, 4], First(is_odd, default=False))
False
"""
# The impl of th... | First |
python | ray-project__ray | python/ray/data/tests/test_projection_fusion.py | {
"start": 1176,
"end": 53647
} | class ____:
"""Test topological sorting in projection pushdown fusion."""
@pytest.fixture(autouse=True)
def setup(self):
"""Set up test fixtures."""
self.context = DataContext.get_current()
# Create UDFs for testing
@udf(return_dtype=DataType.int64())
def multiply_b... | TestProjectionFusion |
python | pandas-dev__pandas | asv_bench/benchmarks/multiindex_object.py | {
"start": 6148,
"end": 6618
} | class ____:
def setup(self):
self.mi = MultiIndex.from_product(
[
date_range("2000-01-01", periods=1000),
RangeIndex(1000),
]
)
self.mi_deepcopy = self.mi.copy(deep=True)
self.idx_non_object = RangeIndex(1)
def time_equals_... | Equals |
python | simonw__datasette | datasette/views/table.py | {
"start": 1354,
"end": 11340
} | class ____:
def __init__(self, cells):
self.cells = cells
def __iter__(self):
return iter(self.cells)
def __getitem__(self, key):
for cell in self.cells:
if cell["column"] == key:
return cell["raw"]
raise KeyError
def display(self, key):
... | Row |
python | numba__numba | numba/core/errors.py | {
"start": 17540,
"end": 17733
} | class ____(Exception):
"""Unsupported bytecode is non-recoverable
"""
def __init__(self, msg, loc=None):
super().__init__(f"{msg}. Raised from {loc}")
| UnsupportedBytecodeError |
python | tornadoweb__tornado | demos/blog/blog.py | {
"start": 4410,
"end": 4714
} | class ____(BaseHandler):
async def get(self):
entries = await self.query(
"SELECT * FROM entries ORDER BY published DESC LIMIT 5"
)
if not entries:
self.redirect("/compose")
return
self.render("home.html", entries=entries)
| HomeHandler |
python | optuna__optuna | optuna/cli.py | {
"start": 22585,
"end": 26581
} | class ____(_BaseCommand):
"""Create a new trial and suggest parameters."""
def add_arguments(self, parser: ArgumentParser) -> None:
parser.add_argument("--study-name", type=str, help="Name of study.")
parser.add_argument("--sampler", type=str, help="Class name of sampler object to create.")
... | _Ask |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 217070,
"end": 218918
} | class ____(Response):
"""
Response of tasks.edit endpoint.
:param updated: Number of tasks updated (0 or 1)
:type updated: int
:param fields: Updated fields names and values
:type fields: dict
"""
_service = "tasks"
_action = "edit"
_version = "2.13"
_schema = {
"de... | EditResponse |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_web_fetch_tool_20250910_param.py | {
"start": 446,
"end": 1775
} | class ____(TypedDict, total=False):
name: Required[Literal["web_fetch"]]
"""Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
"""
type: Required[Literal["web_fetch_20250910"]]
allowed_callers: List[Literal["direct", "code_execution_20250825"]]
a... | BetaWebFetchTool20250910Param |
python | tensorflow__tensorflow | tensorflow/python/distribute/cross_device_utils_test.py | {
"start": 5268,
"end": 7020
} | class ____(test.TestCase):
def testPreferLargerPack(self):
# Each packs except the last one should be equal or larger than
# bytes_per_pack.
values = [
# size = 2 * 4 * 4 * 4 = 128
array_ops.ones([2, 4, 4], dtype=dtypes.float32),
# size = 8 * 4 = 32
array_ops.ones([8], dty... | GroupBySizeTest |
python | pandas-dev__pandas | pandas/tests/indexing/test_coercion.py | {
"start": 815,
"end": 4384
} | class ____(CoercionBase):
method = "setitem"
# disable comprehensiveness tests, as most of these have been moved to
# tests.series.indexing.test_setitem in SetitemCastingEquivalents subclasses.
klasses: list[str] = []
def test_setitem_series_no_coercion_from_values_list(self):
# GH35865 -... | TestSetitemCoercion |
python | pytorch__pytorch | torchgen/model.py | {
"start": 13344,
"end": 14088
} | class ____(Enum):
aliasing = auto()
aliasing_inplace = auto()
non_aliasing = auto()
# The basic input to the code generation is native_functions.yaml.
# The name "native", BTW, comes from the distinction between native
# functions and legacy TH functions. The legacy TH functions are gone,
# but the "nati... | ViewSchemaKind |
python | huggingface__transformers | src/transformers/models/gpt_oss/modeling_gpt_oss.py | {
"start": 2964,
"end": 7418
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.intermediate_size = config.intermediate_size
self.num_experts = config.num_local_experts
self.hidden_size = config.hidden_size
self.expert_dim = self.intermediate_size
self.gate_up_proj = nn.Pa... | GptOssExperts |
python | django__django | tests/admin_ordering/models.py | {
"start": 600,
"end": 698
} | class ____(admin.StackedInline):
model = Song
ordering = ("duration",)
| SongInlineNewOrdering |
python | huggingface__transformers | src/transformers/models/qwen3_vl_moe/modular_qwen3_vl_moe.py | {
"start": 17232,
"end": 17299
} | class ____(Qwen3MoeDecoderLayer):
pass
| Qwen3VLMoeTextDecoderLayer |
python | pallets__werkzeug | examples/simplewiki/database.py | {
"start": 1697,
"end": 2483
} | class ____:
"""
Represents one revision of a page.
This is useful for editing particular revision of pages or creating
new revisions. It's also used for the diff system and the revision
log.
"""
query = session.query_property()
def __init__(self, page, text, change_note="", timestamp=... | Revision |
python | huggingface__transformers | src/transformers/models/convnext/modeling_convnext.py | {
"start": 11894,
"end": 13692
} | class ____(ConvNextPreTrainedModel):
accepts_loss_kwargs = False
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.convnext = ConvNextModel(config)
# Classifier head
if config.num_labels > 0:
self.classifier = nn.... | ConvNextForImageClassification |
python | sqlalchemy__sqlalchemy | test/base/test_utils.py | {
"start": 59722,
"end": 60632
} | class ____(fixtures.TestBase):
def assert_eq(self, identityset, expected_iterable):
expected = [id(o) for o in expected_iterable]
found = [id(o) for o in identityset]
eq_(found, expected)
def test_add(self):
elem = object
s = util.OrderedIdentitySet()
s.add(elem(... | OrderedIdentitySetTest |
python | astral-sh__uv | scripts/benchmark/src/benchmark/resolver.py | {
"start": 21743,
"end": 29470
} | class ____(Suite):
def __init__(self, *, python: str, path: str | None = None) -> None:
self.python = python
self.name = path or "pdm"
self.path = path or "pdm"
def setup(self, requirements_file: str, *, cwd: str) -> None:
"""Initialize a PDM project from a requirements file."""... | Pdm |
python | PyCQA__pydocstyle | src/pydocstyle/parser.py | {
"start": 9306,
"end": 9996
} | class ____(Exception):
"""Raised when there is a problem with __all__ when parsing."""
def __init__(self, message):
"""Initialize the error with a more specific message."""
Exception.__init__(
self,
message
+ textwrap.dedent(
"""
... | AllError |
python | django__django | django/db/models/expressions.py | {
"start": 72414,
"end": 72635
} | class ____(Enum):
CURRENT_ROW = "CURRENT ROW"
GROUP = "GROUP"
TIES = "TIES"
NO_OTHERS = "NO OTHERS"
def __repr__(self):
return f"{self.__class__.__qualname__}.{self._name_}"
| WindowFrameExclusion |
python | celery__celery | celery/utils/log.py | {
"start": 3221,
"end": 5131
} | class ____(logging.Formatter):
"""Logging formatter that adds colors based on severity."""
#: Loglevel -> Color mapping.
COLORS = colored().names
colors = {
'DEBUG': COLORS['blue'],
'WARNING': COLORS['yellow'],
'ERROR': COLORS['red'],
'CRITICAL': COLORS['magenta'],
}... | ColorFormatter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.