language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | getsentry__sentry | src/sentry/rules/history/endpoints/project_rule_stats.py | {
"start": 979,
"end": 1317
} | class ____(Serializer):
def serialize(
self, obj: TimeSeriesValue, attrs: Mapping[Any, Any], user: Any, **kwargs: Any
) -> TimeSeriesValueResponse:
return {
"date": obj.bucket,
"count": obj.count,
}
@extend_schema(tags=["issue_alerts"])
@region_silo_endpoint
| TimeSeriesValueSerializer |
python | run-llama__llama_index | llama-index-core/llama_index/core/evaluation/base.py | {
"start": 341,
"end": 1523
} | class ____(BaseModel):
"""
Evaluation result.
Output of an BaseEvaluator.
"""
query: Optional[str] = Field(default=None, description="Query string")
contexts: Optional[Sequence[str]] = Field(
default=None, description="Context strings"
)
response: Optional[str] = Field(default=... | EvaluationResult |
python | pytorch__pytorch | test/test_datapipe.py | {
"start": 147278,
"end": 147630
} | class ____(IterDataPipe):
def __init__(self) -> None:
self.n = 10
self.iter = iter(range(self.n))
def __iter__(self):
return self
def __next__(self):
return next(self.iter)
def reset(self):
self.iter = iter(range(self.n))
def __len__(self):
return ... | _CustomSelfNextTestDataPipe |
python | django-compressor__django-compressor | compressor/tests/test_offline.py | {
"start": 15211,
"end": 15846
} | class ____(
SuperMixin, OfflineTestCaseMixin, TestCase
):
templates_dir = "test_block_super_extra"
def _test_offline(self, engine, verbosity=0):
count, result = CompressCommand().handle_inner(
engines=[engine], verbosity=verbosity
)
self.assertEqual(2, count)
sel... | OfflineCompressBlockSuperTestCaseWithExtraContent |
python | keras-team__keras | keras/src/layers/rnn/bidirectional_test.py | {
"start": 130,
"end": 10040
} | class ____(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_basics(self):
self.run_layer_test(
layers.Bidirectional,
init_kwargs={"layer": layers.SimpleRNN(4)},
input_shape=(3, 2, 4),
expected_output_shape=(3, 8),
expected_nu... | SimpleRNNTest |
python | Pylons__pyramid | tests/test_config/test_assets.py | {
"start": 18844,
"end": 30536
} | class ____(unittest.TestCase):
def _getTargetClass(self):
from pyramid.config.assets import PackageOverrides
return PackageOverrides
def _makeOne(self, package=None, pkg_resources=None):
if package is None:
package = DummyPackage('package')
klass = self._getTargetCl... | TestPackageOverrides |
python | pytest-dev__pytest | src/_pytest/capture.py | {
"start": 6323,
"end": 6618
} | class ____(io.TextIOWrapper):
def __init__(self) -> None:
super().__init__(io.BytesIO(), encoding="UTF-8", newline="", write_through=True)
def getvalue(self) -> str:
assert isinstance(self.buffer, io.BytesIO)
return self.buffer.getvalue().decode("UTF-8")
| CaptureIO |
python | facelessuser__pymdown-extensions | pymdownx/fancylists.py | {
"start": 17084,
"end": 17401
} | class ____(Treeprocessor):
"""Clean up fancy list metadata."""
def run(self, root):
"""Remove intermediate fancy list type metadata."""
for ol in root.iter('ol'):
if '__fancylist' in ol.attrib:
del ol.attrib['__fancylist']
return root
| FancyListTreeprocessor |
python | pallets__flask | src/flask/cli.py | {
"start": 793,
"end": 8628
} | class ____(click.UsageError):
"""Raised if an application cannot be found or loaded."""
def find_best_app(module: ModuleType) -> Flask:
"""Given a module instance this tries to find the best possible
application in the module or raises an exception.
"""
from . import Flask
# Search for the mo... | NoAppException |
python | pypa__pip | src/pip/_vendor/urllib3/contrib/ntlmpool.py | {
"start": 731,
"end": 4528
} | class ____(HTTPSConnectionPool):
"""
Implements an NTLM authentication version of an urllib3 connection pool
"""
scheme = "https"
def __init__(self, user, pw, authurl, *args, **kwargs):
"""
authurl is a random URL on the server that is protected by NTLM.
user is the Windows... | NTLMConnectionPool |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_R.py | {
"start": 7584,
"end": 8729
} | class ____(Benchmark):
r"""
Rosenbrock objective function.
This class defines the Rosenbrock [1]_ global optimization problem. This is a
multimodal minimization problem defined as follows:
.. math::
f_{\text{Rosenbrock}}(x) = \sum_{i=1}^{n-1} [100(x_i^2
- x_{i+1})^2 + (x_i - 1)^2]
... | Rosenbrock |
python | huggingface__transformers | tests/utils/import_structures/import_structure_register_with_duplicates.py | {
"start": 713,
"end": 882
} | class ____:
def __init__(self):
pass
@requires(backends=("torch", "torch"))
def c0():
pass
@requires(backends=("torch", "torch"))
# That's a statement
| C0 |
python | bokeh__bokeh | src/bokeh/core/property/visual.py | {
"start": 4264,
"end": 4757
} | class ____(Either):
""" Accept built-in fill hatching specifications.
Accepts either "long" names, e.g. "horizontal-wave" or the single letter
abbreviations, e.g. "v"
"""
def __init__(self, default=[], *, help: str | None = None) -> None:
types = Enum(enums.HatchPattern), Enum(enums.Hatch... | HatchPatternType |
python | cherrypy__cherrypy | cherrypy/test/test_conn.py | {
"start": 2885,
"end": 9270
} | class ____(helper.CPWebCase):
setup_server = staticmethod(setup_server)
def test_HTTP11(self):
if cherrypy.server.protocol_version != 'HTTP/1.1':
return self.skip()
self.PROTOCOL = 'HTTP/1.1'
self.persistent = True
# Make the first request and assert there's no "C... | ConnectionCloseTests |
python | pydata__xarray | xarray/tests/test_datatree.py | {
"start": 61422,
"end": 63642
} | class ____:
def test_drop_nodes(self) -> None:
sue = DataTree.from_dict({"Mary": None, "Kate": None, "Ashley": None})
# test drop just one node
dropped_one = sue.drop_nodes(names="Mary")
assert "Mary" not in dropped_one.children
# test drop multiple nodes
dropped = ... | TestRestructuring |
python | readthedocs__readthedocs.org | readthedocs/api/v3/permissions.py | {
"start": 1014,
"end": 1269
} | class ____(BasePermission):
"""Grant permission if user is the same as the one being accessed."""
def has_permission(self, request, view):
user = view._get_parent_user()
if user == request.user:
return True
| IsCurrentUser |
python | apache__airflow | airflow-core/src/airflow/utils/context.py | {
"start": 3021,
"end": 3644
} | class ____(ConnectionAccessorSDK):
"""Wrapper to access Connection entries in template."""
def __getattr__(self, conn_id: str) -> Any:
from airflow.models.connection import Connection
return Connection.get_connection_from_secrets(conn_id)
def get(self, conn_id: str, default_conn: Any = No... | ConnectionAccessor |
python | pytorch__pytorch | torch/ao/nn/quantized/modules/rnn.py | {
"start": 67,
"end": 1898
} | class ____(torch.ao.nn.quantizable.LSTM):
r"""A quantized long short-term memory (LSTM).
For the description and the argument types, please, refer to :class:`~torch.nn.LSTM`
Attributes:
layers : instances of the `_LSTMLayer`
.. note::
To access the weights and biases, you need to acce... | LSTM |
python | openai__openai-python | src/openai/types/responses/tool_choice_types_param.py | {
"start": 220,
"end": 838
} | class ____(TypedDict, total=False):
type: Required[
Literal[
"file_search",
"web_search_preview",
"computer_use_preview",
"web_search_preview_2025_03_11",
"image_generation",
"code_interpreter",
]
]
"""The type of hosted... | ToolChoiceTypesParam |
python | python-pillow__Pillow | src/PIL/ImageFilter.py | {
"start": 8782,
"end": 8969
} | class ____(BuiltinFilter):
name = "Find Edges"
# fmt: off
filterargs = (3, 3), 1, 0, (
-1, -1, -1,
-1, 8, -1,
-1, -1, -1,
)
# fmt: on
| FIND_EDGES |
python | scikit-learn__scikit-learn | sklearn/linear_model/tests/test_sgd.py | {
"start": 1631,
"end": 2173
} | class ____(linear_model.SGDRegressor):
def fit(self, X, y, *args, **kw):
X = sp.csr_matrix(X)
return linear_model.SGDRegressor.fit(self, X, y, *args, **kw)
def partial_fit(self, X, y, *args, **kw):
X = sp.csr_matrix(X)
return linear_model.SGDRegressor.partial_fit(self, X, y, *ar... | _SparseSGDRegressor |
python | django__django | django/db/models/fields/json.py | {
"start": 10733,
"end": 10933
} | class ____(HasKeyLookup):
lookup_name = "has_keys"
postgres_operator = "?&"
logical_operator = " AND "
def get_prep_lookup(self):
return [str(item) for item in self.rhs]
| HasKeys |
python | pytorch__pytorch | test/dynamo/test_tree_map.py | {
"start": 2917,
"end": 11601
} | class ____(TestCase):
def setUp(self):
super().setUp()
torch._dynamo.reset()
def _run_tree_map(self, tree_map_impl, kwargs):
lhs = _build_tree(0)
rhs = _build_tree(7)
def fn(a, b):
return tree_map_impl(_combine_leaves, a, b, **kwargs)
compiled = tor... | TreeMapCompileTests |
python | numba__numba | numba/cuda/stubs.py | {
"start": 6030,
"end": 6342
} | class ____(Stub):
'''
lanemask_lt()
Returns a 32-bit integer mask of all lanes (including inactive ones) with
ID less than the current lane.
'''
_description_ = '<lanemask_lt()>'
# -------------------------------------------------------------------------------
# memory fences
| lanemask_lt |
python | ijl__orjson | test/test_transform.py | {
"start": 248,
"end": 3750
} | class ____:
def _pass_transform(self, filename, reference=None):
data = _read_file(filename)
assert orjson.dumps(orjson.loads(data)) == (reference or data)
def _fail_transform(self, filename):
data = _read_file(filename)
with pytest.raises(orjson.JSONDecodeError):
or... | TestJSONTestSuiteTransform |
python | django__django | tests/model_forms/models.py | {
"start": 9495,
"end": 9619
} | class ____(models.Model):
biggie = models.BigIntegerField()
def __str__(self):
return str(self.biggie)
| BigInt |
python | pydantic__pydantic | pydantic-core/tests/serializers/test_any.py | {
"start": 29143,
"end": 29256
} | class ____(ipaddress.IPv4Network):
def __str__(self):
return super().__str__() + '_subclassed'
| SubNetV4 |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/vertex_ai/test_feature_store.py | {
"start": 12123,
"end": 13770
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("feature_store.FeatureStoreHook"))
def test_execute(self, mock_hook_class):
# Create the mock hook and set up its return value
mock_hook = mock.MagicMock()
mock_hook_class.return_value = mock_hook
# Set up the return value for get_fea... | TestGetFeatureOnlineStoreOperator |
python | scikit-learn__scikit-learn | sklearn/gaussian_process/kernels.py | {
"start": 17778,
"end": 23303
} | class ____(Kernel):
"""Kernel which is composed of a set of other kernels.
.. versionadded:: 0.18
Parameters
----------
kernels : list of Kernels
The other kernels
Examples
--------
>>> from sklearn.gaussian_process.kernels import WhiteKernel
>>> from sklearn.gaussian_proc... | CompoundKernel |
python | pytorch__pytorch | test/higher_order_ops/test_invoke_subgraph.py | {
"start": 57246,
"end": 58315
} | class ____(torch.nn.Module):
def forward(self, primals_1: "f32[8, 8]"):
partitioned_fw_subgraph_0_0 = self.partitioned_fw_subgraph_0_0
invoke_subgraph_2 = torch.ops.higher_order.invoke_subgraph(partitioned_fw_subgraph_0_0, 'partitioned_fw_subgraph_0_0', primals_1); partitioned_fw_subgraph_0_0 = pri... | GraphModule |
python | patrick-kidger__equinox | equinox/_errors.py | {
"start": 2577,
"end": 14002
} | class ____(RuntimeError):
pass
@filter_custom_jvp
def _error(x, pred, index, *, msgs, on_error, stack):
if on_error == "raise":
def raises(_index):
# Sneakily smuggle out the information about the error. Inspired by
# `sys.last_value`.
msg = msgs[_index.item()]
... | EquinoxTracetimeError |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/mapper.py | {
"start": 4981,
"end": 156646
} | class ____(
ORMFromClauseRole,
ORMEntityColumnsClauseRole[_O],
MemoizedHasCacheKey,
InspectionAttr,
log.Identified,
inspection.Inspectable["Mapper[_O]"],
EventTarget,
Generic[_O],
):
"""Defines an association between a Python class and a database table or
other relational structu... | Mapper |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pycodestyle/E30.py | {
"start": 6545,
"end": 7294
} | class ____: ...
# end
# E302
@overload
def fn(a: int) -> int: ...
@overload
def fn(a: str) -> str: ...
def fn(a: int | str) -> int | str:
...
# end
# E303
def fn():
_ = None
# arbitrary comment
def inner(): # E306 not expected (pycodestyle detects E306)
pass
# end
# E303
def fn():
... | B |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/string_conversion.py | {
"start": 3003,
"end": 3777
} | class ____(float):
def __str__(self):
x = _test_source()
return f"{x}" # __str__ method may introduce sources
def base_exception(e: Exception):
return f"{type(e)}"
def function_call_target_1(error_type: Union[str, Type[Exception]]):
f"{error_type}" # Resolved as an implicit call to a f... | OverrideStr |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_inline_schemas/pipeline.py | {
"start": 4378,
"end": 7332
} | class ____(Step):
context: ConnectorContext
title = "Migrate connector to inline schemas."
def __init__(self, context: PipelineContext) -> None:
super().__init__(context)
async def _run(self) -> StepResult:
connector = self.context.connector
connector_path = connector.code_dir... | InlineSchemas |
python | PrefectHQ__prefect | tests/test_tasks.py | {
"start": 174341,
"end": 177285
} | class ____:
@pytest.mark.parametrize(
"args, kwargs",
[
((42, 42), {}),
([42, 42], {}),
((), {"x": 42, "y": 42}),
([42], {"y": 42}),
],
)
async def test_delay_with_args_kwargs(self, args, kwargs):
@task
def multiply(x, y... | TestDelay |
python | google__jax | tests/pallas/tpu_pallas_test.py | {
"start": 114610,
"end": 137157
} | class ____(PallasBaseTest):
"""Tests for reported bugs. Only pass in interpret mode unless fixed."""
def test_casting_bool_to_i8(self):
if not jtu.is_device_tpu_at_least(5):
self.skipTest("Operation not supported on this TPU version.")
if not jtu.if_cloud_tpu_at_least(2025, 9, 12):
self.skipTes... | MiscellaneousTest |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vectors.py | {
"start": 12720,
"end": 76417
} | class ____:
@staticmethod
def self_provided(
*,
name: Optional[str] = None,
quantizer: Optional[_QuantizerConfigCreate] = None,
vector_index_config: Optional[_VectorIndexConfigCreate] = None,
):
"""Create a vector using no vectorizer. You will need to provide the vect... | _Vectors |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-vertex-endpoint/llama_index/embeddings/vertex_endpoint/utils.py | {
"start": 681,
"end": 1056
} | class ____(BaseIOHandler):
"""Handles serialization of input and deserialization of output."""
def serialize_input(self, request: List[str]) -> List[Dict[str, Any]]:
return [{"inputs": text} for text in request]
def deserialize_output(self, response: Any) -> List[List[float]]:
return [pred... | IOHandler |
python | scipy__scipy | benchmarks/benchmarks/stats_sampling.py | {
"start": 1886,
"end": 2526
} | class ____:
def __init__(self):
self.mode = 0
def pdf(self, x):
return 0.05 + 0.45 * (1 + np.sin(2*np.pi*x))
def dpdf(self, x):
return 0.2 * 0.45 * (2*np.pi) * np.cos(2*np.pi*x)
def cdf(self, x):
return (0.05*(x + 1) +
0.9*(1. + 2.*np.pi*(1 + x) - np.co... | contdist4 |
python | allegroai__clearml | clearml/backend_api/services/v2_23/queues.py | {
"start": 77250,
"end": 79613
} | class ____(Request):
"""
Moves a task entry one step forward towards the top of the queue.
:param queue: Queue id
:type queue: str
:param task: Task id
:type task: str
:param count: Number of positions in the queue to move the task forward
relative to the current position. Optional,... | MoveTaskForwardRequest |
python | kamyu104__LeetCode-Solutions | Python/maximize-sum-of-squares-of-digits.py | {
"start": 38,
"end": 428
} | class ____(object):
def maxSumOfSquares(self, num, sum):
"""
:type num: int
:type sum: int
:rtype: str
"""
if num*9 < sum:
return ""
q, r = divmod(sum, 9)
result = ['0']*num
for i in xrange(q):
result[i] = '9'
if... | Solution |
python | facebook__pyre-check | tools/generate_taint_models/generator_specifications.py | {
"start": 1451,
"end": 1968
} | class ____(ParameterAnnotation):
def __init__(
self,
parameter_taint: str,
parameter_kind: str,
) -> None:
self.parameter_taint = parameter_taint
self.parameter_kind = parameter_kind
def get(self, parameter: "Parameter") -> Optional[str]:
sanitized_parameter_... | AllParametersAnnotationWithParameterNameAsSubKind |
python | scrapy__scrapy | tests/test_selector.py | {
"start": 307,
"end": 3923
} | class ____:
def test_simple_selection(self):
"""Simple selector tests"""
body = b"<p><input name='a'value='1'/><input name='b'value='2'/></p>"
response = TextResponse(url="http://example.com", body=body, encoding="utf-8")
sel = Selector(response)
xl = sel.xpath("//input")
... | TestSelector |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 92029,
"end": 92814
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
output_link: Optional[str] = Field(
None, description="The link to find the output results."
)
query_text: Optional[str] = Field(
None,
... | SqlAlertOutput |
python | kamyu104__LeetCode-Solutions | Python/minimum-edge-weight-equilibrium-queries-in-a-tree.py | {
"start": 2773,
"end": 3901
} | class ____(object):
def minOperationsQueries(self, n, edges, queries):
"""
:type n: int
:type edges: List[List[int]]
:type queries: List[List[int]]
:rtype: List[int]
"""
adj = [[] for _ in xrange(n)]
for u, v, w in edges:
w -= 1
... | Solution |
python | astropy__astropy | astropy/time/tests/test_custom_formats.py | {
"start": 260,
"end": 7496
} | class ____(ValueError):
pass
@pytest.fixture
def custom_format_name():
for i in count():
if not i:
custom = "custom_format_name"
else:
custom = f"custom_format_name_{i}"
if custom not in Time.FORMATS:
break
yield custom
Time.FORMATS.pop(custo... | SpecificException |
python | has2k1__plotnine | plotnine/scales/scale_color.py | {
"start": 14755,
"end": 14820
} | class ____(scale_color_brewer):
pass
@alias
| scale_colour_brewer |
python | facebookresearch__faiss | contrib/datasets.py | {
"start": 4470,
"end": 5418
} | class ____(Dataset):
"""
The original dataset is available at: http://corpus-texmex.irisa.fr/
(ANN_SIFT1M)
"""
def __init__(self):
Dataset.__init__(self)
self.d, self.nt, self.nb, self.nq = 128, 100000, 1000000, 10000
self.basedir = dataset_basedir + 'sift1M/'
def get_q... | DatasetSIFT1M |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-sheets/components.py | {
"start": 18766,
"end": 23337
} | class ____(DefaultErrorHandler):
"""
Custom error handler for handling 500 errors with grid data requests.
This handler extends the DefaultErrorHandler by adding special handling for 500 errors
when includeGridData=true. When a 500 error occurs, it immediately tests if the sheet can be
fetched with... | GridDataErrorHandler |
python | kamyu104__LeetCode-Solutions | Python/string-transformation.py | {
"start": 3071,
"end": 4519
} | class ____(object):
def numberOfWays(self, s, t, k):
"""
:type s: str
:type t: str
:type k: int
:rtype: int
"""
MOD = 10**9+7
def matrix_mult(A, B):
ZB = zip(*B)
return [[sum(a*b % MOD for a, b in itertools.izip(row, col)) % MOD... | Solution3 |
python | spack__spack | lib/spack/spack/test/error_messages.py | {
"start": 2059,
"end": 2315
} | class ____(Package):
version("2.1")
version("2.0")
variant("v2", default=True, when="@2.1:")
""",
)
# Cluster of packages that includes requirements - goal is to "chain"
# the requirements like other constraints.
_pkgw4 = (
"w4",
"""\
| Z3 |
python | pyca__cryptography | tests/hazmat/primitives/test_pkcs7.py | {
"start": 54868,
"end": 55128
} | class ____:
def test_pkcs7_decrypt_unsupported(self, backend):
cert, key = _load_rsa_cert_key()
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_PADDING):
pkcs7.pkcs7_decrypt_der(b"", cert, key, [])
| TestPKCS7DecryptUnsupported |
python | pyca__cryptography | src/cryptography/hazmat/primitives/hashes.py | {
"start": 4725,
"end": 5100
} | class ____(HashAlgorithm):
name = "blake2s"
block_size = 64
_max_digest_size = 32
_min_digest_size = 1
def __init__(self, digest_size: int):
if digest_size != 32:
raise ValueError("Digest size must be 32")
self._digest_size = digest_size
@property
def digest_si... | BLAKE2s |
python | automl__auto-sklearn | autosklearn/evaluation/test_evaluator.py | {
"start": 558,
"end": 4640
} | class ____(AbstractEvaluator):
def __init__(
self,
backend: Backend,
queue: multiprocessing.Queue,
metrics: Sequence[Scorer],
additional_components: Dict[str, ThirdPartyComponents],
port: Optional[int],
configuration: Optional[Union[int, Configuration]] = None... | TestEvaluator |
python | matplotlib__matplotlib | lib/matplotlib/dates.py | {
"start": 42120,
"end": 52317
} | class ____(DateLocator):
"""
On autoscale, this class picks the best `DateLocator` to set the view
limits and the tick locations.
Attributes
----------
intervald : dict
Mapping of tick frequencies to multiples allowed for that ticking.
The default is ::
self.interv... | AutoDateLocator |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_index.py | {
"start": 920,
"end": 973
} | class ____:
def __index__(self):
...
| Index3 |
python | wandb__wandb | wandb/sdk/artifacts/_generated/registry_team_members.py | {
"start": 265,
"end": 355
} | class ____(GQLResult):
project: Optional[RegistryTeamMembersProject]
| RegistryTeamMembers |
python | django__django | tests/postgres_tests/array_default_migrations/0001_initial.py | {
"start": 81,
"end": 799
} | class ____(migrations.Migration):
dependencies = []
operations = [
migrations.CreateModel(
name="IntegerArrayDefaultModel",
fields=[
(
"id",
models.BigAutoField(
verbose_name="ID",
... | Migration |
python | plotly__plotly.py | _plotly_utils/basevalidators.py | {
"start": 53076,
"end": 55276
} | class ____(BaseValidator):
"""
"subplotid": {
"description": "An id string of a subplot type (given by dflt),
optionally followed by an integer >1. e.g. if
dflt='geo', we can have 'geo', 'geo2', 'geo3',
...",
"requiredOpts":... | SubplotidValidator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1003519,
"end": 1004148
} | class ____(sgqlc.types.Type):
"""Represents a single highlight in a search result match."""
__schema__ = github_schema
__field_names__ = ("begin_indice", "end_indice", "text")
begin_indice = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="beginIndice")
"""The indice in the fragment where... | TextMatchHighlight |
python | huggingface__transformers | src/transformers/models/bart/modeling_bart.py | {
"start": 10612,
"end": 13619
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: BartConfig, layer_idx: Optional[int] = None):
super().__init__()
self.embed_dim = config.d_model
self.self_attn = BartAttention(
embed_dim=self.embed_dim,
num_heads=config.encoder_attention_heads,
... | BartEncoderLayer |
python | pandas-dev__pandas | pandas/io/formats/format.py | {
"start": 51028,
"end": 55458
} | class ____(_GenericArrayFormatter):
values: ExtensionArray
def _format_strings(self) -> list[str]:
values = self.values
formatter = self.formatter
fallback_formatter = None
if formatter is None:
fallback_formatter = values._formatter(boxed=True)
if isinstan... | _ExtensionArrayFormatter |
python | pytorch__pytorch | torch/_vendor/packaging/version.py | {
"start": 1727,
"end": 4491
} | class ____:
_key: Tuple[Any, ...]
def __hash__(self) -> int:
return hash(self._key)
# Please keep the duplicated `isinstance` check
# in the six comparisons hereunder
# unless you find a way to avoid adding overhead function calls.
def __lt__(self, other: "_BaseVersion") -> bool:
... | _BaseVersion |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 163434,
"end": 163991
} | class ____(SendrecvmsgDgramFlagsBase,
SendrecvmsgConnectionlessBase,
ThreadedSocketTestMixin, UDP6TestBase):
def checkRecvmsgAddress(self, addr1, addr2):
# Called to compare the received address with the address of
# the peer, ignoring sco... | SendrecvmsgUDP6TestBase |
python | django__django | tests/composite_pk/models/tenant.py | {
"start": 705,
"end": 742
} | class ____(AbstractUser):
pass
| User |
python | python-markdown__markdown | markdown/extensions/toc.py | {
"start": 15510,
"end": 18330
} | class ____(Extension):
TreeProcessorClass = TocTreeprocessor
def __init__(self, **kwargs):
self.config = {
'marker': [
'[TOC]',
'Text to find and replace with Table of Contents. Set to an empty string to disable. '
'Default: `[TOC]`.'
... | TocExtension |
python | Textualize__textual | docs/examples/guide/layout/grid_layout3_row_col_adjust.py | {
"start": 80,
"end": 536
} | class ____(App):
CSS_PATH = "grid_layout3_row_col_adjust.tcss"
def compose(self) -> ComposeResult:
yield Static("One", classes="box")
yield Static("Two", classes="box")
yield Static("Three", classes="box")
yield Static("Four", classes="box")
yield Static("Five", classes=... | GridLayoutExample |
python | getsentry__sentry | src/sentry/api/serializers/models/user_social_auth.py | {
"start": 273,
"end": 520
} | class ____(Serializer):
def serialize(self, obj, attrs, user, **kwargs):
return {
"id": str(obj.id),
"provider": obj.provider,
"providerLabel": get_provider_label(obj),
}
| UserSocialAuthSerializer |
python | mwaskom__seaborn | seaborn/matrix.py | {
"start": 2739,
"end": 17203
} | class ____:
"""Draw a heatmap plot of a matrix with nice labels and colormaps."""
def __init__(self, data, vmin, vmax, cmap, center, robust, annot, fmt,
annot_kws, cbar, cbar_kws,
xticklabels=True, yticklabels=True, mask=None):
"""Initialize the plotting object."""
... | _HeatMapper |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-ibm/tests/test_ibm.py | {
"start": 141,
"end": 3537
} | class ____:
TEST_URL = "https://us-south.ml.cloud.ibm.com"
TEST_APIKEY = "apikey"
TEST_PROJECT_ID = "project_id"
TEST_MODEL = "test_model"
def mock_embed_query(self) -> List[float]:
return [-0.053358648, -0.009175377, -0.025022397]
def mock_embed_texts(self) -> List[List[float]]:
... | TestWasonxLLMInference |
python | python__mypy | mypy/patterns.py | {
"start": 2457,
"end": 2857
} | class ____(Pattern):
# None corresponds to *_ in a list pattern. It will match multiple items but won't bind them to
# a name.
capture: NameExpr | None
def __init__(self, capture: NameExpr | None) -> None:
super().__init__()
self.capture = capture
def accept(self, visitor: PatternV... | StarredPattern |
python | google__pytype | pytype/tests/test_paramspec.py | {
"start": 7468,
"end": 15560
} | class ____(test_base.BaseTest):
"""Tests for ParamSpec imported from pyi files."""
def test_decorator(self):
with self.DepTree([("foo.pyi", _DECORATOR_PYI)]):
ty, _ = self.InferWithErrors("""
import foo
class A:
pass
@foo.decorator
def h(a: A, b: str) -> int:
... | PyiParamSpecTest |
python | astropy__astropy | astropy/extern/configobj/validate.py | {
"start": 14149,
"end": 14553
} | class ____(VdtValueError):
"""The value supplied was of the correct type, but was too long."""
def __init__(self, value):
"""
>>> raise VdtValueTooLongError('jedie')
Traceback (most recent call last):
VdtValueTooLongError: the value "jedie" is too long.
"""
Valid... | VdtValueTooLongError |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-web/llama_index/readers/web/agentql_web/base.py | {
"start": 369,
"end": 3021
} | class ____(BasePydanticReader):
"""
Scrape a URL with or without a agentql query and returns document in json format.
Args:
api_key (str): The AgentQL API key, get one at https://dev.agentql.com
params (dict): Additional parameters to pass to the AgentQL API. Visit https://docs.agentql.com/... | AgentQLWebReader |
python | allegroai__clearml | clearml/utilities/gpu/pynvml.py | {
"start": 41187,
"end": 41901
} | class ____(_PrintableStructure):
_fields_ = [
# Moved to the new busId location below
('busIdLegacy', c_char * NVML_DEVICE_PCI_BUS_ID_BUFFER_V2_SIZE),
('domain', c_uint),
('bus', c_uint),
('device', c_uint),
('pciDeviceId', c_uint),
# Added in 2.285
(... | nvmlPciInfo_t |
python | walkccc__LeetCode | solutions/673. Number of Longest Increasing Subsequence/673.py | {
"start": 0,
"end": 794
} | class ____:
def findNumberOfLIS(self, nums: list[int]) -> int:
ans = 0
maxLength = 0
# length[i] := the length of the LIS ending in nums[i]
length = [1] * len(nums)
# count[i] := the number of LIS's ending in nums[i]
count = [1] * len(nums)
# Calculate the `length` and `count` arrays.
... | Solution |
python | apache__airflow | providers/google/tests/unit/google/cloud/sensors/test_dataflow.py | {
"start": 14054,
"end": 20993
} | class ____:
@pytest.mark.parametrize(
("job_current_state", "fail_on_terminal_state"),
[
(DataflowJobStatus.JOB_STATE_RUNNING, True),
(DataflowJobStatus.JOB_STATE_RUNNING, False),
(DataflowJobStatus.JOB_STATE_DONE, False),
],
)
@mock.patch("airflow... | TestDataflowJobMessagesSensor |
python | pytorch__pytorch | torch/nn/modules/pooling.py | {
"start": 1773,
"end": 4963
} | class ____(_MaxPoolNd):
r"""Applies a 1D max pooling over an input signal composed of several input planes.
In the simplest case, the output value of the layer with input size :math:`(N, C, L)`
and output :math:`(N, C, L_{out})` can be precisely described as:
.. math::
out(N_i, C_j, k) = \max_... | MaxPool1d |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 22414,
"end": 22527
} | class ____(InetTestBase):
"""Base class for IPv6 socket tests."""
host = socket_helper.HOSTv6
| Inet6TestBase |
python | apache__airflow | airflow-core/src/airflow/example_dags/example_dynamic_task_mapping_with_no_taskflow_operators.py | {
"start": 1255,
"end": 2017
} | class ____(BaseOperator):
"""A custom operator that sums the input."""
template_fields = ("values",)
def __init__(self, values, **kwargs):
super().__init__(**kwargs)
self.values = values
def execute(self, context):
total = sum(self.values)
print(f"Total was {total}")
... | SumItOperator |
python | nedbat__coveragepy | coverage/multiproc.py | {
"start": 702,
"end": 2198
} | class ____(OriginalProcess): # pylint: disable=abstract-method
"""A replacement for multiprocess.Process that starts coverage."""
def _bootstrap(self, *args, **kwargs): # type: ignore[no-untyped-def]
"""Wrapper around _bootstrap to start coverage."""
debug: DebugControl | None = None
... | ProcessWithCoverage |
python | PrefectHQ__prefect | src/prefect/events/filters.py | {
"start": 5922,
"end": 7120
} | class ____(EventDataFilter):
id: Optional[list[str]] = Field(
default=None, description="Only include events for resources with these IDs"
)
id_prefix: Optional[list[str]] = Field(
default=None,
description=(
"Only include events for resources with IDs starting with these... | EventAnyResourceFilter |
python | python__mypy | mypy/test/teststubtest.py | {
"start": 3096,
"end": 3324
} | class ____(Sequence[T]): ...
def property(f: T) -> T: ...
def classmethod(f: T) -> T: ...
def staticmethod(f: T) -> T: ...
"""
stubtest_enum_stub = """
import sys
from typing import Any, TypeVar, Iterator
_T = TypeVar('_T')
| list |
python | pennersr__django-allauth | allauth/headless/account/response.py | {
"start": 283,
"end": 515
} | class ____(APIResponse):
def __init__(self, request, verification_sent):
super().__init__(
request, status=HTTPStatus.OK if verification_sent else HTTPStatus.FORBIDDEN
)
| RequestEmailVerificationResponse |
python | allegroai__clearml | clearml/backend_api/services/v2_9/workers.py | {
"start": 74405,
"end": 74643
} | class ____(Response):
"""
Response of workers.register endpoint.
"""
_service = "workers"
_action = "register"
_version = "2.9"
_schema = {"definitions": {}, "properties": {}, "type": "object"}
| RegisterResponse |
python | davidhalter__jedi | test/completion/stdlib.py | {
"start": 4987,
"end": 5847
} | class ____(enum.Enum):
attr_x = 3
attr_y = 2.0
#? ['mro']
X.mro
#? ['attr_x', 'attr_y']
X.attr_
#? str()
X.attr_x.name
#? int()
X.attr_x.value
#? str()
X.attr_y.name
#? float()
X.attr_y.value
#? str()
X().name
#? float()
X().attr_x.attr_y.value
# -----------------
# functools
# -----------------
import functo... | X |
python | django__django | tests/m2m_through_regress/models.py | {
"start": 351,
"end": 615
} | class ____(models.Model):
id = models.AutoField(db_column="usermembership_id", primary_key=True)
user = models.ForeignKey(User, models.CASCADE)
group = models.ForeignKey("Group", models.CASCADE)
price = models.IntegerField(default=100)
| UserMembership |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/compute_log_manager.py | {
"start": 5555,
"end": 15103
} | class ____(ABC, MayHaveInstanceWeakref[T_DagsterInstance]):
"""Abstract base class for capturing the unstructured logs (stdout/stderr) in the current
process, stored / retrieved with a provided log_key.
"""
@abstractmethod
@contextmanager
def capture_logs(self, log_key: Sequence[str]) -> Genera... | ComputeLogManager |
python | sqlalchemy__sqlalchemy | examples/space_invaders/space_invaders.py | {
"start": 7030,
"end": 7327
} | class ____(EnemyGlyph):
"""Describe the enemy saucer flying overhead."""
__mapper_args__ = {"polymorphic_identity": "saucer"}
def glyph_for_state(self, coord, state):
if state["flip"] == 0:
return self.alt_data
else:
return self.data
| SaucerGlyph |
python | chroma-core__chroma | chromadb/test/property/test_collections_with_database_tenant.py | {
"start": 523,
"end": 6047
} | class ____(CollectionStateMachine):
"""A collection state machine test that includes tenant and database information,
and switches between them."""
tenants: Bundle # [str]
databases: Bundle # [Tuple[str, str]] # database to tenant it belongs to
tenant_to_database_to_model: Dict[
str, Dic... | TenantDatabaseCollectionStateMachine |
python | PrefectHQ__prefect | src/prefect/events/actions.py | {
"start": 2823,
"end": 2964
} | class ____(DeploymentAction):
"""Pauses the given Deployment"""
type: Literal["pause-deployment"] = "pause-deployment"
| PauseDeployment |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramSpec4.py | {
"start": 2836,
"end": 3405
} | class ____(Generic[R, P]):
f: Callable[P, str]
prop: R
def __init__(self, f: Callable[P, str], prop: R) -> None:
self.f = f
self.prop = prop
def func10(q: int, /) -> str: ...
y1 = A(func10, 1)
assert_type(y1, A[int, [int]])
reveal_type(y1, expected_text="A[int, (q: int, /)]")
# This s... | A |
python | miyuchina__mistletoe | mistletoe/span_token.py | {
"start": 6504,
"end": 7079
} | class ____(SpanToken):
"""
Escape sequence token. ("\\\\*")
This is an inline token with a single child of type RawText.
Attributes:
children (iterator): a single RawText node containing the escaped character.
"""
pattern = re.compile(r"\\([!\"#$%&'()*+,-./:;<=>?@\[\\\]^_`{|}~])")
p... | EscapeSequence |
python | docker__docker-py | docker/types/networks.py | {
"start": 1738,
"end": 1901
} | class ____(dict):
def __init__(self, endpoints_config=None):
if endpoints_config:
self["EndpointsConfig"] = endpoints_config
| NetworkingConfig |
python | huggingface__transformers | tests/models/layoutlm/test_modeling_layoutlm.py | {
"start": 8812,
"end": 13837
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(
LayoutLMModel,
LayoutLMForMaskedLM,
LayoutLMForSequenceClassification,
LayoutLMForTokenClassification,
LayoutLMForQuestionAnswering,
)
if ... | LayoutLMModelTest |
python | tensorflow__tensorflow | tensorflow/python/ops/weak_tensor_np_math_ops_test.py | {
"start": 1889,
"end": 8143
} | class ____(test_util.TensorFlowTestCase, parameterized.TestCase):
def setUp(self):
super(MathTest, self).setUp()
self.array_transforms = [
lambda x: x, # Identity,
_get_weak_tensor,
np_array_ops.array,
]
self.types = [np.int32, np.int64, np.float32, np.float64]
def _testUn... | MathTest |
python | ray-project__ray | python/ray/util/client/dataclient.py | {
"start": 4292,
"end": 7522
} | class ____:
"""
This object collects chunks from async get requests via __call__, and
calls the underlying callback when the object is fully received, or if an
exception while retrieving the object occurs.
This is not used in synchronous gets (synchronous gets interact with the
raylet servicer ... | ChunkCollector |
python | fastai__fastai | fastai/data/load.py | {
"start": 2537,
"end": 3781
} | class ____(Exception):
"Raised to notify `DataLoader` to skip an item"
pass
# %% ../../nbs/02_data.load.ipynb 15
def collate_error(e:Exception, batch):
"Raises error when the batch could not collate, stating what items in the batch are different sizes and their types"
err = f'Error when trying to colla... | SkipItemException |
python | sympy__sympy | sympy/physics/quantum/gate.py | {
"start": 30464,
"end": 42588
} | class ____(TwoQubitGate):
"""Two qubit SWAP gate.
This gate swap the values of the two qubits.
Parameters
----------
label : tuple
A tuple of the form (target1, target2).
Examples
========
"""
is_hermitian = True
gate_name = 'SWAP'
gate_name_latex = r'\text{SWAP}'... | SwapGate |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.