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 | pypa__pip | src/pip/_vendor/idna/codec.py | {
"start": 188,
"end": 767
} | class ____(codecs.Codec):
def encode(self, data: str, errors: str = "strict") -> Tuple[bytes, int]:
if errors != "strict":
raise IDNAError('Unsupported error handling "{}"'.format(errors))
if not data:
return b"", 0
return encode(data), len(data)
def decode(sel... | Codec |
python | google__pytype | pytype/tools/xref/indexer.py | {
"start": 9361,
"end": 9556
} | class ____:
"""Representation of a function call."""
name: str
scope: str
func: str
location: source.Location
end_location: source.Location
args: list[Any]
return_type: str
| Funcall |
python | numba__numba | numba/tests/npyufunc/test_vectorize_decor.py | {
"start": 2442,
"end": 2565
} | class ____(unittest.TestCase, BaseVectorizeDecor):
target = 'cpu'
wrapper = jit(nopython=True)
| TestCPUVectorizeJitted |
python | numba__numba | numba/np/arrayobj.py | {
"start": 27779,
"end": 30828
} | class ____(Indexer):
"""
Compute indices from an array of boolean predicates.
"""
def __init__(self, context, builder, idxty, idxary):
self.context = context
self.builder = builder
self.idxty = idxty
self.idxary = idxary
assert idxty.ndim == 1
self.ll_int... | BooleanArrayIndexer |
python | tensorflow__tensorflow | tensorflow/python/keras/metrics.py | {
"start": 100910,
"end": 101773
} | class ____(MeanMetricWrapper):
"""Computes the Poisson metric between `y_true` and `y_pred`.
`metric = y_pred - y_true * log(y_pred)`
Args:
name: (Optional) string name of the metric instance.
dtype: (Optional) data type of the metric result.
Standalone usage:
>>> m = tf.keras.metrics.Poisson()
... | Poisson |
python | openai__openai-python | tests/api_resources/beta/test_threads.py | {
"start": 16203,
"end": 32777
} | class ____:
parametrize = pytest.mark.parametrize(
"async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"]
)
@parametrize
async def test_method_create(self, async_client: AsyncOpenAI) -> None:
with pytest.warns(DeprecationWarning):
... | TestAsyncThreads |
python | huggingface__transformers | src/transformers/models/swinv2/modeling_swinv2.py | {
"start": 17684,
"end": 24696
} | class ____(nn.Module):
def __init__(self, config, dim, num_heads, window_size, pretrained_window_size=[0, 0]):
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})"
... | Swinv2SelfAttention |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 35156,
"end": 36390
} | class ____(Loops):
def make_loader(self) -> Callable[[Sequence[Expr]], OpsValue]:
# Make zero-element loops into a no-op
if self.is_zero_elements():
return partial(nop_loader_fn, dtype=self.dtype)
return self.inner_fn
def __str__(self) -> str:
return self._to_str(("... | Pointwise |
python | keras-team__keras | keras/src/layers/regularization/alpha_dropout_test.py | {
"start": 125,
"end": 2212
} | class ____(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_alpha_dropout_basics(self):
self.run_layer_test(
layers.AlphaDropout,
init_kwargs={
"rate": 0.2,
},
input_shape=(2, 3),
call_kwargs={"training": True... | AlphaDropoutTest |
python | run-llama__llama_index | llama-index-experimental/llama_index/experimental/query_engine/pandas/pandas_query_engine.py | {
"start": 1911,
"end": 9355
} | class ____(BaseQueryEngine):
"""
Pandas query engine.
Convert natural language to Pandas python code.
WARNING: This tool provides the Agent access to the `eval` function.
Arbitrary code execution is possible on the machine running this tool.
This tool is not recommended to be used in a product... | PandasQueryEngine |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/env_vars.py | {
"start": 1885,
"end": 2061
} | class ____(graphene.Union):
class Meta:
types = (GrapheneLocationDocsJson, GraphenePythonError)
name = "LocationDocsJsonOrError"
| GrapheneLocationDocsJsonOrError |
python | pandas-dev__pandas | asv_bench/benchmarks/io/csv.py | {
"start": 7798,
"end": 8237
} | class ____(StringIORewind):
iso8601 = "%Y-%m-%d %H:%M:%S"
def setup(self):
rng = date_range("1/1/2000", periods=50000, freq="s")
self.StringIO_input = StringIO("\n".join(rng.strftime(self.iso8601).tolist()))
def time_read_csv(self):
read_csv(
self.data(self.StringIO_inp... | ReadCSVConcatDatetime |
python | google__jax | jax/_src/lax/lax.py | {
"start": 17091,
"end": 72719
} | class ____(enum.Enum):
HIGHEST = 1
DEFAULT = 2
@export
def exp(x: ArrayLike, accuracy=None) -> Array:
r"""Elementwise exponential: :math:`e^x`.
This function lowers directly to the `stablehlo.exponential`_ operation.
Args:
x: input array. Must have floating-point or complex type.
accuracy: Optiona... | AccuracyMode |
python | scikit-learn__scikit-learn | sklearn/mixture/_base.py | {
"start": 1235,
"end": 21074
} | class ____(DensityMixin, BaseEstimator, metaclass=ABCMeta):
"""Base class for mixture models.
This abstract class specifies an interface for all mixture classes and
provides basic common methods for mixture models.
"""
_parameter_constraints: dict = {
"n_components": [Interval(Integral, 1,... | BaseMixture |
python | pypa__warehouse | warehouse/admin/views/organizations.py | {
"start": 17474,
"end": 42120
} | class ____(OrganizationNameMixin, SaveOrganizationForm):
def __init__(self, *args, organization_service, user, **kwargs):
super().__init__(*args, **kwargs)
self.organization_service = organization_service
self.user = user
@view_config(
route_name="admin.organization_application.detail"... | OrganizationApplicationForm |
python | vyperlang__vyper | vyper/ast/nodes.py | {
"start": 35165,
"end": 35252
} | class ____(Operator):
__slots__ = ()
_description = "logical or"
_op = any
| Or |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 17766,
"end": 18372
} | class ____(AbstractTemplate):
key = "static_getitem"
def generic(self, args, kws):
tup, idx = args
ret = None
if not isinstance(tup, types.BaseTuple):
return
if isinstance(idx, int):
try:
ret = tup.types[idx]
except IndexError:... | StaticGetItemTuple |
python | ray-project__ray | rllib/evaluation/tests/test_rollout_worker.py | {
"start": 2055,
"end": 2403
} | 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
):
raise Exception(... | BadPolicy |
python | spyder-ide__spyder | spyder/plugins/explorer/widgets/utils.py | {
"start": 2765,
"end": 3481
} | class ____(QFileIconProvider):
"""Project tree widget icon provider"""
@Slot(int)
@Slot(QFileInfo)
def icon(self, icontype_or_qfileinfo):
"""Reimplement Qt method"""
if isinstance(icontype_or_qfileinfo, QFileIconProvider.IconType):
return super().icon(icontype_or_qfileinfo)
... | IconProvider |
python | pallets__flask | src/flask/json/provider.py | {
"start": 318,
"end": 3966
} | class ____:
"""A standard set of JSON operations for an application. Subclasses
of this can be used to customize JSON behavior or use different
JSON libraries.
To implement a provider for a specific library, subclass this base
class and implement at least :meth:`dumps` and :meth:`loads`. All
ot... | JSONProvider |
python | RaRe-Technologies__gensim | gensim/test/test_bm25model.py | {
"start": 271,
"end": 551
} | class ____(BM25ABC):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def precompute_idfs(self, dfs, num_docs):
return dict()
def get_term_weights(self, num_tokens, term_frequencies, idfs):
return term_frequencies
| BM25Stub |
python | astropy__astropy | astropy/units/quantity.py | {
"start": 4393,
"end": 5456
} | class ____(ParentDtypeInfo):
# This is on a base class rather than QuantityInfo directly, so that
# it can be used for EarthLocationInfo yet make clear that that class
# should not be considered a typical Quantity subclass by Table.
attrs_from_parent = {"dtype", "unit"} # dtype and unit taken from pare... | QuantityInfoBase |
python | django__django | django/db/models/functions/datetime.py | {
"start": 404,
"end": 1010
} | class ____:
tzinfo = None
def get_tzname(self):
# Timezone conversions must happen to the input datetime *before*
# applying a function. 2015-12-31 23:00:00 -02:00 is stored in the
# database as 2016-01-01 01:00:00 +00:00. Any results should be
# based on the input datetime not ... | TimezoneMixin |
python | pennersr__django-allauth | allauth/core/internal/ratelimit.py | {
"start": 1207,
"end": 1536
} | class ____:
cache_key: str
cache_duration: Union[float, int]
timestamp: float
def rollback(self) -> None:
history = cache.get(self.cache_key, [])
history = [ts for ts in history if ts != self.timestamp]
cache.set(self.cache_key, history, self.cache_duration)
@dataclass
| SingleRateLimitUsage |
python | doocs__leetcode | solution/2500-2599/2588.Count the Number of Beautiful Subarrays/Solution.py | {
"start": 0,
"end": 247
} | class ____:
def beautifulSubarrays(self, nums: List[int]) -> int:
cnt = Counter({0: 1})
ans = mask = 0
for x in nums:
mask ^= x
ans += cnt[mask]
cnt[mask] += 1
return ans
| Solution |
python | ray-project__ray | rllib/utils/metrics/metrics_logger.py | {
"start": 566,
"end": 65156
} | class ____:
"""A generic class collecting and processing metrics in RL training and evaluation.
This class represents the main API used by all of RLlib's components (internal and
user facing) in order to log, collect, and process (reduce) stats during training
and evaluation/inference.
It supports... | MetricsLogger |
python | dask__dask | dask/_task_spec.py | {
"start": 24875,
"end": 27057
} | class ____(Task, Iterable):
constructor: Callable
klass: type
__slots__ = tuple(__annotations__)
def __init__(
self,
/,
*args: Any,
**kwargs: Any,
):
if len(args) == 1 and isinstance(args[0], self.klass):
args = args[0] # type: ignore[assignment]... | NestedContainer |
python | joke2k__faker | tests/providers/test_currency.py | {
"start": 17213,
"end": 17878
} | class ____:
"""Test vi_VN currency provider"""
num_samples = 100
@classmethod
def setup_class(cls):
from faker.providers.currency.vi_VN import Provider as ViVNCurrencyProvider
cls.provider = ViVNCurrencyProvider
cls.currencies = cls.provider.currencies
def test_currency(s... | TestViVn |
python | celery__celery | t/unit/backends/test_azureblockblob.py | {
"start": 7934,
"end": 8718
} | class ____:
def setup_method(self):
self.url = (
"azureblockblob://"
"DefaultEndpointsProtocol=protocol;"
"AccountName=name;"
"AccountKey=account_key;"
"EndpointSuffix=suffix"
)
self.backend = AzureBlockBlobBackend(
app=... | test_as_uri |
python | huggingface__transformers | tests/models/prompt_depth_anything/test_modeling_prompt_depth_anything.py | {
"start": 5023,
"end": 8777
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as Prompt Depth Anything does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
all_model_classes = (PromptDepthAnythingForDepthEstimatio... | PromptDepthAnythingModelTest |
python | lepture__authlib | authlib/jose/rfc7518/jwe_algs.py | {
"start": 1610,
"end": 2857
} | class ____(JWEAlgorithm):
#: A key of size 2048 bits or larger MUST be used with these algorithms
#: RSA1_5, RSA-OAEP, RSA-OAEP-256
key_size = 2048
def __init__(self, name, description, pad_fn):
self.name = name
self.description = description
self.padding = pad_fn
def prepa... | RSAAlgorithm |
python | ray-project__ray | python/ray/data/_internal/execution/streaming_executor_state.py | {
"start": 5713,
"end": 6205
} | class ____:
"""The scheduling status of an operator.
This will be updated each time when StreamingExecutor makes
a scheduling decision, i.e., in each `select_operator_to_run`
call.
"""
# Whether the op was considered runnable in the last scheduling
# decision.
runnable: bool = False
... | OpSchedulingStatus |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/dag_stats.py | {
"start": 963,
"end": 1094
} | class ____(BaseModel):
"""DagStatsState serializer for responses."""
state: DagRunState
count: int
| DagStatsStateResponse |
python | bokeh__bokeh | tests/unit/bokeh/core/test_serialization.py | {
"start": 32051,
"end": 45654
} | class ____:
def setup_method(self, test_method):
from json import loads
from bokeh.core.json_encoder import serialize_json
self.serialize = serialize_json
self.deserialize = loads
def test_with_basic(self) -> None:
assert self.serialize({'test': [1, 2, 3]}) == '{"test":... | TestSerializeJson |
python | kamyu104__LeetCode-Solutions | Python/the-number-of-weak-characters-in-the-game.py | {
"start": 563,
"end": 1044
} | class ____(object):
def numberOfWeakCharacters(self, properties):
"""
:type properties: List[List[int]]
:rtype: int
"""
lookup = collections.defaultdict(list)
for a, d in properties:
lookup[a].append(d)
result = max_d = 0
for a in sorted(lo... | Solution |
python | run-llama__llama_index | llama-index-core/llama_index/core/chat_engine/types.py | {
"start": 3192,
"end": 14020
} | class ____:
"""Streaming chat response to user and writing to chat history."""
response: str = ""
sources: List[ToolOutput] = field(default_factory=list)
chat_stream: Optional[ChatResponseGen] = None
achat_stream: Optional[ChatResponseAsyncGen] = None
source_nodes: List[NodeWithScore] = field(d... | StreamingAgentChatResponse |
python | TheAlgorithms__Python | data_structures/linked_list/swap_nodes.py | {
"start": 216,
"end": 4157
} | class ____:
head: Node | None = None
def __iter__(self) -> Iterator:
"""
>>> linked_list = LinkedList()
>>> list(linked_list)
[]
>>> linked_list.push(0)
>>> tuple(linked_list)
(0,)
"""
node = self.head
while node:
yield... | LinkedList |
python | conda__conda | conda/exceptions.py | {
"start": 36098,
"end": 36612
} | class ____(CondaError):
def __init__(self, prefix: PathType, message: str = "", **kwargs):
error = f"Cannot modify '{prefix}'. The environment is marked as frozen. "
if message:
error += "Reason:\n\n"
error += indent(message, " ")
error += "\n\n"
error ... | EnvironmentIsFrozenError |
python | ray-project__ray | python/ray/dashboard/modules/aggregator/tests/test_multi_consumer_event_buffer.py | {
"start": 887,
"end": 10322
} | class ____:
@pytest.mark.asyncio
async def test_add_and_consume_event_basic(self):
"""Test basic event addition."""
buffer = MultiConsumerEventBuffer(max_size=10, max_batch_size=5)
consumer_name = "test_consumer"
await buffer.register_consumer(consumer_name)
assert await ... | TestMultiConsumerEventBuffer |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 8060,
"end": 8905
} | class ____(VOTableSpecWarning):
"""Array uses commas rather than whitespace.
The VOTable spec states:
If a cell contains an array or complex number, it should be
encoded as multiple numbers separated by whitespace.
Many VOTable files in the wild use commas as a separator instead,
and ... | W01 |
python | streamlit__streamlit | lib/streamlit/elements/lib/image_utils.py | {
"start": 2007,
"end": 15964
} | class ____(IntEnum):
"""
Special values that are recognized by the frontend and allow us to change the
behavior of the displayed image.
"""
ORIGINAL = -1
COLUMN = -2
AUTO = -3
MIN_IMAGE_OR_CONTAINER = -4
MAX_IMAGE_OR_CONTAINER = -5
WidthBehavior.ORIGINAL.__doc__ = """Display the i... | WidthBehavior |
python | pydantic__pydantic | tests/test_main.py | {
"start": 23108,
"end": 25488
} | class ____(str, Enum):
FOO = 'foo'
BAR = 'bar'
@pytest.mark.parametrize('value', [StrFoo.FOO, StrFoo.FOO.value, 'foo', 'hello'])
def test_literal_use_enum_values_multi_type(value) -> None:
class Model(BaseModel):
baz: Literal[StrFoo.FOO, 'hello']
model_config = ConfigDict(use_enum_values=T... | StrFoo |
python | walkccc__LeetCode | solutions/259. 3Sum Smaller/259.py | {
"start": 0,
"end": 525
} | class ____:
def threeSumSmaller(self, nums: list[int], target: int) -> int:
if len(nums) < 3:
return 0
ans = 0
nums.sort()
for i in range(len(nums) - 2):
l = i + 1
r = len(nums) - 1
while l < r:
if nums[i] + nums[l] + nums[r] < target:
# (nums[i], nums[l], ... | Solution |
python | chroma-core__chroma | chromadb/test/property/strategies.py | {
"start": 8602,
"end": 24087
} | class ____(ExternalCollection):
"""
An internal view of a collection.
This strategy contains all the information Chroma uses internally to manage a
collection. It is a superset of ExternalCollection and should be used to test
internal Chroma logic.
"""
id: uuid.UUID
dimension: int
... | Collection |
python | pypa__pipenv | pipenv/patched/pip/_internal/distributions/wheel.py | {
"start": 425,
"end": 1377
} | class ____(AbstractDistribution):
"""Represents a wheel distribution.
This does not need any preparation as wheels can be directly unpacked.
"""
@property
def build_tracker_id(self) -> Optional[str]:
return None
def get_metadata_distribution(self) -> BaseDistribution:
"""Loads... | WheelDistribution |
python | gevent__gevent | src/greentest/3.14/test_socket.py | {
"start": 6787,
"end": 6942
} | class ____(unittest.TestCase):
@cpython_only
def test_lazy_import(self):
ensure_lazy_imports("socket", {"array", "selectors"})
| TestLazyImport |
python | astropy__astropy | astropy/modeling/tests/test_fitters.py | {
"start": 1461,
"end": 3325
} | class ____:
"""Tests for 2D polynomial fitting."""
def setup_class(self):
self.model = models.Polynomial2D(2)
self.y, self.x = np.mgrid[:5, :5]
def poly2(x, y):
return 1 + 2 * x + 3 * x**2 + 4 * y + 5 * y**2 + 6 * x * y
self.z = poly2(self.x, self.y)
def test_... | TestPolynomial2D |
python | scipy__scipy | scipy/signal/tests/test_filter_design.py | {
"start": 69079,
"end": 70396
} | class ____:
@xfail_xp_backends(
'dask.array', reason='https://github.com/dask/dask/issues/11883'
)
def test_basic(self, xp):
z = xp.asarray([])
p = xp.asarray([(-1+1j) / math.sqrt(2), (-1-1j) / math.sqrt(2)])
k = 1
z_lp, p_lp, k_lp = lp2lp_zpk(z, p, k, 5)
xp_... | TestLp2lp_zpk |
python | modin-project__modin | modin/tests/pandas/utils.py | {
"start": 16089,
"end": 16317
} | class ____:
def __init__(self, value: int):
self.value = value
def __add__(self, other):
return self.value + other
def __radd__(self, other):
return other + self.value
| CustomIntegerForAddition |
python | pypa__setuptools | setuptools/_vendor/typeguard/_union_transformer.py | {
"start": 585,
"end": 1354
} | class ____(NodeTransformer):
def __init__(self, union_name: Name | None = None):
self.union_name = union_name or Name(id="Union", ctx=Load())
def visit_BinOp(self, node: BinOp) -> Any:
self.generic_visit(node)
if isinstance(node.op, BitOr):
return Subscript(
... | UnionTransformer |
python | pytorch__pytorch | torch/_inductor/template_heuristics/triton.py | {
"start": 92253,
"end": 92661
} | class ____(
TMATemplateConfigMixin, XPUConfigHeuristic
):
"""Persistent TMA template heuristic for XPU"""
def __init__(self) -> None:
super().__init__()
# Override mm_configs to use persistent_mm_configs
self.mm_configs = self.persistent_mm_configs
@register_template_heuristic(per... | XPUPersistentTMATemplateConfigHeuristic |
python | PyCQA__pylint | tests/functional/c/class_scope.py | {
"start": 712,
"end": 893
} | class ____:
"""right"""
class Result1:
"""result one"""
OK = 0
def work(self) -> Result1:
"""good type hint"""
return self.Result1.OK
| Right |
python | google__jax | jax/_src/custom_transpose.py | {
"start": 5777,
"end": 9204
} | class ____(core.Primitive):
call_primitive = False
map_primitive = False
multiple_results = True
def bind(self, *args, **params):
return self._true_bind(*args, **params)
def bind_with_trace(self, trace, call_args, params):
call, tracers = call_args[0], call_args[1:]
return trace.process_custom_t... | CustomTransposePrimitive |
python | huggingface__transformers | src/transformers/models/yoso/modeling_yoso.py | {
"start": 17528,
"end": 18137
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.self = YosoSelfAttention(config)
self.output = YosoSelfOutput(config)
def forward(self, hidden_states, attention_mask=None, output_attentions=False):
self_outputs = self.self(hidden_states, attention_mask... | YosoAttention |
python | cython__cython | Cython/Plex/Errors.py | {
"start": 53,
"end": 100
} | class ____(Exception):
message = ""
| PlexError |
python | keras-team__keras | keras/src/ops/math.py | {
"start": 33912,
"end": 34473
} | class ____(Operation):
def call(self, x):
return backend.math.logdet(x)
def compute_output_spec(self, x):
return KerasTensor(x.shape[:-2], dtype=x.dtype)
@keras_export(["keras.ops.logdet"])
def logdet(x):
"""Computes log of the determinant of a hermitian positive definite matrix.
Arg... | Logdet |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/bigquery.py | {
"start": 13574,
"end": 19980
} | class ____(
_BigQueryDbHookMixin, SQLValueCheckOperator, _BigQueryOperatorsEncryptionConfigurationMixin
):
"""
Perform a simple value check using sql code.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:BigQueryValueCheckOpe... | BigQueryValueCheckOperator |
python | ray-project__ray | doc/source/custom_directives.py | {
"start": 12850,
"end": 14663
} | class ____(Enum):
"""Enum which allows easier enumeration of members for example metadata."""
@classmethod
def items(cls: type) -> Iterable[Tuple["ExampleEnum", str]]:
"""Return an iterable mapping between the enum type and the corresponding value.
Returns
-------
Dict['Exa... | ExampleEnum |
python | django__django | tests/test_runner_apps/failures/tests_failures.py | {
"start": 234,
"end": 356
} | class ____(TestCase):
@expectedFailure
def test_sample(self):
self.assertEqual(0, 1)
| ExpectedFailureTestCase |
python | celery__celery | celery/exceptions.py | {
"start": 5928,
"end": 6022
} | class ____(TaskPredicate):
"""A task can raise this to ignore doing state updates."""
| Ignore |
python | wireservice__csvkit | csvkit/utilities/csvstat.py | {
"start": 1530,
"end": 14580
} | class ____(CSVKitUtility):
description = 'Print descriptive statistics for each column in a CSV file.'
def add_arguments(self):
self.argparser.add_argument(
'--csv', dest='csv_output', action='store_true',
help='Output results as a CSV table, rather than plain text.')
se... | CSVStat |
python | dask__distributed | distributed/tests/test_spill.py | {
"start": 6454,
"end": 10007
} | class ____:
def __init__(self, size):
self.size = size
def __getstate__(self):
raise MyError()
def __sizeof__(self):
return self.size
def test_spillbuffer_fail_to_serialize(tmp_path):
buf = SpillBuffer(str(tmp_path), target=200, max_spill=600)
# bad data individually lar... | Bad |
python | django__django | tests/syndication_tests/feeds.py | {
"start": 4842,
"end": 5250
} | class ____(TestRss2Feed):
"""
A feed to test custom context data in templates for title or description.
"""
title_template = "syndication/title_context.html"
description_template = "syndication/description_context.html"
def get_context_data(self, **kwargs):
context = super().get_contex... | TemplateContextFeed |
python | spack__spack | lib/spack/spack/util/debug.py | {
"start": 1228,
"end": 2840
} | class ____(pdb.Pdb):
"""
This class allows the python debugger to follow forked processes
and can set tracepoints allowing the Python Debugger Pdb to be used
from a python multiprocessing child process.
This is used the same way one would normally use Pdb, simply import this
class and use as a ... | ForkablePdb |
python | pypa__pip | src/pip/_vendor/packaging/_tokenizer.py | {
"start": 184,
"end": 245
} | class ____:
name: str
text: str
position: int
| Token |
python | pennersr__django-allauth | allauth/account/views.py | {
"start": 46358,
"end": 47151
} | class ____(_BaseVerifyPhoneView):
@method_decorator(never_cache)
def dispatch(self, request, *args, **kwargs):
self.stage = request._login_stage
self.process = flows.phone_verification.PhoneVerificationStageProcess.resume(
self.stage
)
if not self.process:
... | _VerifyPhoneSignupView |
python | doocs__leetcode | solution/0700-0799/0752.Open the Lock/Solution2.py | {
"start": 0,
"end": 1315
} | class ____:
def openLock(self, deadends: List[str], target: str) -> int:
def next(s):
res = []
s = list(s)
for i in range(4):
c = s[i]
s[i] = '9' if c == '0' else str(int(c) - 1)
res.append(''.join(s))
s[i] =... | Solution |
python | great-expectations__great_expectations | great_expectations/datasource/datasource_dict.py | {
"start": 5166,
"end": 7464
} | class ____(DatasourceDict):
"""
Extends the capabilites of the DatasourceDict by placing a caching layer in front of the underlying store.
Any retrievals will firstly check an in-memory dictionary before requesting from the store. Other CRUD methods will ensure that
both cache and store are kept in syn... | CacheableDatasourceDict |
python | openai__openai-python | src/openai/resources/responses/input_tokens.py | {
"start": 14006,
"end": 14243
} | class ____:
def __init__(self, input_tokens: InputTokens) -> None:
self._input_tokens = input_tokens
self.count = to_streamed_response_wrapper(
input_tokens.count,
)
| InputTokensWithStreamingResponse |
python | getsentry__sentry | tests/acceptance/test_shared_issue.py | {
"start": 265,
"end": 1341
} | class ____(AcceptanceTestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user("foo@example.com")
self.org = self.create_organization(owner=self.user, name="Rowdy Tiger")
self.team = self.create_team(organization=self.org, name="Mariachi Band")
self.pro... | SharedIssueTest |
python | huggingface__transformers | src/transformers/models/eomt/modular_eomt.py | {
"start": 10768,
"end": 10812
} | class ____(Mask2FormerLoss):
pass
| EomtLoss |
python | tensorflow__tensorflow | tensorflow/python/framework/convert_to_constants.py | {
"start": 29514,
"end": 32928
} | class ____(_ConverterData):
"""Container for ConcreteFunction-based conversion data."""
def __init__(self,
func,
lower_control_flow,
aggressive_inlining,
variable_names_allowlist=None,
variable_names_denylist=None):
"""Creates the conve... | _FunctionConverterData |
python | ansible__ansible | test/units/module_utils/basic/test_imports.py | {
"start": 403,
"end": 3448
} | class ____(unittest.TestCase):
def clear_modules(self, mods):
for mod in mods:
if mod in sys.modules:
del sys.modules[mod]
@patch.object(builtins, '__import__')
def test_module_utils_basic_import_syslog(self, mock_import):
def _mock_import(name, *args, **kwargs)... | TestImports |
python | google__jax | jax/_src/pallas/core.py | {
"start": 10227,
"end": 10386
} | class ____:
"""Represents a one-sized block dimension that is squeezed out in the kernel."""
squeezed = Squeezed()
@dataclasses.dataclass(frozen=True)
| Squeezed |
python | numpy__numpy | tools/swig/test/testMatrix.py | {
"start": 12850,
"end": 14439
} | class ____(MatrixTestCase):
def __init__(self, methodName="runTest"):
MatrixTestCase.__init__(self, methodName)
self.typeStr = "double"
self.typeCode = "d"
######################################################################
if __name__ == "__main__":
# Build the test suite
sui... | doubleTestCase |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_scatter14.py | {
"start": 315,
"end": 1633
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_scatter14.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.g... | TestCompareXLSXFiles |
python | Textualize__textual | src/textual/css/_style_properties.py | {
"start": 7576,
"end": 9238
} | class ____:
"""Descriptor for lists of scalars.
Args:
percent_unit: The dimension to which percentage scalars will be relative to.
refresh_children: Whether to refresh the node children on value change.
"""
def __init__(self, percent_unit: Unit, refresh_children: bool = False) -> None:... | ScalarListProperty |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/comms.py | {
"start": 21481,
"end": 21572
} | class ____(BaseModel):
ok: bool
type: Literal["OKResponse"] = "OKResponse"
| OKResponse |
python | openai__openai-python | src/openai/types/responses/response_code_interpreter_tool_call.py | {
"start": 345,
"end": 519
} | class ____(BaseModel):
logs: str
"""The logs output from the code interpreter."""
type: Literal["logs"]
"""The type of the output. Always `logs`."""
| OutputLogs |
python | huggingface__transformers | src/transformers/models/phi/modular_phi.py | {
"start": 925,
"end": 2491
} | class ____(LlamaRotaryEmbedding):
@staticmethod
def compute_default_rope_parameters(
config: Optional[PhiConfig] = None,
device: Optional["torch.device"] = None,
seq_len: Optional[int] = None,
) -> tuple["torch.Tensor", float]:
"""
Computes the inverse frequencies acc... | PhiRotaryEmbedding |
python | great-expectations__great_expectations | tests/core/test_expectation_configuration.py | {
"start": 6035,
"end": 10863
} | class ____:
@pytest.mark.unit
def test_hash_consistency_with_equality(self, config1, config2):
assert config1 == config2
assert hash(config1) == hash(config2)
@pytest.mark.unit
def test_hash_different_for_different_types(self):
config1 = ExpectationConfiguration(
typ... | TestExpectationConfigurationHash |
python | apache__airflow | airflow-core/tests/unit/serialization/test_dag_serialization.py | {
"start": 164379,
"end": 176619
} | class ____:
"""Test MappedOperator serialization with client defaults and callback properties."""
def test_mapped_operator_client_defaults_application(self, operator_defaults):
"""Test that client_defaults are correctly applied to MappedOperator during deserialization."""
with operator_defaults... | TestMappedOperatorSerializationAndClientDefaults |
python | davidhalter__jedi | test/completion/classes.py | {
"start": 3851,
"end": 4007
} | class ____(classgetter()):
def react(self):
#? ['shout']
self.s
# -----------------
# multiple inheritance # 1071
# -----------------
| Dude |
python | sqlalchemy__sqlalchemy | test/sql/test_deprecations.py | {
"start": 3691,
"end": 4860
} | class ____(fixtures.TablesTest, AssertsCompiledSQL):
__dialect__ = default.DefaultDialect(supports_native_boolean=True)
run_setup_bind = None
run_create_tables = None
@classmethod
def define_tables(cls, metadata):
Table(
"people",
metadata,
Column("peop... | LateralSubqueryCoercionsTest |
python | pytorch__pytorch | torch/distributed/checkpoint/_experimental/types.py | {
"start": 430,
"end": 759
} | class ____:
"""
Information about the current rank in a distributed training environment.
Attributes:
global_rank: The global rank ID of the current process.
global_world_size: The total number of processes in the distributed environment.
"""
global_rank: int
global_world_size:... | RankInfo |
python | sqlalchemy__sqlalchemy | test/sql/test_selectable.py | {
"start": 132557,
"end": 133480
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = "default"
def test_basic_clone(self):
t = table("t", column("c"))
s = select(t).with_for_update(read=True, of=t.c.c)
s2 = visitors.ReplacingCloningVisitor().traverse(s)
assert s2._for_update_arg is not s._for_updat... | ForUpdateTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py | {
"start": 10358,
"end": 10534
} | class ____(IncrementalShopifyGraphQlBulkStream):
parent_stream_class = Customers
bulk_query: CustomerAddresses = CustomerAddresses
cursor_field = "id"
| CustomerAddress |
python | falconry__falcon | falcon/util/mediatypes.py | {
"start": 4306,
"end": 11803
} | class ____:
main_type: str
subtype: str
quality: float
params: dict
__slots__ = ('main_type', 'subtype', 'quality', 'params')
_NOT_MATCHING = (-1, -1, -1, -1, 0.0)
_Q_VALUE_ERROR_MESSAGE = (
'If provided, the q parameter must be a real number in the range 0 through 1.'
)
... | _MediaRange |
python | walkccc__LeetCode | solutions/430. Flatten a Multilevel Doubly Linked List/430-2.py | {
"start": 0,
"end": 438
} | class ____:
def flatten(self, head: 'Node') -> 'Node':
curr = head
while curr:
if curr.child:
cachedNext = curr.next
curr.next = curr.child
curr.child.prev = curr
curr.child = None
tail = curr.next
while tail.next:
tail = tail.next
tail.... | Solution |
python | allegroai__clearml | clearml/backend_api/services/v2_9/tasks.py | {
"start": 183116,
"end": 184971
} | class ____(Response):
"""
Response of tasks.failed 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 = "failed"
_version = "2.9"
_schema = {
... | FailedResponse |
python | pyca__cryptography | tests/hazmat/primitives/test_hashes.py | {
"start": 1516,
"end": 1767
} | class ____:
test_sha1 = generate_base_hash_test(
hashes.SHA1(),
digest_size=20,
)
@pytest.mark.supported(
only_if=lambda backend: backend.hash_supported(hashes.SHA224()),
skip_message="Does not support SHA224",
)
| TestSHA1 |
python | anthropics__anthropic-sdk-python | src/anthropic/lib/tools/_beta_builtin_memory_tool.py | {
"start": 4859,
"end": 9123
} | class ____(BetaAsyncBuiltinFunctionTool):
"""Abstract base class for memory tool implementations.
This class provides the interface for implementing a custom memory backend for Claude.
Subclass this to create your own memory storage solution (e.g., database, cloud storage, encrypted files, etc.).
Exa... | BetaAsyncAbstractMemoryTool |
python | mitsuhiko__rye | rye-devtools/src/rye_devtools/find_downloads.py | {
"start": 946,
"end": 8855
} | class ____(Finder):
implementation = PythonImplementation.CPYTHON
RELEASE_URL = (
"https://api.github.com/repos/indygreg/python-build-standalone/releases"
)
FLAVOR_PREFERENCES = [
"shared-pgo",
"shared-noopt",
"shared-noopt",
"pgo+lto",
"pgo",
"l... | CPythonFinder |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/instigation.py | {
"start": 30607,
"end": 31170
} | class ____(graphene.Union):
class Meta:
types = (GrapheneInstigationStates, GraphenePythonError)
name = "InstigationStatesOrError"
types = [
GrapheneDryRunInstigationTick,
GrapheneDryRunInstigationTicks,
GrapheneInstigationTypeSpecificData,
GrapheneInstigationState,
GrapheneIns... | GrapheneInstigationStatesOrError |
python | ApeWorX__ape | src/ape_ethereum/ecosystem.py | {
"start": 6769,
"end": 11295
} | class ____(PluginConfig):
"""
L2 plugins should use this as their config base-class.
"""
DEFAULT_TRANSACTION_TYPE: ClassVar[int] = TransactionType.DYNAMIC.value
DEFAULT_LOCAL_GAS_LIMIT: ClassVar[GasLimit] = "max"
NETWORKS: ClassVar[dict[str, tuple[int, int]]] = NETWORKS
default_network: st... | BaseEthereumConfig |
python | pytorch__pytorch | test/distributed/pipelining/model_registry.py | {
"start": 5428,
"end": 5946
} | class ____(torch.nn.Module):
def __init__(self, d_hid: int, n_layers: int = 2):
super().__init__()
self.layers = torch.nn.ModuleList([MLPModule(d_hid) for _ in range(n_layers)])
# For testing purpose only, this should be defined by user
self.split_spec = {
f"layers.{i}": ... | MultiMLP |
python | lepture__authlib | authlib/integrations/flask_client/apps.py | {
"start": 1590,
"end": 2417
} | class ____(FlaskAppMixin, OAuth1Mixin, BaseApp):
client_cls = OAuth1Session
def authorize_access_token(self, **kwargs):
"""Fetch access token in one step.
:return: A token dict.
"""
params = request.args.to_dict(flat=True)
state = params.get("oauth_token")
if no... | FlaskOAuth1App |
python | pytorch__pytorch | test/jit/test_device_analysis.py | {
"start": 395,
"end": 11473
} | class ____(JitTestCase):
@classmethod
def setUpClass(cls):
cls.cpu = torch.device("cpu")
cls.cuda = torch.device("cuda")
cls.vulkan = torch.device("vulkan")
cls.mkldnn = torch.device(
"mkldnn"
) # MKLDNN can't mix with other device types at all
cls.de... | TestDeviceAnalysis |
python | python-pillow__Pillow | src/PIL/ExifTags.py | {
"start": 8197,
"end": 9126
} | class ____(IntEnum):
GPSVersionID = 0x00
GPSLatitudeRef = 0x01
GPSLatitude = 0x02
GPSLongitudeRef = 0x03
GPSLongitude = 0x04
GPSAltitudeRef = 0x05
GPSAltitude = 0x06
GPSTimeStamp = 0x07
GPSSatellites = 0x08
GPSStatus = 0x09
GPSMeasureMode = 0x0A
GPSDOP = 0x0B
GPSSpeed... | GPS |
python | jschneier__django-storages | tests/test_s3.py | {
"start": 37685,
"end": 39308
} | class ____(TestCase):
def setUp(self) -> None:
self.storage = s3.S3Storage()
self.storage._connections.connection = mock.MagicMock()
def test_loading_ssec(self):
params = {"SSECustomerKey": "xyz", "CacheControl": "never"}
self.storage.get_object_parameters = lambda name: params
... | S3FileTests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.