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 | xlwings__xlwings | xlwings/udfs.py | {
"start": 8364,
"end": 28421
} | class ____(Range):
"""
A Range subclass that stores the impl as
a serialized COM object so it can be passed between
threads easily
https://devblogs.microsoft.com/oldnewthing/20151021-00/?p=91311
"""
def __init__(self, rng):
super().__init__(impl=rng.impl)
self._ser_thread ... | ComRange |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_set_column11.py | {
"start": 315,
"end": 1673
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("set_column06.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
python | scrapy__scrapy | scrapy/downloadermiddlewares/httpauth.py | {
"start": 544,
"end": 1604
} | class ____:
"""Set Basic HTTP Authorization header
(http_user and http_pass spider class attributes)"""
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
o = cls()
crawler.signals.connect(o.spider_opened, signal=signals.spider_opened)
return o
def spider_opened(... | HttpAuthMiddleware |
python | ansible__ansible | test/units/parsing/vault/test_vault.py | {
"start": 25379,
"end": 42829
} | class ____(unittest.TestCase):
def setUp(self):
self.vault_password = "test-vault-password"
text_secret = TextVaultSecret(self.vault_password)
self.vault_secrets = [('default', text_secret),
('test_id', text_secret)]
self.v = vault.VaultLib(self.vault_se... | TestVaultLib |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 112172,
"end": 113300
} | class ____:
def test_format_timeframe(self):
assert self.locale._format_timeframe("now", 0) == "agora"
assert self.locale._format_timeframe("second", 1) == "um segundo"
assert self.locale._format_timeframe("seconds", 30) == "30 segundos"
assert self.locale._format_timeframe("minute",... | TestBrazilianPortugueseLocale |
python | doocs__leetcode | solution/0900-0999/0911.Online Election/Solution.py | {
"start": 0,
"end": 564
} | class ____:
def __init__(self, persons: List[int], times: List[int]):
cnt = Counter()
self.times = times
self.wins = []
cur = 0
for p in persons:
cnt[p] += 1
if cnt[cur] <= cnt[p]:
cur = p
self.wins.append(cur)
def q(s... | TopVotedCandidate |
python | huggingface__transformers | src/transformers/models/granite/configuration_granite.py | {
"start": 1168,
"end": 9190
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`GraniteModel`]. It is used to instantiate an Granite
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar conf... | GraniteConfig |
python | python-openxml__python-docx | tests/test_table.py | {
"start": 21861,
"end": 23103
} | class ____:
"""Unit-test suite for `docx.table._Columns` objects."""
def it_has_sequence_behaviors(self, table_: Mock):
columns = _Columns(cast(CT_Tbl, element("w:tbl/w:tblGrid/(w:gridCol,w:gridCol)")), table_)
# -- it supports len() --
assert len(columns) == 2
# -- it is itera... | Describe_Columns |
python | allegroai__clearml | clearml/backend_api/services/v2_9/events.py | {
"start": 88805,
"end": 89689
} | class ____(Request):
"""
:param task: Task ID
:type task: str
"""
_service = "events"
_action = "get_vector_metrics_and_variants"
_version = "2.9"
_schema = {
"definitions": {},
"properties": {"task": {"description": "Task ID", "type": "string"}},
"required": ["t... | GetVectorMetricsAndVariantsRequest |
python | django__django | tests/admin_changelist/models.py | {
"start": 2813,
"end": 2944
} | class ____(models.Manager):
def get_queryset(self):
return super().get_queryset().order_by("number")
| OrderedObjectManager |
python | google__pytype | pytype/rewrite/flow/frame_base.py | {
"start": 928,
"end": 3890
} | class ____(Generic[_T]):
"""Virtual machine frame.
Attributes:
_final_locals: The frame's `locals` dictionary after it finishes execution.
This is a protected attribute so that subclasses can choose whether and
how to expose control flow information.
current_opcode: The current opcode.
"""
... | FrameBase |
python | jina-ai__jina | jina/types/request/data.py | {
"start": 14234,
"end": 14701
} | class ____(DataRequest):
"""
Response is the :class:`~jina.types.request.Request` object returned by the flow.
At the moment it is an alias for :class:`~jina.types.request.Request`,
and therefore shares an identical representation.
Currently, its sole purpose is to give a more consistent semantic o... | Response |
python | celery__celery | celery/backends/dynamodb.py | {
"start": 667,
"end": 19580
} | class ____(KeyValueStoreBackend):
"""AWS DynamoDB result backend.
Raises:
celery.exceptions.ImproperlyConfigured:
if module :pypi:`boto3` is not available.
"""
#: default DynamoDB table name (`default`)
table_name = 'celery'
#: Read Provisioned Throughput (`default`)
r... | DynamoDBBackend |
python | has2k1__plotnine | plotnine/scales/scale_manual.py | {
"start": 2478,
"end": 3715
} | class ____(_scale_manual):
"""
Custom discrete linetype scale
See Also
--------
[](`matplotlib.markers`)
"""
values: InitVar[Sequence[Any] | dict[Any, Any]]
"""
Linetypes that make up the palette. Possible values of the list are:
1. Strings like
```python
'solid' ... | scale_linetype_manual |
python | keras-team__keras | keras/src/callbacks/early_stopping_test.py | {
"start": 212,
"end": 9576
} | class ____(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_early_stopping(self):
x_train = np.random.random((10, 5))
y_train = np.random.random((10, 1))
x_test = np.random.random((10, 5))
y_test = np.random.random((10, 1))
model = models.Sequential(
... | EarlyStoppingTest |
python | getsentry__sentry | tests/sentry/utils/sdk_crashes/test_sdk_crash_detection.py | {
"start": 6506,
"end": 13674
} | class ____(
TestCase,
PerformanceEventTestMixin,
SDKCrashReportTestMixin,
):
def create_event(self, data, project_id, assert_no_errors=True):
return self.store_event(data=data, project_id=project_id, assert_no_errors=assert_no_errors)
@pytest.mark.parametrize(
["sample_rate", "random_value... | SDKCrashDetectionTest |
python | pytorch__pytorch | torch/_higher_order_ops/partitioner.py | {
"start": 12529,
"end": 13594
} | class ____:
@staticmethod
def create_partitioned_graph(
fw_fn: Callable,
fw_args: tuple[Union[torch.Tensor, torch.SymInt], ...],
*,
always_recompute_complex_exprs: bool = False,
) -> HopPartitionedGraph:
"""
Inputs:
- fw_fn: the forward function th... | HopGraphMinCutPartitioner |
python | plotly__plotly.py | plotly/graph_objs/choroplethmap/colorbar/title/_font.py | {
"start": 233,
"end": 9944
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "choroplethmap.colorbar.title"
_path_str = "choroplethmap.colorbar.title.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
... | Font |
python | keras-team__keras | keras/src/metrics/confusion_metrics_test.py | {
"start": 28632,
"end": 32127
} | class ____(testing.TestCase):
def test_config(self):
s_obj = metrics.SpecificityAtSensitivity(
0.4,
num_thresholds=100,
class_id=12,
name="specificity_at_sensitivity_1",
)
self.assertEqual(s_obj.name, "specificity_at_sensitivity_1")
sel... | SpecificityAtSensitivityTest |
python | bokeh__bokeh | src/bokeh/core/property/descriptor_factory.py | {
"start": 3055,
"end": 5110
} | class ____(Generic[T]):
""" Base class for all Bokeh properties.
A Bokeh property really consist of two parts: the familiar "property"
portion, such as ``Int``, ``String``, etc., as well as an associated
Python descriptor that delegates attribute access (e.g. ``range.start``)
to the property instan... | PropertyDescriptorFactory |
python | pypa__warehouse | tests/unit/admin/views/test_users.py | {
"start": 4084,
"end": 6665
} | class ____:
def test_gets_user(self, db_request):
email = EmailFactory.create(primary=True)
user = UserFactory.create(emails=[email])
project = ProjectFactory.create()
roles = sorted([RoleFactory(project=project, user=user, role_name="Owner")])
journal_entries = sorted(
... | TestUserDetail |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 107336,
"end": 108450
} | class ____(Operation):
def __init__(self, dtype=None, *, name=None):
super().__init__(name=name)
self.dtype = None if dtype is None else backend.standardize_dtype(dtype)
def call(self, x, fill_value):
return backend.numpy.full_like(x, fill_value, dtype=self.dtype)
def compute_outpu... | FullLike |
python | django__django | tests/view_tests/tests/test_debug.py | {
"start": 78766,
"end": 79094
} | class ____(SafeExceptionReporterFilter):
cleansed_substitute = "XXXXXXXXXXXXXXXXXXXX"
hidden_settings = _lazy_re_compile("PASS|DATABASE", flags=re.I)
@override_settings(
ROOT_URLCONF="view_tests.urls",
DEFAULT_EXCEPTION_REPORTER_FILTER="%s.CustomExceptionReporterFilter" % __name__,
)
| CustomExceptionReporterFilter |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/progress_gradient.py | {
"start": 120,
"end": 715
} | class ____(App[None]):
def compose(self) -> ComposeResult:
gradient = Gradient.from_colors(
"#881177",
"#aa3355",
"#cc6666",
"#ee9944",
"#eedd00",
"#99dd55",
"#44dd88",
"#22ccbb",
"#00bbcc",
... | ProgressApp |
python | allegroai__clearml | clearml/backend_api/services/v2_20/auth.py | {
"start": 15603,
"end": 18944
} | class ____(Response):
"""
Response of auth.get_credentials endpoint.
:param credentials: List of credentials, each with an empty secret field.
:type credentials: Sequence[CredentialKey]
:param additional_credentials: The user credentials for the user tenant
companies, each with an empty sec... | GetCredentialsResponse |
python | pydata__xarray | xarray/tests/__init__.py | {
"start": 9549,
"end": 9620
} | class ____:
def __getitem__(self, key):
return key
| ReturnItem |
python | django__django | tests/utils_tests/test_archive.py | {
"start": 3053,
"end": 4652
} | class ____(SimpleTestCase):
def test_extract_function_traversal(self):
archives_dir = os.path.join(os.path.dirname(__file__), "traversal_archives")
tests = [
("traversal.tar", ".."),
("traversal_absolute.tar", "/tmp/evil.py"),
]
if sys.platform == "win32":
... | TestArchiveInvalid |
python | langchain-ai__langchain | libs/partners/groq/tests/integration_tests/test_standard.py | {
"start": 426,
"end": 2822
} | class ____(ChatModelIntegrationTests):
@property
def chat_model_class(self) -> type[BaseChatModel]:
return ChatGroq
@property
def chat_model_params(self) -> dict:
return {"model": "llama-3.3-70b-versatile", "rate_limiter": rate_limiter}
@pytest.mark.xfail(reason="Not yet implemente... | TestGroq |
python | tensorflow__tensorflow | tensorflow/python/ops/distributions/distribution.py | {
"start": 7343,
"end": 9682
} | class ____:
"""Instances of this class represent how sampling is reparameterized.
Two static instances exist in the distributions library, signifying
one of two possible properties for samples from a distribution:
`FULLY_REPARAMETERIZED`: Samples from the distribution are fully
reparameterized, and straig... | ReparameterizationType |
python | kamyu104__LeetCode-Solutions | Python/prison-cells-after-n-days.py | {
"start": 29,
"end": 424
} | class ____(object):
def prisonAfterNDays(self, cells, N):
"""
:type cells: List[int]
:type N: int
:rtype: List[int]
"""
N -= max(N-1, 0) // 14 * 14 # 14 is got from Solution2
for i in xrange(N):
cells = [0] + [cells[i-1] ^ cells[i+1] ^ 1 for i in ... | Solution |
python | pytorch__pytorch | torch/_subclasses/fake_tensor.py | {
"start": 24223,
"end": 39589
} | class ____(Tensor):
"""
Meta tensors give you the ability to run PyTorch code without having to
actually do computation through tensors allocated on a `meta` device.
Because the device is `meta`, meta tensors do not model device propagation.
FakeTensor extends MetaTensors to also carry an additional... | FakeTensor |
python | getsentry__sentry | src/sentry/utils/snuba.py | {
"start": 14961,
"end": 15152
} | class ____(QueryExecutionError):
"""
Exception raised when a query is rejected due to too many simultaneous
queries being performed on the database.
"""
| QueryTooManySimultaneous |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/asset_graph.py | {
"start": 6434,
"end": 7530
} | class ____(graphene.ObjectType):
class Meta:
name = "AssetDependency"
asset = graphene.NonNull("dagster_graphql.schema.asset_graph.GrapheneAssetNode")
partitionMapping = graphene.Field(GraphenePartitionMapping)
def __init__(
self,
*,
asset_key: AssetKey,
partiti... | GrapheneAssetDependency |
python | PyCQA__pylint | pylint/reporters/ureports/nodes.py | {
"start": 2646,
"end": 2925
} | class ____(VNode):
"""A text portion.
attributes :
* data : the text value as an encoded or unicode string
"""
def __init__(self, data: str, escaped: bool = True) -> None:
super().__init__()
self.escaped = escaped
self.data = data
| Text |
python | keras-team__keras | keras/src/layers/convolutional/conv3d.py | {
"start": 179,
"end": 5918
} | class ____(BaseConv):
"""3D convolution layer.
This layer creates a convolution kernel that is convolved with the layer
input over a 3D spatial (or temporal) dimension (width,height and depth) to
produce a tensor of outputs. If `use_bias` is True, a bias vector is created
and added to the outputs. ... | Conv3D |
python | walkccc__LeetCode | solutions/490. The Maze/490-2.py | {
"start": 0,
"end": 733
} | class ____:
def hasPath(
self,
maze: list[list[int]],
start: list[int],
destination: list[int],
) -> bool:
DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))
m = len(maze)
n = len(maze[0])
seen = set()
def isValid(x: int, y: int) -> bool:
return 0 <= x < m and 0 <= y < n a... | Solution |
python | nedbat__coveragepy | tests/test_oddball.py | {
"start": 5271,
"end": 8852
} | class ____(CoverageTest):
"""Attempt the impossible: test that memory doesn't leak.
Note: this test is truly unusual, and has had a colorful history. See
for example: https://github.com/coveragepy/coveragepy/issues/186
It may still fail occasionally, especially on PyPy.
"""
@pytest.mark.fla... | MemoryLeakTest |
python | facebook__pyre-check | client/language_server/protocol.py | {
"start": 1468,
"end": 5571
} | class ____(Exception):
pass
async def _read_headers(
input_channel: connections.AsyncTextReader,
) -> List[str]:
headers = []
header = await input_channel.read_until("\r\n")
while header != "\r\n":
headers.append(header)
header = await input_channel.read_until("\r\n")
return he... | ReadChannelClosedError |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 120746,
"end": 121947
} | class ____(RecvmsgGenericTests):
# Tests for recvmsg() which can use any socket type.
def testRecvmsgBadArgs(self):
# Check that recvmsg() rejects invalid arguments.
self.assertRaises(TypeError, self.serv_sock.recvmsg)
self.assertRaises(ValueError, self.serv_sock.recvmsg,
... | RecvmsgTests |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI019_0.py | {
"start": 3605,
"end": 3729
} | class ____:
def m[S](self: S, other: S): ...
@classmethod
def n[S](cls: type[S], other: S): ...
| NoReturnAnnotations |
python | getsentry__sentry | tests/sentry/integrations/vsts/test_issues.py | {
"start": 2753,
"end": 6529
} | class ____(TestCase):
def setUp(self) -> None:
with assume_test_silo_mode(SiloMode.CONTROL):
model = self.create_provider_integration(
provider="vsts",
external_id="vsts_external_id",
name="fabrikam-fiber-inc",
metadata={
... | VstsIssueBase |
python | python-openxml__python-docx | src/docx/package.py | {
"start": 1643,
"end": 3971
} | class ____:
"""Collection of |ImagePart| objects corresponding to images in the package."""
def __init__(self):
self._image_parts: list[ImagePart] = []
def __contains__(self, item: object):
return self._image_parts.__contains__(item)
def __iter__(self):
return self._image_part... | ImageParts |
python | pytorch__pytorch | torchgen/model.py | {
"start": 85857,
"end": 86122
} | class ____:
argument: Argument
# Bundle of arguments that represent a TensorOptions. This is mostly
# relevant for the public C++ API but we bake it into the core data
# model because other APIs often have to interact with it
@dataclass(frozen=True)
| SelfArgument |
python | scrapy__scrapy | tests/test_downloadermiddleware_httpcache.py | {
"start": 3540,
"end": 5454
} | class ____:
"""Mixin containing storage-specific test methods."""
def test_storage(self):
with self._storage() as (storage, crawler):
request2 = self.request.copy()
assert storage.retrieve_response(crawler.spider, request2) is None
storage.store_response(crawler.spi... | StorageTestMixin |
python | getsentry__sentry | src/sentry/api/exceptions.py | {
"start": 492,
"end": 641
} | class ____(APIException):
status_code = status.HTTP_404_NOT_FOUND
default_detail = "The requested resource does not exist"
| ResourceDoesNotExist |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/utils/kubernetes.py | {
"start": 4424,
"end": 4605
} | class ____(BaseModel):
model_config = {
"extra": "allow",
"json_schema_extra": {"$ref": create_definition_ref("io.k8s.api.core.v1.VolumeMount")},
}
| VolumeMount |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/need_mocks.py | {
"start": 769,
"end": 944
} | class ____(missing_module.Class):
"""docstring"""
pass
sphinx.missing_module4.missing_function(len(missing_name2))
#: docstring
Alias = missing_module2.Class
| Inherited |
python | pandas-dev__pandas | pandas/tests/scalar/timestamp/test_timestamp.py | {
"start": 758,
"end": 8029
} | class ____:
def test_properties_business(self):
freq = to_offset("B")
ts = Timestamp("2017-10-01")
assert ts.dayofweek == 6
assert ts.day_of_week == 6
assert ts.is_month_start # not a weekday
assert not freq.is_month_start(ts)
assert freq.is_month_start(ts +... | TestTimestampProperties |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/path_registry.py | {
"start": 24580,
"end": 24841
} | class ____(Dict[Any, Any]):
def __init__(self, registry: _CachingEntityRegistry):
self.registry = registry
def __missing__(self, key: Any) -> _PropRegistry:
self[key] = item = _PropRegistry(self.registry, key)
return item
| _ERDict |
python | doocs__leetcode | solution/2100-2199/2146.K Highest Ranked Items Within a Price Range/Solution.py | {
"start": 0,
"end": 1005
} | class ____:
def highestRankedKItems(
self, grid: List[List[int]], pricing: List[int], start: List[int], k: int
) -> List[List[int]]:
m, n = len(grid), len(grid[0])
row, col = start
low, high = pricing
q = deque([(row, col)])
pq = []
if low <= grid[row][col... | Solution |
python | apache__airflow | devel-common/src/tests_common/test_utils/asserts.py | {
"start": 2032,
"end": 2951
} | class ____(NamedTuple):
"""QueriesTraceInfo holds information about the queries executed in the context."""
traces: tuple[QueriesTraceRecord, ...]
@classmethod
def from_traceback(cls, trace: traceback.StackSummary) -> QueriesTraceInfo:
records = [
QueriesTraceRecord.from_frame(f)
... | QueriesTraceInfo |
python | apache__airflow | providers/http/src/airflow/providers/http/operators/http.py | {
"start": 1613,
"end": 15536
} | class ____(BaseOperator):
"""
Calls an endpoint on an HTTP system to execute an action.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:HttpOperator`
:param http_conn_id: The :ref:`http connection<howto/connection:http>` to ... | HttpOperator |
python | pypa__setuptools | setuptools/tests/test_editable_install.py | {
"start": 27747,
"end": 31767
} | class ____:
PYPROJECT = """\
[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"
[project]
name = "mypkg"
version = "3.14159"
"""
# Any: Would need a TypedDict. Keep it simple for tests
FLAT_LAYOUT: dict[str, Any] = {
... | TestOverallBehaviour |
python | scipy__scipy | benchmarks/benchmarks/special.py | {
"start": 705,
"end": 1098
} | class ____(Benchmark):
def setup(self, *args):
self.N = np.arange(1, 1000, 50)
self.k = np.arange(1, 1000, 50)
@with_attributes(params=[(10, 100, 1000, 10000), (1, 10, 100)],
param_names=['N', 'k'])
def time_comb_exact(self, N, k):
comb(N, k, exact=True)
d... | Comb |
python | huggingface__transformers | src/transformers/models/reformer/modeling_reformer.py | {
"start": 58355,
"end": 61795
} | class ____(nn.Module):
def __init__(self, config, layer_id=0):
super().__init__()
self.layer_id = layer_id
self.attn_layers = config.attn_layers
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
if len(set(self.attn_layers)) == 1 and self.attn_la... | ReformerAttention |
python | pymupdf__PyMuPDF | pipcl.py | {
"start": 93264,
"end": 119112
} | class ____:
'''
Compile/link flags for the current python, for example the include path
needed to get `Python.h`.
The 'PIPCL_PYTHON_CONFIG' environment variable allows to override
the location of the python-config executable.
Members:
.includes:
String containing compiler f... | PythonFlags |
python | modin-project__modin | modin/core/storage_formats/pandas/merge.py | {
"start": 1381,
"end": 13122
} | class ____:
"""Provide implementations for merge/join."""
@classmethod
def range_partitioning_merge(cls, left, right, kwargs):
"""
Execute merge using range-partitioning implementation.
Parameters
----------
left : PandasQueryCompiler
right : PandasQueryComp... | MergeImpl |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_excel2003_style07.py | {
"start": 315,
"end": 1174
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("excel2003_style07.xlsx")
self.ignore_elements = {
"xl/drawings/drawing1.xml": [
"<xdr:cNvPr",
"<a:p... | TestCompareXLSXFiles |
python | boto__boto3 | boto3/docs/client.py | {
"start": 614,
"end": 1003
} | class ____(ClientDocumenter):
def _add_client_creation_example(self, section):
section.style.start_codeblock()
section.style.new_line()
section.write('import boto3')
section.style.new_line()
section.style.new_line()
section.write(f'client = boto3.client(\'{self._servi... | Boto3ClientDocumenter |
python | kubernetes-client__python | kubernetes/base/config/kube_config.py | {
"start": 2657,
"end": 5616
} | class ____(object):
"""Utility class to read content of obj[%data_key_name] or file's
content of obj[%file_key_name] and represent it as file or data.
Note that the data is preferred. The obj[%file_key_name] will be used iff
obj['%data_key_name'] is not set or empty. Assumption is file content is
... | FileOrData |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_pattern10.py | {
"start": 315,
"end": 2203
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_pattern10.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.g... | TestCompareXLSXFiles |
python | astropy__astropy | astropy/utils/masked/tests/test_functions.py | {
"start": 22085,
"end": 26434
} | class ____:
"""Test with structure dtypes, using erfa ufuncs."""
def test_erfa_d2tf_tf2d(self):
mask = np.array([True, False, False])
days = Masked([0.25, 0.875, 0.0625], mask=mask)
sign, ihmsf = erfa_ufunc.d2tf(3, days)
assert_array_equal(sign.mask["sign"], mask)
sign =... | TestStructuredUfuncs |
python | huggingface__transformers | src/transformers/models/unispeech/modeling_unispeech.py | {
"start": 43240,
"end": 48498
} | class ____(UniSpeechPreTrainedModel):
def __init__(self, config: UniSpeechConfig):
super().__init__(config)
self.unispeech = UniSpeechModel(config)
self.dropout_features = nn.Dropout(config.feat_quantizer_dropout)
self.quantizer = UniSpeechGumbelVectorQuantizer(config)
self.... | UniSpeechForPreTraining |
python | getsentry__sentry | tests/sentry/monitors/endpoints/test_base_monitor_details.py | {
"start": 1142,
"end": 8674
} | class ____(MonitorTestCase):
__test__ = False
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
def test_simple(self) -> None:
monitor = self._create_monitor()
resp = self.get_success_response(self.organization.slug, monitor.slug)
assert resp.d... | BaseMonitorDetailsTest |
python | yaml__pyyaml | lib/yaml/tokens.py | {
"start": 745,
"end": 807
} | class ____(Token):
id = '<document start>'
| DocumentStartToken |
python | ray-project__ray | doc/source/custom_directives.py | {
"start": 16962,
"end": 18125
} | class ____(ExampleEnum):
"""Library type for example metadata."""
DATA = "Data"
SERVE = "Serve"
TRAIN = "Train"
@classmethod
def formatted_name(cls):
return "Library"
@classmethod
def key(cls: type) -> str:
return "library"
@classmethod
def from_path(cls, path... | Library |
python | huggingface__transformers | src/transformers/generation/streamers.py | {
"start": 6280,
"end": 9229
} | class ____(TextStreamer):
"""
Streamer that stores print-ready text in a queue, to be used by a downstream application as an iterator. This is
useful for applications that benefit from accessing the generated text in a non-blocking way (e.g. in an interactive
Gradio demo).
<Tip warning={true}>
... | TextIteratorStreamer |
python | joke2k__faker | faker/providers/phone_number/sv_SE/__init__.py | {
"start": 49,
"end": 367
} | class ____(PhoneNumberProvider):
formats = (
"+46 (0)8 ### ### ##",
"+46 (0)## ## ## ##",
"+46 (0)### ### ##",
"08-### ### ##",
"08-### ## ##",
"08-## ## ##",
"0##-### ## ##",
"0##-## ## ##",
"0###-## ## ##",
"0###-### ##",
)
| Provider |
python | django__django | django/db/models/query.py | {
"start": 84052,
"end": 84342
} | class ____(metaclass=InstanceCheckMeta):
"""
Marker class to checking if a queryset is empty by .none():
isinstance(qs.none(), EmptyQuerySet) -> True
"""
def __init__(self, *args, **kwargs):
raise TypeError("EmptyQuerySet can't be instantiated")
| EmptyQuerySet |
python | pypa__hatch | tests/backend/builders/test_wheel.py | {
"start": 18995,
"end": 22601
} | class ____:
def test_default(self, isolation):
builder = WheelBuilder(str(isolation))
assert builder.config.extra_metadata == builder.config.extra_metadata == {}
def test_invalid_type(self, isolation):
config = {"tool": {"hatch": {"build": {"targets": {"wheel": {"extra-metadata": 42}}}... | TestExtraMetadata |
python | getsentry__sentry | tests/sentry/relocation/tasks/test_transfer.py | {
"start": 1791,
"end": 3629
} | class ____(TestCase):
@patch("sentry.relocation.tasks.transfer.process_relocation_transfer_control")
def test_no_records(self, mock_process: MagicMock) -> None:
find_relocation_transfer_control()
assert not mock_process.delay.called
@patch("sentry.relocation.tasks.transfer.process_relocatio... | FindRelocationTransferControlTest |
python | modin-project__modin | modin/tests/pandas/extensions/conftest.py | {
"start": 1185,
"end": 1352
} | class ____(NativeQueryCompiler):
storage_format = property(lambda self: "Test1_Storage_Format")
engine = property(lambda self: "Test1_Engine")
| Test1QueryCompiler |
python | pytorch__pytorch | test/inductor/test_torchinductor.py | {
"start": 10562,
"end": 24932
} | class ____:
n: int
device: str
def dense(self):
return torch.randn((self.n, self.n), device=self.device)
def transposed(self):
return self.dense().transpose(0, 1)
def strided(self):
return torch.randn((self.n * 2, self.n * 3), device=self.device)[
self.n :, sel... | InputGen |
python | PrefectHQ__prefect | tests/workers/test_base_worker.py | {
"start": 62167,
"end": 69431
} | class ____:
async def test_start_syncs_with_the_server(self, work_pool: WorkPool):
worker = WorkerTestImpl(work_pool_name=work_pool.name)
assert worker._work_pool is None
await worker.start(run_once=True)
assert worker._work_pool is not None
assert worker._work_pool.base_jo... | TestBaseWorkerStart |
python | jina-ai__jina | tests/unit/orchestrate/flow/flow-construct/test_flow_except.py | {
"start": 288,
"end": 399
} | class ____(Executor):
@requests
def craft(self, *args, **kwargs):
return 1 / 0
| DummyCrafterExcept |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 77832,
"end": 80677
} | class ____(BaseModel, extra="forbid"):
deleted_threshold: Optional[float] = Field(
default=None,
description="The minimal fraction of deleted vectors in a segment, required to perform segment optimization",
)
vacuum_min_vector_number: Optional[int] = Field(
default=None, description=... | OptimizersConfigDiff |
python | getsentry__sentry | tests/sentry/migrations/test_0913_split_discover_dataset_dashboards_self_hosted.py | {
"start": 522,
"end": 7027
} | class ____(TestMigrations, SnubaTestCase):
migrate_from = "0912_make_organizationmemberteam_replica_is_active_true"
migrate_to = "0913_split_discover_dataset_dashboards_self_hosted"
def setup_before_migration(self, apps):
User = apps.get_model("sentry", "User")
Dashboard = apps.get_model("s... | SplitDiscoverDatasetDashboardsSelfHostedTest |
python | python__mypy | mypyc/ir/ops.py | {
"start": 19523,
"end": 20619
} | class ____(RegisterOp):
"""Native method call obj.method(arg, ...)"""
def __init__(self, obj: Value, method: str, args: list[Value], line: int = -1) -> None:
self.obj = obj
self.method = method
self.args = args
assert isinstance(obj.type, RInstance), "Methods can only be called ... | MethodCall |
python | scrapy__scrapy | tests/test_command_runspider.py | {
"start": 631,
"end": 3223
} | class ____(scrapy.Spider):
name = "bad"
async def start(self):
raise Exception("oops!")
yield
"""
def runspider(
self, cwd: Path, code: str, name: str | None = None, args: Iterable[str] = ()
) -> tuple[int, str, str]:
fname = cwd / (name or self.spider_filename)
... | BadSpider |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py | {
"start": 38385,
"end": 39222
} | class ____(BaseModel):
type: Literal["WaitUntilTimeFromHeader"]
header: str = Field(
...,
description="The name of the response header defining how long to wait before retrying.",
examples=["wait_time"],
title="Response Header",
)
min_wait: Optional[Union[float, str]] = F... | WaitUntilTimeFromHeader |
python | getsentry__sentry | src/sentry/seer/anomaly_detection/types.py | {
"start": 1997,
"end": 2099
} | class ____(StrEnum):
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
| AnomalyDetectionSensitivity |
python | Textualize__textual | docs/examples/app/widgets04.py | {
"start": 74,
"end": 281
} | class ____(App):
async def on_key(self) -> None:
await self.mount(Welcome())
self.query_one(Button).label = "YES!"
if __name__ == "__main__":
app = WelcomeApp()
app.run()
| WelcomeApp |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/ndb/projection_queries/snippets.py | {
"start": 1187,
"end": 1652
} | class ____(ndb.Model):
name = ndb.StringProperty()
addresses = ndb.StructuredProperty(Address, repeated=True)
def fetch_sub_properties():
Contact.query().fetch(projection=["name", "addresses.city"])
Contact.query().fetch(projection=[Contact.name, Contact.addresses.city])
def demonstrate_ndb_grouping... | Contact |
python | tiangolo__fastapi | fastapi/security/http.py | {
"start": 3247,
"end": 7069
} | class ____(HTTPBase):
"""
HTTP Basic authentication.
Ref: https://datatracker.ietf.org/doc/html/rfc7617
## Usage
Create an instance object and use that object as the dependency in `Depends()`.
The dependency result will be an `HTTPBasicCredentials` object containing the
`username` and th... | HTTPBasic |
python | django__django | tests/multiple_database/tests.py | {
"start": 80539,
"end": 84387
} | class ____(TestCase):
databases = {"default", "other"}
def override_router(self):
return override_settings(DATABASE_ROUTERS=[WriteToOtherRouter()])
def test_database_arg_save_and_delete(self):
"""
The pre/post_save signal contains the correct database.
"""
# Make so... | SignalTests |
python | langchain-ai__langchain | libs/langchain/langchain_classic/agents/structured_chat/output_parser.py | {
"start": 2201,
"end": 4075
} | class ____(AgentOutputParser):
"""Output parser with retries for the structured chat agent."""
base_parser: AgentOutputParser = Field(default_factory=StructuredChatOutputParser)
"""The base parser to use."""
output_fixing_parser: OutputFixingParser | None = None
"""The output fixing parser to use."... | StructuredChatOutputParserWithRetries |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/strategies/_internal/collections.py | {
"start": 1418,
"end": 4118
} | class ____(SearchStrategy[tuple[Ex, ...]]):
"""A strategy responsible for fixed length tuples based on heterogeneous
strategies for each of their elements."""
def __init__(self, strategies: Iterable[SearchStrategy[Any]]):
super().__init__()
self.element_strategies = tuple(strategies)
d... | TupleStrategy |
python | kamyu104__LeetCode-Solutions | Python/best-team-with-no-conflicts.py | {
"start": 2525,
"end": 3185
} | class ____(object):
def bestTeamScore(self, scores, ages):
"""
:type scores: List[int]
:type ages: List[int]
:rtype: int
"""
players = sorted(zip(scores, ages))
sorted_ages = sorted(set(ages))
lookup = {age:i for i, age in enumerate(sorted_ages)} # co... | Solution |
python | pytorch__pytorch | test/dynamo/test_base_hop.py | {
"start": 1575,
"end": 4887
} | class ____(torch.nn.Module):
def forward(self, L_x_: "f32[3, 3]", L_y_: "f32[3, 3]"):
l_x_ = L_x_
l_y_ = L_y_
subgraph_0 = self.subgraph_0
invoke_quant_test = torch.ops.higher_order.invoke_quant_test(subgraph_0, l_x_, l_y_, scheme = 'nf4'); subgraph_0 = l_x_ = l_y_ = None
g... | GraphModule |
python | pytorch__pytorch | tools/test/test_cmake.py | {
"start": 336,
"end": 3879
} | class ____(unittest.TestCase):
@unittest.mock.patch("multiprocessing.cpu_count")
def test_build_jobs(self, mock_cpu_count: unittest.mock.MagicMock) -> None:
"""Tests that the number of build jobs comes out correctly."""
mock_cpu_count.return_value = 13
cases = [
# MAX_JOBS, U... | TestCMake |
python | mwaskom__seaborn | tests/_core/test_plot.py | {
"start": 73563,
"end": 73671
} | class ____:
def test_default_repr(self):
assert repr(Default()) == "<default>"
| TestDefaultObject |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/pygments/formatters/terminal256.py | {
"start": 10210,
"end": 11753
} | class ____(Terminal256Formatter):
r"""
Format tokens with ANSI color sequences, for output in a true-color
terminal or console. Like in `TerminalFormatter` color sequences
are terminated at newlines, so that paging the output works correctly.
.. versionadded:: 2.1
Options accepted:
`styl... | TerminalTrueColorFormatter |
python | huggingface__transformers | src/transformers/models/mbart/modeling_mbart.py | {
"start": 5676,
"end": 11272
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
embed_dim: int,
num_heads: int,
dropout: float = 0.0,
is_decoder: bool = False,
bias: bool = True,
is_causal: bool = False,
config: Opti... | MBartAttention |
python | numba__numba | numba/tests/npyufunc/test_ufuncbuilding.py | {
"start": 365,
"end": 3018
} | class ____(TestCase):
def test_basic_ufunc(self):
from numba.tests.npyufunc.ufuncbuilding_usecases import add
ufb = UFuncBuilder(add)
cres = ufb.add("int32(int32, int32)")
self.assertFalse(cres.objectmode)
cres = ufb.add("int64(int64, int64)")
self.assertFalse(cres.o... | TestUfuncBuilding |
python | google__jax | jax/_src/pallas/core.py | {
"start": 3561,
"end": 3640
} | class ____(AbstractSemaphoreTy):
name = "semaphore"
type = semaphore
| Semaphore |
python | allegroai__clearml | clearml/utilities/enum.py | {
"start": 37,
"end": 840
} | class ____(object):
"""Base class for enum-like classes using class-attributes with string values to represent enum key/value pairs"""
__cache = None
@classmethod
def values(cls) -> List[str]:
"""Extract list of enum-like options based on the derived classes' attributes.
Any class attr... | EnumOptions |
python | scipy__scipy | scipy/stats/_discrete_distns.py | {
"start": 16784,
"end": 22270
} | class ____(rv_discrete):
r"""A hypergeometric discrete random variable.
The hypergeometric distribution models drawing objects from a bin.
`M` is the total number of objects, `n` is total number of Type I objects.
The random variate represents the number of Type I objects in `N` drawn
without repla... | hypergeom_gen |
python | getsentry__sentry | tests/sentry/issues/endpoints/test_organization_group_search_view_details.py | {
"start": 403,
"end": 3538
} | class ____(APITestCase):
def create_base_data(self) -> dict[str, list[GroupSearchView]]:
user_1 = self.user
self.user_2 = self.create_user()
self.user_3 = self.create_user()
self.create_member(organization=self.organization, user=self.user_2)
self.create_member(organization=... | BaseGSVTestCase |
python | django__django | docs/_ext/djangodocs.py | {
"start": 3691,
"end": 6672
} | class ____(HTMLTranslator):
"""
Django-specific reST to HTML tweaks.
"""
# Don't use border=1, which docutils does by default.
def visit_table(self, node):
self.context.append(self.compact_p)
self.compact_p = True
# Needed by Sphinx.
self._table_row_indices.append(0)... | DjangoHTMLTranslator |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-core/dagster_dg_core/context.py | {
"start": 25256,
"end": 25577
} | class ____:
timestamp: float
raw_versions: list[str]
@property
def datetime(self) -> datetime.datetime:
return datetime.datetime.fromtimestamp(self.timestamp)
@cached_property
def versions(self) -> list[Version]:
return sorted(Version(v) for v in self.raw_versions)
| DgPyPiVersionInfo |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.