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/dagster/dagster/_core/definitions/input.py | {
"start": 12512,
"end": 12828
} | class ____(NamedTuple("_InputPointer", [("node_name", str), ("input_name", str)])):
def __new__(cls, node_name: str, input_name: str):
return super().__new__(
cls,
check.str_param(node_name, "node_name"),
check.str_param(input_name, "input_name"),
)
| InputPointer |
python | walkccc__LeetCode | solutions/146. LRU Cache/146.py | {
"start": 142,
"end": 1219
} | class ____:
def __init__(self, capacity: int):
self.capacity = capacity
self.keyToNode = {}
self.head = Node(-1, -1)
self.tail = Node(-1, -1)
self.join(self.head, self.tail)
def get(self, key: int) -> int:
if key not in self.keyToNode:
return -1
node = self.keyToNode[key]
sel... | LRUCache |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/elements.py | {
"start": 178186,
"end": 182472
} | class ____(util.MemoizedSlots, str):
"""Represent a SQL identifier combined with quoting preferences.
:class:`.quoted_name` is a Python unicode/str subclass which
represents a particular identifier name along with a
``quote`` flag. This ``quote`` flag, when set to
``True`` or ``False``, overrides ... | quoted_name |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/svd_op_test.py | {
"start": 13914,
"end": 17625
} | class ____(test.Benchmark):
shapes = [
(4, 4),
(8, 8),
(16, 16),
(101, 101),
(256, 256),
(1024, 1024),
(2048, 2048),
(1, 8, 8),
(10, 8, 8),
(100, 8, 8),
(1000, 8, 8),
(1, 32, 32),
(10, 32, 32),
(100, 32, 32),
(1000, 32, 32),
... | SVDBenchmark |
python | getsentry__sentry | src/sentry/notifications/platform/templates/sample.py | {
"start": 868,
"end": 4384
} | class ____(NotificationTemplate[ErrorAlertData]):
category = NotificationCategory.DEBUG
example_data = ErrorAlertData(
error_type="ValueError",
error_message="'NoneType' object has no attribute 'get'",
project_name="my-app",
issue_id="12345",
error_count=15,
first... | ErrorAlertNotificationTemplate |
python | doocs__leetcode | solution/1400-1499/1406.Stone Game III/Solution.py | {
"start": 0,
"end": 540
} | class ____:
def stoneGameIII(self, stoneValue: List[int]) -> str:
@cache
def dfs(i: int) -> int:
if i >= n:
return 0
ans, s = -inf, 0
for j in range(3):
if i + j >= n:
break
s += stoneValue[i + j]... | Solution |
python | pypa__packaging | src/packaging/specifiers.py | {
"start": 26668,
"end": 39539
} | class ____(BaseSpecifier):
"""This class abstracts handling of a set of version specifiers.
It can be passed a single specifier (``>=3.0``), a comma-separated list of
specifiers (``>=3.0,!=3.1``), or no specifier at all.
"""
__slots__ = ("_prereleases", "_specs")
def __init__(
self,
... | SpecifierSet |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 397284,
"end": 397570
} | class ____(BatchRequest):
"""
Updates a batch of tasks.
Headers
Content type should be 'application/json-lines'.
"""
_service = "tasks"
_action = "update_batch"
_version = "2.13"
_batched_request_cls = UpdateRequest
| UpdateBatchRequest |
python | getsentry__sentry | src/sentry/api/serializers/base.py | {
"start": 2762,
"end": 4730
} | class ____:
"""A Serializer class contains the logic to serialize a specific type of object."""
def __call__(
self,
obj: Any,
attrs: Mapping[Any, Any],
user: User | RpcUser | AnonymousUser,
**kwargs: Any,
) -> Mapping[str, Any] | None:
"""See documentation fo... | Serializer |
python | matplotlib__matplotlib | lib/matplotlib/collections.py | {
"start": 93090,
"end": 97068
} | class ____(_MeshData, Collection):
r"""
Class for the efficient drawing of a quadrilateral mesh.
A quadrilateral mesh is a grid of M by N adjacent quadrilaterals that are
defined via a (M+1, N+1) grid of vertices. The quadrilateral (m, n) is
defined by the vertices ::
(m+1, n) -----... | QuadMesh |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/ddl.py | {
"start": 34021,
"end": 34159
} | class ____(_CreateBase["Sequence"]):
"""Represent a CREATE SEQUENCE statement."""
__visit_name__ = "create_sequence"
| CreateSequence |
python | dask__dask | dask/dataframe/dask_expr/_merge.py | {
"start": 18842,
"end": 24040
} | class ____(Merge, PartitionsFiltered):
_parameters = [
"left",
"right",
"how",
"left_on",
"right_on",
"left_index",
"right_index",
"suffixes",
"indicator",
"_partitions",
"shuffle_left_on",
"shuffle_right_on",
"_... | HashJoinP2P |
python | walkccc__LeetCode | solutions/1420. Build Array Where You Can Find The Maximum Exactly K Comparisons/1420.py | {
"start": 0,
"end": 947
} | class ____:
def numOfArrays(self, n: int, m: int, k: int) -> int:
MOD = 1_000_000_007
# dp[i][j][k] := the number of ways to build an array of length i, where j
# is the maximum number and k is `search_cost`
dp = [[[0] * (k + 1) for j in range(m + 1)] for _ in range(n + 1)]
for j in range(1, m + ... | Solution |
python | ansible__ansible | test/lib/ansible_test/_internal/classification/__init__.py | {
"start": 5434,
"end": 34143
} | class ____:
"""Map file paths to test commands and targets."""
def __init__(self, args: TestConfig) -> None:
self.args = args
self.integration_all_target = get_integration_all_target(self.args)
self.integration_targets = list(walk_integration_targets())
self.module_targets = li... | PathMapper |
python | neetcode-gh__leetcode | python/0682-baseball-game.py | {
"start": 0,
"end": 792
} | class ____:
def calPoints(self, operations: List[str]) -> int:
score_stack = []
for o in operations:
# it is +, D, or C
# if stack isn't of sufficient length, then operation is voided
if o == "+" and len(score_stack) >= 2:
... | Solution |
python | altair-viz__altair | altair/vegalite/v6/schema/_config.py | {
"start": 73219,
"end": 74292
} | class ____(TypedDict, total=False):
"""
:class:`altair.CompositionConfig` ``TypedDict`` wrapper.
Parameters
----------
columns
The number of columns to include in the view composition layout.
**Default value**: ``undefined`` -- An infinite number of columns (a single row)
w... | CompositionConfigKwds |
python | ansible__ansible | test/lib/ansible_test/_internal/host_configs.py | {
"start": 4683,
"end": 5446
} | class ____(PythonConfig):
"""Configuration for Python in a virtual environment."""
system_site_packages: t.Optional[bool] = None
def apply_defaults(self, context: HostContext, defaults: PosixCompletionConfig) -> None:
"""Apply default settings."""
super().apply_defaults(context, defaults)
... | VirtualPythonConfig |
python | ray-project__ray | python/ray/data/preprocessors/vectorizer.py | {
"start": 7094,
"end": 13502
} | class ____(Preprocessor):
"""Count the frequency of tokens in a column of strings.
:class:`CountVectorizer` operates on columns that contain strings. For example:
.. code-block::
corpus
0 I dislike Python
1 I like Python
This preprocessor creates a li... | CountVectorizer |
python | squidfunk__mkdocs-material | material/plugins/projects/builder/log.py | {
"start": 1529,
"end": 4033
} | class ____(Filter):
# Filter log messages
def filter(self, record):
message = record.getMessage()
return not message.startswith("A 'dirty' build")
# -----------------------------------------------------------------------------
# Functions
# -----------------------------------------------------... | ProjectsFilter |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/instancenorm_test.py | {
"start": 285,
"end": 920
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, dims):
num_channels = dims[1]
self.inputs = {
"input": (torch.rand(*dims) - 0.5) * 256,
"weight": torch.rand(num_channels, dtype=torch.float),
"bias": torch.rand(num_channels, dtype=torch.float),
... | InstanceNormBenchmark |
python | lepture__authlib | authlib/jose/errors.py | {
"start": 158,
"end": 232
} | class ____(JoseError):
error = "missing_algorithm"
| MissingAlgorithmError |
python | tensorflow__tensorflow | tensorflow/python/framework/convert_to_constants.py | {
"start": 2151,
"end": 2414
} | class ____(
collections.namedtuple("_TensorData", ["numpy", "dtype", "index"])):
"""Data about a tensor that was converted to a constant."""
__slots__ = ()
@property
def dtype_attr(self):
return attr_value_pb2.AttrValue(type=self.dtype)
| _TensorData |
python | lazyprogrammer__machine_learning_examples | ab_testing/optimistic.py | {
"start": 505,
"end": 1914
} | class ____:
def __init__(self, p):
# p: the win rate
self.p = p
self.p_estimate = 5.
self.N = 1. # num samples collected so far
def pull(self):
# draw a 1 with probability p
return np.random.random() < self.p
def update(self, x):
self.N += 1.
self.p_estimate = ((self.N - 1)*self.... | Bandit |
python | lepture__authlib | authlib/jose/errors.py | {
"start": 2584,
"end": 2781
} | class ____(JoseError):
error = "missing_claim"
def __init__(self, claim):
description = f"Missing '{claim}' claim"
super().__init__(description=description)
| MissingClaimError |
python | tensorflow__tensorflow | tensorflow/python/ops/clustering_ops_test.py | {
"start": 933,
"end": 2048
} | class ____(test.TestCase):
# All but one input point are close to (101, 1). With uniform random sampling,
# it is highly improbable for (-1, -1) to be selected.
def setUp(self):
self._points = np.array([[100., 0.],
[101., 2.],
[102., 0.],
... | KmeansPlusPlusInitializationTest |
python | getsentry__sentry | src/sentry/api/event_search.py | {
"start": 15638,
"end": 16393
} | class ____(NamedTuple):
name: str
@property
def is_tag(self) -> bool:
return bool(TAG_KEY_RE.match(self.name)) or (
self.name not in SEARCH_MAP
and self.name not in FIELD_ALIASES
and not self.is_measurement
and not self.is_span_op_breakdown
)
... | SearchKey |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1147107,
"end": 1147367
} | class ____(VegaLiteSchema):
"""ScaleInvalidDataShowAstheta schema wrapper."""
_schema = {"$ref": '#/definitions/ScaleInvalidDataShowAs<"theta">'}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| ScaleInvalidDataShowAstheta |
python | redis__redis-py | redis/commands/search/__init__.py | {
"start": 5732,
"end": 5841
} | class ____(AsyncSearchCommands, AsyncioPipeline, Pipeline):
"""AsyncPipeline for the module."""
| AsyncPipeline |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-google/llama_index/readers/google/docs/base.py | {
"start": 1173,
"end": 9026
} | class ____(BasePydanticReader):
"""
Google Docs reader.
Reads a page from Google Docs
"""
is_remote: bool = True
split_on_heading_level: Optional[int] = Field(
default=None,
description="If set the document will be split on the specified heading level.",
)
include_to... | GoogleDocsReader |
python | run-llama__llama_index | llama-index-integrations/storage/chat_store/llama-index-storage-chat-store-azurecosmosmongovcore/llama_index/storage/chat_store/azurecosmosmongovcore/base.py | {
"start": 848,
"end": 5452
} | class ____(BaseChatStore, ABC):
"""Creates an Azure Cosmos DB NoSql Chat Store."""
_mongo_client = MongoClient
_database = Database
_collection = Collection
def __init__(
self,
mongo_client: MongoClient,
uri: Optional[str] = None,
host: Optional[str] = None,
... | AzureCosmosMongoVCoreChatStore |
python | gevent__gevent | src/gevent/events.py | {
"start": 9713,
"end": 9986
} | class ____(Interface):
"""
The root for all monkey-patch events gevent emits.
"""
source = Attribute("The source object containing the patches.")
target = Attribute("The destination object to be patched.")
@implementer(IGeventPatchEvent)
| IGeventPatchEvent |
python | fastai__fastai | fastai/test_utils.py | {
"start": 1171,
"end": 1778
} | class ____(Module):
def __init__(self): self.a,self.b = nn.Parameter(torch.randn(1)),nn.Parameter(torch.randn(1))
def forward(self, x): return x*self.a + self.b
# %% ../nbs/97_test_utils.ipynb 6
@delegates(Learner.__init__)
def synth_learner(n_trn=10, n_val=2, cuda=False, lr=1e-3, data=None, model=None, **kwar... | RegModel |
python | huggingface__transformers | src/transformers/models/led/modeling_led.py | {
"start": 90959,
"end": 101887
} | class ____(LEDPreTrainedModel, GenerationMixin):
base_model_prefix = "led"
_keys_to_ignore_on_load_missing = ["final_logits_bias"]
_tied_weights_keys = {
"lm_head.weight": "led.shared.weight",
}
def __init__(self, config: LEDConfig):
super().__init__(config)
self.led = LEDMo... | LEDForConditionalGeneration |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 42923,
"end": 43250
} | class ____(fftw_info):
section = 'fftw'
dir_env_var = 'FFTW'
ver_info = [{'name':'sfftw threads',
'libs':['srfftw_threads', 'sfftw_threads'],
'includes':['sfftw_threads.h', 'srfftw_threads.h'],
'macros':[('SCIPY_SFFTW_THREADS_H', None)]}]
| sfftw_threads_info |
python | PrefectHQ__prefect | tests/cli/test_start_server.py | {
"start": 12184,
"end": 14738
} | class ____:
@pytest.mark.skipif(
sys.platform == "win32",
reason="SIGTERM is only used in non-Windows environments",
)
async def test_sigint_shutsdown_cleanly(self):
async with start_server_process() as server_process:
server_process.send_signal(signal.SIGINT)
... | TestUvicornSignalForwarding |
python | huggingface__transformers | tests/models/superglue/test_modeling_superglue.py | {
"start": 1256,
"end": 4356
} | class ____:
def __init__(
self,
parent,
batch_size=2,
image_width=80,
image_height=60,
keypoint_detector_config=None,
hidden_size: int = 64,
keypoint_encoder_sizes: list[int] = [32, 64],
gnn_layers_types: list[str] = ["self", "cross"] * 2,
... | SuperGlueModelTester |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 87894,
"end": 89047
} | class ____(Response):
"""
Response of tasks.archive endpoint.
:param archived: Indicates number of archived tasks
:type archived: int
"""
_service = "tasks"
_action = "archive"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"archived": ... | ArchiveResponse |
python | kamyu104__LeetCode-Solutions | Python/minimum-domino-rotations-for-equal-row.py | {
"start": 48,
"end": 423
} | class ____(object):
def minDominoRotations(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: int
"""
intersect = reduce(set.__and__, [set(d) for d in itertools.izip(A, B)])
if not intersect:
return -1
x = intersect.pop()
... | Solution |
python | pytorch__pytorch | torch/testing/_internal/optests/generate_tests.py | {
"start": 16904,
"end": 26700
} | class ____(TorchFunctionMode):
"""
For a given test, OpCheckMode intercepts calls to operators and runs
test_util(op, args, kwargs) for each intercepted (op, args, kwargs).
"""
def __init__(
self,
namespaces: list[str],
test_util_name: str,
test_util: Callable,
... | OpCheckMode |
python | redis__redis-py | tests/test_maint_notifications_handling.py | {
"start": 93103,
"end": 104454
} | class ____(
TestMaintenanceNotificationsBase
):
"""Integration tests for maintenance notifications handling with real connection pool."""
def setup_method(self):
"""Set up test fixtures with mocked sockets."""
super().setup_method()
self.orig_host = "test.address.com"
ips =... | TestMaintenanceNotificationsHandlingMultipleProxies |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_illinois_zip.py | {
"start": 1751,
"end": 4094
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid Illinois zipcodes.
See https://pypi.org/project/zipcodes/ for more information.
"""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
... | ExpectColumnValuesToBeValidIllinoisZip |
python | matplotlib__matplotlib | lib/matplotlib/scale.py | {
"start": 25976,
"end": 26449
} | class ____(Transform):
input_dims = output_dims = 1
def __init__(self, nonpositive='mask'):
super().__init__()
self._nonpositive = nonpositive
def transform_non_affine(self, values):
"""logistic transform (base 10)"""
return 1.0 / (1 + 10**(-values))
def inverted(self)... | LogisticTransform |
python | openai__openai-python | src/openai/types/evals/run_create_params.py | {
"start": 6301,
"end": 6608
} | class ____(
TypedDict, total=False
):
text: Required[str]
"""The text output from the model."""
type: Required[Literal["output_text"]]
"""The type of the output text. Always `output_text`."""
| DataSourceCreateEvalResponsesRunDataSourceInputMessagesTemplateTemplateEvalItemContentOutputText |
python | huggingface__transformers | tests/models/deepseek_vl/test_modeling_deepseek_vl.py | {
"start": 1287,
"end": 4270
} | class ____:
def __init__(
self,
parent,
batch_size=2,
seq_length=25,
num_channels=3,
initializer_range=0.02,
is_training=True,
use_cache=False,
text_config={
"num_hidden_layers": 2,
"vocab_size": 99,
"hidden_... | DeepseekVLModelTester |
python | kamyu104__LeetCode-Solutions | Python/substring-matching-pattern.py | {
"start": 40,
"end": 1160
} | class ____(object):
def hasMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
def getPrefix(pattern):
prefix = [-1]*len(pattern)
j = -1
for i in xrange(1, len(pattern)):
while j+1 > 0 and pattern[j+1] ... | Solution |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_base.py | {
"start": 1352,
"end": 1922
} | class ____:
def test_handles_deepcopy_with_method_default(self):
op = GoogleSampleOperator(task_id=TASK_ID)
copied_op = copy.deepcopy(op)
assert copied_op.retry == DEFAULT
assert copied_op.config is None
def test_handles_deepcopy_with_non_default_retry(self):
op = Googl... | TestGoogleCloudBaseOperator |
python | apache__avro | lang/py/avro/io.py | {
"start": 41548,
"end": 52013
} | class ____:
"""DatumWriter for generic python objects."""
_writers_schema: Optional[avro.schema.Schema]
def __init__(self, writers_schema: Optional[avro.schema.Schema] = None) -> None:
self._writers_schema = writers_schema
@property
def writers_schema(self) -> Optional[avro.schema.Schema]... | DatumWriter |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/zip_test.py | {
"start": 8582,
"end": 14518
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(
combinations.times(test_base.default_test_combinations(),
combinations.combine(index=[-1, 3, 4])))
def testInvalidIndex(self, index):
dataset = dataset_ops.Dataset.zip(
(dataset_ops.Dat... | ZipRandomAccessTest |
python | PrefectHQ__prefect | tests/test_tasks.py | {
"start": 143537,
"end": 149317
} | class ____:
def test_noniterable_hook_raises(self):
def failure_hook():
pass
with pytest.raises(
TypeError,
match=re.escape(
"Expected iterable for 'on_failure'; got function instead. Please"
" provide a list of hooks to 'on_failur... | TestTaskHooksOnFailure |
python | pypa__warehouse | warehouse/utils/enum.py | {
"start": 78,
"end": 396
} | class ____(str, enum.Enum):
"""Base class for Enum with string value and display label."""
label: str
# Name = "value", _("Label")
def __new__(cls, value: str, label: str) -> Self:
obj = str.__new__(cls, value)
obj._value_ = value
obj.label = label
return obj
| StrLabelEnum |
python | encode__django-rest-framework | tests/test_views.py | {
"start": 2389,
"end": 2841
} | class ____(TestCase):
def setUp(self):
self.view = basic_view
def test_400_parse_error(self):
request = factory.post('/', 'f00bar', content_type='application/json')
response = self.view(request)
expected = {
'detail': JSON_ERROR
}
assert response.stat... | FunctionBasedViewIntegrationTests |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1232730,
"end": 1234639
} | class ____(sgqlc.types.Type, Node):
"""Entries in a MergeQueue"""
__schema__ = github_schema
__field_names__ = (
"base_commit",
"enqueued_at",
"enqueuer",
"estimated_time_to_merge",
"head_commit",
"jump",
"merge_queue",
"position",
"pu... | MergeQueueEntry |
python | ray-project__ray | python/ray/_common/tests/test_formatters.py | {
"start": 4042,
"end": 5149
} | class ____:
def test_record_with_user_provided_context(self):
formatter = TextFormatter()
record = logging.makeLogRecord({"user": "ray"})
formatted = formatter.format(record)
assert "user=ray" in formatted
def test_record_with_exception(self):
formatter = TextFormatter()... | TestTextFormatter |
python | python-visualization__folium | folium/features.py | {
"start": 48821,
"end": 51042
} | class ____(GeoJsonDetail):
"""
Create a popup feature to bind to each element of a GeoJson layer based on
its attributes.
Parameters
----------
fields: list or tuple.
Labels of GeoJson/TopoJson 'properties' or GeoPandas GeoDataFrame
columns you'd like to display.
aliases: li... | GeoJsonPopup |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_imsi.py | {
"start": 855,
"end": 1842
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.to_be_valid_imsi"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas... | ColumnValuesToBeValidImsi |
python | apache__airflow | providers/google/tests/unit/google/cloud/sensors/test_dataform.py | {
"start": 1433,
"end": 6524
} | class ____:
@pytest.mark.parametrize(
("expected_status", "current_status", "sensor_return"),
[
(WorkflowInvocationAction.State.SUCCEEDED, WorkflowInvocationAction.State.SUCCEEDED, True),
(WorkflowInvocationAction.State.SUCCEEDED, WorkflowInvocationAction.State.RUNNING, False... | TestDataformWorkflowInvocationActionStateSensor |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/shortcuts/progress_bar/formatters.py | {
"start": 5900,
"end": 6876
} | class ____(Formatter):
"""
Display the progress as text. E.g. "8/20"
"""
template = HTML("<current>{current:>3}</current>/<total>{total:>3}</total>")
def format(
self,
progress_bar: ProgressBar,
progress: ProgressBarCounter[object],
width: int,
) -> AnyFormatte... | Progress |
python | getsentry__sentry | fixtures/safe_migrations_apps/bad_flow_change_char_type_that_unsafe_app/migrations/0002_change_type_from_char120_to_char100.py | {
"start": 153,
"end": 469
} | class ____(CheckedMigration):
dependencies = [
("bad_flow_change_char_type_that_unsafe_app", "0001_initial"),
]
operations = [
migrations.AlterField(
model_name="testtable",
name="field",
field=models.CharField(max_length=100),
),
]
| Migration |
python | gevent__gevent | src/gevent/pool.py | {
"start": 1132,
"end": 11662
} | class ____(object):
# Internal, non-public API class.
# Provides mixin methods for implementing mapping pools. Subclasses must define:
__slots__ = ()
def spawn(self, func, *args, **kwargs):
"""
A function that runs *func* with *args* and *kwargs*, potentially
asynchronously. Re... | GroupMappingMixin |
python | joke2k__faker | faker/providers/lorem/fr_FR/__init__.py | {
"start": 68,
"end": 26958
} | class ____(LoremProvider):
"""Implement lorem provider for ``fr_FR`` locale.
Word list is drawn from the French Education Ministry's website Eduscol. The
"lexical frequency list" can be found in the source(s) below.
Sources:
- http://eduscol.education.fr/cid47915/liste-des-mots-classee-par-ordre-... | Provider |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/loop18.py | {
"start": 168,
"end": 203
} | class ____:
parent: Self | None
| A |
python | openai__openai-python | src/openai/types/fine_tuning/fine_tuning_job_wandb_integration.py | {
"start": 202,
"end": 1026
} | class ____(BaseModel):
project: str
"""The name of the project that the new run will be created under."""
entity: Optional[str] = None
"""The entity to use for the run.
This allows you to set the team or username of the WandB user that you would
like associated with the run. If not set, the de... | FineTuningJobWandbIntegration |
python | joke2k__faker | faker/providers/bank/no_NO/__init__.py | {
"start": 42,
"end": 185
} | class ____(BankProvider):
"""Implement bank provider for ``no_NO`` locale."""
bban_format = "###########"
country_code = "NO"
| Provider |
python | celery__celery | celery/bin/base.py | {
"start": 8513,
"end": 9174
} | class ____(click.Choice):
"""Log level option."""
def __init__(self):
"""Initialize the log level option with the relevant choices."""
super().__init__(('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL', 'FATAL'))
def convert(self, value, param, ctx):
if isinstance(value, numbers.Int... | LogLevel |
python | ansible__ansible | lib/ansible/_internal/_templating/_jinja_bits.py | {
"start": 16825,
"end": 17200
} | class ____(_ambient_context.AmbientContextBase):
"""
This context is active during Ansible's explicit compilation of templates/expressions, but not during Jinja's runtime compilation.
Historically, Ansible-specific pre-processing like `escape_backslashes` was not applied to imported/included templates.
... | _TemplateCompileContext |
python | huggingface__transformers | src/transformers/utils/chat_template_utils.py | {
"start": 23051,
"end": 23630
} | class ____:
"""This class is intended to just be used internally for pipelines and not exposed to users. We convert chats
to this format because the rest of the pipeline code tends to assume that lists of messages are
actually a batch of samples rather than messages in the same conversation."""
def __i... | Chat |
python | PrefectHQ__prefect | tests/blocks/test_block_reference.py | {
"start": 2937,
"end": 6598
} | class ____:
@pytest.fixture
def ParamBlock(self) -> Type[Block]:
# Ignore warning caused by matching key in registry due to block fixture
warnings.filterwarnings("ignore", category=UserWarning)
class ParamBlock(Block):
a: int
b: str
return ParamBlock
... | TestFlowWithBlockParam |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess1.py | {
"start": 619,
"end": 847
} | class ____:
bar = DescriptorA[str]()
@classmethod
def func1(cls):
a: DescriptorA[str] = cls.bar
reveal_type(ClassA.bar, expected_text="DescriptorA[str]")
reveal_type(ClassA().bar, expected_text="str")
| ClassA |
python | great-expectations__great_expectations | great_expectations/expectations/metrics/column_aggregate_metrics/column_proportion_of_unique_values.py | {
"start": 1490,
"end": 3125
} | class ____(ColumnAggregateMetricProvider):
metric_name = "column.unique_proportion"
@metric_value(engine=PandasExecutionEngine)
def _pandas(*args, metrics, **kwargs):
return unique_proportion(metrics)
@metric_value(engine=SqlAlchemyExecutionEngine)
def _sqlalchemy(*args, metrics, **kwargs)... | ColumnUniqueProportion |
python | dagster-io__dagster | python_modules/automation/automation_tests/dagster_dev_tests/ai_review_tests/test_ai_review_summarize_smoke.py | {
"start": 219,
"end": 5666
} | class ____:
"""Basic smoke tests for the ai-review-summarize command."""
def test_import_and_basic_structure(self):
"""Test that command can be imported and has expected structure."""
from automation.dagster_dev.commands.ai_review_summarize import ai_review_summarize
assert ai_review_s... | TestAiReviewSummarizeSmoke |
python | pandas-dev__pandas | asv_bench/benchmarks/io/csv.py | {
"start": 10815,
"end": 11210
} | class ____(StringIORewind):
params = ["c", "python"]
param_names = ["engine"]
def setup(self, engine):
data = ["A,B,C"] + (["1,2,3 # comment"] * 100000)
self.StringIO_input = StringIO("\n".join(data))
def time_comment(self, engine):
read_csv(
self.data(self.StringIO... | ReadCSVComment |
python | plotly__plotly.py | plotly/graph_objs/scatter3d/line/colorbar/_title.py | {
"start": 233,
"end": 4021
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter3d.line.colorbar"
_path_str = "scatter3d.line.colorbar.title"
_valid_props = {"font", "side", "text"}
@property
def font(self):
"""
Sets this color bar's title font.
The 'font' property is an instance of Font
... | Title |
python | doocs__leetcode | solution/0700-0799/0718.Maximum Length of Repeated Subarray/Solution.py | {
"start": 0,
"end": 423
} | class ____:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
m, n = len(nums1), len(nums2)
f = [[0] * (n + 1) for _ in range(m + 1)]
ans = 0
for i in range(1, m + 1):
for j in range(1, n + 1):
if nums1[i - 1] == nums2[j - 1]:
... | Solution |
python | mlflow__mlflow | mlflow/data/spark_dataset_source.py | {
"start": 190,
"end": 2110
} | class ____(DatasetSource):
"""
Represents the source of a dataset stored in a spark table.
"""
def __init__(
self,
path: str | None = None,
table_name: str | None = None,
sql: str | None = None,
):
if (path, table_name, sql).count(None) != 2:
rais... | SparkDatasetSource |
python | getsentry__sentry | tests/snuba/search/test_backend.py | {
"start": 1849,
"end": 3914
} | class ____(SnubaTestCase):
@property
def backend(self) -> SnubaSearchBackendBase:
raise NotImplementedError(self)
def build_search_filter(self, query, projects=None, user=None, environments=None):
user = user if user is not None else self.user
projects = projects if projects is not ... | SharedSnubaMixin |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/random/random_shuffle_queue_test.py | {
"start": 1358,
"end": 51354
} | class ____(test.TestCase):
def setUp(self):
# Useful for debugging when a test times out.
super(RandomShuffleQueueTest, self).setUp()
tf_logging.error("Starting: %s", self._testMethodName)
# We need each thread to keep its own device stack or the device scopes
# won't be properly nested.
ops.... | RandomShuffleQueueTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeAlias2.py | {
"start": 223,
"end": 269
} | class ____(Base):
pass
Mix = Union[A, B]
| B |
python | kamyu104__LeetCode-Solutions | Python/reverse-substrings-between-each-pair-of-parentheses.py | {
"start": 658,
"end": 1091
} | class ____(object):
def reverseParentheses(self, s):
"""
:type s: str
:rtype: str
"""
stk = [[]]
for c in s:
if c == '(':
stk.append([])
elif c == ')':
end = stk.pop()
end.reverse()
... | Solution2 |
python | kamyu104__LeetCode-Solutions | Python/cycle-length-queries-in-a-tree.py | {
"start": 45,
"end": 480
} | class ____(object):
def cycleLengthQueries(self, n, queries):
"""
:type n: int
:type queries: List[List[int]]
:rtype: List[int]
"""
result = []
for x, y in queries:
cnt = 1
while x != y:
if x > y:
x, ... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/streams.py | {
"start": 29048,
"end": 33367
} | class ____(IncrementalMixin, GithubStream):
"""
API docs: https://docs.github.com/en/rest/commits/commits?apiVersion=2022-11-28#list-commits
Pull commits from each branch of each repository, tracking state for each branch
"""
primary_key = "sha"
cursor_field = "created_at"
slice_keys = ["r... | Commits |
python | doocs__leetcode | solution/1300-1399/1395.Count Number of Teams/Solution.py | {
"start": 0,
"end": 325
} | class ____:
def numTeams(self, rating: List[int]) -> int:
ans, n = 0, len(rating)
for i, b in enumerate(rating):
l = sum(a < b for a in rating[:i])
r = sum(c > b for c in rating[i + 1 :])
ans += l * r
ans += (i - l) * (n - i - 1 - r)
return ans... | Solution |
python | realpython__materials | celery-async-tasks/source_code_final/feedback/forms.py | {
"start": 79,
"end": 412
} | class ____(forms.Form):
email = forms.EmailField(label="Email Address")
message = forms.CharField(
label="Message", widget=forms.Textarea(attrs={"rows": 5})
)
def send_email(self):
send_feedback_email_task.delay(
self.cleaned_data["email"], self.cleaned_data["message"]
... | FeedbackForm |
python | realpython__materials | python-type-checking/hearts.py | {
"start": 976,
"end": 2408
} | class ____(Sequence[Card]):
def __init__(self, cards: List[Card]) -> None:
self.cards = cards
@classmethod
def create(cls, shuffle: bool = False) -> "Deck":
"""Create a new deck of 52 cards"""
cards = [Card(s, r) for r in Card.RANKS for s in Card.SUITS]
if shuffle:
... | Deck |
python | django__django | tests/admin_utils/models.py | {
"start": 1135,
"end": 1417
} | class ____(models.Model):
num = models.PositiveSmallIntegerField()
parent = models.ForeignKey("self", models.DB_CASCADE, null=True)
def __str__(self):
return str(self.num)
class Meta:
required_db_features = {"supports_on_delete_db_cascade"}
| DBCascade |
python | nedbat__coveragepy | tests/test_concurrency.py | {
"start": 12309,
"end": 14746
} | class ____(CoverageTest):
"""Tests of what happens if the requested concurrency isn't installed."""
@pytest.mark.parametrize("module", ["eventlet", "gevent", "greenlet"])
def test_missing_module(self, module: str) -> None:
self.make_file("prog.py", "a = 1")
sys.modules[module] = None # typ... | WithoutConcurrencyModuleTest |
python | plotly__plotly.py | plotly/io/_base_renderers.py | {
"start": 1595,
"end": 1982
} | class ____(MimetypeRenderer):
"""
Renderer to display figures as JSON hierarchies. This renderer is
compatible with JupyterLab and VSCode.
mime type: 'application/json'
"""
def to_mimebundle(self, fig_dict):
value = json.loads(to_json(fig_dict, validate=False, remove_uids=False))
... | JsonRenderer |
python | scipy__scipy | scipy/signal/tests/test_windows.py | {
"start": 26380,
"end": 27576
} | class ____:
def test_basic(self, xp):
xp_assert_close(windows.nuttall(6, sym=False, xp=xp),
xp.asarray([0.0003628, 0.0613345, 0.5292298, 1.0, 0.5292298,
0.0613345], dtype=xp.float64))
xp_assert_close(windows.nuttall(7, sym=False, xp=xp),
... | TestNuttall |
python | apache__airflow | devel-common/src/sphinx_exts/operators_and_hooks_ref.py | {
"start": 12950,
"end": 14865
} | class ____(Directive):
"""The base directive for OperatorsHooksReferenceDirective and TransfersReferenceDirective"""
optional_arguments = 1
option_spec = {"tags": directives.unchanged, "header-separator": directives.unchanged_required}
def run(self):
tags_arg = self.options.get("tags")
... | BaseJinjaReferenceDirective |
python | realpython__materials | python-property/currency_v2.py | {
"start": 23,
"end": 565
} | class ____:
def __init__(self, units, cents):
self._total_cents = units * CENTS_PER_UNIT + cents
@property
def units(self):
return self._total_cents // CENTS_PER_UNIT
@units.setter
def units(self, value):
self._total_cents = self.cents + value * CENTS_PER_UNIT
@propert... | Currency |
python | prakhar1989__Algorithms | tests/lcs_test.py | {
"start": 28,
"end": 405
} | class ____(unittest.TestCase):
def test_lcs(self):
self.assertEqual(lcs.longest_common_subsequence("ABCD", "BBDABXYDCCAD"), (4, "ABCD"))
self.assertEqual(lcs.longest_common_subsequence("BANANA", "ATANA"), (4, "AANA"))
self.assertEqual(lcs.longest_common_subsequence("ABCDEFG", "BDGK"), (3, "B... | TestLCS |
python | cython__cython | runtests.py | {
"start": 85719,
"end": 86508
} | class ____(object):
# This is an exclude selector so it can override the (include) selectors.
# It may not provide uniform distribution (in time or count), but is a
# determanistic partition of the tests which is important.
# Random seed to improve the hash distribution.
_seed = base64.b64decode(b'... | ShardExcludeSelector |
python | pytorch__pytorch | test/cpp/aoti_inference/test.py | {
"start": 138,
"end": 559
} | class ____(torch.nn.Module):
def __init__(self, device, size=4):
super().__init__()
self.w_pre = torch.randn(size, size, device=device)
self.w_add = torch.randn(size, size, device=device)
def forward(self, x):
w_transpose = torch.transpose(self.w_pre, 0, 1)
w_relu = torc... | Net |
python | pypa__hatch | tests/backend/builders/test_wheel.py | {
"start": 11846,
"end": 15389
} | class ____:
def test_default(self, isolation):
builder = WheelBuilder(str(isolation))
assert builder.config.shared_data == builder.config.shared_data == {}
def test_invalid_type(self, isolation):
config = {"tool": {"hatch": {"build": {"targets": {"wheel": {"shared-data": 42}}}}}}
... | TestSharedData |
python | pydantic__pydantic | pydantic/_internal/_namespace_utils.py | {
"start": 5443,
"end": 12878
} | class ____:
"""A class responsible for the namespaces resolving logic for annotations evaluation.
This class handles the namespace logic when evaluating annotations mainly for class objects.
It holds a stack of classes that are being inspected during the core schema building,
and the `types_namespace`... | NsResolver |
python | huggingface__transformers | src/transformers/models/detr/modeling_detr.py | {
"start": 3945,
"end": 6398
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
bounding box loss. The latter is defined as a linear combination of... | DetrObjectDetectionOutput |
python | fastapi__sqlmodel | docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001_py310.py | {
"start": 292,
"end": 1975
} | 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")
team: Team | None = Relationship(back_popula... | Hero |
python | tensorflow__tensorflow | tensorflow/python/tpu/tpu_embedding_v3_utils_test.py | {
"start": 1701,
"end": 9018
} | class ____(test.TestCase, parameterized.TestCase):
def test_unpadding(self):
self.assertAllEqual(
v3_utils.remove_padding_from_sc(
array_ops.ones((4, 5)), variable_shape=(3, 2)
),
array_ops.ones((3, 2)),
)
x = array_ops.reshape(math_ops.range(12), (3, 4))
self.asse... | TpuEmbeddingV3UtilsTest |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_table25.py | {
"start": 315,
"end": 1641
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("table25.xlsx")
def test_create_file_style_is_none(self):
"""Test the creation of a simple XlsxWriter file with tables."""
workbook... | TestCompareXLSXFiles |
python | joke2k__faker | tests/providers/test_currency.py | {
"start": 3152,
"end": 3817
} | class ____:
"""Test az_AZ currency provider"""
num_samples = 100
@classmethod
def setup_class(cls):
from faker.providers.currency.az_AZ import Provider as AzAzCurrencyProvider
cls.provider = AzAzCurrencyProvider
cls.currencies = cls.provider.currencies
def test_currency(s... | TestAzAz |
python | pandas-dev__pandas | pandas/core/strings/accessor.py | {
"start": 4591,
"end": 133744
} | class ____(NoNewAttributesMixin):
"""
Vectorized string functions for Series and Index.
NAs stay NA unless handled otherwise by a particular method.
Patterned after Python's string methods, with some inspiration from
R's stringr package.
Parameters
----------
data : Series or Index
... | StringMethods |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.