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 | vyperlang__vyper | vyper/ast/nodes.py | {
"start": 25210,
"end": 25381
} | class ____(Num):
"""
An integer.
Attributes
----------
value : int
Value of the node, represented as an integer.
"""
__slots__ = ()
| Int |
python | gevent__gevent | src/gevent/tests/test__event.py | {
"start": 10738,
"end": 11028
} | class ____(greentest.TestCase):
N = 1
def test(self):
e = Event()
waiters = [gevent.spawn(e.wait) for i in range(self.N)]
gevent.sleep(0.001)
e.set()
e.clear()
for greenlet in waiters:
greenlet.join()
| TestEvent_SetThenClear |
python | pyqtgraph__pyqtgraph | pyqtgraph/multiprocess/remoteproxy.py | {
"start": 28094,
"end": 30228
} | class ____(object):
"""
Request objects are returned when calling an ObjectProxy in asynchronous mode
or if a synchronous call has timed out. Use hasResult() to ask whether
the result of the call has been returned yet. Use result() to get
the returned value.
"""
def __init__(self, process, r... | Request |
python | matplotlib__matplotlib | lib/matplotlib/units.py | {
"start": 2366,
"end": 3480
} | class ____:
"""
Information to support default axis labeling, tick labeling, and limits.
An instance of this class must be returned by
`ConversionInterface.axisinfo`.
"""
def __init__(self, majloc=None, minloc=None,
majfmt=None, minfmt=None, label=None,
default... | AxisInfo |
python | huggingface__transformers | src/transformers/models/glm46v/image_processing_glm46v.py | {
"start": 1856,
"end": 3693
} | class ____(ImagesKwargs, total=False):
"""
patch_size (`int`, *optional*, defaults to 14):
The spatial patch size of the vision encoder.
temporal_patch_size (`int`, *optional*, defaults to 2):
The temporal patch size of the vision encoder.
merge_size (`int`, *optional*, defaults to 2):
... | Glm46VImageProcessorKwargs |
python | jazzband__django-oauth-toolkit | oauth2_provider/models.py | {
"start": 1032,
"end": 1866
} | class ____(models.CharField):
def pre_save(self, model_instance, add):
secret = getattr(model_instance, self.attname)
should_be_hashed = getattr(model_instance, "hash_client_secret", True)
if not should_be_hashed:
return super().pre_save(model_instance, add)
try:
... | ClientSecretField |
python | etianen__django-reversion | tests/test_app/tests/test_models.py | {
"start": 13713,
"end": 14413
} | class ____(TestModelMixin, TestBase):
def testRevert(self):
with reversion.create_revision():
obj_1 = TestModel.objects.create(
name="obj_1 v1"
)
obj_2 = TestModel.objects.create(
name="obj_2 v1"
)
with reversion.create... | RevisionRevertTest |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-solr/llama_index/vector_stores/solr/client/_base.py | {
"start": 163,
"end": 1911
} | class ____:
"""Base Solr client for shared functionality."""
def __init__(
self,
base_url: str,
request_timeout_sec: int = SolrConstants.DEFAULT_TIMEOUT_SEC,
headers: Optional[dict[str, str]] = None,
**client_kwargs: Any,
) -> None:
"""
Initialize the... | _BaseSolrClient |
python | dagster-io__dagster | python_modules/libraries/dagster-k8s/dagster_k8s/client.py | {
"start": 902,
"end": 983
} | class ____(Enum):
Ready = "READY"
Terminated = "TERMINATED"
| WaitForPodState |
python | scikit-learn__scikit-learn | sklearn/linear_model/_stochastic_gradient.py | {
"start": 61783,
"end": 75040
} | class ____(BaseSGDRegressor):
"""Linear model fitted by minimizing a regularized empirical loss with SGD.
SGD stands for Stochastic Gradient Descent: the gradient of the loss is
estimated each sample at a time and the model is updated along the way with
a decreasing strength schedule (aka learning rate... | SGDRegressor |
python | huggingface__transformers | src/transformers/models/aya_vision/modeling_aya_vision.py | {
"start": 14914,
"end": 21802
} | class ____(AyaVisionPreTrainedModel, GenerationMixin):
_checkpoint_conversion_mapping = {
r"^language_model.model": "model.language_model",
r"^vision_tower": "model.vision_tower",
r"^multi_modal_projector": "model.multi_modal_projector",
r"^language_model.lm_head": "lm_head",
}
... | AyaVisionForConditionalGeneration |
python | apache__airflow | airflow-core/src/airflow/utils/log/log_reader.py | {
"start": 1781,
"end": 8320
} | class ____:
"""Task log reader."""
STREAM_LOOP_SLEEP_SECONDS = 1
"""Time to sleep between loops while waiting for more logs"""
STREAM_LOOP_STOP_AFTER_EMPTY_ITERATIONS = 10
"""Number of empty loop iterations before stopping the stream"""
@staticmethod
def get_no_log_state_message(ti: TaskI... | TaskLogReader |
python | donnemartin__interactive-coding-challenges | sorting_searching/selection_sort/test_selection_sort.py | {
"start": 18,
"end": 932
} | class ____(unittest.TestCase):
def test_selection_sort(self, func):
print('None input')
self.assertRaises(TypeError, func, None)
print('Empty input')
self.assertEqual(func([]), [])
print('One element')
self.assertEqual(func([5]), [5])
print('Two or more el... | TestSelectionSort |
python | pandas-dev__pandas | pandas/util/version/__init__.py | {
"start": 611,
"end": 1227
} | class ____:
def __repr__(self) -> str:
return "Infinity"
def __hash__(self) -> int:
return hash(repr(self))
def __lt__(self, other: object) -> bool:
return False
def __le__(self, other: object) -> bool:
return False
def __eq__(self, other: object) -> bool:
... | InfinityType |
python | google__jax | tests/shard_map_test.py | {
"start": 2413,
"end": 158053
} | class ____(jtu.JaxTestCase):
def test_identity(self):
mesh, a, _ = create_inputs(P('z', ('x', 'y')), P(None, None))
assert a.addressable_data(0).shape == (4, 2)
def identity(x):
return x
@jax.jit
def fwd(a):
c = shard_map(
identity,
mesh=mesh,
in_specs=... | ShardMapTest |
python | ansible__ansible | lib/ansible/modules/hostname.py | {
"start": 26407,
"end": 26525
} | class ____(Hostname):
platform = 'Darwin'
distribution = None
strategy_class = DarwinStrategy
| DarwinHostname |
python | streamlit__streamlit | e2e_playwright/shared/data_mocks.py | {
"start": 898,
"end": 7168
} | class ____(NamedTuple):
expected_rows: int
expected_cols: int
expected_data_format: DataFormat
SHARED_TEST_CASES = [
# None:
(None, CaseMetadata(0, 0, DataFormat.EMPTY)),
# Empty list:
([], CaseMetadata(0, 0, DataFormat.LIST_OF_VALUES)),
# Empty tuple:
((), CaseMetadata(0, 0, DataF... | CaseMetadata |
python | astropy__astropy | astropy/modeling/tests/test_fitting_parallel.py | {
"start": 5267,
"end": 12282
} | class ____:
def test_no_world(self):
# This also doubles as a test when there are no iterating dimensions
data = gaussian(np.arange(20), 2, 10, 1)
model = Gaussian1D(amplitude=1.5, mean=12, stddev=1.5)
fitter = LevMarLSQFitter()
model_fit = parallel_fit_dask(
data... | TestWorld |
python | mozilla__bleach | bleach/_vendor/html5lib/_tokenizer.py | {
"start": 639,
"end": 77040
} | class ____(object):
""" This class takes care of tokenizing HTML.
* self.currentToken
Holds the token that is currently being processed.
* self.state
Holds a reference to the method to be invoked... XXX
* self.stream
Points to HTMLInputStream object.
"""
def __init__(self, ... | HTMLTokenizer |
python | kubernetes-client__python | kubernetes/client/models/v1_device_attribute.py | {
"start": 383,
"end": 5816
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1DeviceAttribute |
python | pypa__setuptools | setuptools/tests/test_build_ext.py | {
"start": 6669,
"end": 10099
} | class ____:
def get_build_ext_cmd(self, optional: bool, **opts) -> build_ext:
files: dict[str, str | dict[str, dict[str, str]]] = {
"eggs.c": "#include missingheader.h\n",
".build": {"lib": {}, "tmp": {}},
}
path.build(files)
extension = Extension('spam.eggs',... | TestBuildExtInplace |
python | ipython__ipython | tests/test_guarded_eval.py | {
"start": 8134,
"end": 8188
} | class ____(TypedDict):
name: str
year: int
| Movie |
python | streamlit__streamlit | lib/streamlit/web/server/app_static_file_handler.py | {
"start": 1504,
"end": 3224
} | class ____(tornado.web.StaticFileHandler):
def initialize(self, path: str, default_filename: str | None = None) -> None:
super().initialize(path, default_filename)
def validate_absolute_path(self, root: str, absolute_path: str) -> str | None:
full_path = os.path.abspath(absolute_path)
... | AppStaticFileHandler |
python | django-haystack__django-haystack | test_haystack/elasticsearch_tests/test_elasticsearch_backend.py | {
"start": 7997,
"end": 25386
} | class ____(TestCase):
def setUp(self):
super().setUp()
# Wipe it clean.
self.raw_es = elasticsearch.Elasticsearch(
settings.HAYSTACK_CONNECTIONS["elasticsearch"]["URL"]
)
clear_elasticsearch_index()
# Stow.
self.old_ui = connections["elasticsearc... | ElasticsearchSearchBackendTestCase |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/managed_kafka.py | {
"start": 12042,
"end": 14663
} | class ____(ManagedKafkaBaseOperator):
"""
Get an Apache Kafka cluster.
:param project_id: Required. The ID of the Google Cloud project that the service belongs to.
:param location: Required. The ID of the Google Cloud region that the service belongs to.
:param cluster_id: Required. The ID of the cl... | ManagedKafkaGetClusterOperator |
python | anthropics__anthropic-sdk-python | src/anthropic/types/raw_content_block_delta_event.py | {
"start": 259,
"end": 393
} | class ____(BaseModel):
delta: RawContentBlockDelta
index: int
type: Literal["content_block_delta"]
| RawContentBlockDeltaEvent |
python | google__jax | jax/_src/source_info_util.py | {
"start": 6399,
"end": 6784
} | class ____(threading.local):
context: SourceInfo
def __init__(self):
self.context = new_source_info()
_source_info_context = _SourceInfoContext()
def current() -> SourceInfo:
source_info = _source_info_context.context
if not source_info.traceback:
source_info = source_info.replace(traceback=xla_clien... | _SourceInfoContext |
python | huggingface__transformers | src/transformers/models/xlnet/modeling_xlnet.py | {
"start": 10004,
"end": 10875
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.layer_norm = nn.LayerNorm(config.d_model, eps=config.layer_norm_eps)
self.layer_1 = nn.Linear(config.d_model, config.d_inner)
self.layer_2 = nn.Linear(config.d_inner, config.d_model)
self.dropout = nn.... | XLNetFeedForward |
python | tensorflow__tensorflow | tensorflow/python/keras/saving/saved_model/serialized_attributes.py | {
"start": 12538,
"end": 12862
} | class ____(
SerializedAttributes.with_attributes(
'MetricAttributes',
checkpointable_objects=['variables'],
functions=[],
)):
"""Attributes that are added to Metric objects when saved to SavedModel.
List of all attributes:
variables: list of all variables
"""
pass
| MetricAttributes |
python | getsentry__sentry | tests/sentry/issues/auto_source_code_config/test_process_event.py | {
"start": 12535,
"end": 17650
} | class ____(BaseDeriveCodeMappings):
"""Behaviour that is not specific to a language."""
def test_skips_not_supported_platforms(self) -> None:
with patch(f"{CODE_ROOT}.utils.platform.get_platform_config", return_value={}):
self._process_and_assert_configuration_changes(
repo_... | TestGenericBehaviour |
python | huggingface__transformers | src/transformers/models/voxtral/processing_voxtral.py | {
"start": 1956,
"end": 20004
} | class ____(ProcessorMixin):
r"""
Constructs a Voxtral processor which wraps [`WhisperFeatureExtractor`] and
[`MistralCommonBackend`] into a single processor that inherits both the audio feature extraction and
tokenizer functionalities.
Args:
feature_extractor ([`WhisperFeatureExtractor`]):
... | VoxtralProcessor |
python | facebook__pyre-check | client/configuration/search_path.py | {
"start": 840,
"end": 1094
} | class ____(abc.ABC):
@abc.abstractmethod
def path(self) -> str:
raise NotImplementedError()
@abc.abstractmethod
def command_line_argument(self) -> str:
raise NotImplementedError()
@dataclasses.dataclass(frozen=True)
| Element |
python | pypa__setuptools | setuptools/_distutils/command/install.py | {
"start": 4860,
"end": 30072
} | class ____(Command):
description = "install everything from build directory"
user_options = [
# Select installation scheme and set base director(y|ies)
('prefix=', None, "installation prefix"),
('exec-prefix=', None, "(Unix only) prefix for platform-specific files"),
('home=', N... | install |
python | sphinx-doc__sphinx | sphinx/builders/xml.py | {
"start": 550,
"end": 3335
} | class ____(Builder):
"""Builds Docutils-native XML."""
name = 'xml'
format = 'xml'
epilog = __('The XML files are in %(outdir)s.')
out_suffix = '.xml'
allow_parallel = True
default_translator_class = XMLTranslator
def init(self) -> None:
pass
def get_outdated_docs(self) ... | XMLBuilder |
python | arrow-py__arrow | tests/test_parser.py | {
"start": 53299,
"end": 54576
} | class ____:
def test_shortmonth_capitalized(self):
assert self.parser.parse("2013-Jan-01", "YYYY-MMM-DD") == datetime(2013, 1, 1)
def test_shortmonth_allupper(self):
assert self.parser.parse("2013-JAN-01", "YYYY-MMM-DD") == datetime(2013, 1, 1)
def test_shortmonth_alllower(self):
a... | TestDateTimeParserMonthName |
python | skorch-dev__skorch | skorch/tests/test_probabilistic.py | {
"start": 19744,
"end": 21599
} | class ____(BaseProbabilisticTests):
"""Tests for GPRegressor."""
##########################
# constants and fixtures #
##########################
n_samples = 60
n_targets = 1
supports_predict_proba = False
supports_return_std = True
supports_return_cov = True
settable_params = ... | TestGPRegressorVariational |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-bedrock/tests/test_bedrock_async.py | {
"start": 447,
"end": 761
} | class ____:
async def __aenter__(self) -> "AsyncMockClient":
return self
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
pass
async def invoke_model(self, *args, **kwargs):
return {"contentType": "application/json", "body": AsyncMockStreamReader()}
| AsyncMockClient |
python | scrapy__scrapy | tests/test_utils_datatypes.py | {
"start": 6833,
"end": 8353
} | class ____:
def test_list(self):
seq = [1, 2, 3]
d = SequenceExclude(seq)
assert 0 in d
assert 4 in d
assert 2 not in d
def test_range(self):
seq = range(10, 20)
d = SequenceExclude(seq)
assert 5 in d
assert 20 in d
assert 15 not i... | TestSequenceExclude |
python | allegroai__clearml | clearml/utilities/plotlympl/mplexporter/renderers/vincent_renderer.py | {
"start": 191,
"end": 2227
} | class ____(Renderer):
def open_figure(self, fig: Any, props: Dict[str, Union[int, float]]) -> None:
self.chart = None
self.figwidth = int(props["figwidth"] * props["dpi"])
self.figheight = int(props["figheight"] * props["dpi"])
def draw_line(
self,
data: numpy.ndarray,
... | VincentRenderer |
python | PyCQA__pylint | tests/functional/g/generic_alias/generic_alias_related.py | {
"start": 720,
"end": 1072
} | class ____(typing.List):
pass
ClsUnsubscriptable()[1] # [unsubscriptable-object]
ClsUnsubscriptable[int] # [unsubscriptable-object]
ClsGetItem()[1]
ClsGetItem[int] # [unsubscriptable-object]
ClsClassGetItem()[1] # [unsubscriptable-object]
ClsClassGetItem[int]
# subscriptable because of inheritance
ClsList(... | ClsList |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/overloadOverride1.py | {
"start": 796,
"end": 1145
} | class ____(Base3):
@overload
def foo(self, x: float) -> float: ...
@overload
def foo(self, x: str) -> str: ...
# This should generate an error because no overloaded signature
# is compatible with the base method, nor is the implementation.
def foo(self, x: int | str | float) -> int | str |... | Derived3 |
python | pytorch__pytorch | torch/distributed/checkpoint/filesystem.py | {
"start": 3299,
"end": 6704
} | class ____(_TensorLoader):
def __init__(
self,
resolve_fun: Callable,
stream: Optional[torch.Stream] = None,
inflight_threshhold: int = 1_000_000,
) -> None:
self.resolve_fun = resolve_fun
self.items: list[tuple[int, object]] = []
self.inflight_threshhold ... | _OverlappingCpuLoader |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/django/toystore/models.py | {
"start": 1769,
"end": 1871
} | class ____(models.Model):
b = models.ForeignKey("LoopB", null=False, on_delete=models.CASCADE)
| LoopA |
python | django__django | tests/auth_tests/operations_migrations/0001_initial.py | {
"start": 43,
"end": 295
} | class ____(migrations.Migration):
initial = True
operations = [
migrations.CreateModel(
name="OldModel",
fields=[
("id", models.AutoField(primary_key=True)),
],
),
]
| Migration |
python | scipy__scipy | benchmarks/benchmarks/stats.py | {
"start": 19061,
"end": 22639
} | class ____(Benchmark):
# list of distributions to time
dists = ["pareto", "laplace", "rayleigh", "invgauss", "gumbel_r",
"gumbel_l", "powerlaw", "lognorm"]
# add custom values for rvs and fit, if desired, for any distribution:
# key should match name in dists and value should be list of loc... | ContinuousFitAnalyticalMLEOverride |
python | getsentry__sentry | src/sentry/api/serializers/rest_framework/commit.py | {
"start": 102,
"end": 468
} | class ____(serializers.Serializer):
path = serializers.CharField(max_length=510)
type = serializers.CharField(max_length=1)
def validate_type(self, value):
if not CommitFileChange.is_valid_type(value):
raise serializers.ValidationError("Commit patch_set type %s is not supported." % valu... | CommitPatchSetSerializer |
python | jazzband__django-simple-history | simple_history/tests/tests/test_manager.py | {
"start": 4033,
"end": 9692
} | class ____(TestCase):
def test_create_and_delete(self):
document = Document.objects.create()
now = datetime.now()
document.delete()
docs_as_of_now = Document.history.as_of(now)
doc = docs_as_of_now[0]
# as_of queries inject a property allowing callers
# to go... | AsOfTestCaseWithoutSetUp |
python | run-llama__llama_index | llama-index-core/llama_index/core/agent/react/formatter.py | {
"start": 1418,
"end": 4595
} | class ____(BaseAgentChatFormatter):
"""ReAct chat formatter."""
system_header: str = REACT_CHAT_SYSTEM_HEADER # default
context: str = "" # not needed w/ default
observation_role: MessageRole = Field(
default=MessageRole.USER,
description=(
"Message role of tool outputs. I... | ReActChatFormatter |
python | django__django | django/forms/fields.py | {
"start": 35822,
"end": 36555
} | class ____(Field):
"""
A Field whose clean() method calls multiple Field clean() methods.
"""
def __init__(self, fields, **kwargs):
super().__init__(**kwargs)
# Set 'required' to False on the individual fields, because the
# required validation will be handled by ComboField, not... | ComboField |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance5.py | {
"start": 161,
"end": 215
} | class ____:
def __call__(self, x: str) -> int: ...
| B |
python | mlflow__mlflow | mlflow/types/responses_helpers.py | {
"start": 7293,
"end": 7486
} | class ____(BaseModel):
input_tokens: int
input_tokens_details: InputTokensDetails
output_tokens: int
output_tokens_details: OutputTokensDetails
total_tokens: int
| ResponseUsage |
python | encode__django-rest-framework | tests/test_serializer.py | {
"start": 1684,
"end": 7640
} | class ____:
def setup_method(self):
class ExampleSerializer(serializers.Serializer):
char = serializers.CharField()
integer = serializers.IntegerField()
self.Serializer = ExampleSerializer
def test_valid_serializer(self):
serializer = self.Serializer(data={'char... | TestSerializer |
python | ray-project__ray | doc/source/serve/doc_code/getting_started/model_deployment.py | {
"start": 267,
"end": 1339
} | class ____:
def __init__(self):
# Load model
self.model = pipeline("translation_en_to_fr", model="t5-small")
def translate(self, text: str) -> str:
# Run inference
model_output = self.model(text)
# Post-process output to return only the translation text
translat... | Translator |
python | pytorch__pytorch | benchmarks/tensorexpr/reduction.py | {
"start": 26,
"end": 2325
} | class ____(benchmark.Benchmark):
def __init__(self, mode, device, dtype, case, M, N, K, skip_input_transform):
super().__init__(mode, device, dtype)
self.case = case
self.M = M
self.N = N
self.K = K
self._set_skip_input_transform(skip_input_transform)
self.in... | ReduceBench |
python | openai__openai-python | src/openai/types/webhooks/eval_run_failed_webhook_event.py | {
"start": 316,
"end": 743
} | class ____(BaseModel):
id: str
"""The unique ID of the event."""
created_at: int
"""The Unix timestamp (in seconds) of when the eval run failed."""
data: Data
"""Event data payload."""
type: Literal["eval.run.failed"]
"""The type of the event. Always `eval.run.failed`."""
object:... | EvalRunFailedWebhookEvent |
python | gevent__gevent | src/gevent/tests/test__pywsgi.py | {
"start": 49721,
"end": 51223
} | class ____(TestCase):
validator = None
# pywsgi checks content-length, but wsgi does not
content_length = None
assert TestCase.handler_class._print_unexpected_exc
class handler_class(TestCase.handler_class):
def _print_unexpected_exc(self):
raise AssertionError("Should not prin... | BadRequestTests |
python | wandb__wandb | wandb/apis/public/registries/registries_search.py | {
"start": 4402,
"end": 8054
} | class ____(
SizedRelayPaginator["RegistryCollectionFragment", "ArtifactCollection"]
):
"""An lazy iterator of `ArtifactCollection` objects in a Registry."""
QUERY: ClassVar[Document | None] = None
last_response: RegistryCollectionConnection | None
def __init__(
self,
client: Retryi... | Collections |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py | {
"start": 29495,
"end": 32521
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
config: Qwen2_5OmniAudioEncoderConfig,
):
super().__init__()
self.embed_dim = config.d_model
self.num_heads = config.encoder_attention_heads
self.dr... | Qwen2_5OmniAudioAttention |
python | lepture__authlib | authlib/integrations/starlette_client/apps.py | {
"start": 416,
"end": 1628
} | class ____:
async def save_authorize_data(self, request, **kwargs):
state = kwargs.pop("state", None)
if state:
if self.framework.cache:
session = None
else:
session = request.session
await self.framework.set_state_data(session, sta... | StarletteAppMixin |
python | Netflix__metaflow | metaflow/plugins/aws/aws_client.py | {
"start": 63,
"end": 4287
} | class ____(object):
name = "boto3"
@staticmethod
def get_client(
module, with_error=False, role_arn=None, session_vars=None, client_params=None
):
from metaflow.exception import MetaflowException
from metaflow.metaflow_config import (
AWS_SANDBOX_ENABLED,
... | Boto3ClientProvider |
python | numpy__numpy | numpy/_core/tests/test_umath.py | {
"start": 51927,
"end": 52315
} | class ____:
def test_type_conversion(self):
arg_type = '?bhilBHILefdgFDG'
res_type = 'ddddddddddddgDDG'
for dtin, dtout in zip(arg_type, res_type):
msg = f"dtin: {dtin}, dtout: {dtout}"
arg = np.ones(1, dtype=dtin)
res = np.float_power(arg, arg)
... | TestFloat_power |
python | sphinx-doc__sphinx | sphinx/domains/cpp/__init__.py | {
"start": 3988,
"end": 16570
} | class ____(ObjectDescription[ASTDeclaration]):
"""Description of a C++ language object."""
doc_field_types: list[Field] = [
GroupedField(
'template parameter',
label=_('Template Parameters'),
names=('tparam', 'template parameter'),
can_collapse=True,
... | CPPObject |
python | Netflix__metaflow | metaflow/_vendor/click/_winconsole.py | {
"start": 6041,
"end": 10009
} | class ____(object):
"""
Wraps a stream (such as stdout), acting as a transparent proxy for all
attribute access apart from method 'write()' which we wrap to write in
limited chunks due to a Windows limitation on binary console streams.
"""
def __init__(self, wrapped):
# double-underscor... | WindowsChunkedWriter |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/execution_tests/engine_tests/test_child_process_executor.py | {
"start": 930,
"end": 1121
} | class ____(ChildProcessCommand):
def execute(self): # pyright: ignore[reportIncompatibleMethodOverride]
# access inner API to simulate hard crash
segfault()
| SegfaultCommand |
python | langchain-ai__langchain | libs/langchain/tests/unit_tests/retrievers/test_parent_document.py | {
"start": 406,
"end": 1537
} | class ____(InMemoryVectorStore):
@override
def similarity_search(
self,
query: str,
k: int = 4,
**kwargs: Any,
) -> list[Document]:
res = self.store.get(query)
if res is None:
return []
return [res]
@override
def add_documents(self... | InMemoryVectorstoreWithSearch |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-finance/llama_index/tools/finance/base.py | {
"start": 238,
"end": 6866
} | class ____(BaseToolSpec):
spec_functions = [
"find_similar_companies",
"get_earnings_history",
"get_stocks_with_upcoming_earnings",
"get_current_gainer_stocks",
"get_current_loser_stocks",
"get_current_undervalued_growth_stocks",
"get_current_technology_growth... | FinanceAgentToolSpec |
python | RaRe-Technologies__gensim | gensim/test/test_corpora.py | {
"start": 23437,
"end": 30604
} | class ____(TestTextCorpus):
def setUp(self):
self.corpus_class = wikicorpus.WikiCorpus
self.file_extension = '.xml.bz2'
self.fname = datapath('testcorpus.' + self.file_extension.lstrip('.'))
self.enwiki = datapath('enwiki-latest-pages-articles1.xml-p000000010p000030302-shortened.bz2'... | TestWikiCorpus |
python | fastapi__sqlmodel | docs_src/tutorial/where/tutorial010_py310.py | {
"start": 71,
"end": 1569
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
secret_name: str
age: int | None = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLM... | Hero |
python | facebook__pyre-check | client/commands/report_any_expressions.py | {
"start": 2088,
"end": 2930
} | class ____(json_mixins.SnakeCaseAndExcludeJsonMixin):
any_expression_count: int
total_expression_count: int
# Records cases where the backend couldn't process the module.
error: Optional[str] = None
@staticmethod
def from_error(
error: str,
) -> ExpressionStatistics:
return ... | ExpressionStatistics |
python | sympy__sympy | sympy/printing/c.py | {
"start": 4506,
"end": 22974
} | class ____(CodePrinter):
"""A printer to convert Python expressions to strings of C code"""
printmethod = "_ccode"
language = "C"
standard = "C89"
reserved_words = set(reserved_words)
_default_settings: dict[str, Any] = dict(CodePrinter._default_settings, **{
'precision': 17,
'u... | C89CodePrinter |
python | lazyprogrammer__machine_learning_examples | rnn_class/rrnn_language.py | {
"start": 526,
"end": 6854
} | class ____:
def __init__(self, D, M, V):
self.D = D # dimensionality of word embedding
self.M = M # hidden layer size
self.V = V # vocabulary size
def fit(self, X, learning_rate=10., mu=0.9, reg=0., activation=T.tanh, epochs=500, show_fig=False):
N = len(X)
D = self.D
... | SimpleRNN |
python | openai__openai-python | src/openai/types/evals/create_eval_completions_run_data_source_param.py | {
"start": 1848,
"end": 2048
} | class ____(TypedDict, total=False):
id: Required[str]
"""The identifier of the file."""
type: Required[Literal["file_id"]]
"""The type of jsonl source. Always `file_id`."""
| SourceFileID |
python | numba__numba | numba/core/datamodel/models.py | {
"start": 15516,
"end": 22369
} | class ____(CompositeModel):
_value_type = None
_data_type = None
def __init__(self, dmm, fe_type, members):
super(StructModel, self).__init__(dmm, fe_type)
if members:
self._fields, self._members = zip(*members)
else:
self._fields = self._members = ()
... | StructModel |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linalg_ops_test.py | {
"start": 5910,
"end": 9968
} | class ____(parameterized.TestCase, test.TestCase):
def testShapeInferenceNoBatch(self):
self.assertEqual((2, 2), linalg_ops.eye(num_rows=2).shape)
self.assertEqual((2, 3), linalg_ops.eye(num_rows=2, num_columns=3).shape)
def testShapeInferenceStaticBatch(self):
batch_shape = (2, 3)
self.assertEqua... | EyeTest |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/external.py | {
"start": 2685,
"end": 3339
} | class ____(graphene.Enum):
LOADING = "LOADING"
LOADED = "LOADED"
class Meta:
name = "RepositoryLocationLoadStatus"
@classmethod
def from_python_status(cls, python_status):
check.inst_param(python_status, "python_status", CodeLocationLoadStatus)
if python_status == CodeLocat... | GrapheneRepositoryLocationLoadStatus |
python | dask__dask | dask/bag/tests/test_bag.py | {
"start": 33109,
"end": 43216
} | class ____(db.Bag):
def get(self, key, default=None):
return self.map(lambda d: d.get(key, default))
def set(self, key, value):
def setter(d):
d[key] = value
return d
return self.map(setter)
def test_bag_class_extend():
dictbag = BagOfDicts(*db.from_sequen... | BagOfDicts |
python | doocs__leetcode | solution/3300-3399/3349.Adjacent Increasing Subarrays Detection I/Solution.py | {
"start": 0,
"end": 338
} | class ____:
def hasIncreasingSubarrays(self, nums: List[int], k: int) -> bool:
mx = pre = cur = 0
for i, x in enumerate(nums):
cur += 1
if i == len(nums) - 1 or x >= nums[i + 1]:
mx = max(mx, cur // 2, min(pre, cur))
pre, cur = cur, 0
r... | Solution |
python | dagster-io__dagster | python_modules/libraries/dagster-dbt/dagster_dbt/cloud_v2/resources.py | {
"start": 15599,
"end": 16925
} | class ____(StateBackedDefinitionsLoader[DbtCloudWorkspaceData]):
workspace: DbtCloudWorkspace
translator: DagsterDbtTranslator
select: str
exclude: str
selector: str
@property
def defs_key(self) -> str:
return f"{DBT_CLOUD_RECONSTRUCTION_METADATA_KEY_PREFIX}.{self.workspace.unique_i... | DbtCloudWorkspaceDefsLoader |
python | conda__conda | conda/exceptions.py | {
"start": 34145,
"end": 34409
} | class ____(CondaError, MemoryError):
def __init__(self, caused_by: Any, **kwargs):
message = "The conda process ran out of memory. Increase system memory and/or try again."
super().__init__(message, caused_by=caused_by, **kwargs)
| CondaMemoryError |
python | sanic-org__sanic | sanic/models/futures.py | {
"start": 1601,
"end": 1667
} | class ____(NamedTuple):
name: str
func: Callable
| FutureCommand |
python | google__jax | tests/pallas/mgpu_examples_test.py | {
"start": 1342,
"end": 34012
} | class ____:
tile_m: int
tile_n: int
tile_k: int
max_concurrent_steps: int
epilogue_tile_n: int = 64
grid_minor_dim: int = 0
grid_tile_width: int = 1
def matmul0(a, b, config: TuningConfig):
dtype = a.dtype
m, k = a.shape
_, n = b.shape
tile_m, tile_n, tile_k = config.tile_m, config.tile_n, confi... | TuningConfig |
python | ray-project__ray | python/ray/serve/tests/unit/test_proxy_request_response.py | {
"start": 338,
"end": 6077
} | class ____:
def create_asgi_proxy_request(self, scope: dict) -> ASGIProxyRequest:
receive = MagicMock()
send = MagicMock()
return ASGIProxyRequest(scope=scope, receive=receive, send=send)
def test_request_type(self):
"""Test calling request_type on an instance of ASGIProxyReques... | TestASGIProxyRequest |
python | openai__openai-python | src/openai/types/realtime/realtime_mcp_list_tools_param.py | {
"start": 611,
"end": 975
} | class ____(TypedDict, total=False):
server_label: Required[str]
"""The label of the MCP server."""
tools: Required[Iterable[Tool]]
"""The tools available on the server."""
type: Required[Literal["mcp_list_tools"]]
"""The type of the item. Always `mcp_list_tools`."""
id: str
"""The uni... | RealtimeMcpListToolsParam |
python | pypa__pip | src/pip/_vendor/rich/progress.py | {
"start": 32176,
"end": 32381
} | class ____(NamedTuple):
"""Sample of progress for a given time."""
timestamp: float
"""Timestamp of sample."""
completed: float
"""Number of steps completed."""
@dataclass
| ProgressSample |
python | walkccc__LeetCode | solutions/2342. Max Sum of a Pair With Equal Sum of Digits/2342.py | {
"start": 0,
"end": 488
} | class ____:
def maximumSum(self, nums: list[int]) -> int:
MAX = 9 * 9 # 999,999,999
ans = -1
count = [[] for _ in range(MAX + 1)]
for num in nums:
count[self._getDigitSum(num)].append(num)
for groupNums in count:
if len(groupNums) < 2:
continue
groupNums.sort(reverse=T... | Solution |
python | neetcode-gh__leetcode | python/1631-path-with-minimum-effort.py | {
"start": 0,
"end": 1024
} | class ____:
def minimumEffortPath(self, heights: List[List[int]]) -> int:
m, n = len(heights), len(heights[0])
efforts = [[float('inf')] * n for _ in range(m)]
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
efforts[0][0] = 0
pq = [(0, 0, 0)] # (effort, row... | Solution |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 120908,
"end": 121556
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
job_cluster_key: str = Field(
...,
description=(
"A unique name for the job cluster. This field is required and must be"
" uniqu... | JobCluster |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/configuration_qwen3_omni_moe.py | {
"start": 17168,
"end": 21397
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Qwen3OmniMoeThinker`]. It is used to instantiate a
Qwen3-Omni-Thinker model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yie... | Qwen3OmniMoeThinkerConfig |
python | numba__numba | numba/core/intrinsics.py | {
"start": 91,
"end": 2008
} | class ____(ir.Visitor):
def visit_Instruction(self, instr):
if instr.type == ir.IntType(64):
if instr.opname in ['srem', 'urem', 'sdiv', 'udiv']:
name = 'numba_{op}'.format(op=instr.opname)
fn = self.module.globals.get(name)
# Declare the function ... | _DivmodFixer |
python | langchain-ai__langchain | libs/partners/huggingface/langchain_huggingface/embeddings/huggingface_endpoint.py | {
"start": 362,
"end": 5677
} | class ____(BaseModel, Embeddings):
"""HuggingFaceHub embedding models.
To use, you should have the `huggingface_hub` python package installed, and the
environment variable `HUGGINGFACEHUB_API_TOKEN` set with your API token, or pass
it as a named parameter to the constructor.
Example:
```py... | HuggingFaceEndpointEmbeddings |
python | ApeWorX__ape | src/ape/api/providers.py | {
"start": 5676,
"end": 7160
} | class ____(BaseModel, ManagerAccessMixin):
"""
The result of a call.
NOTE: Currently, you only get this for reverted calls from ``ProviderAPI``.
"""
revert: Optional[ContractLogicError] = None
"""
The revert, if the call reverted.
"""
returndata: HexBytes
"""
The raw return... | CallResult |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/translate.py | {
"start": 2270,
"end": 2639
} | class ____(Exception):
"""Wait operation not done yet error."""
pass
def _if_exc_is_wait_failed_error(exc: Exception):
return isinstance(exc, WaitOperationNotDoneYetError)
def _check_if_operation_done(operation: Operation):
if not operation.done():
raise WaitOperationNotDoneYetError("Operat... | WaitOperationNotDoneYetError |
python | cookiecutter__cookiecutter | cookiecutter/exceptions.py | {
"start": 1960,
"end": 2140
} | class ____(CookiecutterException):
"""
Exception for failed JSON decoding.
Raised when a project's JSON context file can not be decoded.
"""
| ContextDecodingException |
python | RaRe-Technologies__gensim | gensim/interfaces.py | {
"start": 7428,
"end": 9106
} | class ____(utils.SaveLoad):
"""Transformation interface.
A 'transformation' is any object which accepts document in BoW format via the `__getitem__` (notation `[]`)
and returns another sparse document in its stead:
.. sourcecode:: pycon
>>> from gensim.models import LsiModel
>>> from ... | TransformationABC |
python | streamlit__streamlit | lib/tests/streamlit/elements/space_test.py | {
"start": 819,
"end": 2823
} | class ____(DeltaGeneratorTestCase):
"""Test ability to marshall space protos."""
def test_space_default(self):
"""Test st.space() with default size."""
st.space()
c = self.get_delta_from_queue().new_element
assert c.space is not None
# Default is "small" = 0.75rem
... | SpaceTest |
python | doocs__leetcode | solution/0900-0999/0903.Valid Permutations for DI Sequence/Solution3.py | {
"start": 0,
"end": 544
} | class ____:
def numPermsDISequence(self, s: str) -> int:
mod = 10**9 + 7
n = len(s)
f = [1] + [0] * n
for i, c in enumerate(s, 1):
pre = 0
g = [0] * (n + 1)
if c == "D":
for j in range(i, -1, -1):
pre = (pre + f[... | Solution |
python | django__django | tests/test_runner_apps/sample/tests_sample.py | {
"start": 551,
"end": 700
} | class ____(TestCase):
pass
def load_tests(loader, tests, ignore):
tests.addTests(doctest.DocTestSuite(doctests))
return tests
| EmptyTestCase |
python | spack__spack | lib/spack/spack/build_environment.py | {
"start": 58411,
"end": 63186
} | class ____(InstallError):
"""Special exception class for wrapping exceptions from child processes
in Spack's build environment.
The main features of a ChildError are:
1. They're serializable, so when a child build fails, we can send one
of these to the parent and let the parent report what happ... | ChildError |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/session.py | {
"start": 28201,
"end": 49992
} | class ____(_StateChange, TransactionalContext):
"""A :class:`.Session`-level transaction.
:class:`.SessionTransaction` is produced from the
:meth:`_orm.Session.begin`
and :meth:`_orm.Session.begin_nested` methods. It's largely an internal
object that in modern use provides a context manager for s... | SessionTransaction |
python | apache__airflow | providers/smtp/tests/unit/smtp/operators/test_smtp.py | {
"start": 1075,
"end": 3692
} | class ____:
def setup_method(self):
self.default_op_kwargs = dict(to="to", subject="subject", html_content="content")
@patch("airflow.providers.smtp.hooks.smtp.SmtpHook.get_connection")
@patch(smtplib_string)
def test_loading_sender_email_from_connection(self, mock_smtplib, mock_hook_conn):
... | TestEmailOperator |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.