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 | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/hooks/logs.py | {
"start": 1584,
"end": 9010
} | class ____(AwsBaseHook):
"""
Interact with Amazon CloudWatch Logs.
Provide thin wrapper around :external+boto3:py:class:`boto3.client("logs") <CloudWatchLogs.Client>`.
Additional arguments (such as ``aws_conn_id``) may be specified and
are passed down to the underlying AwsBaseHook.
.. seealso... | AwsLogsHook |
python | mlflow__mlflow | tests/pyfunc/test_pyfunc_model_config.py | {
"start": 487,
"end": 5259
} | class ____(mlflow.pyfunc.PythonModel):
def predict(self, context, model_input, params=None):
# This mock class returns the internal inference configuration keys and values available
return context.model_config.items()
def test_save_with_model_config(model_path, model_config):
model = Inference... | InferenceContextModel |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 977606,
"end": 978333
} | class ____(ValueChannelMixin, core.PositionValueDef):
"""
XValue schema wrapper.
Definition object for a constant value (primitive value or gradient definition) of an
encoding channel.
Parameters
----------
value : dict, float, :class:`ExprRef`, Literal['height', 'width']
A constan... | XValue |
python | zarr-developers__zarr-python | tests/test_metadata/test_consolidated.py | {
"start": 1710,
"end": 31582
} | class ____:
async def test_open_consolidated_false_raises(self) -> None:
store = zarr.storage.MemoryStore()
with pytest.raises(TypeError, match="use_consolidated"):
await zarr.api.asynchronous.open_consolidated(store, use_consolidated=False) # type: ignore[arg-type]
def test_open_c... | TestConsolidated |
python | run-llama__llama_index | llama-index-integrations/storage/docstore/llama-index-storage-docstore-gel/llama_index/storage/docstore/gel/base.py | {
"start": 235,
"end": 835
} | class ____(KVDocumentStore):
"""
Gel Document (Node) store.
A Gel store for Document and Node objects.
Args:
gel_kvstore (GelKVStore): Gel key-value store
namespace (str): namespace for the docstore
batch_size (int): batch size for bulk operations
"""
def __init__(
... | GelDocumentStore |
python | huggingface__transformers | tests/models/superpoint/test_image_processing_superpoint.py | {
"start": 1230,
"end": 3737
} | class ____:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
image_size=18,
min_resolution=30,
max_resolution=400,
do_resize=True,
size=None,
do_grayscale=True,
):
size = size if size is not None else {"height": 480... | SuperPointImageProcessingTester |
python | getsentry__sentry | fixtures/page_objects/base.py | {
"start": 494,
"end": 843
} | class ____(BaseElement):
label_attr = "aria-label"
disabled_attr = "aria-disabled"
@property
def disabled(self):
return self.element.get_attribute(self.disabled_attr)
@property
def label(self):
return self.element.get_attribute(self.label_attr)
def click(self):
sel... | ButtonElement |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 73885,
"end": 74007
} | class ____:
xlLinkTypeExcelLinks = 1 # from enum XlLinkType
xlLinkTypeOLELinks = 2 # from enum XlLinkType
| LinkType |
python | pytorch__pytorch | torch/nn/modules/dropout.py | {
"start": 3847,
"end": 5974
} | class ____(_DropoutNd):
r"""Randomly zero out entire channels.
A channel is a 2D feature map,
e.g., the :math:`j`-th channel of the :math:`i`-th sample in the
batched input is a 2D tensor :math:`\text{input}[i, j]`.
Each channel will be zeroed out independently on every forward call with
proba... | Dropout2d |
python | doocs__leetcode | solution/3100-3199/3134.Find the Median of the Uniqueness Array/Solution.py | {
"start": 0,
"end": 672
} | class ____:
def medianOfUniquenessArray(self, nums: List[int]) -> int:
def check(mx: int) -> bool:
cnt = defaultdict(int)
k = l = 0
for r, x in enumerate(nums):
cnt[x] += 1
while len(cnt) > mx:
y = nums[l]
... | Solution |
python | kamyu104__LeetCode-Solutions | Python/best-time-to-buy-and-sell-stock-using-strategy.py | {
"start": 60,
"end": 694
} | class ____(object):
def maxProfit(self, prices, strategy, k):
"""
:type prices: List[int]
:type strategy: List[int]
:type k: int
:rtype: int
"""
result = curr = 0
for i in xrange(len(prices)):
curr += prices[i]*(0 if i < k//2 else 1) if i <... | Solution |
python | python-pillow__Pillow | Tests/test_imageops.py | {
"start": 268,
"end": 19128
} | class ____(ImageOps.SupportsGetMesh):
def getmesh(
self, im: Image.Image
) -> list[
tuple[tuple[int, int, int, int], tuple[int, int, int, int, int, int, int, int]]
]:
x, y = im.size
return [((0, 0, x, y), (0, 0, x, 0, x, y, y, 0))]
deformer = Deformer()
def test_sanity() ... | Deformer |
python | Textualize__textual | docs/examples/guide/actions/actions01.py | {
"start": 57,
"end": 374
} | class ____(App):
def action_set_background(self, color: str) -> None:
self.screen.styles.background = color
def on_key(self, event: events.Key) -> None:
if event.key == "r":
self.action_set_background("red")
if __name__ == "__main__":
app = ActionsApp()
app.run()
| ActionsApp |
python | walkccc__LeetCode | solutions/1493. Longest Subarray of 1's After Deleting One Element/1493-2.py | {
"start": 0,
"end": 264
} | class ____:
def longestSubarray(self, nums: list[int]) -> int:
l = 0
zeros = 0
for num in nums:
if num == 0:
zeros += 1
if zeros > 1:
if nums[l] == 0:
zeros -= 1
l += 1
return len(nums) - l - 1
| Solution |
python | django-import-export__django-import-export | tests/core/tests/test_resources/test_bulk_operations.py | {
"start": 22134,
"end": 22756
} | class ____(BulkTest):
class DeleteBookResource(resources.ModelResource):
def for_delete(self, row, instance):
return True
class Meta:
model = UUIDBook
use_bulk = True
batch_size = 5
def setUp(self):
super().setUp()
self.resource =... | BulkUUIDBookDeleteTest |
python | doocs__leetcode | lcof2/剑指 Offer II 020. 回文子字符串的个数/Solution.py | {
"start": 0,
"end": 362
} | class ____:
def countSubstrings(self, s: str) -> int:
def f(i, j):
cnt = 0
while i >= 0 and j < n:
if s[i] != s[j]:
break
cnt += 1
i, j = i - 1, j + 1
return cnt
n = len(s)
return sum(f(i... | Solution |
python | pypa__warehouse | warehouse/manage/views/teams.py | {
"start": 7728,
"end": 23839
} | class ____:
def __init__(self, team, request):
self.team = team
self.request = request
self.organization_service = request.find_service(
IOrganizationService, context=None
)
self.user_service = request.find_service(IUserService, context=None)
self.user_cho... | ManageTeamRolesViews |
python | uqfoundation__dill | dill/tests/test_classdef.py | {
"start": 623,
"end": 723
} | class ____(object):
def _method(self):
pass
def ok(self):
return True
| _newclass |
python | python-jsonschema__jsonschema | jsonschema/tests/test_validators.py | {
"start": 9928,
"end": 27519
} | class ____(TestCase):
def message_for(self, instance, schema, *args, **kwargs):
cls = kwargs.pop("cls", validators._LATEST_VERSION)
cls.check_schema(schema)
validator = cls(schema, *args, **kwargs)
errors = list(validator.iter_errors(instance))
self.assertTrue(errors, msg=f"N... | TestValidationErrorMessages |
python | spyder-ide__spyder | spyder/plugins/remoteclient/widgets/connectionpages.py | {
"start": 30643,
"end": 43339
} | class ____(BaseConnectionPage):
"""Page to receive SSH credentials for a remote connection."""
MAX_WIDTH = 600 if MAC else 580
LOAD_FROM_CONFIG = False
NEW_CONNECTION = True
# ---- SidebarPage API
# -------------------------------------------------------------------------
def get_name(self... | NewConnectionPage |
python | sympy__sympy | sympy/series/sequences.py | {
"start": 31972,
"end": 35543
} | class ____(SeqExprOp):
r"""Represents term-wise multiplication of sequences.
Explanation
===========
Handles multiplication of sequences only. For multiplication
with other objects see :func:`SeqBase.coeff_mul`.
Rules:
* The interval on which sequence is defined is the intersection
... | SeqMul |
python | cython__cython | Cython/Compiler/Main.py | {
"start": 25666,
"end": 26708
} | class ____:
"""
Results from the Cython compiler:
c_file string or None The generated C source file
h_file string or None The generated C header file
i_file string or None The generated .pxi file
api_file string or None The generated C API .h file
... | CompilationResult |
python | getsentry__sentry | tests/sentry/users/api/endpoints/test_user_emails_confirm.py | {
"start": 324,
"end": 8254
} | class ____(APITestCase):
endpoint = "sentry-api-0-user-emails-confirm"
method = "post"
def setUp(self) -> None:
super().setUp()
self.login_as(self.user)
@mock.patch("sentry.users.models.user.User.send_confirm_email_singular")
def test_can_confirm(self, send_confirm_email: mock.Magi... | UserEmailsConfirmTest |
python | pytorch__pytorch | test/onnx/model_defs/emb_seq.py | {
"start": 350,
"end": 658
} | class ____(nn.Module):
def __init__(self, in_space=10, dim=3):
super().__init__()
self.embedding = nn.Embedding(in_space, dim)
self.seq = nn.Sequential(self.embedding, nn.Linear(dim, 1), nn.Sigmoid())
def forward(self, indices):
return self.seq(indices)
| EmbeddingNetwork2 |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_D.py | {
"start": 3184,
"end": 4521
} | class ____(Benchmark):
r"""
Deb 3 objective function.
This class defines the Deb 3 [1]_ global optimization problem. This is a
multimodal minimization problem defined as follows:
.. math::
f_{\text{Deb03}}(x) = - \frac{1}{N} \sum_{i=1}^n \sin^6 \left[ 5 \pi
\left ( x_i^{3/4} - 0.0... | Deb03 |
python | huggingface__transformers | src/transformers/modeling_gguf_pytorch_utils.py | {
"start": 4669,
"end": 6368
} | class ____(TensorProcessor):
def __init__(self, config=None):
super().__init__(config=config)
def process(self, weights, name, **kwargs):
if "attn_qkv" in name:
num_heads = self.config["n_head"]
n_embed = self.config["hidden_size"]
if "weight" in name:
... | BloomTensorProcessor |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/distributions/util_test.py | {
"start": 28412,
"end": 29301
} | class ____(FillTriangularTest):
def _run_test(self, x_, use_deferred_shape=False, **kwargs):
x_ = np.asarray(x_)
with self.cached_session() as sess:
static_shape = None if use_deferred_shape else x_.shape
x_pl = array_ops.placeholder_with_default(x_, shape=static_shape)
zeros_like_x_pl = (x... | FillTriangularInverseTest |
python | wandb__wandb | wandb/automations/actions.py | {
"start": 2289,
"end": 2514
} | class ____(GQLBase):
typename__: Annotated[
Literal["GenericWebhookIntegration"],
Field(alias="__typename", frozen=True, repr=False),
] = "GenericWebhookIntegration"
id: GQLId
| _WebhookIntegrationStub |
python | pytest-dev__pytest | testing/test_tmpdir.py | {
"start": 11136,
"end": 13872
} | class ____:
PREFIX = "fun-"
def test_make(self, tmp_path):
for i in range(10):
d = make_numbered_dir(root=tmp_path, prefix=self.PREFIX)
assert d.name.startswith(self.PREFIX)
assert d.name.endswith(str(i))
symlink = tmp_path.joinpath(self.PREFIX + "current")
... | TestNumberedDir |
python | dagster-io__dagster | python_modules/dagster/dagster/components/resolved/base.py | {
"start": 1017,
"end": 1148
} | class ____(Enum):
SEQUENCE = auto()
OPTIONAL = auto()
DICT = auto()
_DERIVED_MODEL_REGISTRY = {}
@public
| _TypeContainer |
python | tensorflow__tensorflow | tensorflow/python/distribute/values.py | {
"start": 14861,
"end": 16034
} | class ____(type_spec.TypeSpec):
"""Type specification for a `PerReplica`."""
__slots__ = ["_value_specs"]
value_type = property(lambda self: PerReplica)
def __init__(self, *value_specs):
self._value_specs = tuple(value_specs)
def _serialize(self):
return self._value_specs
@property
def _compo... | PerReplicaSpec |
python | pandas-dev__pandas | pandas/tests/series/test_ufunc.py | {
"start": 8384,
"end": 14988
} | class ____:
# TODO: cases with NAs, axis kwarg for DataFrame
def test_multiply(self, values_for_np_reduce, box_with_array, request):
box = box_with_array
values = values_for_np_reduce
with tm.assert_produces_warning(None):
obj = box(values)
if isinstance(values, pd... | TestNumpyReductions |
python | wandb__wandb | wandb/vendor/pygments/lexers/configs.py | {
"start": 7539,
"end": 9669
} | class ____(RegexLexer):
"""
Lexer for `CFEngine3 <http://cfengine.org>`_ policy files.
.. versionadded:: 1.5
"""
name = 'CFEngine3'
aliases = ['cfengine3', 'cf3']
filenames = ['*.cf']
mimetypes = []
tokens = {
'root': [
(r'#.*?\n', Comment),
(r'(bod... | Cfengine3Lexer |
python | openai__openai-python | src/openai/types/responses/response_code_interpreter_tool_call_param.py | {
"start": 812,
"end": 1723
} | class ____(TypedDict, total=False):
id: Required[str]
"""The unique ID of the code interpreter tool call."""
code: Required[Optional[str]]
"""The code to run, or null if not available."""
container_id: Required[str]
"""The ID of the container used to run the code."""
outputs: Required[Opt... | ResponseCodeInterpreterToolCallParam |
python | Netflix__metaflow | metaflow/plugins/azure/azure_credential.py | {
"start": 0,
"end": 2174
} | class ____(object):
name = "azure-default"
@staticmethod
def create_cacheable_azure_credential(*args, **kwargs):
"""azure.identity.DefaultAzureCredential is not readily cacheable in a dictionary
because it does not have a content based hash and equality implementations.
We implemen... | AzureDefaultClientProvider |
python | allegroai__clearml | clearml/utilities/pigar/modules.py | {
"start": 539,
"end": 1692
} | class ____(Modules):
def __init__(self) -> None:
super(ImportedModules, self).__init__()
def add(self, name: str, file: str, lineno: int) -> None:
if name is None:
return
names = list()
special_name = ".".join(name.split(".")[:2])
# Flask extension.
... | ImportedModules |
python | marshmallow-code__apispec | tests/test_ext_marshmallow.py | {
"start": 51199,
"end": 52853
} | class ____:
def test_dict_values_resolve_to_additional_properties(self, spec):
class SchemaWithDict(Schema):
dict_field = Dict(values=String())
spec.components.schema("SchemaWithDict", schema=SchemaWithDict)
result = get_schemas(spec)["SchemaWithDict"]["properties"]["dict_field"... | TestDictValues |
python | doocs__leetcode | solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/Solution.py | {
"start": 445,
"end": 1148
} | class ____:
def minInteger(self, num: str, k: int) -> str:
pos = defaultdict(deque)
for i, v in enumerate(num, 1):
pos[int(v)].append(i)
ans = []
n = len(num)
tree = BinaryIndexedTree(n)
for i in range(1, n + 1):
for v in range(10):
... | Solution |
python | joke2k__faker | tests/providers/test_currency.py | {
"start": 9776,
"end": 10671
} | class ____:
"""Test es_ES currency provider"""
num_samples = 100
@classmethod
def setup_class(cls):
from faker.providers.currency.es_ES import Provider as EsEsCurrencyProvider
cls.provider = EsEsCurrencyProvider
cls.currencies = cls.provider.currencies
cls.currency_cod... | TestEsEs |
python | facebook__pyre-check | client/commands/pyre_language_server.py | {
"start": 17962,
"end": 26619
} | class ____:
"""
The dispatcher provides the top-level, "foreground" logic for a Pyre
language server. Its only job is to read requests from standard input,
parse them, and dispatch to the appropriate lower-level logic.
There are two compontents to which we might dispatch:
- We'll dispatch to th... | PyreLanguageServerDispatcher |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_with.py | {
"start": 3222,
"end": 6446
} | class ____(__TestCase):
def testNameError(self):
def fooNotDeclared():
with foo: pass
self.assertRaises(NameError, fooNotDeclared)
def testEnterAttributeError1(self):
with torch._dynamo.error_on_graph_break(False):
class LacksEnter(object):
def __... | FailureTestCase |
python | Textualize__textual | src/textual/scrollbar.py | {
"start": 645,
"end": 756
} | class ____(Message, bubble=False):
"""Base class for all scrollbar messages."""
@rich.repr.auto
| ScrollMessage |
python | huggingface__transformers | src/transformers/models/lfm2_moe/modular_lfm2_moe.py | {
"start": 9753,
"end": 9883
} | class ____(LlamaForCausalLM):
pass
__all__ = ["Lfm2MoeForCausalLM", "Lfm2MoeModel", "Lfm2MoePreTrainedModel"]
| Lfm2MoeForCausalLM |
python | tox-dev__tox | src/tox/tox_env/package.py | {
"start": 1367,
"end": 3842
} | class ____(ToxEnv, ABC):
def __init__(self, create_args: ToxEnvCreateArgs) -> None:
self._thread_lock = RLock()
self._file_lock: FileLock | None = None
super().__init__(create_args)
self._envs: set[str] = set()
def __getattribute__(self, name: str) -> Any:
# the packagin... | PackageToxEnv |
python | django__django | tests/decorators/test_vary.py | {
"start": 210,
"end": 1360
} | class ____(SimpleTestCase):
def test_wrapped_sync_function_is_not_coroutine_function(self):
def sync_view(request):
return HttpResponse()
wrapped_view = vary_on_headers()(sync_view)
self.assertIs(iscoroutinefunction(wrapped_view), False)
def test_wrapped_async_function_is_c... | VaryOnHeadersTests |
python | scrapy__scrapy | tests/test_spidermiddleware_output_chain.py | {
"start": 797,
"end": 1192
} | class ____(_BaseSpiderMiddleware):
def process_spider_exception(self, response, exception):
self.crawler.spider.logger.info(
"Middleware: %s exception caught", exception.__class__.__name__
)
return [
{"from": "process_spider_exception"},
Request(response.u... | RecoveryMiddleware |
python | realpython__materials | python-class/person.py | {
"start": 327,
"end": 537
} | class ____:
def __init__(self, name):
self.name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value.upper()
| Person |
python | altair-viz__altair | altair/vegalite/v6/theme.py | {
"start": 2605,
"end": 3823
} | class ____:
"""Implementation of a builtin vega theme."""
def __init__(self, theme: str) -> None:
self.theme = theme
def __call__(self) -> ThemeConfig:
return {
"usermeta": {"embedOptions": {"theme": self.theme}},
"config": {"view": {"continuousWidth": 300, "continu... | VegaTheme |
python | apache__airflow | providers/openai/src/airflow/providers/openai/operators/openai.py | {
"start": 3468,
"end": 7230
} | class ____(BaseOperator):
"""
Operator that triggers an OpenAI Batch API endpoint and waits for the batch to complete.
:param file_id: Required. The ID of the batch file to trigger.
:param endpoint: Required. The OpenAI Batch API endpoint to trigger.
:param conn_id: Optional. The OpenAI connection ... | OpenAITriggerBatchOperator |
python | ray-project__ray | rllib/algorithms/algorithm_config.py | {
"start": 319329,
"end": 320356
} | class ____(str, Enum):
"""Enumerates schemes of what parts of the TorchLearner can be compiled.
This can be either the entire update step of the learner or only the forward
methods (and therein the forward_train method) of the RLModule.
.. note::
- torch.compiled code can become slow on graph ... | TorchCompileWhatToCompile |
python | tiangolo__fastapi | scripts/people.py | {
"start": 2311,
"end": 2385
} | class ____(BaseModel):
data: DiscussionsResponseData
| DiscussionsResponse |
python | pennersr__django-allauth | allauth/headless/mfa/views.py | {
"start": 3931,
"end": 4589
} | class ____(AuthenticatedAPIView):
input_class = GenerateRecoveryCodesInput
def get(self, request, *args, **kwargs):
authenticator = recovery_codes_flows.view_recovery_codes(request)
if not authenticator:
return response.RecoveryCodesNotFoundResponse(request)
return response.... | ManageRecoveryCodesView |
python | doocs__leetcode | solution/0200-0299/0294.Flip Game II/Solution.py | {
"start": 0,
"end": 548
} | class ____:
def canWin(self, currentState: str) -> bool:
@cache
def dfs(mask):
for i in range(n - 1):
if (mask & (1 << i)) == 0 or (mask & (1 << (i + 1)) == 0):
continue
if dfs(mask ^ (1 << i) ^ (1 << (i + 1))):
cont... | Solution |
python | kamyu104__LeetCode-Solutions | Python/the-employee-that-worked-on-the-longest-task.py | {
"start": 37,
"end": 322
} | class ____(object):
def hardestWorker(self, n, logs):
"""
:type n: int
:type logs: List[List[int]]
:rtype: int
"""
return logs[max(xrange(len(logs)), key=lambda x: (logs[x][1]-(logs[x-1][1] if x-1 >= 0 else 0), -logs[x][0]))][0]
| Solution |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 5284,
"end": 6184
} | class ____(PrefectOperatorFilterBaseModel):
"""Filter by `Flow.tags`."""
all_: Optional[list[str]] = Field(
default=None,
examples=[["tag-1", "tag-2"]],
description=(
"A list of tags. Flows will be returned only if their tags are a superset"
" of the list"
... | FlowFilterTags |
python | tensorflow__tensorflow | tensorflow/dtensor/python/tests/spmd_test.py | {
"start": 5805,
"end": 93281
} | class ____(test_util.DTensorBaseTest):
def setUp(self):
super(DTensorSPMDTest, self).setUp()
self.skipForDeviceType(['TPU'],
'all tests require 8 TPU cores.',
unless_device_count_equals_to=8)
global_ids = test_util.create_device_ids_array((2, 4))
... | DTensorSPMDTest |
python | great-expectations__great_expectations | great_expectations/core/expectation_diagnostics/supporting_types.py | {
"start": 4912,
"end": 5015
} | class ____(TypedDict):
message: str
passed: bool
@dataclass
| ExpectationDiagnosticCheckMessageDict |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyflakes/F841_0.py | {
"start": 2779,
"end": 2873
} | class ____:
class B:
def set_class(self, cls):
__class__ = cls # F841
| A |
python | numpy__numpy | numpy/random/tests/test_generator_mt19937.py | {
"start": 11929,
"end": 13268
} | class ____:
def _create_rng(self):
seed = 1234567890
rg = Generator(MT19937(seed))
bit_generator = rg.bit_generator
state = bit_generator.state
legacy_state = (state['bit_generator'],
state['state']['key'],
state['state']['pos']... | TestSetState |
python | allegroai__clearml | clearml/backend_api/services/v2_9/events.py | {
"start": 101007,
"end": 103110
} | class ____(Response):
"""
Response of events.vector_metrics_iter_histogram endpoint.
:param images:
:type images: Sequence[dict]
"""
_service = "events"
_action = "vector_metrics_iter_histogram"
_version = "2.9"
_schema = {
"definitions": {},
"properties": {"images"... | VectorMetricsIterHistogramResponse |
python | ray-project__ray | python/ray/autoscaler/_private/node_tracker.py | {
"start": 85,
"end": 2744
} | class ____:
"""Map nodes to their corresponding logs.
We need to be a little careful here. At an given point in time, node_id <->
ip can be interchangeably used, but the node_id -> ip relation is not
bijective _across time_ since IP addresses can be reused. Therefore, we
should treat node_id as the... | NodeTracker |
python | mlflow__mlflow | mlflow/store/tracking/dbmodels/initial_models.py | {
"start": 5205,
"end": 6133
} | class ____(Base):
"""
DB model for :py:class:`mlflow.entities.RunTag`. These are recorded in ``tags`` table.
"""
__tablename__ = "tags"
key = Column(String(250))
"""
Tag key: `String` (limit 250 characters). *Primary Key* for ``tags`` table.
"""
value = Column(String(250), nullable... | SqlTag |
python | marshmallow-code__marshmallow | tests/test_decorators.py | {
"start": 13228,
"end": 30022
} | class ____:
def test_validator_nested_many_invalid_data(self):
class NestedSchema(Schema):
foo = fields.Int(required=True)
class MySchema(Schema):
nested = fields.Nested(NestedSchema, required=True, many=True)
schema = MySchema()
errors = schema.validate({"n... | TestValidatesSchemaDecorator |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/config_types.py | {
"start": 11082,
"end": 12428
} | class ____(graphene.ObjectType):
class Meta:
interfaces = (GrapheneConfigType,)
name = "EnumConfigType"
values = non_null_list(GrapheneEnumConfigValue)
given_name = graphene.NonNull(graphene.String)
def __init__(
self,
get_config_type: Callable[[str], ConfigTypeSnap],
... | GrapheneEnumConfigType |
python | openai__openai-python | src/openai/types/realtime/realtime_response_usage_input_token_details.py | {
"start": 228,
"end": 613
} | class ____(BaseModel):
audio_tokens: Optional[int] = None
"""The number of cached audio tokens used as input for the Response."""
image_tokens: Optional[int] = None
"""The number of cached image tokens used as input for the Response."""
text_tokens: Optional[int] = None
"""The number of cached... | CachedTokensDetails |
python | docker__docker-py | docker/errors.py | {
"start": 5169,
"end": 5340
} | class ____(DockerException):
def __init__(self, name):
self.name = name
def __str__(self):
return (f"context '{self.name}' not found")
| ContextNotFound |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 29829,
"end": 31829
} | class ____(RegexLexer):
"""
Base lexer for Genshi markup, used by `HtmlGenshiLexer` and
`GenshiLexer`.
"""
flags = re.DOTALL
tokens = {
'root': [
(r'[^<$]+', Other),
(r'(<\?python)(.*?)(\?>)',
bygroups(Comment.Preproc, using(PythonLexer), Comment.Pr... | GenshiMarkupLexer |
python | cherrypy__cherrypy | cherrypy/test/test_encoding.py | {
"start": 412,
"end": 18947
} | class ____(helper.CPWebCase):
@staticmethod
def setup_server():
class Root:
@cherrypy.expose
def index(self, param):
assert param == europoundUnicode, '%r != %r' % (
param,
europoundUnicode,
)
... | EncodingTests |
python | django__django | tests/admin_widgets/models.py | {
"start": 5045,
"end": 5350
} | class ____(models.Model):
name = models.CharField(max_length=255)
if Image:
photo = models.ImageField(
storage=temp_storage, upload_to="photos", blank=True, null=True
)
class Meta:
ordering = ("name",)
def __str__(self):
return self.name
| Student |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 347598,
"end": 348728
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"encoded_name",
"encoding",
"extension",
"is_image",
"is_truncated",
"language",
"name",
"size",
"text",
)... | GistFile |
python | facebook__pyre-check | tools/upgrade/commands/codemods.py | {
"start": 2929,
"end": 4920
} | class ____(Command):
def __init__(self, *, repository: Repository, only_fix_error_code: int) -> None:
super().__init__(repository)
self._only_fix_error_code: int = only_fix_error_code
@staticmethod
def from_arguments(
arguments: argparse.Namespace, repository: Repository
) -> "M... | MissingGlobalAnnotations |
python | kamyu104__LeetCode-Solutions | Python/kth-missing-positive-number.py | {
"start": 32,
"end": 567
} | class ____(object):
def findKthPositive(self, arr, k):
"""
:type arr: List[int]
:type k: int
:rtype: int
"""
def check(arr, k, x):
return arr[x]-(x+1) < k
left, right = 0, len(arr)-1
while left <= right:
mid = left + (right-lef... | Solution |
python | streamlit__streamlit | lib/tests/streamlit/elements/file_uploader_test.py | {
"start": 1276,
"end": 15697
} | class ____(DeltaGeneratorTestCase):
def test_just_label(self):
"""Test that it can be called with no other values."""
st.file_uploader("the label")
c = self.get_delta_from_queue().new_element.file_uploader
assert c.label == "the label"
assert (
c.label_visibility... | FileUploaderTest |
python | pytorch__pytorch | torch/distributed/fsdp/_fully_shard/_fsdp_param_group.py | {
"start": 39082,
"end": 40430
} | class ____(torch.autograd.Function):
@staticmethod
def _assert_not_tracing_fsdp():
if compiled_autograd_enabled():
# TODO: Find a way to print the offending FSDP2 module.
msg = """\
When Traceable FSDP2 is enabled, we should not be calling into `RegisterPostBackwardFunction`.
Ins... | RegisterPostBackwardFunction |
python | pytorch__pytorch | torch/testing/_internal/common_pruning.py | {
"start": 5449,
"end": 6147
} | class ____(nn.Module):
r"""Model with only Conv2d layers, some with bias, some in a Sequential and some outside.
Used to test pruned Conv2d-Bias-Conv2d fusion."""
def __init__(self) -> None:
super().__init__()
self.seq = nn.Sequential(
nn.Conv2d(1, 32, 3, 1, bias=True),
... | Conv2dBias |
python | google__pytype | pytype/metrics.py | {
"start": 5624,
"end": 6077
} | class ____(Metric):
"""A counter that measures the time spent in a "with" statement."""
def __enter__(self):
self._start_time = get_cpu_clock()
def __exit__(self, exc_type, exc_value, traceback):
self._total = get_cpu_clock() - self._start_time
del self._start_time
def _summary(self):
return ... | StopWatch |
python | numpy__numpy | numpy/distutils/command/install_data.py | {
"start": 269,
"end": 848
} | class ____ (old_install_data):
def run(self):
old_install_data.run(self)
if have_setuptools:
# Run install_clib again, since setuptools does not run sub-commands
# of install automatically
self.run_command('install_clib')
def finalize_options (self):
... | install_data |
python | kamyu104__LeetCode-Solutions | Python/can-place-flowers.py | {
"start": 29,
"end": 508
} | class ____(object):
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
for i in xrange(len(flowerbed)):
if flowerbed[i] == 0 and (i == 0 or flowerbed[i-1] == 0) and \
(i == len(flowerbed)-1... | Solution |
python | ray-project__ray | python/ray/data/_internal/datasource/clickhouse_datasink.py | {
"start": 2788,
"end": 3415
} | class ____(IntEnum):
"""
Enum of possible modes for sinking data
Attributes:
CREATE: Create a new table; fail if that table already exists.
APPEND: Use an existing table if present, otherwise create one; then append data.
OVERWRITE: Drop the table if it already exists, then re-creat... | SinkMode |
python | tiangolo__fastapi | scripts/notify_translations.py | {
"start": 3616,
"end": 12994
} | class ____(BaseModel):
pull_request: PartialGitHubEventIssue | None = None
def get_graphql_response(
*,
settings: Settings,
query: str,
after: Union[str, None] = None,
category_id: Union[str, None] = None,
discussion_number: Union[int, None] = None,
discussion_id: Union[str, None] = No... | PartialGitHubEvent |
python | doocs__leetcode | solution/2800-2899/2832.Maximal Range That Each Element Is Maximum in It/Solution.py | {
"start": 0,
"end": 630
} | class ____:
def maximumLengthOfRanges(self, nums: List[int]) -> List[int]:
n = len(nums)
left = [-1] * n
right = [n] * n
stk = []
for i, x in enumerate(nums):
while stk and nums[stk[-1]] <= x:
stk.pop()
if stk:
left[i] =... | Solution |
python | django__django | django/contrib/auth/models.py | {
"start": 17855,
"end": 18126
} | class ____(AbstractUser):
"""
Users within the Django authentication system are represented by this
model.
Username and password are required. Other fields are optional.
"""
class Meta(AbstractUser.Meta):
swappable = "AUTH_USER_MODEL"
| User |
python | walkccc__LeetCode | solutions/2662. Minimum Cost of a Path With Special Roads/2662.py | {
"start": 0,
"end": 1478
} | class ____:
def minimumCost(
self,
start: list[int],
target: list[int],
specialRoads: list[list[int]],
) -> int:
return self.dijkstra(specialRoads, *start, *target)
def dijkstra(
self,
specialRoads: list[list[int]],
srcX: int,
srcY: int,
dstX: int,
... | Solution |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_lookup.py | {
"start": 5770,
"end": 9486
} | class ____:
pass
@pytest.mark.parametrize(
"typ,coll_type",
[
(typing.ChainMap[Elem, ElemValue], typing.ChainMap),
(typing.DefaultDict[Elem, ElemValue], typing.DefaultDict),
(typing.OrderedDict[Elem, ElemValue], typing.OrderedDict),
],
ids=repr,
)
@given(data=st.data())
def... | ElemValue |
python | huggingface__transformers | src/transformers/models/auto/modeling_auto.py | {
"start": 91604,
"end": 91848
} | class ____(_BaseAutoModelClass):
_model_mapping = MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING
AutoModelForMaskedImageModeling = auto_class_update(AutoModelForMaskedImageModeling, head_doc="masked image modeling")
| AutoModelForMaskedImageModeling |
python | sphinx-doc__sphinx | sphinx/transforms/post_transforms/__init__.py | {
"start": 13673,
"end": 14420
} | class ____(SphinxPostTransform):
"""Add the domain name of the parent node as a class in each desc_signature node."""
default_priority = 200
def run(self, **kwargs: Any) -> None:
for node in self.document.findall(addnodes.desc_signature):
if node.parent.get('domain'):
n... | PropagateDescDomain |
python | huggingface__transformers | src/transformers/models/clap/modeling_clap.py | {
"start": 54447,
"end": 56114
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.layer = nn.ModuleList([ClapTextLayer(config) for i in range(config.num_hidden_layers)])
self.gradient_checkpointing = False
@can_return_tuple
def forward(
self,
hi... | ClapTextEncoder |
python | pydantic__pydantic | pydantic-core/tests/test_tzinfo.py | {
"start": 741,
"end": 1358
} | class ____:
"""
Object that is less than anything (except itself).
"""
def __eq__(self, other):
return isinstance(other, _SMALLEST)
def __gt__(self, other):
return False
SMALLEST = _SMALLEST()
pickle_choices = [(pickle, pickle, proto) for proto in range(pickle.HIGHEST_PROTOCOL ... | _SMALLEST |
python | walkccc__LeetCode | solutions/3464. Maximize the Distance Between Points on a Square/3464.py | {
"start": 60,
"end": 273
} | class ____:
startX: int
startY: int
endX: int
endY: int
length: int
def __iter__(self):
yield self.startX
yield self.startY
yield self.endX
yield self.endY
yield self.length
| Sequence |
python | gevent__gevent | src/gevent/queue.py | {
"start": 22657,
"end": 23379
} | class ____(Queue):
'''A subclass of :class:`Queue` that retrieves entries in priority order (lowest first).
Entries are typically tuples of the form: ``(priority number, data)``.
.. versionchanged:: 1.2a1
Any *items* given to the constructor will now be passed through
:func:`heapq.heapify` t... | PriorityQueue |
python | run-llama__llama_index | llama-index-core/llama_index/core/indices/keyword_table/base.py | {
"start": 1392,
"end": 8264
} | class ____(BaseIndex[KeywordTable]):
"""
Base Keyword Table Index.
This index extracts keywords from the text, and maps each
keyword to the node(s) that it corresponds to. In this sense it mimics a
"hash table". During index construction, the keyword table is constructed
by extracting keywords ... | BaseKeywordTableIndex |
python | gevent__gevent | src/gevent/tests/test__server.py | {
"start": 3034,
"end": 10605
} | class ____(greentest.TestCase):
# pylint: disable=too-many-public-methods
__timeout__ = greentest.LARGE_TIMEOUT
Settings = Settings
server = None
def cleanup(self):
if getattr(self, 'server', None) is not None:
self.server.stop()
self.server = None
sleep_to_c... | TestCase |
python | openai__openai-python | src/openai/_response.py | {
"start": 12938,
"end": 16393
} | class ____(BaseAPIResponse[R]):
@property
def request_id(self) -> str | None:
return self.http_response.headers.get("x-request-id") # type: ignore[no-any-return]
@overload
async def parse(self, *, to: type[_T]) -> _T: ...
@overload
async def parse(self) -> R: ...
async def parse(... | AsyncAPIResponse |
python | jmcnamara__XlsxWriter | xlsxwriter/test/contenttypes/test_contenttypes01.py | {
"start": 351,
"end": 2651
} | class ____(unittest.TestCase):
"""
Test assembling a complete ContentTypes file.
"""
def test_assemble_xml_file(self):
"""Test writing an ContentTypes file."""
self.maxDiff = None
fh = StringIO()
content = ContentTypes()
content._set_filehandle(fh)
con... | TestAssembleContentTypes |
python | pypa__pipenv | pipenv/patched/pip/_internal/resolution/resolvelib/requirements.py | {
"start": 1547,
"end": 4142
} | class ____(Requirement):
def __init__(self, ireq: InstallRequirement) -> None:
assert ireq.link is None, "This is a link, not a specifier"
self._ireq = ireq
self._equal_cache: Optional[str] = None
self._hash: Optional[int] = None
self._extras = frozenset(canonicalize_name(e) ... | SpecifierRequirement |
python | ray-project__ray | python/ray/train/_internal/backend_executor.py | {
"start": 29798,
"end": 30697
} | class ____:
# TODO: fix inheritence. perhaps create WorkerGroupInterface.
# Need to define getstate and setstate so that getattr does not screwup
# pickling. See https://stackoverflow.com/a/50888571/11249691
def __getstate__(self):
return vars(self)
def __setstate__(self, state):
v... | InactiveWorkerGroup |
python | apache__airflow | task-sdk/src/airflow/sdk/bases/decorator.py | {
"start": 11850,
"end": 23794
} | class ____(ExpandableFactory, Generic[FParams, FReturn, OperatorSubclass]):
"""
Helper class for providing dynamic task mapping to decorated functions.
``task_decorator_factory`` returns an instance of this, instead of just a plain wrapped function.
:meta private:
"""
function: Callable[FPara... | _TaskDecorator |
python | pytorch__pytorch | torch/onnx/errors.py | {
"start": 484,
"end": 1672
} | class ____(OnnxExporterError):
"""Raised when an operator is unsupported by the exporter."""
# NOTE: This is legacy and is only used by the torchscript exporter
# Clean up when the torchscript exporter is removed
def __init__(self, name: str, version: int, supported_version: int | None) -> None:
... | UnsupportedOperatorError |
python | getsentry__sentry | src/sentry/replays/endpoints/project_replay_clicks_index.py | {
"start": 1992,
"end": 9746
} | class ____(ProjectEndpoint):
owner = ApiOwner.REPLAY
publish_status = {
"GET": ApiPublishStatus.PUBLIC,
}
@extend_schema(
operation_id="List Clicked Nodes",
parameters=[
CursorQueryParam,
GlobalParams.ORG_ID_OR_SLUG,
GlobalParams.PROJECT_ID_OR... | ProjectReplayClicksIndexEndpoint |
python | spack__spack | var/spack/test_repos/spack_repo/tutorial/packages/mpich/package.py | {
"start": 239,
"end": 5524
} | class ____(AutotoolsPackage):
"""MPICH is a high performance and widely portable implementation of
the Message Passing Interface (MPI) standard."""
homepage = "http://www.mpich.org"
url = "http://www.mpich.org/static/downloads/3.0.4/mpich-3.0.4.tar.gz"
git = "https://github.com/pmodels/mpich.git"
... | Mpich |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.