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 | pypa__hatch | tests/backend/builders/test_config.py | {
"start": 22919,
"end": 26353
} | class ____:
def test_default(self, isolation):
builder = MockBuilder(str(isolation))
assert builder.config.packages == builder.config.packages == []
def test_global_invalid_type(self, isolation):
config = {"tool": {"hatch": {"build": {"packages": ""}}}}
builder = MockBuilder(st... | TestPackages |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarTuple15.py | {
"start": 268,
"end": 625
} | class ____(Generic[Unpack[Shape]]): ...
def func0(x: Array[Unpack[Shape]]) -> Array[Unpack[Shape]]: ...
def func1(y: Array[int, Unpack[tuple[Any, ...]]]):
reveal_type(func0(y), expected_text="Array[int, *tuple[Any, ...]]")
def func2(y: Array[Unpack[tuple[int, ...]], int]):
reveal_type(func0(y), expected_t... | Array |
python | bokeh__bokeh | src/bokeh/models/sources.py | {
"start": 32125,
"end": 35177
} | class ____(WebDataSource):
''' A data source that can populate columns by making Ajax calls to REST
endpoints.
The ``AjaxDataSource`` can be especially useful if you want to make a
standalone document (i.e. not backed by the Bokeh server) that can still
dynamically update using an existing REST API... | AjaxDataSource |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/widgets/toolbars.py | {
"start": 5954,
"end": 6546
} | class ____:
def __init__(self) -> None:
def get_formatted_text() -> StyleAndTextTuples:
arg = get_app().key_processor.arg or ""
if arg == "-":
arg = "-1"
return [
("class:arg-toolbar", "Repeat: "),
("class:arg-toolbar.text"... | ArgToolbar |
python | crytic__slither | slither/detectors/statements/pyth_unchecked_publishtime.py | {
"start": 143,
"end": 1553
} | class ____(PythUnchecked):
"""
Documentation: This detector finds when the publishTime of a Pyth price is not checked
"""
ARGUMENT = "pyth-unchecked-publishtime"
HELP = "Detect when the publishTime of a Pyth price is not checked"
IMPACT = DetectorClassification.MEDIUM
CONFIDENCE = DetectorC... | PythUncheckedPublishTime |
python | pallets__werkzeug | examples/cupoftee/network.py | {
"start": 408,
"end": 1921
} | class ____(Syncable):
def __init__(self, cup):
self.cup = cup
self.servers = cup.db.setdefault("servers", dict)
def _sync(self):
to_delete = set(self.servers)
for x in range(1, 17):
addr = (f"master{x}.teeworlds.com", 8300)
print(addr)
try:
... | ServerBrowser |
python | redis__redis-py | redis/asyncio/multidb/database.py | {
"start": 1083,
"end": 1835
} | class ____(BaseDatabase, AsyncDatabase):
def __init__(
self,
client: Union[Redis, RedisCluster],
circuit: CircuitBreaker,
weight: float,
health_check_url: Optional[str] = None,
):
self._client = client
self._cb = circuit
self._cb.database = self
... | Database |
python | PrefectHQ__prefect | src/prefect/flows.py | {
"start": 3568,
"end": 4232
} | class ____(Protocol, Generic[P, R]):
"""
A callable that is invoked when a flow enters a given state.
"""
__name__: str
def __call__(
self, flow: Flow[P, R], flow_run: FlowRun, state: State
) -> Awaitable[None] | None: ...
if TYPE_CHECKING:
import logging
from prefect.client... | FlowStateHook |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-firebolt/destination_firebolt/writer.py | {
"start": 6660,
"end": 8421
} | class ____(FireboltWriter):
"""
Data writer using the SQL writing strategy. Data is buffered in memory
and flushed using INSERT INTO SQL statement. This is less effective strategy
better suited for testing and small data sets.
"""
flush_interval = 1000
def __init__(self, connection: Connec... | FireboltSQLWriter |
python | django-haystack__django-haystack | haystack/apps.py | {
"start": 173,
"end": 963
} | class ____(AppConfig):
name = "haystack"
signal_processor = None
stream = None
def ready(self):
# Setup default logging.
log = logging.getLogger("haystack")
self.stream = logging.StreamHandler()
self.stream.setLevel(logging.INFO)
log.addHandler(self.stream)
... | HaystackConfig |
python | google__pytype | pytype/errors/error_printer.py | {
"start": 567,
"end": 661
} | class ____(enum.Enum):
OBJECT = 0
SYMBOL = 1
MODULE = 2
@dataclasses.dataclass
| BadAttrType |
python | huggingface__transformers | src/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py | {
"start": 64144,
"end": 69367
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: BigBirdPegasusConfig, layer_idx: Optional[int] = None):
super().__init__()
self.embed_dim = config.d_model
self.self_attn = BigBirdPegasusDecoderAttention(
embed_dim=self.embed_dim,
num_heads=config.de... | BigBirdPegasusDecoderLayer |
python | pydata__xarray | xarray/tests/test_dataarray.py | {
"start": 186378,
"end": 203570
} | class ____(TestReduce):
def test_min(
self,
x: np.ndarray,
minindex: int | float,
maxindex: int | float,
nanindex: int | None,
) -> None:
ar = xr.DataArray(
x, dims=["x"], coords={"x": np.arange(x.size) * 4}, attrs=self.attrs
)
if np.i... | TestReduce1D |
python | allegroai__clearml | clearml/backend_api/services/v2_13/models.py | {
"start": 94127,
"end": 95388
} | class ____(Request):
"""
Convert public models to private
:param ids: Ids of the models to convert. Only the models originated by the
company can be converted
:type ids: Sequence[str]
"""
_service = "models"
_action = "make_private"
_version = "2.13"
_schema = {
"de... | MakePrivateRequest |
python | xlwings__xlwings | xlwings/pro/_xlremote.py | {
"start": 25381,
"end": 26486
} | class ____(base_classes.Collection):
def __init__(self, parent):
self._parent = parent
self._api = parent.api[self._attr]
@property
def api(self):
return self._api
@property
def parent(self):
return self._parent
def __call__(self, key):
if isinstance(ke... | Collection |
python | scipy__scipy | scipy/stats/tests/test_morestats.py | {
"start": 2803,
"end": 3924
} | class ____:
def test_basic(self):
# Expected values in this test simply taken from the function. For
# some checks regarding correctness of implementation, see review in
# gh-674
data = [6, 9, 12, 7, 8, 8, 13]
mean, var, std = stats.bayes_mvs(data)
assert_almost_equa... | TestBayes_mvs |
python | huggingface__transformers | tests/models/blip/test_modeling_blip.py | {
"start": 33652,
"end": 38657
} | class ____(ModelTesterMixin, unittest.TestCase):
all_model_classes = (BlipForConditionalGeneration,) if is_torch_available() else ()
# Doesn't run generation tests due to custom generation logic -- wont fix
all_generative_model_classes = ()
test_resize_embeddings = True
test_attention_outputs = Fal... | BlipTextImageModelTest |
python | astropy__astropy | astropy/io/fits/tests/test_fitsheader.py | {
"start": 208,
"end": 8211
} | class ____(FitsTestCase):
def test_help(self):
with pytest.raises(SystemExit) as e:
fitsheader.main(["-h"])
assert e.value.code == 0
def test_version(self, capsys):
with pytest.raises(SystemExit) as e:
fitsheader.main(["--version"])
out = capsys.reado... | TestFITSheader_script |
python | ansible__ansible | lib/ansible/module_utils/_internal/_patches/__init__.py | {
"start": 397,
"end": 2565
} | class ____(abc.ABC):
"""Base class for patches that provides abstractions for validation of broken behavior, installation of patches, and validation of fixed behavior."""
target_container: t.ClassVar
"""The module object containing the function to be patched."""
target_attribute: t.ClassVar[str]
"... | CallablePatch |
python | tensorflow__tensorflow | tensorflow/tools/docs/tf_doctest.py | {
"start": 4593,
"end": 6851
} | class ____(tf.test.TestCase):
def set_up(self, test):
# Enable soft device placement to run distributed doctests.
tf.config.set_soft_device_placement(True)
self.setUp()
context.async_wait()
def tear_down(self, test):
self.tearDown()
def load_tests(unused_loader, tests, unused_ignore):
"""L... | TfTestCase |
python | getsentry__sentry | tests/sentry/runner/commands/test_migrations.py | {
"start": 427,
"end": 3229
} | class ____(TransactionTestCase):
command = migrations
# Copy paste from CliTest as this test needs to escape auto transactions
@property
def runner(self) -> CliRunner:
return CliRunner()
def invoke(self, *args, **kwargs):
return self.runner.invoke(self.command, args, obj={}, **kwar... | MigrationsRunTest |
python | getsentry__sentry | src/sentry/notifications/models/notificationsettingoption.py | {
"start": 248,
"end": 1138
} | class ____(NotificationSettingBase):
__relocation_scope__ = RelocationScope.Excluded
class Meta:
app_label = "notifications"
db_table = "sentry_notificationsettingoption"
unique_together = (
(
"scope_type",
"scope_identifier",
... | NotificationSettingOption |
python | apache__airflow | providers/standard/tests/unit/standard/triggers/test_external_task.py | {
"start": 22448,
"end": 30839
} | class ____:
DAG_ID = "test_dag_state_trigger"
RUN_ID = "external_task_run_id"
STATES = ["success", "fail"]
EXECUTION_DATE = timezone.datetime(2022, 1, 1)
@pytest.mark.db_test
@pytest.mark.asyncio
@pytest.mark.skipif(AIRFLOW_V_3_0_PLUS, reason="Airflow 3 had a different implementation")
... | TestDagStateTrigger |
python | PrefectHQ__prefect | src/prefect/exceptions.py | {
"start": 7976,
"end": 8115
} | class ____(PrefectException, ValueError):
"""
Raised when a name contains characters that are not permitted.
"""
| InvalidNameError |
python | kamyu104__LeetCode-Solutions | Python/lexicographically-smallest-string-after-adjacent-removals.py | {
"start": 38,
"end": 912
} | class ____(object):
def lexicographicallySmallestString(self, s):
"""
:type s: str
:rtype: str
"""
dp = [[False]*len(s) for _ in xrange(len(s))]
for l in xrange(2, len(s)+1, 2):
for i in xrange(len(s)-(l-1)):
j = i+(l-1)
if ... | Solution |
python | pydantic__pydantic | pydantic/networks.py | {
"start": 19375,
"end": 22234
} | class ____(AnyUrl):
"""A type that will accept any http or https URL.
* TLD not required
* Host not required
* Max length 2083
```python
from pydantic import BaseModel, HttpUrl, ValidationError
class MyModel(BaseModel):
url: HttpUrl
m = MyModel(url='http://www.example.com') ... | HttpUrl |
python | realpython__materials | thread-safety-locks/bank_multithreaded_withdrawal.py | {
"start": 64,
"end": 622
} | class ____:
def __init__(self):
self.balance = 1000
def withdraw(self, amount):
if self.balance >= amount:
new_balance = self.balance - amount
time.sleep(0.1) # Simulate a delay
self.balance = new_balance
else:
raise ValueError("Insuffici... | BankAccount |
python | Textualize__textual | tests/test_validation.py | {
"start": 2725,
"end": 8907
} | class ____(Validator):
def validate(self, value: str) -> ValidationResult:
return self.failure(value=value, description="ABC")
def describe_failure(self, failure: Failure) -> str | None:
return "describe_failure"
def test_Failure_description_describe_and_description_inside_validate():
# T... | ValidatorWithFailureMessageAndDescribe |
python | pypa__pip | src/pip/_internal/exceptions.py | {
"start": 10466,
"end": 10540
} | class ____(InstallationError):
"""Unsupported wheel."""
| UnsupportedWheel |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/check_ops_test.py | {
"start": 33427,
"end": 35391
} | class ____(test.TestCase):
@test_util.run_in_graph_and_eager_modes
def test_doesnt_raise_when_negative(self):
frank = constant_op.constant([-1, -2], name="frank")
with ops.control_dependencies([check_ops.assert_negative(frank)]):
out = array_ops.identity(frank)
self.evaluate(out)
@test_util.ru... | AssertNegativeTest |
python | psf__black | tests/data/cases/comments9.py | {
"start": 517,
"end": 658
} | class ____:
pass
some = statement
# This should be stick to the statement above
# This should be split from the above by two lines
| MyClass |
python | sympy__sympy | sympy/simplify/hyperexpand.py | {
"start": 30552,
"end": 33136
} | class ____:
""" A collection of formulae to use as origins. """
def __init__(self):
""" Doing this globally at module init time is a pain ... """
self.symbolic_formulae = {}
self.concrete_formulae = {}
self.formulae = []
add_formulae(self.formulae)
# Now proces... | FormulaCollection |
python | keras-team__keras | keras/src/ops/linalg.py | {
"start": 22665,
"end": 26736
} | class ____(Operation):
def __init__(self, has_aux=False, *, name=None):
super().__init__(name=name)
self.has_aux = has_aux
def call(self, fun, primals, tangents):
"""Computes the JVP of `fun` at `primals` along `tangents`.
Args:
fun: A callable that takes tensors (o... | JVP |
python | allegroai__clearml | clearml/backend_api/services/v2_13/models.py | {
"start": 78108,
"end": 83012
} | class ____(Response):
"""
Response of models.get_all endpoint.
:param models: Models list
:type models: Sequence[Model]
"""
_service = "models"
_action = "get_all"
_version = "2.13"
_schema = {
"definitions": {
"model": {
"properties": {
... | GetAllResponse |
python | getsentry__sentry | src/sentry/snuba/sessions_v2.py | {
"start": 7357,
"end": 7974
} | class ____:
def get_snuba_columns(self):
return []
def get_snuba_groupby(self):
return []
def get_keys_for_row(self, row):
return [
("session.status", key)
for key in ["healthy", "abnormal", "crashed", "errored", "unhandled"]
]
# NOTE: in the futur... | SessionStatusGroupBy |
python | gevent__gevent | src/greentest/3.12/test_socket.py | {
"start": 214786,
"end": 217001
} | class ____(SocketTCPTest):
def testTCPTimeout(self):
def raise_timeout(*args, **kwargs):
self.serv.settimeout(1.0)
self.serv.accept()
self.assertRaises(TimeoutError, raise_timeout,
"Error generating a timeout exception (TCP)")
def testTimeo... | TCPTimeoutTest |
python | sympy__sympy | sympy/physics/vector/frame.py | {
"start": 2414,
"end": 57260
} | class ____:
"""A reference frame in classical mechanics.
ReferenceFrame is a class used to represent a reference frame in classical
mechanics. It has a standard basis of three unit vectors in the frame's
x, y, and z directions.
It also can have a rotation relative to a parent frame; this rotation ... | ReferenceFrame |
python | TheAlgorithms__Python | searches/jump_search.py | {
"start": 440,
"end": 1839
} | class ____(Protocol):
def __lt__(self, other: Any, /) -> bool: ...
T = TypeVar("T", bound=Comparable)
def jump_search(arr: Sequence[T], item: T) -> int:
"""
Python implementation of the jump search algorithm.
Return the index if the `item` is found, otherwise return -1.
Examples:
>>> jump_s... | Comparable |
python | huggingface__transformers | src/transformers/image_processing_utils.py | {
"start": 1170,
"end": 13931
} | class ____(ImageProcessingMixin):
valid_kwargs = ImagesKwargs
def __init__(self, **kwargs):
super().__init__(**kwargs)
@property
def is_fast(self) -> bool:
"""
`bool`: Whether or not this image processor is a fast processor (backed by PyTorch and TorchVision).
"""
... | BaseImageProcessor |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constrainedTypeVar4.py | {
"start": 535,
"end": 802
} | class ____(Generic[T]):
value: T | None
def __init__(self, source: T | None) -> None:
self.value = source
def read(self) -> T | None:
if self.value is None:
raise RuntimeError(f"Item is required!")
return self.value
| Item |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_complex.py | {
"start": 3545,
"end": 3587
} | class ____(complex):
pass
| ComplexSubclass |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/unitofwork.py | {
"start": 24121,
"end": 25344
} | class ____(_PostSortRec):
__slots__ = "dependency_processor", "isdelete", "state", "sort_key"
def __init__(self, uow, dependency_processor, isdelete, state):
self.dependency_processor = dependency_processor
self.sort_key = ("ProcessState", dependency_processor.sort_key)
self.isdelete = ... | _ProcessState |
python | kubernetes-client__python | kubernetes/client/models/v1_stateful_set_list.py | {
"start": 383,
"end": 6928
} | 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... | V1StatefulSetList |
python | numba__numba | numba/core/typing/context.py | {
"start": 6332,
"end": 27970
} | class ____(object):
"""A typing context for storing function typing constrain template.
"""
def __init__(self):
# A list of installed registries
self._registries = {}
# Typing declarations extracted from the registries or other sources
self._functions = defaultdict(list)
... | BaseContext |
python | gevent__gevent | src/greentest/3.11/test_ftplib.py | {
"start": 16612,
"end": 32263
} | class ____(TestCase):
def setUp(self, encoding=DEFAULT_ENCODING):
self.server = DummyFTPServer((HOST, 0), encoding=encoding)
self.server.start()
self.client = ftplib.FTP(timeout=TIMEOUT, encoding=encoding)
self.client.connect(self.server.host, self.server.port)
def tearDown(sel... | TestFTPClass |
python | apache__airflow | providers/cloudant/src/airflow/providers/cloudant/cloudant_fake.py | {
"start": 1026,
"end": 1197
} | class ____:
"""Phony class to pass mypy when real class is not imported."""
def __init__(self, username: str, password: str):
pass
| CouchDbSessionAuthenticator |
python | plotly__plotly.py | plotly/graph_objs/contour/colorbar/title/_font.py | {
"start": 233,
"end": 9913
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "contour.colorbar.title"
_path_str = "contour.colorbar.title.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
... | Font |
python | huggingface__transformers | src/transformers/models/modernbert/modeling_modernbert.py | {
"start": 5107,
"end": 6937
} | class ____(RotaryEmbedding):
"""
The rotary position embeddings applied directly to unpadded sequences.
"""
def __init__(
self,
dim: int,
base: float = 10000.0,
max_seqlen: Optional[int] = None,
device: Optional[torch.device] = None,
dtype: Optional[torch... | ModernBertUnpaddedRotaryEmbedding |
python | pytorch__pytorch | torch/_export/serde/serialize.py | {
"start": 157650,
"end": 159629
} | class ____:
"""
Base class for handling extension operators.
"""
@classmethod
def namespace(cls) -> str:
raise NotImplementedError(f"{cls.__class__} namespace() must be implemented")
@classmethod
def to_op_name(cls, op) -> str:
raise NotImplementedError(f"{cls.__class__} op... | ExtensionHandler |
python | pytorch__pytorch | torch/_export/serde/schema.py | {
"start": 7532,
"end": 7664
} | class ____:
# Actually, only tensors and SymInts are allowed here
arg: Annotated[Argument, 10]
@_union_dataclass
| UserInputSpec |
python | Lightning-AI__lightning | tests/tests_pytorch/test_cli.py | {
"start": 26153,
"end": 26311
} | class ____(torch.optim.Adam):
def __init__(self, params, num_classes: Optional[int] = None, **kwargs):
super().__init__(params, **kwargs)
| CustomAdam |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 37480,
"end": 38070
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
package: str = Field(
default=...,
description="The name of the CRAN package to install. This field is required.",
examples=["geojson"],
)
... | RCranLibrary |
python | airbytehq__airbyte | airbyte-ci/connectors/erd/src/erd/relationships.py | {
"start": 364,
"end": 2783
} | class ____:
def merge(
self,
estimated_relationships: Relationships,
confirmed_relationships: Relationships,
) -> Relationships:
streams = []
for estimated_stream in estimated_relationships["streams"]:
confirmed_relationships_for_stream = self._get_stream(
... | RelationshipsMerger |
python | django__django | django/core/serializers/jsonl.py | {
"start": 331,
"end": 1247
} | class ____(PythonSerializer):
"""Convert a queryset to JSON Lines."""
internal_use_only = False
def _init_options(self):
self._current = None
self.json_kwargs = self.options.copy()
self.json_kwargs.pop("stream", None)
self.json_kwargs.pop("fields", None)
self.json_k... | Serializer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-amplitude/components.py | {
"start": 2198,
"end": 3576
} | class ____(RecordTransformation):
def __init__(self):
self.name = "events"
self.date_time_fields = [
"event_time",
"server_upload_time",
"processed_time",
"server_received_time",
"user_creation_time",
"client_upload_time",
... | TransformDatetimesToRFC3339 |
python | modin-project__modin | asv_bench/benchmarks/benchmarks.py | {
"start": 33602,
"end": 34454
} | class ____:
params = [get_benchmark_shapes("TimeDropDuplicatesDataframe")]
param_names = ["shape"]
def setup(self, shape):
rows, cols = shape
N = rows // 10
K = 10
data = {}
# dataframe would have cols-1 keys(strings) and one value(int) column
for col in rang... | TimeDropDuplicatesDataframe |
python | dask__dask | dask/dataframe/dask_expr/_rolling.py | {
"start": 5106,
"end": 5160
} | class ____(RollingReduction):
how = "var"
| RollingVar |
python | huggingface__transformers | src/transformers/models/olmo2/modular_olmo2.py | {
"start": 8851,
"end": 9233
} | class ____(LlamaRMSNorm):
def forward(self, hidden_states):
input_dtype = hidden_states.dtype
hidden_states = hidden_states.to(torch.float32)
variance = hidden_states.pow(2).mean(-1, keepdim=True)
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
r... | Olmo2RMSNorm |
python | mkdocs__mkdocs | mkdocs/config/config_options.py | {
"start": 10858,
"end": 11894
} | class ____(Generic[T], OptionallyRequired[T]):
"""
Type Config Option.
Validate the type of a config option against a given Python type.
"""
@overload
def __init__(self, type_: type[T], /, length: int | None = None, **kwargs):
...
@overload
def __init__(self, type_: tuple[type... | Type |
python | huggingface__transformers | src/transformers/models/poolformer/modeling_poolformer.py | {
"start": 12003,
"end": 14150
} | class ____(PoolFormerPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.poolformer = PoolFormerModel(config)
# Final norm
self.norm = PoolFormerGroupNorm(config.hidden_sizes[-1])
# Classifier head
s... | PoolFormerForImageClassification |
python | pyca__cryptography | tests/test_utils.py | {
"start": 187720,
"end": 188321
} | class ____:
def test_getattr(self):
with pytest.warns(DeprecationWarning):
assert deprecated_module.DEPRECATED == 3
assert deprecated_module.NOT_DEPRECATED == 12
def test_inspect_deprecated_module(self):
# Check if inspection is supported by _ModuleWithDeprecations.
... | TestDeprecated |
python | plotly__plotly.py | plotly/figure_factory/_quiver.py | {
"start": 3853,
"end": 9181
} | class ____(object):
"""
Refer to FigureFactory.create_quiver() for docstring
"""
def __init__(self, x, y, u, v, scale, arrow_scale, angle, scaleratio=1, **kwargs):
try:
x = utils.flatten(x)
except exceptions.PlotlyError:
pass
try:
y = utils.f... | _Quiver |
python | xlwings__xlwings | xlwings/base_classes.py | {
"start": 7002,
"end": 12108
} | class ____:
def adjust_indent(self, amount):
raise NotImplementedError()
def group(self, by):
raise NotImplementedError()
def ungroup(self, by):
raise NotImplementedError()
@property
def coords(self):
raise NotImplementedError()
@property
def api(self):
... | Range |
python | scipy__scipy | scipy/stats/tests/test_generation/reference_distributions.py | {
"start": 14095,
"end": 14537
} | class ____(ReferenceDistribution):
def __init__(self, *, alpha, beta):
super().__init__(alpha=alpha, beta=beta)
def _pdf(self, x, alpha, beta):
# Implemented as described in https://www.jstor.org/stable/4616433
# Equations 2.1 - 2.3
q = mp.sqrt(1 + x**2)
a = mp.pi**-1 *... | NormInvGauss |
python | tensorflow__tensorflow | tensorflow/python/eager/record.py | {
"start": 785,
"end": 4436
} | class ____(object):
"""A scope that tracks all trainable variable accesses within it.
This explicitly ignores variables that are not marked as trainable.
Sample usage:
var = tf.Variable(0.0)
with VariableWatcher() as variable_watcher:
var.assign_add(1.0)
assert variable_watcher.watched_variables == ... | VariableWatcher |
python | django__django | tests/middleware/test_csp.py | {
"start": 7036,
"end": 7659
} | class ____(SeleniumTestCase, StaticLiveServerTestCase):
available_apps = ["middleware"]
def setUp(self):
self.addCleanup(csp_reports.clear)
super().setUp()
def test_reports_are_generated(self):
url = self.live_server_url + "/csp-failure/"
self.selenium.get(url)
time... | CSPSeleniumTestCase |
python | bokeh__bokeh | src/bokeh/util/warnings.py | {
"start": 1630,
"end": 3108
} | class ____(UserWarning):
''' A Bokeh-specific ``UserWarning`` subclass.
Used to selectively filter Bokeh warnings for unconditional display.
'''
def warn(message: str, category: type[Warning] | None = None, stacklevel: int | None = None) -> None:
if stacklevel is None:
stacklevel = find_stack... | BokehUserWarning |
python | ansible__ansible | lib/ansible/_internal/_templating/_jinja_bits.py | {
"start": 8266,
"end": 10838
} | class ____(Context):
"""
A custom context which intercepts resolve_or_missing() calls and
runs them through AnsibleAccessContext. This allows usage of variables
to be tracked. If needed, values can also be modified before being returned.
"""
environment: AnsibleEnvironment # narrow the type sp... | AnsibleContext |
python | huggingface__transformers | tests/utils/test_hf_argparser.py | {
"start": 2436,
"end": 2711
} | class ____:
foo_int: list[int] = list_field(default=[])
bar_int: list[int] = list_field(default=[1, 2, 3])
foo_str: list[str] = list_field(default=["Hallo", "Bonjour", "Hello"])
foo_float: list[float] = list_field(default=[0.1, 0.2, 0.3])
@dataclass
| ListExample |
python | pytest-dev__pytest | testing/test_capture.py | {
"start": 1687,
"end": 4526
} | class ____:
@pytest.mark.parametrize("method", ["no", "sys", "fd"])
def test_capturing_basic_api(self, method) -> None:
capouter = StdCaptureFD()
old = sys.stdout, sys.stderr, sys.stdin
try:
capman = CaptureManager(method)
capman.start_global_capturing()
... | TestCaptureManager |
python | PyCQA__pylint | tests/functional/m/method_hidden.py | {
"start": 2131,
"end": 2204
} | class ____:
def __init__(self):
self.__private = None
| ParentTwo |
python | django__django | tests/multiple_database/models.py | {
"start": 1994,
"end": 2187
} | class ____(models.Model):
user = models.OneToOneField(User, models.SET_NULL, null=True)
flavor = models.CharField(max_length=100)
class Meta:
ordering = ("flavor",)
| UserProfile |
python | matplotlib__matplotlib | lib/matplotlib/colors.py | {
"start": 115244,
"end": 120683
} | class ____(Normalize):
"""
Generate a colormap index based on discrete intervals.
Unlike `Normalize` or `LogNorm`, `BoundaryNorm` maps values to integers
instead of to the interval 0-1.
"""
# Mapping to the 0-1 interval could have been done via piece-wise linear
# interpolation, but using ... | BoundaryNorm |
python | doocs__leetcode | solution/3500-3599/3536.Maximum Product of Two Digits/Solution.py | {
"start": 0,
"end": 242
} | class ____:
def maxProduct(self, n: int) -> int:
a = b = 0
while n:
n, x = divmod(n, 10)
if a < x:
a, b = x, a
elif b < x:
b = x
return a * b
| Solution |
python | crytic__slither | slither/tools/upgradeability/checks/constant.py | {
"start": 3058,
"end": 5950
} | class ____(AbstractCheck):
ARGUMENT = "became-constant"
IMPACT = CheckClassification.HIGH
HELP = "Variables that should not be constant"
WIKI = "https://github.com/crytic/slither/wiki/Upgradeability-Checks#variables-that-should-not-be-constant"
WIKI_TITLE = "Variables that should not be constant"
... | BecameConstant |
python | scipy__scipy | scipy/stats/tests/test_rank.py | {
"start": 328,
"end": 2424
} | class ____:
def test_empty(self):
"""An empty array requires no correction, should return 1.0."""
ranks = np.array([], dtype=np.float64)
c = tiecorrect(ranks)
assert_equal(c, 1.0)
def test_one(self):
"""A single element requires no correction, should return 1.0."""
... | TestTieCorrect |
python | tensorflow__tensorflow | tensorflow/python/feature_column/feature_column_v2.py | {
"start": 92191,
"end": 96437
} | class ____(
DenseColumn,
fc_old._DenseColumn, # pylint: disable=protected-access
collections.namedtuple(
'NumericColumn',
('key', 'shape', 'default_value', 'dtype', 'normalizer_fn'))):
"""see `numeric_column`."""
@property
def _is_v2_column(self):
return True
@property
def n... | NumericColumn |
python | joke2k__faker | faker/providers/currency/de_CH/__init__.py | {
"start": 48,
"end": 388
} | class ____(CurrencyProvider):
# source: https://de.wikipedia.org/wiki/Schreibweise_von_Zahlen#Dezimaltrennzeichen_2
price_formats = ["\N{FIGURE DASH}.##", "%.##", "%#.##", "%##.##", "% ###.##", "%# ###.##"]
def pricetag(self):
return "Fr.\N{NO-BREAK SPACE}" + self.numerify(self.random_element(self.... | Provider |
python | xlwings__xlwings | xlwings/base_classes.py | {
"start": 17686,
"end": 17944
} | class ____:
@property
def api(self):
raise NotImplementedError()
@property
def print_area(self):
raise NotImplementedError()
@print_area.setter
def print_area(self, value):
raise NotImplementedError()
| PageSetup |
python | pydantic__pydantic | tests/mypy/outputs/mypy-plugin-strict_ini/plugin_fail_baseConfig.py | {
"start": 1370,
"end": 1556
} | class ____(BaseModel):
class Config:
extra = 'forbid'
ForbidExtraModel(x=1)
# MYPY: error: Unexpected keyword argument "x" for "ForbidExtraModel" [call-arg]
| ForbidExtraModel |
python | google__pytype | pytype/overlays/attr_overlay.py | {
"start": 9899,
"end": 11284
} | class ____(AttrsBase):
"""Implements the @attr.define decorator.
See https://www.attrs.org/en/stable/api.html#next-generation-apis
"""
# Override the default arguments.
DEFAULT_ARGS: ClassVar[dict[str, Any]] = {
# Entries from Decorator.DEFAULT_ARGS
"init": True,
"kw_only": False,
# ... | AttrsNextGenDefine |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 81586,
"end": 84299
} | class ____(TestCase):
def assertAllGroupsEqual(self, groupby1, groupby2):
for a, b in zip(groupby1, groupby2):
key1, group1 = a
key2, group2 = b
self.assertEqual(key1, key2)
self.assertListEqual(list(group1), list(group2))
self.assertRaises(StopIterati... | GroupByTransformTests |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_bigquery.py | {
"start": 22034,
"end": 31608
} | class ____:
@pytest.mark.parametrize("as_dict", [True, False])
@mock.patch("airflow.providers.google.cloud.operators.bigquery.BigQueryHook")
def test_execute__table(self, mock_hook, as_dict):
max_results = 100
selected_fields = "DATE"
operator = BigQueryGetDataOperator(
g... | TestBigQueryGetDataOperator |
python | keras-team__keras | keras/src/ops/core.py | {
"start": 19887,
"end": 22350
} | class ____(Operation):
def __init__(self, cond, body, maximum_iterations=None, *, name=None):
super().__init__(name=name)
self.cond = cond
self.body = body
self.maximum_iterations = maximum_iterations
def call(self, loop_vars):
return backend.core.while_loop(
... | WhileLoop |
python | sqlalchemy__sqlalchemy | test/orm/test_core_compilation.py | {
"start": 90279,
"end": 95897
} | class ____(
_poly_fixtures._PolymorphicAliasedJoins, RelationshipNaturalInheritedTest
):
# this is the label style for the polymorphic selectable, not the
# outside query
label_style = LABEL_STYLE_DISAMBIGUATE_ONLY
straight_company_to_person_expected = (
"SELECT companies.company_id, compan... | RelNaturalAliasedJoinsDisamTest |
python | PrefectHQ__prefect | src/prefect/server/schemas/core.py | {
"start": 41182,
"end": 43288
} | class ____(ORMBaseModel):
key: Optional[str] = Field(
default=None, description="An optional unique reference key for this artifact."
)
type: Optional[str] = Field(
default=None,
description=(
"An identifier that describes the shape of the data field. e.g. 'result',"
... | Artifact |
python | pytorch__pytorch | scripts/release_notes/test_release_notes.py | {
"start": 69,
"end": 2235
} | class ____(unittest.TestCase):
def test_create_new(self):
with tempfile.TemporaryDirectory() as tempdir:
commit_list_path = f"{tempdir}/commitlist.csv"
commit_list = CommitList.create_new(
commit_list_path, "v1.5.0", "6000dca5df"
)
self.assertE... | TestCommitList |
python | doocs__leetcode | lcci/05.08.Draw Line/Solution.py | {
"start": 0,
"end": 380
} | class ____:
def drawLine(self, length: int, w: int, x1: int, x2: int, y: int) -> List[int]:
ans = [0] * length
i = (y * w + x1) // 32
j = (y * w + x2) // 32
for k in range(i, j + 1):
ans[k] = -1
ans[i] = (ans[i] & 0xFFFFFFFF) >> (x1 % 32) if x1 % 32 else -1
... | Solution |
python | numba__numba | numba/core/datamodel/models.py | {
"start": 28450,
"end": 28905
} | class ____(ArrayModel):
def __init__(self, dmm, fe_type):
self._be_type = dmm.lookup(fe_type.dtype).get_data_type()
super(NestedArrayModel, self).__init__(dmm, fe_type)
def as_storage_type(self):
"""Return the LLVM type representation for the storage of
the nestedarray.
... | NestedArrayModel |
python | huggingface__transformers | src/transformers/models/oneformer/modeling_oneformer.py | {
"start": 80710,
"end": 83210
} | class ____(nn.Module):
def __init__(
self, embed_dim, num_heads, dropout=0.0, activation="relu", normalize_before=False, layer_norm_eps=1e-05
):
super().__init__()
self.multihead_attn = nn.MultiheadAttention(embed_dim, num_heads, dropout=dropout)
self.norm = nn.LayerNorm(embed_d... | OneFormerTransformerDecoderCrossAttentionLayer |
python | patrick-kidger__equinox | equinox/nn/_batch_norm.py | {
"start": 393,
"end": 11415
} | class ____(StatefulLayer):
r"""Computes a mean and standard deviation over the batch and spatial
dimensions of an array, and uses these to normalise the whole array. Optionally
applies a channelwise affine transformation afterwards.
Given an input array $x = [x_1, ... x_C]$ with $C$ channels, this laye... | BatchNorm |
python | huggingface__transformers | src/transformers/models/ministral/modeling_ministral.py | {
"start": 1617,
"end": 5640
} | 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=False)
self.up_... | MinistralMLP |
python | kamyu104__LeetCode-Solutions | Python/number-of-pairs-satisfying-inequality.py | {
"start": 586,
"end": 1102
} | class ____(object): # 0-indexed.
def __init__(self, n):
self.__bit = [0]*(n+1) # Extra one for dummy node.
def add(self, i, val):
i += 1 # Extra one for dummy node.
while i < len(self.__bit):
self.__bit[i] += val
i += (i & -i)
def query(self, i):
... | BIT |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-chroma/destination_chroma/config.py | {
"start": 1334,
"end": 1741
} | class ____(BaseModel):
mode: Literal["persistent_client"] = Field("persistent_client", const=True)
path: str = Field(..., title="Path", description="Where Chroma will store its database files on disk, and load them on start.")
class Config:
title = "Persistent Client Mode"
schema_extra = {"... | PersistentMode |
python | ray-project__ray | rllib/connectors/common/tensor_to_numpy.py | {
"start": 382,
"end": 826
} | class ____(ConnectorV2):
"""Converts (framework) tensors across the entire input data into numpy arrays."""
@override(ConnectorV2)
def __call__(
self,
*,
rl_module: RLModule,
batch: Dict[str, Any],
episodes: List[EpisodeType],
explore: Optional[bool] = None,
... | TensorToNumpy |
python | spack__spack | lib/spack/spack/vendor/jinja2/ext.py | {
"start": 21152,
"end": 21539
} | class ____(Extension):
"""Adds break and continue to the template engine."""
tags = {"break", "continue"}
def parse(self, parser: "Parser") -> t.Union[nodes.Break, nodes.Continue]:
token = next(parser.stream)
if token.value == "break":
return nodes.Break(lineno=token.lineno)
... | LoopControlExtension |
python | getsentry__sentry | src/sentry/db/models/fields/uuid.py | {
"start": 1993,
"end": 5778
} | class ____(models.Field):
"""Field for storing UUIDs."""
description = "Universally unique identifier."
def __init__(self, auto_add=False, coerce_to=UUID, **kwargs):
"""Instantiate the field."""
# If the `auto_add` argument is specified as True, substitute an
# appropriate callabl... | UUIDField |
python | PrefectHQ__prefect | tests/test_flows.py | {
"start": 55018,
"end": 61381
} | class ____:
async def test_subflow_with_one_upstream_task_future(self, prefect_client):
@task
def child_task(x):
return x
@flow
def child_flow(x):
return x
@flow
def parent_flow():
task_future = child_task.submit(1)
fl... | TestSubflowTaskInputs |
python | pytorch__pytorch | test/onnx/exporter/test_tensors.py | {
"start": 229,
"end": 584
} | class ____(common_utils.TestCase):
def test_it_is_hashable(self):
tensor = _tensors.SymbolicTensor(
opset=onnxscript.values.Opset(domain="test", version=1)
)
self.assertEqual(hash(tensor), hash(tensor))
self.assertIn(tensor, {tensor})
if __name__ == "__main__":
comm... | SymbolicTensorTest |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF024.py | {
"start": 684,
"end": 876
} | class ____: ...
dict.fromkeys(pierogi_fillings, MysteryBox)
bar.fromkeys(pierogi_fillings, [])
def bad_dict() -> None:
dict = MysteryBox()
dict.fromkeys(pierogi_fillings, [])
| MysteryBox |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.