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 | Netflix__metaflow | metaflow/plugins/storage_executor.py | {
"start": 3871,
"end": 6137
} | class ____(object):
"""Thin wrapper around a ProcessPoolExecutor, or a ThreadPoolExecutor where
the former may be unsafe.
"""
def __init__(self, use_processes=False):
(
processpool_max_workers,
threadpool_max_workers,
) = _compute_executor_max_workers()
i... | StorageExecutor |
python | spack__spack | lib/spack/spack/package_base.py | {
"start": 107251,
"end": 107443
} | class ____(ExtensionError):
"""Raised when there are problems activating an extension."""
def __init__(self, msg, long_msg=None):
super().__init__(msg, long_msg)
| ActivationError |
python | scikit-learn__scikit-learn | sklearn/ensemble/_weight_boosting.py | {
"start": 10312,
"end": 28532
} | class ____(
_RoutingNotSupportedMixin, ClassifierMixin, BaseWeightBoosting
):
"""An AdaBoost classifier.
An AdaBoost [1]_ classifier is a meta-estimator that begins by fitting a
classifier on the original dataset and then fits additional copies of the
classifier on the same dataset but where the we... | AdaBoostClassifier |
python | neetcode-gh__leetcode | python/0151-reverse-words-in-a-string.py | {
"start": 0,
"end": 403
} | class ____:
def reverseWords(self, s: str) -> str:
# Remove leading and trailing spaces
s = s.strip()
# Split the string into words
words = s.split()
# Reverse the order of words
words = words[::-1]
# Join the words with a single spa... | Solution |
python | python__mypy | mypy/expandtype.py | {
"start": 4160,
"end": 4869
} | class ____(BoolTypeQuery):
def __init__(self) -> None:
super().__init__(ANY_STRATEGY)
def visit_callable_type(self, t: CallableType) -> bool:
return t.is_generic() or super().visit_callable_type(t)
# Share a singleton since this is performance sensitive
has_generic_callable: Final = HasGeneri... | HasGenericCallable |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocolExplicit1.py | {
"start": 1280,
"end": 1312
} | class ____:
x = 3
@final
| Mixin |
python | coleifer__peewee | peewee.py | {
"start": 269118,
"end": 269444
} | class ____(ModelDictCursorWrapper):
constructor = tuple
def process_row(self, row):
columns, converters = self.columns, self.converters
return self.constructor([
(converters[i](row[i]) if converters[i] is not None else row[i])
for i in range(self.ncols)])
| ModelTupleCursorWrapper |
python | getsentry__sentry | tests/sentry/notifications/platform/test_registry.py | {
"start": 474,
"end": 1251
} | class ____(TestCase):
def test_get_all(self) -> None:
providers = provider_registry.get_all()
expected_providers = [
EmailNotificationProvider,
SlackNotificationProvider,
MSTeamsNotificationProvider,
DiscordNotificationProvider,
]
asse... | NotificationProviderRegistryTest |
python | numba__numba | numba/stencils/stencil.py | {
"start": 2449,
"end": 39893
} | class ____(object):
"""
A special type to hold stencil information for the IR.
"""
id_counter = 0
def __init__(self, kernel_ir, mode, options):
self.id = type(self).id_counter
type(self).id_counter += 1
self.kernel_ir = kernel_ir
self.mode = mode
self.option... | StencilFunc |
python | fastai__fastai | fastai/layers.py | {
"start": 24885,
"end": 25302
} | class ____(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
ctx.save_for_backward(x)
return _mish_jit_fwd(x)
@staticmethod
def backward(ctx, grad_output):
x = ctx.saved_variables[0]
return _mish_jit_bwd(x, grad_output)
# %% ../nbs/01_layers.ipynb 163
def mis... | MishJitAutoFn |
python | fluentpython__example-code-2e | 15-more-types/cafeteria/cafeteria.py | {
"start": 782,
"end": 2137
} | class ____:
def __init__(
self,
dispenser: BeverageDispenser[Juice],
trash_can: TrashCan[Biodegradable],
):
"""Initialize..."""
################################################ exact types
juice_dispenser = BeverageDispenser(Juice())
bio_can: TrashCan[Biodegradable] = TrashCan... | Cafeteria |
python | tornadoweb__tornado | demos/blog/blog.py | {
"start": 8280,
"end": 9354
} | class ____(BaseHandler):
async def get(self):
# If there are no authors, redirect to the account creation page.
if not await self.any_author_exists():
self.redirect("/auth/create")
else:
self.render("login.html", error=None)
async def post(self):
try:
... | AuthLoginHandler |
python | scipy__scipy | scipy/optimize/_minimize.py | {
"start": 47866,
"end": 48427
} | class ____:
# Patches a callback that accepts an intermediate_result
def __init__(self, callback, i_fixed, x_fixed):
self.callback = callback
self.i_fixed = i_fixed
self.x_fixed = x_fixed
def __call__(self, intermediate_result):
x_in = intermediate_result.x
x_out = n... | _Patch_Callback_Equal_Variables |
python | numpy__numpy | numpy/_core/tests/test_ufunc.py | {
"start": 6389,
"end": 116310
} | class ____:
def test_pickle(self):
for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
assert_(pickle.loads(pickle.dumps(np.sin,
protocol=proto)) is np.sin)
# Check that ufunc not defined in the top level numpy namespace
# su... | TestUfunc |
python | django__django | tests/logging_tests/tests.py | {
"start": 1732,
"end": 1961
} | class ____:
@classmethod
def setUpClass(cls):
super().setUpClass()
logging.config.dictConfig(DEFAULT_LOGGING)
cls.addClassCleanup(logging.config.dictConfig, settings.LOGGING)
| SetupDefaultLoggingMixin |
python | django__django | tests/admin_changelist/admin.py | {
"start": 1690,
"end": 1765
} | class ____(ChildAdmin):
paginator = CustomPaginator
| CustomPaginationAdmin |
python | ray-project__ray | python/ray/cluster_utils.py | {
"start": 4392,
"end": 15512
} | class ____:
def __init__(
self,
initialize_head: bool = False,
connect: bool = False,
head_node_args: dict = None,
shutdown_at_exit: bool = True,
):
"""Initializes all services of a Ray cluster.
Args:
initialize_head: Automatically start a Ray... | Cluster |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 542347,
"end": 547733
} | class ____(ExprNode):
"""
Short-circuiting boolean operation.
Note that this node provides the same code generation method as
BoolBinopResultNode to simplify expression nesting.
operator string "and"/"or"
operand1 BoolBinopNode/BoolBinopResultNode left operand
... | BoolBinopNode |
python | pandas-dev__pandas | pandas/tests/series/indexing/test_setitem.py | {
"start": 22603,
"end": 23468
} | class ____:
@pytest.mark.parametrize("unique", [True, False])
@pytest.mark.parametrize("val", [3, 3.0, "3"], ids=type)
def test_setitem_non_bool_into_bool(self, val, indexer_sli, unique):
# dont cast these 3-like values to bool
ser = Series([True, False])
if not unique:
s... | TestSetitemCasting |
python | getsentry__sentry | tests/sentry/preprod/api/endpoints/test_organization_preprod_artifact_assemble.py | {
"start": 1040,
"end": 9565
} | class ____(TestCase):
"""Unit tests for schema validation function - no database required."""
def test_valid_minimal_schema(self) -> None:
"""Test valid minimal schema passes validation."""
data = {"checksum": "a" * 40, "chunks": []}
body = orjson.dumps(data)
result, error = val... | ValidatePreprodArtifactSchemaTest |
python | pennersr__django-allauth | allauth/socialaccount/providers/clever/provider.py | {
"start": 514,
"end": 1753
} | class ____(OAuth2Provider):
id = "clever"
name = "Clever"
account_class = CleverAccount
oauth2_adapter_class = CleverOAuth2Adapter
def extract_uid(self, data):
return data["data"]["id"]
def get_user_type(self, data):
return list(data.get("data", {}).get("roles", {}).keys())[0]
... | CleverProvider |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 10110,
"end": 10214
} | class ____(ShowFieldTypeAndContent, PolymorphicModel):
b = models.CharField(max_length=1)
| CustomPkBase |
python | pydantic__pydantic | tests/mypy/modules/plugin_fail.py | {
"start": 3502,
"end": 3666
} | class ____(BaseModel):
x: int = 1
y = 2
z = 2 # type: ignore[pydantic-field]
AliasGeneratorModel2(x=1)
AliasGeneratorModel2(y=1, z=1)
| UntypedFieldModel |
python | PrefectHQ__prefect | tests/custom_types/test_self_validating_types.py | {
"start": 1053,
"end": 2503
} | class ____:
@pytest.mark.parametrize(
"value,delim,expected",
[
(None, None, set()),
("", None, set()),
("429", None, {429}),
("404,429,503", None, {404, 429, 503}),
("401|403|409", "|", {401, 403, 409}),
(419, None, {419}),
... | TestCustomValidationLogic |
python | google__pytype | pytype/pytd/optimize.py | {
"start": 13881,
"end": 14855
} | class ____(visitors.Visitor):
"""Shortens long unions to object (or "?").
Poor man's version of FindCommonSuperClasses. Shorten types like
"str or unicode or int or float or list" to just "object" or "?".
Additionally, if the union already contains at least one "object", we also
potentially replace the enti... | CollapseLongUnions |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_optimize06.py | {
"start": 315,
"end": 1210
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("optimize06.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(
... | TestCompareXLSXFiles |
python | lazyprogrammer__machine_learning_examples | supervised_class2/util.py | {
"start": 1052,
"end": 1763
} | class ____:
def __init__(self, n_estimators, max_depth=None):
self.B = n_estimators
self.max_depth = max_depth
def fit(self, X, Y):
N = len(X)
self.models = []
for b in range(self.B):
idx = np.random.choice(N, size=N, replace=True)
Xb = X[idx]
Yb = Y[idx]
model = Decisi... | BaggedTreeRegressor |
python | Pylons__pyramid | tests/test_httpexceptions.py | {
"start": 2425,
"end": 14717
} | class ____(unittest.TestCase):
def _getTargetClass(self):
from pyramid.httpexceptions import HTTPException
return HTTPException
def _getTargetSubclass(
self,
code='200',
title='OK',
explanation='explanation',
empty_body=False,
):
cls = self._... | TestHTTPException |
python | kamyu104__LeetCode-Solutions | Python/closest-node-to-path-in-tree.py | {
"start": 225,
"end": 1159
} | class ____(object): # Time: O(n * alpha(n)), Space: O(n)
def __init__(self, n):
self.set = range(n)
self.rank = [0]*n
self.ancestor = range(n) # added
def find_set(self, x):
stk = []
while self.set[x] != x: # path compression
stk.append(x)
x = ... | UnionFind |
python | plotly__plotly.py | _plotly_utils/exceptions.py | {
"start": 1054,
"end": 1572
} | class ____(PlotlyGraphObjectError):
def __init__(self, obj, path, notes=()):
"""See PlotlyGraphObjectError.__init__ for param docs."""
format_dict = {"attribute": path[-1], "object_name": obj._name}
message = "'{attribute}' is not allowed in '{object_name}'".format(
**format_dict... | PlotlyDictKeyError |
python | PyCQA__pylint | doc/data/messages/i/invalid-str-returned/good.py | {
"start": 0,
"end": 105
} | class ____:
"""__str__ returns <type 'str'>"""
def __str__(self):
return "oranges"
| CustomStr |
python | django__django | django/views/generic/edit.py | {
"start": 6479,
"end": 6939
} | class ____(ModelFormMixin, ProcessFormView):
"""
Base view for updating an existing object.
This requires subclassing to provide a response mixin.
"""
def get(self, request, *args, **kwargs):
self.object = self.get_object()
return super().get(request, *args, **kwargs)
def post... | BaseUpdateView |
python | apache__airflow | task-sdk/tests/task_sdk/definitions/test_taskgroup.py | {
"start": 1265,
"end": 31761
} | class ____:
@pytest.mark.parametrize(
("group_id", "exc_type", "exc_value"),
[
pytest.param(
123,
TypeError,
"The key has to be a string and is <class 'int'>:123",
id="type",
),
pytest.param(
... | TestTaskGroup |
python | pennersr__django-allauth | allauth/mfa/webauthn/views.py | {
"start": 2444,
"end": 2892
} | class ____(ListView):
template_name = (
"mfa/webauthn/authenticator_list." + account_settings.TEMPLATE_EXTENSION
)
context_object_name = "authenticators"
def get_queryset(self):
return Authenticator.objects.filter(
user=self.request.user, type=Authenticator.Type.WEBAUTHN
... | ListWebAuthnView |
python | pytorch__pytorch | test/inductor/test_ordered_set.py | {
"start": 30356,
"end": 30751
} | class ____(TestBasicOps, TestCase):
def setUp(self):
super().setUp()
self.case = "empty OrderedSet"
self.values = []
self.OrderedSet = OrderedSet(self.values)
self.dup = OrderedSet(self.values)
self.length = 0
self.repr = "OrderedSet()"
# -------------------... | TestBasicOpsEmpty |
python | openai__openai-python | src/openai/types/responses/response_input_item.py | {
"start": 6521,
"end": 6931
} | class ____(BaseModel):
commands: List[str]
"""Ordered shell commands for the execution environment to run."""
max_output_length: Optional[int] = None
"""
Maximum number of UTF-8 characters to capture from combined stdout and stderr
output.
"""
timeout_ms: Optional[int] = None
"""Ma... | ShellCallAction |
python | neetcode-gh__leetcode | python/0110-balanced-binary-tree.py | {
"start": 192,
"end": 572
} | class ____:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def dfs(root):
if not root:
return [True, 0]
left, right = dfs(root.left), dfs(root.right)
balanced = left[0] and right[0] and abs(left[1] - right[1]) <= 1
return [balanced, 1... | Solution |
python | econchick__interrogate | src/interrogate/coverage.py | {
"start": 2938,
"end": 20374
} | class ____:
"""The doc coverage interrogator!
:param list(str) paths: list of paths to interrogate.
:param config.InterrogateConfig conf: interrogation configuration.
:param tuple(str) excluded: tuple of files and directories to exclude
in assessing coverage.
:param list[str] extensions: ad... | InterrogateCoverage |
python | sqlalchemy__sqlalchemy | test/orm/test_eager_relations.py | {
"start": 130218,
"end": 137637
} | class ____(fixtures.MappedTest, testing.AssertsCompiledSQL):
"""test #2188"""
__dialect__ = "default"
run_create_tables = None
@classmethod
def define_tables(cls, metadata):
Table("a", metadata, Column("id", Integer, primary_key=True))
Table(
"b",
metadata,... | SubqueryAliasingTest |
python | getsentry__sentry | src/sentry/web/api.py | {
"start": 2711,
"end": 4259
} | class ____(BaseView):
def get(self, request: Request) -> HttpResponse:
return HttpResponse(json.dumps(get_client_config(request)), content_type="application/json")
@all_silo_view
@cache_control(max_age=3600, public=True)
def robots_txt(request):
if settings.SENTRY_MODE == SentryMode.SAAS and not reque... | ClientConfigView |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_bar15.py | {
"start": 315,
"end": 1829
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_bar15.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_f... | TestCompareXLSXFiles |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-web/llama_index/readers/web/olostep_web/base.py | {
"start": 259,
"end": 5215
} | class ____(BasePydanticReader):
"""
A web reader that uses Olostep API to scrape web pages.
Args:
api_key (str): The Olostep API key.
mode (str): The mode to run the loader in. One of "scrape" or "search".
Default is "scrape".
params (Optional[dict]): Additional ... | OlostepWebReader |
python | nryoung__algorithms | tests/test_math.py | {
"start": 1517,
"end": 1777
} | class ____(unittest.TestCase):
def test_lcm(self):
# Find lcm of (16, 20) and (20, 16)
r, r2 = lcm(16, 20), lcm(20, 16)
self.assertEqual(r, 80)
# Checks that lcm function is commutative
self.assertEqual(r, r2)
| TestLCM |
python | pytorch__pytorch | test/test_datapipe.py | {
"start": 146967,
"end": 147278
} | class ____(IterDataPipe):
def __init__(self) -> None:
self.n = 10
self.source = list(range(self.n))
# This class's `__iter__` is not a generator function
def __iter__(self):
return iter(self.source)
def __len__(self):
return self.n
| _CustomNonGeneratorTestDataPipe |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/configurable.py | {
"start": 2753,
"end": 4718
} | class ____(ConfigurableDefinition):
"""An interface that makes the `configured` method not accept a name argument."""
def configured(
self,
config_or_config_fn: Any,
config_schema: CoercableToConfigSchema = None,
description: Optional[str] = None,
) -> Self:
"""Wraps... | AnonymousConfigurableDefinition |
python | scipy__scipy | scipy/spatial/tests/test_kdtree.py | {
"start": 18720,
"end": 19006
} | class ____(count_neighbors_consistency):
def setup_method(self):
n = 50
m = 2
np.random.seed(1234)
self.T1 = self.kdtree_type(np.random.randn(n, m), leafsize=2)
self.T2 = self.kdtree_type(np.random.randn(n, m), leafsize=2)
| _Test_count_neighbors |
python | tornadoweb__tornado | tornado/test/simple_httpclient_test.py | {
"start": 23981,
"end": 25064
} | class ____(AsyncHTTPTestCase):
def respond_100(self, request):
self.http1 = request.version.startswith("HTTP/1.")
if not self.http1:
request.connection.write_headers(
ResponseStartLine("", 200, "OK"), HTTPHeaders()
)
request.connection.finish()
... | HTTP100ContinueTestCase |
python | allegroai__clearml | clearml/backend_api/services/v2_20/queues.py | {
"start": 50049,
"end": 51836
} | class ____(Request):
"""
Gets queue information
:param queue: Queue ID
:type queue: str
:param max_task_entries: Max number of queue task entries to return
:type max_task_entries: int
"""
_service = "queues"
_action = "get_by_id"
_version = "2.20"
_schema = {
"defin... | GetByIdRequest |
python | has2k1__plotnine | plotnine/stats/stat_boxplot.py | {
"start": 139,
"end": 6034
} | class ____(stat):
"""
Compute boxplot statistics
{usage}
Parameters
----------
{common_parameters}
coef : float, default=1.5
Length of the whiskers as a multiple of the Interquartile
Range.
See Also
--------
plotnine.geom_boxplot: The default `geom` for this `s... | stat_boxplot |
python | django__django | tests/admin_registration/tests.py | {
"start": 500,
"end": 4347
} | class ____(SimpleTestCase):
def setUp(self):
self.site = admin.AdminSite()
def test_bare_registration(self):
self.site.register(Person)
self.assertIsInstance(self.site.get_model_admin(Person), admin.ModelAdmin)
self.site.unregister(Person)
self.assertEqual(self.site._reg... | TestRegistration |
python | spyder-ide__spyder | spyder/plugins/completion/providers/languageserver/conftabs/linting.py | {
"start": 600,
"end": 10891
} | class ____(SpyderPreferencesTab):
"""Linting configuration tab."""
TITLE = _('Linting')
def __init__(self, parent):
super().__init__(parent)
newcb = self.create_checkbox
linting_label = QLabel(
_(
"Spyder can highlight syntax errors and possible problem... | LintingConfigTab |
python | allegroai__clearml | clearml/backend_api/services/v2_9/projects.py | {
"start": 34834,
"end": 46924
} | class ____(Request):
"""
Get all the company's projects and all public projects
:param id: List of IDs to filter by
:type id: Sequence[str]
:param name: Get only projects whose name matches this pattern (python regular
expression syntax)
:type name: str
:param description: Get only ... | GetAllRequest |
python | django__django | tests/postgres_tests/test_functions.py | {
"start": 874,
"end": 1246
} | class ____(PostgreSQLTestCase):
def test_random_uuid(self):
m1 = UUIDTestModel.objects.create()
m2 = UUIDTestModel.objects.create()
UUIDTestModel.objects.update(uuid=RandomUUID())
m1.refresh_from_db()
m2.refresh_from_db()
self.assertIsInstance(m1.uuid, uuid.UUID)
... | TestRandomUUID |
python | numba__numba | numba/cpython/setobj.py | {
"start": 12301,
"end": 41796
} | class ____(object):
def __init__(self, context, builder, set_type, set_val):
self._context = context
self._builder = builder
self._ty = set_type
self._entrysize = get_entry_size(context, set_type)
self._set = context.make_helper(builder, set_type, set_val)
@property
... | SetInstance |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_unicode_polish_utf8.py | {
"start": 315,
"end": 1548
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("unicode_polish_utf8.xlsx")
self.set_text_file("unicode_polish_utf8.txt")
def test_create_file(self):
"""Test example file convertin... | TestCompareXLSXFiles |
python | sqlalchemy__sqlalchemy | examples/versioned_rows/versioned_update_old_row.py | {
"start": 4688,
"end": 8253
} | class ____(VersionedStartEnd, Base):
__tablename__ = "child"
id = Column(Integer, primary_key=True)
start = Column(DateTime, primary_key=True)
end = Column(DateTime, primary_key=True)
data = Column(String)
def new_version(self, session):
# expire parent's reference to us
sessio... | Child |
python | encode__django-rest-framework | tests/test_permissions.py | {
"start": 20065,
"end": 21911
} | class ____(TestCase):
def setUp(self):
BasicModel(text='foo').save()
User.objects.create_user('username', 'username@example.com', 'password')
credentials = basic_auth_header('username', 'password')
self.request = factory.get('/1', format='json', HTTP_AUTHORIZATION=credentials)
... | CustomPermissionsTests |
python | ray-project__ray | cpp/src/ray/test/cluster/test_cross_language_invocation.py | {
"start": 125,
"end": 307
} | class ____(object):
def __init__(self, value):
self.value = int(value)
def increase(self, delta):
self.value += int(delta)
return str(self.value)
| Counter |
python | huggingface__transformers | tests/models/wav2vec2_bert/test_modeling_wav2vec2_bert.py | {
"start": 15613,
"end": 24523
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
# Ignore copy
all_model_classes = (
(
Wav2Vec2BertForCTC,
Wav2Vec2BertModel,
Wav2Vec2BertForSequenceClassification,
Wav2Vec2BertForAudioFrameClassification,
Wav2Vec2BertForXV... | Wav2Vec2BertModelTest |
python | pytorch__pytorch | tools/experimental/torchfuzz/operators/arg.py | {
"start": 125,
"end": 1035
} | class ____(Operator):
"""Operator for function arguments/parameters."""
def __init__(self):
super().__init__("arg")
@property
def torch_op_name(self) -> str | None:
"""Arg is not a torch operation, it represents function arguments."""
return None
def can_produce(self, outp... | ArgOperator |
python | crytic__slither | slither/core/declarations/structure_contract.py | {
"start": 117,
"end": 372
} | class ____(Structure, ContractLevel):
def is_declared_by(self, contract):
"""
Check if the element is declared by the contract
:param contract:
:return:
"""
return self.contract == contract
| StructureContract |
python | dask__dask | dask/dataframe/dask_expr/_reductions.py | {
"start": 36695,
"end": 37550
} | class ____(Reduction):
_parameters = ["frame", "skipna", "numeric_only", "split_every", "axis"]
_defaults = {"skipna": True, "numeric_only": False, "split_every": False, "axis": 0}
@functools.cached_property
def _meta(self):
return make_meta(
meta_nonempty(self.frame._meta).mean(
... | Mean |
python | scikit-image__scikit-image | src/skimage/_shared/utils.py | {
"start": 18239,
"end": 21393
} | class ____:
"""Decorator for automatically making channels axis last for all arrays.
This decorator reorders axes for compatibility with functions that only
support channels along the last axis. After the function call is complete
the channels axis is restored back to its original position.
Parame... | channel_as_last_axis |
python | pydata__xarray | xarray/core/groupby.py | {
"start": 62540,
"end": 62675
} | class ____(
DataArrayGroupByBase,
DataArrayGroupByAggregations,
ImplementsArrayReduce,
):
__slots__ = ()
| DataArrayGroupBy |
python | pytorch__pytorch | test/dynamo/test_higher_order_ops.py | {
"start": 164128,
"end": 165993
} | class ____(torch.nn.Module):
def forward(self, L_x_: "f32[1, 1]"):
l_x_ = L_x_
l__self___l1: "f32[1, 1]" = self.L__self___l1(l_x_); l_x_ = None
l__self___buffer: "f32[1]" = self.L__self___buffer
add: "f32[1, 1]" = l__self___l1 + l__self___buffer; l__self___l1 = l__self___buffer = ... | GraphModule |
python | lepture__authlib | authlib/oauth2/rfc6749/errors.py | {
"start": 1828,
"end": 2238
} | class ____(OAuth2Error):
"""The request is missing a required parameter, includes an
unsupported parameter value (other than grant type),
repeats a parameter, includes multiple credentials,
utilizes more than one mechanism for authenticating the
client, or is otherwise malformed.
https://tools.... | InvalidRequestError |
python | pytorch__pytorch | test/cpp_extensions/libtorch_agnostic_2_9_extension/setup.py | {
"start": 303,
"end": 2343
} | class ____(distutils.command.clean.clean):
def run(self):
# Run default behavior first
distutils.command.clean.clean.run(self)
# Remove extension
for path in (ROOT_DIR / "libtorch_agnostic_2_9").glob("**/*.so"):
path.unlink()
# Remove build and dist and egg-info ... | clean |
python | sympy__sympy | sympy/simplify/hyperexpand.py | {
"start": 37001,
"end": 37343
} | class ____(Operator):
""" Increment an upper index. """
def __init__(self, ai):
ai = sympify(ai)
if ai == 0:
raise ValueError('Cannot increment zero upper index.')
self._poly = Poly(_x/ai + 1, _x)
def __str__(self):
return '<Increment upper %s.>' % (1/self._poly... | ShiftA |
python | openai__openai-python | src/openai/_exceptions.py | {
"start": 3620,
"end": 3750
} | class ____(APIStatusError):
status_code: Literal[409] = 409 # pyright: ignore[reportIncompatibleVariableOverride]
| ConflictError |
python | getsentry__sentry | tests/sentry/receivers/test_transactions.py | {
"start": 674,
"end": 4511
} | class ____(TestCase):
@cached_property
def min_ago(self) -> str:
return before_now(minutes=1).isoformat()
def test_transaction_processed(self) -> None:
assert not self.project.flags.has_transactions
event = self.store_event(
data={
"type": "transaction",
... | RecordFirstTransactionTest |
python | boto__boto3 | boto3/utils.py | {
"start": 2377,
"end": 3141
} | class ____:
"""A lazily loaded waiter model
This does not load the service waiter model until an attempt is made
to retrieve the waiter model for a specific waiter. This is helpful
in docstring generation where we do not need to actually need to grab
the waiter-2.json until it is accessed through a... | LazyLoadedWaiterModel |
python | ethereum__web3.py | web3/contract/base_contract.py | {
"start": 29454,
"end": 32968
} | class ____(Generic[TContractFn]):
"""Class containing contract function objects"""
_functions: Sequence[ABIFunction] = None
def __init__(
self,
abi: ABI,
w3: Union["Web3", "AsyncWeb3[Any]"],
contract_function_class: type[TContractFn],
address: ChecksumAddress | None... | BaseContractFunctions |
python | pandas-dev__pandas | pandas/core/tools/datetimes.py | {
"start": 2665,
"end": 41479
} | class ____(YearMonthDayDict, total=False):
hour: DatetimeDictArg
hours: DatetimeDictArg
minute: DatetimeDictArg
minutes: DatetimeDictArg
second: DatetimeDictArg
seconds: DatetimeDictArg
ms: DatetimeDictArg
us: DatetimeDictArg
ns: DatetimeDictArg
DictConvertible = Union[Fulldatetime... | FulldatetimeDict |
python | PrefectHQ__prefect | tests/server/schemas/test_actions.py | {
"start": 1000,
"end": 1316
} | class ____:
def test_model_dump_json_mode_succeeds_with_parameters(
self, test_params, expected_dict
):
frc = FlowRunCreate(flow_id=uuid4(), flow_version="0.1", parameters=test_params)
res = frc.model_dump(mode="json")
assert res["parameters"] == expected_dict
| TestFlowRunCreate |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 356349,
"end": 356676
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("IpAllowListEntry", graphql_name="node")
| IpAllowListEntryEdge |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/compiler.py | {
"start": 29771,
"end": 30356
} | class ____(
roles.BinaryElementRole[Any], elements.CompilerColumnElement
):
"""lightweight label object which acts as an expression.Label."""
__visit_name__ = "label"
__slots__ = "element", "name", "_alt_names"
def __init__(self, col, name, alt_names=()):
self.element = col
self.na... | _CompileLabel |
python | pydata__xarray | xarray/namedarray/_typing.py | {
"start": 6911,
"end": 7165
} | class ____(
_array[_ShapeType_co, _DType_co], Protocol[_ShapeType_co, _DType_co]
):
"""
Minimal sparse duck array.
Corresponds to np.ndarray.
"""
def todense(self) -> np.ndarray[Any, _DType_co]: ...
@runtime_checkable
| _sparsearray |
python | bokeh__bokeh | tests/unit/bokeh/application/handlers/test_server_lifecycle.py | {
"start": 1832,
"end": 7814
} | class ____:
# Public methods ----------------------------------------------------------
async def test_empty_lifecycle(self) -> None:
doc = Document()
result: dict[str, Handler] = {}
def load(filename: str):
handler = bahs.ServerLifecycleHandler(filename=filename)
... | Test_ServerLifecycleHandler |
python | ray-project__ray | python/ray/data/tests/test_namespace_expressions.py | {
"start": 20181,
"end": 21949
} | class ____:
"""Tests for chaining and combining namespace expressions."""
def test_list_with_arithmetic(self, dataset_format):
"""Test list operations combined with arithmetic."""
data = [{"items": [1, 2, 3]}]
ds = _create_dataset(data, dataset_format)
result = ds.with_column("... | TestNamespaceIntegration |
python | ray-project__ray | python/ray/train/backend.py | {
"start": 724,
"end": 1761
} | class ____(metaclass=Singleton):
"""Singleton for distributed communication backend.
Attributes:
share_cuda_visible_devices: If True, each worker
process will have CUDA_VISIBLE_DEVICES set as the visible device
IDs of all workers on the same node for this training instance.
... | Backend |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/auth/managers/models/resource_details.py | {
"start": 1342,
"end": 1464
} | class ____:
"""Represents the details of a backfill."""
id: NonNegativeInt | None = None
@dataclass
| BackfillDetails |
python | jazzband__django-model-utils | tests/test_fields/test_field_tracker.py | {
"start": 35893,
"end": 36195
} | class ____(ModelTrackerTests):
tracked_class = InheritedModelTracked
def test_child_fields_not_tracked(self) -> None:
self.name2 = 'test'
self.assertEqual(self.tracker.previous('name2'), None)
self.assertTrue(self.tracker.has_changed('name2'))
| InheritedModelTrackerTests |
python | marshmallow-code__apispec | tests/schemas.py | {
"start": 1655,
"end": 1785
} | class ____(Schema):
id = fields.Int()
name = fields.Str(required=True)
breed = fields.Str(dump_only=True)
| CategorySchema |
python | pypa__installer | tests/test_core.py | {
"start": 3286,
"end": 32859
} | class ____:
def test_calls_destination_correctly(self, mock_destination):
# Create a fake wheel
source = FakeWheelSource(
distribution="fancy",
version="1.0.0",
regular_files={
"fancy/__init__.py": b"""\
def main():
... | TestInstall |
python | charliermarsh__ruff | python/ruff-ecosystem/ruff_ecosystem/projects.py | {
"start": 10459,
"end": 14357
} | class ____(Repository, Serializable):
"""
A cloned GitHub repository, which includes the hash of the current commit.
"""
commit_hash: str
path: Path
def url_for(
self: Self,
path: str,
line_number: int | None = None,
end_line_number: int | None = None,
) -> ... | ClonedRepository |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/matchClass1.py | {
"start": 14551,
"end": 14770
} | class ____:
x: int
def func22(subj: Proto1 | int):
match subj:
case Proto1():
reveal_type(subj, expected_text="Proto1")
case _:
reveal_type(subj, expected_text="int")
| Impl1 |
python | dask__dask | dask/dataframe/dask_expr/_groupby.py | {
"start": 31140,
"end": 31573
} | class ____(GroupByApply):
_defaults = {
"observed": None,
"dropna": None,
"_slice": None,
"func": None,
"group_keys": True,
}
@functools.cached_property
def grp_func(self):
return functools.partial(groupby_slice_shift, shuffled=False)
def _shuffle_gr... | GroupByShift |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 54701,
"end": 55030
} | class ____(EnumDDLEventTest):
@testing.fixture
def produce_event_target(self, produce_subject, connection):
return produce_subject
@testing.fixture
def produce_subject(self):
return ENUM(
"x",
"y",
"z",
name="status",
)
| NativeEnumDDLEventTest |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/class_interval.py | {
"start": 6599,
"end": 6696
} | class ____(A16):
def m0(self):
return self.m1()
def m2(self):
return 0
| B16 |
python | catalyst-team__catalyst | catalyst/callbacks/batch_transform.py | {
"start": 486,
"end": 9358
} | class ____(Callback):
"""
Preprocess your batch with specified function.
Args:
transform: Function to apply. If string will get function from registry.
scope: ``"on_batch_end"`` (post-processing model output) or
``"on_batch_start"`` (pre-processing model input).
input_ke... | BatchTransformCallback |
python | paramiko__paramiko | tests/test_gssapi.py | {
"start": 1288,
"end": 8574
} | class ____(KerberosTestCase):
def setUp(self):
super().setUp()
# TODO: these vars should all come from os.environ or whatever the
# approved pytest method is for runtime-configuring test data.
self.krb5_mech = "1.2.840.113554.1.2.2"
self.targ_name = self.realm.hostname
... | GSSAPITest |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/lambda_function.py | {
"start": 6585,
"end": 10696
} | class ____(AwsBaseOperator[LambdaHook]):
"""
Invokes an AWS Lambda function.
You can invoke a function synchronously (and wait for the response), or asynchronously.
To invoke a function asynchronously, set `invocation_type` to `Event`. For more details,
review the boto3 Lambda invoke docs.
.. ... | LambdaInvokeFunctionOperator |
python | lazyprogrammer__machine_learning_examples | rl2/cartpole/pg_tf.py | {
"start": 1261,
"end": 3465
} | class ____:
def __init__(self, D, K, hidden_layer_sizes):
# create the graph
# K = number of actions
self.layers = []
M1 = D
for M2 in hidden_layer_sizes:
layer = HiddenLayer(M1, M2)
self.layers.append(layer)
M1 = M2
# final layer
# layer = HiddenLayer(M1, K, lambda x: x... | PolicyModel |
python | django__django | tests/model_fields/models.py | {
"start": 11694,
"end": 11996
} | class ____(json.JSONDecoder):
def __init__(self, object_hook=None, *args, **kwargs):
return super().__init__(object_hook=self.as_uuid, *args, **kwargs)
def as_uuid(self, dct):
if "uuid" in dct:
dct["uuid"] = uuid.UUID(dct["uuid"])
return dct
| CustomJSONDecoder |
python | facebookresearch__faiss | tests/test_index_composite.py | {
"start": 21639,
"end": 25462
} | class ____(unittest.TestCase):
def test_sidebyside(self):
""" provide double-sized vectors to the index, where each vector
is the concatenation of twice the same vector """
ds = SyntheticDataset(32, 1000, 500, 50)
index = faiss.index_factory(ds.d, "IVF32,SQ8")
index.train(d... | TestIndependentQuantizer |
python | matplotlib__matplotlib | lib/matplotlib/layout_engine.py | {
"start": 3749,
"end": 4545
} | class ____(LayoutEngine):
"""
This layout engine does not adjust the figure layout at all.
The purpose of this `.LayoutEngine` is to act as a placeholder when the user removes
a layout engine to ensure an incompatible `.LayoutEngine` cannot be set later.
Parameters
----------
adjust_compat... | PlaceHolderLayoutEngine |
python | huggingface__transformers | src/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py | {
"start": 36108,
"end": 45690
} | class ____(PreTrainedModel):
config: Wav2Vec2ConformerConfig
base_model_prefix = "wav2vec2_conformer"
main_input_name = "input_values"
input_modalities = "audio"
supports_gradient_checkpointing = True
@torch.no_grad()
def _init_weights(self, module):
"""Initialize the weights"""
... | Wav2Vec2ConformerPreTrainedModel |
python | plotly__plotly.py | plotly/graph_objs/bar/hoverlabel/_font.py | {
"start": 233,
"end": 17123
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "bar.hoverlabel"
_path_str = "bar.hoverlabel.font"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc",
"size",
... | Font |
python | huggingface__transformers | src/transformers/models/tapas/tokenization_tapas.py | {
"start": 101984,
"end": 120139
} | class ____:
original_text: str # The original raw question string.
text: str # The question string after normalization.
numeric_spans: Optional[list[NumericValueSpan]] = None
# Below: all functions from number_utils.py as well as 2 functions (namely get_all_spans and normalize_for_match)
# from text_uti... | Question |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methods1.py | {
"start": 1181,
"end": 2037
} | class ____:
a: ClassVar[Callable[[Any], None]] = lambda self: None
b1 = lambda self: None
b2: ClassVar = lambda self: None
c1 = func1
c2: ClassVar = func1
d1: CallableA = CallableA()
d2: ClassVar[CallableA] = CallableA()
e1 = deco1(func1)
e2: ClassVar = deco1(func1)
@deco1
... | ClassA |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.