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 | huggingface__transformers | tests/models/informer/test_modeling_informer.py | {
"start": 7699,
"end": 19398
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (InformerModel, InformerForPrediction) if is_torch_available() else ()
pipeline_model_mapping = {"feature-extraction": InformerModel} if is_torch_available() else {}
is_encoder_decoder = True
test_missing_keys = F... | InformerModelTest |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_storage_transfer_service.py | {
"start": 14572,
"end": 17515
} | class ____(GoogleCloudBaseOperator):
"""
Delete a transfer job.
This is a soft delete. After a transfer job is deleted, the job and all the transfer
executions are subject to garbage collection. Transfer jobs become eligible for garbage
collection 30 days after soft delete.
.. seealso::
... | CloudDataTransferServiceDeleteJobOperator |
python | getsentry__sentry | tests/sentry/preprod/size_analysis/test_size_analysis_tasks.py | {
"start": 22794,
"end": 26153
} | class ____(TestCase):
def setUp(self):
super().setUp()
self.organization = self.create_organization(owner=self.user)
self.project = self.create_project(organization=self.organization)
def _create_size_metrics(self, **kwargs):
"""Helper to create PreprodArtifactSizeMetrics."""
... | ManualSizeAnalysisComparisonTest |
python | zostera__django-bootstrap4 | src/bootstrap4/renderers.py | {
"start": 992,
"end": 2609
} | class ____:
"""A content renderer."""
def __init__(self, *args, **kwargs):
self.layout = kwargs.get("layout", "")
self.form_group_class = kwargs.get("form_group_class", FORM_GROUP_CLASS)
self.field_class = kwargs.get("field_class", "")
self.label_class = kwargs.get("label_class"... | BaseRenderer |
python | gevent__gevent | src/greentest/3.13/test_queue.py | {
"start": 22846,
"end": 23000
} | class ____(PriorityQueueTest, unittest.TestCase):
queue = c_queue
# A Queue subclass that can provoke failure at a moment's notice :)
| CPriorityQueueTest |
python | chroma-core__chroma | chromadb/utils/embedding_functions/schemas/bm25_tokenizer.py | {
"start": 4519,
"end": 5159
} | class ____:
def __init__(self, seed: int = 0) -> None:
try:
import mmh3
except ImportError:
raise ValueError(
"The murmurhash3 python package is not installed. Please install it with `pip install murmurhash3`"
)
self.hasher = mmh3.hash
... | Murmur3AbsHasher |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_properties06.py | {
"start": 315,
"end": 1769
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("properties06.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got... | TestCompareXLSXFiles |
python | numba__numba | numba/core/typing/cmathdecl.py | {
"start": 971,
"end": 1202
} | class ____(ConcreteTemplate):
# unary cmath.log()
cases = [signature(tp, tp) for tp in sorted(types.complex_domain)]
# binary cmath.log()
cases += [signature(tp, tp, tp) for tp in sorted(types.complex_domain)]
| Cmath_log |
python | run-llama__llama_index | llama-index-integrations/callbacks/llama-index-callbacks-openinference/llama_index/callbacks/openinference/base.py | {
"start": 4167,
"end": 9844
} | class ____(BaseCallbackHandler):
"""
Callback handler for storing generation data in OpenInference format.
OpenInference is an open standard for capturing and storing AI model
inferences. It enables production LLMapp servers to seamlessly integrate
with LLM observability solutions such as Arize and ... | OpenInferenceCallbackHandler |
python | openai__openai-python | src/openai/_base_client.py | {
"start": 47023,
"end": 64733
} | class ____(BaseClient[httpx.AsyncClient, AsyncStream[Any]]):
_client: httpx.AsyncClient
_default_stream_cls: type[AsyncStream[Any]] | None = None
def __init__(
self,
*,
version: str,
base_url: str | URL,
_strict_response_validation: bool,
max_retries: int = D... | AsyncAPIClient |
python | getsentry__sentry | tests/sentry/models/test_rule.py | {
"start": 70,
"end": 2603
} | class ____(TestCase):
def setUp(self) -> None:
self.action_uuid = str(uuid4())
self.action = {
"targetType": "IssueOwners",
"fallthroughType": "ActiveMembers",
"id": "sentry.mail.actions.NotifyEmailAction",
"targetIdentifier": "",
"uuid": s... | TestRule_GetRuleActionDetailsByUuid |
python | openai__gym | gym/error.py | {
"start": 4453,
"end": 4929
} | class ____(Exception):
"""Raised when `reset`, or `step` is called asynchronously (e.g. with `reset_async`, or `step_async` respectively), and `reset_async`, or `step_async` (respectively) is called again (without a complete call to `reset_wait`, or `step_wait` respectively)."""
def __init__(self, message: str... | AlreadyPendingCallError |
python | Farama-Foundation__Gymnasium | gymnasium/core.py | {
"start": 26706,
"end": 27979
} | class ____(Wrapper[ObsType, ActType, ObsType, ActType]):
"""Superclass of wrappers that can modify the returning reward from a step.
If you would like to apply a function to the reward that is returned by the base environment before
passing it to learning code, you can simply inherit from :class:`RewardWra... | RewardWrapper |
python | pennersr__django-allauth | allauth/socialaccount/providers/openid_connect/provider.py | {
"start": 1047,
"end": 4239
} | class ____(OAuth2Provider):
id = "openid_connect"
name = "OpenID Connect"
account_class = OpenIDConnectProviderAccount
oauth2_adapter_class = OpenIDConnectOAuth2Adapter
supports_token_authentication = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
se... | OpenIDConnectProvider |
python | pytorch__pytorch | test/dynamo/test_functions.py | {
"start": 118142,
"end": 118342
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.m = ModuleWithDefaultTensorArgsMethod()
def forward(self):
return self.m()
| WrapperModule |
python | donnemartin__interactive-coding-challenges | arrays_strings/fizz_buzz/test_fizz_buzz.py | {
"start": 18,
"end": 761
} | class ____(unittest.TestCase):
def test_fizz_buzz(self):
solution = Solution()
self.assertRaises(TypeError, solution.fizz_buzz, None)
self.assertRaises(ValueError, solution.fizz_buzz, 0)
expected = [
'1',
'2',
'Fizz',
'4',
... | TestFizzBuzz |
python | pytorch__pytorch | torch/cuda/graphs.py | {
"start": 7897,
"end": 28121
} | class ____:
r"""Context-manager that captures CUDA work into a :class:`torch.cuda.CUDAGraph` object for later replay.
See :ref:`CUDA Graphs <cuda-graph-semantics>` for a general introduction,
detailed use, and constraints.
Arguments:
cuda_graph (torch.cuda.CUDAGraph): Graph object used for cap... | graph |
python | ray-project__ray | doc/source/serve/doc_code/load_shedding.py | {
"start": 637,
"end": 1671
} | class ____:
async def do_request(self) -> int:
async with aiohttp.ClientSession("http://localhost:8000/") as session:
return (await session.get("/")).status
r = Requester.remote()
serve.run(SlowDeployment.bind())
# Send 4 requests first.
# 2 of these will be sent to the replica. These requests... | Requester |
python | getsentry__sentry | src/sentry/integrations/utils/atlassian_connect.py | {
"start": 571,
"end": 6175
} | class ____(Exception):
pass
def get_query_hash(
uri: str, method: str, query_params: Mapping[str, str | Sequence[str]] | None = None
) -> str:
# see
# https://developer.atlassian.com/static/connect/docs/latest/concepts/understanding-jwt.html#qsh
uri = uri.rstrip("/")
method = method.upper()
... | AtlassianConnectValidationError |
python | docker__docker-py | docker/types/services.py | {
"start": 32722,
"end": 33328
} | class ____(dict):
"""
Network attachment options for a service.
Args:
target (str): The target network for attachment.
Can be a network name or ID.
aliases (:py:class:`list`): A list of discoverable alternate names
for the service.
... | NetworkAttachmentConfig |
python | huggingface__transformers | src/transformers/models/kyutai_speech_to_text/modeling_kyutai_speech_to_text.py | {
"start": 37930,
"end": 50217
} | class ____(KyutaiSpeechToTextPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = KyutaiSpeechToTextEmbeddings(config)
self.layers = nn.ModuleList(
[
... | KyutaiSpeechToTextModel |
python | tensorflow__tensorflow | tensorflow/python/compiler/tensorrt/test/conv2d_test.py | {
"start": 3935,
"end": 4663
} | class ____(trt_test.TfTrtIntegrationTestBase):
"""Testing conversion of Conv2D (data_format=NCHW) in TF-TRT conversion."""
def GraphFn(self, inp):
np.random.seed(1234)
return build_graph(
inp=inp,
dtype=dtypes.float32,
num_filters=5,
data_format="channels_last",
kern... | Conv2DNHWCTest |
python | pytorch__pytorch | torch/utils/data/datapipes/datapipe.py | {
"start": 16416,
"end": 17117
} | class ____(_DataPipeSerializationWrapper, IterDataPipe):
def __init__(self, datapipe: IterDataPipe[_T_co]) -> None:
super().__init__(datapipe)
# pyrefly: ignore [invalid-type-var]
self._datapipe_iter: Iterator[_T_co] | None = None
def __iter__(self) -> "_IterDataPipeSerializationWrapper... | _IterDataPipeSerializationWrapper |
python | matplotlib__matplotlib | galleries/examples/widgets/annotated_cursor.py | {
"start": 877,
"end": 13331
} | class ____(Cursor):
"""
A crosshair cursor like `~matplotlib.widgets.Cursor` with a text showing \
the current coordinates.
For the cursor to remain responsive you must keep a reference to it.
The data of the axis specified as *dataaxis* must be in ascending
order. Otherwise, the `numpy.searchs... | AnnotatedCursor |
python | sphinx-doc__sphinx | sphinx/domains/__init__.py | {
"start": 1759,
"end": 12447
} | class ____:
"""A Domain is meant to be a group of "object" description directives for
objects of a similar nature, and corresponding roles to create references to
them. Examples would be Python modules, classes, functions etc., elements
of a templating language, Sphinx roles and directives, etc.
E... | Domain |
python | PrefectHQ__prefect | src/prefect/filesystems.py | {
"start": 18280,
"end": 21751
} | class ____(WritableFileSystem, WritableDeploymentStorage):
"""
Store data as a file on a SMB share.
Example:
Load stored SMB config:
```python
from prefect.filesystems import SMB
smb_block = SMB.load("BLOCK_NAME")
```
"""
_block_type_name = "SMB"
_logo_... | SMB |
python | pytorch__pytorch | torch/distributed/checkpoint/planner.py | {
"start": 10408,
"end": 16263
} | class ____:
"""
Abstract class defining the protocol used by load_state_dict to plan the load process.
LoadPlanner are stateful objects that can be used to customize the whole load process.
LoadPlanner acts as an access proxy to the state_dict, so any transformation done to it
will be visible to t... | LoadPlanner |
python | jupyterlab__jupyterlab | jupyterlab/handlers/error_handler.py | {
"start": 463,
"end": 831
} | class ____(ExtensionHandlerMixin, JupyterHandler):
def initialize(self, messages=None, name=None):
super().initialize(name=name)
self.messages = messages
@web.authenticated
@web.removeslash
def get(self):
msgs = [f"<h2>{msg}</h2>" for msg in self.messages]
self.write(TEM... | ErrorHandler |
python | pytorch__pytorch | test/test_cuda_multigpu.py | {
"start": 50725,
"end": 70835
} | class ____(TestCase):
def _test_broadcast(self, input):
if not TEST_MULTIGPU:
raise unittest.SkipTest("only one GPU detected")
# test regular
results = comm.broadcast(input, (0, 1))
for i, t in enumerate(results):
self.assertEqual(t.get_device(), i)
... | TestCudaComm |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linear_operator_test.py | {
"start": 2450,
"end": 3947
} | class ____(linalg.LinearOperator):
"""LinearOperator that wraps a [batch] matrix and implements matmul/solve."""
def __init__(self,
matrix,
is_non_singular=None,
is_self_adjoint=None,
is_positive_definite=None,
is_square=None):
paramete... | LinearOperatorMatmulSolve |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_unittest/test_assertions.py | {
"start": 1463,
"end": 6472
} | class ____(__TestCase):
def test_AlmostEqual(self):
self.assertAlmostEqual(1.00000001, 1.0)
self.assertNotAlmostEqual(1.0000001, 1.0)
self.assertRaises(self.failureException,
self.assertAlmostEqual, 1.0000001, 1.0)
self.assertRaises(self.failureException,
... | Test_Assertions |
python | ray-project__ray | python/ray/llm/_internal/serve/core/ingress/ingress.py | {
"start": 11006,
"end": 24443
} | class ____(DeploymentProtocol):
def __init__(
self,
llm_deployments: List[DeploymentHandle],
*,
_get_lora_model_metadata_func: Optional[
Callable[[str, LLMConfig], Awaitable[Dict[str, Any]]]
] = None,
):
self._default_serve_handles: Dict[str, Deploymen... | OpenAiIngress |
python | tensorflow__tensorflow | tensorflow/python/autograph/core/converter_test.py | {
"start": 1157,
"end": 1998
} | class ____(converter_testing.TestCase):
def test_to_ast(self):
opts = converter.ConversionOptions()
opts_ast = opts.to_ast()
template = '''
def f():
return opts_ast
'''
opts_packed = templates.replace(template, opts_ast=opts_ast)
reparsed, _, _ = loader.load_ast(opts_packed)
f... | ConversionOptionsTest |
python | run-llama__llama_index | llama-index-integrations/retrievers/llama-index-retrievers-tldw/llama_index/retrievers/tldw/base.py | {
"start": 969,
"end": 2887
} | class ____(BaseRetriever):
r"""
A retriever that searches for relevant video moments from the TL;DW collection.
Args:
api_key (str): The API key for authentication.
collection_id (str): The ID of the video collection to search within.
callback_manager (Optional[CallbackManager]): Op... | TldwRetriever |
python | ray-project__ray | python/ray/tune/tests/execution/utils.py | {
"start": 661,
"end": 933
} | class ____(FixedResourceManager):
def __init__(self, total_resources: Dict[str, float]):
self._allow_strict_pack = True
self._total_resources = total_resources
self._requested_resources = []
self._used_resources = []
| BudgetResourceManager |
python | apache__airflow | providers/qdrant/src/airflow/providers/qdrant/operators/qdrant.py | {
"start": 1348,
"end": 4122
} | class ____(BaseOperator):
"""
Upload points to a Qdrant collection.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:QdrantIngestOperator`
:param conn_id: The connection id to connect to a Qdrant instance.
:param collecti... | QdrantIngestOperator |
python | justquick__django-activity-stream | runtests/testapp/tests/test_drf.py | {
"start": 391,
"end": 908
} | class ____(BaseDRFTestCase):
def test_urls(self):
self._check_urls('actions', 'follows', 'groups', 'sites',
'players', 'nested-models', 'my-users')
def test_serializers(self):
models = (Group, MyUser, Player, Site, NestedModel)
self.assertSetEqual(serializers.... | DRFTestAppTests |
python | mlflow__mlflow | dev/set_matrix.py | {
"start": 26811,
"end": 28581
} | class ____(json.JSONEncoder):
def default(self, o):
if isinstance(o, MatrixItem):
return o.model_dump(exclude_none=True)
elif isinstance(o, Version):
return str(o)
return super().default(o)
def set_action_output(name, value):
with open(os.getenv("GITHUB_OUTPUT")... | CustomEncoder |
python | dask__dask | dask/dataframe/tseries/resample.py | {
"start": 5094,
"end": 5770
} | class ____(Blockwise):
_parameters = [
"frame",
"divisions_left",
"divisions_right",
"closed",
"rule",
"kwargs",
"how",
"fill_value",
"how_args",
"how_kwargs",
]
operation = staticmethod(_resample_series)
@functools.cached_... | ResampleAggregation |
python | doocs__leetcode | solution/0200-0299/0225.Implement Stack using Queues/Solution.py | {
"start": 0,
"end": 608
} | class ____:
def __init__(self):
self.q1 = deque()
self.q2 = deque()
def push(self, x: int) -> None:
self.q2.append(x)
while self.q1:
self.q2.append(self.q1.popleft())
self.q1, self.q2 = self.q2, self.q1
def pop(self) -> int:
return self.q1.poplef... | MyStack |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarTuple30.py | {
"start": 104,
"end": 208
} | class ____[*Ts]:
def __init__(self, *args: *Ts): ...
def method(self):
Child(self)
| Parent |
python | jazzband__prettytable | tests/test_prettytable.py | {
"start": 62222,
"end": 63599
} | class ____:
def test_fields_at_class_declaration(self) -> None:
table = PrettyTable(
field_names=CITY_DATA_HEADER,
fields=["City name", "Annual Rainfall"],
)
for row in CITY_DATA:
table.add_row(row)
assert (
"""+-----------+------------... | TestFields |
python | ray-project__ray | ci/ray_ci/linux_container.py | {
"start": 309,
"end": 3904
} | class ____(Container):
def __init__(
self,
docker_tag: str,
volumes: Optional[List[str]] = None,
envs: Optional[List[str]] = None,
python_version: Optional[str] = None,
tmp_filesystem: Optional[str] = None,
architecture: Optional[str] = None,
privilege... | LinuxContainer |
python | pytorch__pytorch | benchmarks/dynamo/common.py | {
"start": 2678,
"end": 23700
} | class ____(NamedTuple):
backend: str # aot_eager or inductor
training: bool
dynamic: bool = False
device: str = "cuda"
CI_SKIP_OPTIMIZER = {
# HF
"MobileBertForMaskedLM", # Stack issue in fx
}
try:
from .fb.common import INTERNAL_CI_SKIP_DYNAMIC_BATCH_ONLY
except ImportError:
INTERN... | CI |
python | tensorflow__tensorflow | tensorflow/dtensor/python/tests/input_util_test.py | {
"start": 19286,
"end": 21052
} | class ____(test_util.DTensorBaseTest):
@parameterized.parameters(
{
'mesh_dims': [(MESH_DIM_BATCH, 8)],
'layout_specs': [UNSHARDED],
'batch_dim': None,
'counts': [1],
}, {
'mesh_dims': [(MESH_DIM_BATCH, 8)],
'layout_specs': [MESH_DIM_BATCH],
... | InputUtilHelpersTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDictClosed3.py | {
"start": 274,
"end": 394
} | class ____(Parent1, extra_items=int | None):
pass
# This should generate an error because of a type mismatch.
| Child1_1 |
python | spyder-ide__spyder | spyder/plugins/completion/providers/languageserver/transport/main.py | {
"start": 2990,
"end": 3076
} | class ____(Exception):
"""Terminal exception descriptor."""
pass
| TerminateSignal |
python | pennersr__django-allauth | allauth/socialaccount/providers/trainingpeaks/views.py | {
"start": 228,
"end": 1896
} | class ____(OAuth2Adapter):
# https://github.com/TrainingPeaks/PartnersAPI/wiki/OAuth
provider_id = "trainingpeaks"
def get_settings(self):
"""Provider settings"""
return app_settings.PROVIDERS.get(self.provider_id, {})
def get_hostname(self):
"""Return hostname depending on san... | TrainingPeaksOAuth2Adapter |
python | eth-brownie__brownie | brownie/_cli/console.py | {
"start": 3942,
"end": 12150
} | class ____(code.InteractiveConsole):
# This value is used as the `input` arg when initializing `prompt_toolkit.PromptSession`.
# During testing there is a conflict with how pytest suppresses stdin/out, so stdin is
# replaced with `prompt_toolkit.input.defaults.create_pipe_input`
prompt_input = None
... | Console |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_sensors.py | {
"start": 25218,
"end": 27228
} | class ____(ReadonlyGraphQLContextTestMatrix):
def test_start_sensor_failure(self, graphql_context: WorkspaceRequestContext):
sensor_selector = infer_sensor_selector(
graphql_context, "always_no_config_sensor_with_tags_and_metadata"
)
result = execute_dagster_graphql(
... | TestReadonlySensorPermissions |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 4860,
"end": 6395
} | class ____(ASTBase):
def __init__(
self,
identOrOp: ASTIdentifier | ASTOperator,
templateArgs: ASTTemplateArgs | None,
) -> None:
self.identOrOp = identOrOp
self.templateArgs = templateArgs
def __eq__(self, other: object) -> bool:
if not isinstance(other, AST... | ASTNestedNameElement |
python | langchain-ai__langchain | libs/partners/openai/tests/unit_tests/chat_models/test_base.py | {
"start": 11607,
"end": 36379
} | class ____:
def __init__(self, chunk_list: list) -> None:
self.current_chunk = 0
self.chunk_list = chunk_list
self.chunk_num = len(chunk_list)
def __enter__(self) -> Self:
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc: Bas... | MockSyncContextManager |
python | getsentry__sentry | src/sentry/grouping/api.py | {
"start": 4887,
"end": 5088
} | class ____(ProjectGroupingConfigLoader):
"""The currently active grouping config"""
option_name = "sentry:grouping_config"
cache_prefix = "grouping-enhancements:"
| PrimaryGroupingConfigLoader |
python | charliermarsh__ruff | crates/ty_python_semantic/resources/corpus/73_class_generic_tuple_default.py | {
"start": 0,
"end": 43
} | class ____[*T = *tuple[int, str]]:
x: T
| Foo |
python | lepture__authlib | authlib/oauth2/rfc6749/requests.py | {
"start": 4705,
"end": 5095
} | class ____:
def __init__(self, method, uri, headers=None):
self.method = method
self.uri = uri
self.headers = headers or {}
self.payload = None
@property
def data(self):
deprecate(
"'request.data' is deprecated in favor of 'request.payload.data'",
... | JsonRequest |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 144341,
"end": 145322
} | class ____(TestCase):
def test_defaults(self):
self.assertEqual(mi.only([]), None)
self.assertEqual(mi.only([1]), 1)
self.assertRaises(ValueError, lambda: mi.only([1, 2]))
def test_custom_value(self):
self.assertEqual(mi.only([], default='!'), '!')
self.assertEqual(mi.on... | OnlyTests |
python | falconry__falcon | falcon/errors.py | {
"start": 85023,
"end": 87373
} | class ____(HTTPError):
"""508 Loop Detected.
The 508 (Loop Detected) status code indicates that the server
terminated an operation because it encountered an infinite loop while
processing a request with "Depth: infinity". This status indicates
that the entire operation failed.
(See also: RFC 5... | HTTPLoopDetected |
python | explosion__spaCy | spacy/lang/zh/__init__.py | {
"start": 917,
"end": 1303
} | class ____(str, Enum):
char = "char"
jieba = "jieba"
pkuseg = "pkuseg"
@classmethod
def values(cls):
return list(cls.__members__.keys())
def create_chinese_tokenizer(segmenter: Segmenter = Segmenter.char):
def chinese_tokenizer_factory(nlp):
return ChineseTokenizer(nlp.vocab, ... | Segmenter |
python | wandb__wandb | wandb/automations/_utils.py | {
"start": 2465,
"end": 4259
} | class ____(TriggeredActionConfig):
"""Prepares action configuration data for saving an automation."""
# NOTE: `QueueJobActionInput` for defining a Launch job is deprecated,
# so while it's allowed here to update EXISTING mutations, we don't
# currently expose it through the public API to create NEW aut... | InputActionConfig |
python | walkccc__LeetCode | solutions/345. Reverse Vowels of a String/345.py | {
"start": 0,
"end": 372
} | class ____:
def reverseVowels(self, s: str) -> str:
chars = list(s)
VOWELS = 'aeiouAEIOU'
l = 0
r = len(s) - 1
while l < r:
while l < r and chars[l] not in VOWELS:
l += 1
while l < r and chars[r] not in VOWELS:
r -= 1
chars[l], chars[r] = chars[r], chars[l]
... | Solution |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 394726,
"end": 396618
} | class ____(VegaLiteSchema):
"""
Feature schema wrapper.
A feature object which contains a geometry and associated properties.
https://tools.ietf.org/html/rfc7946#section-3.2
Parameters
----------
geometry : dict, :class:`Point`, :class:`Polygon`, :class:`Geometry`, :class:`LineString`, :cl... | Feature |
python | justquick__django-activity-stream | actstream/gfk.py | {
"start": 195,
"end": 478
} | class ____(Manager):
"""
A manager that returns a GFKQuerySet instead of a regular QuerySet.
"""
def get_query_set(self):
return GFKQuerySet(self.model)
get_queryset = get_query_set
def none(self):
return self.get_queryset().none()
| GFKManager |
python | huggingface__transformers | src/transformers/models/openai/modeling_openai.py | {
"start": 4421,
"end": 5286
} | class ____(nn.Module):
def __init__(self, n_positions, config, scale=False):
super().__init__()
nx = config.n_embd
self.attn = Attention(nx, n_positions, config, scale)
self.ln_1 = nn.LayerNorm(nx, eps=config.layer_norm_epsilon)
self.mlp = MLP(4 * nx, config)
self.ln_... | Block |
python | sympy__sympy | sympy/polys/matrices/ddm.py | {
"start": 2957,
"end": 32362
} | class ____(list):
"""Dense matrix based on polys domain elements
This is a list subclass and is a wrapper for a list of lists that supports
basic matrix arithmetic +, -, *, **.
"""
fmt = 'dense'
is_DFM = False
is_DDM = True
def __init__(self, rowslist, shape, domain):
if not (... | DDM |
python | psf__black | tests/data/cases/preview_long_strings__regression.py | {
"start": 39299,
"end": 45984
} | class ____:
async def foo(self):
msg = ""
for candidate in CANDIDATES:
msg += (
"**{candidate.object_type} {candidate.rev}**"
" - {candidate.description}\n"
)
temp_msg = (
f"{f'{humanize_number(pos)}.': <{pound_len+2}} "
f"{balance: <... | X |
python | ray-project__ray | python/ray/tune/tests/test_trial_scheduler.py | {
"start": 8188,
"end": 8370
} | class ____(_FutureTrainingResult):
def __init__(self, result):
self.result = result
def resolve(self, block: bool = True):
return self.result
| _FakeFutureResult |
python | ray-project__ray | python/ray/serve/tests/test_runtime_env.py | {
"start": 479,
"end": 1717
} | class ____:
def __call__(self, *args):
return open("hello").read()
handle = serve.run(Test.bind())
try:
handle.remote().result()
assert False, "Should not get here"
except FileNotFoundError:
pass
"""
run_string_as_driver(driver)
@pytest.mark.skipif(sys.platform == "win32", reason="Fail t... | Test |
python | huggingface__transformers | src/transformers/models/csm/processing_csm.py | {
"start": 1980,
"end": 16218
} | class ____(ProcessorMixin):
r"""
Constructs a Csm processor which wraps [`EncodecFeatureExtractor`] and
[`PretrainedTokenizerFast`] into a single processor that inherits both the audio feature extraction and
tokenizer functionalities. See the [`~CsmProcessor.__call__`] for more
information.
The ... | CsmProcessor |
python | great-expectations__great_expectations | great_expectations/checkpoint/checkpoint.py | {
"start": 18485,
"end": 20483
} | class ____(BaseModel):
"""
The result of running a Checkpoint.
Contains information about Expectation successes and failures from running
each Validation Definition in the Checkpoint.
"""
run_id: RunIdentifier
run_results: Dict[ValidationResultIdentifier, ExpectationSuiteValidationResult]
... | CheckpointResult |
python | coleifer__peewee | peewee.py | {
"start": 22073,
"end": 22248
} | class ____(Node):
def __init__(self, source):
self.source = source
def __sql__(self, ctx):
return ctx.sql(QualifiedNames(self.source)).literal('.*')
| Star |
python | celery__celery | celery/local.py | {
"start": 1360,
"end": 8056
} | class ____:
"""Proxy to another object."""
# Code stolen from werkzeug.local.Proxy.
__slots__ = ('__local', '__args', '__kwargs', '__dict__')
def __init__(self, local,
args=None, kwargs=None, name=None, __doc__=None):
object.__setattr__(self, '_Proxy__local', local)
ob... | Proxy |
python | apache__avro | lang/py/avro/test/test_schema.py | {
"start": 39104,
"end": 41094
} | class ____(unittest.TestCase):
"""Enable generating attribute test cases over all the other-prop test schema."""
_type_map = {
"cp_array": list,
"cp_boolean": bool,
"cp_float": float,
"cp_int": int,
"cp_null": type(None),
"cp_object": dict,
"cp_string": s... | OtherAttributesTestCase |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 162943,
"end": 164095
} | class ____(ExprNode):
# Base class for indexing nodes.
#
# base ExprNode the value being indexed
def is_ephemeral(self):
# in most cases, indexing will return a safe reference to an object in a container,
# so we consider the result safe if the base object is
return self.bas... | _IndexingBaseNode |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py | {
"start": 1472,
"end": 1678
} | class ____(IncrementalShopifyStreamWithDeletedEvents):
data_field = "articles"
cursor_field = "id"
order_field = "id"
filter_field = "since_id"
deleted_events_api_name = "Article"
| Articles |
python | scrapy__scrapy | tests/test_utils_log.py | {
"start": 4771,
"end": 6593
} | class ____:
@pytest.fixture
def log_stream(self) -> StringIO:
return StringIO()
@pytest.fixture
def spider(self) -> LogSpider:
return LogSpider()
@pytest.fixture(autouse=True)
def logger(self, log_stream: StringIO) -> Generator[logging.Logger]:
handler = logging.StreamH... | TestLogging |
python | fastapi__sqlmodel | docs_src/tutorial/fastapi/delete/tutorial001.py | {
"start": 475,
"end": 2609
} | class ____(SQLModel):
name: Optional[str] = None
secret_name: Optional[str] = None
age: Optional[int] = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
connect_args = {"check_same_thread": False}
engine = create_engine(sqlite_url, echo=True, connect_args=connect_args)
... | HeroUpdate |
python | run-llama__llama_index | llama-index-integrations/voice_agents/llama-index-voice-agents-gemini-live/llama_index/voice_agents/gemini_live/events.py | {
"start": 219,
"end": 277
} | class ____(BaseVoiceAgentEvent):
text: str
| TextSentEvent |
python | sqlalchemy__sqlalchemy | test/orm/test_assorted_eager.py | {
"start": 22574,
"end": 26123
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"design_types",
metadata,
Column(
"design_type_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
... | EagerTest6 |
python | django__django | django/db/migrations/executor.py | {
"start": 250,
"end": 19029
} | class ____:
"""
End-to-end migration execution - load migrations and run them up or down
to a specified set of targets.
"""
def __init__(self, connection, progress_callback=None):
self.connection = connection
self.loader = MigrationLoader(self.connection)
self.recorder = Mig... | MigrationExecutor |
python | Textualize__textual | tests/test_binding_inheritance.py | {
"start": 7961,
"end": 9238
} | class ____(AppKeyRecorder):
"""An application with bindings."""
BINDINGS = AppKeyRecorder.make_bindings()
async def test_pressing_alpha_on_app() -> None:
"""Test that pressing the alpha key, when it's bound on the app, results in an action fire."""
async with AppWithMovementKeysBound().run_test() as ... | AppWithMovementKeysBound |
python | Lightning-AI__lightning | src/lightning/fabric/strategies/single_xla.py | {
"start": 1101,
"end": 3250
} | class ____(SingleDeviceStrategy):
"""Strategy for training on a single XLA device."""
def __init__(
self,
device: _DEVICE,
accelerator: Optional[Accelerator] = None,
checkpoint_io: Optional[XLACheckpointIO] = None,
precision: Optional[XLAPrecision] = None,
):
... | SingleDeviceXLAStrategy |
python | tensorflow__tensorflow | tensorflow/python/saved_model/model_utils/mode_keys.py | {
"start": 1200,
"end": 1765
} | class ____(object):
"""Standard names for Estimator model modes.
The following standard keys are defined:
* `TRAIN`: training/fitting mode.
* `EVAL`: testing/evaluation mode.
* `PREDICT`: predication/inference mode.
"""
TRAIN = 'train'
EVAL = 'eval'
PREDICT = 'infer'
def is_predict(mode):
retur... | EstimatorModeKeys |
python | huggingface__transformers | src/transformers/models/rt_detr_v2/modeling_rt_detr_v2.py | {
"start": 38203,
"end": 40524
} | class ____(nn.Module):
"""
BatchNorm2d where the batch statistics and the affine parameters are fixed.
Copy-paste from torchvision.misc.ops with added eps before rqsrt, without which any other models than
torchvision.models.resnet[18,34,50,101] produce nans.
"""
def __init__(self, n):
... | RTDetrV2FrozenBatchNorm2d |
python | encode__django-rest-framework | tests/test_generics.py | {
"start": 705,
"end": 889
} | class ____(RESTFrameworkModel):
email = models.EmailField()
content = models.CharField(max_length=200)
created = models.DateTimeField(auto_now_add=True)
# Serializers
| Comment |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 375619,
"end": 376194
} | class ____:
def test_empty_ustring_array_is_falsey(self):
assert_(not np.array([''], dtype=np.str_))
def test_whitespace_ustring_array_is_truthy(self):
a = np.array(['eggs'], dtype=np.str_)
a[0] = ' \0\0'
assert_(a)
def test_all_null_ustring_array_is_falsey(self):
... | TestUnicodeArrayNonzero |
python | plotly__plotly.py | plotly/graph_objs/scattersmith/_unselected.py | {
"start": 233,
"end": 3419
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattersmith"
_path_str = "scattersmith.unselected"
_valid_props = {"marker", "textfont"}
@property
def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance... | Unselected |
python | pytorch__pytorch | test/dynamo/test_callback.py | {
"start": 517,
"end": 5770
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self._on_compile_start = Mock()
self._on_compile_end = Mock()
callback_handler.register_start_callback(self._on_compile_start)
callback_handler.register_end_callback(self._on_compile_end)
def tearDown(self) -... | CallbackTests |
python | spack__spack | lib/spack/spack/vendor/jinja2/nodes.py | {
"start": 20227,
"end": 20581
} | class ____(Helper):
"""A key, value pair for dicts."""
fields = ("key", "value")
key: Expr
value: Expr
def as_const(
self, eval_ctx: t.Optional[EvalContext] = None
) -> t.Tuple[t.Any, t.Any]:
eval_ctx = get_eval_context(self, eval_ctx)
return self.key.as_const(eval_ctx)... | Pair |
python | simonw__sqlite-utils | sqlite_utils/db.py | {
"start": 4039,
"end": 4302
} | class ____(Exception):
pass
ForeignKeyIndicator = Union[
str,
ForeignKey,
Tuple[str, str],
Tuple[str, str, str],
Tuple[str, str, str, str],
]
ForeignKeysType = Union[Iterable[ForeignKeyIndicator], List[ForeignKeyIndicator]]
| TransformError |
python | django__django | tests/queryset_pickle/models.py | {
"start": 1958,
"end": 2057
} | class ____(Event):
class Meta:
abstract = True
ordering = ["title"]
| AbstractEvent |
python | encode__django-rest-framework | rest_framework/exceptions.py | {
"start": 2752,
"end": 4085
} | class ____(Exception):
"""
Base class for REST framework exceptions.
Subclasses should provide `.status_code` and `.default_detail` properties.
"""
status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
default_detail = _('A server error occurred.')
default_code = 'error'
def __init__(self... | APIException |
python | walkccc__LeetCode | solutions/2122. Recover the Original Array/2122.py | {
"start": 0,
"end": 633
} | class ____:
def recoverArray(self, nums: list[int]) -> list[int]:
nums = sorted(nums)
def getArray(x: int, count: collections.Counter) -> list[int]:
arr = []
for num in nums:
if count[num] == 0:
continue
if count[num + x] == 0:
return []
count[num] -= 1... | Solution |
python | plotly__plotly.py | plotly/graph_objs/heatmap/legendgrouptitle/_font.py | {
"start": 233,
"end": 9927
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "heatmap.legendgrouptitle"
_path_str = "heatmap.legendgrouptitle.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight... | Font |
python | django__django | tests/admin_views/tests.py | {
"start": 90128,
"end": 145291
} | class ____(TestCase):
"""Tests for Admin Views Permissions."""
@classmethod
def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(
username="super", password="secret", email="super@example.com"
)
cls.viewuser = User.objects.create_user(
userna... | AdminViewPermissionsTest |
python | milvus-io__pymilvus | pymilvus/bulk_writer/remote_bulk_writer.py | {
"start": 1138,
"end": 13652
} | class ____(LocalBulkWriter):
class S3ConnectParam:
def __init__(
self,
bucket_name: str = DEFAULT_BUCKET_NAME,
endpoint: Optional[str] = None,
access_key: Optional[str] = None,
secret_key: Optional[str] = None,
secure: bool = False,
... | RemoteBulkWriter |
python | joke2k__faker | faker/providers/job/de_DE/__init__.py | {
"start": 42,
"end": 952
} | class ____(BaseProvider):
"""
Source: http://planet-beruf.de/schuelerinnen/mein-beruf/berufe-von-a-z/
"""
jobs = [
"Altenpfleger",
"Asphaltbauer",
"Artist",
"Augenoptiker",
"Ausbaufacharbeiter",
"Bäcker",
"Bankkaufmann",
"Beamter",
... | Provider |
python | MongoEngine__mongoengine | mongoengine/fields.py | {
"start": 77300,
"end": 78256
} | class ____(BaseField):
"""A list storing a longitude and latitude coordinate.
.. note:: this represents a generic point in a 2D plane and a legacy way of
representing a geo point. It admits 2d indexes but not "2dsphere" indexes
in MongoDB > 2.4 which are more natural for modeling geospatial poi... | GeoPointField |
python | google__jax | jax/experimental/pallas/ops/gpu/hopper_matmul_mgpu.py | {
"start": 1034,
"end": 1212
} | class ____(enum.IntEnum):
M = 0
N = 1
def __str__(self):
return self.name
def __repr__(self):
return self.name
@dataclasses.dataclass(frozen=True)
| MatmulDimension |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/class_interval.py | {
"start": 5193,
"end": 5298
} | class ____:
def f(self):
return self.g()
@abstractmethod
def g(self):
pass
| A13 |
python | docker__docker-py | docker/utils/proxy.py | {
"start": 40,
"end": 2246
} | class ____(dict):
'''
Hold the client's proxy configuration
'''
@property
def http(self):
return self.get('http')
@property
def https(self):
return self.get('https')
@property
def ftp(self):
return self.get('ftp')
@property
def no_proxy(self):
... | ProxyConfig |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.