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 | dagster-io__dagster | python_modules/libraries/dagster-shared/dagster_shared/serdes/serdes.py | {
"start": 20968,
"end": 21057
} | class ____(ABC):
pass
T_Enum = TypeVar("T_Enum", bound=Enum, default=Enum)
| Serializer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 58939,
"end": 59291
} | class ____(sgqlc.types.Enum):
"""Various content states of a ProjectCard
Enumeration Choices:
* `CONTENT_ONLY`: The card has content only.
* `NOTE_ONLY`: The card has a note only.
* `REDACTED`: The card is redacted.
"""
__schema__ = github_schema
__choices__ = ("CONTENT_ONLY", "NOTE_O... | ProjectCardState |
python | eriklindernoren__ML-From-Scratch | mlfromscratch/unsupervised_learning/apriori.py | {
"start": 86,
"end": 313
} | class ____():
def __init__(self, antecedent, concequent, confidence, support):
self.antecedent = antecedent
self.concequent = concequent
self.confidence = confidence
self.support = support
| Rule |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 1015412,
"end": 1016103
} | class ____(ValueChannelMixin, core.ValueDefnumber):
"""
XError2Value schema wrapper.
Definition object for a constant value (primitive value or gradient definition) of an
encoding channel.
Parameters
----------
value : float
A constant value in visual domain (e.g., ``"red"`` / ``"#... | XError2Value |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 337173,
"end": 358803
} | class ____(Request):
"""
Get all the company's tasks and all public tasks
:param id: List of IDs to filter by
:type id: Sequence[str]
:param name: Get only tasks whose name matches this pattern (python regular
expression syntax)
:type name: str
:param user: List of user IDs used to ... | GetAllRequest |
python | pytorch__pytorch | test/cpp/aoti_inference/test.py | {
"start": 559,
"end": 6579
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.w = torch.randn(30, 1, device="cuda")
def forward(self, x, y):
z = self.w * x * y
return z[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17]]
data = {}
large_data = {}
cuda_alloc_data = {... | NetWithTensorConstants |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol41.py | {
"start": 649,
"end": 744
} | class ____(Protocol[_T_contra]):
def write(self, __s: _T_contra) -> object: ...
| SupportsWrite |
python | doocs__leetcode | solution/0000-0099/0014.Longest Common Prefix/Solution.py | {
"start": 0,
"end": 254
} | class ____:
def longestCommonPrefix(self, strs: List[str]) -> str:
for i in range(len(strs[0])):
for s in strs[1:]:
if len(s) <= i or s[i] != strs[0][i]:
return s[:i]
return strs[0]
| Solution |
python | getsentry__sentry | src/sentry/users/models/userpermission.py | {
"start": 663,
"end": 2709
} | class ____(OverwritableConfigMixin, ControlOutboxProducingModel):
"""
Permissions are applied to administrative users and control explicit scope-like permissions within the API.
Generally speaking, they should only apply to active superuser sessions.
"""
__relocation_scope__ = RelocationScope.Conf... | UserPermission |
python | tiangolo__fastapi | scripts/contributors.py | {
"start": 1712,
"end": 1778
} | class ____(BaseModel):
edges: list[PullRequestEdge]
| PullRequests |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 70937,
"end": 71985
} | class ____(Elemwise):
"""Column Selection"""
_parameters = ["frame"]
operation = getattr
@functools.cached_property
def _meta(self):
meta = self.frame._meta
# Handle scalar results
if is_series_like(meta) or is_dataframe_like(meta):
return self.frame._meta.index... | Index |
python | apache__airflow | providers/presto/tests/unit/presto/transfers/test_gcs_to_presto.py | {
"start": 1237,
"end": 5612
} | class ____:
@mock.patch("airflow.providers.presto.transfers.gcs_to_presto.PrestoHook")
@mock.patch("airflow.providers.presto.transfers.gcs_to_presto.GCSHook")
@mock.patch("airflow.providers.presto.transfers.gcs_to_presto.NamedTemporaryFile")
def test_execute_without_schema(self, mock_tempfile, mock_gcs_... | TestGCSToPrestoOperator |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 16551,
"end": 16733
} | class ____(PydanticValueError):
code = 'payment_card_number.invalid_length_for_brand'
msg_template = 'Length for a {brand} card must be {required_length}'
| InvalidLengthForBrand |
python | bottlepy__bottle | bottle.py | {
"start": 6442,
"end": 6891
} | class ____:
""" A property that is only computed once per instance and then replaces
itself with an ordinary attribute. Deleting the attribute resets the
property. """
def __init__(self, func):
update_wrapper(self, func)
self.func = func
def __get__(self, obj, cls):
... | cached_property |
python | viewflow__viewflow | tests/workflow/test_flow_viewset__flow.py | {
"start": 3432,
"end": 3578
} | class ____(Flow):
process_class = TestFlowViewestProcess
start = flow.StartHandle().Next(this.end)
end = flow.End()
| TestFlowViewestFlow |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_pure_fp16.py | {
"start": 990,
"end": 5520
} | class ____(FSDPTest):
@skip_if_lt_x_gpu(2)
def test_pure_fp16_training(self):
"""Tests pure FP16 training, including when the parameter's dtype is
changed after FSDP initialization and before training."""
self.run_subtests(
{
"cpu_offload": [
... | TestPureFP16 |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/schedules/base.py | {
"start": 753,
"end": 7439
} | class ____(abc.ABC, MayHaveInstanceWeakref[T_DagsterInstance]):
"""Abstract class for managing persistance of scheduler artifacts."""
@abc.abstractmethod
def wipe(self) -> None:
"""Delete all schedules from storage."""
@abc.abstractmethod
def all_instigator_state(
self,
rep... | ScheduleStorage |
python | pyparsing__pyparsing | pyparsing/core.py | {
"start": 148186,
"end": 148348
} | class ____(Token):
def __init__(self) -> None:
super().__init__()
self._may_return_empty = True
self.mayIndexError = False
| PositionToken |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/sticky_variant_dependent/package.py | {
"start": 227,
"end": 604
} | class ____(AutotoolsPackage):
"""Package with a sticky variant and a conflict"""
homepage = "http://www.example.com"
url = "http://www.example.com/a-1.0.tar.gz"
version("1.0", md5="0123456789abcdef0123456789abcdef")
depends_on("sticky-variant")
conflicts("%gcc", when="^sticky-variant~allow-gc... | StickyVariantDependent |
python | django__django | tests/postgres_tests/test_operations.py | {
"start": 1140,
"end": 6910
} | class ____(OptimizerTestBase, OperationTestBase):
app_label = "test_add_concurrently"
def test_requires_atomic_false(self):
project_state = self.set_up_test_model(self.app_label)
new_state = project_state.clone()
operation = AddIndexConcurrently(
"Pony",
Index(fi... | AddIndexConcurrentlyTests |
python | astropy__astropy | astropy/io/ascii/core.py | {
"start": 13513,
"end": 18004
} | class ____(BaseSplitter):
"""Default class to split strings into columns using python csv. The class
attributes are taken from the csv Dialect class.
Typical usage::
# lines = ..
splitter = ascii.DefaultSplitter()
for col_vals in splitter(lines):
for col_val in col_vals:
... | DefaultSplitter |
python | coleifer__peewee | tests/regressions.py | {
"start": 18705,
"end": 18812
} | class ____(BaseVersionedModel):
user = ForeignKeyField(VUser, null=True)
content = TextField()
| VTweet |
python | pennersr__django-allauth | allauth/mfa/migrations/0001_initial.py | {
"start": 159,
"end": 1486
} | class ____(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="Authenticator",
fields=[
(
"id",
m... | Migration |
python | tornadoweb__tornado | tornado/test/queues_test.py | {
"start": 2525,
"end": 5987
} | class ____(AsyncTestCase):
@gen_test
def test_blocking_get(self):
q = queues.Queue() # type: queues.Queue[int]
q.put_nowait(0)
self.assertEqual(0, (yield q.get()))
def test_nonblocking_get(self):
q = queues.Queue() # type: queues.Queue[int]
q.put_nowait(0)
... | QueueGetTest |
python | cherrypy__cherrypy | cherrypy/test/test_conn.py | {
"start": 17832,
"end": 27560
} | class ____(helper.CPWebCase):
setup_server = staticmethod(setup_server)
def test_readall_or_close(self):
if cherrypy.server.protocol_version != 'HTTP/1.1':
return self.skip()
self.PROTOCOL = 'HTTP/1.1'
if self.scheme == 'https':
self.HTTP_CONN = HTTPSConnection... | ConnectionTests |
python | bokeh__bokeh | src/bokeh/embed/bundle.py | {
"start": 2584,
"end": 7454
} | class ____:
js_files: list[URL]
js_raw: list[str]
css_files: list[URL]
css_raw: list[str]
hashes: Hashes
def __init__(self, js_files: list[URL] = [], js_raw: list[str] = [],
css_files: list[URL] = [], css_raw: list[str] = [], hashes: Hashes = {}):
self.js_files = js_files[:... | Bundle |
python | wandb__wandb | wandb/sdk/data_types/audio.py | {
"start": 6385,
"end": 6508
} | class ____(_dtypes.Type):
name = "audio-file"
types = [Audio]
_dtypes.TypeRegistry.add(_AudioFileType)
| _AudioFileType |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/callpath/package.py | {
"start": 217,
"end": 838
} | class ____(Package):
homepage = "https://github.com/tgamblin/callpath"
url = "http://github.com/tgamblin/callpath-1.0.tar.gz"
version("0.8", md5="0123456789abcdef0123456789abcdef")
version("0.9", md5="0123456789abcdef0123456789abcdef")
version("1.0", md5="0123456789abcdef0123456789abcdef")
dep... | Callpath |
python | psf__black | src/black/trans.py | {
"start": 13455,
"end": 31200
} | class ____(StringTransformer, CustomSplitMapMixin):
"""StringTransformer that merges strings together.
Requirements:
(A) The line contains adjacent strings such that ALL of the validation checks
listed in StringMerger._validate_msg(...)'s docstring pass.
OR
(B) The line contains... | StringMerger |
python | pytorch__pytorch | torch/testing/_internal/common_utils.py | {
"start": 119932,
"end": 193296
} | class ____(expecttest.TestCase):
# NOTE: "precision" lets classes and generated tests set minimum
# atol values when comparing tensors. Used by @precisionOverride and @toleranceOverride, for
# example.
# NOTE: "rel_tol" lets classes and generated tests set minimum
# rtol values when comparing tensor... | TestCase |
python | qdrant__qdrant-client | qdrant_client/grpc/collections_service_pb2_grpc.py | {
"start": 12768,
"end": 21674
} | class ____(object):
"""Missing associated documentation comment in .proto file."""
@staticmethod
def Get(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_f... | Collections |
python | apache__airflow | providers/fab/src/airflow/providers/fab/auth_manager/api_fastapi/datamodels/roles.py | {
"start": 1040,
"end": 1141
} | class ____(BaseModel):
"""Outgoing representation of a resource."""
name: str
| ResourceResponse |
python | huggingface__transformers | src/transformers/models/esm/modeling_esm.py | {
"start": 17475,
"end": 19666
} | class ____(GradientCheckpointingLayer):
def __init__(self, config):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = EsmAttention(config)
self.is_decoder = config.is_decoder
self.add_cross_attention... | EsmLayer |
python | django-guardian__django-guardian | example_project_custom_group/articles/migrations/0002_initial.py | {
"start": 159,
"end": 4302
} | class ____(migrations.Migration):
initial = True
dependencies = [
("auth", "0012_alter_user_first_name_max_length"),
("contenttypes", "0002_remove_content_type_name"),
("articles", "0001_initial"),
("core", "0001_initial"),
migrations.swappable_dependency(settings.AUTH_U... | Migration |
python | huggingface__transformers | src/transformers/models/maskformer/modeling_maskformer_swin.py | {
"start": 18071,
"end": 18614
} | class ____(nn.Module):
def __init__(self, config, dim):
super().__init__()
self.dense = nn.Linear(dim, dim)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
hidden_states = ... | MaskFormerSwinSelfOutput |
python | fastapi__sqlmodel | docs_src/tutorial/connect/select/tutorial001_py310.py | {
"start": 222,
"end": 2153
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: int | None = Field(default=None, index=True)
team_id: int | None = Field(default=None, foreign_key="team.id")
sqlite_file_name = "database.db"
sqlite_url = ... | Hero |
python | getsentry__sentry | tests/sentry/integrations/github/test_client.py | {
"start": 51926,
"end": 68440
} | class ____(GitHubClientFileBlameBase):
"""
Tests that get_blame_for_files handles the GraphQL response correctly
"""
def setUp(self) -> None:
super().setUp()
self.file1 = SourceLineInfo(
path="src/sentry/integrations/github/client_1.py",
lineno=10,
r... | GitHubClientFileBlameResponseTest |
python | eriklindernoren__ML-From-Scratch | mlfromscratch/supervised_learning/regression.py | {
"start": 9136,
"end": 10499
} | class ____(Regression):
""" Regression where a combination of l1 and l2 regularization are used. The
ratio of their contributions are set with the 'l1_ratio' parameter.
Parameters:
-----------
degree: int
The degree of the polynomial that the independent variable X will be transformed to.
... | ElasticNet |
python | doocs__leetcode | solution/1000-1099/1031.Maximum Sum of Two Non-Overlapping Subarrays/Solution.py | {
"start": 0,
"end": 586
} | class ____:
def maxSumTwoNoOverlap(self, nums: List[int], firstLen: int, secondLen: int) -> int:
n = len(nums)
s = list(accumulate(nums, initial=0))
ans = t = 0
i = firstLen
while i + secondLen - 1 < n:
t = max(t, s[i] - s[i - firstLen])
ans = max(ans,... | Solution |
python | explosion__spaCy | spacy/lang/id/__init__.py | {
"start": 302,
"end": 593
} | class ____(BaseDefaults):
tokenizer_exceptions = TOKENIZER_EXCEPTIONS
prefixes = TOKENIZER_PREFIXES
suffixes = TOKENIZER_SUFFIXES
infixes = TOKENIZER_INFIXES
syntax_iterators = SYNTAX_ITERATORS
lex_attr_getters = LEX_ATTRS
stop_words = STOP_WORDS
| IndonesianDefaults |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/pooling.py | {
"start": 23904,
"end": 27848
} | class ____(Layer):
"""Pooling layer for arbitrary pooling functions, for 3D inputs.
This class only exists for code reuse. It will never be an exposed API.
Args:
pool_function: The pooling function to apply, e.g. `tf.nn.max_pool2d`.
pool_size: An integer or tuple/list of 3 integers:
(pool_depth, p... | Pooling3D |
python | realpython__materials | python-serialize/http-payload/django-rest-api/rest_api/apps.py | {
"start": 36,
"end": 147
} | class ____(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "rest_api"
| RestApiConfig |
python | ray-project__ray | rllib/examples/offline_rl/classes/image_offline_prelearner.py | {
"start": 601,
"end": 3734
} | class ____(OfflinePreLearner):
"""This class transforms image data to `MultiAgentBatch`es.
While the `ImageOfflineData` class transforms raw image
bytes to `numpy` arrays, this class maps these data in
`SingleAgentEpisode` instances through the learner connector
pipeline and finally outputs a >`Mul... | ImageOfflinePreLearner |
python | pyqtgraph__pyqtgraph | pyqtgraph/parametertree/parameterTypes/basetypes.py | {
"start": 9380,
"end": 10482
} | class ____(Parameter):
"""
Parameter representing a single value.
This parameter is backed by :class:`~pyqtgraph.parametertree.parameterTypes.basetypes.WidgetParameterItem`
to represent the following parameter names through various subclasses:
- 'int'
- 'float'
- 'bool'
- 'str... | SimpleParameter |
python | scipy__scipy | scipy/io/_harwell_boeing/_fortran_format_parser.py | {
"start": 2427,
"end": 4632
} | class ____:
@classmethod
def from_number(cls, n, min=None):
"""Given a float number, returns a "reasonable" ExpFormat instance to
represent any number between -n and n.
Parameters
----------
n : float
max number one wants to be able to represent
min :... | ExpFormat |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/recursiveTypeAlias8.py | {
"start": 371,
"end": 806
} | class ____(TypedDict):
options: list[CorD]
type: int
CorD = ClassC | ClassD
def foo(a: CorD):
reveal_type(a, expected_text="ClassC | ClassD")
options = a.get("options", [])
reveal_type(options, expected_text="list[ClassC | ClassD] | Any | list[Any]")
for option in options:
reveal_ty... | ClassD |
python | ray-project__ray | rllib/policy/tf_mixins.py | {
"start": 2530,
"end": 4735
} | class ____:
"""Mixin for TFPolicy that adds entropy coeff decay."""
def __init__(self, entropy_coeff, entropy_coeff_schedule):
self._entropy_coeff_schedule = None
if entropy_coeff_schedule is None:
self.entropy_coeff = get_variable(
entropy_coeff, framework="tf", tf_... | EntropyCoeffSchedule |
python | plotly__plotly.py | plotly/graph_objs/layout/scene/camera/_up.py | {
"start": 235,
"end": 2878
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.scene.camera"
_path_str = "layout.scene.camera.up"
_valid_props = {"x", "y", "z"}
@property
def x(self):
"""
The 'x' property is a number and may be specified as:
- An int or float
Returns
--... | Up |
python | wepe__MachineLearning | DeepLearning Tutorials/cnn_LeNet/convolutional_mlp_commentate.py | {
"start": 980,
"end": 3363
} | class ____(object):
def __init__(self, rng, input, filter_shape, image_shape, poolsize=(2, 2)):
#assert condition,condition为True,则继续往下执行,condition为False,中断程序
#image_shape[1]和filter_shape[1]都是num input feature maps,它们必须是一样的。
assert image_shape[1] == filter_shape[1]
self.input = input
#每个隐层神经元(即像素... | LeNetConvPoolLayer |
python | tiangolo__fastapi | docs_src/body/tutorial003.py | {
"start": 87,
"end": 362
} | class ____(BaseModel):
name: str
description: Union[str, None] = None
price: float
tax: Union[float, None] = None
app = FastAPI()
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
return {"item_id": item_id, **item.dict()}
| Item |
python | allegroai__clearml | clearml/utilities/proxy_object.py | {
"start": 11077,
"end": 14687
} | class ____(type):
# This metaclass is heavily inspired by the Object Proxying python recipe
# (http://code.activestate.com/recipes/496741/). It adds special methods
# to the wrapper class so it can proxy the wrapped class. In addition, it
# adds a field __overrides__ in the wrapper class dictionary, con... | WrapperBase |
python | huggingface__transformers | src/transformers/models/vitdet/modeling_vitdet.py | {
"start": 27237,
"end": 29902
} | class ____(VitDetPreTrainedModel, BackboneMixin):
def __init__(self, config):
super().__init__(config)
super()._init_backbone(config)
self.embeddings = VitDetEmbeddings(config)
self.encoder = VitDetEncoder(config)
self.num_features = [config.hidden_size for _ in range(config... | VitDetBackbone |
python | pypa__warehouse | tests/common/db/subscriptions.py | {
"start": 713,
"end": 1006
} | class ____(WarehouseFactory):
class Meta:
model = StripeSubscriptionProduct
id = factory.Faker("uuid4", cast_to=None)
product_id = "prod_123"
product_name = factory.Faker("pystr", max_chars=12)
description = factory.Faker("sentence")
| StripeSubscriptionProductFactory |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/stack_test.py | {
"start": 1561,
"end": 2675
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, sizes, N, dim, device):
random.seed(42)
inputs = []
gen_sizes = []
if type(sizes) is list and N == -1:
gen_sizes = sizes
else:
for i in range(N):
gen_sizes.append(
... | StackBenchmark |
python | google__jax | jax/_src/pallas/fuser/block_spec.py | {
"start": 1697,
"end": 2261
} | class ____:
avals_in: tuple[core.AbstractValue, ...]
avals_out: tuple[core.AbstractValue, ...]
out_usages: tuple[set[Usage], ...]
eval_function: Any = dataclasses.field(default=None, init=False)
scalar_prefetch_fn: Any = dataclasses.field(default=None, init=False)
scalar_prefetch_handler: Any | None
grid:... | PullRuleContext |
python | getsentry__sentry | src/sentry/discover/endpoints/discover_saved_query_detail.py | {
"start": 6094,
"end": 6808
} | class ____(DiscoverSavedQueryBase):
publish_status = {
"POST": ApiPublishStatus.PRIVATE,
}
def has_feature(self, organization, request):
return features.has("organizations:discover-query", organization, actor=request.user)
def post(self, request: Request, organization, query) -> Respon... | DiscoverSavedQueryVisitEndpoint |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events_spans_performance.py | {
"start": 39165,
"end": 61703
} | class ____(OrganizationEventsSpansEndpointTestBase):
URL = "sentry-api-0-organization-events-spans"
def test_no_projects(self) -> None:
user = self.create_user()
org = self.create_organization(owner=user)
self.login_as(user=user)
url = reverse(
self.URL,
... | OrganizationEventsSpansExamplesEndpointTest |
python | pyparsing__pyparsing | tests/test_unit.py | {
"start": 391152,
"end": 391811
} | class ____(Test02_WithoutPackrat):
"""
rerun Test2 tests, now that packrat is enabled
"""
def test000_assert_packrat_status(self):
print("Packrat enabled:", ParserElement._packratEnabled)
print(
"Packrat cache:",
type(ParserElement.packrat_cache).__name__,
... | Test04_WithPackrat |
python | pypa__setuptools | setuptools/_vendor/packaging/_tokenizer.py | {
"start": 2128,
"end": 5273
} | class ____:
"""Context-sensitive token parsing.
Provides methods to examine the input stream to check whether the next token
matches.
"""
def __init__(
self,
source: str,
*,
rules: dict[str, str | re.Pattern[str]],
) -> None:
self.source = source
... | Tokenizer |
python | facebook__pyre-check | client/language_server/code_navigation_request.py | {
"start": 1189,
"end": 1472
} | class ____(json_mixins.CamlCaseAndExcludeJsonMixin):
errors: List[Dict[str, Any]]
def to_errors_response(self) -> List[error.Error]:
return [error.Error.from_json(error_response) for error_response in self.errors]
@dataclasses.dataclass(frozen=True)
| TypeErrorsResponse |
python | walkccc__LeetCode | solutions/2104. Sum of Subarray Ranges/2104.py | {
"start": 0,
"end": 893
} | class ____:
def subArrayRanges(self, nums: list[int]) -> int:
prevGt, nextGt = self._getPrevNext(nums, operator.lt)
prevLt, nextLt = self._getPrevNext(nums, operator.gt)
return sum(num * (i - prevGt[i]) * (nextGt[i] - i) -
num * (i - prevLt[i]) * (nextLt[i] - i)
for i, num in... | Solution |
python | executablebooks__jupyter-book | py/jupyter_book/nodeenv.py | {
"start": 230,
"end": 3219
} | class ____(Exception): ...
def is_windows():
return platform.system() == "Windows"
def get_triple_node_version(node_path):
# Check version
_version = subprocess.run(
[node_path, "-v"], capture_output=True, check=True, text=True
).stdout
match = re.match(r"^v(\d+)\.(\d+)\.(\d+).*$", _vers... | NodeVersionError |
python | pypa__warehouse | warehouse/ip_addresses/models.py | {
"start": 356,
"end": 442
} | class ____(enum.Enum):
AUTHENTICATION_ATTEMPTS = "authentication-attempts"
| BanReason |
python | PrefectHQ__prefect | tests/blocks/test_notifications.py | {
"start": 11878,
"end": 14852
} | class ____:
API_KEY = "api_key"
async def test_notify_async(self):
with patch("apprise.Apprise", autospec=True) as AppriseMock:
apprise_instance_mock = AppriseMock.return_value
apprise_instance_mock.async_notify = AsyncMock()
block = OpsgenieWebhook(apikey=self.API_... | TestOpsgenieWebhook |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_task_instances.py | {
"start": 132723,
"end": 151153
} | class ____(TestTaskInstanceEndpoint):
def test_should_respond_200(self, test_client, session):
self.create_task_instances(
session=session, task_instances=[{"state": State.SUCCESS}], with_ti_history=True
)
with assert_queries_count(3):
response = test_client.get(
... | TestGetTaskInstanceTries |
python | coleifer__peewee | peewee.py | {
"start": 221242,
"end": 222021
} | class ____(object):
def __init__(self, models, database, bind_refs, bind_backrefs):
self.models = models
self.database = database
self.bind_refs = bind_refs
self.bind_backrefs = bind_backrefs
def __enter__(self):
self._orig_database = []
for model in self.models:... | _BoundModelsContext |
python | cython__cython | Cython/Compiler/TypeSlots.py | {
"start": 15197,
"end": 16351
} | class ____(InternalMethodSlot):
# Descriptor for a slot whose value depends on whether
# the type participates in GC.
def __init__(self, slot_name, **kargs):
InternalMethodSlot.__init__(self, slot_name, **kargs)
def slot_code(self, scope):
# We treat external types as needing gc, but... | GCDependentSlot |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1140843,
"end": 1141875
} | class ____(ScaleInvalidDataShowAssize):
"""
ScaleInvalidDataShowAsValuesize schema wrapper.
Parameters
----------
value : float
Default size for marks.
* For ``point``/``circle``/``square``, this represents the pixel area of the marks.
Note that this value sets the area o... | ScaleInvalidDataShowAsValuesize |
python | astropy__astropy | astropy/units/function/logarithmic.py | {
"start": 15307,
"end": 15363
} | class ____(LogQuantity):
_unit_class = MagUnit
| Magnitude |
python | doocs__leetcode | lcp/LCP 05. 发 LeetCoin/Solution.py | {
"start": 1766,
"end": 2592
} | class ____:
def bonus(
self, n: int, leadership: List[List[int]], operations: List[List[int]]
) -> List[int]:
def dfs(u):
nonlocal idx
begin[u] = idx
for v in g[u]:
dfs(v)
end[u] = idx
idx += 1
g = defaultdict(l... | Solution |
python | pytorch__pytorch | torch/distributed/debug/_frontend.py | {
"start": 7250,
"end": 11105
} | class ____:
def __init__(self, port: int):
# Setup templates
loader = DictLoader(templates)
self._jinja_env = Environment(loader=loader, enable_async=True)
self._jinja_env.globals.update(
zip=zip,
format_json=format_json,
enumerate=enumerate,
... | FrontendServer |
python | milvus-io__pymilvus | pymilvus/bulk_writer/local_bulk_writer.py | {
"start": 928,
"end": 5154
} | class ____(BulkWriter):
def __init__(
self,
schema: CollectionSchema,
local_path: str,
chunk_size: int = 128 * MB,
file_type: BulkFileType = BulkFileType.PARQUET,
config: Optional[dict] = None,
**kwargs,
):
super().__init__(schema, chunk_size, file... | LocalBulkWriter |
python | getsentry__sentry | src/sentry/integrations/slack/analytics.py | {
"start": 1184,
"end": 1414
} | class ____(analytics.Event):
organization_id: int
actor_id: int
invitation_type: str
invited_member_id: int
@analytics.eventclass("integrations.slack.reject_member_invitation")
| SlackIntegrationApproveMemberInvitation |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/streams.py | {
"start": 56929,
"end": 60360
} | class ____(GithubStream):
"""
API docs: https://docs.github.com/en/rest/projects/columns?apiVersion=2022-11-28#list-project-columns
"""
use_cache = True
cursor_field = "updated_at"
def __init__(self, parent: HttpStream, start_date: str, **kwargs):
super().__init__(**kwargs)
sel... | ProjectColumns |
python | tensorflow__tensorflow | tensorflow/python/distribute/cross_device_ops.py | {
"start": 39352,
"end": 40467
} | class ____(AllReduceCrossDeviceOps):
"""NCCL all-reduce implementation of CrossDeviceOps.
It uses Nvidia NCCL for all-reduce. For the batch API, tensors will be
repacked or aggregated for more efficient cross-device transportation.
For reduces that are not all-reduce, it falls back to
`tf.distribute.Reducti... | NcclAllReduce |
python | numpy__numpy | numpy/_core/tests/test_abc.py | {
"start": 116,
"end": 2221
} | class ____:
def test_abstract(self):
assert_(issubclass(np.number, numbers.Number))
assert_(issubclass(np.inexact, numbers.Complex))
assert_(issubclass(np.complexfloating, numbers.Complex))
assert_(issubclass(np.floating, numbers.Real))
assert_(issubclass(np.integer, number... | TestABC |
python | scikit-learn__scikit-learn | sklearn/exceptions.py | {
"start": 1895,
"end": 2061
} | class ____(UserWarning):
"""Custom warning to capture convergence problems
.. versionchanged:: 0.18
Moved from sklearn.utils.
"""
| ConvergenceWarning |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 4771,
"end": 4869
} | class ____(HistoryManager):
def low_ids(self):
return self.filter(id__lte=3)
| PollManager |
python | django__django | tests/queries/models.py | {
"start": 13985,
"end": 14090
} | class ____(models.Model):
text = models.TextField()
page = models.ManyToManyField("Page")
| Paragraph |
python | sympy__sympy | sympy/physics/biomechanics/tests/test_curve.py | {
"start": 27149,
"end": 35041
} | class ____:
@pytest.fixture(autouse=True)
def _fiber_force_length_passive_arguments_fixture(self):
self.fl_M_pas = Symbol('fl_M_pas')
self.c0 = Symbol('c_0')
self.c1 = Symbol('c_1')
self.constants = (self.c0, self.c1)
@staticmethod
def test_class():
assert issub... | TestFiberForceLengthPassiveInverseDeGroote2016 |
python | wandb__wandb | tests/fixtures/wandb_backend_spy/spy.py | {
"start": 14840,
"end": 15417
} | class ____:
def __init__(self) -> None:
# See docs on WandbBackendSnapshot methods.
self._was_ever_preempting = False
self._uploaded_files: set[str] = set()
self._file_stream_files: dict[str, dict[int, str]] = {}
self._config_json_string: str | None = None
self._tags:... | _RunData |
python | pandas-dev__pandas | pandas/tests/frame/indexing/test_setitem.py | {
"start": 43974,
"end": 53181
} | class ____:
def test_setitem_always_copy(self, float_frame):
assert "E" not in float_frame.columns
s = float_frame["A"].copy()
float_frame["E"] = s
float_frame.iloc[5:10, float_frame.columns.get_loc("E")] = np.nan
assert notna(s[5:10]).all()
@pytest.mark.parametrize("co... | TestDataFrameSetitemCopyViewSemantics |
python | apache__airflow | task-sdk/src/airflow/sdk/api/datamodels/_generated.py | {
"start": 11601,
"end": 11955
} | class ____(RootModel[list[JsonValue]]):
"""
XCom schema with minimal structure for slice-based access.
"""
root: Annotated[
list[JsonValue],
Field(
description="XCom schema with minimal structure for slice-based access.",
title="XComSequenceSliceResponse",
... | XComSequenceSliceResponse |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 234696,
"end": 240587
} | class ____(Request):
"""
Delete tasks
:param ids: IDs of the tasks to delete
:type ids: Sequence[str]
:param move_to_trash: Move task to trash instead of deleting it. For internal
use only, tasks in the trash are not visible from the API and cannot be
restored!
:type move_to_tra... | DeleteManyRequest |
python | Textualize__textual | src/textual/demo/widgets.py | {
"start": 22484,
"end": 23782
} | class ____(PageScreen):
"""The Widgets screen"""
CSS = """
WidgetsScreen {
align-horizontal: center;
Markdown { background: transparent; }
& > VerticalScroll {
scrollbar-gutter: stable;
& > * {
&:even { background: $... | WidgetsScreen |
python | pypa__setuptools | pkg_resources/__init__.py | {
"start": 65056,
"end": 65991
} | class ____(EggProvider):
"""Provides access to package resources in the filesystem"""
def _has(self, path) -> bool:
return os.path.exists(path)
def _isdir(self, path) -> bool:
return os.path.isdir(path)
def _listdir(self, path):
return os.listdir(path)
def get_resource_st... | DefaultProvider |
python | scipy__scipy | scipy/optimize/_hessian_update_strategy.py | {
"start": 16302,
"end": 18423
} | class ____(FullHessianUpdateStrategy):
"""Symmetric-rank-1 Hessian update strategy.
Parameters
----------
min_denominator : float
This number, scaled by a normalization factor,
defines the minimum denominator magnitude allowed
in the update. When the condition is violated we ski... | SR1 |
python | keras-team__keras | keras/src/optimizers/adamax_test.py | {
"start": 172,
"end": 3190
} | class ____(testing.TestCase):
def test_config(self):
optimizer = Adamax(
learning_rate=0.5,
beta_1=0.8,
beta_2=0.95,
epsilon=1e-5,
)
self.run_class_serialization_test(optimizer)
def test_single_step(self):
optimizer = Adamax(learni... | AdamaxTest |
python | aio-libs__aiohttp | aiohttp/web_exceptions.py | {
"start": 4868,
"end": 4922
} | class ____(HTTPSuccessful):
status_code = 200
| HTTPOk |
python | django-compressor__django-compressor | compressor/tests/test_offline.py | {
"start": 3074,
"end": 9847
} | class ____:
CHARSET = "utf-8"
template_name = "test_compressor_offline.html"
# Change this for each test class
templates_dir = ""
expected_basename = "output"
expected_hash = ""
# Engines to test
engines = ("django", "jinja2")
additional_test_settings = None
def setUp(self):
... | OfflineTestCaseMixin |
python | matplotlib__matplotlib | lib/mpl_toolkits/axes_grid1/axes_size.py | {
"start": 3597,
"end": 4365
} | class ____(_Base):
"""
Scaled size whose relative part corresponds to the data height
of the *axes* multiplied by the *aspect*.
"""
def __init__(self, axes, aspect=1., ref_ax=None):
self._axes = axes
self._aspect = aspect
if aspect == "axes" and ref_ax is None:
r... | AxesY |
python | ray-project__ray | python/ray/air/_internal/device_manager/nvidia_gpu.py | {
"start": 154,
"end": 2993
} | class ____(TorchDeviceManager):
"""CUDA device manager"""
def is_available(self) -> bool():
return torch.cuda.is_available()
def get_devices(self) -> List[torch.device]:
"""Gets the correct torch device list configured for this process.
Returns a list of torch CUDA devices allocat... | CUDATorchDeviceManager |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_overridden_method.py | {
"start": 1276,
"end": 1861
} | class ____:
@property
@abc.abstractmethod
def prop(self):
return
# https://github.com/pylint-dev/pylint/issues/4368
# Decrator functions with a nested property decorator should still be
# inferred as property.
def my_property(func):
@property
def _wrapper(self):
pass
return _... | AbstractProperty |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 971382,
"end": 972102
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for Sponsor."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("SponsorEdge"), graphql_name="edges")
"""A list of edges."""
nodes = sgqlc.... | SponsorConnection |
python | kubernetes-client__python | kubernetes/client/models/v1beta2_device_constraint.py | {
"start": 383,
"end": 8480
} | 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... | V1beta2DeviceConstraint |
python | PyCQA__pylint | tests/functional/m/method_cache_max_size_none.py | {
"start": 401,
"end": 1437
} | class ____:
@lru_cache()
def my_func(self, param):
return param + 1
@lru_cache(1)
def my_func(self, param):
return param + 1
@lru_cache(None) # [method-cache-max-size-none]
def my_func(self, param):
return param + 1
@functools.lru_cache(None) # [method-cache-max-... | MyClassWithMethods |
python | pytorch__pytorch | test/inductor/test_ordered_set.py | {
"start": 46331,
"end": 46584
} | class ____(TestSubsets, TestCase):
left = OrderedSet([1])
right = OrderedSet([2])
name = "neither empty, neither contains"
cases = "!="
# ==============================================================================
| TestSubsetNonOverlap |
python | tiangolo__fastapi | docs_src/body_nested_models/tutorial004_py39.py | {
"start": 157,
"end": 499
} | class ____(BaseModel):
name: str
description: Union[str, None] = None
price: float
tax: Union[float, None] = None
tags: set[str] = set()
image: Union[Image, None] = None
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
results = {"item_id": item_id, "item": ite... | Item |
python | getsentry__sentry | src/sentry/snuba/models.py | {
"start": 6946,
"end": 8677
} | class ____(DataSourceTypeHandler[QuerySubscription]):
@override
@staticmethod
def bulk_get_query_object(
data_sources: list[DataSource],
) -> dict[int, QuerySubscription | None]:
query_subscription_ids: list[int] = []
for ds in data_sources:
try:
subs... | QuerySubscriptionDataSourceHandler |
python | openai__openai-python | src/openai/types/responses/response_code_interpreter_tool_call.py | {
"start": 807,
"end": 1650
} | class ____(BaseModel):
id: str
"""The unique ID of the code interpreter tool call."""
code: Optional[str] = None
"""The code to run, or null if not available."""
container_id: str
"""The ID of the container used to run the code."""
outputs: Optional[List[Output]] = None
"""
The ou... | ResponseCodeInterpreterToolCall |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.