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 | keras-team__keras | keras/src/models/cloning_test.py | {
"start": 2291,
"end": 8983
} | class ____(testing.TestCase):
def assert_models_equal(self, model1, model2, ref_input):
result1 = model1(ref_input)
result2 = model2(ref_input)
for r1, r2 in zip(tree.flatten(result1), tree.flatten(result2)):
self.assertAllClose(
ops.convert_to_numpy(r1), ops.conv... | CloneModelTest |
python | django-extensions__django-extensions | django_extensions/management/commands/runjobs.py | {
"start": 280,
"end": 3518
} | class ____(BaseCommand):
help = "Runs scheduled maintenance jobs."
when_options = [
"minutely",
"quarter_hourly",
"hourly",
"daily",
"weekly",
"monthly",
"yearly",
]
def add_arguments(self, parser):
super().add_arguments(parser)
p... | Command |
python | Textualize__textual | examples/five_by_five.py | {
"start": 4392,
"end": 9471
} | class ____(Screen):
"""Main 5x5 game grid screen."""
SIZE: Final = 5
"""The size of the game grid. Clue's in the name really."""
BINDINGS = [
Binding("n", "new_game", "New Game"),
Binding("question_mark", "app.push_screen('help')", "Help", key_display="?"),
Binding("q", "app.qu... | Game |
python | mlflow__mlflow | tests/langgraph/sample_code/langgraph_prebuilt.py | {
"start": 308,
"end": 1618
} | class ____(ChatOpenAI, extra="allow"):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._responses = itertools.cycle(
[
AIMessage(
content="",
tool_calls=[ToolCall(name="get_weather", args={"city": "sf"},... | FakeOpenAI |
python | getsentry__sentry | src/sentry/integrations/repository/issue_alert.py | {
"start": 1596,
"end": 1698
} | class ____(NotificationMessageValidationError):
pass
| NewIssueAlertNotificationMessageValidationError |
python | openai__openai-python | src/openai/resources/chat/completions/completions.py | {
"start": 81258,
"end": 160117
} | class ____(AsyncAPIResource):
@cached_property
def messages(self) -> AsyncMessages:
return AsyncMessages(self._client)
@cached_property
def with_raw_response(self) -> AsyncCompletionsWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
... | AsyncCompletions |
python | kamyu104__LeetCode-Solutions | Python/longest-common-prefix.py | {
"start": 71,
"end": 527
} | class ____(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
for i in xrange(len(strs[0])):
for string in strs[1:]:
if i >= len(string) or string[i] != strs[0][i]:
... | Solution |
python | walkccc__LeetCode | solutions/1370. Increasing Decreasing String/1370.py | {
"start": 0,
"end": 312
} | class ____:
def sortString(self, s: str) -> str:
ans = []
count = collections.Counter(s)
while count:
for chars in string.ascii_lowercase, reversed(string.ascii_lowercase):
ans += [c for c in chars if c in count]
count -= dict.fromkeys(count, 1)
return ''.join(ans)
| Solution |
python | psf__black | tests/data/cases/raw_docstring.py | {
"start": 127,
"end": 170
} | class ____:
R"""Raw"""
# output
| UpperCaseR |
python | doocs__leetcode | solution/1400-1499/1431.Kids With the Greatest Number of Candies/Solution.py | {
"start": 0,
"end": 191
} | class ____:
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
mx = max(candies)
return [candy + extraCandies >= mx for candy in candies]
| Solution |
python | numpy__numpy | benchmarks/benchmarks/bench_function_base.py | {
"start": 1790,
"end": 2606
} | class ____(Benchmark):
def setup(self):
self.e = np.arange(10000, dtype=np.float32)
self.o = np.arange(10001, dtype=np.float32)
self.tall = np.random.random((10000, 20))
self.wide = np.random.random((20, 10000))
def time_even(self):
np.median(self.e)
def time_odd(se... | Median |
python | boto__boto3 | tests/functional/test_s3.py | {
"start": 850,
"end": 1904
} | class ____(unittest.TestCase):
def test_transfer_methods_injected_to_client(self):
session = boto3.session.Session(region_name='us-west-2')
client = session.client('s3')
assert hasattr(client, 'upload_file')
assert hasattr(client, 'download_file')
assert hasattr(client, 'copy... | TestS3MethodInjection |
python | tensorflow__tensorflow | tensorflow/python/data/ops/dataset_ops.py | {
"start": 186831,
"end": 188104
} | class ____(composite_tensor.CompositeTensor):
def __init__(self, variant_tensor, element_spec, dataset_shape):
self._variant_tensor = variant_tensor
self._element_spec = element_spec
self._dataset_shape = dataset_shape
@property
def _type_spec(self):
return DatasetSpec(self._element_spec, self._... | _NestedVariant |
python | ray-project__ray | python/ray/data/tests/test_json.py | {
"start": 18726,
"end": 21058
} | class ____:
@pytest.mark.parametrize(
"data",
[{"a": []}, {"a": [1]}, {"a": [1, 2, 3]}],
ids=["empty", "single", "multiple"],
)
@pytest.mark.parametrize(
"compression,filename",
[("gzip", "test.json.gz"), ("infer", "test.json")], # infer = default
)
def test_... | TestPandasJSONDatasource |
python | pytorch__pytorch | test/test_utils.py | {
"start": 23147,
"end": 23278
} | class ____(TestCase):
def test_import_hipify(self):
from torch.utils.hipify import hipify_python # noqa: F401
| TestHipify |
python | kamyu104__LeetCode-Solutions | Python/insert-into-a-sorted-circular-linked-list.py | {
"start": 29,
"end": 134
} | class ____(object):
def __init__(self, val, next):
self.val = val
self.next = next
| Node |
python | bottlepy__bottle | test/test_environ.py | {
"start": 19717,
"end": 31884
} | class ____(unittest.TestCase):
def test_constructor_body(self):
self.assertEqual('',
BaseResponse('').body)
self.assertEqual('YAY',
BaseResponse('YAY').body)
def test_constructor_status(self):
self.assertEqual(200,
BaseResponse('YAY', 200).status_co... | TestResponse |
python | doocs__leetcode | solution/0800-0899/0831.Masking Personal Information/Solution.py | {
"start": 0,
"end": 331
} | class ____:
def maskPII(self, s: str) -> str:
if s[0].isalpha():
s = s.lower()
return s[0] + '*****' + s[s.find('@') - 1 :]
s = ''.join(c for c in s if c.isdigit())
cnt = len(s) - 10
suf = '***-***-' + s[-4:]
return suf if cnt == 0 else f'+{"*" * cnt}-... | Solution |
python | run-llama__llama_index | llama-index-core/llama_index/core/agent/workflow/workflow_events.py | {
"start": 544,
"end": 650
} | class ____(Event):
"""LLM input."""
input: list[ChatMessage]
current_agent_name: str
| AgentInput |
python | eth-brownie__brownie | brownie/test/managers/base.py | {
"start": 427,
"end": 10517
} | class ____:
"""
Brownie plugin base hooks.
Pytest hooks in this class are used in every testing mode.
"""
def __init__(self, config, project):
_apply_given_wrapper()
self.config = config
# required when brownie project is in a subfolder of another project
config._r... | PytestBrownieBase |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/ddl.py | {
"start": 23514,
"end": 28423
} | class ____(DialectKWArgs, _TableViaSelect):
"""Represent a CREATE VIEW statement.
This creates a new view based on a particular SELECT statement. The schema
of the view is based on the columns of the SELECT statement, and the data
present in the view is derived from the rows represented by the
SELE... | CreateView |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_numeric.py | {
"start": 106536,
"end": 108845
} | class ____(TestCase):
def test_broadcast_in_args(self):
# gh-5881
arrs = [
np.empty((6, 7)),
np.empty((5, 6, 1)),
np.empty((7,)),
np.empty((5, 1, 7)),
]
mits = [
np.broadcast(*arrs),
np.broadcast(np.broadcast(*ar... | TestBroadcast |
python | psf__black | tests/data/cases/preview_long_strings__regression.py | {
"start": 23733,
"end": 23999
} | class ____:
def foo():
XXXXXXXXXXXX.append((
"xxx_xxxxxxxxxx(xxxxx={}, xxxx={}, xxxxx, xxxx_xxxx_xxxxxxxxxx={})".format(
xxxxx, xxxx, xxxx_xxxx_xxxxxxxxxx
),
my_var,
my_other_var,
))
| A |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dataproc.py | {
"start": 18895,
"end": 19545
} | class ____(DataprocTestBase):
@classmethod
def setup_class(cls):
if AIRFLOW_V_3_0_PLUS:
cls.extra_links_expected_calls = [
call.ti.xcom_push(key="conf", value=DATAPROC_JOB_CONF_EXPECTED),
call.hook().wait_for_job(job_id=TEST_JOB_ID, region=GCP_REGION, project_... | DataprocJobTestBase |
python | huggingface__transformers | tests/models/layoutxlm/test_processing_layoutxlm.py | {
"start": 5326,
"end": 21526
} | class ____(unittest.TestCase):
@cached_property
def get_images(self):
# we verify our implementation on 2 document images from the DocVQA dataset
from datasets import load_dataset
ds = load_dataset("hf-internal-testing/fixtures_docvqa", split="test")
return ds[0]["image"].conver... | LayoutXLMProcessorIntegrationTests |
python | astropy__astropy | astropy/cosmology/_src/tests/io/test_yaml.py | {
"start": 1648,
"end": 5852
} | class ____(ToFromTestMixinBase):
"""
Tests for a Cosmology[To/From]Format with ``format="yaml"``.
This class will not be directly called by :mod:`pytest` since its name does
not begin with ``Test``. To activate the contained tests this class must
be inherited in a subclass. Subclasses must define a ... | ToFromYAMLTestMixin |
python | doocs__leetcode | solution/1800-1899/1855.Maximum Distance Between a Pair of Values/Solution2.py | {
"start": 0,
"end": 318
} | class ____:
def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:
m, n = len(nums1), len(nums2)
ans = i = j = 0
while i < m:
while j < n and nums1[i] <= nums2[j]:
j += 1
ans = max(ans, j - i - 1)
i += 1
return ans
| Solution |
python | getsentry__sentry | src/sentry/sentry_apps/api/serializers/platform_external_issue.py | {
"start": 540,
"end": 1038
} | class ____(Serializer):
def serialize(
self,
obj: PlatformExternalIssue,
attrs: Mapping[str, Any],
user: User | AnonymousUser | RpcUser,
**kwargs: Any,
) -> PlatformExternalIssueSerializerResponse:
return {
"id": str(obj.id),
"issueId": str... | PlatformExternalIssueSerializer |
python | getsentry__sentry | src/sentry/integrations/api/endpoints/organization_integration_serverless_functions.py | {
"start": 887,
"end": 3162
} | class ____(RegionOrganizationIntegrationBaseEndpoint):
owner = ApiOwner.INTEGRATIONS
publish_status = {
"GET": ApiPublishStatus.UNKNOWN,
"POST": ApiPublishStatus.UNKNOWN,
}
def get(
self,
request: Request,
organization: Organization,
integration_id: int,
... | OrganizationIntegrationServerlessFunctionsEndpoint |
python | scipy__scipy | scipy/sparse/linalg/tests/test_onenormest.py | {
"start": 288,
"end": 1069
} | class ____(scipy.sparse.linalg.LinearOperator):
"""
This is purely for onenormest testing.
"""
def __init__(self, A, B):
if A.ndim != 2 or B.ndim != 2:
raise ValueError('expected ndarrays representing matrices')
if A.shape[1] != B.shape[0]:
raise ValueError('inco... | MatrixProductOperator |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/mariadb.py | {
"start": 965,
"end": 1111
} | class ____(sqltypes.TypeEngine[str]):
"""INET6 column type for MariaDB
.. versionadded:: 2.0.37
"""
__visit_name__ = "INET6"
| INET6 |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 249293,
"end": 249492
} | class ____(unittest.TestCase):
def test_tcp_keepalive(self):
self.assertTrue(socket.TCP_KEEPALIVE)
@unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
| TestMacOSTCPFlags |
python | huggingface__transformers | tests/models/dinov2_with_registers/test_modeling_dinov2_with_registers.py | {
"start": 11301,
"end": 12840
} | class ____(unittest.TestCase):
@cached_property
def default_image_processor(self):
return (
AutoImageProcessor.from_pretrained("facebook/dinov2-with-registers-base")
if is_vision_available()
else None
)
@slow
def test_inference_no_head(self):
... | Dinov2WithRegistersModelIntegrationTest |
python | huggingface__transformers | src/transformers/models/fsmt/configuration_fsmt.py | {
"start": 781,
"end": 1225
} | class ____(PreTrainedConfig):
r"""
Configuration class for FSMT's decoder specific things. note: this is a private helper class
"""
model_type = "fsmt_decoder"
def __init__(self, vocab_size=0, bos_token_id=0, is_encoder_decoder=True, **kwargs):
super().__init__(**kwargs)
self.vocab... | DecoderConfig |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/sparse/csr_sparse_matrix_test.py | {
"start": 5017,
"end": 9975
} | class ____(test.TestCase):
@classmethod
def setUpClass(cls): # pylint: disable=g-missing-super-call
cls._gpu_available = test_util.is_gpu_available()
def _testSparseSparse(self, transpose_a, transpose_b, adjoint_a, adjoint_b):
if not self._gpu_available:
return
sparsify = lambda m: m * (m > 0... | SparseMatrixMatmulTest |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-you/llama_index/llms/you/base.py | {
"start": 1535,
"end": 3956
} | class ____(CustomLLM):
"""
Wrapper around You.com's conversational Smart and Research APIs.
Each API endpoint is designed to generate conversational
responses to a variety of query types, including inline citations
and web results when relevant.
Smart Mode:
- Quick, reliable answers for a ... | You |
python | cython__cython | docs/examples/userguide/language_basics/override.py | {
"start": 165,
"end": 244
} | class ____(B): # NOTE: no cclass decorator
def foo(self):
print("C")
| C |
python | apache__airflow | providers/common/sql/tests/unit/common/sql/operators/test_sql.py | {
"start": 2545,
"end": 2654
} | class ____:
def get_records(self):
return
def _get_mock_db_hook():
return MockHook()
| MockHook |
python | django__django | django/contrib/auth/backends.py | {
"start": 9371,
"end": 12845
} | class ____(ModelBackend):
"""
This backend is to be used in conjunction with the ``RemoteUserMiddleware``
found in the middleware module of this package, and is used when the server
is handling authentication outside of Django.
By default, the ``authenticate`` method creates ``User`` objects for
... | RemoteUserBackend |
python | getsentry__sentry | src/sentry/migrations/0974_hc_json_field.py | {
"start": 244,
"end": 2057
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | numba__numba | numba/tests/test_extending_types.py | {
"start": 734,
"end": 4990
} | class ____(unittest.TestCase):
def setUp(self):
class Dummy(object):
def __init__(self, value):
self.value = value
class DummyType(types.Type):
def __init__(self):
super(DummyType, self).__init__(name='Dummy')
dummy_type = DummyType(... | TestExtTypDummy |
python | ray-project__ray | python/ray/autoscaler/v2/tests/test_node_provider.py | {
"start": 10917,
"end": 29381
} | class ____(unittest.TestCase):
def setUp(self):
raycluster_cr = get_basic_ray_cr()
# Remove fake TPU and GPU worker groups from CR since podlist1 only
# contains small-group.
raycluster_cr["spec"]["workerGroupSpecs"][1]["replicas"] = 0
raycluster_cr["spec"]["workerGroupSpecs"... | KubeRayProviderIntegrationTest |
python | getsentry__sentry | src/sentry/metrics/logging.py | {
"start": 103,
"end": 1983
} | class ____(MetricsBackend):
def incr(
self,
key: str,
instance: str | None = None,
tags: Tags | None = None,
amount: float | int = 1,
sample_rate: float = 1,
unit: str | None = None,
stacklevel: int = 0,
) -> None:
logger.debug("%r: %+g", k... | LoggingBackend |
python | scikit-learn__scikit-learn | sklearn/utils/_tags.py | {
"start": 6126,
"end": 9817
} | class ____:
"""Tags for the estimator.
See :ref:`estimator_tags` for more information.
Parameters
----------
estimator_type : str or None
The type of the estimator. Can be one of:
- "classifier"
- "regressor"
- "transformer"
- "clusterer"
- "outlier_... | Tags |
python | ansible__ansible | lib/ansible/utils/context_objects.py | {
"start": 1589,
"end": 1907
} | class ____(Singleton, ABCMeta):
"""
Combine ABCMeta based classes with Singleton based classes
Combine Singleton and ABCMeta so we have a metaclass that unambiguously knows which can override
the other. Useful for making new types of containers which are also Singletons.
"""
pass
| _ABCSingleton |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/random/random_ops_test.py | {
"start": 10161,
"end": 15773
} | class ____(RandomOpTestCommon):
def _Sampler(self, num, minv, maxv, dtype, use_gpu, seed=None):
def func():
with self.session(use_gpu=use_gpu, graph=ops.Graph()) as sess:
rng = random_ops.random_uniform(
[num], minval=minv, maxval=maxv, dtype=dtype, seed=seed)
ret = np.empty([1... | RandomUniformTest |
python | huggingface__transformers | src/transformers/models/llava_next_video/modeling_llava_next_video.py | {
"start": 7740,
"end": 13349
} | class ____(PreTrainedModel):
config: LlavaNextVideoConfig
base_model_prefix = "model"
input_modalities = ("image", "video", "text")
supports_gradient_checkpointing = True
_no_split_modules = ["LlamaDecoderLayer"]
_skip_keys_device_placement = "past_key_values"
_supports_flash_attn = True
... | LlavaNextVideoPreTrainedModel |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_run.py | {
"start": 3833,
"end": 6086
} | class ____(GoogleCloudBaseOperator):
"""
Updates a job and wait for the operation to be completed. Pushes the updated job to xcom.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param region: Required. The ID of the Google Cloud region that the service bel... | CloudRunUpdateJobOperator |
python | django__django | tests/auth_tests/test_auth_backends.py | {
"start": 50557,
"end": 52696
} | class ____(TestCase):
backend = "auth_tests.test_auth_backends.CustomModelBackend"
other_backend = "auth_tests.test_auth_backends.OtherModelBackend"
username = "username"
password = "password"
def assertBackendInSession(self, backend):
request = HttpRequest()
request.session = self.... | SelectingBackendTests |
python | pydata__xarray | xarray/tests/test_datatree.py | {
"start": 85904,
"end": 86416
} | class ____:
def __init__(self):
self.closed = False
def close(self):
if self.closed:
raise RuntimeError("already closed")
self.closed = True
@pytest.fixture
def tree_and_closers():
tree = DataTree.from_dict({"/child/grandchild": None})
closers = {
"/": Clos... | Closer |
python | google__jax | jax/experimental/pallas/ops/tpu/paged_attention/quantization_utils.py | {
"start": 703,
"end": 2556
} | class ____(NamedTuple):
"""A tensor which has been quantized to int8 and its scales.
Attributes:
weight: Weight
scales: Scales
"""
weight: jnp.ndarray
scales: jnp.ndarray
def to_int8(x: jnp.ndarray, h: jnp.ndarray) -> jnp.ndarray:
"""Converts a float array to an int8 array with a scale.
Args:... | QuantizedTensor |
python | pytorch__pytorch | torch/_dynamo/convert_frame.py | {
"start": 68221,
"end": 76285
} | class ____:
def __init__(
self,
compiler_fn: CompilerFn,
hooks: Hooks,
package: Optional[CompilePackage] = None,
) -> None:
self._torchdynamo_orig_backend = compiler_fn
self._inner_convert = convert_frame_assert(
compiler_fn, one_graph=False, package=p... | ConvertFrame |
python | sympy__sympy | sympy/codegen/fnodes.py | {
"start": 18470,
"end": 18605
} | class ____(FFunction):
""" Fortran complex conversion function. """
nargs = 2 # may be extended to (2, 3) at a later point
| cmplx |
python | openai__openai-python | src/openai/types/responses/response_output_text.py | {
"start": 482,
"end": 804
} | class ____(BaseModel):
file_id: str
"""The ID of the file."""
filename: str
"""The filename of the file cited."""
index: int
"""The index of the file in the list of files."""
type: Literal["file_citation"]
"""The type of the file citation. Always `file_citation`."""
| AnnotationFileCitation |
python | huggingface__transformers | src/transformers/models/clvp/modeling_clvp.py | {
"start": 28427,
"end": 34711
} | class ____(nn.Module):
"""
This class processes the log-mel spectrograms(extracted by the Feature Extractor) and text tokens(produced by the
tokenizer) as inputs for the decoder model.
First each log-mel spectrogram is processed into a single vector which captures valuable characteristics from each
... | ClvpConditioningEncoder |
python | python-excel__xlrd | tests/test_biffh.py | {
"start": 272,
"end": 575
} | class ____(unittest.TestCase):
def test_hex_char_dump(self):
sio = StringIO()
biffh.hex_char_dump(b"abc\0e\01", 0, 6, fout=sio)
s = sio.getvalue()
assert "61 62 63 00 65 01" in s, s
assert "abc~e?" in s, s
if __name__=='__main__':
unittest.main()
| TestHexDump |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/history.py | {
"start": 8066,
"end": 9441
} | class ____(History):
"""
:class:`.History` class that stores all strings in a file.
"""
def __init__(self, filename: _StrOrBytesPath) -> None:
self.filename = filename
super().__init__()
def load_history_strings(self) -> Iterable[str]:
strings: list[str] = []
lines:... | FileHistory |
python | doocs__leetcode | solution/0300-0399/0384.Shuffle an Array/Solution.py | {
"start": 0,
"end": 580
} | class ____:
def __init__(self, nums: List[int]):
self.nums = nums
self.original = nums.copy()
def reset(self) -> List[int]:
self.nums = self.original.copy()
return self.nums
def shuffle(self) -> List[int]:
for i in range(len(self.nums)):
j = random.randr... | Solution |
python | joke2k__faker | tests/providers/test_currency.py | {
"start": 11521,
"end": 11946
} | class ____:
"""Test fr_FR currency provider"""
num_samples = 100
@classmethod
def setup_class(cls):
from faker.providers.currency.fr_FR import Provider as FrFrCurrencyProvider
cls.provider = FrFrCurrencyProvider
def test_pricetag(self, faker, num_samples):
for _ in range(... | TestFrFr |
python | openai__gym | gym/envs/mujoco/inverted_double_pendulum_v4.py | {
"start": 109,
"end": 9332
} | class ____(MujocoEnv, utils.EzPickle):
"""
### Description
This environment originates from control theory and builds on the cartpole
environment based on the work done by Barto, Sutton, and Anderson in
["Neuronlike adaptive elements that can solve difficult learning control problems"](https://ieee... | InvertedDoublePendulumEnv |
python | PyCQA__pylint | pylint/pyreverse/printer.py | {
"start": 566,
"end": 770
} | class ____(Enum):
INHERITS = "inherits"
COMPOSITION = "composition"
ASSOCIATION = "association"
AGGREGATION = "aggregation"
USES = "uses"
TYPE_DEPENDENCY = "type_dependency"
| EdgeType |
python | aio-libs__aiohttp | aiohttp/_websocket/models.py | {
"start": 1359,
"end": 1688
} | class ____(NamedTuple):
data: bytes
size: int
extra: str | None = None
type: Literal[WSMsgType.BINARY] = WSMsgType.BINARY
def json(
self, *, loads: Callable[[str | bytes | bytearray], Any] = json.loads
) -> Any:
"""Return parsed JSON data."""
return loads(self.data)
| WSMessageBinary |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingFalsy1.py | {
"start": 2006,
"end": 2180
} | class ____(NT1):
pass
def func9(val: NT2) -> None:
if val:
reveal_type(val, expected_text="NT2")
else:
reveal_type(val, expected_text="Never")
| NT2 |
python | getsentry__sentry | src/sentry/rules/conditions/event_frequency.py | {
"start": 32678,
"end": 39322
} | class ____(BaseEventFrequencyCondition):
id = "sentry.rules.conditions.event_frequency.EventFrequencyPercentCondition"
label = "The issue affects more than {value} percent of sessions in {interval}"
logger = logging.getLogger("sentry.rules.event_frequency")
def __init__(self, *args: Any, **kwargs: Any)... | EventFrequencyPercentCondition |
python | PrefectHQ__prefect | tests/utilities/test_importtools.py | {
"start": 596,
"end": 11546
} | class ____:
pass
# Note we use the hosted API to avoid Postgres engine caching errors
pytest.mark.usefixtures("hosted_orion")
@pytest.mark.parametrize(
"obj,expected",
[
(to_qualified_name, "prefect.utilities.importtools.to_qualified_name"),
(prefect.tasks.Task, "prefect.tasks.Task"),
... | Foo |
python | psf__black | tests/data/cases/class_methods_new_line.py | {
"start": 30,
"end": 68
} | class ____:
a = 1
| ClassWithSingleField |
python | keras-team__keras | keras/src/layers/preprocessing/mel_spectrogram.py | {
"start": 250,
"end": 14697
} | class ____(DataLayer):
"""A preprocessing layer to convert raw audio signals to Mel spectrograms.
This layer takes `float32`/`float64` single or batched audio signal as
inputs and computes the Mel spectrogram using Short-Time Fourier Transform
and Mel scaling. The input should be a 1D (unbatched) or 2D... | MelSpectrogram |
python | pandas-dev__pandas | pandas/tests/series/test_arithmetic.py | {
"start": 33110,
"end": 36304
} | class ____:
@pytest.mark.parametrize(
"dtype1, dtype2, dtype_expected, dtype_mul",
(
("Int64", "Int64", "Int64", "Int64"),
("float", "float", "float", "float"),
("Int64", "float", "Float64", "Float64"),
("Int64", "Float64", "Float64", "Float64"),
... | TestInplaceOperations |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/layout/processors.py | {
"start": 1641,
"end": 2255
} | class ____(metaclass=ABCMeta):
"""
Manipulate the fragments for a given line in a
:class:`~prompt_toolkit.layout.controls.BufferControl`.
"""
@abstractmethod
def apply_transformation(
self, transformation_input: TransformationInput
) -> Transformation:
"""
Apply tran... | Processor |
python | pytorch__pytorch | torch/ao/quantization/_learnable_fake_quantize.py | {
"start": 110,
"end": 7959
} | class ____(torch.ao.quantization.FakeQuantizeBase):
r"""Generalized extension of the FakeQuantize module in fake_quantize.py.
This is an extension of the FakeQuantize module in fake_quantize.py, which
supports more generalized lower-bit quantization and supports learning of the scale
and zero point par... | _LearnableFakeQuantize |
python | huggingface__transformers | tests/models/patchtsmixer/test_modeling_patchtsmixer.py | {
"start": 18063,
"end": 20996
} | class ____(unittest.TestCase):
def test_pretrain_head(self):
model = PatchTSMixerForPretraining.from_pretrained("ibm/patchtsmixer-etth1-pretrain").to(torch_device)
batch = prepare_batch()
torch.manual_seed(0)
with torch.no_grad():
output = model(past_values=batch["past_v... | PatchTSMixerModelIntegrationTests |
python | numpy__numpy | numpy/ma/tests/test_subclassing.py | {
"start": 13507,
"end": 15150
} | class ____:
"""Quantity-like class that does not inherit from ndarray"""
def __init__(self, data, units):
self.magnitude = data
self.units = units
def __getattr__(self, attr):
return getattr(self.magnitude, attr)
def test_array_no_inheritance():
data_masked = np.ma.array([1, 2... | ArrayNoInheritance |
python | redis__redis-py | tests/test_credentials.py | {
"start": 22020,
"end": 22867
} | class ____:
@pytest.mark.parametrize(
"r_entra",
[
{
"cred_provider_class": EntraIdCredentialsProvider,
"single_connection_client": False,
},
{
"cred_provider_class": EntraIdCredentialsProvider,
"sing... | TestClusterEntraIdCredentialsProvider |
python | numba__numba | numba/tests/test_dictobject.py | {
"start": 28300,
"end": 29450
} | class ____(TestCase):
def check_good(self, fromty, toty):
_sentry_safe_cast(fromty, toty)
def check_bad(self, fromty, toty):
with self.assertRaises(TypingError) as raises:
_sentry_safe_cast(fromty, toty)
self.assertIn(
'cannot safely cast {fromty} to {toty}'.form... | TestDictTypeCasting |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/roots/mutation.py | {
"start": 7777,
"end": 8031
} | class ____(graphene.Interface):
"""Interface indicating that a run was terminated."""
run = graphene.Field(graphene.NonNull(GrapheneRun))
class Meta:
name = "TerminatePipelineExecutionSuccess"
| GrapheneTerminatePipelineExecutionSuccess |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_s3.py | {
"start": 16008,
"end": 16946
} | class ____:
def test_execute(self):
operator = S3ListOperator(
task_id="test-s3-list-operator",
bucket=BUCKET_NAME,
prefix="TEST",
delimiter=".csv",
)
operator.hook = mock.MagicMock()
operator.hook.list_keys.return_value = ["TEST1.csv",... | TestS3ListOperator |
python | sqlalchemy__sqlalchemy | test/orm/test_froms.py | {
"start": 35545,
"end": 39132
} | class ____(fixtures.MappedTest, AssertsCompiledSQL):
run_setup_mappers = "once"
@classmethod
def define_tables(cls, metadata):
Table(
"a",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
... | AddEntityEquivalenceTest |
python | viewflow__viewflow | viewflow/workflow/apps.py | {
"start": 91,
"end": 344
} | class ____(AppConfig):
"""Default application config."""
default_auto_field = "django.db.models.BigAutoField"
name = "viewflow.workflow"
label = "viewflow" # keep backward compatible with 1.x
verbose_name = _("Workflow")
| WorkflowConfig |
python | getsentry__sentry | src/sentry/api/endpoints/release_thresholds/release_threshold_status_index.py | {
"start": 3898,
"end": 22101
} | class ____(OrganizationReleasesBaseEndpoint):
owner: ApiOwner = ApiOwner.ENTERPRISE
publish_status = {
"GET": ApiPublishStatus.PUBLIC,
}
@extend_schema(
operation_id="Retrieve Statuses of Release Thresholds (Alpha)",
parameters=[GlobalParams.ORG_ID_OR_SLUG, ReleaseThresholdStatu... | ReleaseThresholdStatusIndexEndpoint |
python | pytorch__pytorch | torch/distributed/elastic/rendezvous/api.py | {
"start": 4400,
"end": 7806
} | class ____(ABC):
"""Main rendezvous interface.
Note:
Distributed Torch users normally **do not** need to implement their own
``RendezvousHandler``. An implementation based on C10d Store is already
provided, and is recommended for most users.
"""
@abstractmethod
def get_back... | RendezvousHandler |
python | pyinstaller__pyinstaller | bootloader/waflib/Task.py | {
"start": 19098,
"end": 27668
} | class ____(object):
def __init__(self, prev, next):
self.prev = prev
self.next = next
self.done = False
def get_hasrun(self):
for k in self.prev:
if not k.hasrun:
return NOT_RUN
return SUCCESS
hasrun = property(get_hasrun, None)
def set... | TaskGroup |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/processing_qwen2_5_omni.py | {
"start": 1530,
"end": 2213
} | class ____(ProcessingKwargs, total=False):
videos_kwargs: Qwen2_5_OmniVideosKwargs
_defaults = {
"text_kwargs": {
"padding": False,
"padding_side": "left",
},
"videos_kwargs": {
"seconds_per_chunk": 2.0,
"position_id_per_seconds": 25,
... | Qwen2_5OmniProcessorKwargs |
python | ansible__ansible | test/lib/ansible_test/_internal/util_common.py | {
"start": 2147,
"end": 2930
} | class ____:
"""A simple substitution template for shell scripts."""
def __init__(self, template: str) -> None:
self.template = template
def substitute(self, **kwargs: t.Union[str, list[str]]) -> str:
"""Return a string templated with the given arguments."""
kvp = dict((k, self.quot... | ShellScriptTemplate |
python | streamlit__streamlit | lib/streamlit/components/v2/bidi_component/serialization.py | {
"start": 6697,
"end": 9403
} | class ____:
"""Serialization and deserialization logic for a bidirectional component.
This class handles the conversion of component state between the frontend
(JSON strings) and the backend (Python objects).
The canonical shape is a flat mapping of state keys to values.
Parameters
----------... | BidiComponentSerde |
python | huggingface__transformers | src/transformers/models/seggpt/image_processing_seggpt.py | {
"start": 3143,
"end": 31072
} | class ____(BaseImageProcessor):
r"""
Constructs a SegGpt image processor.
Args:
do_resize (`bool`, *optional*, defaults to `True`):
Whether to resize the image's (height, width) dimensions to the specified `(size["height"],
size["width"])`. Can be overridden by the `do_resiz... | SegGptImageProcessor |
python | pandas-dev__pandas | pandas/tests/extension/list/array.py | {
"start": 793,
"end": 3973
} | class ____(ExtensionArray):
dtype = ListDtype()
__array_priority__ = 1000
def __init__(self, values, dtype=None, copy=False) -> None:
if not isinstance(values, np.ndarray):
raise TypeError("Need to pass a numpy array as values")
for val in values:
if not isinstance(v... | ListArray |
python | lepture__authlib | tests/flask/test_oauth1/oauth1_server.py | {
"start": 2227,
"end": 3141
} | class ____(TemporaryCredentialMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey("user.id", ondelete="CASCADE"))
user = db.relationship("User")
client_id = db.Column(db.String(48), index=True)
oauth_token = db.Column(db.String(84), unique=Tru... | TemporaryCredential |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 129685,
"end": 130564
} | class ____(GeneratedAirbyteSource):
@public
def __init__(self, name: str, api_key: str, start_date: str, interval: str):
"""Airbyte Source for Chartmogul.
Documentation can be found at https://docs.airbyte.com/integrations/sources/chartmogul
Args:
name (str): The name of th... | ChartmogulSource |
python | streamlit__streamlit | lib/streamlit/errors.py | {
"start": 3035,
"end": 3094
} | class ____(StreamlitAPIException):
pass
| DuplicateWidgetID |
python | Pylons__pyramid | src/pyramid/static.py | {
"start": 11395,
"end": 12265
} | class ____:
"""
An implementation of :class:`~pyramid.interfaces.ICacheBuster` which adds
a token for cache busting in the query string of an asset URL.
The optional ``param`` argument determines the name of the parameter added
to the query string and defaults to ``'x'``.
To use this class, su... | QueryStringCacheBuster |
python | palantir__python-language-server | pyls/config/source.py | {
"start": 138,
"end": 2481
} | class ____(object):
"""Base class for implementing a config source."""
def __init__(self, root_path):
self.root_path = root_path
self.is_windows = sys.platform == 'win32'
self.xdg_home = os.environ.get(
'XDG_CONFIG_HOME', os.path.expanduser('~/.config')
)
def us... | ConfigSource |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_X.py | {
"start": 2778,
"end": 4204
} | class ____(Benchmark):
r"""
Xin-She Yang 3 objective function.
This class defines the Xin-She Yang 3 [1]_ global optimization problem.
This is a multimodal minimization problem defined as follows:
.. math::
f_{\text{XinSheYang03}}(x) = e^{-\sum_{i=1}^{n} (x_i/\beta)^{2m}}
... | XinSheYang03 |
python | realpython__materials | python-unittest/vehicles.py | {
"start": 106,
"end": 249
} | class ____(Vehicle):
def __init__(self, make, model, max_speed):
super().__init__(make, model)
self.max_speed = max_speed
| Car |
python | plotly__plotly.py | plotly/graph_objs/volume/colorbar/_tickformatstop.py | {
"start": 233,
"end": 8509
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "volume.colorbar"
_path_str = "volume.colorbar.tickformatstop"
_valid_props = {"dtickrange", "enabled", "name", "templateitemname", "value"}
@property
def dtickrange(self):
"""
range [*min*, *max*], where "min", "max" - dti... | Tickformatstop |
python | cookiecutter__cookiecutter | cookiecutter/exceptions.py | {
"start": 361,
"end": 643
} | class ____(CookiecutterException):
"""
Exception for when a project's input dir is not templated.
The name of the input directory should always contain a string that is
rendered to something else, so that input_dir != output_dir.
"""
| NonTemplatedInputDirException |
python | anthropics__anthropic-sdk-python | src/anthropic/types/shared/error_response.py | {
"start": 256,
"end": 377
} | class ____(BaseModel):
error: ErrorObject
request_id: Optional[str] = None
type: Literal["error"]
| ErrorResponse |
python | ansible__ansible | test/lib/ansible_test/_internal/host_profiles.py | {
"start": 14981,
"end": 15338
} | class ____[THostConfig: HostConfig](HostProfile[THostConfig], metaclass=abc.ABCMeta):
"""Base class for profiles offering SSH connectivity."""
@abc.abstractmethod
def get_controller_target_connections(self) -> list[SshConnection]:
"""Return SSH connection(s) for accessing the host as a target from ... | SshTargetHostProfile |
python | sqlalchemy__sqlalchemy | examples/sharding/separate_tables.py | {
"start": 3354,
"end": 10852
} | class ____(Base):
__tablename__ = "_prefix__weather_reports"
id: Mapped[int] = mapped_column(primary_key=True)
location_id: Mapped[int] = mapped_column(
ForeignKey("_prefix__weather_locations.id")
)
temperature: Mapped[float]
report_time: Mapped[datetime.datetime] = mapped_column(
... | Report |
python | getsentry__sentry | tests/sentry/api/endpoints/test_admin_project_configs.py | {
"start": 248,
"end": 8722
} | class ____(APITestCase):
endpoint = "sentry-api-0-internal-project-config"
def setUp(self) -> None:
super().setUp()
self.owner = self.create_user(
email="example@example.com", is_superuser=False, is_staff=True, is_active=True
)
self.org = self.create_organization(own... | AdminRelayProjectConfigsEndpointTest |
python | encode__django-rest-framework | tests/schemas/test_coreapi.py | {
"start": 1582,
"end": 1640
} | class ____(serializers.Serializer):
pass
| EmptySerializer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.