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 | plotly__plotly.py | plotly/graph_objs/scattercarpet/_stream.py | {
"start": 233,
"end": 3541
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattercarpet"
_path_str = "scattercarpet.stream"
_valid_props = {"maxpoints", "token"}
@property
def maxpoints(self):
"""
Sets the maximum number of points to keep on the plots from an
incoming stream. If `maxpoints` ... | Stream |
python | pydata__xarray | xarray/tests/test_utils.py | {
"start": 6419,
"end": 7018
} | class ____:
def test_sorted_uniform(self):
assert utils.is_uniform_spaced(np.arange(5))
def test_sorted_not_uniform(self):
assert not utils.is_uniform_spaced([-2, 1, 89])
def test_not_sorted_uniform(self):
assert not utils.is_uniform_spaced([1, -1, 3])
def test_not_sorted_not_... | Test_is_uniform_and_sorted |
python | neetcode-gh__leetcode | python/2482-difference-between-ones-and-zeros-in-row-and-column.py | {
"start": 0,
"end": 787
} | class ____:
def onesMinusZeros(self, grid: List[List[int]]) -> List[List[int]]:
m , n = len(grid), len(grid[0])
rowCount = [[0, 0] for _ in range(m)] # (zeros, ones)
colCount = [[0, 0] for _ in range(n)]
res = []
for r in range(m):
for c in range(n):
... | Solution |
python | TheAlgorithms__Python | geometry/geometry.py | {
"start": 6346,
"end": 7588
} | class ____(Polygon):
"""
A geometric rectangle on a 2D surface.
>>> rectangle_one = Rectangle(5, 10)
>>> rectangle_one.perimeter()
30
>>> rectangle_one.area()
50
>>> Rectangle(-5, 10)
Traceback (most recent call last):
...
TypeError: length must be a positive numeric val... | Rectangle |
python | mlflow__mlflow | .claude/hooks/lint.py | {
"start": 3476,
"end": 6110
} | class ____:
tool_name: Literal["Edit", "Write"]
file_path: Path
@classmethod
def parse(cls) -> "HookInput | None":
# https://code.claude.com/docs/en/hooks#posttooluse-input
data = json.loads(sys.stdin.read())
tool_name = data.get("tool_name")
tool_input = data.get("tool_... | HookInput |
python | PyCQA__pylint | tests/functional/d/dataclass/dataclass_with_field.py | {
"start": 286,
"end": 755
} | class ____:
"""Case class (group Item)"""
name: str
irr: float = 0
items: List[Item] = field(default_factory=lambda: [])
def add_item(self, item: Item) -> None:
"""Add an item to the item list."""
self.items.append(item)
def find_item(self, description: str) -> Item:
... | Case |
python | numba__numba | numba/core/types/containers.py | {
"start": 6991,
"end": 7536
} | class ____(BaseTuple):
def __getitem__(self, i):
"""
Return element at position i
"""
return self.types[i]
def __len__(self):
# Beware: this makes Tuple(()) false-ish
return len(self.types)
def __iter__(self):
return iter(self.types)
@staticmeth... | _HeterogeneousTuple |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/test_utils.py | {
"start": 11540,
"end": 13271
} | class ____(RunLauncher, ConfigurableClass):
def __init__(
self,
inst_data: Optional[ConfigurableClassData] = None,
bad_run_ids=None,
bad_user_code_run_ids=None,
):
self._inst_data = inst_data
self._queue = []
self._launched_run_ids = set()
self.bad... | MockedRunLauncher |
python | getsentry__sentry | tests/sentry/tasks/test_check_auth.py | {
"start": 694,
"end": 2820
} | class ____(TestCase):
@patch("sentry.tasks.auth.check_auth.check_auth_identities")
def test_simple(self, mock_check_auth_identities: MagicMock) -> None:
organization = self.create_organization(name="Test")
user = self.create_user(email="bar@example.com")
auth_provider = AuthProvider.obje... | CheckAuthTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/super2.py | {
"start": 184,
"end": 411
} | class ____:
def __init__(self, **kw: object) -> None:
pass
@classmethod
def factoryA(cls: type[T]) -> T:
return cls()
@classmethod
def get(cls: type[T], key: str) -> T:
return cls()
| A |
python | jazzband__django-formtools | tests/forms.py | {
"start": 426,
"end": 544
} | class ____(forms.Form):
name = forms.CharField()
attachment = forms.FileField(required=False)
| HashTestFormWithFile |
python | apache__airflow | providers/standard/src/airflow/providers/standard/exceptions.py | {
"start": 1046,
"end": 1171
} | class ____(AirflowExternalTaskSensorException):
"""Raised when the external DAG does not exist."""
| ExternalDagNotFoundError |
python | pytorch__pytorch | torch/_inductor/runtime/hints.py | {
"start": 6336,
"end": 7041
} | class ____(typing.NamedTuple):
argtypes: list[HalideInputSpec]
target: str
scheduler: str | None = None
scheduler_flags: dict[str, int | str] | None = None
cuda_device: int | None = None
def args(self) -> list[str]:
"""Command line args to pass to halide generator"""
args = [f"t... | HalideMeta |
python | kamyu104__LeetCode-Solutions | Python/apply-operations-to-maximize-score.py | {
"start": 369,
"end": 2753
} | class ____(object):
def maximumScore(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
MOD = 10**9+7
def linear_sieve_of_eratosthenes(n): # Time: O(n), Space: O(n)
primes = []
spf = [-1]*(n+1) # the smallest prime... | Solution |
python | pytorch__pytorch | torch/_inductor/codegen/wrapper.py | {
"start": 14011,
"end": 14214
} | class ____:
def codegen_fx(self, converter: FxConverter) -> FxConversionFunc:
raise NotImplementedError(f"FX codegen not yet supported for type {type(self)}")
@dataclasses.dataclass
| WrapperLine |
python | wandb__wandb | wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/polling.py | {
"start": 1585,
"end": 3941
} | class ____(EventEmitter):
"""
Platform-independent emitter that polls a directory to detect file
system changes.
"""
def __init__(self, event_queue, watch, timeout=DEFAULT_EMITTER_TIMEOUT,
stat=default_stat, listdir=os.listdir):
EventEmitter.__init__(self, event_queue, watc... | PollingEmitter |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/sql/operators.py | {
"start": 675,
"end": 5496
} | class ____(Base):
__tablename__ = "a"
id: Mapped[int]
string: Mapped[str]
arr: Mapped[List[int]] = mapped_column(ARRAY(Integer))
lt1: "ColumnElement[bool]" = A.id > A.id
lt2: "ColumnElement[bool]" = A.id > 1
lt3: "ColumnElement[bool]" = 1 < A.id
le1: "ColumnElement[bool]" = A.id >= A.id
le2: "ColumnE... | A |
python | pandas-dev__pandas | pandas/tests/indexes/object/test_indexing.py | {
"start": 2520,
"end": 6392
} | class ____:
def test_get_indexer_non_unique_nas(self, nulls_fixture):
# even though this isn't non-unique, this should still work
index = Index(["a", "b", nulls_fixture], dtype=object)
indexer, missing = index.get_indexer_non_unique([nulls_fixture])
expected_indexer = np.array([2], ... | TestGetIndexerNonUnique |
python | sphinx-doc__sphinx | sphinx/ext/autodoc/_legacy_class_based/_documenters.py | {
"start": 93748,
"end": 94901
} | class ____(DataDocumenterMixinBase):
"""Mixin for AttributeDocumenter to provide the feature for supporting non
data-descriptors.
.. note:: This mix-in must be inherited after other mix-ins. Otherwise, docstring
and :value: header will be suppressed unexpectedly.
"""
def import_obje... | NonDataDescriptorMixin |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 133419,
"end": 134140
} | class ____(Operation):
def call(self, x):
return backend.numpy.log10(x)
def compute_output_spec(self, x):
dtype = (
backend.floatx()
if backend.standardize_dtype(x.dtype) == "int64"
else dtypes.result_type(x.dtype, float)
)
return KerasTensor(... | Log10 |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-ads/source_google_ads/components.py | {
"start": 33126,
"end": 33345
} | class ____:
inside_string: bool = False
escape_next_character: bool = False
collected_string_chars: List[str] = field(default_factory=list)
last_parsed_key: Optional[str] = None
@dataclass
| StringParseState |
python | pandas-dev__pandas | asv_bench/benchmarks/indexing.py | {
"start": 15431,
"end": 15690
} | class ____:
def setup(self):
N = 500_000
cols = 500
self.df = DataFrame(np.random.rand(N, cols))
def time_setitem(self):
self.df[100] = 100
def time_setitem_list(self):
self.df[[100, 200, 300]] = 100
| Setitem |
python | numba__numba | numba/cuda/tests/cudadrv/test_emm_plugins.py | {
"start": 3845,
"end": 6683
} | class ____(CUDATestCase):
"""
Tests that the API of an EMM Plugin that implements device allocations
only is used correctly by Numba.
"""
def setUp(self):
super().setUp()
# Always start afresh with a new context and memory manager
cuda.close()
cuda.set_memory_manager... | TestDeviceOnlyEMMPlugin |
python | matplotlib__matplotlib | lib/mpl_toolkits/mplot3d/axis3d.py | {
"start": 29058,
"end": 29327
} | class ____(Axis):
axis_name = "z"
get_view_interval, set_view_interval = maxis._make_getset_interval(
"view", "zz_viewLim", "intervalx")
get_data_interval, set_data_interval = maxis._make_getset_interval(
"data", "zz_dataLim", "intervalx")
| ZAxis |
python | pytorch__pytorch | test/test_typing.py | {
"start": 4597,
"end": 7678
} | class ____(TestCase):
_lock = Lock()
_cached_output: Optional[dict[str, list[str]]] = None
@classmethod
def get_mypy_output(cls) -> dict[str, list[str]]:
with cls._lock:
if cls._cached_output is None:
cls._cached_output = _run_mypy()
return cls._cached_ou... | TestTyping |
python | huggingface__transformers | tests/models/opt/test_modeling_opt.py | {
"start": 14632,
"end": 16191
} | class ____(unittest.TestCase):
def setUp(self):
super().setUp()
self.path_model = "facebook/opt-350m"
def test_load_model(self):
try:
_ = OPTForCausalLM.from_pretrained(self.path_model)
except BaseException:
self.fail("Failed loading model")
def test... | OPTEmbeddingsTest |
python | apache__airflow | airflow-core/src/airflow/metrics/validators.py | {
"start": 10837,
"end": 11148
} | class ____(ListValidator):
"""Only allow names that do not match the blocked strings."""
def test(self, name: str) -> bool:
if self.validate_list is not None:
return not super()._has_pattern_match(name)
return True # default is all metrics are allowed
| PatternBlockListValidator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-recharge/unit_tests/integration/streams/test_credit_adjustments.py | {
"start": 513,
"end": 1848
} | class ____(StreamTestCase):
_STREAM_NAME = "credit_adjustments"
@HttpMocker()
def test_given_one_page_when_read_then_return_records(self, http_mocker: HttpMocker) -> None:
http_mocker.get(
self.stream_request().with_limit(250).with_updated_at_min(START_DATE).build(),
get_str... | TestFullRefresh |
python | ZoranPandovski__al-go-rithms | cryptography/porta_cipher/python/porta.py | {
"start": 119,
"end": 2732
} | class ____(Cipher):
"""The Porta Cipher is a polyalphabetic substitution cipher, and has a key consisting of a word e.g. 'FORTIFICATION'.
:param key: The keyword, any word or phrase will do. Must consist of alphabetical characters only, no punctuation of numbers.
"""
def __init__(self,key... | Porta |
python | PrefectHQ__prefect | src/prefect/server/database/orm_models.py | {
"start": 43504,
"end": 44441
} | class ____(Base):
__table_args__: Any = (
sa.Index(
"uq_automation_bucket__automation_id__trigger_id__bucketing_key",
"automation_id",
"trigger_id",
"bucketing_key",
unique=True,
),
sa.Index(
"ix_automation_bucket__autom... | AutomationBucket |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/model_query_annotated.py | {
"start": 336,
"end": 911
} | class ____:
a: Annotated[Optional[float], Color.RED] = None
b: Annotated[Optional[float], Color.BLUE] = None
x: Annotated[Optional[float], "foo", Color.RED] = None
y: Annotated[Optional[float], Color.BLUE, Color.RED] = None
def test1_alarm1(c: Test1_C) -> None:
c.a = 1.01
c.b = 1.01
_test_... | Test1_C |
python | wandb__wandb | wandb/automations/events.py | {
"start": 10304,
"end": 10426
} | class ____(_BaseEventInput):
scope: ProjectScope
"""The scope of the event: must be a project."""
| _BaseRunEventInput |
python | scipy__scipy | scipy/linalg/tests/test_matfuncs.py | {
"start": 1446,
"end": 3106
} | class ____:
def test_nils(self):
a = array([[29.2, -24.2, 69.5, 49.8, 7.],
[-9.2, 5.2, -18., -16.8, -2.],
[-10., 6., -20., -18., -2.],
[-9.6, 9.6, -25.5, -15.4, -2.],
[9.8, -4.8, 18., 18.2, 2.]])
cr = array([[11.94933333,-2... | TestSignM |
python | getsentry__sentry | src/sentry/services/eventstore/processing/redis.py | {
"start": 308,
"end": 721
} | class ____(EventProcessingStore):
"""
Creates an instance of the processing store which uses a Redis Cluster
client as its backend.
"""
def __init__(self, **options: Any) -> None:
super().__init__(
KVStorageCodecWrapper(
RedisKVStorage(redis_clusters.get(options.... | RedisClusterEventProcessingStore |
python | django__django | tests/migrations/test_migrations_squashed_extra/0001_squashed_0002.py | {
"start": 35,
"end": 176
} | class ____(migrations.Migration):
replaces = [
("migrations", "0001_initial"),
("migrations", "0002_second"),
]
| Migration |
python | pallets__werkzeug | examples/i18nurls/application.py | {
"start": 564,
"end": 1066
} | class ____(BaseRequest):
def __init__(self, environ, urls):
super().__init__(environ)
self.urls = urls
self.matched_url = None
def url_for(self, endpoint, **args):
if "lang_code" not in args:
args["lang_code"] = self.language
if endpoint == "this":
... | Request |
python | pyinstaller__pyinstaller | tests/functional/scripts/pyi_future.py | {
"start": 1714,
"end": 3362
} | class ____(list):
def append(self, item):
print('Adding an item')
super().append(item)
# Fix: this fails on 32-bit Python. The traceback::
#
# E:\pyinstaller>python tests\functional\scripts\pyi_future.py
# Traceback (most recent call last):
# File "tests\functional\scripts\pyi_futu... | VerboseList |
python | huggingface__transformers | src/transformers/models/aimv2/modeling_aimv2.py | {
"start": 4647,
"end": 5348
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.intermediate_size = config.intermediate_size
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
... | Aimv2MLP |
python | sympy__sympy | sympy/assumptions/predicates/matrices.py | {
"start": 11635,
"end": 12142
} | class ____(Predicate):
"""
Unit triangular matrix predicate.
Explanation
===========
A unit triangular matrix is a triangular matrix with 1s
on the diagonal.
Examples
========
>>> from sympy import Q, ask, MatrixSymbol
>>> X = MatrixSymbol('X', 4, 4)
>>> ask(Q.triangular(... | UnitTriangularPredicate |
python | getsentry__sentry | tests/sentry/plugins/bases/test_issue.py | {
"start": 306,
"end": 1280
} | class ____(TestCase):
def _get_mock_user(self) -> mock.Mock:
user = mock.Mock(spec=User(id=1))
user.is_authenticated = False
return user
def test_requires_auth_provider(self) -> None:
user = self._get_mock_user()
p = IssueTrackingPlugin()
pytest.raises(AssertionE... | GetAuthForUserTest |
python | bokeh__bokeh | src/bokeh/core/property_mixins.py | {
"start": 8792,
"end": 8994
} | class ____(HasProps):
''' Properties relevant to rendering images.
Mirrors the BokehJS ``properties.Image`` class.
'''
global_alpha = Alpha(help=_alpha_help % "images")
| ScalarImageProps |
python | bokeh__bokeh | src/bokeh/core/property/wrappers.py | {
"start": 10880,
"end": 18579
} | class ____(PropertyValueDict[Sequence[Any]]):
""" A property value container for ColumnData that supports change
notifications on mutating operations.
This property value container affords specialized code paths for
updating the .data dictionary for ColumnDataSource. When possible,
more efficient C... | PropertyValueColumnData |
python | doocs__leetcode | solution/0700-0799/0782.Transform to Chessboard/Solution.py | {
"start": 0,
"end": 1568
} | class ____:
def movesToChessboard(self, board: List[List[int]]) -> int:
def f(mask, cnt):
ones = mask.bit_count()
if n & 1:
if abs(n - 2 * ones) != 1 or abs(n - 2 * cnt) != 1:
return -1
if ones == n // 2:
return ... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1393565,
"end": 1398487
} | class ____(sgqlc.types.Type, Node, UniformResourceLocatable, Reactable):
"""A release contains the content for a release."""
__schema__ = github_schema
__field_names__ = (
"author",
"created_at",
"description",
"description_html",
"is_draft",
"is_latest",
... | Release |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_blocks/test_captions.py | {
"start": 47076,
"end": 48282
} | class ____(util.MdCase):
"""Test Blocks caption cases with `auto` level."""
extension = ['pymdownx.blocks.caption']
extension_configs = {
'pymdownx.blocks.caption': {
'types': [
'caption',
{
'name': 'figure-caption',
... | TestBlocksCaptionCustomPrefix |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_task_runs.py | {
"start": 7429,
"end": 8524
} | class ____:
async def test_read_task_run(self, flow_run, task_run, client):
# make sure we we can read the task run correctly
response = await client.get(f"/task_runs/{task_run.id}")
assert response.status_code == status.HTTP_200_OK
assert response.json()["id"] == str(task_run.id)
... | TestReadTaskRun |
python | doocs__leetcode | solution/0400-0499/0410.Split Array Largest Sum/Solution.py | {
"start": 0,
"end": 404
} | class ____:
def splitArray(self, nums: List[int], k: int) -> int:
def check(mx):
s, cnt = inf, 0
for x in nums:
s += x
if s > mx:
s = x
cnt += 1
return cnt <= k
left, right = max(nums), sum(n... | Solution |
python | openai__openai-python | src/openai/types/responses/tool_choice_allowed_param.py | {
"start": 256,
"end": 1107
} | class ____(TypedDict, total=False):
mode: Required[Literal["auto", "required"]]
"""Constrains the tools available to the model to a pre-defined set.
`auto` allows the model to pick from among the allowed tools and generate a
message.
`required` requires the model to call one or more of the allowed... | ToolChoiceAllowedParam |
python | getsentry__sentry | src/sentry_plugins/slack/plugin.py | {
"start": 784,
"end": 10055
} | class ____(CorePluginMixin, notify.NotificationPlugin):
title = "Slack"
slug = "slack"
description = "Post notifications to a Slack channel."
conf_key = "slack"
required_field = "webhook"
feature_descriptions = [
FeatureDescription(
"""
Configure rule based Slack ... | SlackPlugin |
python | eriklindernoren__ML-From-Scratch | mlfromscratch/supervised_learning/decision_tree.py | {
"start": 9482,
"end": 10235
} | class ____(DecisionTree):
def _calculate_variance_reduction(self, y, y1, y2):
var_tot = calculate_variance(y)
var_1 = calculate_variance(y1)
var_2 = calculate_variance(y2)
frac_1 = len(y1) / len(y)
frac_2 = len(y2) / len(y)
# Calculate the variance reduction
... | RegressionTree |
python | Textualize__textual | docs/examples/widgets/collapsible_nested.py | {
"start": 92,
"end": 355
} | class ____(App[None]):
def compose(self) -> ComposeResult:
with Collapsible(collapsed=False):
with Collapsible():
yield Label("Hello, world.")
if __name__ == "__main__":
app = CollapsibleApp()
app.run()
| CollapsibleApp |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/models/secrets.py | {
"start": 508,
"end": 796
} | class ____(str):
"""The use of this string subtype will prevent accidental prints of secret value to the console."""
@property
def _masked_value(self) -> str:
return "<SecretString: hidden>"
def __repr__(self) -> str:
return self._masked_value
| SecretString |
python | great-expectations__great_expectations | great_expectations/core/batch.py | {
"start": 22421,
"end": 27565
} | class ____(BatchRequestBase):
"""A RuntimeBatchRequest creates a Batch for a RuntimeDataConnector.
Instead of serving as a description of what data Great Expectations should
fetch, a RuntimeBatchRequest serves as a wrapper for data that is passed in
at runtime (as an in-memory dataframe, file/S3 path, ... | RuntimeBatchRequest |
python | google__pytype | pytype/tools/xref/testdata/subclass.py | {
"start": 101,
"end": 314
} | class ____:
#- @foo defines/binding FnFoo
#- FnFoo.node/kind function
def foo(self, x):
return 10
@staticmethod
#- @bar defines/binding FnBar
#- FnBar.node/kind function
def bar():
return 42
| A |
python | doocs__leetcode | solution/1800-1899/1810.Minimum Path Cost in a Hidden Grid/Solution.py | {
"start": 286,
"end": 1704
} | class ____(object):
def findShortestPath(self, master: 'GridMaster') -> int:
def dfs(i, j):
nonlocal target
if master.isTarget():
target = (i, j)
for dir, (a, b, ndir) in dirs.items():
x, y = i + a, j + b
if 0 <= x < N and 0... | Solution |
python | dagster-io__dagster | python_modules/libraries/dagster-databricks/dagster_databricks_tests/components/databricks_asset_bundle/test_component.py | {
"start": 9559,
"end": 10266
} | class ____(TestOpCustomization):
def test_translation(
self,
attributes: Mapping[str, Any],
assertion: Callable[[OpSpec], bool],
databricks_config_path: str,
) -> None:
component = load_component_for_test(
DatabricksAssetBundleComponent,
{
... | TestDatabricksOpCustomization |
python | astropy__astropy | astropy/time/core.py | {
"start": 126232,
"end": 127142
} | class ____(Exception):
pass
def _make_array(val, copy=COPY_IF_NEEDED):
"""
Take ``val`` and convert/reshape to an array. If ``copy`` is `True`
then copy input values.
Returns
-------
val : ndarray
Array version of ``val``.
"""
if isinstance(val, (tuple, list)) and len(val... | ScaleValueError |
python | bottlepy__bottle | bottle.py | {
"start": 99199,
"end": 99825
} | class ____:
""" This only exists to be able to attach a .close method to iterators that
do not support attribute assignment (most of itertools). """
def __init__(self, iterator, close=None):
self.iterator = iterator
self.close_callbacks = makelist(close)
def __iter__(self):
... | _closeiter |
python | ansible__ansible | lib/ansible/modules/hostname.py | {
"start": 23748,
"end": 23880
} | class ____(Hostname):
platform = 'Linux'
distribution = 'Virtuozzo'
strategy_class = RedHatStrategy
| VirtuozzoLinuxHostname |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 559105,
"end": 559561
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of DeleteProjectV2"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "project_v2")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mut... | DeleteProjectV2Payload |
python | pytorch__pytorch | test/functorch/discover_coverage.py | {
"start": 21735,
"end": 26618
} | class ____:
def __init__(self, name):
self.name = name
self.opinfos = NAME_TO_OPINFO.get(name, None)
assert self.opinfos is None or len(self.opinfos) > 0
def has_opinfo(self):
return self.opinfos is not None
def __repr__(self):
return f'Operator("{self.name}")'
... | Operator |
python | dask__distributed | distributed/diagnostics/websocket.py | {
"start": 186,
"end": 2513
} | class ____(SchedulerPlugin):
name = "websocket"
def __init__(self, socket, scheduler):
self.socket = socket
self.scheduler = scheduler
def restart(self, scheduler, **kwargs):
"""Run when the scheduler restarts itself"""
self.socket.send("restart", {})
def add_worker(se... | WebsocketPlugin |
python | spyder-ide__spyder | spyder/plugins/findinfiles/widgets/combobox.py | {
"start": 943,
"end": 8718
} | class ____(SpyderComboBox):
"""
Non editable combo box handling the path locations of the FindOptions
widget.
"""
# Signals
sig_redirect_stdio_requested = Signal(bool)
def __init__(self, external_path_history=None, parent=None, id_=None):
super().__init__(parent)
self.setS... | SearchInComboBox |
python | ray-project__ray | ci/pipeline/determine_tests_to_run.py | {
"start": 1376,
"end": 4803
} | class ____:
def __init__(
self,
tags: List[str],
lineno: int,
dirs: Optional[List[str]] = None,
files: Optional[List[str]] = None,
patterns: Optional[List[str]] = None,
):
self.tags = set(tags)
self.lineno = lineno
self.dirs = dirs or []
... | TagRule |
python | astropy__astropy | astropy/visualization/stretch.py | {
"start": 23212,
"end": 24406
} | class ____(BaseStretch):
"""
A histogram equalization stretch.
Parameters
----------
data : array-like
The data defining the equalization.
values : array-like, optional
The input image values, which should already be normalized to
the [0:1] range.
"""
def __init... | HistEqStretch |
python | numba__numba | numba/core/ir.py | {
"start": 40713,
"end": 51901
} | class ____(object):
def __init__(self, blocks, is_generator, func_id, loc,
definitions, arg_count, arg_names):
self.blocks = blocks
self.is_generator = is_generator
self.func_id = func_id
self.loc = loc
self.arg_count = arg_count
self.arg_names = arg... | FunctionIR |
python | kamyu104__LeetCode-Solutions | Python/valid-word.py | {
"start": 38,
"end": 552
} | class ____(object):
def isValid(self, word):
"""
:type word: str
:rtype: bool
"""
VOWELS = "aeiou"
if len(word) < 3:
return False
vowel = consonant = False
for x in word:
if x.isalpha():
if x.lower() in VOWELS:
... | Solution |
python | pandas-dev__pandas | asv_bench/benchmarks/indexing.py | {
"start": 13059,
"end": 13418
} | class ____:
def setup(self):
self.df_string_col = DataFrame(np.random.randn(3000, 1), columns=["A"])
self.df_int_col = DataFrame(np.random.randn(3000, 1))
def time_frame_getitem_single_column_label(self):
self.df_string_col["A"]
def time_frame_getitem_single_column_int(self):
... | GetItemSingleColumn |
python | keon__algorithms | algorithms/stack/stack.py | {
"start": 614,
"end": 1174
} | class ____(metaclass=ABCMeta):
"""Abstract Class for Stacks."""
def __init__(self):
self._top = -1
def __len__(self):
return self._top + 1
def __str__(self):
result = " ".join(map(str, self))
return 'Top-> ' + result
def is_empty(self):
return self._top == ... | AbstractStack |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType28.py | {
"start": 1562,
"end": 1692
} | class ____(Class6[T_co, T_contra]): ...
# This should generate an error because T_co isn't
# compatible with T_contra.
| Class6_Child1 |
python | ray-project__ray | python/ray/tests/test_advanced_9.py | {
"start": 9974,
"end": 16438
} | class ____:
pass
A.options(name="a", lifetime="detached").remote()
print(ray.get([use_gpu.remote(), use_gpu.remote()]))
"""
proc = run_string_as_driver_nonblocking(script)
gcs_cli = ray._raylet.GcsClient(address=f"{call_ray_start}")
def check_demands(n):
status = gcs_cli.internal_kv_get(
... | A |
python | sqlalchemy__sqlalchemy | test/sql/test_types.py | {
"start": 36564,
"end": 42520
} | class ____(
_UserDefinedTypeFixture, fixtures.TablesTest, AssertsCompiledSQL
):
run_create_tables = None
run_inserts = None
run_deletes = None
"""tests user-defined types."""
def test_typedecorator_literal_render(self):
class MyType(types.TypeDecorator):
impl = String
... | UserDefinedTest |
python | django__django | django/db/models/fields/related_lookups.py | {
"start": 5682,
"end": 5740
} | class ____(RelatedLookupMixin, Exact):
pass
| RelatedExact |
python | Pylons__pyramid | docs/quick_tutorial/functional_testing/tutorial/tests.py | {
"start": 47,
"end": 412
} | class ____(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
def tearDown(self):
testing.tearDown()
def test_hello_world(self):
from tutorial import hello_world
request = testing.DummyRequest()
response = hello_world(request)
self.assertEqu... | TutorialViewTests |
python | google__jax | tests/shape_poly_test.py | {
"start": 51660,
"end": 56536
} | class ____(Harness):
"""Tests a function with shape polymorphism.
Exports `fun` with shape polymorphism, then checks that the JAX native and
the exported function produce the same results.
"""
def __init__(self,
group_name: str, name: str,
fun: Callable[..., Any],
... | PolyHarness |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-amazon-seller-partner/components.py | {
"start": 3449,
"end": 4412
} | class ____(Decoder):
"""
Decoder strategy that returns the json-encoded content of a response, if any.
"""
parameters: InitVar[Mapping[str, Any]]
def is_stream_response(self) -> bool:
return False
def decode(self, response: requests.Response) -> Generator[MutableMapping[str, Any], Non... | GzipXmlDecoder |
python | django__django | tests/auth_tests/test_migrations.py | {
"start": 4731,
"end": 9768
} | class ____(TransactionTestCase):
available_apps = [
"auth_tests",
"django.contrib.auth",
"django.contrib.contenttypes",
]
def setUp(self):
"""
Create proxy permissions with content_type to the concrete model
rather than the proxy model (as they were before Dj... | ProxyModelWithSameAppLabelTests |
python | pytorch__pytorch | torch/profiler/profiler.py | {
"start": 24098,
"end": 38305
} | class ____(_KinetoProfile):
"""Profiler context manager.
Args:
activities (iterable): list of activity groups (CPU, CUDA) to use in profiling, supported values:
``torch.profiler.ProfilerActivity.CPU``, ``torch.profiler.ProfilerActivity.CUDA``,
``torch.profiler.ProfilerActivity.X... | profile |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/test/utils.py | {
"start": 949,
"end": 1189
} | class ____(Protocol):
@property
def data(self) -> Mapping[str, Any]: ...
@property
def errors(self) -> Optional[Sequence[str]]: ...
Selector: TypeAlias = dict[str, Any]
GqlVariables: TypeAlias = Mapping[str, Any]
| GqlResult |
python | getsentry__sentry | src/sentry/workflow_engine/typings/notification_action.py | {
"start": 15961,
"end": 16118
} | class ____(TicketActionTranslator):
@property
def action_type(self) -> ActionType:
return ActionType.JIRA_SERVER
| JiraServerActionTranslatorBase |
python | Textualize__textual | tests/test_binding_inheritance.py | {
"start": 6107,
"end": 7961
} | class ____(App[None]):
"""Base application class that can be used to record keystrokes."""
ALPHAS = "abcxyz"
"""str: The alpha keys to test against."""
ALL_KEYS = [*ALPHAS, *MOVEMENT_KEYS]
"""list[str]: All the test keys."""
@staticmethod
def make_bindings(action_prefix: str = "") -> list... | AppKeyRecorder |
python | fluentpython__example-code | 21-class-metaprog/bulkfood/model_v7.py | {
"start": 1694,
"end": 1800
} | class ____(metaclass=EntityMeta): # <3>
"""Business entity with validated fields"""
# END MODEL_V7
| Entity |
python | boto__boto3 | tests/unit/test_utils.py | {
"start": 741,
"end": 1713
} | class ____(unittest.TestCase):
def test_lazy_call(self):
with mock.patch('boto3.utils.import_module') as importer:
importer.return_value = FakeModule
lazy_function = utils.lazy_call(
'fakemodule.FakeModule.entry_point'
)
assert lazy_function(a=... | TestUtils |
python | google__jax | jax/_src/stages.py | {
"start": 35537,
"end": 35651
} | class ____(NamedTuple):
source_info: source_info_util.SourceInfo
eqn_name: str
@dataclasses.dataclass
| SourceInfo |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/offsets.py | {
"start": 87,
"end": 340
} | class ____(Static):
DEFAULT_CSS = """
Box {
border: solid white;
background: darkblue;
width: 16;
height: auto;
}
"""
def compose(self) -> ComposeResult:
yield Label("FOO\nBAR\nBAZ")
| Box |
python | python-poetry__poetry | src/poetry/vcs/git/backend.py | {
"start": 2599,
"end": 6436
} | class ____:
branch: str | None = None
revision: str | None = None
tag: str | None = None
ref: bytes = dataclasses.field(default_factory=lambda: b"HEAD")
def resolve(self, remote_refs: FetchPackResult, repo: Repo) -> None:
"""
Resolve the ref using the provided remote refs.
"... | GitRefSpec |
python | huggingface__transformers | tests/models/nllb_moe/test_modeling_nllb_moe.py | {
"start": 22345,
"end": 33459
} | class ____(unittest.TestCase):
r"""
Switch Transformers has different blocks from classic transformer based models.
The Swift MLP contains a Router class, that has to be tested to check if it is correctly implemented
Original implementation of the routers here:
"""
config = NllbMoeConfig(
... | NllbMoeRouterTest |
python | dask__distributed | distributed/protocol/serialize.py | {
"start": 18618,
"end": 26763
} | class ____:
"""An object that is already pickled into header and frames
Normal pickled objects are unpickled by the scheduler.
"""
def __init__(self, header, frames):
self.header = header
self.frames = frames
def __eq__(self, other):
return (
isinstance(other, ... | Pickled |
python | pydantic__pydantic | tests/mypy/modules/plugin_success.py | {
"start": 5027,
"end": 5757
} | class ____:
foo: InitVar[str]
bar: str
MyDataClass(foo='foo', bar='bar')
def get_my_custom_validator(field_name: str) -> Any:
@validator(field_name, allow_reuse=True)
def my_custom_validator(cls: Any, v: int) -> int:
return v
return my_custom_validator
def foo() -> None:
class MyM... | MyDataClass |
python | google__pytype | pytype/abstract/abstract_test.py | {
"start": 1236,
"end": 7399
} | class ____(AbstractTestBase):
def setUp(self):
super().setUp()
self._is_instance = special_builtins.IsInstance.make(self._ctx)
# Easier access to some primitive instances.
self._bool = self._ctx.convert.primitive_instances[bool]
self._int = self._ctx.convert.primitive_instances[int]
self._str... | IsInstanceTest |
python | numpy__numpy | numpy/distutils/fcompiler/environment.py | {
"start": 73,
"end": 3080
} | class ____:
def __init__(self, distutils_section='ALL', **kw):
self._distutils_section = distutils_section
self._conf_keys = kw
self._conf = None
self._hook_handler = None
def dump_variable(self, name):
conf_desc = self._conf_keys[name]
hook, envvar, confvar, con... | EnvironmentConfig |
python | pytest-dev__pytest-django | tests/test_db_setup.py | {
"start": 4943,
"end": 8089
} | class ____:
db_settings: ClassVar = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "db_name",
"TEST": {"NAME": "test_custom_db_name"},
}
}
def test_sqlite_test_name_used(self, django_pytester: DjangoPytester) -> None:
django_pytest... | TestSqlite |
python | facelessuser__soupsieve | tests/test_level4/test_future.py | {
"start": 51,
"end": 803
} | class ____(util.TestCase):
"""Test future selectors."""
MARKUP = """
<body>
<div id="div">
<p id="0">Some text <span id="1" class="foo:bar:foobar"> in a paragraph</span>.
<a id="2" class="bar" href="http://google.com">Link</a>
<a id="3">Placeholder text.</a>
</p>
</div>
</body>
... | TestFuture |
python | python-openxml__python-docx | src/docx/section.py | {
"start": 16433,
"end": 18412
} | class ____(_BaseHeaderFooter):
"""Page header, used for all three types (default, even-page, and first-page).
Note that, like a document or table cell, a header must contain a minimum of one
paragraph and a new or otherwise "empty" header contains a single empty paragraph.
This first paragraph can be a... | _Header |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/sparse_ops/sparse_ops_test.py | {
"start": 30884,
"end": 31474
} | class ____(test_util.TensorFlowTestCase):
def testValuesInVariable(self):
indices = constant_op.constant([[0]], dtype=dtypes.int64)
values = variables.Variable([1], trainable=False, dtype=dtypes.float32)
shape = constant_op.constant([1], dtype=dtypes.int64)
sp_input = sparse_tensor.SparseTensor(indi... | SparseAddTest |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/non_slot_assignment.py | {
"start": 1121,
"end": 1421
} | class ____(object):
__slots__ = ("name", "__dict__")
def __init__(self, name, middle_name):
self.name = name
self.middle_name = middle_name # [assigning-non-slot]
self.setup()
def setup(self):
pass
# https://github.com/astral-sh/ruff/issues/11358
| StudentF |
python | eventlet__eventlet | eventlet/green/subprocess.py | {
"start": 1310,
"end": 5575
} | class ____(subprocess_orig.Popen):
"""eventlet-friendly version of subprocess.Popen"""
# We do not believe that Windows pipes support non-blocking I/O. At least,
# the Python file objects stored on our base-class object have no
# setblocking() method, and the Python fcntl module doesn't exist on
# W... | Popen |
python | PyCQA__mccabe | mccabe.py | {
"start": 444,
"end": 1291
} | class ____(object):
"""Performs a depth-first walk of the AST."""
def __init__(self):
self.node = None
self._cache = {}
def default(self, node, *args):
for child in iter_child_nodes(node):
self.dispatch(child, *args)
def dispatch(self, node, *args):
self.no... | ASTVisitor |
python | doocs__leetcode | solution/0200-0299/0263.Ugly Number/Solution.py | {
"start": 0,
"end": 201
} | class ____:
def isUgly(self, n: int) -> bool:
if n < 1:
return False
for x in [2, 3, 5]:
while n % x == 0:
n //= x
return n == 1
| Solution |
python | pydata__xarray | xarray/tests/test_dataarray.py | {
"start": 203570,
"end": 234504
} | class ____(TestReduce):
def test_min(
self,
x: np.ndarray,
minindex: list[int | float],
maxindex: list[int | float],
nanindex: list[int | None],
) -> None:
ar = xr.DataArray(
x,
dims=["y", "x"],
coords={"x": np.arange(x.shape[1]... | TestReduce2D |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.