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 | ansible__ansible | test/lib/ansible_test/_internal/commands/sanity/pep8.py | {
"start": 619,
"end": 3126
} | class ____(SanitySingleVersion):
"""Sanity test for PEP 8 style guidelines using pycodestyle."""
@property
def error_code(self) -> t.Optional[str]:
"""Error code for ansible-test matching the format used by the underlying test program, or None if the program does not use error codes."""
ret... | Pep8Test |
python | pola-rs__polars | py-polars/src/polars/exceptions.py | {
"start": 5500,
"end": 5649
} | class ____(PolarsWarning):
"""Warning issued when a custom ufunc is handled differently than numpy ufunc would.""" # noqa: W505
| CustomUFuncWarning |
python | django-extensions__django-extensions | tests/testapp/models.py | {
"start": 12603,
"end": 12964
} | class ____(models.Model):
cafe = models.IntegerField(verbose_name="café")
parent_cafe = models.ForeignKey(
"self",
related_name="children",
on_delete=models.CASCADE,
verbose_name="café latte",
)
class Meta:
app_label = "django_extensions"
verbose_name = "... | UnicodeVerboseNameModel |
python | google__pytype | pytype/tests/test_pyi1.py | {
"start": 109,
"end": 29637
} | class ____(test_base.BaseTest):
"""Tests for PYI."""
def test_module_parameter(self):
"""This test that types.ModuleType works."""
with test_utils.Tempdir() as d:
d.create_file(
"mod.pyi",
"""
import types
def f(x: types.ModuleType = ...) -> None: ...
""",
... | PYITest |
python | keras-team__keras | keras/src/layers/pooling/average_pooling3d.py | {
"start": 185,
"end": 3238
} | class ____(BasePooling):
"""Average pooling operation for 3D data (spatial or spatio-temporal).
Downsamples the input along its spatial dimensions (depth, height, and
width) by taking the average value over an input window (of size defined by
`pool_size`) for each channel of the input. The window is sh... | AveragePooling3D |
python | numba__numba | numba/tests/test_cli.py | {
"start": 1165,
"end": 3934
} | class ____(TestCase):
def test_as_module_exit_code(self):
cmdline = [sys.executable, "-m", "numba"]
with self.assertRaises(AssertionError) as raises:
run_cmd(cmdline)
self.assertIn("process failed with code 1", str(raises.exception))
def test_sysinfo_from_module(self):
... | TestCLI |
python | neetcode-gh__leetcode | python/0704-binary-search.py | {
"start": 0,
"end": 383
} | class ____:
def search(self, nums: List[int], target: int) -> int:
l, r = 0, len(nums) - 1
while l <= r:
m = l + ((r - l) // 2) # (l + r) // 2 can lead to overflow
if nums[m] > target:
r = m - 1
elif nums[m] < target:
l = m + 1
... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/metaclass2.py | {
"start": 157,
"end": 375
} | class ____(Enum):
apple = 1
orange = 2
pear = 3
def requires_fruit_mapping(a: Mapping[str, Fruit]):
pass
requires_fruit_mapping(Fruit.__members__)
aaa = len(Fruit)
for i in Fruit:
print(i)
| Fruit |
python | bokeh__bokeh | tests/unit/bokeh/test_objects.py | {
"start": 16253,
"end": 21558
} | class ____(TestContainerMutation):
def test_whether_included_in_props_with_values(self) -> None:
obj = HasStringDictProp()
assert 'foo' not in obj.properties_with_values(include_defaults=False)
assert 'foo' in obj.properties_with_values(include_defaults=True)
# simply reading the pr... | TestDictMutation |
python | huggingface__transformers | utils/notification_service.py | {
"start": 4093,
"end": 69242
} | class ____:
def __init__(
self,
title: str,
ci_title: str,
model_results: dict,
additional_results: dict,
selected_warnings: list | None = None,
prev_ci_artifacts=None,
other_ci_artifacts=None,
):
self.title = title
self.ci_title = ... | Message |
python | pandas-dev__pandas | pandas/tests/groupby/test_grouping.py | {
"start": 548,
"end": 5495
} | class ____:
def test_select_bad_cols(self):
df = DataFrame([[1, 2]], columns=["A", "B"])
g = df.groupby("A")
with pytest.raises(KeyError, match="\"Columns not found: 'C'\""):
g[["C"]]
with pytest.raises(KeyError, match="^[^A]+$"):
# A should not be referenced... | TestSelection |
python | plotly__plotly.py | plotly/graph_objs/scatterpolargl/_line.py | {
"start": 233,
"end": 3488
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatterpolargl"
_path_str = "scatterpolargl.line"
_valid_props = {"color", "dash", "width"}
@property
def color(self):
"""
Sets the line color.
The 'color' property is a color and may be specified as:
- A he... | Line |
python | huggingface__transformers | src/transformers/cache_utils.py | {
"start": 529,
"end": 2642
} | class ____(ABC):
"""Base, abstract class for a single layer's cache."""
is_compileable = False
def __init__(self):
self.keys: Optional[torch.Tensor] = None
self.values: Optional[torch.Tensor] = None
self.is_initialized = False
def __repr__(self):
return f"{self.__class... | CacheLayerMixin |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/s3/sensor.py | {
"start": 206,
"end": 3442
} | class ____(Exception):
pass
def get_objects(
bucket: str,
prefix: str = "",
since_key: Optional[str] = None,
since_last_modified: Optional[datetime] = None,
client=None,
) -> list[ObjectTypeDef]:
"""Retrieves a list of object keys in S3 for a given `bucket`, `prefix`, and filter option.
... | ClientException |
python | ApeWorX__ape | src/ape/types/private_mempool.py | {
"start": 526,
"end": 763
} | class ____(str, Enum):
"""
The version of the MEV-share API to use.
"""
BETA1 = "beta-1"
"""
The beta-1 version of the API.
"""
V0_1 = "v0.1"
"""
The 0.1 version of the API.
"""
| ProtocolVersion |
python | neetcode-gh__leetcode | python/2215-find-the-difference-of-two-arrays.py | {
"start": 56,
"end": 822
} | class ____:
def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
nums1 = set(nums1)
nums2 = set(nums2)
table = {}
for _, val in enumerate(nums2):
table[val] = 1
unik1 = []
unik2 = []
for i in nums1:
if i in ... | Solution |
python | pytest-dev__pytest-django | tests/test_django_configurations.py | {
"start": 271,
"end": 4456
} | class ____(Configuration):
# At least one database must be configured
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
},
}
SECRET_KEY = 'foobar'
"""
def test_dc_env(pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch... | MySettings |
python | plotly__plotly.py | plotly/graph_objs/streamtube/_hoverlabel.py | {
"start": 233,
"end": 11262
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "streamtube"
_path_str = "streamtube.hoverlabel"
_valid_props = {
"align",
"alignsrc",
"bgcolor",
"bgcolorsrc",
"bordercolor",
"bordercolorsrc",
"font",
"namelength",
"namelengthsr... | Hoverlabel |
python | readthedocs__readthedocs.org | readthedocs/projects/forms.py | {
"start": 14711,
"end": 15639
} | class ____(ProjectFormPrevalidateMixin, PrevalidatedForm):
def clean_prevalidation(self):
super().clean_prevalidation()
if settings.RTD_ALLOW_ORGANIZATIONS:
if self.user_is_nonowner_with_sso:
raise RichValidationError(
_(
"Proje... | ProjectManualForm |
python | django__django | tests/messages_tests/test_session.py | {
"start": 835,
"end": 2167
} | class ____(BaseTests, TestCase):
storage_class = SessionStorage
def get_request(self):
self.session = {}
request = super().get_request()
request.session = self.session
return request
def stored_messages_count(self, storage, response):
return stored_session_messages_... | SessionTests |
python | jazzband__django-oauth-toolkit | tests/db_router.py | {
"start": 1041,
"end": 1644
} | class ____:
def db_for_read(self, model, **hints):
if model._meta.app_label in apps_in_beta:
return "beta"
return None
def db_for_write(self, model, **hints):
if model._meta.app_label in apps_in_beta:
return "beta"
return None
def allow_relation(self... | BetaRouter |
python | sqlalchemy__sqlalchemy | test/ext/asyncio/test_engine.py | {
"start": 2063,
"end": 7277
} | class ____:
@config.fixture(
params=[
(rollback, run_second_execute, begin_nested)
for rollback in (True, False)
for run_second_execute in (True, False)
for begin_nested in (True, False)
]
)
def async_trans_ctx_manager_fixture(self, request, me... | AsyncFixture |
python | plotly__plotly.py | plotly/graph_objs/bar/_selected.py | {
"start": 233,
"end": 3254
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "bar"
_path_str = "bar.selected"
_valid_props = {"marker", "textfont"}
@property
def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.g... | Selected |
python | cython__cython | tests/run/typing_module.py | {
"start": 740,
"end": 1066
} | class ____:
"""
>>> TestClassVar.cls
5
>>> TestClassVar.regular # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
AttributeError:
"""
regular: int
cls: typing.ClassVar[int] = 5 # this is a little redundant really because the assignment ensures it
| TestClassVar |
python | automl__auto-sklearn | test/test_pipeline/components/regression/test_decision_tree.py | {
"start": 157,
"end": 735
} | class ____(BaseRegressionComponentTest):
__test__ = True
res = dict()
res["default_boston"] = 0.35616796434879905
res["default_boston_iterative"] = None
res["default_boston_sparse"] = 0.18031669797027394
res["default_boston_iterative_sparse"] = None
res["default_diabetes"] = 0.156459244951... | DecisionTreeComponentTest |
python | pytorch__pytorch | torchgen/api/types/signatures.py | {
"start": 438,
"end": 4659
} | class ____:
"""
A CppSignature represents a single overload in the C++ API. For
any given function schema, there may be multiple CppSignatures
corresponding to it, based on how we desugar to C++. See also
CppSignatureGroup.
"""
# The schema this signature is derived from
func: Functio... | CppSignature |
python | tensorflow__tensorflow | tensorflow/python/distribute/distribute_lib.py | {
"start": 17006,
"end": 28138
} | class ____(_ThreadMode):
"""Type of default value returned by `_get_per_thread_mode()`.
Used when the thread-local stack is empty.
"""
def __init__(self):
_ThreadMode.__init__(self, _get_default_strategy(), None,
_get_default_replica_context())
def _get_per_thread_mode():
try:... | _DefaultReplicaThreadMode |
python | getsentry__sentry | tests/sentry/users/api/endpoints/test_user_authenticator_enroll.py | {
"start": 1098,
"end": 12929
} | class ____(APITestCase):
endpoint = "sentry-api-0-user-authenticator-enroll"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.org = self.create_organization(owner=self.user, name="foo")
@mock.patch("sentry.auth.authenticators.TotpInterface.validate_otp", ... | UserAuthenticatorEnrollTest |
python | aio-libs__aiohttp | aiohttp/web_urldispatcher.py | {
"start": 1754,
"end": 2046
} | class ____(TypedDict, total=False):
path: str
formatter: str
pattern: Pattern[str]
directory: Path
prefix: str
routes: Mapping[str, "AbstractRoute"]
app: "Application"
domain: str
rule: "AbstractRuleMatching"
http_exception: HTTPException
| _InfoDict |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/composition.py | {
"start": 4670,
"end": 4739
} | class ____(NamedTuple):
input_def: InputDefinition
| InputMappingNode |
python | ApeWorX__ape | tests/functional/test_dependencies.py | {
"start": 19883,
"end": 26333
} | class ____:
@pytest.fixture
def mock_client(self, mocker):
return mocker.MagicMock()
def test_ref_or_version_is_required(self):
expected = r"GitHub dependency must have either ref or version specified"
with pytest.raises(ValidationError, match=expected):
_ = GithubDepend... | TestGitHubDependency |
python | PrefectHQ__prefect | src/prefect/server/api/server.py | {
"start": 4841,
"end": 5331
} | class ____(StaticFiles):
"""
Implementation of `StaticFiles` for serving single page applications.
Adds `get_response` handling to ensure that when a resource isn't found the
application still returns the index.
"""
async def get_response(self, path: str, scope: Any) -> Response:
try:
... | SPAStaticFiles |
python | mahmoud__boltons | boltons/dictutils.py | {
"start": 30935,
"end": 35480
} | class ____:
"""
a dict-like entity that represents a many-to-many relationship
between two groups of objects
behaves like a dict-of-tuples; also has .inv which is kept
up to date which is a dict-of-tuples in the other direction
also, can be used as a directed graph among hashable python object... | ManyToMany |
python | kamyu104__LeetCode-Solutions | Python/distribute-candies.py | {
"start": 29,
"end": 252
} | class ____(object):
def distributeCandies(self, candies):
"""
:type candies: List[int]
:rtype: int
"""
lookup = set(candies)
return min(len(lookup), len(candies)/2)
| Solution |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 2670,
"end": 2933
} | class ____(str, _Action, Enum):
CREATE = "create_aliases"
READ = "read_aliases"
UPDATE = "update_aliases"
DELETE = "delete_aliases"
@staticmethod
def values() -> List[str]:
return [action.value for action in AliasAction]
| AliasAction |
python | django__django | django/template/loaders/cached.py | {
"start": 313,
"end": 3716
} | class ____(BaseLoader):
def __init__(self, engine, loaders):
self.get_template_cache = {}
self.loaders = engine.get_template_loaders(loaders)
super().__init__(engine)
def get_dirs(self):
for loader in self.loaders:
if hasattr(loader, "get_dirs"):
yiel... | Loader |
python | kamyu104__LeetCode-Solutions | Python/find-closest-person.py | {
"start": 36,
"end": 252
} | class ____(object):
def findClosest(self, x, y, z):
"""
:type x: int
:type y: int
:type z: int
:rtype: int
"""
return range(3)[cmp(abs(y-z), abs(x-z))]
| Solution |
python | kamyu104__LeetCode-Solutions | Python/apply-discount-to-prices.py | {
"start": 38,
"end": 917
} | class ____(object):
def discountPrices(self, sentence, discount):
"""
:type sentence: str
:type discount: int
:rtype: str
"""
result = []
i = 0
while i < len(sentence):
j = sentence.find(' ', i)
if j == -1: j = len(sentence)
... | Solution |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 8603,
"end": 8801
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("LOGIN", "REMOTE_CREATED_AT")
| EnterpriseServerUserAccountOrderField |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1530681,
"end": 1534290
} | class ____(sgqlc.types.Type, Node, Starrable):
"""A topic aggregates entities that are related to a subject."""
__schema__ = github_schema
__field_names__ = ("name", "related_topics", "repositories")
name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name")
"""The topic's name."""... | Topic |
python | ray-project__ray | rllib/models/action_dist.py | {
"start": 232,
"end": 3425
} | class ____:
"""The policy action distribution of an agent.
Attributes:
inputs: input vector to compute samples from.
model (ModelV2): reference to model producing the inputs.
"""
def __init__(self, inputs: List[TensorType], model: ModelV2):
"""Initializes an ActionDist object.
... | ActionDistribution |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_sessions.py | {
"start": 79097,
"end": 98760
} | class ____(BaseMetricsTestCase, APITestCase):
def do_request(self, query, user=None, org=None):
self.login_as(user=user or self.user)
url = reverse(
"sentry-api-0-organization-sessions",
kwargs={"organization_id_or_slug": (org or self.organization).slug},
)
re... | SessionsMetricsSortReleaseTimestampTest |
python | tiangolo__fastapi | docs_src/header_param_models/tutorial003_an.py | {
"start": 158,
"end": 478
} | class ____(BaseModel):
host: str
save_data: bool
if_modified_since: Union[str, None] = None
traceparent: Union[str, None] = None
x_tag: List[str] = []
@app.get("/items/")
async def read_items(
headers: Annotated[CommonHeaders, Header(convert_underscores=False)],
):
return headers
| CommonHeaders |
python | kamyu104__LeetCode-Solutions | Python/lexicographically-smallest-generated-string.py | {
"start": 109,
"end": 1995
} | class ____(object):
def generateString(self, str1, str2):
"""
:type str1: str
:type str2: str
:rtype: str
"""
def getPrefix(pattern):
prefix = [-1]*len(pattern)
j = -1
for i in xrange(1, len(pattern)):
while j+1 > 0 ... | Solution |
python | pytorch__pytorch | test/distributed/_pycute/test_complement.py | {
"start": 2091,
"end": 3468
} | class ____(TestCase):
def helper_test_complement(self, layout):
layoutR = complement(layout)
_LOGGER.debug(f"{layout} => {layoutR}")
# Post-condition: test disjointedness of the codomains
for a in range(size(layout)):
for b in range(size(layoutR)):
ass... | TestComplement |
python | Textualize__textual | docs/examples/how-to/containers06.py | {
"start": 272,
"end": 655
} | class ____(App):
"""Simple app to play with containers."""
CSS = """
.with-border {
border: heavy green;
}
"""
def compose(self) -> ComposeResult:
with Horizontal(classes="with-border"):
for n in range(10):
yield Box(label=f"Box {n+1}")
if __name__... | ContainerApp |
python | sqlalchemy__sqlalchemy | test/sql/test_types.py | {
"start": 130734,
"end": 131255
} | class ____(AssertsCompiledSQL, fixtures.TestBase):
__sparse_driver_backend__ = True
def test_user_defined(self):
"""test that dialects pass the column through on DDL."""
class MyType(types.UserDefinedType):
def get_col_spec(self, **kw):
return "FOOB %s" % kw["type_e... | TestKWArgPassThru |
python | google__flatbuffers | python/flatbuffers/reflection/Object.py | {
"start": 179,
"end": 6861
} | class ____(object):
__slots__ = ['_tab']
@classmethod
def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = Object()
x.Init(buf, n + offset)
return x
@classmethod
def GetRootAsObject(cls, buf, offset=0):
"... | Object |
python | pydantic__pydantic | pydantic/v1/types.py | {
"start": 25034,
"end": 25916
} | class ____(abc.ABC):
"""
Note: this should be implemented as a generic like `SecretField(ABC, Generic[T])`,
the `__init__()` should be part of the abstract class and the
`get_secret_value()` method should use the generic `T` type.
However Cython doesn't support very well generics ... | SecretField |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/guides/tutorials/multi-asset-integration/integration.py | {
"start": 1725,
"end": 2765
} | class ____:
@public
def get_asset_key(self, table_definition: Mapping[str, str]) -> dg.AssetKey:
return dg.AssetKey(str(table_definition.get("name")))
def custom_replication_assets(
*,
replication_project: ReplicationProject,
name: Optional[str] = None,
group_name: Optional[str] = None... | ReplicationTranslator |
python | pytorch__pytorch | tools/experimental/torchfuzz/operators/nn_functional.py | {
"start": 12209,
"end": 16095
} | class ____(Operator):
"""Operator for torch.nn.functional.layer_norm."""
def __init__(self):
super().__init__("torch.nn.functional.layer_norm")
@property
def torch_op_name(self) -> str | None:
"""Return the torch operation name."""
return "torch.nn.functional.layer_norm"
d... | LayerNormOperator |
python | falconry__falcon | tests/test_before_hooks.py | {
"start": 5645,
"end": 11398
} | class ____(ZooResource):
def on_get(self, req, resp):
super().on_get(
req,
resp,
# Test passing a mixture of args and kwargs
'fluffy',
'not fluffy',
fish='slippery',
)
@pytest.fixture
def wrapped_aware_resource():
return C... | ZooResourceChild |
python | tensorflow__tensorflow | tensorflow/python/keras/optimizer_v2/nadam.py | {
"start": 1303,
"end": 9274
} | class ____(optimizer_v2.OptimizerV2):
r"""Optimizer that implements the NAdam algorithm.
Much like Adam is essentially RMSprop with momentum, Nadam is Adam with
Nesterov momentum.
Args:
learning_rate: A Tensor or a floating point value. The learning rate.
beta_1: A float value or a constant float tens... | Nadam |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 346073,
"end": 346308
} | class ____(Response):
"""
Response of tasks.move endpoint.
"""
_service = "tasks"
_action = "move"
_version = "2.20"
_schema = {"additionalProperties": True, "definitions": {}, "type": "object"}
| MoveResponse |
python | tensorflow__tensorflow | tensorflow/python/framework/function_test.py | {
"start": 55960,
"end": 58360
} | class ____(test.TestCase):
def _testSimpleModel(self, use_forward_func, use_resource=False):
def _Model(x):
w = variable_scope.get_variable(
"w", (64, 64),
initializer=init_ops.random_uniform_initializer(seed=312),
use_resource=use_resource)
b = variable_scope.get_varia... | VariableHoistingTest |
python | numba__numba | numba/tests/test_withlifting.py | {
"start": 32886,
"end": 34119
} | class ____(BaseTestWithLifting):
def test_undefined_global(self):
the_ir = get_func_ir(lift_undefiend)
with self.assertRaises(errors.CompilerError) as raises:
with_lifting(
the_ir, self.typingctx, self.targetctx, self.flags, locals={},
)
self.assertIn... | TestBogusContext |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 3385,
"end": 3897
} | class ____(type):
# Set this as a metaclass to trace function calls in code.
# This slows down code generation and makes much larger files.
def __new__(cls, name, bases, attrs):
from types import FunctionType
from .Code import CCodeWriter
attrs = dict(attrs)
for mname, m in a... | VerboseCodeWriter |
python | kamyu104__LeetCode-Solutions | Python/remove-vowels-from-a-string.py | {
"start": 29,
"end": 235
} | class ____(object):
def removeVowels(self, S):
"""
:type S: str
:rtype: str
"""
lookup = set("aeiou")
return "".join(c for c in S if c not in lookup)
| Solution |
python | getsentry__sentry | src/sentry/incidents/grouptype.py | {
"start": 12527,
"end": 14167
} | class ____(GroupType):
type_id = 8001
slug = "metric_issue"
description = "Metric issue triggered"
category = GroupCategory.METRIC_ALERT.value
category_v2 = GroupCategory.METRIC.value
creation_quota = Quota(3600, 60, 100)
default_priority = PriorityLevel.HIGH
enable_auto_resolve = False
... | MetricIssue |
python | PyCQA__pylint | tests/testutils/test_output_line.py | {
"start": 546,
"end": 5195
} | class ____(Protocol):
def __call__(self, confidence: Confidence = HIGH) -> Message: ...
@pytest.fixture()
def message() -> _MessageCallable:
def inner(confidence: Confidence = HIGH) -> Message:
return Message(
symbol="missing-docstring",
msg_id="C0123",
location=Mes... | _MessageCallable |
python | sphinx-doc__sphinx | sphinx/addnodes.py | {
"start": 11120,
"end": 11257
} | class ____(desc_sig_element, _sig_element=True):
"""Node for a general keyword in a signature."""
classes = ['k']
| desc_sig_keyword |
python | tensorflow__tensorflow | tensorflow/python/keras/saving/utils_v1/mode_keys.py | {
"start": 798,
"end": 1260
} | class ____:
"""Standard names for model modes.
The following standard keys are defined:
* `TRAIN`: training/fitting mode.
* `TEST`: testing/evaluation mode.
* `PREDICT`: prediction/inference mode.
"""
TRAIN = 'train'
TEST = 'test'
PREDICT = 'predict'
def is_predict(mode):
return mode == KerasMo... | KerasModeKeys |
python | pytorch__pytorch | test/quantization/pt2e/test_representation.py | {
"start": 694,
"end": 10168
} | class ____(QuantizationTestCase):
def _test_representation(
self,
model: torch.nn.Module,
example_inputs: tuple[Any, ...],
quantizer: Quantizer,
ref_node_occurrence: dict[ns, int],
non_ref_node_occurrence: dict[ns, int],
fixed_output_tol: Optional[float] = Non... | TestPT2ERepresentation |
python | scipy__scipy | benchmarks/benchmarks/sparse.py | {
"start": 16372,
"end": 16959
} | class ____(Benchmark):
param_names = ['sparse_type', 'density', 'format']
params = [
['spmatrix', 'sparray'],
[0.05, 0.01],
['csr', 'csc', 'lil'],
]
def setup(self, sparse_type, density, format):
n = 500
k = 1000
if sparse_type == "sparray":
s... | Iteration |
python | plotly__plotly.py | plotly/graph_objs/contour/colorbar/_tickfont.py | {
"start": 233,
"end": 9918
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "contour.colorbar"
_path_str = "contour.colorbar.tickfont"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
... | Tickfont |
python | huggingface__transformers | src/transformers/models/vit/configuration_vit.py | {
"start": 794,
"end": 5556
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`ViTModel`]. It is used to instantiate an ViT
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuratio... | ViTConfig |
python | huggingface__transformers | src/transformers/integrations/fbgemm_fp8.py | {
"start": 1012,
"end": 3157
} | class ____(torch.nn.Linear):
def __init__(self, in_features, out_features, bias, weight_dtype=torch.float32):
super().__init__(in_features, out_features, bias)
self.in_features = in_features
self.out_features = out_features
self.weight = torch.nn.Parameter(torch.zeros((out_features,... | FbgemmFp8Linear |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 42215,
"end": 42780
} | class ____(sgqlc.types.Enum):
"""The state of an OAuth application when it was created.
Enumeration Choices:
* `ACTIVE`: The OAuth application was active and allowed to have
OAuth Accesses.
* `PENDING_DELETION`: The OAuth application was in the process of
being deleted.
* `SUSPENDED`: ... | OauthApplicationCreateAuditEntryState |
python | kamyu104__LeetCode-Solutions | Python/minimum-speed-to-arrive-on-time.py | {
"start": 58,
"end": 819
} | class ____(object):
def minSpeedOnTime(self, dist, hour):
"""
:type dist: List[int]
:type hour: float
:rtype: int
"""
def ceil(a, b):
return (a+b-1)//b
def total_time(dist, x):
return sum(ceil(dist[i], x) for i in xrange(len(dist)-1)) ... | Solution |
python | tornadoweb__tornado | tornado/test/httpclient_test.py | {
"start": 1642,
"end": 1848
} | class ____(RequestHandler):
def prepare(self):
# For testing error handling of a redirect with no location header.
self.set_status(301)
self.finish()
| RedirectWithoutLocationHandler |
python | bokeh__bokeh | src/bokeh/models/callbacks.py | {
"start": 8452,
"end": 9038
} | class ____(Callback):
""" Open a dialog box. """
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
dialog = Required(Instance(".models.ui.Dialog"), help="""
A dialog instance to open.
This will eithe... | OpenDialog |
python | django-haystack__django-haystack | test_haystack/spatial/models.py | {
"start": 48,
"end": 986
} | class ____(models.Model):
username = models.CharField(max_length=255)
# We're going to do some non-GeoDjango action, since the setup is
# complex enough. You could just as easily do:
#
# location = models.PointField()
#
# ...and your ``search_indexes.py`` could be less complex.
latitud... | Checkin |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/common/parameters.py | {
"start": 10943,
"end": 15628
} | class ____(BaseParam[T]):
"""Filter on attribute."""
def __init__(
self,
attribute: InstrumentedAttribute,
value: T | None = None,
filter_option: FilterOptionEnum = FilterOptionEnum.EQUAL,
skip_none: bool = True,
) -> None:
super().__init__(value, skip_none)
... | FilterParam |
python | allegroai__clearml | clearml/utilities/dicts.py | {
"start": 897,
"end": 1714
} | class ____(dict):
"""
Overloading getitem so that the 'data' copy is only done when the dictionary item is accessed.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
super(BlobsDict, self).__init__(*args, **kwargs)
def __getitem__(self, k: Any) -> Any:
val = super(BlobsDi... | BlobsDict |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/descriptor1.py | {
"start": 212,
"end": 1281
} | class ____:
@property
def prop1(self) -> int | None: ...
@prop1.setter
def prop1(self, val: int | None) -> None: ...
@property
def prop2(self) -> int | None: ...
@prop2.setter
def prop2(self, val: int) -> None: ...
@prop2.deleter
def prop2(self) -> None: ...
@property
... | A |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/links/test_glue.py | {
"start": 1170,
"end": 2170
} | class ____(BaseAwsLinksTestCase):
link_class = GlueJobRunDetailsLink
def test_extra_link(self, mock_supervisor_comms):
if AIRFLOW_V_3_0_PLUS and mock_supervisor_comms:
mock_supervisor_comms.send.return_value = XComResult(
key=self.link_class.key,
value={
... | TestGlueJobRunDetailsLink |
python | tensorflow__tensorflow | tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py | {
"start": 35194,
"end": 36576
} | class ____(test.TestCase):
def _validateInTopK(self, predictions, target, k, expected):
np_ans = np.array(expected, np.bool)
with self.cached_session(use_gpu=True) as _:
output = nn_ops.in_top_k(predictions, target, k)
nn_ans = self.evaluate(output)
self.assertAllEqual(np_ans, nn_ans)
... | InTopKTest |
python | pytorch__pytorch | test/distributed/tensor/test_dtensor_dispatch_overhead.py | {
"start": 2019,
"end": 5346
} | class ____(DTensorTestBase):
@property
def world_size(self) -> int:
return 4
@skip_if_lt_x_gpu(4)
@with_comms
def test_dtensor_add_op_dispatch_overhead(self):
if torch.cuda.is_available():
device_props = torch.cuda.get_device_name(0)
gpu_name = device_props
... | DistOpDispatchOverHead |
python | tiangolo__fastapi | tests/test_response_model_sub_types.py | {
"start": 128,
"end": 5379
} | class ____(BaseModel):
name: str
app = FastAPI()
@app.get("/valid1", responses={"500": {"model": int}})
def valid1():
pass
@app.get("/valid2", responses={"500": {"model": List[int]}})
def valid2():
pass
@app.get("/valid3", responses={"500": {"model": Model}})
def valid3():
pass
@app.get("/vali... | Model |
python | numba__numba | numba/tests/test_conditions_as_predicates.py | {
"start": 142,
"end": 5275
} | class ____(TestCase):
def test_scalars(self):
# checks that scalar types can be used as predicates
dts = [np.int8, np.uint16, np.int64, np.float32, np.float64,
np.complex128, int, float, complex, str, bool]
for dt in dts:
for c in 1, 0:
x = dt(c)
... | TestConditionsAsPredicates |
python | Netflix__metaflow | metaflow/plugins/airflow/airflow_decorator.py | {
"start": 516,
"end": 1781
} | class ____(StepDecorator):
name = "airflow_internal"
def task_pre_step(
self,
step_name,
task_datastore,
metadata,
run_id,
task_id,
flow,
graph,
retry_count,
max_user_code_retries,
ubf_context,
inputs,
):
... | AirflowInternalDecorator |
python | ansible__ansible | test/units/module_utils/basic/test_exit_json.py | {
"start": 3933,
"end": 7480
} | class ____:
"""
Test that ExitJson and FailJson remove password-like values
"""
OMIT = 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER'
DATA = (
(
dict(username='person', password='$ecret k3y'),
dict(one=1, pwd='$ecret k3y', url='https://username:password12345@foo.com/login/',
... | TestAnsibleModuleExitValuesRemoved |
python | django-extensions__django-extensions | tests/templatetags/test_syntax_color.py | {
"start": 227,
"end": 3652
} | class ____(TestCase):
"""Tests for syntax_color tags."""
@classmethod
def setUpClass(cls):
cls.tmpdir = mkdtemp()
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmpdir)
def test_should_generate_pygments_css_file_in_temp_directory(self):
generate_pygments_css(se... | SyntaxColorTagTests |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/quantization_test.py | {
"start": 988,
"end": 2075
} | class ____(op_bench.TorchBenchmarkBase):
r"""Benchmarks both quantization and dequantization."""
def init(self, C, M, N, dtype, mode):
assert mode in ("Q", "D")
self.input = torch.rand(C, M, N)
self.dtype = dtype
self.op = nnq.Quantize(scale=1.0, zero_point=0, dtype=dtype)
... | QuantizePerTensorBenchmark |
python | getsentry__sentry | src/sentry/users/services/user/model.py | {
"start": 540,
"end": 638
} | class ____(RpcModel):
id: int = 0
email: str = ""
is_verified: bool = False
| RpcUserEmail |
python | python-visualization__folium | folium/raster_layers.py | {
"start": 5597,
"end": 8143
} | class ____(Layer):
"""
Creates a Web Map Service (WMS) layer.
Parameters
----------
url : str
The url of the WMS server.
layers : str
Comma-separated list of WMS layers to show.
styles : str, optional
Comma-separated list of WMS styles.
fmt : str, default 'image/... | WmsTileLayer |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 59425,
"end": 61945
} | class ____:
# sfx is sf(x). The values were computed with mpmath:
#
# from mpmath import mp
# mp.dps = 100
# def halfnorm_sf(x):
# return 2*(1 - mp.ncdf(x))
#
# E.g.
#
# >>> float(halfnorm_sf(1))
# 0.3173105078629141
#
@pytest.mark.parametrize('x, sf... | TestHalfNorm |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1587558,
"end": 1587740
} | class ____(sgqlc.types.Union):
"""Used for return value of Repository.issueOrPullRequest."""
__schema__ = github_schema
__types__ = (Issue, PullRequest)
| IssueOrPullRequest |
python | numba__numba | numba/core/types/containers.py | {
"start": 14754,
"end": 15956
} | class ____(Container):
"""
Type class for homogeneous sets.
"""
mutable = True
def __init__(self, dtype, reflected=False):
assert isinstance(dtype, (Hashable, Undefined))
self.dtype = dtype
self.reflected = reflected
cls_name = "reflected set" if reflected else "set... | Set |
python | pydata__xarray | xarray/tests/test_backends.py | {
"start": 173115,
"end": 173626
} | class ____(ZarrBase):
@contextlib.contextmanager
def create_zarr_target(self):
# TODO the zarr version would need to be >3.08 for the supports_consolidated_metadata property to have any effect
yield NoConsolidatedMetadataSupportStore(
zarr.storage.MemoryStore({}, read_only=False)
... | TestZarrNoConsolidatedMetadataSupport |
python | google__jax | tests/pallas/fusion_test.py | {
"start": 8419,
"end": 8507
} | class ____:
x0: jax.Array
x1: jax.Array
@dataclasses.dataclass(frozen=True)
| ArrayTuple |
python | numba__llvmlite | llvmlite/ir/types.py | {
"start": 10737,
"end": 11008
} | class ____(_BaseFloatType):
"""
The type for single-precision floats.
"""
null = '0.0'
intrinsic_name = 'f32'
def __str__(self):
return 'float'
def format_constant(self, value):
return _format_double(_as_float(value))
| FloatType |
python | pandas-dev__pandas | pandas/core/computation/expr.py | {
"start": 23476,
"end": 23893
} | class ____(BaseExprVisitor):
def __init__(
self,
env,
engine,
parser,
preparser=partial(
_preparse,
f=_compose(_replace_locals, _replace_booleans, clean_backtick_quoted_toks),
),
) -> None:
super().__init__(env, engine, parser, prep... | PandasExprVisitor |
python | sqlalchemy__sqlalchemy | test/sql/test_labels.py | {
"start": 16901,
"end": 27183
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = "DefaultDialect"
table1 = table(
"some_large_named_table",
column("this_is_the_primarykey_column"),
column("this_is_the_data_column"),
)
table2 = table(
"table_with_exactly_29_characs",
column("thi... | LabelLengthTest |
python | getsentry__sentry | tests/sentry/issues/auto_source_code_config/test_process_event.py | {
"start": 2470,
"end": 10792
} | class ____(TestCase):
# We may only want to change this for TestTaskBehavior when we add support
# for other providers
provider = "github"
domain_name = "github.com"
def setUp(self) -> None:
self.integration = self.create_integration(
organization=self.organization,
... | BaseDeriveCodeMappings |
python | dagster-io__dagster | python_modules/libraries/dagster-pandas/dagster_pandas/constraints.py | {
"start": 3389,
"end": 4244
} | class ____(ConstraintViolationException):
"""Indicates that a column constraint has been violated."""
def __init__(self, constraint_name, constraint_description, column_name, offending_rows=None):
self.constraint_name = constraint_name
self.constraint_description = constraint_description
... | ColumnConstraintViolationException |
python | django__django | django/utils/autoreload.py | {
"start": 13343,
"end": 14719
} | class ____(BaseReloader):
SLEEP_TIME = 1 # Check for changes once per second.
def tick(self):
mtimes = {}
while True:
for filepath, mtime in self.snapshot_files():
old_time = mtimes.get(filepath)
mtimes[filepath] = mtime
if old_time i... | StatReloader |
python | davidhalter__jedi | test/completion/decorators.py | {
"start": 2762,
"end": 3032
} | class ____:
@not_found_decorator2
def a(self):
return 1
#? ['__call__']
JustAClass().a.__call__
#? int()
JustAClass().a()
#? ['__call__']
JustAClass.a.__call__
#? int()
JustAClass.a()
# -----------------
# illegal decorators
# -----------------
| JustAClass |
python | django__django | django/db/models/functions/window.py | {
"start": 1567,
"end": 2204
} | class ____(Func):
function = "NTH_VALUE"
window_compatible = True
def __init__(self, expression, nth=1, **extra):
if expression is None:
raise ValueError(
"%s requires a non-null source expression." % self.__class__.__name__
)
if nth is None or nth <=... | NthValue |
python | google__pytype | pytype/rewrite/abstract/functions_test.py | {
"start": 5375,
"end": 6407
} | class ____(test_utils.ContextfulTestBase):
def test_call(self):
f = functions.InterpreterFunction(
ctx=self.ctx, name='f', code=_get_const('def f(self): ...'),
enclosing_scope=(), parent_frame=FakeFrame(self.ctx))
callself = self.ctx.consts[42]
bound_f = f.bind_to(callself)
frame = bo... | BoundFunctionTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.