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 | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/elements.py | {
"start": 93208,
"end": 93838
} | class ____(DQLDMLClauseElement):
"""Describe a list of clauses that will be space separated.
This is a minimal version of :class:`.ClauseList` which is used by
the :class:`.HasSyntaxExtension` class. It does not do any coercions
so should be used internally only.
.. versionadded:: 2.1
"""
... | ElementList |
python | pytorch__pytorch | torch/fx/experimental/proxy_tensor.py | {
"start": 5195,
"end": 5821
} | class ____(Protocol):
meta: dict[str, PySymType]
def is_sym_node(node: _HasMeta) -> bool:
assert hasattr(node, "meta"), "All nodes traced with proxy_tensor should have meta"
return "val" in node.meta and isinstance(node.meta["val"], py_sym_types)
@overload # type: ignore[no-overload-impl]
def set_proxy... | _HasMeta |
python | PyCQA__pylint | pylint/config/callback_actions.py | {
"start": 750,
"end": 1118
} | class ____(argparse.Action):
"""Custom callback action."""
@abc.abstractmethod
def __call__(
self,
parser: argparse.ArgumentParser,
namespace: argparse.Namespace,
values: str | Sequence[Any] | None,
option_string: str | None = None,
) -> None:
raise NotIm... | _CallbackAction |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/engine/base.py | {
"start": 104782,
"end": 106035
} | class ____(RootTransaction):
"""Represent a two-phase transaction.
A new :class:`.TwoPhaseTransaction` object may be procured
using the :meth:`_engine.Connection.begin_twophase` method.
The interface is the same as that of :class:`.Transaction`
with the addition of the :meth:`prepare` method.
... | TwoPhaseTransaction |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_unused_arguments/ARG.py | {
"start": 3952,
"end": 4154
} | class ____:
def __init__(self, x) -> None:
print(locals())
###
# Should trigger for t-string here
# even though the corresponding f-string
# does not trigger (since it is common in stubs)
###
| C |
python | walkccc__LeetCode | solutions/1818. Minimum Absolute Sum Difference/1818.py | {
"start": 0,
"end": 489
} | class ____:
def minAbsoluteSumDiff(self, nums1: list[int], nums2: list[int]) -> int:
ans = math.inf
diffs = [abs(a - b) for a, b in zip(nums1, nums2)]
sumDiff = sum(diffs)
nums1.sort()
for num, diff in zip(nums2, diffs):
i = bisect.bisect_left(nums1, num)
if i > 0:
ans = min(... | Solution |
python | lepture__authlib | authlib/oauth2/rfc6750/errors.py | {
"start": 428,
"end": 2308
} | class ____(OAuth2Error):
"""The access token provided is expired, revoked, malformed, or
invalid for other reasons. The resource SHOULD respond with
the HTTP 401 (Unauthorized) status code. The client MAY
request a new access token and retry the protected resource
request.
https://tools.ietf.o... | InvalidTokenError |
python | ansible__ansible | lib/ansible/modules/hostname.py | {
"start": 24006,
"end": 24125
} | class ____(Hostname):
platform = 'Linux'
distribution = 'Debian'
strategy_class = FileStrategy
| DebianHostname |
python | graphql-python__graphene | graphene/types/tests/test_objecttype.py | {
"start": 437,
"end": 588
} | class ____(ObjectType):
class Meta:
interfaces = (MyInterface,)
field1 = Field(MyType)
field2 = Field(MyType)
| ContainerWithInterface |
python | huggingface__transformers | src/transformers/models/gemma3/modular_gemma3.py | {
"start": 17158,
"end": 17292
} | class ____(Gemma2RMSNorm):
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__(dim=dim, eps=eps)
| Gemma3RMSNorm |
python | jazzband__django-simple-history | simple_history/tests/tests/test_index.py | {
"start": 227,
"end": 569
} | class ____(TestCase):
def test_has_composite_index(self):
self.assertEqual(settings.SIMPLE_HISTORY_DATE_INDEX, "Composite")
class Foo(models.Model):
history = HistoricalRecords()
self.assertEqual(
["history_date", "id"], Foo.history.model._meta.indexes[0].fields
... | HistoricalIndexTest |
python | tensorflow__tensorflow | tensorflow/python/training/saver_test.py | {
"start": 78307,
"end": 113791
} | class ____(test.TestCase):
def _get_test_dir(self, dirname):
test_dir = os.path.join(self.get_temp_dir(), dirname)
gfile.MakeDirs(test_dir)
return test_dir
@test_util.run_v1_only(
"Queue-based input pipelines have been replaced by `tf.data` "
"and not supported in V2.")
def testAddCollec... | MetaGraphTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/oracle/vector.py | {
"start": 5584,
"end": 6537
} | class ____:
"""
Lightweight SQLAlchemy-side version of SparseVector.
This mimics oracledb.SparseVector.
.. versionadded:: 2.0.43
"""
def __init__(
self,
num_dimensions: int,
indices: Union[list, array.array],
values: Union[list, array.array],
):
if ... | SparseVector |
python | Textualize__textual | src/textual/renderables/gradient.py | {
"start": 1226,
"end": 4627
} | class ____:
"""Render a linear gradient with a rotation.
Args:
angle: Angle of rotation in degrees.
stops: List of stop consisting of pairs of offset (between 0 and 1) and color.
"""
def __init__(
self, angle: float, stops: Sequence[tuple[float, Color | str]]
) -> None:
... | LinearGradient |
python | joke2k__faker | faker/providers/phone_number/ar_JO/__init__.py | {
"start": 49,
"end": 1772
} | class ____(PhoneNumberProvider):
# Source: https://en.wikipedia.org/wiki/Telephone_numbers_in_Jordan
cellphone_formats = (
"+9627{{operator_id}}#######",
"+962 7 {{operator_id}}### ####",
"07{{operator_id}}#######",
"07{{operator_id}} ### ####",
)
telephone_formats = (
... | Provider |
python | streamlit__streamlit | lib/streamlit/elements/lib/column_types.py | {
"start": 3011,
"end": 3151
} | class ____(TypedDict):
type: Literal["text"]
max_chars: NotRequired[int | None]
validate: NotRequired[str | None]
| TextColumnConfig |
python | huggingface__transformers | src/transformers/models/canine/modeling_canine.py | {
"start": 26238,
"end": 28495
} | class ____(nn.Module):
def __init__(
self,
config,
local=False,
always_attend_to_first_position=False,
first_position_attends_to_all=False,
attend_from_chunk_width=128,
attend_from_chunk_stride=128,
attend_to_chunk_width=128,
attend_to_chunk_st... | CanineEncoder |
python | huggingface__transformers | src/transformers/models/altclip/modeling_altclip.py | {
"start": 44481,
"end": 47429
} | class ____(AltCLIPPreTrainedModel):
config: AltCLIPTextConfig
input_modalities = ("text",)
def __init__(self, config):
super().__init__(config)
self.roberta = AltRobertaModel(config, add_pooling_layer=False)
self.transformation = nn.Linear(config.hidden_size, config.project_dim)
... | AltCLIPTextModel |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/util/_collections.py | {
"start": 15532,
"end": 15601
} | class ____(Protocol):
def __call__(self) -> Any: ...
| _ScopeFuncType |
python | kamyu104__LeetCode-Solutions | Python/number-of-valid-words-for-each-puzzle.py | {
"start": 1566,
"end": 2572
} | class ____(object):
def findNumOfValidWords(self, words, puzzles):
"""
:type words: List[str]
:type puzzles: List[str]
:rtype: List[int]
"""
L = 7
lookup = collections.defaultdict(list)
for i in xrange(len(puzzles)):
bits = []
b... | Solution2 |
python | Netflix__metaflow | metaflow/graph.py | {
"start": 9429,
"end": 19311
} | class ____(object):
def __init__(self, flow):
self.name = flow.__name__
self.nodes = self._create_nodes(flow)
self.doc = deindent_docstring(flow.__doc__)
# nodes sorted in topological order.
self.sorted_nodes = []
self._traverse_graph()
self._postprocess()
... | FlowGraph |
python | eventlet__eventlet | tests/isolated/wsgi_connection_timeout.py | {
"start": 2861,
"end": 5505
} | class ____(eventlet.greenio._fileobject):
def __init__(self, sock, mode='rb', bufsize=-1, close=False):
super(self.__class__, self).__init__(sock, mode)
self.armed = False
def arm(self):
output_buffer.append("beep")
self.armed = True
def _fuse(self):
if self.armed:... | ExplodingSocketFile |
python | scrapy__scrapy | tests/test_logformatter.py | {
"start": 9363,
"end": 9593
} | class ____(LogFormatter):
def crawled(self, *args, **kwargs):
return None
def scraped(self, *args, **kwargs):
return None
def dropped(self, *args, **kwargs):
return None
| SkipMessagesLogFormatter |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 554629,
"end": 554843
} | class ____(VegaLiteSchema):
"""LegendBinding schema wrapper."""
_schema = {"$ref": "#/definitions/LegendBinding"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| LegendBinding |
python | dagster-io__dagster | python_modules/libraries/dagster-azure/dagster_azure/adls2/io_manager.py | {
"start": 4808,
"end": 8626
} | class ____(ConfigurableIOManager):
"""Persistent IO manager using Azure Data Lake Storage Gen2 for storage.
Serializes objects via pickling. Suitable for objects storage for distributed executors, so long
as each execution node has network connectivity and credentials for ADLS and the backing
container... | ADLS2PickleIOManager |
python | numba__numba | numba/core/event.py | {
"start": 7104,
"end": 12095
} | class ____(Listener):
"""A listener that records all events and stores them in the ``.buffer``
attribute as a list of 2-tuple ``(float, Event)``, where the first element
is the time the event occurred as returned by ``time.time()`` and the second
element is the event.
"""
def __init__(self):
... | RecordingListener |
python | tensorflow__tensorflow | tensorflow/python/distribute/mirrored_strategy_test.py | {
"start": 33721,
"end": 34430
} | class ____(
strategy_test_lib.DistributionTestBase,
parameterized.TestCase):
def testThreeDevices(self, distribution):
def model_fn():
v = variable_v1.VariableV1(1.0, name="foo")
distribute_lib.get_replica_context().merge_call(lambda _: _)
return v
with distribution.scope():
... | MirroredThreeDeviceDistributionTest |
python | django__django | django/db/models/lookups.py | {
"start": 7959,
"end": 8780
} | class ____(Lookup):
def process_lhs(self, compiler, connection, lhs=None):
lhs_sql, params = super().process_lhs(compiler, connection, lhs)
field_internal_type = self.lhs.output_field.get_internal_type()
lhs_sql = (
connection.ops.lookup_cast(self.lookup_name, field_internal_type... | BuiltinLookup |
python | dask__distributed | distributed/tests/test_core.py | {
"start": 4348,
"end": 40107
} | class ____(Server):
default_port = 8756
@pytest.mark.slow
@gen_test()
async def test_server_listen():
"""
Test various Server.listen() arguments and their effect.
"""
import socket
try:
EXTERNAL_IP4 = get_ip()
if has_ipv6():
EXTERNAL_IP6 = get_ipv6()
except soc... | MyServer |
python | kamyu104__LeetCode-Solutions | Python/longest-increasing-subsequence.py | {
"start": 2507,
"end": 5009
} | class ____(object): # 0-based index
def __init__(self, N,
build_fn=lambda x, y: [y]*(2*x),
query_fn=lambda x, y: y if x is None else max(x, y), # (lambda x, y: y if x is None else min(x, y))
update_fn=lambda x, y: y,
default_val=0):
self.... | SegmentTree |
python | kamyu104__LeetCode-Solutions | Python/minimum-deletion-cost-to-avoid-repeating-letters.py | {
"start": 29,
"end": 491
} | class ____(object):
def minCost(self, s, cost):
"""
:type s: str
:type cost: List[int]
:rtype: int
"""
result = accu = max_cost = 0
for i in xrange(len(s)):
if i and s[i] != s[i-1]:
result += accu-max_cost
accu = max... | Solution |
python | google__pytype | pytype/overlays/fiddle_overlay.py | {
"start": 7175,
"end": 8985
} | class ____(abstract.ParameterizedClass):
"""Base generic class for fiddle.Config and fiddle.Partial."""
def __init__(self, base_cls, underlying, ctx, template=None, module="fiddle"):
if isinstance(underlying, _FUNCTION_OR_METHOD_TYPES):
# We don't support functions for now, but falling back to Any here g... | BuildableType |
python | ansible__ansible | hacking/azp/incidental.py | {
"start": 11813,
"end": 13140
} | class ____:
def __init__(self):
self.analyze_cmd = ['ansible-test', 'coverage', 'analyze', 'targets']
def combine(self, input_paths, output_path):
subprocess.check_call(self.analyze_cmd + ['combine'] + input_paths + [output_path])
def filter(self, input_path, output_path, include_targets=N... | CoverageTool |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_reflection.py | {
"start": 16747,
"end": 20429
} | class ____:
def __call__(self, x):
return x
def instance_identity(self, x):
return x
def instance_self(self):
return self
@staticmethod
def static_identity(x):
return x
@classmethod
def class_identity(cls, x):
return x
@pytest.mark.parametrize(
... | Identity |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 2176,
"end": 2244
} | class ____(Base):
field_y = models.CharField(max_length=30)
| ModelY |
python | pytorch__pytorch | torch/distributed/checkpoint/planner.py | {
"start": 746,
"end": 812
} | class ____:
nbytes: int
@dataclass(frozen=True)
| BytesIOWriteData |
python | kamyu104__LeetCode-Solutions | Python/intersection-of-two-arrays-ii.py | {
"start": 3266,
"end": 3861
} | class ____(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1.sort(), nums2.sort() # O(max(m, n) * log(max(m, n)))
res = []
it1, it2 = 0, 0
while it1 < len(nums1) and it2... | Solution |
python | allegroai__clearml | clearml/utilities/gpu/pynvml.py | {
"start": 40424,
"end": 40580
} | class ____(Structure):
pass # opaque handle
c_nvmlDevice_t = POINTER(struct_c_nvmlDevice_t)
# Legacy pciInfo used for _v1 and _v2
| struct_c_nvmlDevice_t |
python | gevent__gevent | src/greentest/3.9/test_socket.py | {
"start": 20112,
"end": 20756
} | class ____(SocketTestBase):
"""Base class for Unix-domain socket tests."""
# This class is used for file descriptor passing tests, so we
# create the sockets in a private directory so that other users
# can't send anything that might be problematic for a privileged
# user running the tests.
de... | UnixSocketTestBase |
python | gevent__gevent | src/gevent/event.py | {
"start": 675,
"end": 6252
} | class ____(AbstractLinkable): # pylint:disable=undefined-variable
"""
A synchronization primitive that allows one greenlet to wake up
one or more others. It has the same interface as
:class:`threading.Event` but works across greenlets.
.. important::
This object is for communicating among gr... | Event |
python | automl__auto-sklearn | autosklearn/ensembles/singlebest_ensemble.py | {
"start": 11068,
"end": 14288
} | class ____(AbstractSingleModelEnsemble):
"""
In the case of a crash, this class searches
for the best individual model.
Such model is returned as an ensemble of a single
object, to comply with the expected interface of an
AbstractEnsemble.
Do not use by yourself!
"""
def __init__(... | SingleBestFromRunhistory |
python | redis__redis-py | redis/_parsers/resp2.py | {
"start": 2406,
"end": 4813
} | class ____(_AsyncRESPBase):
"""Async class for the RESP2 protocol"""
async def read_response(self, disable_decoding: bool = False):
if not self._connected:
raise ConnectionError(SERVER_CLOSED_CONNECTION_ERROR)
if self._chunks:
# augment parsing buffer with previously rea... | _AsyncRESP2Parser |
python | ray-project__ray | python/ray/train/torch/config.py | {
"start": 5577,
"end": 8451
} | class ____(Backend):
share_cuda_visible_devices: bool = True
def on_start(self, worker_group: BaseWorkerGroup, backend_config: TorchConfig):
if dist.is_available():
# Set the appropriate training backend.
if backend_config.backend is None:
resources = worker_grou... | _TorchBackend |
python | numba__llvmlite | llvmlite/ir/types.py | {
"start": 11008,
"end": 11347
} | class ____(_BaseFloatType):
"""
The type for double-precision floats.
"""
null = '0.0'
intrinsic_name = 'f64'
def __str__(self):
return 'double'
def format_constant(self, value):
return _format_double(value)
for _cls in (HalfType, FloatType, DoubleType):
_cls._create_... | DoubleType |
python | python-openxml__python-docx | tests/oxml/unitdata/text.py | {
"start": 445,
"end": 552
} | class ____(BaseBuilder):
__tag__ = "w:jc"
__nspfxs__ = ("w",)
__attrs__ = ("w:val",)
| CT_JcBuilder |
python | kamyu104__LeetCode-Solutions | Python/count-array-pairs-divisible-by-k.py | {
"start": 888,
"end": 1387
} | class ____(object):
def countPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def gcd(x, y):
while y:
x, y = y, x%y
return x
result = 0
gcds = collections.Counter()
for x in n... | Solution2 |
python | celery__celery | celery/bin/logtool.py | {
"start": 869,
"end": 4267
} | class ____:
def __init__(self, on_task_error=None, on_trace=None, on_debug=None):
self.ids = set()
self.names = {}
self.results = {}
self.ready = set()
self.task_types = Counter()
self.task_errors = 0
self.on_task_error = on_task_error
self.on_trace =... | Audit |
python | kamyu104__LeetCode-Solutions | Python/video-stitching.py | {
"start": 33,
"end": 645
} | class ____(object):
def videoStitching(self, clips, T):
"""
:type clips: List[List[int]]
:type T: int
:rtype: int
"""
if T == 0:
return 0
result = 1
curr_reachable, reachable = 0, 0
clips.sort()
for left, right in clips:
... | Solution |
python | pypa__pip | tests/conftest.py | {
"start": 24465,
"end": 25071
} | class ____(Enum):
"""All the types of values we might be provided for the data-dist-info-metadata
attribute from PEP 658."""
# Valid: will read metadata from the dist instead.
No = "none"
# Valid: will read the .metadata file, but won't check its hash.
Unhashed = "unhashed"
# Valid: will re... | MetadataKind |
python | keras-team__keras | keras/src/backend/tensorflow/saved_model_test.py | {
"start": 957,
"end": 1434
} | class ____(models.Model):
def __init__(self):
super(CustomSignatureModel, self).__init__()
self.v = tf.Variable(1.0)
@tf.function
def __call__(self, x):
return x * self.v
@tf.function(input_signature=[tf.TensorSpec([], tf.float32)])
def mutate(self, new_v):
self.v.a... | CustomSignatureModel |
python | SmileyChris__easy-thumbnails | easy_thumbnails/models.py | {
"start": 2389,
"end": 2977
} | class ____(models.Model):
thumbnail = models.OneToOneField(Thumbnail, related_name="dimensions",
on_delete=models.CASCADE)
width = models.PositiveIntegerField(null=True)
height = models.PositiveIntegerField(null=True)
def __str__(self):
return "%sx%s" % (sel... | ThumbnailDimensions |
python | great-expectations__great_expectations | great_expectations/render/renderer/page_renderer.py | {
"start": 24105,
"end": 34328
} | class ____(Renderer):
def __init__(self, column_section_renderer=None) -> None:
super().__init__()
if column_section_renderer is None:
column_section_renderer = {"class_name": "ExpectationSuiteColumnSectionRenderer"}
module_name = "great_expectations.render.renderer.column_sectio... | ExpectationSuitePageRenderer |
python | spack__spack | lib/spack/spack/variant.py | {
"start": 29714,
"end": 29823
} | class ____(spack.error.SpecError):
"""Raised when variants have invalid values."""
| InvalidVariantValueError |
python | facebook__pyre-check | client/configuration/tests/python_version_test.py | {
"start": 304,
"end": 1118
} | class ____(testslide.TestCase):
def test_from_string(self) -> None:
def assert_parsed(input: str, expected: PythonVersion) -> None:
self.assertEqual(PythonVersion.from_string(input), expected)
def assert_not_parsed(input: str) -> None:
with self.assertRaises(InvalidPythonVer... | PythonVersionTest |
python | python-openxml__python-docx | src/docx/oxml/text/parfmt.py | {
"start": 1523,
"end": 10347
} | class ____(BaseOxmlElement):
"""``<w:pPr>`` element, containing the properties for a paragraph."""
get_or_add_ind: Callable[[], CT_Ind]
get_or_add_pStyle: Callable[[], CT_String]
get_or_add_sectPr: Callable[[], CT_SectPr]
_insert_sectPr: Callable[[CT_SectPr], None]
_remove_pStyle: Callable[[], ... | CT_PPr |
python | sympy__sympy | sympy/physics/mechanics/tests/test_wrapping_geometry.py | {
"start": 4343,
"end": 9790
} | class ____:
@staticmethod
def test_valid_constructor():
N = ReferenceFrame('N')
r = Symbol('r', positive=True)
pO = Point('pO')
cylinder = WrappingCylinder(r, pO, N.x)
assert isinstance(cylinder, WrappingCylinder)
assert hasattr(cylinder, 'radius')
assert... | TestWrappingCylinder |
python | modin-project__modin | modin/tests/pandas/native_df_interoperability/test_compiler_caster.py | {
"start": 6220,
"end": 6649
} | class ____(CalculatorTestQc):
"Represents a query compiler which returns non-sensical costs"
def get_backend(self):
return "Adversarial"
def move_to_cost(self, other_qc_cls, api_cls_name, op, arguments):
return {
CloudQC: -1000,
CloudQCHighSelf: -1000,
C... | AdversarialQC |
python | getsentry__sentry | src/sentry/sentry_metrics/indexer/base.py | {
"start": 1214,
"end": 1523
} | class ____:
use_case_id: UseCaseID
org_id: OrgId
string: str
id: int | None
@classmethod
def from_string(cls: type[UR], key: str, id: int) -> UR:
use_case_id, org_id, string = key.split(":", 2)
return cls(UseCaseID(use_case_id), int(org_id), string, id)
| UseCaseKeyResult |
python | scipy__scipy | scipy/stats/_discrete_distns.py | {
"start": 60507,
"end": 63174
} | class ____(_nchypergeom_gen):
r"""A Fisher's noncentral hypergeometric discrete random variable.
Fisher's noncentral hypergeometric distribution models drawing objects of
two types from a bin. `M` is the total number of objects, `n` is the
number of Type I objects, and `odds` is the odds ratio: the odd... | nchypergeom_fisher_gen |
python | spyder-ide__spyder | spyder/plugins/completion/tests/test_plugin.py | {
"start": 503,
"end": 751
} | class ____(QObject):
"""Dummy class that can handle LSP responses."""
sig_response = Signal(str, dict)
@Slot(str, dict)
def handle_response(self, method, params):
self.sig_response.emit(method, params)
| DummyCompletionReceiver |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_a_non_bot_user_agent.py | {
"start": 725,
"end": 1899
} | 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.equal_non_bot_user_agent"
# This method defines the business logic for e... | ColumnValuesEqualNonBotUserAgent |
python | doocs__leetcode | solution/2400-2499/2468.Split Message Based on Limit/Solution.py | {
"start": 0,
"end": 608
} | class ____:
def splitMessage(self, message: str, limit: int) -> List[str]:
n = len(message)
sa = 0
for k in range(1, n + 1):
sa += len(str(k))
sb = len(str(k)) * k
sc = 3 * k
if limit * k - (sa + sb + sc) >= n:
ans = []
... | Solution |
python | uqfoundation__dill | dill/tests/test_sources.py | {
"start": 543,
"end": 666
} | class ____(object):
def bar(self, x):
return x*x+x
_foo = Foo()
def add(x,y):
return x+y
squared = lambda x:x**2
| Foo |
python | realpython__materials | dwitter-part-3/source_code_final/dwitter/models.py | {
"start": 159,
"end": 500
} | class ____(models.Model):
user = models.ForeignKey(
User, related_name="dweets", on_delete=models.DO_NOTHING
)
body = models.CharField(max_length=140)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.user} ({self.created_at:%Y-%m-%d %H:%M}): {se... | Dweet |
python | pytorch__pytorch | torch/_dynamo/variables/builder.py | {
"start": 8851,
"end": 8901
} | class ____:
pass
@dataclasses.dataclass
| _missing |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP045.py | {
"start": 474,
"end": 695
} | class ____:
service_specification: Optional[
list[ServiceSpecificationRef]
| list[ServiceSpecification]
] = None
# Regression test for: https://github.com/astral-sh/ruff/issues/7201
| ServiceRefOrValue |
python | arrow-py__arrow | arrow/locales.py | {
"start": 13709,
"end": 15020
} | class ____(Locale):
past = "il y a {0}"
future = "dans {0}"
and_word = "et"
timeframes = {
"now": "maintenant",
"second": "une seconde",
"seconds": "{0} secondes",
"minute": "une minute",
"minutes": "{0} minutes",
"hour": "une heure",
"hours": "{0... | FrenchBaseLocale |
python | sqlalchemy__sqlalchemy | test/orm/test_subquery_relations.py | {
"start": 74375,
"end": 78604
} | class ____(_Polymorphic):
@classmethod
def define_tables(cls, metadata):
Table(
"companies",
metadata,
Column(
"company_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
... | SubRelationFromJoinedSubclassMultiLevelTest |
python | facelessuser__pymdown-extensions | pymdownx/blocks/html.py | {
"start": 3448,
"end": 5743
} | class ____(Block):
"""
HTML.
Arguments (1 required):
- HTML tag name
Options:
- `markdown` (string): specify how content inside the element should be treated:
- `auto`: will automatically determine how an element's content should be handled.
- `inline`: treat content as an inline e... | HTML |
python | altair-viz__altair | altair/vegalite/v6/api.py | {
"start": 29685,
"end": 30073
} | class ____(Protocol):
# NOTE: Temporary solution to non-SchemaBase copy
_condition: _Condition
def _when_then(
self, statement: _StatementType, kwds: dict[str, Any], /
) -> _ConditionClosed | _Condition:
condition: Any = _deepcopy(self._condition)
then = _parse_then(statement, k... | _BaseWhen |
python | langchain-ai__langchain | libs/core/langchain_core/utils/utils.py | {
"start": 10643,
"end": 16192
} | class ____:
"""Type to indicate no default value is provided."""
_NoDefault = _NoDefaultType()
@overload
def from_env(key: str, /) -> Callable[[], str]: ...
@overload
def from_env(key: str, /, *, default: str) -> Callable[[], str]: ...
@overload
def from_env(key: Sequence[str], /, *, default: str) -> Callab... | _NoDefaultType |
python | jd__tenacity | tenacity/stop.py | {
"start": 1236,
"end": 1517
} | class ____(stop_base):
"""Stop if any of the stop condition is valid."""
def __init__(self, *stops: stop_base) -> None:
self.stops = stops
def __call__(self, retry_state: "RetryCallState") -> bool:
return any(x(retry_state) for x in self.stops)
| stop_any |
python | kamyu104__LeetCode-Solutions | Python/find-the-winning-player-in-coin-game.py | {
"start": 36,
"end": 232
} | class ____(object):
def losingPlayer(self, x, y):
"""
:type x: int
:type y: int
:rtype: str
"""
return "Alice" if min(x, y//4)%2 else "Bob"
| Solution |
python | scipy__scipy | scipy/interpolate/tests/test_ndgriddata.py | {
"start": 6829,
"end": 9569
} | class ____:
def test_nearest_options(self):
# smoke test that NearestNDInterpolator accept cKDTree options
npts, nd = 4, 3
x = np.arange(npts*nd).reshape((npts, nd))
y = np.arange(npts)
nndi = NearestNDInterpolator(x, y)
opts = {'balanced_tree': False, 'compact_nodes... | TestNearestNDInterpolator |
python | ray-project__ray | rllib/evaluation/sampler.py | {
"start": 1749,
"end": 3647
} | class ____(InputReader, metaclass=ABCMeta):
"""Reads input experiences from an existing sampler."""
@override(InputReader)
def next(self) -> SampleBatchType:
batches = [self.get_data()]
batches.extend(self.get_extra_batches())
if len(batches) == 0:
raise RuntimeError("No... | SamplerInput |
python | aimacode__aima-python | reinforcement_learning4e.py | {
"start": 256,
"end": 2645
} | class ____:
"""
Passive (non-learning) agent that uses direct utility estimation
on a given MDP and policy.
import sys
from mdp import sequential_decision_environment
north = (0, 1)
south = (0,-1)
west = (-1, 0)
east = (1, 0)
policy = {(0, 2): east, (1, 2): east, (2, 2): east, (... | PassiveDUEAgent |
python | pallets__click | src/click/core.py | {
"start": 77203,
"end": 101764
} | class ____:
r"""A parameter to a command comes in two versions: they are either
:class:`Option`\s or :class:`Argument`\s. Other subclasses are currently
not supported by design as some of the internals for parsing are
intentionally not finalized.
Some settings are supported by both options and arg... | Parameter |
python | huggingface__transformers | src/transformers/models/vits/tokenization_vits.py | {
"start": 1432,
"end": 9444
} | class ____(PreTrainedTokenizer):
"""
Construct a VITS tokenizer. Also supports MMS-TTS.
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
this superclass for more information regarding those methods.
Args:
vocab_file (`str`)... | VitsTokenizer |
python | pydantic__pydantic | tests/test_parse.py | {
"start": 265,
"end": 7432
} | class ____(BaseModel):
a: float
b: int = 10
def test_obj():
m = Model.model_validate(dict(a=10.2))
assert str(m) == 'a=10.2 b=10'
def test_model_validate_fails():
with pytest.raises(ValidationError) as exc_info:
Model.model_validate([1, 2, 3])
assert exc_info.value.errors(include_url... | Model |
python | pandas-dev__pandas | pandas/errors/__init__.py | {
"start": 1175,
"end": 1704
} | class ____(ValueError):
"""
Exception raised when a ``freq`` cannot be null.
Particularly ``DatetimeIndex.shift``, ``TimedeltaIndex.shift``,
``PeriodIndex.shift``.
See Also
--------
Index.shift : Shift values of Index.
Series.shift : Shift values of Series.
Examples
--------
... | NullFrequencyError |
python | scipy__scipy | scipy/stats/tests/test_qmc.py | {
"start": 15773,
"end": 16981
} | class ____:
def test_van_der_corput(self):
sample = van_der_corput(10)
out = [0.0, 0.5, 0.25, 0.75, 0.125, 0.625,
0.375, 0.875, 0.0625, 0.5625]
assert_allclose(sample, out)
sample = van_der_corput(10, workers=4)
assert_allclose(sample, out)
sample = v... | TestVDC |
python | getsentry__sentry | src/sentry/similarity/signatures.py | {
"start": 88,
"end": 448
} | class ____:
def __init__(self, columns: int, rows: int) -> None:
self.columns = columns
self.rows = rows
def __call__(self, features: Iterable[str]) -> list[int]:
return [
min(mmh3.hash(feature, column) % self.rows for feature in features)
for column in range(sel... | MinHashSignatureBuilder |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess5.py | {
"start": 142,
"end": 240
} | class ____:
def __get__(self, instance: object, owner: Any) -> int:
return 0
| IntProvider |
python | pypa__hatch | tests/env/plugin/test_interface.py | {
"start": 15930,
"end": 17987
} | class ____:
def test_default(self, isolation, isolated_data_dir, platform, global_application):
config = {"project": {"name": "my_app", "version": "0.0.1"}}
project = Project(isolation, config=config)
environment = MockEnvironment(
isolation,
project.metadata,
... | TestDevMode |
python | doocs__leetcode | lcci/04.10.Check SubTree/Solution.py | {
"start": 164,
"end": 700
} | class ____:
def checkSubTree(self, t1: TreeNode, t2: TreeNode) -> bool:
def dfs(t1, t2):
if t2 is None:
return t1 is None
if t1 is None or t1.val != t2.val:
return False
return dfs(t1.left, t2.left) and dfs(t1.right, t2.right)
if t... | Solution |
python | ApeWorX__ape | src/ape/api/networks.py | {
"start": 1531,
"end": 2787
} | class ____(BaseModel):
"""
Information about a proxy contract.
"""
target: AddressType
"""The address of the implementation contract."""
type_name: str = ""
@model_validator(mode="before")
@classmethod
def _validate_type_name(cls, model):
if "type_name" in model:
... | ProxyInfoAPI |
python | getsentry__sentry | src/sentry/auth/providers/saml2/provider.py | {
"start": 12863,
"end": 13072
} | class ____(TypedDict):
entityId: str
assertionConsumerService: _SamlConfigService
singleLogoutService: _SamlConfigService
x509cert: NotRequired[str]
privateKey: NotRequired[str]
| _SamlConfigSp |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0003_project_cdn_enabled.py | {
"start": 100,
"end": 464
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0002_add_importedfile_model"),
]
operations = [
migrations.AddField(
model_name="project",
name="cdn_enabled",
field=models.BooleanField(default=False, verbose... | Migration |
python | modin-project__modin | modin/config/envvars.py | {
"start": 29862,
"end": 30438
} | class ____(EnvironmentVariable, type=bool):
"""Whether or not to perform computations synchronously."""
varname = "MODIN_BENCHMARK_MODE"
default = False
@classmethod
def put(cls, value: bool) -> None:
"""
Set ``BenchmarkMode`` value only if progress bar feature is disabled.
... | BenchmarkMode |
python | langchain-ai__langchain | libs/partners/openai/tests/unit_tests/chat_models/test_base.py | {
"start": 36512,
"end": 40311
} | class ____(BaseModel):
"Make a sandwich given a list of ingredients."
bread_type: str
cheese_type: str
condiments: list[str]
vegetables: list[str]
@pytest.mark.parametrize(
"tool_choice",
[
"any",
"none",
"auto",
"required",
"GenerateUsername",
... | MakeASandwich |
python | docker__docker-py | tests/unit/utils_test.py | {
"start": 22544,
"end": 23595
} | class ____(unittest.TestCase):
def test_format_env_binary_unicode_value(self):
env_dict = {
'ARTIST_NAME': b'\xec\x86\xa1\xec\xa7\x80\xec\x9d\x80'
}
assert format_environment(env_dict) == ['ARTIST_NAME=송지은']
def test_format_env_no_value(self):
env_dict = {
... | FormatEnvironmentTest |
python | Lightning-AI__lightning | tests/tests_fabric/plugins/precision/test_double_integration.py | {
"start": 756,
"end": 2020
} | class ____(nn.Module):
def __init__(self):
super().__init__()
self.layer = torch.nn.Linear(32, 2)
self.register_buffer("complex_buffer", torch.complex(torch.rand(10), torch.rand(10)), False)
def forward(self, x):
assert x.dtype == torch.float64
# the default dtype for ne... | BoringDoubleModule |
python | kubernetes-client__python | kubernetes/client/models/v1_ip_address_spec.py | {
"start": 383,
"end": 3613
} | 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... | V1IPAddressSpec |
python | doocs__leetcode | lcof/面试题32 - I. 从上到下打印二叉树/Solution.py | {
"start": 164,
"end": 612
} | class ____:
def levelOrder(self, root: TreeNode) -> List[int]:
ans = []
if root is None:
return ans
q = deque([root])
while q:
for _ in range(len(q)):
node = q.popleft()
ans.append(node.val)
if node.left:
... | Solution |
python | walkccc__LeetCode | solutions/3238. Find the Number of Winning Players/3238.py | {
"start": 0,
"end": 305
} | class ____:
def winningPlayerCount(self, n: int, pick: list[list[int]]) -> int:
counts = [collections.Counter() for _ in range(n)]
for player, color in pick:
counts[player][color] += 1
return sum(max(count.values(), default=0) > i
for i, count in enumerate(counts))
| Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/asset_backfill.py | {
"start": 4929,
"end": 28178
} | class ____(NamedTuple):
"""Has custom serialization instead of standard Dagster NamedTuple serialization because the
asset graph is required to build the AssetGraphSubset objects.
"""
target_subset: AssetGraphSubset
requested_runs_for_target_roots: bool
latest_storage_id: Optional[int]
mate... | AssetBackfillData |
python | has2k1__plotnine | plotnine/mapping/_atomic.py | {
"start": 646,
"end": 1237
} | class ____(Generic[T]):
"""
Atomic aesthetic value
The goal of this base class is simplify working with the more complex
aesthetic values. e.g. if a value is a tuple, we don't want it to be
seen as a sequence of values when assigning it to a dataframe column.
The subclasses should be able to re... | ae_value |
python | PyCQA__pylint | tests/functional/m/missing/missing_docstring_new_style.py | {
"start": 234,
"end": 311
} | class ____:
pass
# pylint: enable=missing-class-docstring
| ClassUndocumented |
python | pandas-dev__pandas | pandas/tests/frame/methods/test_to_period.py | {
"start": 185,
"end": 2863
} | class ____:
def test_to_period(self, frame_or_series):
K = 5
dr = date_range("1/1/2000", "1/1/2001", freq="D")
obj = DataFrame(
np.random.default_rng(2).standard_normal((len(dr), K)),
index=dr,
columns=["A", "B", "C", "D", "E"],
)
obj["mix... | TestToPeriod |
python | openai__openai-python | src/openai/types/chat/chat_completion_custom_tool_param.py | {
"start": 775,
"end": 1066
} | class ____(TypedDict, total=False):
grammar: Required[CustomFormatGrammarGrammar]
"""Your chosen grammar."""
type: Required[Literal["grammar"]]
"""Grammar format. Always `grammar`."""
CustomFormat: TypeAlias = Union[CustomFormatText, CustomFormatGrammar]
| CustomFormatGrammar |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.