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 | pytorch__pytorch | torch/distributions/constraints.py | {
"start": 11552,
"end": 12043
} | class ____(Constraint):
"""
Constrain to an integer interval `(-inf, upper_bound]`.
"""
is_discrete = True
def __init__(self, upper_bound):
self.upper_bound = upper_bound
super().__init__()
def check(self, value):
return (value % 1 == 0) & (value <= self.upper_bound)
... | _IntegerLessThan |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1567405,
"end": 1568890
} | class ____(VegaLiteSchema):
"""
ValueDefWithConditionMarkPropFieldOrDatumDefstringnull schema wrapper.
Parameters
----------
condition : dict, :class:`ConditionalMarkPropFieldOrDatumDef`, :class:`ConditionalValueDefstringnullExprRef`, :class:`ConditionalParameterMarkPropFieldOrDatumDef`, :class:`Co... | ValueDefWithConditionMarkPropFieldOrDatumDefstringnull |
python | getsentry__sentry | src/sentry/shared_integrations/exceptions/__init__.py | {
"start": 4273,
"end": 4327
} | class ____(ApiError):
code = 429
| ApiRateLimitedError |
python | walkccc__LeetCode | solutions/187. Repeated DNA Sequences/187.py | {
"start": 0,
"end": 250
} | class ____:
def findRepeatedDnaSequences(self, s: str) -> list[str]:
ans = set()
seen = set()
for i in range(len(s) - 9):
seq = s[i:i + 10]
if seq in seen:
ans.add(seq)
seen.add(seq)
return list(ans)
| Solution |
python | getsentry__sentry | tests/sentry/grouping/test_enhancer.py | {
"start": 17709,
"end": 29073
} | class ____(TestCase):
def setUp(self) -> None:
self.rules_text = """
function:sit +app # should end up in classifiers
function:roll_over category=trick # should end up in classifiers
function:shake +group ... | EnhancementsTest |
python | mlflow__mlflow | dev/check_function_signatures.py | {
"start": 8369,
"end": 12530
} | class ____(ast.NodeVisitor):
def __init__(self):
self.functions: dict[str, ast.FunctionDef | ast.AsyncFunctionDef] = {}
self.stack: list[ast.ClassDef] = []
def visit_ClassDef(self, node: ast.ClassDef) -> None:
self.stack.append(node)
self.generic_visit(node)
self.stack.p... | FunctionSignatureExtractor |
python | doocs__leetcode | solution/1100-1199/1128.Number of Equivalent Domino Pairs/Solution.py | {
"start": 0,
"end": 276
} | class ____:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
cnt = Counter()
ans = 0
for a, b in dominoes:
x = a * 10 + b if a < b else b * 10 + a
ans += cnt[x]
cnt[x] += 1
return ans
| Solution |
python | sqlalchemy__sqlalchemy | examples/asyncio/async_orm.py | {
"start": 679,
"end": 731
} | class ____(AsyncAttrs, DeclarativeBase):
pass
| Base |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 23955,
"end": 24922
} | class ____(sgqlc.types.Enum):
"""The possible funding platforms for repository funding links.
Enumeration Choices:
* `COMMUNITY_BRIDGE`: Community Bridge funding platform.
* `CUSTOM`: Custom funding platform.
* `GITHUB`: GitHub funding platform.
* `ISSUEHUNT`: IssueHunt funding platform.
*... | FundingPlatform |
python | ansible__ansible | lib/ansible/modules/dnf5.py | {
"start": 16805,
"end": 32677
} | class ____(YumDnf):
def __init__(self, module):
super(Dnf5Module, self).__init__(module)
self.auto_install_module_deps = self.module.params["auto_install_module_deps"]
self._ensure_dnf()
self.pkg_mgr_name = "dnf5"
def fail_on_non_existing_plugins(self, base):
# https:/... | Dnf5Module |
python | scipy__scipy | scipy/interpolate/_cubic.py | {
"start": 13908,
"end": 22329
} | class ____(CubicHermiteSpline):
r"""Akima "visually pleasing" interpolator (C1 smooth).
Fit piecewise cubic polynomials, given vectors x and y. The interpolation
method by Akima uses a continuously differentiable sub-spline built from
piecewise cubic polynomials. The resultant curve passes through the ... | Akima1DInterpolator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1310536,
"end": 1313253
} | class ____(sgqlc.types.Type, Node):
"""A column inside a project."""
__schema__ = github_schema
__field_names__ = ("cards", "created_at", "database_id", "name", "project", "purpose", "resource_path", "updated_at", "url")
cards = sgqlc.types.Field(
sgqlc.types.non_null(ProjectCardConnection),
... | ProjectColumn |
python | Pylons__pyramid | tests/test_authentication.py | {
"start": 54747,
"end": 58520
} | class ____(unittest.TestCase):
def _getTargetClass(self):
from pyramid.authentication import SessionAuthenticationPolicy
return SessionAuthenticationPolicy
def _makeOne(self, callback=None, prefix=''):
return self._getTargetClass()(prefix=prefix, callback=callback)
def test_class_... | TestSessionAuthenticationPolicy |
python | astropy__astropy | astropy/table/tests/test_table.py | {
"start": 34704,
"end": 34953
} | class ____(SetupData):
def test_column_view(self, table_types):
self._setup(table_types)
t = self.t
a = t.columns["a"]
a[2] = 10
assert t["a"][2] == 10
@pytest.mark.usefixtures("table_types")
| TestTableColumn |
python | PrefectHQ__prefect | src/integrations/prefect-azure/prefect_azure/credentials.py | {
"start": 2597,
"end": 10154
} | class ____(Block):
"""
Stores credentials for authenticating with Azure Blob Storage.
Args:
account_url: The URL for your Azure storage account. If provided, the account
URL will be used to authenticate with the discovered default Azure
credentials.
connection_string... | AzureBlobStorageCredentials |
python | apache__airflow | task-sdk/tests/task_sdk/execution_time/test_task_runner.py | {
"start": 90342,
"end": 98855
} | class ____:
FROM = "from@airflow"
@pytest.mark.parametrize(
("emails", "sent"),
[
pytest.param(
"test@example.com",
True,
id="one-email",
),
pytest.param(
["test@example.com"],
Tr... | TestEmailNotifications |
python | getsentry__sentry | tests/sentry/web/frontend/test_react_page.py | {
"start": 594,
"end": 20718
} | class ____(TestCase):
def test_redirects_unauthenticated_request(self) -> None:
owner = self.create_user("bar@example.com")
org = self.create_organization(owner=owner)
path = reverse("sentry-organization-home", args=[org.slug])
resp = self.client.get(path)
self.assertRedire... | ReactPageViewTest |
python | mlflow__mlflow | mlflow/utils/databricks_utils.py | {
"start": 8723,
"end": 22881
} | class ____:
spark: "SparkConnectSession"
image_version: str
runtime_version: str
platform_machine: str
mlflow_version: str
_dbconnect_udf_sandbox_info_cache: DBConnectUDFSandboxInfo | None = None
def get_dbconnect_udf_sandbox_info(spark):
"""
Get Databricks UDF sandbox info which include... | DBConnectUDFSandboxInfo |
python | huggingface__transformers | src/transformers/models/swinv2/modeling_swinv2.py | {
"start": 4026,
"end": 5690
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `bool_masked_pos` is provided):
Masked image modeling (MLM) loss.
reconstruction (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
Reconstructed pixel values.
resh... | Swinv2MaskedImageModelingOutput |
python | getsentry__sentry | src/sentry/flags/models.py | {
"start": 793,
"end": 1244
} | class ____(Enum):
EMAIL = 0
ID = 1
NAME = 2
@classmethod
def to_string(cls, integer):
if integer == 0:
return "email"
if integer == 1:
return "id"
if integer == 2:
return "name"
raise ValueError
CREATED_BY_TYPE_MAP = {
"email... | CreatedByTypeEnum |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_hyperlink17.py | {
"start": 315,
"end": 1063
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("hyperlink17.xlsx")
def test_create_file(self):
"""
Test the creation of a simple XlsxWriter file with hyperlinks.This
examp... | TestCompareXLSXFiles |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/clsregistry.py | {
"start": 10998,
"end": 12221
} | class ____:
__slots__ = ("cls",)
cls: Type[Any]
def __init__(self, cls: Type[Any]):
self.cls = cls
def __getattr__(self, key: str) -> Any:
mp = class_mapper(self.cls, configure=False)
if mp:
if key not in mp.all_orm_descriptors:
raise AttributeError... | _GetColumns |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/overloadOverlap1.py | {
"start": 4488,
"end": 4691
} | class ____(Generic[_T1]):
@overload
def __call__(self, f: _T1) -> _T1: ...
@overload
def __call__(self, f: _T1 | None) -> _T1: ...
def __call__(self, f: _T1 | None) -> _T1: ...
| ClassA |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/engine/base.py | {
"start": 92294,
"end": 96563
} | class ____(TransactionalContext):
"""Represent a database transaction in progress.
The :class:`.Transaction` object is procured by
calling the :meth:`_engine.Connection.begin` method of
:class:`_engine.Connection`::
from sqlalchemy import create_engine
engine = create_engine("postgres... | Transaction |
python | getsentry__sentry | src/sentry/api/endpoints/organization_events_spans_performance.py | {
"start": 1678,
"end": 3281
} | class ____:
suspect_op_group_columns: list[str]
suspect_op_group_sort: list[str]
suspect_example_functions: list[str]
SPAN_PERFORMANCE_COLUMNS: dict[str, SpanPerformanceColumn] = {
"count": SpanPerformanceColumn(
["count()", "sumArray(spans_exclusive_time)"],
["count()", "sumArray(span... | SpanPerformanceColumn |
python | google__jax | jax/experimental/mosaic/gpu/launch_context.py | {
"start": 2568,
"end": 2673
} | class ____(enum.Enum):
UP = enum.auto()
DOWN = enum.auto()
@dataclasses.dataclass(frozen=True)
| Rounding |
python | pydantic__pydantic | pydantic/v1/types.py | {
"start": 28725,
"end": 32326
} | class ____(str):
"""
Based on: https://en.wikipedia.org/wiki/Payment_card_number
"""
strip_whitespace: ClassVar[bool] = True
min_length: ClassVar[int] = 12
max_length: ClassVar[int] = 19
bin: str
last4: str
brand: PaymentCardBrand
def __init__(self, card_number: str):
s... | PaymentCardNumber |
python | google__pytype | pytype/overlays/dataclass_overlay.py | {
"start": 6443,
"end": 6728
} | class ____(abstract.SimpleValue):
"""Return value of a field() call."""
def __init__(self, ctx, init, default, kw_only):
super().__init__("field", ctx)
self.init = init
self.default = default
self.kw_only = kw_only
self.cls = ctx.convert.unsolvable
| FieldInstance |
python | explosion__spaCy | spacy/schemas.py | {
"start": 2445,
"end": 6529
} | class ____:
extra = "forbid"
arbitrary_types_allowed = True
def get_arg_model(
func: Callable,
*,
exclude: Iterable[str] = tuple(),
name: str = "ArgModel",
strict: bool = True,
) -> ModelMetaclass:
"""Generate a pydantic model for function arguments.
func (Callable): The function ... | ArgSchemaConfigExtra |
python | davidhalter__jedi | jedi/inference/gradual/stub_value.py | {
"start": 2624,
"end": 3343
} | class ____(ParserTreeFilter):
name_class = StubName
def _is_name_reachable(self, name):
if not super()._is_name_reachable(name):
return False
# Imports in stub files are only public if they have an "as"
# export.
definition = name.get_definition()
if definit... | StubFilter |
python | davidhalter__jedi | jedi/inference/names.py | {
"start": 3275,
"end": 8432
} | class ____(AbstractNameDefinition):
def __init__(self, parent_context, tree_name):
self.parent_context = parent_context
self.tree_name = tree_name
def get_qualified_names(self, include_module_names=False):
import_node = search_ancestor(self.tree_name, 'import_name', 'import_from')
... | AbstractTreeName |
python | numpy__numpy | tools/swig/test/testTensor.py | {
"start": 11943,
"end": 12247
} | class ____(TensorTestCase):
def __init__(self, methodName="runTest"):
TensorTestCase.__init__(self, methodName)
self.typeStr = "uchar"
self.typeCode = "B"
self.result = int(self.result)
######################################################################
| ucharTestCase |
python | pytorch__pytorch | tools/test/heuristics/test_heuristics.py | {
"start": 4716,
"end": 6486
} | class ____(TestTD):
def test_get_keywords(self) -> None:
self.assertEqual(get_keywords("test/test_car.py"), ["car"])
self.assertEqual(get_keywords("test/nn/test_amp.py"), ["nn", "amp"])
self.assertEqual(get_keywords("torch/nn/test_amp.py"), ["nn", "amp"])
self.assertEqual(
... | TestFilePath |
python | jazzband__django-oauth-toolkit | tests/app/idp/idp/apps.py | {
"start": 1006,
"end": 1152
} | class ____(AppConfig):
name = "idp"
default = True
def ready(self):
check_request_enabled.connect(cors_allow_origin)
| IDPAppConfig |
python | spack__spack | var/spack/test_repos/spack_repo/edges_test/packages/blas_only_client/package.py | {
"start": 217,
"end": 603
} | class ____(Package):
"""This package depends on the 'blas' virtual only, but should be able to use also provider
that provide e.g. 'blas' together with 'lapack'.
"""
homepage = "http://www.openblas.net"
url = "http://github.com/xianyi/OpenBLAS/archive/v0.2.15.tar.gz"
version("0.2.16", md5="b11... | BlasOnlyClient |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/dagster/subschema/daemon.py | {
"start": 1347,
"end": 1809
} | class ____(BaseModel):
enabled: bool
type: RunCoordinatorType
config: RunCoordinatorConfig
model_config = ConfigDict(
extra="forbid",
json_schema_extra={
"allOf": create_json_schema_conditionals(
{
RunCoordinatorType.QUEUED: "queuedRunCoor... | RunCoordinator |
python | doocs__leetcode | solution/2400-2499/2492.Minimum Score of a Path Between Two Cities/Solution.py | {
"start": 0,
"end": 489
} | class ____:
def minScore(self, n: int, roads: List[List[int]]) -> int:
def dfs(i):
nonlocal ans
for j, d in g[i]:
ans = min(ans, d)
if not vis[j]:
vis[j] = True
dfs(j)
g = defaultdict(list)
for a... | Solution |
python | PyCQA__pylint | tests/functional/i/init_not_called.py | {
"start": 1178,
"end": 1254
} | class ____:
def __init__(self, num: int):
self.number = num
| Parent |
python | huggingface__transformers | tests/models/blip/test_modeling_blip.py | {
"start": 25431,
"end": 28504
} | class ____(ModelTesterMixin, unittest.TestCase):
all_model_classes = (BlipForQuestionAnswering,) if is_torch_available() else ()
# Doesn't run generation tests due to custom generation logic -- won't fix
all_generative_model_classes = ()
test_resize_embeddings = True
test_attention_outputs = False
... | BlipVQAModelTest |
python | sympy__sympy | sympy/stats/crv_types.py | {
"start": 120730,
"end": 122371
} | class ____(SingleContinuousDistribution):
_argnames = ('R',)
@property
def set(self):
return Interval(-self.R, self.R)
@staticmethod
def check(R):
_value_check(R > 0, "Radius R must be positive.")
def pdf(self, x):
R = self.R
return 2/(pi*R**2)*sqrt(R**2 - x**2... | WignerSemicircleDistribution |
python | airbytehq__airbyte | airbyte-ci/connectors/live-tests/src/live_tests/regression_tests/test_read.py | {
"start": 669,
"end": 25484
} | class ____:
"""This class contains tests that check if the data integrity is preserved between the control and target versions.
The tests have some overlap but they are meant to be gradually stricter in terms of integrity checks.
1. test_record_count: On each stream, check if the target version produces at... | TestDataIntegrity |
python | getsentry__sentry | tests/sentry/utils/email/test_backend.py | {
"start": 102,
"end": 735
} | class ____(TestCase):
def test_get_mail_backend(self) -> None:
with self.options({"mail.backend": "smtp"}):
assert get_mail_backend() == "django.core.mail.backends.smtp.EmailBackend"
with self.options({"mail.backend": "dummy"}):
assert get_mail_backend() == "django.core.mail... | GetMailBackendTest |
python | astropy__astropy | astropy/io/fits/tests/test_fitsdiff.py | {
"start": 550,
"end": 12094
} | class ____(FitsTestCase):
def test_help(self):
with pytest.raises(SystemExit) as e:
fitsdiff.main(["-h"])
assert e.value.code == 0
def test_version(self, capsys):
with pytest.raises(SystemExit) as e:
fitsdiff.main(["--version"])
out = capsys.readouter... | TestFITSDiff_script |
python | tensorflow__tensorflow | tensorflow/python/framework/experimental/unified_api_test.py | {
"start": 2205,
"end": 12876
} | class ____(test.TestCase, parameterized.TestCase):
@parameterized.named_parameters([
("Graph", False),
("Mlir", True),
])
def testAdd(self, use_mlir):
if use_mlir:
SetTracingImplementation("mlir")
def model(a, b):
return unified_math_ops.add(a, b)
with context_lib.set_defaul... | UnifiedApiTest |
python | kamyu104__LeetCode-Solutions | Python/total-cost-to-hire-k-workers.py | {
"start": 73,
"end": 980
} | class ____(object):
def totalCost(self, costs, k, candidates):
"""
:type costs: List[int]
:type k: int
:type candidates: int
:rtype: int
"""
left, right = candidates, max(len(costs)-candidates, candidates)-1
min_heap1, min_heap2 = costs[:left], costs[r... | Solution |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/datacatalog.py | {
"start": 1921,
"end": 2470
} | class ____(BaseGoogleLink):
"""Helper class for constructing Data Catalog Entry Group Link."""
name = "Data Catalog Entry Group"
key = "data_catalog_entry_group"
format_str = ENTRY_GROUP_LINK
@deprecated(
planned_removal_date="January 30, 2026",
use_instead="airflow.providers.google.cloud.lin... | DataCatalogEntryGroupLink |
python | py-pdf__pypdf | pypdf/_page.py | {
"start": 4147,
"end": 10322
} | class ____:
"""
Represent a 2D transformation.
The transformation between two coordinate systems is represented by a 3-by-3
transformation matrix with the following form::
a b 0
c d 0
e f 1
Because a transformation matrix has only six elements that can be changed,
it i... | Transformation |
python | django__django | django/db/models/functions/window.py | {
"start": 2504,
"end": 2622
} | class ____(Func):
function = "PERCENT_RANK"
output_field = FloatField()
window_compatible = True
| PercentRank |
python | pymupdf__PyMuPDF | src/__init__.py | {
"start": 305597,
"end": 314899
} | class ____:
def __del__(self):
if type(self) is not Font:
return None
def __init__(
self,
fontname=None,
fontfile=None,
fontbuffer=None,
script=0,
language=None,
ordering=-1,
is_bold=0,
... | Font |
python | Netflix__metaflow | metaflow/packaging_sys/__init__.py | {
"start": 19755,
"end": 24901
} | class ____(MetaflowCodeContent, version_id=0):
@classmethod
def get_info_impl(
cls, mfcontent_info: Optional[Dict[str, Any]]
) -> Optional[Dict[str, Any]]:
path_to_file = os.path.join(get_metaflow_root(), "INFO")
if os.path.isfile(path_to_file):
with open(path_to_file, "r... | MetaflowCodeContentV0 |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 94389,
"end": 94753
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("column_id", "client_mutation_id")
column_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="columnId")
client_mutation_id = sgqlc.types.Field(String, graphql_nam... | DeleteProjectColumnInput |
python | networkx__networkx | networkx/algorithms/centrality/tests/test_eigenvector_centrality.py | {
"start": 4031,
"end": 5254
} | class ____:
def test_multigraph(self):
with pytest.raises(nx.NetworkXException):
nx.eigenvector_centrality(nx.MultiGraph())
def test_multigraph_numpy(self):
with pytest.raises(nx.NetworkXException):
nx.eigenvector_centrality_numpy(nx.MultiGraph())
def test_null(self... | TestEigenvectorCentralityExceptions |
python | joke2k__faker | faker/providers/address/bn_BD/__init__.py | {
"start": 115,
"end": 12390
} | class ____(AddressProvider):
area_names = (
"আলি",
"আলম",
"অভয়",
"আনোয়ার",
"ব্রাহ্মণ",
"বটিয়া",
"বাঘার",
"বেগম",
"বিজয়",
"বন্দর",
"বালিয়া",
"বাজিত",
"বাকের",
"বোরহান",
"বকশী",
"বদর",
... | Provider |
python | pandas-dev__pandas | pandas/tests/frame/test_query_eval.py | {
"start": 2645,
"end": 7743
} | class ____:
# smaller hits python, larger hits numexpr
@pytest.mark.parametrize("n", [4, 4000])
@pytest.mark.parametrize(
"op_str,op,rop",
[
("+", "__add__", "__radd__"),
("-", "__sub__", "__rsub__"),
("*", "__mul__", "__rmul__"),
("/", "__true... | TestDataFrameEval |
python | pytorch__pytorch | test/torch_np/test_reductions.py | {
"start": 923,
"end": 1067
} | class ____(TestCase):
def test_basic(self):
x = np.arange(-2, 3)
assert_equal(np.flatnonzero(x), [0, 1, 3, 4])
| TestFlatnonzero |
python | jazzband__django-simple-history | simple_history/models.py | {
"start": 32624,
"end": 33299
} | class ____:
def get_queryset(self, **hints):
instance = hints.get("instance")
if instance:
history = getattr(instance, SIMPLE_HISTORY_REVERSE_ATTR_NAME, None)
histmgr = getattr(
self.get_related_model(),
getattr(
self.get_r... | HistoricDescriptorMixin |
python | PrefectHQ__prefect | src/integrations/prefect-gcp/prefect_gcp/models/cloud_run_v2.py | {
"start": 8210,
"end": 12094
} | class ____(BaseModel):
"""
ExecutionV2 is a data model for an execution of a job that will be run on
Cloud Run API v2.
"""
name: str
uid: str
generation: str
labels: Dict[str, str]
annotations: Dict[str, str]
createTime: str
startTime: Optional[str]
completionTime: O... | ExecutionV2 |
python | huggingface__transformers | src/transformers/models/timesformer/modeling_timesformer.py | {
"start": 11836,
"end": 17954
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: TimesformerConfig, layer_index: int) -> None:
super().__init__()
attention_type = config.attention_type
drop_path_rates = [
x.item() for x in torch.linspace(0, config.drop_path_rate, config.num_hidden_layers, de... | TimesformerLayer |
python | sympy__sympy | sympy/functions/elementary/miscellaneous.py | {
"start": 1233,
"end": 9694
} | class ____(Lambda, metaclass=Singleton):
"""
The identity function
Examples
========
>>> from sympy import Id, Symbol
>>> x = Symbol('x')
>>> Id(x)
x
"""
_symbol = Dummy('x')
@property
def signature(self):
return Tuple(self._symbol)
@property
def exp... | IdentityFunction |
python | arrow-py__arrow | tests/test_factory.py | {
"start": 12610,
"end": 12828
} | class ____:
def test_utcnow(self):
assert_datetime_equality(
self.factory.utcnow()._datetime,
datetime.now(timezone.utc),
)
@pytest.mark.usefixtures("arrow_factory")
| TestUtcNow |
python | great-expectations__great_expectations | tests/datasource/fluent/test_metadatasource.py | {
"start": 10243,
"end": 24276
} | class ____:
def test_ds_type_field_not_set(self, empty_sources: DataSourceManager):
with pytest.raises(
TypeRegistrationError,
match=r"`MissingTypeDatasource` is missing a `type` attribute",
):
class MissingTypeDatasource(Datasource):
@property
... | TestMisconfiguredMetaDatasource |
python | doocs__leetcode | solution/1000-1099/1057.Campus Bikes/Solution.py | {
"start": 0,
"end": 604
} | class ____:
def assignBikes(
self, workers: List[List[int]], bikes: List[List[int]]
) -> List[int]:
n, m = len(workers), len(bikes)
arr = []
for i, j in product(range(n), range(m)):
dist = abs(workers[i][0] - bikes[j][0]) + abs(workers[i][1] - bikes[j][1])
... | Solution |
python | huggingface__transformers | tests/models/bamba/test_modeling_bamba.py | {
"start": 1570,
"end": 9734
} | class ____:
config_class = BambaConfig
if is_torch_available():
model_class = BambaModel
for_causal_lm_class = BambaForCausalLM
def __init__(
self,
parent,
batch_size=13,
seq_length=7,
is_training=True,
use_input_mask=True,
use_labels=... | BambaModelTester |
python | numba__llvmlite | llvmlite/tests/test_refprune.py | {
"start": 12096,
"end": 15660
} | class ____(BaseTestByIR):
refprune_bitmask = llvm.RefPruneSubpasses.FANOUT_RAISE
fanout_raise_1 = r"""
define i32 @main(i8* %ptr, i1 %cond, i8** %excinfo) {
bb_A:
call void @NRT_incref(i8* %ptr)
br i1 %cond, label %bb_B, label %bb_C
bb_B:
call void @NRT_decref(i8* %ptr)
ret i32 0
bb_C:
stor... | TestFanoutRaise |
python | astropy__astropy | astropy/visualization/wcsaxes/frame.py | {
"start": 4750,
"end": 9378
} | class ____(OrderedDict, metaclass=abc.ABCMeta):
"""
Base class for frames, which are collections of
:class:`~astropy.visualization.wcsaxes.frame.Spine` instances.
"""
spine_class = Spine
def __init__(self, parent_axes, transform, path=None):
super().__init__()
self.parent_axes... | BaseFrame |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/dataclass_taint.py | {
"start": 611,
"end": 842
} | class ____:
bad: int
def __init__(self, bad: int) -> None:
self.bad = bad
_test_sink(bad)
def issue_in_dataclass_constructor() -> None:
DataClassWIthInit(bad=_test_source())
@dataclass
| DataClassWIthInit |
python | sympy__sympy | sympy/physics/quantum/spin.py | {
"start": 36499,
"end": 40294
} | class ____(SpinState, Ket):
"""Eigenket of Jz.
Spin state which is an eigenstate of the Jz operator. Uncoupled states,
that is states representing the interaction of multiple separate spin
states, are defined as a tensor product of states.
Parameters
==========
j : Number, Symbol
... | JzKet |
python | facebook__pyre-check | tools/generate_taint_models/tests/get_undecorated_sources_test.py | {
"start": 631,
"end": 3881
} | class ____(unittest.TestCase):
@patch.object(RESTApiSourceGenerator, "generate_models")
# pyre-fixme[56]: Argument
# `"{}.AnnotatedFreeFunctionWithDecoratorGenerator".format(tools.pyre.tools.generate_taint_models.get_undecorated_sources.__name__)`
# to decorator factory `unittest.mock.patch` could not... | GetUndecoratedSourcesTest |
python | pypa__pip | src/pip/_vendor/pygments/lexers/python.py | {
"start": 30360,
"end": 31955
} | class ____(DelegatingLexer):
"""
For Python console output or doctests, such as:
.. sourcecode:: pycon
>>> a = 'foo'
>>> print(a)
foo
>>> 1 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer divisi... | PythonConsoleLexer |
python | sympy__sympy | sympy/physics/quantum/cg.py | {
"start": 1164,
"end": 4480
} | class ____(Expr):
"""Class for the Wigner-3j symbols.
Explanation
===========
Wigner 3j-symbols are coefficients determined by the coupling of
two angular momenta. When created, they are expressed as symbolic
quantities that, for numerical parameters, can be evaluated using the
``.doit()``... | Wigner3j |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 793283,
"end": 795005
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"body",
"conditions",
"description",
"featured",
"hidden",
"implementation",
"key",
"limitations",
"name... | License |
python | google__jax | tests/pmap_test.py | {
"start": 97791,
"end": 107074
} | class ____(jtu.JaxTestCase):
def testAllDevices(self):
f = pmap(lambda x: x - lax.psum(x, 'i'), axis_name='i',
devices=jax.devices())
shape = (jax.device_count(), 4)
x = np.arange(math.prod(shape), dtype=np.float32).reshape(shape)
expected = x - np.sum(x, 0)
ans = f(x)
self.asser... | PmapWithDevicesTest |
python | kamyu104__LeetCode-Solutions | Python/find-minimum-operations-to-make-all-elements-divisible-by-three.py | {
"start": 36,
"end": 253
} | class ____(object):
def minimumOperations(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(x%3 != 0 for x in nums)
# Time: O(n)
# Space: O(1)
# math
| Solution |
python | ray-project__ray | python/ray/tune/progress_reporter.py | {
"start": 1522,
"end": 3323
} | class ____:
"""Abstract class for experiment progress reporting.
`should_report()` is called to determine whether or not `report()` should
be called. Tune will call these functions after trial state transitions,
receiving training results, and so on.
"""
def setup(
self,
start_... | ProgressReporter |
python | getsentry__sentry | tests/sentry/runner/commands/test_cleanup.py | {
"start": 478,
"end": 958
} | class ____:
"""Mock task queue that partially implements the _WorkQueue protocol but executes tasks synchronously."""
def __init__(self) -> None:
# You can use this to inspect the calls to the queue.
self.put_calls: list[tuple[str, tuple[int, ...]]] = []
def put(self, item: tuple[str, tupl... | SynchronousTaskQueue |
python | pytorch__pytorch | torch/optim/swa_utils.py | {
"start": 3723,
"end": 15467
} | class ____(Module):
r"""Implements averaged model for Stochastic Weight Averaging (SWA) and Exponential Moving Average (EMA).
Stochastic Weight Averaging was proposed in `Averaging Weights Leads to
Wider Optima and Better Generalization`_ by Pavel Izmailov, Dmitrii
Podoprikhin, Timur Garipov, Dmitry Ve... | AveragedModel |
python | apache__airflow | airflow-core/tests/unit/serialization/test_serialized_objects.py | {
"start": 9048,
"end": 18033
} | class ____(LazySelectSequence):
_data = ["a", "b", "c"]
def __init__(self):
super().__init__(None, None, session="MockSession")
def __iter__(self) -> Iterator[str]:
return iter(self._data)
def __len__(self) -> int:
return len(self._data)
@pytest.mark.parametrize(
("input... | MockLazySelectSequence |
python | django__django | tests/generic_inline_admin/admin.py | {
"start": 370,
"end": 443
} | class ____(GenericTabularInline):
model = PhoneNumber
| PhoneNumberInline |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/events.py | {
"start": 117609,
"end": 125363
} | class ____(event.Events[Query[Any]]):
"""Represent events within the construction of a :class:`_query.Query`
object.
.. legacy:: The :class:`_orm.QueryEvents` event methods are legacy
as of SQLAlchemy 2.0, and only apply to direct use of the
:class:`_orm.Query` object. They are not used for... | QueryEvents |
python | dateutil__dateutil | src/dateutil/tz/_common.py | {
"start": 8750,
"end": 12977
} | class ____(_tzinfo):
"""
This is an abstract base class for time zones represented by an annual
transition into and out of DST. Child classes should implement the following
methods:
* ``__init__(self, *args, **kwargs)``
* ``transitions(self, year)`` - this is expected to return a tuple ... | tzrangebase |
python | sympy__sympy | sympy/codegen/ast.py | {
"start": 16799,
"end": 18450
} | class ____(AugmentedAssignment):
binop = '%'
# Mapping from binary op strings to AugmentedAssignment subclasses
augassign_classes = {
cls.binop: cls for cls in [
AddAugmentedAssignment, SubAugmentedAssignment, MulAugmentedAssignment,
DivAugmentedAssignment, ModAugmentedAssignment
]
}
def... | ModAugmentedAssignment |
python | MorvanZhou__Reinforcement-learning-with-tensorflow | contents/9_Deep_Deterministic_Policy_Gradient_DDPG/DDPG_update.py | {
"start": 719,
"end": 5712
} | class ____(object):
def __init__(self, a_dim, s_dim, a_bound,):
self.memory = np.zeros((MEMORY_CAPACITY, s_dim * 2 + a_dim + 1), dtype=np.float32)
self.pointer = 0
self.sess = tf.Session()
self.a_dim, self.s_dim, self.a_bound = a_dim, s_dim, a_bound,
self.S = tf.placeholder(... | DDPG |
python | apache__airflow | providers/edge3/src/airflow/providers/edge3/worker_api/datamodels.py | {
"start": 3296,
"end": 3712
} | class ____(EdgeJobBase):
"""Job that is to be executed on the edge worker."""
command: Annotated[
ExecuteTask,
Field(
title="Command",
description="Command line to use to execute the job in Airflow 2. Task definition in Airflow 3",
),
]
concurrency_slots:... | EdgeJobFetched |
python | huggingface__transformers | src/transformers/models/luke/modeling_luke.py | {
"start": 3617,
"end": 5554
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
The sum of masked language modeling (MLM) loss and entity prediction loss.
mlm_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
... | LukeMaskedLMOutput |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/cachecontrol/heuristics.py | {
"start": 1850,
"end": 2431
} | class ____(BaseHeuristic):
"""
Cache the response by providing an expires 1 day in the
future.
"""
def update_headers(self, response: HTTPResponse) -> dict[str, str]:
headers = {}
if "expires" not in response.headers:
date = parsedate(response.headers["date"])
... | OneDayCache |
python | coleifer__peewee | tests/sqlite.py | {
"start": 2976,
"end": 3048
} | class ____(TestModel):
key = TextField()
data = JSONField()
| KeyData |
python | redis__redis-py | redis/commands/timeseries/__init__.py | {
"start": 3356,
"end": 3450
} | class ____(TimeSeriesCommands, redis.client.Pipeline):
"""Pipeline for the module."""
| Pipeline |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/input/posix_utils.py | {
"start": 142,
"end": 3973
} | class ____:
"""
Wrapper around stdin which reads (nonblocking) the next available 1024
bytes and decodes it.
Note that you can't be sure that the input file is closed if the ``read``
function returns an empty string. When ``errors=ignore`` is passed,
``read`` can return an empty string if all m... | PosixStdinReader |
python | allegroai__clearml | clearml/backend_api/services/v2_23/datasets.py | {
"start": 215721,
"end": 226589
} | class ____(Request):
"""
Publishes the specified version and creates a draft child version for it
:param dataset: Dataset ID
:type dataset: str
:param version: Draft version ID
:type version: str
:param publish_name: New name for the published version. The default value is
'snapshot... | PublishAndCreateChildVersionRequest |
python | wandb__wandb | wandb/apis/public/artifacts.py | {
"start": 5394,
"end": 8630
} | class ____:
"""An artifact object that satisfies query based on the specified type.
Args:
client: The client instance to use for querying W&B.
entity: The entity (user or team) that owns the project.
project: The name of the project to query for artifact types.
type_name: The na... | ArtifactType |
python | tensorflow__tensorflow | tensorflow/python/profiler/profiler_v2.py | {
"start": 1889,
"end": 6608
} | class ____(
collections.namedtuple('ProfilerOptions', [
'host_tracer_level', 'python_tracer_level', 'device_tracer_level',
'delay_ms'
])):
"""Options for finer control over the profiler.
Use `tf.profiler.experimental.ProfilerOptions` to control `tf.profiler`
behavior.
Fields:
host_... | ProfilerOptions |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 300028,
"end": 302110
} | class ____(StatNode):
# del statement
#
# args [ExprNode]
child_attrs = ["args"]
ignore_nonexisting = False
def analyse_declarations(self, env):
for arg in self.args:
arg.analyse_target_declaration(env)
def analyse_expressions(self, env):
for i, arg in en... | DelStatNode |
python | kubernetes-client__python | kubernetes/client/models/v1beta1_resource_claim.py | {
"start": 383,
"end": 7590
} | 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... | V1beta1ResourceClaim |
python | keon__algorithms | tests/test_strings.py | {
"start": 18402,
"end": 18867
} | class ____(unittest.TestCase):
"""[summary]
Test for the file atbash_cipher.py
Arguments:
unittest {[type]} -- [description]
"""
def test_atbash_cipher(self):
self.assertEqual("zyxwvutsrqponml", atbash("abcdefghijklmno"))
self.assertEqual("KbgslM", atbash("PythoN"))
... | TestAtbashCipher |
python | sqlalchemy__sqlalchemy | test/orm/test_dataclasses.py | {
"start": 21159,
"end": 25452
} | class ____(FieldEmbeddedMixinWLambdaTest):
@classmethod
def setup_classes(cls):
declarative = cls.DeclarativeBasic.registry.mapped
@dataclasses.dataclass
class WidgetDC:
__sa_dataclass_metadata_key__ = "sa"
widget_id: int = dataclasses.field(
ini... | FieldEmbeddedMixinWDeclaredAttrTest |
python | docker__docker-py | tests/integration/models_containers_test.py | {
"start": 188,
"end": 11572
} | class ____(BaseIntegrationTest):
def test_run(self):
client = docker.from_env(version=TEST_API_VERSION)
assert client.containers.run(
"alpine", "echo hello world", remove=True
) == b'hello world\n'
def test_run_detach(self):
client = docker.from_env(version=TEST_API... | ContainerCollectionTest |
python | tensorflow__tensorflow | tensorflow/python/distribute/coordinator/fault_tolerance_test.py | {
"start": 2379,
"end": 5670
} | class ____(test.TestCase):
"""Test preemptions during strategy init."""
def setUp(self):
super().setUp()
self.num_workers = 2
self.num_ps = 2
self._cluster = multi_worker_test_base.create_multi_process_cluster(
num_workers=self.num_workers,
num_ps=self.num_ps,
rpc_layer="grp... | InitFaultToleranceTest |
python | sympy__sympy | sympy/polys/polyclasses.py | {
"start": 3641,
"end": 41552
} | class ____(CantSympify, Generic[Er]):
"""Dense Multivariate Polynomials over `K`. """
__slots__ = ()
lev: int
dom: Domain[Er]
def __new__(cls, rep: dmp[Er], dom: Domain[Er], lev: int | None = None):
if lev is None:
rep, lev = dmp_validate(rep, dom)
elif not isinstance... | DMP |
python | apache__airflow | providers/google/tests/unit/google/marketing_platform/sensors/test_display_video.py | {
"start": 1202,
"end": 2627
} | class ____:
@mock.patch(f"{MODULE_NAME}.GoogleDisplayVideo360Hook")
@mock.patch(f"{MODULE_NAME}.BaseSensorOperator")
def test_poke(self, mock_base_op, hook_mock):
operation_name = "operation_name"
op = GoogleDisplayVideo360GetSDFDownloadOperationSensor(
operation_name=operation_n... | TestGoogleDisplayVideo360Sensor |
python | getsentry__sentry | src/sentry/seer/models.py | {
"start": 1462,
"end": 1595
} | class ____(BaseModel):
trace_ids: list[str]
suggested_investigations: list[PageWebVitalsInsight]
| SummarizePageWebVitalsResponse |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.