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 | fluentpython__example-code-2e | 24-class-metaprog/metabunch/nutshell3e/bunch.py | {
"start": 3447,
"end": 3752
} | class ____(metaclass=MetaBunch):
""" For convenience: inheriting from Bunch can be used to get
the new metaclass (same as defining metaclass= yourself).
In v2, remove the (metaclass=MetaBunch) above and add
instead __metaclass__=MetaBunch as the class body.
"""
pass
| Bunch |
python | PyCQA__pylint | tests/message/unittest_message_definition.py | {
"start": 1254,
"end": 1651
} | class ____(BaseChecker):
def __init__(self) -> None:
super().__init__(PyLinter())
name = "FalseChecker"
msgs = {
"W1234": ("message one", "msg-symbol-one", "msg description"),
"W1235": (
"message two",
"msg-symbol-two",
"msg description",
... | FalseChecker |
python | Textualize__textual | docs/examples/styles/link_background_hover.py | {
"start": 64,
"end": 778
} | class ____(App):
CSS_PATH = "link_background_hover.tcss"
def compose(self):
yield Label(
"Visit the [link='https://textualize.io']Textualize[/link] website.",
id="lbl1", # (1)!
)
yield Label(
"Click [@click=app.bell]here[/] for the bell sound.",
... | LinkHoverBackgroundApp |
python | redis__redis-py | tests/entraid_utils.py | {
"start": 858,
"end": 5646
} | class ____(Enum):
MANAGED_IDENTITY = "managed_identity"
SERVICE_PRINCIPAL = "service_principal"
DEFAULT_AZURE_CREDENTIAL = "default_azure_credential"
def identity_provider(request) -> IdentityProviderInterface:
if hasattr(request, "param"):
kwargs = request.param.get("idp_kwargs", {})
else... | AuthType |
python | PrefectHQ__prefect | src/prefect/transactions.py | {
"start": 15314,
"end": 26819
} | class ____(BaseTransaction):
"""
A model representing the state of an asynchronous transaction.
"""
async def begin(self) -> None:
if (
self.store
and self.key
and self.isolation_level == IsolationLevel.SERIALIZABLE
):
self.logger.debug(f"... | AsyncTransaction |
python | ipython__ipython | IPython/utils/ipstruct.py | {
"start": 878,
"end": 11856
} | class ____(dict):
"""A dict subclass with attribute style access.
This dict subclass has a a few extra features:
* Attribute style access.
* Protection of class members (like keys, items) when using attribute
style access.
* The ability to restrict assignment to only existing keys.
* Int... | Struct |
python | spack__spack | lib/spack/spack/test/variant.py | {
"start": 13884,
"end": 32259
} | class ____:
def test_invalid_values(self) -> None:
# Value with invalid type
a = VariantMap(Spec())
with pytest.raises(TypeError):
a["foo"] = 2
# Duplicate variant
a["foo"] = MultiValuedVariant("foo", ("bar", "baz"))
with pytest.raises(DuplicateVariantErr... | TestVariantMapTest |
python | huggingface__transformers | src/transformers/models/roc_bert/modeling_roc_bert.py | {
"start": 69020,
"end": 72287
} | class ____(RoCBertPreTrainedModel):
# Copied from transformers.models.bert.modeling_bert.BertForTokenClassification.__init__ with Bert->RoCBert,bert->roc_bert
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.roc_bert = RoCBertModel(config, ad... | RoCBertForTokenClassification |
python | python-openxml__python-docx | tests/opc/unitdata/rels.py | {
"start": 233,
"end": 614
} | class ____:
"""
Provides common behavior for all data builders.
"""
@property
def element(self):
"""Return element based on XML generated by builder"""
return parse_xml(self.xml)
def with_indent(self, indent):
"""Add integer `indent` spaces at beginning of element XML""... | BaseBuilder |
python | jina-ai__jina | tests/integration/reduce/test_reduce.py | {
"start": 3325,
"end": 3479
} | class ____(Executor):
@requests
def endpoint(self, docs: DocumentArray, **kwargs):
for doc in docs:
doc.text = 'exec1'
| Executor1 |
python | python-openxml__python-docx | src/docx/text/tabstops.py | {
"start": 2445,
"end": 3896
} | class ____(ElementProxy):
"""An individual tab stop applying to a paragraph or style.
Accessed using list semantics on its containing |TabStops| object.
"""
def __init__(self, element):
super(TabStop, self).__init__(element, None)
self._tab = element
@property
def alignment(se... | TabStop |
python | getsentry__sentry | tests/sentry/auth/test_idpmigration.py | {
"start": 440,
"end": 3335
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user()
self.login_as(self.user)
self.email = "test@example.com"
self.org = self.create_organization()
self.provider = AuthProvider.objects.create(organization_id=self.org.id, provid... | IDPMigrationTests |
python | huggingface__transformers | src/transformers/modeling_outputs.py | {
"start": 79608,
"end": 81221
} | class ____(ModelOutput):
"""
Base class for outputs of image classification models.
Args:
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Classification (or regression if config.num_labels==1) loss.
logits (`torch.FloatTensor` of shape... | ImageClassifierOutput |
python | automl__auto-sklearn | autosklearn/metalearning/metafeatures/metafeatures.py | {
"start": 18129,
"end": 18437
} | class ____(MetaFeature):
def _calculate(self, X, y, logger, feat_type):
values = [val for val in helper_functions.get_value("NumSymbols") if val > 0]
std = np.nanstd(values)
return std if np.isfinite(std) else 0
@metafeatures.define("SymbolsSum", dependency="NumSymbols")
| SymbolsSTD |
python | doocs__leetcode | solution/2700-2799/2767.Partition String Into Minimum Beautiful Substrings/Solution.py | {
"start": 0,
"end": 619
} | class ____:
def minimumBeautifulSubstrings(self, s: str) -> int:
@cache
def dfs(i: int) -> int:
if i >= n:
return 0
if s[i] == "0":
return inf
x = 0
ans = inf
for j in range(i, n):
x = x << 1 ... | Solution |
python | ray-project__ray | python/ray/serve/_private/request_router/common.py | {
"start": 756,
"end": 1812
} | class ____:
"""A request that is pending execution by a replica."""
args: List[Any]
"""Positional arguments for the request."""
kwargs: Dict[Any, Any]
"""Keyword arguments for the request."""
metadata: RequestMetadata
"""Metadata for the request, including request ID and whether it's stre... | PendingRequest |
python | scrapy__scrapy | scrapy/exporters.py | {
"start": 8234,
"end": 10964
} | class ____(BaseItemExporter):
def __init__(
self,
file: BytesIO,
include_headers_line: bool = True,
join_multivalued: str = ",",
errors: str | None = None,
**kwargs: Any,
):
super().__init__(dont_fail=True, **kwargs)
if not self.encoding:
... | CsvItemExporter |
python | automl__auto-sklearn | test/test_pipeline/components/regression/test_extra_trees.py | {
"start": 166,
"end": 998
} | class ____(BaseRegressionComponentTest):
__test__ = True
res = dict()
res["default_boston"] = 0.8539264243687228
res["boston_n_calls"] = 9
res["default_boston_iterative"] = res["default_boston"]
res["default_boston_sparse"] = 0.411211701806908
res["default_boston_iterative_sparse"] = res["... | ExtraTreesComponentTest |
python | ApeWorX__ape | src/ape/cli/choices.py | {
"start": 5522,
"end": 10796
} | class ____(PromptChoice):
"""
Prompts the user to select an alias from their accounts.
Useful for adhoc scripts to lessen the need to hard-code aliases.
"""
DEFAULT_PROMPT = "Select an account"
def __init__(
self,
key: _ACCOUNT_TYPE_FILTER = None,
prompt_message: Option... | AccountAliasPromptChoice |
python | walkccc__LeetCode | solutions/1329. Sort the Matrix Diagonally/1329.py | {
"start": 0,
"end": 417
} | class ____:
def diagonalSort(self, mat: list[list[int]]) -> list[list[int]]:
m = len(mat)
n = len(mat[0])
count = collections.defaultdict(list)
for i in range(m):
for j in range(n):
count[i - j].append(mat[i][j])
for value in count.values():
value.sort(reverse=1)
for i ... | Solution |
python | walkccc__LeetCode | solutions/3398. Smallest Substring With Identical Characters I/3398.py | {
"start": 0,
"end": 721
} | class ____:
def minLength(self, s: str, numOps: int) -> int:
def getMinOps(k: int) -> int:
"""
Returns the minimum number of operations needed to make all groups of
identical characters of length k or less.
"""
if k == 1:
res = sum(1 for i, c in enumerate(s) if int(c) == i % ... | Solution |
python | Netflix__metaflow | metaflow/plugins/pypi/pip.py | {
"start": 400,
"end": 709
} | class ____(MetaflowException):
headline = "Pip ran into an error while setting up environment"
def __init__(self, error):
if isinstance(error, (list,)):
error = "\n".join(error)
msg = "{error}".format(error=error)
super(PipException, self).__init__(msg)
| PipException |
python | scipy__scipy | scipy/interpolate/tests/test_bsplines.py | {
"start": 143283,
"end": 146902
} | class ____:
def _get_xyk(self, m=10, k=3, xp=np):
x = xp.arange(m, dtype=xp.float64) * xp.pi / m
y = [xp.sin(x), xp.cos(x)]
return x, y, k
@pytest.mark.parametrize('s', [0, 0.1, 1e-3, 1e-5])
def test_simple_vs_splprep(self, s):
# Check/document the interface vs splPrep
... | TestMakeSplprep |
python | scipy__scipy | scipy/stats/tests/test_hypotests.py | {
"start": 1024,
"end": 3959
} | class ____:
@pytest.mark.parametrize('dtype', [None, 'float32', 'float64'])
def test_statistic_1(self, dtype, xp):
# first example in Goerg & Kaiser, also in original paper of
# Epps & Singleton. Note: values do not match exactly, the
# value of the interquartile range varies depending o... | TestEppsSingleton |
python | davidhalter__jedi | jedi/inference/context.py | {
"start": 10326,
"end": 10640
} | class ____(TreeContextMixin, ValueContext):
def get_filters(self, until_position=None, origin_scope=None):
yield ParserTreeFilter(
self.inference_state,
parent_context=self,
until_position=until_position,
origin_scope=origin_scope
)
| FunctionContext |
python | django-extensions__django-extensions | django_extensions/management/jobs.py | {
"start": 456,
"end": 519
} | class ____(BaseJob):
when = "quarter_hourly"
| QuarterHourlyJob |
python | cherrypy__cherrypy | cherrypy/__init__.py | {
"start": 3646,
"end": 5347
} | class ____(object):
"""Handle signals from other processes.
Based on the configured platform handlers above.
"""
def __init__(self, bus):
self.bus = bus
def subscribe(self):
"""Add the handlers based on the platform."""
if hasattr(self.bus, 'signal_handler'):
s... | _HandleSignalsPlugin |
python | fastai__fastai | fastai/collab.py | {
"start": 398,
"end": 586
} | class ____(TabularPandas):
"Instance of `TabularPandas` suitable for collaborative filtering (with no continuous variable)"
with_cont=False
# %% ../nbs/45_collab.ipynb 9
| TabularCollab |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataplex.py | {
"start": 129095,
"end": 133774
} | class ____(DataplexCatalogBaseOperator):
"""
Update an EntryType resource.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:DataplexCatalogUpdateEntryTypeOperator`
:param project_id: Required. The ID of the Google Cloud proje... | DataplexCatalogUpdateEntryTypeOperator |
python | django__django | django/core/serializers/json.py | {
"start": 450,
"end": 1794
} | class ____(PythonSerializer):
"""Convert a queryset to JSON."""
internal_use_only = False
def _init_options(self):
self._current = None
self.json_kwargs = self.options.copy()
self.json_kwargs.pop("stream", None)
self.json_kwargs.pop("fields", None)
if self.options.g... | Serializer |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/inheritance.py | {
"start": 435,
"end": 541
} | class ____(Base, AnotherBase):
def inheritedmeth(self):
# no docstring here
pass
| Derived |
python | kamyu104__LeetCode-Solutions | Python/bricks-falling-when-hit.py | {
"start": 704,
"end": 2254
} | class ____(object):
def hitBricks(self, grid, hits):
"""
:type grid: List[List[int]]
:type hits: List[List[int]]
:rtype: List[int]
"""
def index(C, r, c):
return r*C+c
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
R, C = len(grid), len(g... | Solution |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/transfers/imap_attachment_to_s3.py | {
"start": 1228,
"end": 4584
} | class ____(BaseOperator):
"""
Transfers a mail attachment from a mail server into s3 bucket.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:ImapAttachmentToS3Operator`
:param imap_attachment_name: The file name of the mail ... | ImapAttachmentToS3Operator |
python | pytest-dev__pytest | src/_pytest/outcomes.py | {
"start": 5015,
"end": 10138
} | class ____:
"""Imperatively xfail an executing test or setup function with the given reason.
This function should be called only during testing (setup, call or teardown).
No other code is executed after using ``xfail()`` (it is implemented
internally by raising an exception).
:param reason:
... | _XFail |
python | run-llama__llama_index | llama-index-instrumentation/tests/test_dispatcher.py | {
"start": 1137,
"end": 1248
} | class ____(BaseEvent):
@classmethod
def class_name(cls):
return "_TestStartEvent"
| _TestStartEvent |
python | django__django | tests/auth_tests/test_auth_backends.py | {
"start": 39007,
"end": 40461
} | class ____(TestCase):
"""
Tests for changes in the settings.AUTHENTICATION_BACKENDS
"""
backend = "auth_tests.test_auth_backends.NewModelBackend"
TEST_USERNAME = "test_user"
TEST_PASSWORD = "test_password"
TEST_EMAIL = "test@example.com"
@classmethod
def setUpTestData(cls):
... | ChangedBackendSettingsTest |
python | doocs__leetcode | solution/0400-0499/0464.Can I Win/Solution.py | {
"start": 0,
"end": 516
} | class ____:
def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:
@cache
def dfs(mask: int, s: int) -> bool:
for i in range(1, maxChoosableInteger + 1):
if mask >> i & 1 ^ 1:
if s + i >= desiredTotal or not dfs(mask | 1 << i, s + i):
... | Solution |
python | getsentry__sentry | src/sentry/integrations/slack/views/unlink_identity.py | {
"start": 997,
"end": 1713
} | class ____(SlackIdentityLinkageView, UnlinkIdentityView):
"""
Django view for unlinking user from slack account. Deletes from Identity table.
"""
@property
def command_response(self) -> SlackCommandResponse:
return SlackCommandResponse("unlink", SUCCESS_UNLINKED_MESSAGE, "slack.unlink-ident... | SlackUnlinkIdentityView |
python | gevent__gevent | src/greentest/3.10/test_smtpd.py | {
"start": 33987,
"end": 35548
} | class ____(unittest.TestCase):
def setUp(self):
smtpd.socket = asyncore.socket = mock_socket
self.old_debugstream = smtpd.DEBUGSTREAM
self.debug = smtpd.DEBUGSTREAM = io.StringIO()
self.server = DummyServer((socket_helper.HOST, 0), ('b', 0))
conn, addr = self.server.accept()... | SMTPDChannelWithDecodeDataFalse |
python | optuna__optuna | optuna/pruners/_hyperband.py | {
"start": 345,
"end": 14269
} | class ____(BasePruner):
"""Pruner using Hyperband.
As SuccessiveHalving (SHA) requires the number of configurations
:math:`n` as its hyperparameter. For a given finite budget :math:`B`,
all the configurations have the resources of :math:`B \\over n` on average.
As you can see, there will be a trad... | HyperbandPruner |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 89406,
"end": 89892
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("discussion_id", "body", "client_mutation_id")
discussion_id = sgqlc.types.Field(
sgqlc.types.non_null(ID), graphql_name="discussionId"
)
body = sgqlc.types.Field... | CreateTeamDiscussionCommentInput |
python | dask__dask | dask/array/_array_expr/random.py | {
"start": 661,
"end": 17219
} | class ____:
"""
Container for the BitGenerators.
``Generator`` exposes a number of methods for generating random
numbers drawn from a variety of probability distributions and serves
as a replacement for ``RandomState``. The main difference between the
two is that ``Generator`` relies on an addi... | Generator |
python | doocs__leetcode | solution/3200-3299/3226.Number of Bit Changes to Make Two Integers Equal/Solution.py | {
"start": 0,
"end": 122
} | class ____:
def minChanges(self, n: int, k: int) -> int:
return -1 if n & k != k else (n ^ k).bit_count()
| Solution |
python | numba__numba | numba/tests/test_sort.py | {
"start": 18072,
"end": 22584
} | class ____(BaseSortingTest):
# NOTE these tests assume a non-argsort quicksort.
def test_insertion_sort(self):
n = 20
def check(l, n):
res = self.array_factory([9999] + l + [-9999])
f(res, res, 1, n)
self.assertEqual(res[0], 9999)
self.assertEqua... | BaseQuicksortTest |
python | astropy__astropy | astropy/nddata/utils.py | {
"start": 866,
"end": 975
} | class ____(ValueError):
"""Raised when determining the overlap of non-overlapping arrays."""
| NoOverlapError |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 806040,
"end": 806308
} | class ____(
sgqlc.types.Type,
Node,
AuditEntry,
EnterpriseAuditEntryData,
OrganizationAuditEntryData,
):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ()
| MembersCanDeleteReposClearAuditEntry |
python | astropy__astropy | astropy/coordinates/tests/test_masked.py | {
"start": 13202,
"end": 16397
} | class ____:
@classmethod
def setup_class(cls):
cls.ra = [0.0, 3.0, 6.0, 12.0, 15.0, 18.0] << u.hourangle
cls.dec = [-15.0, 30.0, 60.0, -60.0, 89.0, -80.0] << u.deg
cls.dis = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0] << u.pc
cls.mask_dis = np.array([False, True, False, True, False, Tru... | TestSkyCoordWithDifferentials |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 106966,
"end": 108150
} | class ____(TestCase):
def test_hashable(self):
iterable = list('www.example.com')
pred = lambda x: x in set('cmowz.')
self.assertEqual(list(mi.lstrip(iterable, pred)), list('example.com'))
self.assertEqual(list(mi.rstrip(iterable, pred)), list('www.example'))
self.assertEqua... | StripFunctionTests |
python | walkccc__LeetCode | solutions/1560. Most Visited Sector in a Circular Track/1560.py | {
"start": 0,
"end": 526
} | class ____:
def mostVisited(self, n: int, rounds: list[int]) -> list[int]:
# 1. if start <= end, [start, end] is the most visited.
#
# s --------- n
# 1 -------------- n
# 1 ------ e
#
# 2. if start > end, [1, end] and [start, n] are the most visited.
#
# s -- n
... | Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_data_validation02.py | {
"start": 315,
"end": 1082
} | 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 a XlsxWriter file with data validation."""
workbook =... | TestCompareXLSXFiles |
python | kubernetes-client__python | kubernetes/client/models/v1_for_node.py | {
"start": 383,
"end": 3518
} | 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... | V1ForNode |
python | spyder-ide__spyder | spyder/api/widgets/menus.py | {
"start": 1162,
"end": 1826
} | class ____(QProxyStyle):
"""Style adjustments that can only be done with a proxy style."""
def pixelMetric(self, metric, option=None, widget=None):
if metric == QStyle.PM_SmallIconSize:
# Change icon size for menus.
# Taken from https://stackoverflow.com/a/42145885/438386
... | SpyderMenuProxyStyle |
python | airbytehq__airbyte | airbyte-ci/connectors/connectors_qa/tests/unit_tests/test_checks/test_packaging.py | {
"start": 2206,
"end": 3809
} | class ____:
def test_pass_with_source_declarative_manifest(self, mocker, tmp_path):
connector = mocker.MagicMock(
code_directory=tmp_path,
metadata={"connectorBuildOptions": {"baseImage": "docker.io/airbyte/source-declarative-manifest:4.3.0@SHA"}},
)
# Act
re... | TestCheckManifestOnlyConnectorBaseImage |
python | falconry__falcon | falcon/errors.py | {
"start": 69477,
"end": 72063
} | class ____(HTTPError):
"""501 Not Implemented.
The 501 (Not Implemented) status code indicates that the server does
not support the functionality required to fulfill the request. This
is the appropriate response when the server does not recognize the
request method and is not capable of supporting... | HTTPNotImplemented |
python | huggingface__transformers | tests/models/doge/test_modeling_doge.py | {
"start": 1319,
"end": 8878
} | class ____:
def __init__(
self,
parent,
batch_size=8,
seq_length=16,
is_training=True,
use_input_mask=True,
use_token_type_ids=False,
use_labels=True,
vocab_size=128,
hidden_size=32,
num_hidden_layers=2,
num_attention_he... | DogeModelTester |
python | doocs__leetcode | solution/1700-1799/1797.Design Authentication Manager/Solution.py | {
"start": 0,
"end": 782
} | class ____:
def __init__(self, timeToLive: int):
self.t = timeToLive
self.d = defaultdict(int)
def generate(self, tokenId: str, currentTime: int) -> None:
self.d[tokenId] = currentTime + self.t
def renew(self, tokenId: str, currentTime: int) -> None:
if self.d[tokenId] <= c... | AuthenticationManager |
python | docker__docker-py | docker/types/containers.py | {
"start": 354,
"end": 571
} | class ____:
_values = (
'json-file',
'syslog',
'journald',
'gelf',
'fluentd',
'none'
)
JSON, SYSLOG, JOURNALD, GELF, FLUENTD, NONE = _values
| LogConfigTypesEnum |
python | tensorflow__tensorflow | tensorflow/python/debug/cli/cli_config.py | {
"start": 951,
"end": 5600
} | class ____(object):
"""Client-facing configurations for TFDBG command-line interfaces."""
_CONFIG_FILE_NAME = ".tfdbg_config"
_DEFAULT_CONFIG = [
("graph_recursion_depth", 20),
("mouse_mode", True),
]
def __init__(self, config_file_path=None):
self._config_file_path = (config_file_path or
... | CLIConfig |
python | zarr-developers__zarr-python | src/zarr/errors.py | {
"start": 2442,
"end": 2543
} | class ____(BaseZarrError):
"""
Raised when an unknown codec was used.
"""
| UnknownCodecError |
python | ray-project__ray | python/ray/train/v2/_internal/execution/worker_group/poll.py | {
"start": 1113,
"end": 1269
} | class ____:
running: bool
error: Optional[Exception] = None
training_report: Optional[_TrainingReport] = None
@dataclass(frozen=True)
| WorkerStatus |
python | ray-project__ray | python/ray/serve/_private/handle_options.py | {
"start": 839,
"end": 1407
} | class ____(InitHandleOptionsBase):
@classmethod
def create(cls, **kwargs) -> "InitHandleOptions":
for k in list(kwargs.keys()):
if kwargs[k] == DEFAULT.VALUE:
# Use default value
del kwargs[k]
# Detect replica source for handles
if (
... | InitHandleOptions |
python | tensorflow__tensorflow | tensorflow/python/distribute/cross_device_utils_test.py | {
"start": 1311,
"end": 5268
} | class ____(test.TestCase, parameterized.TestCase):
def _assert_values_equal(self, left, right):
self.assertAllEqual(
self.evaluate(ops.convert_to_tensor(left)),
self.evaluate(ops.convert_to_tensor(right)))
@test_util.run_in_graph_and_eager_modes
def testAggregateTensors(self):
t0 = const... | IndexedSlicesUtilsTest |
python | pypa__hatch | tests/backend/version/scheme/test_standard.py | {
"start": 3400,
"end": 3780
} | class ____:
def test_begin(self, isolation):
scheme = StandardScheme(str(isolation), {})
assert scheme.update("dev", "9000.0.0-rc.3-7", {}) == "9000.0.0rc3.post7.dev0"
def test_continue(self, isolation):
scheme = StandardScheme(str(isolation), {})
assert scheme.update("dev", "... | TestDev |
python | walkccc__LeetCode | solutions/467. Unique Substrings in Wraparound String/467.py | {
"start": 0,
"end": 479
} | class ____:
def findSubstringInWraproundString(self, s: str) -> int:
maxLength = 1
# count[i] := the number of substrings ending in ('a' + i)
count = [0] * 26
for i in range(len(s)):
if i > 0 and (ord(s[i]) - ord(s[i - 1]) == 1
or ord(s[i - 1]) - ord(s[i]) == 25):
ma... | Solution |
python | sphinx-doc__sphinx | sphinx/util/cfamily.py | {
"start": 2929,
"end": 3979
} | class ____:
def __eq__(self, other: object) -> bool:
if type(self) is not type(other):
return NotImplemented
try:
return self.__dict__ == other.__dict__
except AttributeError:
return False
def __hash__(self) -> int:
return hash(sorted(self.__d... | ASTBaseBase |
python | doocs__leetcode | solution/0700-0799/0709.To Lower Case/Solution.py | {
"start": 0,
"end": 134
} | class ____:
def toLowerCase(self, s: str) -> str:
return "".join([chr(ord(c) | 32) if c.isupper() else c for c in s])
| Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/remote_representation/handle.py | {
"start": 735,
"end": 3163
} | class ____:
repository_name: str
code_location_origin: CodeLocationOrigin
repository_python_origin: Optional[RepositoryPythonOrigin]
display_metadata: Mapping[str, str]
@classmethod
def from_location(cls, repository_name: str, code_location: "CodeLocation"):
from dagster._core.remote_re... | RepositoryHandle |
python | apache__airflow | airflow-core/tests/unit/cli/commands/test_jobs_command.py | {
"start": 1189,
"end": 6123
} | class ____:
@classmethod
def setup_class(cls):
cls.parser = cli_parser.get_parser()
def setup_method(self) -> None:
clear_db_jobs()
self.scheduler_job = None
self.job_runner = None
def teardown_method(self) -> None:
clear_db_jobs()
def test_should_report_su... | TestCliConfigList |
python | spack__spack | lib/spack/spack/package_base.py | {
"start": 107443,
"end": 107708
} | class ____(spack.error.SpackError):
"""Raised when the dependencies cannot be flattened as asked for."""
def __init__(self, conflict):
super().__init__("%s conflicts with another file in the flattened directory." % (conflict))
| DependencyConflictError |
python | jd__tenacity | tests/test_tenacity.py | {
"start": 51899,
"end": 53845
} | class ____(unittest.TestCase):
def test_reraise_by_default(self):
calls = []
@retry(
wait=tenacity.wait_fixed(0.1),
stop=tenacity.stop_after_attempt(2),
reraise=True,
)
def _reraised_by_default():
calls.append("x")
raise Ke... | TestReraiseExceptions |
python | tensorflow__tensorflow | third_party/xla/xla/python/xla_client.py | {
"start": 3463,
"end": 3728
} | class ____:
"""Python representation of a xla.ResultAccuracy protobuf."""
__slots__ = ('mode', 'atol', 'rtol', 'ulps')
def __init__(self):
self.mode = ops.ResultAccuracy_Mode.DEFAULT
self.atol = 0.0
self.rtol = 0.0
self.ulps = 0
| ResultAccuracy |
python | django__django | tests/gis_tests/geo3d/models.py | {
"start": 885,
"end": 959
} | class ____(NamedModel):
poly = models.PolygonField(srid=32140)
| Polygon2D |
python | allegroai__clearml | clearml/backend_api/session/jsonmodels/builders.py | {
"start": 4831,
"end": 5846
} | class ____(Builder):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super(ListBuilder, self).__init__(*args, **kwargs)
self.schemas = []
def add_type_schema(self, schema: Any) -> None:
self.schemas.append(schema)
def build(self) -> dict:
schema = {"type": "array"}
... | ListBuilder |
python | tensorflow__tensorflow | tensorflow/python/client/timeline.py | {
"start": 1229,
"end": 1642
} | class ____(
collections.namedtuple(
'AllocationMaximum', ('timestamp', 'num_bytes', 'tensors')
)
):
"""Stores the maximum allocation for a given allocator within the timelne.
Parameters:
timestamp: `tensorflow::Env::NowMicros()` when this maximum was reached.
num_bytes: the total memory use... | AllocationMaximum |
python | getsentry__sentry | src/sentry/api/endpoints/organization_spans_fields.py | {
"start": 5478,
"end": 7189
} | class ____(OrganizationSpansFieldsEndpointBase):
def get(self, request: Request, organization: Organization, key: str) -> Response:
performance_trace_explorer = features.has(
"organizations:performance-trace-explorer", organization, actor=request.user
)
visibility_explore_view =... | OrganizationSpansFieldValuesEndpoint |
python | doocs__leetcode | lcof2/剑指 Offer II 058. 日程表/Solution.py | {
"start": 0,
"end": 445
} | class ____:
def __init__(self):
self.sd = SortedDict()
def book(self, start: int, end: int) -> bool:
idx = self.sd.bisect_right(start)
if 0 <= idx < len(self.sd):
if end > self.sd.values()[idx]:
return False
self.sd[end] = start
return True
... | MyCalendar |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_tab_color02.py | {
"start": 350,
"end": 906
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("tab_color02.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with a tab color."""
workbook = Wo... | TestCompareXLSXFiles |
python | wandb__wandb | wandb/vendor/pygments/lexers/asm.py | {
"start": 5856,
"end": 6281
} | class ____(DelegatingLexer):
"""
For the output of 'objdump -Sr on compiled C++ files'
"""
name = 'cpp-objdump'
aliases = ['cpp-objdump', 'c++-objdumb', 'cxx-objdump']
filenames = ['*.cpp-objdump', '*.c++-objdump', '*.cxx-objdump']
mimetypes = ['text/x-cpp-objdump']
def __init__(self, *... | CppObjdumpLexer |
python | wandb__wandb | wandb/apis/public/registries/_members.py | {
"start": 1931,
"end": 3350
} | class ____:
kind: MemberKind
index: int
def encode(self) -> str:
"""Converts this parsed ID to a base64-encoded GraphQL ID."""
return b64encode_ascii(f"{self.kind.value}:{self.index}")
@singledispatchmethod
@classmethod
def from_obj(cls, obj: MemberOrId, /) -> MemberId:
... | MemberId |
python | tensorflow__tensorflow | third_party/xla/xla/python/xla_compiler_test.py | {
"start": 1284,
"end": 2873
} | class ____(parameterized.TestCase):
def test_create_literal_from_ndarray_rank_1(self, dtype):
input_array = create_random_array([10], dtype)
shape = xla_extension.Shape.array_shape(
input_array.dtype, input_array.shape
)
literal = xla_extension.Literal(shape)
# use `np.asarray` to ensure ... | ConstructLiteralTest |
python | plotly__plotly.py | plotly/basewidget.py | {
"start": 352,
"end": 34931
} | class ____(BaseFigure, anywidget.AnyWidget):
"""
Base class for FigureWidget. The FigureWidget class is code-generated as a
subclass
"""
_esm = pathlib.Path(__file__).parent / "package_data" / "widgetbundle.js"
# ### _data and _layout ###
# These properties store the current state of the t... | BaseFigureWidget |
python | astropy__astropy | astropy/nddata/tests/test_nddata.py | {
"start": 13292,
"end": 17400
} | class ____(MetaBaseTest):
test_class = NDData
args = np.array([[1.0]])
# Representation tests
def test_nddata_str():
arr1d = NDData(np.array([1, 2, 3]))
assert str(arr1d) == "[1 2 3]"
arr2d = NDData(np.array([[1, 2], [3, 4]]))
assert str(arr2d) == textwrap.dedent(
"""
[[1 2]
... | TestMetaNDData |
python | getsentry__sentry | src/sentry/integrations/discord/views/unlink_identity.py | {
"start": 854,
"end": 1525
} | class ____(DiscordIdentityLinkageView, UnlinkIdentityView):
def get_success_template_and_context(
self, params: Mapping[str, Any], integration: Integration | None
) -> tuple[str, dict[str, Any]]:
return "sentry/integrations/discord/unlinked.html", {}
def get_analytics_event(
self, p... | DiscordUnlinkIdentityView |
python | getsentry__sentry | tests/sentry/api/helpers/test_group_index.py | {
"start": 22008,
"end": 23325
} | class ____(TestCase):
def setUp(self) -> None:
self.group = self.create_group()
self.group_list = [self.group]
self.group_ids = [self.group]
self.project_lookup = {self.group.project_id: self.group.project}
def test_is_bookmarked(self) -> None:
handle_is_bookmarked(True,... | TestHandleIsBookmarked |
python | pytorch__pytorch | test/jit/fixtures_srcs/fixtures_src.py | {
"start": 961,
"end": 1202
} | class ____(torch.nn.Module):
def forward(
self,
a: Union[int, float, complex],
b: Union[int, float, complex],
out: torch.Tensor,
):
return torch.logspace(a, b, out=out)
| TestVersionedLogspaceOutV8 |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/view_resolve_conflict_top/package.py | {
"start": 228,
"end": 933
} | class ____(Package):
"""Package for testing edge cases for views, such as spec ordering and clashing files referring
to the same file on disk. See test_env_view_resolves_identical_file_conflicts."""
has_code = False
version("0.1.0")
depends_on("view-file")
depends_on("view-resolve-conflict-mid... | ViewResolveConflictTop |
python | huggingface__transformers | src/transformers/models/vilt/modeling_vilt.py | {
"start": 17613,
"end": 18269
} | class ____(nn.Module):
def __init__(self, config: ViltConfig):
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.interm... | ViltIntermediate |
python | doocs__leetcode | solution/3600-3699/3662.Filter Characters by Frequency/Solution.py | {
"start": 0,
"end": 218
} | class ____:
def filterCharacters(self, s: str, k: int) -> str:
cnt = Counter(s)
ans = []
for c in s:
if cnt[c] < k:
ans.append(c)
return "".join(ans)
| Solution |
python | pytorch__pytorch | tools/experimental/torchfuzz/operators/item.py | {
"start": 150,
"end": 1475
} | class ____(Operator):
"""Operator for converting 0-d tensor to scalar."""
def __init__(self):
super().__init__("item")
@property
def torch_op_name(self) -> str | None:
"""Item is a tensor method, not a direct torch operation."""
return None
def can_produce(self, output_spe... | ItemOperator |
python | scikit-learn__scikit-learn | asv_benchmarks/benchmarks/linear_model.py | {
"start": 2815,
"end": 3592
} | class ____(Predictor, Estimator, Benchmark):
"""
Benchmarks for Linear Regression.
"""
param_names = ["representation"]
params = (["dense", "sparse"],)
def setup_cache(self):
super().setup_cache()
def make_data(self, params):
(representation,) = params
if represen... | LinearRegressionBenchmark |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance6.py | {
"start": 293,
"end": 328
} | class ____(Generic[_T1]): ...
| ParentA |
python | pypa__pip | src/pip/_vendor/rich/errors.py | {
"start": 344,
"end": 422
} | class ____(ConsoleError):
"""Object is not renderable."""
| NotRenderableError |
python | huggingface__transformers | src/transformers/models/deberta/modeling_deberta.py | {
"start": 5512,
"end": 14884
} | class ____(nn.Module):
"""
Disentangled self-attention module
Parameters:
config (`str`):
A model config class instance with the configuration to build a new model. The schema is similar to
*BertConfig*, for more details, please refer [`DebertaConfig`]
"""
def __in... | DisentangledSelfAttention |
python | huggingface__transformers | examples/modular-transformers/modular_roberta.py | {
"start": 401,
"end": 527
} | class ____(BertModel):
def __init__(self, config, add_pooling_layer=True):
super().__init__(self, config)
| RobertaModel |
python | jupyterlab__jupyterlab | packages/services/examples/typescript-browser-with-output/main.py | {
"start": 1517,
"end": 2448
} | class ____(LabServerApp):
extension_url = "/example"
app_url = "/example"
default_url = "/example"
name = __name__
# In jupyter-server v2 terminals are an extension
load_other_extensions = True
app_name = "JupyterLab Example Service"
static_dir = os.path.join(HERE, "build")
templates... | ExampleApp |
python | readthedocs__readthedocs.org | readthedocs/projects/models.py | {
"start": 65923,
"end": 67358
} | class ____(TimeStampedModel, models.Model):
"""
Define a HTTP header for a user Domain.
All the HTTPHeader(s) associated with the domain are added in the response
from El Proxito.
NOTE: the available headers are hardcoded in the NGINX configuration for
now (see ``dockerfile/nginx/proxito.conf`... | HTTPHeader |
python | allegroai__clearml | clearml/utilities/pyhocon/exceptions.py | {
"start": 0,
"end": 163
} | class ____(Exception):
def __init__(self, message, ex=None):
super(ConfigException, self).__init__(message)
self._exception = ex
| ConfigException |
python | plotly__plotly.py | plotly/graph_objs/parcoords/_unselected.py | {
"start": 233,
"end": 2420
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "parcoords"
_path_str = "parcoords.unselected"
_valid_props = {"line"}
@property
def line(self):
"""
The 'line' property is an instance of Line
that may be specified as:
- An instance of :class:`plotly.graph_o... | Unselected |
python | huggingface__transformers | tests/models/sam2/test_image_processing_sam2.py | {
"start": 3516,
"end": 9873
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
fast_image_processing_class = Sam2ImageProcessorFast if is_torchvision_available() else None
test_slow_image_processor = False
def setUp(self):
super().setUp()
self.image_processor_tester = Sam2ImageProcessingTester(self)
@proper... | SamImageProcessingTest |
python | kamyu104__LeetCode-Solutions | Python/rotated-digits.py | {
"start": 1629,
"end": 2051
} | class ____(object):
def rotatedDigits(self, N):
"""
:type N: int
:rtype: int
"""
invalid, diff = set(['3', '4', '7']), set(['2', '5', '6', '9'])
result = 0
for i in xrange(N+1):
lookup = set(list(str(i)))
if invalid & lookup:
... | Solution3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.