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 | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_data_validation04.py | {
"start": 315,
"end": 2514
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("data_validation02.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file data validation."""
workbook = Wo... | TestCompareXLSXFiles |
python | pikepdf__pikepdf | src/pikepdf/models/outlines.py | {
"start": 421,
"end": 3044
} | class ____(Enum):
"""Page view location definitions, from PDF spec."""
XYZ = 1
Fit = 2
FitH = 3
FitV = 4
FitR = 5
FitB = 6
FitBH = 7
FitBV = 8
PAGE_LOCATION_ARGS = {
PageLocation.XYZ: ('left', 'top', 'zoom'),
PageLocation.FitH: ('top',),
PageLocation.FitV: ('left',),
... | PageLocation |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-airbyte-hubspot/llama_index/readers/airbyte_hubspot/base.py | {
"start": 126,
"end": 701
} | class ____(AirbyteCDKReader):
"""
AirbyteHubspotReader reader.
Retrieve documents from Hubspot
Args:
config: The config object for the hubspot source.
"""
def __init__(
self,
config: Mapping[str, Any],
record_handler: Optional[RecordHandler] = None,
) -> N... | AirbyteHubspotReader |
python | PyCQA__pylint | tests/functional/p/protocol_classes_abstract.py | {
"start": 1031,
"end": 1203
} | class ____(FooBarProtocol):
"""FooBar object"""
def bar(self) -> Literal["bar"]:
return "bar"
def foo(self) -> Literal["foo"]:
return "foo"
| FooBar |
python | FactoryBoy__factory_boy | tests/djapp/models.py | {
"start": 491,
"end": 616
} | class ____(models.Model):
slug = models.SlugField(max_length=20, unique=True)
text = models.TextField()
| MultifieldModel |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_roman_numeral.py | {
"start": 1661,
"end": 3889
} | class ____(ColumnMapExpectation):
"""Expect column values to be valid Roman Numerals."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"well_formed_roman_numeral": [
... | ExpectColumnValuesToBeValidRomanNumeral |
python | walkccc__LeetCode | solutions/3131. Find the Integer Added to Array I/3131.py | {
"start": 0,
"end": 120
} | class ____:
def addedInteger(self, nums1: list[int], nums2: list[int]) -> int:
return min(nums2) - min(nums1)
| Solution |
python | getsentry__sentry | tests/sentry/db/models/fields/test_jsonfield.py | {
"start": 6529,
"end": 6778
} | class ____(TestCase):
def test_saving_null(self) -> None:
obj = BlankJSONFieldTestModel.objects.create(blank_json="", null_json=None)
self.assertEqual("", obj.blank_json)
self.assertEqual(None, obj.null_json)
| SavingModelsTest |
python | pytorch__pytorch | torch/__init__.py | {
"start": 71867,
"end": 72089
} | class ____(_LegacyStorage):
@classproperty
def dtype(self):
_warn_typed_storage_removal(stacklevel=3)
return self._dtype
@classproperty
def _dtype(self):
return torch.int8
| CharStorage |
python | getsentry__sentry | src/sentry/integrations/messaging/commands.py | {
"start": 3169,
"end": 5866
} | class ____(Generic[R], ABC):
"""The set of commands handled by one messaging integration."""
@property
@abstractmethod
def integration_spec(self) -> MessagingIntegrationSpec:
raise NotImplementedError
@property
@abstractmethod
def command_handlers(
self,
) -> Iterable[t... | MessagingIntegrationCommandDispatcher |
python | getsentry__sentry | src/sentry/tempest/migrations/0001_squashed_0002_make_message_type_nullable.py | {
"start": 325,
"end": 3332
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | spyder-ide__spyder | spyder/plugins/projects/widgets/projectexplorer.py | {
"start": 582,
"end": 4180
} | class ____(QSortFilterProxyModel):
"""Proxy model to filter tree view."""
PATHS_TO_HIDE = [
# Useful paths
'.spyproject',
'__pycache__',
'.ipynb_checkpoints',
# VCS paths
'.git',
'.hg',
'.svn',
# Others
'.pytest_cache',
'.D... | ProxyModel |
python | pytorch__pytorch | torch/cuda/__init__.py | {
"start": 23343,
"end": 54609
} | class ____:
r"""Context-manager that selects a given stream.
All CUDA kernels queued within its context will be enqueued on a selected
stream.
Args:
Stream (Stream): selected stream. This manager is a no-op if it's
``None``.
.. note:: Streams are per-device.
"""
cur_st... | StreamContext |
python | scrapy__scrapy | tests/test_http_response.py | {
"start": 36942,
"end": 38789
} | class ____(TestTextResponse):
response_class = CustomResponse
def test_copy(self):
super().test_copy()
r1 = self.response_class(
url="https://example.org",
status=200,
foo="foo",
bar="bar",
lost="lost",
)
r2 = r1.copy()... | TestCustomResponse |
python | sympy__sympy | sympy/plotting/experimental_lambdify.py | {
"start": 7949,
"end": 22828
} | class ____:
def __init__(self, args, expr, print_lambda=False, use_evalf=False,
float_wrap_evalf=False, complex_wrap_evalf=False,
use_np=False, use_python_math=False, use_python_cmath=False,
use_interval=False):
self.print_lambda = print_lambda
sel... | Lambdifier |
python | walkccc__LeetCode | solutions/2588. Count the Number of Beautiful Subarrays/2588.py | {
"start": 0,
"end": 319
} | class ____:
def beautifulSubarrays(self, nums: list[int]) -> int:
# A subarray is beautiful if xor(subarray) = 0.
ans = 0
prefix = 0
prefixCount = collections.Counter({0: 1})
for num in nums:
prefix ^= num
ans += prefixCount[prefix]
prefixCount[prefix] += 1
return ans
| Solution |
python | sympy__sympy | sympy/matrices/expressions/special.py | {
"start": 8021,
"end": 10337
} | class ____(MatrixExpr):
"""
Matrix with only one nonzero entry with value 1. Also called single-entry matrix.
https://en.wikipedia.org/wiki/Matrix_unit
Examples
========
Create a matrix unit of shape `(3, 4)` with unit entry at the second row
and third column, i.e. at `(1, 2)`
>>> fr... | MatrixUnit |
python | kamyu104__LeetCode-Solutions | Python/find-x-value-of-array-ii.py | {
"start": 67,
"end": 2777
} | class ____(object):
def resultArray(self, nums, k, queries):
"""
:type nums: List[int]
:type k: int
:type queries: List[List[int]]
:rtype: List[int]
"""
# Template:
# https://github.com/kamyu104/LeetCode-Solutions/blob/master/Python/block-placement-que... | Solution |
python | Textualize__textual | src/textual/css/stylesheet.py | {
"start": 1310,
"end": 4048
} | class ____:
"""A renderable for stylesheet errors."""
def __init__(self, rules: list[RuleSet]) -> None:
self.rules = rules
self.variables: dict[str, str] = {}
@classmethod
def _get_snippet(cls, code: str, line_no: int) -> RenderableType:
from rich.syntax import Syntax
... | StylesheetErrors |
python | openai__openai-python | src/openai/types/responses/response_prompt.py | {
"start": 495,
"end": 936
} | class ____(BaseModel):
id: str
"""The unique identifier of the prompt template to use."""
variables: Optional[Dict[str, Variables]] = None
"""Optional map of values to substitute in for variables in your prompt.
The substitution values can either be strings, or other Response input types
like ... | ResponsePrompt |
python | fastai__fastai | fastai/medical/imaging.py | {
"start": 5879,
"end": 6081
} | class ____(TensorImageBW):
"Inherits from `TensorImageBW` and converts the `pixel_array` into a `TensorCTScan`"
_show_args = {'cmap':'bone'}
# %% ../../nbs/60_medical.imaging.ipynb 49
| TensorCTScan |
python | Netflix__metaflow | metaflow/extension_support/__init__.py | {
"start": 48260,
"end": 50190
} | class ____(Loader):
def __init__(
self,
fullname,
orig_loader,
previously_loaded_module=None,
previously_loaded_parent_module=None,
):
self._fullname = fullname
self._orig_loader = orig_loader
self._previously_loaded_module = previously_loaded_modu... | _OrigLoader |
python | pypa__setuptools | setuptools/_distutils/compilers/C/errors.py | {
"start": 362,
"end": 492
} | class ____(Error):
"""Failure to link one or more C/C++ object files into an executable
or shared library file."""
| LinkError |
python | getsentry__sentry | src/sentry/issues/endpoints/group_tags.py | {
"start": 778,
"end": 3676
} | class ____(GroupEndpoint):
publish_status = {
"GET": ApiPublishStatus.UNKNOWN,
}
enforce_rate_limit = True
rate_limits = RateLimitConfig(
limit_overrides={
"GET": {
RateLimitCategory.IP: RateLimit(limit=10, window=1, concurrent_limit=10),
Rate... | GroupTagsEndpoint |
python | redis__redis-py | redis/commands/policies.py | {
"start": 8558,
"end": 9350
} | class ____(BasePolicyResolver):
"""
Resolves policy dynamically based on the COMMAND output.
"""
def __init__(
self, commands_parser: CommandsParser, fallback: Optional[PolicyResolver] = None
) -> None:
"""
Parameters:
commands_parser (CommandsParser): COMMAND ou... | DynamicPolicyResolver |
python | facelessuser__pymdown-extensions | tools/collapse_code.py | {
"start": 431,
"end": 2620
} | class ____(Block):
"""Collapse code."""
NAME = 'collapse-code'
def on_init(self):
"""Handle initialization."""
# Track tab group count across the entire page.
if 'collapse_code_count' not in self.tracker:
self.tracker['collapse_code_count'] = 0
self.expand = s... | CollapseCode |
python | kubernetes-client__python | kubernetes/client/models/v1_persistent_volume_claim_volume_source.py | {
"start": 383,
"end": 5132
} | 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... | V1PersistentVolumeClaimVolumeSource |
python | apache__airflow | task-sdk/src/airflow/sdk/definitions/_internal/node.py | {
"start": 2586,
"end": 13269
} | class ____(DependencyMixin, metaclass=ABCMeta):
"""
A base class for a node in the graph of a workflow.
A node may be an Operator or a Task Group, either mapped or unmapped.
"""
dag: DAG | None
task_group: TaskGroup | None
"""The task_group that contains this node"""
start_date: dateti... | DAGNode |
python | huggingface__transformers | src/transformers/models/focalnet/modeling_focalnet.py | {
"start": 14966,
"end": 17550
} | class ____(nn.Module):
r"""Focal Modulation Network layer (block).
Args:
config (`FocalNetConfig`):
Model config.
index (`int`):
Layer index.
dim (`int`):
Number of input channels.
input_resolution (`tuple[int]`):
Input resolution.... | FocalNetLayer |
python | anthropics__anthropic-sdk-python | src/anthropic/resources/beta/messages/batches.py | {
"start": 17377,
"end": 33646
} | class ____(AsyncAPIResource):
@cached_property
def with_raw_response(self) -> AsyncBatchesWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
the raw response object instead of the parsed content.
For more information, see https://www.gi... | AsyncBatches |
python | huggingface__transformers | src/transformers/models/llava_next_video/modular_llava_next_video.py | {
"start": 9142,
"end": 10668
} | class ____(LlavaNextCausalLMOutputWithPast):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss (for next-token prediction).
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
Predicti... | LlavaNextVideoCausalLMOutputWithPast |
python | geekcomputers__Python | nodepad/notepad.py | {
"start": 959,
"end": 8226
} | class ____:
def __init__(self, top=None):
"""This class configures and populates the toplevel window.
top is the toplevel containing window."""
_bgcolor = "#d9d9d9" # X11 color: 'gray85'
_fgcolor = "#000000" # X11 color: 'black'
_compcolor = "#d9d9d9" # X11 color: 'gray85'... | Notepads_managment |
python | mlflow__mlflow | tests/openai/mock_openai.py | {
"start": 9637,
"end": 10816
} | class ____(BaseModel):
input: Any
tools: list[Any] | None = None
stream: bool = False
@app.post("/responses", response_model_exclude_unset=True)
async def responses(payload: ResponsesPayload):
if payload.stream:
content = (
f"event: {d['type']}\ndata: {json.dumps(d)}\n\n" for d in ... | ResponsesPayload |
python | huggingface__transformers | src/transformers/convert_slow_tokenizer.py | {
"start": 10075,
"end": 11668
} | class ____(Converter):
def converted(self) -> Tokenizer:
vocab = self.original_tokenizer.vocab
tokenizer = Tokenizer(WordPiece(vocab, unk_token=str(self.original_tokenizer.unk_token)))
tokenize_chinese_chars = False
strip_accents = False
do_lower_case = False
if hasa... | MPNetConverter |
python | redis__redis-py | tests/test_asyncio/test_multidb/test_failover.py | {
"start": 380,
"end": 2261
} | class ____:
@pytest.mark.asyncio
@pytest.mark.parametrize(
"mock_db,mock_db1,mock_db2",
[
(
{"weight": 0.2, "circuit": {"state": CBState.CLOSED}},
{"weight": 0.7, "circuit": {"state": CBState.CLOSED}},
{"weight": 0.5, "circuit": {"state... | TestAsyncWeightBasedFailoverStrategy |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 3782,
"end": 4046
} | class ____(AbstractTemplate):
key = "iternext"
def generic(self, args, kws):
assert not kws
[it] = args
if isinstance(it, types.IteratorType):
return signature(types.Pair(it.yield_type, types.boolean), it)
@infer
| IterNext |
python | tox-dev__tox | src/tox/config/source/ini_section.py | {
"start": 140,
"end": 643
} | class ____(Section):
@classmethod
def test_env(cls, name: str) -> IniSection:
return cls(TEST_ENV_PREFIX, name)
@property
def is_test_env(self) -> bool:
return self.prefix == TEST_ENV_PREFIX
@property
def names(self) -> list[str]:
return list(extend_factors(self.name))
... | IniSection |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 224948,
"end": 226077
} | class ____(Response):
"""
Response of tasks.delete_artifacts endpoint.
:param deleted: Indicates if the task was updated successfully
:type deleted: int
"""
_service = "tasks"
_action = "delete_artifacts"
_version = "2.23"
_schema = {
"definitions": {},
"properties... | DeleteArtifactsResponse |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance1.py | {
"start": 2096,
"end": 2177
} | class ____:
def __init__(self) -> None:
self.property = True
| TestClass1 |
python | Pylons__pyramid | tests/test_urldispatch.py | {
"start": 11197,
"end": 18419
} | class ____(unittest.TestCase):
def _callFUT(self, pattern):
from pyramid.urldispatch import _compile_route
return _compile_route(pattern)
def test_no_star(self):
matcher, generator = self._callFUT('/foo/:baz/biz/:buz/bar')
self.assertEqual(
matcher('/foo/baz/biz/buz... | TestCompileRoute |
python | huggingface__transformers | tests/models/mra/test_modeling_mra.py | {
"start": 1279,
"end": 9807
} | class ____:
def __init__(
self,
parent,
batch_size=2,
# must be [== max_position_embeddings] AND [multiple of block_size (default = 32)] (?)
seq_length=64,
is_training=True,
use_input_mask=True,
use_token_type_ids=True,
use_labels=True,
... | MraModelTester |
python | langchain-ai__langchain | libs/partners/openai/tests/integration_tests/chat_models/test_base.py | {
"start": 40584,
"end": 40658
} | class ____(BaseModel):
response: str
explanation: str
| ResponseFormat |
python | justquick__django-activity-stream | actstream/migrations/0002_remove_action_data.py | {
"start": 146,
"end": 428
} | class ____(migrations.Migration):
dependencies = [
('actstream', '0001_initial'),
]
if not USE_JSONFIELD:
operations = [
migrations.RemoveField(
model_name='action',
name='data',
),
]
| Migration |
python | allegroai__clearml | clearml/backend_api/services/v2_20/queues.py | {
"start": 78651,
"end": 79944
} | class ____(Response):
"""
Response of queues.move_task_to_back endpoint.
:param position: The new position of the task entry in the queue (index, -1 represents bottom of queue)
:type position: int
"""
_service = "queues"
_action = "move_task_to_back"
_version = "2.20"
_schema = {
... | MoveTaskToBackResponse |
python | pytorch__pytorch | test/higher_order_ops/test_invoke_subgraph.py | {
"start": 48619,
"end": 50746
} | class ____(torch.nn.Module):
def forward(self, L_x_: "f32[8, 8]"):
l_x_ = L_x_
subgraph_0 = self.subgraph_0
invoke_subgraph = torch.ops.higher_order.invoke_subgraph(subgraph_0, 'subgraph_0', l_x_); subgraph_0 = None
getitem: "f32[8, 8]" = invoke_subgraph[0]; invoke_subgraph = None... | GraphModule |
python | pypa__setuptools | pkg_resources/tests/test_resources.py | {
"start": 21804,
"end": 26764
} | class ____:
def testEmptyParse(self):
assert list(parse_requirements('')) == []
def testYielding(self):
for inp, out in [
([], []),
('x', ['x']),
([[]], []),
(' x\n y', ['x', 'y']),
(['x\n\n', 'y'], ['x', 'y']),
]:
... | TestParsing |
python | pennersr__django-allauth | allauth/socialaccount/providers/line/provider.py | {
"start": 404,
"end": 1036
} | class ____(OAuth2Provider):
id = "line"
name = "Line"
account_class = LineAccount
oauth2_adapter_class = LineOAuth2Adapter
def get_default_scope(self):
return []
def extract_uid(self, data):
return str(data.get("userId") or data.get("sub"))
def extract_common_fields(self, ... | LineProvider |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_table36.py | {
"start": 315,
"end": 1586
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("table36.xlsx")
self.ignore_files = [
"xl/calcChain.xml",
"[Content_Types].xml",
"xl/_rels/workbook.xml.rels... | TestCompareXLSXFiles |
python | zarr-developers__zarr-python | src/zarr/codecs/blosc.py | {
"start": 1176,
"end": 1349
} | class ____(TypedDict):
"""Configuration for the V3 Blosc codec"""
cname: CName
clevel: int
shuffle: Shuffle
blocksize: int
typesize: int
| BloscConfigV3 |
python | scrapy__scrapy | tests/test_command_parse.py | {
"start": 4763,
"end": 15092
} | class ____:
component_name = 'my_pipeline'
def process_item(self, item):
logging.info('It Works!')
return item
""",
encoding="utf-8",
)
with (proj_mod_path / "settings.py").open("a", encoding="utf-8") as f:
f.write(
f"""
ITEM_PIPELINES = ... | MyPipeline |
python | bokeh__bokeh | src/bokeh/core/property/primitive.py | {
"start": 1552,
"end": 1901
} | class ____(PrimitiveProperty[None]):
""" Accept only ``None`` value.
Use this in conjunction with ``Either(Null, Type)`` or as ``Nullable(Type)``.
"""
_underlying_type = (type(None),)
def __init__(self, default: Init[None] = None, *, help: str | None = None) -> None:
super().__init__(... | Null |
python | encode__django-rest-framework | tests/test_routers.py | {
"start": 9505,
"end": 10579
} | class ____(URLPatternsTestCase, TestCase):
"""
Ensure the router honors lookup_url_kwarg.
Setup a deep lookup_field, but map it to a simple URL kwarg.
"""
urlpatterns = [
path('example/', include(notes_router.urls)),
path('example2/', include(kwarged_notes_router.urls)),
]
... | TestLookupUrlKwargs |
python | tensorflow__tensorflow | tensorflow/python/summary/writer/writer_test.py | {
"start": 19661,
"end": 26688
} | class ____(FileWriterTestBase, test.TestCase):
"""Tests for FileWriter behavior when passed a Session argument."""
def _FileWriter(self, *args, **kwargs):
if "session" not in kwargs:
# Pass in test_session() as the session. It will be cached during this
# test method invocation so that any other us... | SessionBasedFileWriterTestCase |
python | miyuchina__mistletoe | test/test_span_token.py | {
"start": 7464,
"end": 7748
} | class ____(unittest.TestCase):
def test_contains(self):
token = next(iter(span_token.tokenize_inner('**with some *emphasis* text**')))
self.assertTrue('text' in token)
self.assertTrue('emphasis' in token)
self.assertFalse('foo' in token)
| TestContains |
python | astropy__astropy | astropy/utils/metadata/tests/test_metadata.py | {
"start": 369,
"end": 1826
} | class ____:
def test_none(self):
d = self.test_class(*self.args)
assert isinstance(d.meta, dict)
assert len(d.meta) == 0
@pytest.mark.parametrize(
"meta",
([{"a": 1}, OrderedDict([("a", 1)]), OrderedDictSubclass([("a", 1)])]),
)
def test_mapping_init(self, meta):... | MetaBaseTest |
python | scipy__scipy | scipy/optimize/tests/test_minimize_constrained.py | {
"start": 8014,
"end": 8782
} | class ____(Rosenbrock):
"""Rosenbrock subject to equality and inequality constraints.
The following optimization problem:
minimize sum(100.0*(x[1] - x[0]**2)**2.0 + (1 - x[0])**2)
subject to: x[0] + 2 x[1] <= 1
2 x[0] + x[1] = 1
Taken from matlab ``fimincon`` documentat... | EqIneqRosenbrock |
python | getsentry__sentry | src/sentry/replays/usecases/query/conditions/error_ids.py | {
"start": 570,
"end": 1153
} | class ____(ComputedBase):
"""Error ids array condition visitor."""
@staticmethod
def visit_eq(value: UUID) -> Condition:
return Condition(has_error_id(value), Op.EQ, 1)
@staticmethod
def visit_neq(value: UUID) -> Condition:
return Condition(has_error_id(value), Op.EQ, 0)
@stat... | ErrorIdsArray |
python | tensorflow__tensorflow | tensorflow/python/framework/sparse_tensor_test.py | {
"start": 6042,
"end": 8392
} | class ____(test_util.TensorFlowTestCase):
def test_simple(self):
indices = [[0, 2]]
values = [1]
dense_shape = [5, 5]
sp = sparse_tensor.SparseTensor(indices, values, dense_shape)
self.assertIsInstance(sp.shape, tensor_shape.TensorShape)
self.assertIsInstance(sp.dense_shape, tensor_lib.Tenso... | SparseTensorShapeTest |
python | django__django | tests/gis_tests/geoapp/models.py | {
"start": 349,
"end": 437
} | class ____(NamedModel):
mpoly = models.MultiPolygonField(srid=3857)
| CountryWebMercator |
python | allegroai__clearml | clearml/backend_api/services/v2_23/models.py | {
"start": 112079,
"end": 113526
} | class ____(Request):
"""
Get the list of frameworks used in the company models
:param projects: The list of projects which models will be analyzed. If not
passed or empty then all the company and public models will be analyzed
:type projects: Sequence[str]
"""
_service = "models"
_... | GetFrameworksRequest |
python | realpython__materials | python-del-statement/non_deletable.py | {
"start": 0,
"end": 231
} | class ____:
def __init__(self, value):
self.value = value
def __delattr__(self, name):
raise AttributeError(
f"{type(self).__name__} object doesn't support attribute deletion"
)
| NonDeletable |
python | python__mypy | mypy/test/test_config_parser.py | {
"start": 822,
"end": 4167
} | class ____(unittest.TestCase):
def test_no_config(self) -> None:
with tempfile.TemporaryDirectory() as _tmpdir:
tmpdir = Path(_tmpdir)
(tmpdir / ".git").touch()
with chdir(tmpdir):
result = _find_config_file()
assert result is None
de... | FindConfigFileSuite |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/reader.py | {
"start": 2433,
"end": 10732
} | class ____:
# Reader:
# - determines the data encoding and converts it to a unicode string,
# - checks if characters are in allowed range,
# - adds '\0' to the end.
# Reader accepts
# - a `bytes` object,
# - a `str` object,
# - a file-like object with its `read` method returning `str... | Reader |
python | pytorch__pytorch | .github/scripts/test_trymerge.py | {
"start": 42927,
"end": 44709
} | class ____(TestCase):
# Tests for _revlist_to_prs function
def test__revlist_to_prs_zero_matches(
self, mock_commit_message: mock.MagicMock, *args: Any
) -> None:
# If zero PRs are mentioned in the commit message, it should raise an error
pr_num = 154098
pr = GitHubPR("pytorc... | TestRevListToPR |
python | cython__cython | runtests.py | {
"start": 64833,
"end": 65456
} | class ____(CythonRunTestCase):
def shortDescription(self):
return "[%d] compiling (%s) tests in %s" % (
self.shard_num, self.language, self.description_name())
def run_tests(self, result, ext_so_path):
with self.stats.time(self.name, self.language, 'import'):
module = im... | CythonUnitTestCase |
python | catalyst-team__catalyst | catalyst/contrib/layers/rms_norm.py | {
"start": 100,
"end": 1297
} | class ____(nn.Module):
"""An implementation of RMS Normalization.
@TODO: Docs (link to paper). Contribution is welcome.
"""
def __init__(self, dimension: int, epsilon: float = 1e-8, is_bias: bool = False):
"""
Args:
dimension: the dimension of the layer output to normalize
... | RMSNorm |
python | kamyu104__LeetCode-Solutions | Python/longest-nice-subarray.py | {
"start": 60,
"end": 470
} | class ____(object):
def longestNiceSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = left = curr = 0
for right in xrange(len(nums)):
while curr&nums[right]:
curr ^= nums[left]
left += 1
cur... | Solution |
python | viewflow__viewflow | viewflow/jsonstore.py | {
"start": 7519,
"end": 7576
} | class ____(JSONFieldMixin, BaseJSONField):
pass
| JSONField |
python | gevent__gevent | src/greentest/3.9/test_socket.py | {
"start": 239959,
"end": 248155
} | class ____(unittest.TestCase):
# tests for AF_ALG
def create_alg(self, typ, name):
sock = socket.socket(socket.AF_ALG, socket.SOCK_SEQPACKET, 0)
try:
sock.bind((typ, name))
except FileNotFoundError as e:
# type / algorithm is not available
sock.close()... | LinuxKernelCryptoAPI |
python | huggingface__transformers | src/transformers/models/depth_pro/modeling_depth_pro.py | {
"start": 37655,
"end": 42359
} | class ____(DepthProPreTrainedModel):
def __init__(self, config, use_fov_model=None):
r"""
use_fov_model (bool, *optional*):
Whether to use the field of view model.
"""
super().__init__(config)
self.config = config
self.use_fov_model = use_fov_model if use_... | DepthProForDepthEstimation |
python | django-compressor__django-compressor | compressor/tests/test_offline.py | {
"start": 18073,
"end": 18750
} | class ____(OfflineTestCaseMixin, TestCase):
templates_dir = "test_with_context"
expected_hash = ["8b4a7452e1c5", "55b3123e884c", "bfc63829cc58"]
additional_test_settings = {
"COMPRESS_OFFLINE_CONTEXT": "compressor.tests.test_offline."
"offline_context_generator"
}
def _prepare_conte... | OfflineCompressTestCaseWithContextGenerator |
python | ray-project__ray | python/ray/serve/llm/__init__.py | {
"start": 940,
"end": 1093
} | class ____(_LLMServingArgs):
"""The configuration for starting an LLM deployment application."""
pass
@PublicAPI(stability="alpha")
| LLMServingArgs |
python | sympy__sympy | sympy/multipledispatch/tests/test_core.py | {
"start": 1044,
"end": 4048
} | class ____(C): pass
def test_inheritance():
@dispatch(A)
def f(x): # noqa:F811
return 'a'
@dispatch(B) # noqa:F811
def f(x): # noqa:F811
return 'b'
assert f(A()) == 'a'
assert f(B()) == 'b'
assert f(C()) == 'a'
def test_inheritance_and_multiple_dispatch():
@dispatch... | E |
python | Lightning-AI__lightning | tests/tests_pytorch/callbacks/test_pruning.py | {
"start": 1117,
"end": 1573
} | class ____(BoringModel):
def __init__(self):
super().__init__()
self.layer = Sequential(
OrderedDict([
("mlp_1", nn.Linear(32, 32)),
("mlp_2", nn.Linear(32, 32, bias=False)),
("mlp_3", nn.Linear(32, 2)),
])
)
def tr... | TestModel |
python | django__django | tests/generic_views/models.py | {
"start": 1288,
"end": 1397
} | class ____(models.Model):
content = models.TextField()
template = models.CharField(max_length=255)
| Page |
python | pandas-dev__pandas | pandas/io/formats/format.py | {
"start": 55905,
"end": 61237
} | class ____(_GenericArrayFormatter):
values: TimedeltaArray
def __init__(
self,
values: TimedeltaArray,
nat_rep: str = "NaT",
**kwargs,
) -> None:
# TODO: nat_rep is never passed, na_rep is.
super().__init__(values, **kwargs)
self.nat_rep = nat_rep
... | _Timedelta64Formatter |
python | doocs__leetcode | solution/0600-0699/0670.Maximum Swap/Solution.py | {
"start": 0,
"end": 395
} | class ____:
def maximumSwap(self, num: int) -> int:
s = list(str(num))
n = len(s)
d = list(range(n))
for i in range(n - 2, -1, -1):
if s[i] <= s[d[i + 1]]:
d[i] = d[i + 1]
for i, j in enumerate(d):
if s[i] < s[j]:
s[i], ... | Solution |
python | pyinstaller__pyinstaller | tests/unit/test_modulegraph/test_imports.py | {
"start": 158,
"end": 2400
} | class ____ (unittest.TestCase):
# The tests check that Python's import statement
# works as these tests expect.
def importModule(self, name):
if '.' in name:
script = textwrap.dedent("""\
try:
import %s
except ImportError:
... | TestNativeImport |
python | mitmproxy__pdoc | pdoc/doc.py | {
"start": 6618,
"end": 13742
} | class ____(Doc[U], metaclass=ABCMeta):
"""
A documentation object that can have children. In other words, either a module or a class.
"""
@cached_property
@abstractmethod
def _member_objects(self) -> dict[str, Any]:
"""
A mapping from *all* public and private member names to the... | Namespace |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-quip/llama_index/readers/quip/base.py | {
"start": 284,
"end": 3317
} | class ____(BasePydanticReader):
access_token: str = Field(description="Quip API access token")
request_timeout: Optional[float] = Field(
default=None, description="Request timeout in seconds"
)
headers: Dict[str, str] = Field(
default=None, description="Headers to be sent with the reques... | QuipReader |
python | getsentry__sentry | src/sentry/seer/fetch_issues/utils.py | {
"start": 1383,
"end": 5584
} | class ____(TypedDict):
issues: list[int]
issues_full: list[dict[str, Any]]
def get_repo_and_projects(
organization_id: int,
provider: str,
external_id: str,
run_id: int | None = None,
) -> RepoProjects:
"""
Returns auxilliary info about the repo and its projects.
This info is often... | SeerResponse |
python | HIPS__autograd | examples/rkhs.py | {
"start": 361,
"end": 934
} | class ____:
def __init__(self, kernel, alphas={}):
self.alphas = alphas
self.kernel = kernel
self.vs = RKHSFunVSpace(self)
@primitive
def __call__(self, x):
return sum([a * self.kernel(x, x_repr) for x_repr, a in self.alphas.items()], 0.0)
def __add__(self, f):
... | RKHSFun |
python | apache__airflow | providers/google/tests/unit/google/suite/transfers/test_sql_to_sheets.py | {
"start": 955,
"end": 2083
} | class ____:
"""
Test class for SQLToGoogleSheetsOperator
"""
def setup_method(self):
"""
setup
"""
self.gcp_conn_id = "test"
self.sql_conn_id = "test"
self.sql = "select 1 as my_col"
self.spreadsheet_id = "1234567890"
self.values = [[1, 2... | TestSQLToGoogleSheets |
python | walkccc__LeetCode | solutions/539. Minimum Time Difference/539.py | {
"start": 0,
"end": 325
} | class ____:
def findMinDifference(self, timePoints: list[str]) -> int:
ans = 24 * 60
nums = sorted([int(timePoint[:2]) * 60 + int(timePoint[3:])
for timePoint in timePoints])
for a, b in zip(nums, nums[1:]):
ans = min(ans, b - a)
return min(ans, 24 * 60 - nums[-1] + nums[0])... | Solution |
python | ipython__ipython | IPython/core/history.py | {
"start": 36361,
"end": 41537
} | class ____(threading.Thread):
"""This thread takes care of writing history to the database, so that
the UI isn't held up while that happens.
It waits for the HistoryManager's save_flag to be set, then writes out
the history cache. The main thread is responsible for setting the flag when
the cache s... | HistorySavingThread |
python | huggingface__transformers | src/transformers/models/vit_mae/modeling_vit_mae.py | {
"start": 18256,
"end": 18913
} | class ____(nn.Module):
def __init__(self, config: ViTMAEConfig):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.inte... | ViTMAEIntermediate |
python | cython__cython | Cython/Compiler/PyrexTypes.py | {
"start": 84478,
"end": 85181
} | class ____(CIntType):
to_py_function = "__Pyx_Owned_Py_None"
is_returncode = True
exception_check = False
default_format_spec = ''
def specialization_name(self):
# I don't think we should end up creating PyLong_As_int/PyLong_From_int functions
# for this type, but it's better they... | CReturnCodeType |
python | doocs__leetcode | solution/2200-2299/2274.Maximum Consecutive Floors Without Special Floors/Solution.py | {
"start": 0,
"end": 273
} | class ____:
def maxConsecutive(self, bottom: int, top: int, special: List[int]) -> int:
special.sort()
ans = max(special[0] - bottom, top - special[-1])
for x, y in pairwise(special):
ans = max(ans, y - x - 1)
return ans
| Solution |
python | python-visualization__folium | folium/plugins/search.py | {
"start": 370,
"end": 5650
} | class ____(JSCSSMixin, MacroElement):
"""
Adds a search tool to your map.
Parameters
----------
layer: GeoJson, TopoJson, FeatureGroup, MarkerCluster class object.
The map layer to index in the Search view.
search_label: str, optional
'properties' key in layer to index Search, i... | Search |
python | google__jax | jax/experimental/source_mapper/common.py | {
"start": 1275,
"end": 2508
} | class ____:
name: str
compile_fn: CompileFn
generate_dump: GenerateDumpFn
_pass_registry = {}
def register_pass(pass_: Pass):
if pass_.name in _pass_registry:
raise ValueError(f"Pass {pass_.name} already registered")
_pass_registry[pass_.name] = pass_
def all_passes() -> Sequence[Pass]:
return lis... | Pass |
python | getsentry__sentry | tests/sentry/incidents/endpoints/test_organization_alert_rule_index.py | {
"start": 9798,
"end": 71291
} | class ____(AlertRuleIndexBase, SnubaTestCase):
method = "post"
@assume_test_silo_mode(SiloMode.CONTROL)
def setUp(self) -> None:
super().setUp()
self.create_member(
user=self.user, organization=self.organization, role="owner", teams=[self.team]
)
self.login_as(s... | AlertRuleCreateEndpointTest |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 310619,
"end": 311927
} | class ____(ExprNode):
# Convert argument to tuple. Used for normalising
# the * argument of a function call.
#
# arg ExprNode
subexprs = ['arg']
is_temp = 1
def calculate_constant_result(self):
self.constant_result = tuple(self.arg.constant_result)
def compile_time_value... | AsTupleNode |
python | davidhalter__jedi | jedi/plugins/pytest.py | {
"start": 8098,
"end": 10339
} | class ____(ParserTreeFilter):
def _filter(self, names):
for name in super()._filter(names):
# look for fixture definitions of imported names
if name.parent.type == "import_from":
imported_names = goto_import(self.parent_context, name)
if any(
... | FixtureFilter |
python | getsentry__sentry | src/sentry/incidents/models/alert_rule.py | {
"start": 1863,
"end": 2036
} | class ____(models.TextChoices):
LOW = "low", gettext_lazy("Low")
MEDIUM = "medium", gettext_lazy("Medium")
HIGH = "high", gettext_lazy("High")
| AlertRuleSensitivity |
python | getsentry__sentry | src/sentry/models/files/abstractfileblobindex.py | {
"start": 111,
"end": 280
} | class ____(Model):
__relocation_scope__ = RelocationScope.Excluded
offset = WrappingU32IntegerField()
class Meta:
abstract = True
| AbstractFileBlobIndex |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 526817,
"end": 527607
} | class ____(sgqlc.types.Interface):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("recent_projects",)
recent_projects = sgqlc.types.Field(
sgqlc.types.non_null(ProjectV2Connection),
graphql_name="recentProjects",
args=sgqlc.types.Ar... | ProjectV2Recent |
python | redis__redis-py | tests/test_credentials.py | {
"start": 1769,
"end": 1916
} | class ____(CredentialProvider):
def get_credentials(self) -> Union[Tuple[str], Tuple[str, str]]:
return "username", ""
| NoPassCredProvider |
python | streamlit__streamlit | lib/tests/streamlit/runtime/runtime_test.py | {
"start": 3943,
"end": 19959
} | class ____(RuntimeTestCase):
async def test_start_stop(self):
"""starting and stopping the Runtime should work as expected."""
assert self.runtime.state == RuntimeState.INITIAL
await self.runtime.start()
assert self.runtime.state == RuntimeState.NO_SESSIONS_CONNECTED
self.r... | RuntimeTest |
python | Netflix__metaflow | metaflow/plugins/cards/card_modules/components.py | {
"start": 33949,
"end": 35602
} | class ____(UserComponent):
"""
A component to display Python code with syntax highlighting.
Example:
```python
@card
@step
def my_step(self):
# Using code_func
def my_function():
x = 1
y = 2
return x + y
current.card.append(
... | PythonCode |
python | getsentry__sentry | src/sentry/utils/warnings.py | {
"start": 172,
"end": 1137
} | class ____(DeprecationWarning):
def __init__(
self,
setting: str,
replacement: str,
url: str | None = None,
removed_in_version: str | None = None,
):
self.setting = setting
self.replacement = replacement
self.url = url
self.removed_in_versi... | DeprecatedSettingWarning |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.