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 | getsentry__sentry | src/sentry/utils/function_cache.py | {
"start": 4279,
"end": 5636
} | class ____(Generic[*Ts, R]):
"""
A callable class that wraps a function with caching capabilities and provides a batch method
for processing multiple sets of arguments efficiently.
"""
def __init__(self, func: Callable[[*Ts], R], cache_ttl: timedelta):
self.func = func
self.cache_tt... | CachedFunction |
python | PrefectHQ__prefect | src/prefect/blocks/notifications.py | {
"start": 22663,
"end": 26259
} | class ____(AbstractAppriseNotificationBlock):
"""
Enables sending notifications via a provided Discord webhook.
See [Apprise notify_Discord docs](https://github.com/caronc/apprise/wiki/Notify_Discord) # noqa
Examples:
Load a saved Discord webhook and send a message:
```python
fr... | DiscordWebhook |
python | google__jax | tests/sparse_bcoo_bcsr_test.py | {
"start": 72026,
"end": 79038
} | class ____(sptu.SparseTestCase):
@jtu.sample_product(
[
dict(shape=shape, n_batch=layout.n_batch, n_dense=layout.n_dense)
for shape in [(5, 8), (8, 5), (3, 4, 5), (3, 4, 3, 2)]
for layout in sptu.iter_bcsr_layouts(shape)
],
dtype=all_dtypes,
)
def test_bcsr_dense_r... | BCSRTest |
python | getsentry__sentry | src/sentry/monitors/consumers/incident_occurrences_consumer.py | {
"start": 5875,
"end": 6296
} | class ____(ProcessingStrategyFactory[KafkaPayload]):
def __init__(self) -> None:
pass
def create_with_partitions(
self,
commit: Commit,
partitions: Mapping[Partition, int],
) -> ProcessingStrategy[KafkaPayload]:
return RunTask(
function=process_incident_o... | MonitorIncidentOccurenceStrategyFactory |
python | ray-project__ray | python/ray/llm/_internal/batch/stages/vllm_engine_stage.py | {
"start": 21604,
"end": 25968
} | class ____(StatefulStage):
"""
A stage that runs vLLM engine.
"""
fn: Type[StatefulStageUDF] = vLLMEngineStageUDF
@root_validator(pre=True)
def post_init(cls, values):
"""Post-initialize the stage. Specifically,
this function determines the num_gpus and Ray remote args
... | vLLMEngineStage |
python | huggingface__transformers | examples/modular-transformers/modeling_test_detr.py | {
"start": 38673,
"end": 45341
} | class ____(TestDetrPreTrainedModel):
"""
Transformer encoder consisting of *config.encoder_layers* deformable attention layers. Each layer is a
[`TestDetrEncoderLayer`].
The encoder updates the flattened multi-scale feature maps through multiple deformable attention layers.
Args:
config: T... | TestDetrEncoder |
python | getsentry__sentry | src/sentry/grouping/fingerprinting/rules.py | {
"start": 414,
"end": 530
} | class ____(NamedTuple):
fingerprint: list[str]
attributes: FingerprintRuleAttributes
| FingerprintWithAttributes |
python | huggingface__transformers | tests/models/imagegpt/test_modeling_imagegpt.py | {
"start": 1455,
"end": 8109
} | class ____:
def __init__(
self,
parent,
batch_size=14,
seq_length=7,
is_training=True,
use_token_type_ids=True,
use_input_mask=True,
use_labels=True,
use_mc_token_ids=True,
vocab_size=99,
hidden_size=32,
num_hidden_layer... | ImageGPTModelTester |
python | Lightning-AI__lightning | tests/parity_pytorch/models.py | {
"start": 1028,
"end": 2362
} | class ____(LightningModule):
def __init__(self, backbone="resnet101", hidden_dim=1024, learning_rate=1e-3, weights="DEFAULT"):
super().__init__()
self.save_hyperparameters()
self.learning_rate = learning_rate
self.num_classes = 10
self.backbone = get_torchvision_model(backbo... | ParityModuleCIFAR |
python | huggingface__transformers | tests/models/exaone4/test_modeling_exaone4.py | {
"start": 1518,
"end": 8576
} | class ____(unittest.TestCase):
TEST_MODEL_ID = "LGAI-EXAONE/EXAONE-4.0-32B"
def setUp(self):
cleanup(torch_device, gc_collect=True)
def tearDown(self):
# TODO (joao): automatic compilation, i.e. compilation when `cache_implementation="static"` is used, leaves
# some memory allocate... | Exaone4IntegrationTest |
python | pytorch__pytorch | torch/ao/quantization/quantizer/quantizer.py | {
"start": 601,
"end": 847
} | class ____(ABC): # noqa: B024
"""Base class for different types of quantization specs that allows users to
specify how to quantize a Tensor (input/output of a Node) in the model
"""
@dataclass(eq=True, frozen=True)
| QuantizationSpecBase |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_fibonacci_number.py | {
"start": 997,
"end": 2008
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_fibonacci_number"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _... | ColumnValuesToBeFibonacciNumber |
python | huggingface__transformers | src/transformers/models/jamba/modeling_jamba.py | {
"start": 48569,
"end": 48777
} | class ____(GenericForSequenceClassification, JambaPreTrainedModel):
pass
__all__ = ["JambaForCausalLM", "JambaForSequenceClassification", "JambaModel", "JambaPreTrainedModel"]
| JambaForSequenceClassification |
python | django__django | django/core/checks/messages.py | {
"start": 1890,
"end": 2013
} | class ____(CheckMessage):
def __init__(self, *args, **kwargs):
super().__init__(WARNING, *args, **kwargs)
| Warning |
python | jupyterlab__jupyterlab | jupyterlab/labextensions.py | {
"start": 12387,
"end": 12861
} | class ____(BaseExtensionApp):
description = "Unlink packages by name or path"
def run_task(self):
self.extra_args = self.extra_args or [os.getcwd()]
options = AppOptions(
app_dir=self.app_dir,
logger=self.log,
labextensions_path=self.labextensions_path,
... | UnlinkLabExtensionApp |
python | gevent__gevent | src/gevent/tests/test__socket_ssl.py | {
"start": 356,
"end": 865
} | class ____(greentest.TestCase):
__timeout__ = 30
def test_amazon_response(self):
conn = httplib.HTTPSConnection('sdb.amazonaws.com')
conn.request('GET', '/')
conn.getresponse()
def test_str_and_repr(self):
conn = socket.socket()
conn.connect(('sdb.amazonaws.com', 4... | AmazonHTTPSTests |
python | great-expectations__great_expectations | docs/docusaurus/docs/core/customize_expectations/_examples/define_a_custom_expectation_class.py | {
"start": 1856,
"end": 2803
} | class ____(gx.expectations.ExpectColumnValuesToBeBetween):
# </snippet>
column: str = "passenger_count"
min_value: int = 1
max_value: int = 6
# </snippet>
description: str = "There should be between **1** and **6** passengers."
# </snippet>
# Create an instance of the custom Expectation
# <sn... | ExpectValidPassengerCount |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/data_table_row_labels.py | {
"start": 553,
"end": 1098
} | class ____(App):
def compose(self) -> ComposeResult:
yield DataTable()
def on_mount(self) -> None:
table = self.query_one(DataTable)
table.fixed_rows = 1
table.fixed_columns = 1
table.focus()
rows = iter(ROWS)
column_labels = next(rows)
for column... | TableApp |
python | conda__conda | tests/plugins/test_transaction_hooks.py | {
"start": 492,
"end": 561
} | class ____(DummyTransactionAction):
pass
| DummyPostTransactionAction |
python | modin-project__modin | asv_bench/benchmarks/benchmarks.py | {
"start": 12718,
"end": 14146
} | class ____:
param_names = ["shape", "axis"]
params = [
get_benchmark_shapes("TimeArithmetic"),
[0, 1],
]
def setup(self, shape, axis):
self.df = generate_dataframe("int", *shape, RAND_LOW, RAND_HIGH)
def time_sum(self, shape, axis):
execute(self.df.sum(axis=axis))
... | TimeArithmetic |
python | getsentry__sentry-python | sentry_sdk/integrations/_wsgi_common.py | {
"start": 7073,
"end": 7558
} | class ____:
"""
Wrapper to make it possible to use list[HttpStatusCodeRange] as a Container[int].
Used for backwards compatibility with the old `failed_request_status_codes` option.
"""
def __init__(self, code_ranges):
# type: (list[HttpStatusCodeRange]) -> None
self._code_ranges = ... | HttpCodeRangeContainer |
python | django__django | django/contrib/postgres/operations.py | {
"start": 373,
"end": 2681
} | class ____(Operation):
reversible = True
category = OperationCategory.ADDITION
def __init__(self, name, hints=None):
self.name = name
self.hints = hints or {}
def state_forwards(self, app_label, state):
pass
def database_forwards(self, app_label, schema_editor, from_state,... | CreateExtension |
python | doocs__leetcode | solution/0400-0499/0467.Unique Substrings in Wraparound String/Solution.py | {
"start": 0,
"end": 337
} | class ____:
def findSubstringInWraproundString(self, s: str) -> int:
f = defaultdict(int)
k = 0
for i, c in enumerate(s):
if i and (ord(c) - ord(s[i - 1])) % 26 == 1:
k += 1
else:
k = 1
f[c] = max(f[c], k)
return sum... | Solution |
python | kamyu104__LeetCode-Solutions | Python/finding-pairs-with-a-certain-sum.py | {
"start": 112,
"end": 834
} | class ____(object):
def __init__(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
"""
self.__nums2 = nums2
self.__count1 = collections.Counter(nums1)
self.__count2 = collections.Counter(nums2)
def add(self, index, val):
"""
... | FindSumPairs |
python | doocs__leetcode | solution/3200-3299/3247.Number of Subsequences with Odd Sum/Solution.py | {
"start": 0,
"end": 347
} | class ____:
def subsequenceCount(self, nums: List[int]) -> int:
mod = 10**9 + 7
f = [0] * 2
for x in nums:
if x % 2:
f[0], f[1] = (f[0] + f[1]) % mod, (f[0] + f[1] + 1) % mod
else:
f[0], f[1] = (f[0] + f[0] + 1) % mod, (f[1] + f[1]) % m... | Solution |
python | donnemartin__interactive-coding-challenges | online_judges/merge_ranges/test_merge_ranges.py | {
"start": 18,
"end": 841
} | class ____(unittest.TestCase):
def test_merge_ranges(self):
solution = Solution()
self.assertRaises(TypeError, solution.merge_ranges, None)
self.assertEqual(solution.merge_ranges([]), [])
array = [(2, 3), (7, 9)]
expected = [(2, 3), (7, 9)]
self.assertEqual(solution.... | TestMergeRanges |
python | huggingface__transformers | src/transformers/models/emu3/modeling_emu3.py | {
"start": 46758,
"end": 49998
} | class ____(Emu3PreTrainedModel):
_can_record_outputs = {
"hidden_states": Emu3DecoderLayer,
"attentions": Emu3Attention,
}
def __init__(self, config: Emu3Config):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
... | Emu3TextModel |
python | ray-project__ray | python/ray/experimental/collective/collective.py | {
"start": 615,
"end": 8228
} | class ____:
"""Singleton class to store the mapping between actors and communicators
that the actors are a part of.
"""
def __init__(self):
# Handles to communicators that we created. Key is a user-provided
# name or UUID.
self._remote_communicators: Dict[str, CommunicatorHandle... | RemoteCommunicatorManager |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_flow_runs.py | {
"start": 86822,
"end": 87418
} | class ____:
async def test_history_interval_must_be_one_second_or_larger(self, client):
response = await client.post(
"/flow_runs/history",
json=dict(
history_start=str(now("UTC")),
history_end=str(now("UTC") + datetime.timedelta(days=1)),
... | TestFlowRunHistory |
python | kubernetes-client__python | kubernetes/client/models/v1_mutating_webhook_configuration.py | {
"start": 383,
"end": 7187
} | 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... | V1MutatingWebhookConfiguration |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 2792,
"end": 3082
} | class ____(BaseModel):
debug: bool = Field(..., description="")
service_debug_feature: bool = Field(..., description="")
recovery_mode: bool = Field(..., description="")
gpu: bool = Field(..., description="")
rocksdb: bool = Field(..., description="")
| AppFeaturesTelemetry |
python | huggingface__transformers | tests/models/mllama/test_modeling_mllama.py | {
"start": 9591,
"end": 17952
} | class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
"""
Model tester for `MllamaForConditionalGeneration`.
"""
all_model_classes = (
(
MllamaModel,
MllamaForConditionalGeneration,
)
if is_torch_available()
else ()
)
pip... | MllamaForConditionalGenerationModelTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol53.py | {
"start": 2568,
"end": 2669
} | class ____(Protocol):
def m[T: Proto_ContraGeneric](self: T, x: T) -> None: ...
| Proto_ContraGeneric |
python | crytic__slither | slither/detectors/compiler_bugs/array_by_reference.py | {
"start": 777,
"end": 7152
} | class ____(AbstractDetector):
"""
Detects passing of arrays located in memory to functions which expect to modify arrays via storage reference.
"""
ARGUMENT = "array-by-reference"
HELP = "Modifying storage array by value"
IMPACT = DetectorClassification.HIGH
CONFIDENCE = DetectorClassificat... | ArrayByReference |
python | django__django | tests/model_regress/models.py | {
"start": 869,
"end": 932
} | class ____(models.Model):
when = models.DateTimeField()
| Event |
python | tensorflow__tensorflow | tensorflow/lite/python/convert_phase.py | {
"start": 938,
"end": 1460
} | class ____(enum.Enum):
"""Enum class defining name of the converter components."""
# Validate the given input and prepare and optimize TensorFlow Model.
PREPARE_TF_MODEL = "PREPARE_TF_MODEL"
# Convert to TFLite model format.
CONVERT_TF_TO_TFLITE_MODEL = "CONVERT_TF_TO_TFLITE_MODEL"
# RUN quantization and ... | Component |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py | {
"start": 111358,
"end": 113595
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("model_service.model_service.UploadModelResponse.to_dict"))
@mock.patch(VERTEX_AI_PATH.format("model_service.ModelServiceHook"))
def test_execute(self, mock_hook, to_dict_mock):
op = UploadModelOperator(
task_id=TASK_ID,
gcp_conn_... | TestVertexAIUploadModelOperator |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_page_breaks04.py | {
"start": 315,
"end": 1190
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("page_breaks04.xlsx")
self.ignore_files = [
"xl/printerSettings/printerSettings1.bin",
"xl/worksheets/_rels/sheet1.xml.r... | TestCompareXLSXFiles |
python | etianen__django-reversion | tests/test_app/models.py | {
"start": 2457,
"end": 2689
} | class ____(models.Model):
name = models.CharField(
max_length=191,
default="v1",
)
objects = TestModelWithNaturalKeyManager()
def natural_key(self):
return (self.name,)
| TestModelWithNaturalKey |
python | miyuchina__mistletoe | mistletoe/contrib/mathjax.py | {
"start": 179,
"end": 1266
} | class ____(HtmlRenderer, LaTeXRenderer):
def __init__(self, **kwargs):
"""
Args:
**kwargs: additional parameters to be passed to the ancestors'
constructors.
"""
super().__init__(**kwargs)
mathjax_src = '<script src="https://cdnjs.cloudflare.com... | MathJaxRenderer |
python | pandas-dev__pandas | pandas/tests/tools/test_to_datetime.py | {
"start": 102676,
"end": 103815
} | class ____:
@pytest.mark.parametrize(
"test_list",
[
[
"2011-12-30 00:00:00.000000",
"2011-12-30 00:00:00.000000",
"2011-12-30 00:00:00.000000",
],
[np.nan, np.nan, "2011-12-30 00:00:00.000000"],
["", "20... | TestGuessDatetimeFormat |
python | kamyu104__LeetCode-Solutions | Python/next-greater-element-iv.py | {
"start": 42,
"end": 586
} | class ____(object):
def secondGreaterElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
result, stk1, stk2 = [-1]*len(nums), [], []
for i, x in enumerate(nums):
while stk2 and nums[stk2[-1]] < x:
result[stk2.pop()] = x
... | Solution |
python | crytic__slither | slither/vyper_parsing/ast/types.py | {
"start": 3218,
"end": 3298
} | class ____(ASTNode):
name: str
body: List[ASTNode]
@dataclass
| InterfaceDef |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_metrics.py | {
"start": 1179,
"end": 2961
} | class ____(APITestCase):
(method, endpoint) = ("get", "sentry-api-0-organization-metrics-data")
def setUp(self) -> None:
self.create_project(name="Bar", slug="bar", teams=[self.team], fire_project_created=True)
def send_request(
self, organization: Organization, token: ApiToken, method: st... | OrganizationMetricsPermissionTest |
python | python-pillow__Pillow | src/PIL/MpegImagePlugin.py | {
"start": 402,
"end": 1361
} | class ____:
def __init__(self, fp: SupportsRead[bytes]) -> None:
self.fp = fp
self.bits = 0
self.bitbuffer = 0
def next(self) -> int:
return i8(self.fp.read(1))
def peek(self, bits: int) -> int:
while self.bits < bits:
self.bitbuffer = (self.bitbuffer <<... | BitStream |
python | pypa__warehouse | tests/unit/accounts/test_views.py | {
"start": 141737,
"end": 143268
} | class ____:
def test_view_terms_of_service_no_user(self):
user_service = pretend.stub(
record_tos_engagement=pretend.call_recorder(lambda *a, **kw: None)
)
pyramid_request = pretend.stub(
user=None,
find_service=lambda *a, **kw: user_service,
r... | TestViewTermsOfService |
python | doocs__leetcode | solution/1700-1799/1750.Minimum Length of String After Deleting Similar Ends/Solution.py | {
"start": 0,
"end": 338
} | class ____:
def minimumLength(self, s: str) -> int:
i, j = 0, len(s) - 1
while i < j and s[i] == s[j]:
while i + 1 < j and s[i] == s[i + 1]:
i += 1
while i < j - 1 and s[j - 1] == s[j]:
j -= 1
i, j = i + 1, j - 1
return max(... | Solution |
python | pydata__xarray | xarray/backends/zarr.py | {
"start": 20812,
"end": 61244
} | class ____(AbstractWritableDataStore):
"""Store for reading and writing data via zarr"""
__slots__ = (
"_align_chunks",
"_append_dim",
"_cache_members",
"_close_store_on_close",
"_consolidate_on_close",
"_group",
"_members",
"_mode",
"_rea... | ZarrStore |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 28855,
"end": 29224
} | class ____(BaseModel):
"""
Variable serializer for bodies.
"""
model_config = ConfigDict(
extra="forbid",
)
key: Annotated[str, Field(max_length=250, title="Key")]
value: JsonValue
description: Annotated[str | None, Field(title="Description")] = None
team_id: Annotated[UUID ... | VariableBody |
python | tensorflow__tensorflow | tensorflow/python/keras/callbacks.py | {
"start": 34963,
"end": 40633
} | class ____(Callback):
"""Callback that prints metrics to stdout.
Args:
count_mode: One of `"steps"` or `"samples"`.
Whether the progress bar should
count samples seen or steps (batches) seen.
stateful_metrics: Iterable of string names of metrics that
should *not* be averag... | ProgbarLogger |
python | getsentry__sentry | src/sentry/api/fields/serializedfile.py | {
"start": 425,
"end": 1539
} | class ____(serializers.Field):
def __init__(
self,
max_size=settings.SENTRY_MAX_SERIALIZED_FILE_SIZE,
**kwargs,
):
super().__init__(**kwargs)
self.max_size = max_size
def to_representation(self, value):
if not value:
return ""
if not isins... | SerializedFileField |
python | Unity-Technologies__ml-agents | ml-agents-envs/mlagents_envs/side_channel/raw_bytes_channel.py | {
"start": 123,
"end": 1301
} | class ____(SideChannel):
"""
This is an example of what the SideChannel for raw bytes exchange would
look like. Is meant to be used for general research purpose.
"""
def __init__(self, channel_id: uuid.UUID):
self._received_messages: List[bytes] = []
super().__init__(channel_id)
... | RawBytesChannel |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/dsl/expressions/aggregation.py | {
"start": 682,
"end": 10124
} | class ____(Expr):
__slots__ = ("context", "name", "op", "options", "request")
_non_child = ("dtype", "name", "options", "context")
def __init__(
self,
dtype: DataType,
name: str,
options: Any,
context: ExecutionContext,
*children: Expr,
) -> None:
... | Agg |
python | gevent__gevent | src/gevent/tests/test__refcount.py | {
"start": 3457,
"end": 3984
} | class ____(object):
server_data = None
def __init__(self, server_port):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_port = server_port
def close(self):
self.socket.close()
self.socket = None
def make_request(self):
try:
... | Client |
python | apache__airflow | providers/microsoft/azure/src/airflow/providers/microsoft/azure/triggers/powerbi.py | {
"start": 1322,
"end": 2811
} | class ____(BaseTrigger):
"""
Base class for all PowerBI related triggers.
:param conn_id: The connection Id to connect to PowerBI.
:param timeout: The HTTP timeout being used by the `KiotaRequestAdapter` (default is None).
When no timeout is specified or set to None then there is no HTTP timeou... | BasePowerBITrigger |
python | huggingface__transformers | src/transformers/models/vit_mae/modeling_vit_mae.py | {
"start": 17755,
"end": 18256
} | class ____(nn.Module):
def __init__(self, config: ViTMAEConfig):
super().__init__()
self.attention = ViTMAESelfAttention(config)
self.output = ViTMAESelfOutput(config)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
self_attn_output, _ = self.attention(hidden_sta... | ViTMAEAttention |
python | wandb__wandb | wandb/vendor/watchdog_0_9_0/wandb_watchdog/tricks/__init__.py | {
"start": 858,
"end": 1358
} | class ____(PatternMatchingEventHandler):
"""Your tricks should subclass this class."""
@classmethod
def generate_yaml(cls):
context = dict(module_name=cls.__module__,
klass_name=cls.__name__)
template_yaml = """- %(module_name)s.%(klass_name)s:
args:
- argument1
... | Trick |
python | pytorch__pytorch | test/distributed/tensor/test_xla_integration.py | {
"start": 1206,
"end": 6636
} | class ____(TestCase):
class SimpleLinear(nn.Module):
def __init__(self) -> None:
super(DTensorXLAIntegrationTest.SimpleLinear, self).__init__()
self.fc1 = nn.Linear(128, 64)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(64, 1)
def forward(self, x):
... | DTensorXLAIntegrationTest |
python | neetcode-gh__leetcode | python/0081-search-in-rotated-sorted-array-ii.py | {
"start": 0,
"end": 758
} | class ____:
def search(self, nums: List[int], target: int) -> bool:
left,right = 0,len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return True
#Left sorted portion
if nums[left] < nums[mid]:
... | Solution |
python | walkccc__LeetCode | solutions/1564. Put Boxes Into the Warehouse I/1564.py | {
"start": 0,
"end": 400
} | class ____:
def maxBoxesInWarehouse(self, boxes: list[int], warehouse: list[int]) -> int:
realWarehouse = [warehouse[0]]
for i in range(1, len(warehouse)):
realWarehouse.append(min(realWarehouse[-1], warehouse[i]))
boxes.sort()
i = 0 # boxes' index
for height in reversed(realWarehouse):
... | Solution |
python | numpy__numpy | tools/swig/test/testVector.py | {
"start": 10898,
"end": 11163
} | class ____(VectorTestCase):
def __init__(self, methodName="runTest"):
VectorTestCase.__init__(self, methodName)
self.typeStr = "uchar"
self.typeCode = "B"
######################################################################
| ucharTestCase |
python | getsentry__sentry | tests/sentry/api/endpoints/test_project_repo_path_parsing.py | {
"start": 5183,
"end": 14792
} | class ____(BaseStacktraceLinkTest):
def setUp(self) -> None:
super().setUp()
with assume_test_silo_mode(SiloMode.CONTROL):
self.integration, self.oi = self.create_provider_integration_for(
self.org,
self.user,
provider="github",
... | ProjectStacktraceLinkGithubTest |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/triggers/dms.py | {
"start": 4225,
"end": 5719
} | class ____(AwsBaseWaiterTrigger):
"""
Trigger when an AWS DMS Serverless replication completes.
:param replication_config_arn: The ARN of the replication config.
:param waiter_delay: The amount of time in seconds to wait between attempts.
:param waiter_max_attempts: The maximum number of attempts t... | DmsReplicationCompleteTrigger |
python | streamlit__streamlit | lib/streamlit/runtime/media_file_storage.py | {
"start": 1303,
"end": 4375
} | class ____(Protocol):
@abstractmethod
def load_and_get_id(
self,
path_or_data: str | bytes,
mimetype: str,
kind: MediaFileKind,
filename: str | None = None,
) -> str:
"""Load the given file path or bytes into the manager and return
an ID that uniquely ... | MediaFileStorage |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 93305,
"end": 96909
} | class ____:
"""Use this factory class to generate the correct `xxxConfig` object for use when using the `collection.update()` method.
Each staticmethod provides options specific to the named configuration type in the function's name. Under-the-hood data validation steps
will ensure that any mis-specificati... | Reconfigure |
python | pypa__setuptools | setuptools/_distutils/compilers/C/errors.py | {
"start": 492,
"end": 573
} | class ____(Error):
"""Attempt to process an unknown file type."""
| UnknownFileType |
python | eventlet__eventlet | tests/patcher_test.py | {
"start": 612,
"end": 1718
} | class ____(tests.LimitedTestCase):
TEST_TIMEOUT = 3 # starting processes is time-consuming
def setUp(self):
super().setUp()
self._saved_syspath = sys.path
self.tempdir = tempfile.mkdtemp('_patcher_test')
def tearDown(self):
super().tearDown()
sys.path = self._saved... | ProcessBase |
python | psf__black | tests/data/cases/remove_newline_after_code_block_open.py | {
"start": 363,
"end": 1981
} | class ____:
def bar(self):
print("The newline above me should be kept!")
for i in range(5):
print(f"{i}) The line above me should be kept!")
for i in range(5):
print(f"{i}) The lines above me should be kept!")
for i in range(5):
for j in range(7):
print(f"{i}) The lines abov... | Foo |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 519530,
"end": 519916
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("field", "repository")
field = sgqlc.types.Field(
sgqlc.types.non_null("ProjectV2FieldConfiguration"), graphql_name="field"
)
repository = sgqlc.types.Field("Repos... | ProjectV2ItemFieldRepositoryValue |
python | huggingface__transformers | src/transformers/models/lxmert/modeling_lxmert.py | {
"start": 30801,
"end": 38064
} | class ____(LxmertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.embeddings = LxmertEmbeddings(config)
self.encoder = LxmertEncoder(config)
self.pooler = LxmertPooler(config)
# Initialize weights and apply final processing
self.post_init()
... | LxmertModel |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 46129,
"end": 46284
} | class ____(Elemwise):
_projection_passthrough = True
_parameters = ["frame", "value"]
_defaults = {"value": None}
operation = M.fillna
| Fillna |
python | numpy__numpy | tools/swig/test/testSuperTensor.py | {
"start": 14892,
"end": 15217
} | class ____(SuperTensorTestCase):
def __init__(self, methodName="runTest"):
SuperTensorTestCase.__init__(self, methodName)
self.typeStr = "ulongLong"
self.typeCode = "Q"
#self.result = int(self.result)
######################################################################
| ulongLongTestCase |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/datafusion.py | {
"start": 25794,
"end": 29445
} | class ____(GoogleCloudBaseOperator):
"""
Lists Cloud Data Fusion pipelines.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudDataFusionListPipelinesOperator`
:param instance_name: The name of the instance.
:param lo... | CloudDataFusionListPipelinesOperator |
python | sympy__sympy | sympy/physics/quantum/pauli.py | {
"start": 4797,
"end": 6636
} | class ____(SigmaOpBase):
"""Pauli sigma z operator
Parameters
==========
name : str
An optional string that labels the operator. Pauli operators with
different names commute.
Examples
========
>>> from sympy.physics.quantum import represent
>>> from sympy.physics.quan... | SigmaZ |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/figma/tests.py | {
"start": 238,
"end": 741
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = FigmaProvider.id
def get_mocked_response(self):
return MockedResponse(
HTTPStatus.OK,
"""
{
"id": "2600",
"email": "johndoe@example.com",
"handle": "John D... | FigmaTests |
python | cython__cython | Cython/Compiler/PyrexTypes.py | {
"start": 75479,
"end": 77772
} | class ____(CType):
#
# Base class for all C numeric types.
#
# rank integer Relative size
# signed integer 0 = unsigned, 1 = unspecified, 2 = explicitly signed
#
is_numeric = 1
default_value = "0"
has_attributes = True
scope = None
sign_words = ("unsig... | CNumericType |
python | streamlit__streamlit | lib/tests/streamlit/runtime/caching/hashing_test.py | {
"start": 4410,
"end": 24623
} | class ____(unittest.TestCase):
def test_string(self):
assert get_hash("hello") == get_hash("hello")
assert get_hash("hello") != get_hash("hellö")
def test_int(self):
assert get_hash(145757624235) == get_hash(145757624235)
assert get_hash(10) != get_hash(11)
assert get_ha... | HashTest |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/parsers/key_value_parsers.py | {
"start": 6378,
"end": 7380
} | class ____(KeyValueParser):
"""Composite argument parser for Windows remote key/value pairs."""
def get_parsers(self, state: ParserState) -> dict[str, Parser]:
"""Return a dictionary of key names and value parsers."""
return dict(
provider=ChoicesParser(REMOTE_PROVIDERS),
... | WindowsRemoteKeyValueParser |
python | pyca__cryptography | src/cryptography/x509/extensions.py | {
"start": 54140,
"end": 54914
} | class ____(ExtensionType):
oid = CRLEntryExtensionOID.CRL_REASON
def __init__(self, reason: ReasonFlags) -> None:
if not isinstance(reason, ReasonFlags):
raise TypeError("reason must be an element from ReasonFlags")
self._reason = reason
def __repr__(self) -> str:
retu... | CRLReason |
python | openai__openai-python | src/openai/types/audio/transcription_create_params.py | {
"start": 5502,
"end": 6156
} | class ____(TranscriptionCreateParamsBase, total=False):
stream: Optional[Literal[False]]
"""
If set to true, the model response data will be streamed to the client as it is
generated using
[server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_even... | TranscriptionCreateParamsNonStreaming |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 246971,
"end": 254474
} | class ____(ExternKernel):
def get_kernel_and_metadata(self) -> tuple[Kernel, Any, list[str], list[str]]:
from triton.runtime.autotuner import Autotuner
from torch._higher_order_ops.triton_kernel_wrap import kernel_side_table
kernel = kernel_side_table.get_kernel(self.kernel_idx)
co... | UserDefinedTritonKernel |
python | langchain-ai__langchain | libs/core/langchain_core/language_models/fake_chat_models.py | {
"start": 5985,
"end": 6940
} | class ____(SimpleChatModel):
"""Fake Chat Model wrapper for testing purposes."""
@override
def _call(
self,
messages: list[BaseMessage],
stop: list[str] | None = None,
run_manager: CallbackManagerForLLMRun | None = None,
**kwargs: Any,
) -> str:
return "f... | FakeChatModel |
python | viewflow__viewflow | viewflow/workflow/flow/views/filters.py | {
"start": 345,
"end": 611
} | class ____(DateRangeFilter):
def filter(self, qs, value):
if not value:
if not self.parent.data.get("status"):
return qs.filter(**{f"{self.field_name}__isnull": True})
return super().filter(qs, value)
| NullDateRangeFilter |
python | pydantic__pydantic | pydantic/_internal/_decorators_v1.py | {
"start": 3867,
"end": 4075
} | class ____(Protocol):
"""A simple root validator, supported for V1 validators and V2 validators."""
def __call__(self, __values: RootValidatorValues) -> RootValidatorValues: ...
| V1RootValidatorFunction |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/black/cases/preview_comments7.py | {
"start": 1867,
"end": 4303
} | class ____:
@pytest.mark.parametrize(
("post_data", "message"),
[
# metadata_version errors.
(
{},
"None is an invalid value for Metadata-Version. Error: This field is"
" required. see"
" https://packaging.python... | C |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_releases.py | {
"start": 49591,
"end": 82320
} | class ____(APITestCase):
def test_empty_release_version(self) -> None:
user = self.create_user(is_staff=False, is_superuser=False)
org = self.create_organization()
org.flags.allow_joinleave = False
org.save()
team = self.create_team(organization=org)
project = self.c... | OrganizationReleaseCreateTest |
python | wandb__wandb | tools/perf/scripts/bench_run_log.py | {
"start": 759,
"end": 11258
} | class ____:
"""Generates a payload for logging in the performance testing.
Args:
data_type: The type of data to log.
sparse_metric_count: Number of sparse metrics to log.
metric_key_size: The size (in characters) of the metric.
num_steps: Number of steps in the test.
fra... | PayloadGenerator |
python | dask__distributed | distributed/comm/inproc.py | {
"start": 642,
"end": 2279
} | class ____:
"""
An object coordinating listeners and their addresses.
"""
def __init__(self):
self.listeners = weakref.WeakValueDictionary()
self.addr_suffixes = itertools.count(1)
self._ip = None
self.lock = threading.Lock()
@property
def ip(self):
if n... | Manager |
python | pikepdf__pikepdf | src/pikepdf/models/encryption.py | {
"start": 4719,
"end": 6151
} | class ____(NamedTuple):
"""Specify the encryption settings to apply when a PDF is saved."""
owner: str = ''
"""The owner password to use. This allows full control
of the file. If blank, the PDF will be encrypted and
present as "(SECURED)" in PDF viewers. If the owner password
is blank, the user... | Encryption |
python | bokeh__bokeh | tests/unit/bokeh/models/widgets/test_slider.py | {
"start": 2866,
"end": 4860
} | class ____:
def test_value_and_value_throttled(self) -> None:
start = datetime(2021, 1, 1)
end = datetime(2021, 12, 31)
value = convert_date_to_datetime(datetime(2021, 2, 1))
s0 = mws.DateSlider(start=start, end=end)
with pytest.raises(UnsetValueError):
s0.value
... | TestDateSlider |
python | django-extensions__django-extensions | tests/testapp/models.py | {
"start": 6583,
"end": 6895
} | class ____(models.Model):
title = models.CharField(max_length=42)
slug = AutoSlugField(populate_from="title")
category = models.CharField(max_length=20, null=True)
class Meta:
app_label = "django_extensions"
unique_together = ["slug", "category"]
| SluggedWithUniqueTogetherTestModel |
python | fastai__fastai | fastai/callback/data.py | {
"start": 345,
"end": 687
} | class ____(Callback):
"Collect all batches, along with `pred` and `loss`, into `self.data`. Mainly for testing"
def before_fit(self): self.data = L()
def after_batch(self):
self.data.append(self.learn.to_detach((self.xb,self.yb,self.pred,self.loss)))
# %% ../../nbs/14a_callback.data.ipynb 6
@deleg... | CollectDataCallback |
python | huggingface__transformers | src/transformers/models/dab_detr/modeling_dab_detr.py | {
"start": 11963,
"end": 16332
} | class ____(nn.Module):
"""
This is a more standard version of the position embedding, very similar to the one used by the Attention is all you
need paper, generalized to work on images.
"""
def __init__(self, config: DabDetrConfig):
super().__init__()
self.config = config
se... | DabDetrSinePositionEmbedding |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 294800,
"end": 295253
} | class ____(sgqlc.types.Input):
"""Ordering options for saved reply connections."""
__schema__ = github_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(sgqlc.types.non_null(SavedReplyOrderField), graphql_name="field")
"""The field to order saved replies by."""
directio... | SavedReplyOrder |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/utils/kubernetes.py | {
"start": 5345,
"end": 5560
} | class ____(BaseModel):
model_config = {
"extra": "allow",
"json_schema_extra": {
"$ref": create_definition_ref("io.k8s.api.apps.v1.DeploymentStrategy")
},
}
| DeploymentStrategy |
python | langchain-ai__langchain | libs/core/tests/unit_tests/tracers/test_base_tracer.py | {
"start": 723,
"end": 22457
} | class ____(BaseTracer):
"""Fake tracer that records LangChain execution."""
def __init__(self) -> None:
"""Initialize the tracer."""
super().__init__()
self.runs: list[Run] = []
def _persist_run(self, run: Run) -> None:
"""Persist a run."""
self.runs.append(run)
d... | FakeTracer |
python | spack__spack | lib/spack/spack/fetch_strategy.py | {
"start": 66220,
"end": 66340
} | class ____(spack.error.FetchError):
"""Raised when we can't extrapolate a version for a package."""
| ExtrapolationError |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/runs/base.py | {
"start": 1028,
"end": 1115
} | class ____(TypedDict):
count: int
runs: Sequence[DagsterRun]
@public
| RunGroupInfo |
python | getsentry__sentry | src/social_auth/exceptions.py | {
"start": 2199,
"end": 2366
} | class ____(AuthException):
"""State parameter is incorrect."""
def __str__(self) -> str:
return gettext("Session value state missing.")
| AuthStateMissing |
python | pytorch__pytorch | torch/export/dynamic_shapes.py | {
"start": 8477,
"end": 9010
} | class ____(Dim):
"""
Class for static :func:`Dim` types.
This class is only for setting and checking static dim constraints,
and the user should never interact with it.
"""
def __init__(self, value: int):
self.__name__ = str(value)
self.value = value
@property
def min(... | _StaticDim |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.