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 | Textualize__textual | src/textual/widget.py | {
"start": 6622,
"end": 6727
} | class ____(WidgetError):
"""Error raised when there was a problem with the mount request."""
| MountError |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/init_ops_test.py | {
"start": 9077,
"end": 10172
} | class ____(test.TestCase):
@test_util.run_deprecated_v1
def testInitializerIdentical(self):
for dtype in [dtypes.float32, dtypes.float64]:
init1 = init_ops.random_normal_initializer(0.0, 1.0, seed=1, dtype=dtype)
init2 = init_ops.random_normal_initializer(0.0, 1.0, seed=1, dtype=dtype)
self.a... | RandomNormalInitializationTest |
python | dask__dask | dask/array/gufunc.py | {
"start": 21754,
"end": 33435
} | class ____:
"""
Binds `pyfunc` into ``dask.array.apply_gufunc`` when called.
Parameters
----------
pyfunc : callable
Function to call like ``func(*args, **kwargs)`` on input arrays
(``*args``) that returns an array or tuple of arrays. If multiple
arguments with non-matching ... | gufunc |
python | ipython__ipython | IPython/core/guarded_eval.py | {
"start": 13623,
"end": 13919
} | class ____:
"""Returns the key itself when item is requested via subscript."""
def __getitem__(self, key):
return key
IDENTITY_SUBSCRIPT = _IdentitySubscript()
SUBSCRIPT_MARKER = "__SUBSCRIPT_SENTINEL__"
UNKNOWN_SIGNATURE = Signature()
NOT_EVALUATED = object()
| _IdentitySubscript |
python | pypa__pip | src/pip/_vendor/urllib3/exceptions.py | {
"start": 4660,
"end": 4795
} | class ____(SecurityWarning):
"""Warned when connecting to a host with a certificate missing a SAN."""
pass
| SubjectAltNameWarning |
python | pydata__xarray | xarray/coding/cftime_offsets.py | {
"start": 3905,
"end": 6654
} | class ____:
_freq: ClassVar[str | None] = None
_day_option: ClassVar[DayOption | None] = None
n: int
def __init__(self, n: int = 1) -> None:
if not isinstance(n, int):
raise TypeError(
"The provided multiple 'n' must be an integer. "
f"Instead a value... | BaseCFTimeOffset |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/layout/menus.py | {
"start": 9690,
"end": 22718
} | class ____(UIControl):
"""
Completion menu that displays all the completions in several columns.
When there are more completions than space for them to be displayed, an
arrow is shown on the left or right side.
`min_rows` indicates how many rows will be available in any possible case.
When this... | MultiColumnCompletionMenuControl |
python | pandas-dev__pandas | pandas/tests/indexing/test_coercion.py | {
"start": 25603,
"end": 31040
} | class ____(CoercionBase):
klasses = ["series"]
method = "replace"
rep: dict[str, list] = {}
rep["object"] = ["a", "b"]
rep["int64"] = [4, 5]
rep["float64"] = [1.1, 2.2]
rep["complex128"] = [1 + 1j, 2 + 2j]
rep["bool"] = [True, False]
rep["datetime64[ns]"] = [
pd.Timestamp("2... | TestReplaceSeriesCoercion |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/docstring_signature.py | {
"start": 275,
"end": 477
} | class ____:
def __init__(self):
r"""E(foo: int, bar: int, baz: int) -> None \
E(foo: str, bar: str, baz: str) -> None \
E(foo: float, bar: float, baz: float)""" # NoQA: D209
| E |
python | joerick__pyinstrument | test/test_cmdline.py | {
"start": 561,
"end": 10499
} | class ____:
@pytest.fixture(autouse=True)
def _suppress_warnings(self, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setenv("PYINSTRUMENT_IGNORE_OVERHEAD_WARNING", "1")
def test_command_line(self, pyinstrument_invocation, tmp_path: Path):
busy_wait_py = tmp_path / "busy_wait.py"
bus... | TestCommandLine |
python | kamyu104__LeetCode-Solutions | Python/find-the-most-competitive-subsequence.py | {
"start": 29,
"end": 422
} | class ____(object):
def mostCompetitive(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
stk = []
for i, x in enumerate(nums):
while stk and stk[-1] > x and len(stk)+(len(nums)-i) > k:
stk.pop()
... | Solution |
python | getsentry__sentry | src/sentry/web/frontend/base.py | {
"start": 21593,
"end": 27997
} | class ____(BaseView, abc.ABC):
"""
The 'organization' keyword argument is automatically injected into the resulting dispatch, but currently the
typing of 'organization' will vary based on the subclass. It may either be an RpcOrganization or an orm
Organization based on the subclass. Be mindful during ... | AbstractOrganizationView |
python | RaRe-Technologies__gensim | gensim/test/test_utils.py | {
"start": 339,
"end": 2463
} | class ____(unittest.TestCase):
def test_None(self):
# test None
result = utils.is_corpus(None)
expected = (False, None)
self.assertEqual(expected, result)
def test_simple_lists_of_tuples(self):
# test list words
# one document, one word
potentialCorpus =... | TestIsCorpus |
python | apache__airflow | providers/google/tests/unit/google/cloud/sensors/test_dataprep.py | {
"start": 1040,
"end": 1806
} | class ____:
@mock.patch("airflow.providers.google.cloud.sensors.dataprep.GoogleDataprepHook")
def test_passing_arguments_to_hook(self, hook_mock):
sensor = DataprepJobGroupIsFinishedSensor(
task_id="check_job_group_finished",
job_group_id=JOB_GROUP_ID,
)
hook_moc... | TestDataprepJobGroupIsFinishedSensor |
python | weaviate__weaviate-python-client | weaviate/collections/config/async_.py | {
"start": 187,
"end": 270
} | class ____(_ConfigCollectionExecutor[ConnectionAsync]):
pass
| _ConfigCollectionAsync |
python | ray-project__ray | python/ray/data/preprocessors/torch.py | {
"start": 400,
"end": 5932
} | class ____(Preprocessor):
"""Apply a `TorchVision transform <https://pytorch.org/vision/stable/transforms.html>`_
to image columns.
Examples:
Torch models expect inputs of shape :math:`(B, C, H, W)` in the range
:math:`[0.0, 1.0]`. To convert images to this format, add ``ToTensor`` to your... | TorchVisionPreprocessor |
python | huggingface__transformers | src/transformers/loss/loss_deformable_detr.py | {
"start": 361,
"end": 2243
} | class ____(HungarianMatcher):
@torch.no_grad()
def forward(self, outputs, targets):
"""
Differences:
- out_prob = outputs["logits"].flatten(0, 1).sigmoid() instead of softmax
- class_cost uses alpha and gamma
"""
batch_size, num_queries = outputs["logits"].shape[:... | DeformableDetrHungarianMatcher |
python | numba__llvmlite | llvmlite/tests/test_refprune.py | {
"start": 5679,
"end": 6395
} | class ____(TestCase, PassManagerMixin):
refprune_bitmask = 0
prologue = r"""
declare void @NRT_incref(i8* %ptr)
declare void @NRT_decref(i8* %ptr)
"""
def check(self, irmod, subgraph_limit=None):
mod = llvm.parse_assembly(f"{self.prologue}\n{irmod}")
pb = self.pb()
pm = pb.getModul... | BaseTestByIR |
python | pennersr__django-allauth | allauth/socialaccount/providers/mailcow/views.py | {
"start": 272,
"end": 1294
} | class ____(OAuth2Adapter):
provider_id = "mailcow"
settings = app_settings.PROVIDERS.get(provider_id, {})
server = settings.get("SERVER", "https://hosted.mailcow.de")
access_token_url = "{0}/oauth/token".format(server)
authorize_url = "{0}/oauth/authorize".format(server)
profile_url = "{0}/oauth... | MailcowAdapter |
python | ansible__ansible | test/units/plugins/connection/test_psrp.py | {
"start": 1460,
"end": 7236
} | class ____(object):
OPTIONS_DATA: tuple[tuple[dict[str, t.Any], dict[str, t.Any]], ...] = (
# default options
(
{},
{
'_psrp_auth': 'negotiate',
'_psrp_configuration_name': 'Microsoft.PowerShell',
'_psrp_host': 'inventory_hostn... | TestConnectionPSRP |
python | Pylons__pyramid | tests/test_scripts/test_pserve.py | {
"start": 5113,
"end": 5369
} | class ____(unittest.TestCase):
def _callFUT(self, argv):
from pyramid.scripts.pserve import main
return main(argv, quiet=True)
def test_it(self):
result = self._callFUT(['pserve'])
self.assertEqual(result, 2)
| Test_main |
python | kamyu104__LeetCode-Solutions | Python/minimum-edge-weight-equilibrium-queries-in-a-tree.py | {
"start": 3901,
"end": 6160
} | class ____(object): # Time: O(NlogN), Space: O(NlogN), N is the number of nodes
def __init__(self, adj): # modified
def preprocess(u, p, w):
# depth of the node i
D[u] = 1 if p == -1 else D[p]+1
# ancestors of the node i
if p != -1:
P[u].appe... | TreeInfos2 |
python | kamyu104__LeetCode-Solutions | Python/k-highest-ranked-items-within-a-price-range.py | {
"start": 81,
"end": 2559
} | class ____(object):
def highestRankedKItems(self, grid, pricing, start, k):
"""
:type grid: List[List[int]]
:type pricing: List[int]
:type start: List[int]
:type k: int
:rtype: List[List[int]]
"""
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
... | Solution |
python | pennersr__django-allauth | allauth/socialaccount/providers/zoom/provider.py | {
"start": 263,
"end": 474
} | class ____(ProviderAccount):
def get_profile_url(self):
return self.account.extra_data.get("vanity_url")
def get_avatar_url(self):
return self.account.extra_data.get("pic_url")
| ZoomAccount |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/event/base.py | {
"start": 2727,
"end": 7264
} | class ____(_DispatchCommon[_ET]):
"""Mirror the event listening definitions of an Events class with
listener collections.
Classes which define a "dispatch" member will return a
non-instantiated :class:`._Dispatch` subclass when the member
is accessed at the class level. When the "dispatch" member ... | _Dispatch |
python | pyca__cryptography | tests/x509/test_x509_ext.py | {
"start": 212777,
"end": 221365
} | class ____:
def test_init(self):
with pytest.raises(TypeError):
x509.PrecertificateSignedCertificateTimestamps(
[object()] # type:ignore[list-item]
)
def test_repr(self):
assert repr(x509.PrecertificateSignedCertificateTimestamps([])) == (
"<... | TestPrecertificateSignedCertificateTimestampsExtension |
python | getsentry__sentry | src/sentry/integrations/slack/analytics.py | {
"start": 1013,
"end": 1184
} | class ____(analytics.Event):
organization_id: int
action: str
@analytics.eventclass("integrations.slack.approve_member_invitation")
| SlackIntegrationChartUnfurlAction |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/property9.py | {
"start": 100,
"end": 636
} | class ____:
def __init__(self, converter: Callable[[str, int], int]) -> None:
self.converter = converter
@property
def converter_prop(self) -> Callable[[str, int], int]:
return self.converter
def str_to_int(arg: str, base: int) -> int:
return int(arg, base=base)
obj = ClassA(str_to_... | ClassA |
python | sphinx-doc__sphinx | sphinx/domains/c/_parser.py | {
"start": 1873,
"end": 41734
} | class ____(BaseParser):
@property
def language(self) -> str:
return 'C'
@property
def id_attributes(self) -> Sequence[str]:
return self.config.c_id_attributes
@property
def paren_attributes(self) -> Sequence[str]:
return self.config.c_paren_attributes
def _parse_st... | DefinitionParser |
python | getsentry__sentry | tests/sentry/autofix/test_utils.py | {
"start": 9254,
"end": 12992
} | class ____(TestCase):
@with_feature("organizations:unlimited-auto-triggered-autofix-runs")
@patch("sentry.seer.autofix.utils.track_outcome")
def test_scanner_rate_limited_with_unlimited_flag(self, mock_track_outcome: MagicMock) -> None:
"""Test scanner rate limiting bypassed with unlimited feature f... | TestAutomationRateLimiting |
python | getsentry__sentry | tests/flagpole/test_evaluation_context.py | {
"start": 2619,
"end": 6733
} | class ____:
def test_empty_context_builder(self) -> None:
context_builder = ContextBuilder[ContextData]()
context = context_builder.build()
assert context.size() == 0
def test_static_transformer(self) -> None:
def static_transformer(_data: ContextData) -> dict[str, Any]:
... | TestContextBuilder |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1230141,
"end": 1230759
} | class ____(sgqlc.types.Type, Node):
"""Represents a 'mentioned' event on a given issue or pull request."""
__schema__ = github_schema
__field_names__ = ("actor", "created_at", "database_id")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
"""Identifies the actor who performed the event."""
... | MentionedEvent |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/edmodo/tests.py | {
"start": 240,
"end": 1357
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = EdmodoProvider.id
def get_mocked_response(self):
return MockedResponse(
HTTPStatus.OK,
"""
{
"url": "https://api.edmodo.com/users/74721257",
"id": 74721257,
"type": "teacher",
"username": "getacclaim-teacher1",
"use... | EdmodoTests |
python | conda__conda | conda/core/path_actions.py | {
"start": 20955,
"end": 22407
} | class ____(CreateInPrefixPathAction):
@classmethod
def create_actions(
cls, transaction_context, package_info, target_prefix, requested_link_type
):
shorcuts_lower = [name.lower() for name in (context.shortcuts_only or ())]
if context.shortcuts and (
not context.shortcuts... | MakeMenuAction |
python | google__jax | jax/_src/debugger/core.py | {
"start": 988,
"end": 1365
} | class ____:
keys: list[Hashable]
values: list[Any]
def __init__(self, keys, values):
self._keys = keys
self._values = values
def to_dict(self):
return dict(zip(self._keys, self._values))
def tree_flatten(self):
return self._values, self._keys
@classmethod
def tree_unflatten(cls, keys, ... | _DictWrapper |
python | huggingface__transformers | src/transformers/models/emu3/processing_emu3.py | {
"start": 1149,
"end": 1498
} | class ____(ProcessingKwargs, total=False):
text_kwargs: Emu3TextKwargs
_defaults = {
"text_kwargs": {
"return_for_image_generation": False,
"return_mm_token_type_ids": False,
},
"images_kwargs": {
"ratio": "1:1",
"image_area": 518400,
... | Emu3ProcessorKwargs |
python | wandb__wandb | wandb/vendor/pygments/styles/algol_nu.py | {
"start": 1394,
"end": 2278
} | class ____(Style):
background_color = "#ffffff"
default_style = ""
styles = {
Comment: "italic #888",
Comment.Preproc: "bold noitalic #888",
Comment.Special: "bold noitalic #888",
Keyword: "bold",
Keyword.Decl... | Algol_NuStyle |
python | donnemartin__interactive-coding-challenges | math_probability/power_two/test_is_power_of_two.py | {
"start": 18,
"end": 656
} | class ____(unittest.TestCase):
def test_is_power_of_two(self):
solution = Solution()
self.assertRaises(TypeError, solution.is_power_of_two, None)
self.assertEqual(solution.is_power_of_two(0), False)
self.assertEqual(solution.is_power_of_two(1), True)
self.assertEqual(solutio... | TestSolution |
python | pytorch__pytorch | torch/utils/data/datapipes/_hook_iterator.py | {
"start": 97,
"end": 11972
} | class ____(Enum):
r"""
These are the snapshotting-related states that IterDataPipes can be in.
`NotStarted` - allows you to restore a snapshot and create an iterator with reset
`Restored` - cannot restore again, allows you to create an iterator without resetting the DataPipe
`Iterating` - can resto... | _SnapshotState |
python | pypa__warehouse | tests/unit/test_http.py | {
"start": 208,
"end": 2090
} | class ____:
def test_create(self):
config = {"verify": "foo"}
factory = warehouse.http.ThreadLocalSessionFactory(config)
session_a, session_b = factory(_REQUEST), factory(_REQUEST)
assert session_a is session_b
assert session_a.verify == session_b.verify == config["verify"]
... | TestSession |
python | celery__celery | t/integration/test_tasks.py | {
"start": 1391,
"end": 2118
} | class ____:
@flaky
def test_class_based_task_retried(self, celery_session_app,
celery_session_worker):
task = ClassBasedAutoRetryTask()
celery_session_app.register_task(task)
res = task.delay()
assert res.get(timeout=TIMEOUT) == 1
def _pro... | test_class_based_tasks |
python | django__django | django/contrib/postgres/search.py | {
"start": 3020,
"end": 3649
} | class ____:
ADD = "||"
def _combine(self, other, connector, reversed):
if not isinstance(other, SearchVectorCombinable):
raise TypeError(
"SearchVector can only be combined with other SearchVector "
"instances, got %s." % type(other).__name__
)
... | SearchVectorCombinable |
python | geekcomputers__Python | text_to_audio/main.py | {
"start": 1068,
"end": 5047
} | class ____:
def __init__(
self,
text: str = None,
language: str = "en",
slow: bool = True,
accent: str = "com",
): # Correct the syntax here.
self.lang = language
self.slow = slow
self.accent = accent
if text is None:
self.use... | userAudio |
python | django__django | tests/sitemaps_tests/urls/http.py | {
"start": 2290,
"end": 2612
} | class ____(Sitemap):
"""Not all items have `lastmod`."""
location = "/location/"
def items(self):
o1 = TestModel()
o1.lastmod = datetime(2013, 3, 13, 10, 0, 0)
o2 = TestModel()
return [o1, o2]
def lastmod(self, obj):
return obj.lastmod
| CallableLastmodPartialSitemap |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/connectors/aioodbc.py | {
"start": 1060,
"end": 1178
} | class ____(
AsyncAdapt_aioodbc_cursor, AsyncAdapt_dbapi_ss_cursor
):
__slots__ = ()
| AsyncAdapt_aioodbc_ss_cursor |
python | requests__requests-oauthlib | tests/test_oauth1_session.py | {
"start": 2744,
"end": 14440
} | class ____(unittest.TestCase):
def test_signature_types(self):
def verify_signature(getter):
def fake_send(r, **kwargs):
signature = getter(r)
if isinstance(signature, bytes):
signature = signature.decode("utf-8")
self.assertIn(... | OAuth1SessionTest |
python | spack__spack | lib/spack/spack/vendor/jinja2/nodes.py | {
"start": 31188,
"end": 31501
} | class ____(Expr):
"""Mark the wrapped expression as safe (wrap it as `Markup`)."""
fields = ("expr",)
expr: Expr
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> Markup:
eval_ctx = get_eval_context(self, eval_ctx)
return Markup(self.expr.as_const(eval_ctx))
| MarkSafe |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/class_interval.py | {
"start": 8814,
"end": 8879
} | class ____(A20):
def m0(self, arg):
_test_sink(arg)
| C20 |
python | numba__numba | numba/cuda/deviceufunc.py | {
"start": 24584,
"end": 30955
} | class ____(metaclass=ABCMeta):
"""
Implements memory management and kernel launch operations for GUFunc calls.
One instance of this class is instantiated for each call, and the instance
is specific to the arguments given to the GUFunc call.
The base class implements the overall logic; subclasses p... | GUFuncCallSteps |
python | sphinx-doc__sphinx | sphinx/domains/c/__init__.py | {
"start": 13173,
"end": 13230
} | class ____(CObject):
object_type = 'union'
| CUnionObject |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linalg_ops_test.py | {
"start": 9968,
"end": 11628
} | class ____(object):
def test_batch_default_tolerance(self):
x_ = np.array(
[
[
[2, 3, -2], # = row2+row3
[-1, 1, -2],
[3, 2, 0]
],
[
[0, 2, 0], # = 2*row2
[0, 1, 0],
[0, 3... | _MatrixRankTest |
python | django__django | django/utils/autoreload.py | {
"start": 14719,
"end": 14771
} | class ____(RuntimeError):
pass
| WatchmanUnavailable |
python | tensorflow__tensorflow | tensorflow/python/distribute/strategy_common_test.py | {
"start": 9420,
"end": 11237
} | class ____(test.TestCase, parameterized.TestCase):
def testDenseUpdate(self, strategy, tf_function, update_fn):
if strategy_test_lib.is_tpu_strategy(strategy) and (not tf_function):
self.skipTest('Skip TPUStrategy + eager combination.')
with strategy.scope():
distributed_variable1 = variables.Var... | ReplicaCtxUpdateTest |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/dagster/subschema/daemon.py | {
"start": 413,
"end": 510
} | class ____(BaseModel, extra="forbid"):
applyLimitPerUniqueValue: bool
| TagConcurrencyLimitConfig |
python | numba__numba | numba/core/typing/mathdecl.py | {
"start": 4075,
"end": 4310
} | class ____(ConcreteTemplate):
cases = [
signature(types.Tuple((types.float64, types.intc)), types.float64),
signature(types.Tuple((types.float32, types.intc)), types.float32),
]
@infer_global(math.ldexp)
| Math_frexp |
python | rushter__MLAlgorithms | mla/ensemble/gbm.py | {
"start": 464,
"end": 1421
} | class ____:
"""Base class for loss functions."""
def __init__(self, regularization=1.0):
self.regularization = regularization
def grad(self, actual, predicted):
"""First order gradient."""
raise NotImplementedError()
def hess(self, actual, predicted):
"""Second order g... | Loss |
python | doocs__leetcode | lcof2/剑指 Offer II 076. 数组中的第 k 大的数字/Solution.py | {
"start": 0,
"end": 789
} | class ____:
def findKthLargest(self, nums: List[int], k: int) -> int:
def quick_sort(left, right, k):
if left == right:
return nums[left]
i, j = left - 1, right + 1
x = nums[(left + right) >> 1]
while i < j:
while 1:
... | Solution |
python | pennersr__django-allauth | allauth/mfa/totp/views.py | {
"start": 965,
"end": 2720
} | class ____(FormView):
form_class = ActivateTOTPForm
template_name = "mfa/totp/activate_form." + account_settings.TEMPLATE_EXTENSION
def dispatch(self, request, *args, **kwargs):
if is_mfa_enabled(request.user, [Authenticator.Type.TOTP]):
return HttpResponseRedirect(reverse("mfa_deactiva... | ActivateTOTPView |
python | kamyu104__LeetCode-Solutions | Python/brick-wall.py | {
"start": 127,
"end": 579
} | class ____(object):
def leastBricks(self, wall):
"""
:type wall: List[List[int]]
:rtype: int
"""
widths = collections.defaultdict(int)
result = len(wall)
for row in wall:
width = 0
for i in xrange(len(row)-1):
width += r... | Solution |
python | anthropics__anthropic-sdk-python | tests/api_resources/beta/test_files.py | {
"start": 9982,
"end": 20077
} | class ____:
parametrize = pytest.mark.parametrize(
"async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"]
)
@parametrize
async def test_method_list(self, async_client: AsyncAnthropic) -> None:
file = await async_client.beta.files.lis... | TestAsyncFiles |
python | scikit-learn__scikit-learn | sklearn/tests/test_pipeline.py | {
"start": 2532,
"end": 2773
} | class ____(NoFit):
def fit(self, X, y=None):
return self
def get_params(self, deep=False):
return {"a": self.a, "b": self.b}
def set_params(self, **params):
self.a = params["a"]
return self
| NoTrans |
python | numba__numba | numba/np/ufunc/array_exprs.py | {
"start": 12750,
"end": 16878
} | class ____(ast.NodeTransformer):
def generic_visit(self, node: ast.AST) -> ast.AST:
node = super().generic_visit(node)
if hasattr(node, "lineno"):
if getattr(node, "end_lineno", None) is not None:
if node.lineno > node.end_lineno:
del node.lineno
... | _EraseInvalidLineRanges |
python | PrefectHQ__prefect | tests/cli/transfer/test_dag.py | {
"start": 1706,
"end": 20501
} | class ____:
def test_init_creates_empty_dag(self):
"""Test DAG initialization creates empty structures."""
dag = TransferDAG()
assert dag.nodes == {}
assert dag._dependencies == defaultdict(set)
assert dag._dependents == defaultdict(set)
assert dag._status == {}
... | TestTransferDAG |
python | pandas-dev__pandas | pandas/tests/indexes/interval/test_indexing.py | {
"start": 8907,
"end": 19544
} | class ____:
@pytest.mark.parametrize(
"query, expected",
[
([Interval(2, 4, closed="right")], [1]),
([Interval(2, 4, closed="left")], [-1]),
([Interval(2, 4, closed="both")], [-1]),
([Interval(2, 4, closed="neither")], [-1]),
([Interval(1, ... | TestGetIndexer |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 17805,
"end": 17869
} | class ____(TrackedAbstractBaseA):
pass
| TrackedWithAbstractBase |
python | keon__algorithms | tests/test_strings.py | {
"start": 18867,
"end": 19377
} | class ____(unittest.TestCase):
"""[summary]
Test for the file longest_palindromic_substring.py
Arguments:
unittest {[type]} -- [description]
"""
def test_longest_palindromic_substring(self):
self.assertEqual("bb", longest_palindrome("cbbd"))
self.assertEqual("abba", longest_p... | TestLongestPalindromicSubstring |
python | readthedocs__readthedocs.org | readthedocs/projects/forms.py | {
"start": 23003,
"end": 24295
} | class ____(forms.ModelForm):
"""Form to add/update project relationships."""
parent = forms.CharField(widget=forms.HiddenInput(), required=False)
class Meta:
model = ProjectRelationship
fields = "__all__"
def __init__(self, *args, **kwargs):
self.project = kwargs.pop("project"... | ProjectRelationshipForm |
python | etianen__django-reversion | tests/test_app/models.py | {
"start": 2689,
"end": 2849
} | class ____(models.Model):
test_model = models.ForeignKey(
TestModelWithNaturalKey,
on_delete=models.CASCADE,
)
| TestModelInlineByNaturalKey |
python | sphinx-doc__sphinx | sphinx/highlighting.py | {
"start": 3162,
"end": 7855
} | class ____:
# Set these attributes if you want to have different Pygments formatters
# than the default ones.
html_formatter = HtmlFormatter[str]
latex_formatter = LatexFormatter[str]
def __init__(
self,
dest: str = 'html',
stylename: str = 'sphinx',
latex_engine: st... | PygmentsBridge |
python | walkccc__LeetCode | solutions/990. Satisfiability of Equality Equations/990.py | {
"start": 284,
"end": 660
} | class ____:
def equationsPossible(self, equations: list[str]) -> bool:
uf = UnionFind(26)
for x, op, _, y in equations:
if op == '=':
uf.union(ord(x) - ord('a'),
ord(y) - ord('a'))
return all(
uf.find(ord(x) - ord('a')) !=
uf.find(ord(y) - ord('a'))
... | Solution |
python | apache__airflow | airflow-core/tests/unit/ti_deps/deps/test_valid_state_dep.py | {
"start": 1085,
"end": 1856
} | class ____:
def test_valid_state(self):
"""
Valid state should pass this dep
"""
ti = Mock(state=State.QUEUED, end_date=datetime(2016, 1, 1))
assert ValidStateDep({State.QUEUED}).is_met(ti=ti)
def test_invalid_state(self):
"""
Invalid state should fail th... | TestValidStateDep |
python | uqfoundation__dill | dill/_objects.py | {
"start": 2226,
"end": 19916
} | class ____(object):
__slots__ = ['descriptor']
def _function(x): yield x
def _function2():
try: raise
except Exception:
from sys import exc_info
e, er, tb = exc_info()
return er, tb
if HAS_CTYPES:
class _Struct(ctypes.Structure):
pass
_Struct._fields_ = [("_field", ct... | _newclass2 |
python | spack__spack | lib/spack/spack/rewiring.py | {
"start": 1968,
"end": 2359
} | class ____(RewireError):
"""Raised when the build_spec for a splice was not installed."""
def __init__(self, spliced_spec, build_spec, dep):
super().__init__(
"""Rewire of {0}
failed due to missing install of build spec {1}
for spec {2}""".format(
spl... | PackageNotInstalledError |
python | kamyu104__LeetCode-Solutions | Python/linked-list-random-node.py | {
"start": 839,
"end": 1219
} | class ____(object):
def __init__(self, head):
"""
:type head: Optional[ListNode]
"""
self.__lookup = []
while head:
self.__lookup.append(head.val)
head = head.next
def getRandom(self):
"""
:rtype: int
"""
... | Solution2 |
python | pytorch__pytorch | torch/nn/utils/prune.py | {
"start": 34872,
"end": 58397
} | class ____(BasePruningMethod):
PRUNING_TYPE = "global"
def __init__(self, mask) -> None:
self.mask = mask
def compute_mask(self, t, default_mask):
assert default_mask.shape == self.mask.shape
mask = default_mask * self.mask.to(dtype=default_mask.dtype)
return mask
@cla... | CustomFromMask |
python | google__jax | tests/documentation_coverage_test.py | {
"start": 9424,
"end": 13060
} | class ____(jtu.JaxTestCase):
def setUp(self):
if jtu.runtime_environment() == 'bazel':
self.skipTest("Skipping test in bazel, because rst docs aren't accessible.")
def test_list_public_jax_modules(self):
"""Simple smoke test for list_public_jax_modules()"""
apis = list_public_jax_modules()
... | DocumentationCoverageTest |
python | getsentry__sentry | src/sentry/utils/types.py | {
"start": 3043,
"end": 3462
} | class ____(Type[dict]):
"""Coerce a dict out of a json/yaml string"""
name = "dictionary"
expected_types = (dict,)
def _default(self) -> dict[str, typing.Any]:
# make sure we create a fresh dict each time
return {}
def convert(self, value):
try:
return safe_loa... | DictType |
python | django__django | django/contrib/admin/options.py | {
"start": 99668,
"end": 99755
} | class ____(InlineModelAdmin):
template = "admin/edit_inline/tabular.html"
| TabularInline |
python | getsentry__sentry | src/sentry/api/endpoints/organization_metrics_meta.py | {
"start": 626,
"end": 2639
} | class ____(OrganizationEventsEndpointBase):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
"""Metrics data can contain less than great data like null or unparameterized transactions
This endpoint will return projects that have dynamic sampling turned on, and another list of "compatible p... | OrganizationMetricsCompatibility |
python | airbytehq__airbyte | airbyte-ci/connectors/connectors_qa/src/connectors_qa/checks/documentation/models.py | {
"start": 2893,
"end": 3871
} | class ____(Content):
def __init__(self, connector: Connector):
self.connector = connector
super().__init__()
self.links = self._links()
def _content(self) -> str:
return self.connector.documentation_file_path.read_text().rstrip()
def _links(self) -> list[str]:
retur... | DocumentationContent |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/stackexchange/tests.py | {
"start": 254,
"end": 1713
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = StackExchangeProvider.id
def get_mocked_response(self):
return MockedResponse(
HTTPStatus.OK,
"""
{
"has_more": false,
"items": [
{
"is_employee": false,
... | StackExchangeTests |
python | doocs__leetcode | solution/3700-3799/3742.Maximum Path Score in a Grid/Solution.py | {
"start": 0,
"end": 588
} | class ____:
def maxPathScore(self, grid: List[List[int]], k: int) -> int:
@cache
def dfs(i: int, j: int, k: int) -> int:
if i < 0 or j < 0 or k < 0:
return -inf
if i == 0 and j == 0:
return 0
res = grid[i][j]
if grid[i][... | Solution |
python | airbytehq__airbyte | airbyte-ci/connectors/connectors_qa/src/connectors_qa/checks/documentation/documentation.py | {
"start": 5923,
"end": 8060
} | class ____(CheckDocumentationContent):
name = "Links used in connector documentation are valid"
description = "The user facing connector documentation should update invalid links in connector documentation. For links that are used as example and return 404 status code, use `example: ` before link to skip it."
... | CheckDocumentationLinks |
python | ansible__ansible | test/integration/targets/shell-plugins/connection_plugins/test_connection_override.py | {
"start": 471,
"end": 1017
} | class ____(ConnectionBase):
""" test connection """
transport = 'test_connection_override'
def __init__(self, *args, **kwargs):
self._shell_type = 'powershell' # Set a shell type that is not sh
super(Connection, self).__init__(*args, **kwargs)
def _connect(self):
pass
de... | Connection |
python | tensorflow__tensorflow | tensorflow/lite/python/analyzer.py | {
"start": 1415,
"end": 3937
} | class ____():
"""Provides a collection of TFLite model analyzer tools.
Example:
```python
model = tf.keras.applications.MobileNetV3Large()
fb_model = tf.lite.TFLiteConverterV2.from_keras_model(model).convert()
tf.lite.experimental.Analyzer.analyze(model_content=fb_model)
# === TFLite ModelAnalyzer ===
... | ModelAnalyzer |
python | pandas-dev__pandas | asv_bench/benchmarks/join_merge.py | {
"start": 5262,
"end": 5659
} | class ____:
def setup(self):
N = 5000
self.left = DataFrame(
np.random.randint(1, N / 50, (N, 2)), columns=["jim", "joe"]
)
self.right = DataFrame(
np.random.randint(1, N / 50, (N, 2)), columns=["jolie", "jolia"]
).set_index("jolie")
def time_left... | JoinIndex |
python | huggingface__transformers | src/transformers/models/markuplm/modeling_markuplm.py | {
"start": 11682,
"end": 12389
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.transform = MarkupLMPredictionHeadTransform(config)
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
self.decoder = nn.Linear(config.hidden... | MarkupLMLMPredictionHead |
python | numba__numba | numba/core/untyped_passes.py | {
"start": 4069,
"end": 4741
} | class ____(FunctionPass):
_name = "ir_processing"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
func_ir = state['func_ir']
post_proc = postproc.PostProcessor(func_ir)
post_proc.run()
if config.DEBUG or config.DUMP_IR:
name =... | IRProcessing |
python | getsentry__sentry | src/sentry/runner/commands/presenters/audit_log_presenter.py | {
"start": 297,
"end": 1889
} | class ____(WebhookPresenter):
def __init__(self, source: str, dry_run: bool = False) -> None:
self.dry_run = dry_run
super().__init__(source)
@staticmethod
def is_webhook_enabled() -> bool:
return (
options.get("flags:options-audit-log-is-enabled") is True
an... | AuditLogPresenter |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zoho-crm/source_zoho_crm/types.py | {
"start": 7968,
"end": 8718
} | class ____(FromDictMixin):
api_name: str
module_name: str
api_supported: bool
fields: Optional[Iterable[FieldMeta]] = dataclasses.field(default_factory=list)
@property
def schema(self) -> Schema:
if not self.fields:
raise IncompleteMetaDataException("Not enough data")
... | ModuleMeta |
python | PrefectHQ__prefect | src/integrations/prefect-dbt/tests/cloud/test_utils.py | {
"start": 185,
"end": 2930
} | class ____:
async def test_endpoint_returns_json(self, dbt_cloud_credentials):
with respx.mock(using="httpx") as respx_mock:
respx_mock.get(
"https://cloud.getdbt.com/api/v2/accounts/123456789/projects/",
headers={"Authorization": "Bearer my_api_key"},
... | TestCallDbtCloudAdministrativeApiEndpoint |
python | allegroai__clearml | clearml/utilities/process/mp.py | {
"start": 15749,
"end": 16901
} | class ____(AbstractContextManager):
_instances = []
def __init__(self) -> None:
self._lock = None
SingletonLock._instances.append(self)
def acquire(self, *args: Any, **kwargs: Any) -> bool:
self.create()
return self._lock.acquire(*args, **kwargs)
def release(self, *arg... | SingletonLock |
python | huggingface__transformers | src/transformers/models/longcat_flash/modular_longcat_flash.py | {
"start": 13568,
"end": 14657
} | class ____(PreTrainedModel):
config: LongcatFlashConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["LongcatFlashDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_a... | LongcatFlashPreTrainedModel |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/sqlite/base.py | {
"start": 70036,
"end": 70841
} | class ____(default.DefaultExecutionContext):
@util.memoized_property
def _preserve_raw_colnames(self):
return (
not self.dialect._broken_dotted_colnames
or self.execution_options.get("sqlite_raw_colnames", False)
)
def _translate_colname(self, colname):
# TOD... | SQLiteExecutionContext |
python | huggingface__transformers | tests/models/longt5/test_modeling_longt5.py | {
"start": 19138,
"end": 30832
} | class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (LongT5Model, LongT5ForConditionalGeneration) if is_torch_available() else ()
pipeline_model_mapping = (
{
"feature-extraction": LongT5Model,
"summarization": LongT5Fo... | LongT5ModelTest |
python | huggingface__transformers | src/transformers/models/groupvit/modeling_groupvit.py | {
"start": 22547,
"end": 23548
} | class ____(nn.Module):
def __init__(
self,
config: GroupViTVisionConfig,
hidden_size: Optional[int] = None,
intermediate_size: Optional[int] = None,
output_size: Optional[int] = None,
):
super().__init__()
self.config = config
self.activation_fn = ... | GroupViTMLP |
python | oauthlib__oauthlib | tests/oauth2/rfc6749/clients/test_legacy_application.py | {
"start": 257,
"end": 6427
} | class ____(TestCase):
client_id = "someclientid"
client_secret = 'someclientsecret'
scope = ["/profile"]
kwargs = {
"some": "providers",
"require": "extra arguments"
}
username = "user_username"
password = "user_password"
body = "not=empty"
body_up = "not=empty&gra... | LegacyApplicationClientTest |
python | kamyu104__LeetCode-Solutions | Python/campus-bikes-ii.py | {
"start": 1277,
"end": 2180
} | class ____(object):
def assignBikes(self, workers, bikes):
"""
:type workers: List[List[int]]
:type bikes: List[List[int]]
:rtype: int
"""
def manhattan(p1, p2):
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
min_heap = [(0, 0, 0)]
... | Solution2 |
python | pandas-dev__pandas | pandas/core/computation/pytables.py | {
"start": 17016,
"end": 20197
} | class ____(expr.Expr):
"""
Hold a pytables-like expression, comprised of possibly multiple 'terms'.
Parameters
----------
where : string term expression, PyTablesExpr, or list-like of PyTablesExprs
queryables : a "kinds" map (dict of column name -> kind), or None if column
is non-indexa... | PyTablesExpr |
python | ray-project__ray | python/ray/exceptions.py | {
"start": 24192,
"end": 25458
} | class ____(ObjectLostError):
"""Indicates that the owner of the object has died while there is still a
reference to the object.
Args:
object_ref_hex: Hex ID of the object.
"""
def __str__(self):
log_loc = "`/tmp/ray/session_latest/logs`"
if self.owner_address:
t... | OwnerDiedError |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.