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 | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/libtool_installation/package.py | {
"start": 472,
"end": 545
} | class ____(BuilderBase):
install_libtool_archives = True
| AutotoolsBuilder |
python | Textualize__textual | src/textual/command.py | {
"start": 4955,
"end": 9748
} | class ____(ABC):
"""Base class for command palette command providers.
To create new command provider, inherit from this class and implement
[`search`][textual.command.Provider.search].
"""
def __init__(self, screen: Screen[Any], match_style: Style | None = None) -> None:
"""Initialise the ... | Provider |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-zapier/llama_index/tools/zapier/base.py | {
"start": 235,
"end": 2627
} | class ____(BaseToolSpec):
"""Zapier tool spec."""
spec_functions = []
def __init__(
self, api_key: Optional[str] = None, oauth_access_token: Optional[str] = None
) -> None:
"""Initialize with parameters."""
if api_key:
self._headers = {"x-api-key": api_key}
... | ZapierToolSpec |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 304784,
"end": 313983
} | class ____(rv_continuous):
r"""A skew-normal random variable.
%(before_notes)s
Notes
-----
The pdf is::
skewnorm.pdf(x, a) = 2 * norm.pdf(x) * norm.cdf(a*x)
`skewnorm` takes a real number :math:`a` as a skewness parameter
When ``a = 0`` the distribution is identical to a normal d... | skewnorm_gen |
python | astropy__astropy | astropy/table/tests/test_pprint.py | {
"start": 12156,
"end": 12955
} | class ____:
@pytest.mark.parametrize(
"scalar, exp",
[
(
1,
[
"None",
"----",
" 1",
],
),
(
u.Quantity(0.6, "eV"),
[
... | TestPprintColumn |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/exception.py | {
"start": 591,
"end": 727
} | class ____(CurriculumError):
"""
Any error related to loading the Curriculum config file.
"""
pass
| CurriculumLoadingError |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/completion/fuzzy_completer.py | {
"start": 6580,
"end": 7639
} | class ____(Completer):
"""
Fuzzy completion on a list of words.
(This is basically a `WordCompleter` wrapped in a `FuzzyCompleter`.)
:param words: List of words or callable that returns a list of words.
:param meta_dict: Optional dict mapping words to their meta-information.
:param WORD: When ... | FuzzyWordCompleter |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_build.py | {
"start": 33567,
"end": 37213
} | class ____(GoogleCloudBaseOperator):
"""
Creates a new build using the original build request, which may or may not result in an identical build.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudBuildRetryBuildOperator`
... | CloudBuildRetryBuildOperator |
python | Pylons__pyramid | src/pyramid/config/security.py | {
"start": 13796,
"end": 14271
} | class ____:
def __init__(
self,
require_csrf,
token,
header,
safe_methods,
check_origin,
allow_no_origin,
callback,
):
self.require_csrf = require_csrf
self.token = token
self.header = header
self.safe_methods = froz... | DefaultCSRFOptions |
python | weaviate__weaviate-python-client | weaviate/collections/queries/near_media/generate/executor.py | {
"start": 1056,
"end": 20592
} | class ____(
Generic[ConnectionType, Properties, References], _BaseExecutor[ConnectionType]
):
@overload
def near_media(
self,
media: BLOB_INPUT,
media_type: NearMediaType,
*,
single_prompt: Union[str, _SinglePrompt, None] = None,
grouped_task: Union[str, _Grou... | _NearMediaGenerateExecutor |
python | pyca__cryptography | tests/hazmat/primitives/test_rsa.py | {
"start": 86835,
"end": 94819
} | class ____:
@pytest.mark.parametrize(
("fmt", "password"),
itertools.product(
[
serialization.PrivateFormat.TraditionalOpenSSL,
serialization.PrivateFormat.PKCS8,
],
[
b"s",
b"longerpassword",
... | TestRSAPrivateKeySerialization |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/pipelines/pipeline_run_stats.py | {
"start": 182,
"end": 787
} | class ____(graphene.Interface):
id = graphene.NonNull(graphene.String)
runId = graphene.NonNull(graphene.String)
stepsSucceeded = graphene.NonNull(graphene.Int)
stepsFailed = graphene.NonNull(graphene.Int)
materializations = graphene.NonNull(graphene.Int)
expectations = graphene.NonNull(graphene... | GraphenePipelineRunStatsSnapshot |
python | PyCQA__bandit | bandit/core/metrics.py | {
"start": 157,
"end": 3454
} | class ____:
"""Bandit metric gathering.
This class is a singleton used to gather and process metrics collected when
processing a code base with bandit. Metric collection is stateful, that
is, an active metric block will be set when requested and all subsequent
operations will effect that metric blo... | Metrics |
python | numpy__numpy | tools/swig/test/testTensor.py | {
"start": 12247,
"end": 12551
} | class ____(TensorTestCase):
def __init__(self, methodName="runTest"):
TensorTestCase.__init__(self, methodName)
self.typeStr = "short"
self.typeCode = "h"
self.result = int(self.result)
######################################################################
| shortTestCase |
python | sanic-org__sanic | sanic/cookies/response.py | {
"start": 11211,
"end": 21414
} | class ____:
"""A representation of a HTTP cookie, providing an interface to manipulate cookie attributes intended for a response.
This class is a simplified representation of a cookie, similar to the Morsel SimpleCookie in Python's standard library.
It allows the manipulation of various cookie attributes i... | Cookie |
python | dagster-io__dagster | python_modules/dagster/dagster/components/lib/sql_component/sql_component.py | {
"start": 2548,
"end": 2895
} | class ____(BaseModel):
"""A file containing SQL content."""
path: str = Field(..., description="Path to the SQL file")
ResolvedSqlTemplate = Annotated[
Union[str, SqlFile],
Resolver(
lambda ctx, template: template,
model_field_type=Union[str, SqlFile],
inject_before_resolve=Fa... | SqlFile |
python | huggingface__transformers | tests/pipelines/test_pipelines_zero_shot_object_detection.py | {
"start": 1157,
"end": 9818
} | class ____(unittest.TestCase):
model_mapping = MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING
def get_test_pipeline(
self,
model,
tokenizer=None,
image_processor=None,
feature_extractor=None,
processor=None,
dtype="float32",
):
object_detector =... | ZeroShotObjectDetectionPipelineTests |
python | numba__numba | numba/core/typing/npdatetime.py | {
"start": 4227,
"end": 4347
} | class ____(TimedeltaBinOp):
key = operator.sub
@infer_global(operator.mul)
@infer_global(operator.imul)
| TimedeltaBinSub |
python | ray-project__ray | rllib/examples/rl_modules/classes/action_masking_rlm.py | {
"start": 3442,
"end": 9351
} | class ____(ActionMaskingRLModule, PPOTorchRLModule):
@override(PPOTorchRLModule)
def setup(self):
super().setup()
# We need to reset here the observation space such that the
# super`s (`PPOTorchRLModule`) observation space is the
# original space (i.e. without the action mask) an... | ActionMaskingTorchRLModule |
python | optuna__optuna | optuna/samplers/nsgaii/_crossovers/_base.py | {
"start": 157,
"end": 2063
} | class ____(abc.ABC):
"""Base class for crossovers.
A crossover operation is used by :class:`~optuna.samplers.NSGAIISampler`
to create new parameter combination from parameters of ``n`` parent individuals.
.. note::
Concrete implementations of this class are expected to only accept parameters
... | BaseCrossover |
python | realpython__materials | python-getter-setter/label2.py | {
"start": 0,
"end": 241
} | class ____:
def __init__(self, text, font):
self.set_text(text)
self.font = font
def get_text(self):
return self._text
def set_text(self, value):
self._text = value.upper() # Attached behavior
| Label |
python | explosion__spaCy | spacy/pipeline/tok2vec.py | {
"start": 8784,
"end": 13476
} | class ____(Model):
"""A layer that gets fed its answers from an upstream connection,
for instance from a component earlier in the pipeline.
The Tok2VecListener layer is used as a sublayer within a component such
as a parser, NER or text categorizer. Usually you'll have multiple listeners
connecting... | Tok2VecListener |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 289196,
"end": 289679
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of ResolveReviewThread"""
__schema__ = github_schema
__field_names__ = ("thread_id", "client_mutation_id")
thread_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="threadId")
"""The ID of the thread to resolve"""
client_mu... | ResolveReviewThreadInput |
python | getsentry__sentry | src/sentry/analytics/events/join_request_link_viewed.py | {
"start": 81,
"end": 206
} | class ____(analytics.Event):
organization_id: int
analytics.register(JoinRequestLinkViewedEvent)
| JoinRequestLinkViewedEvent |
python | crytic__slither | slither/printers/summary/require_calls.py | {
"start": 471,
"end": 1984
} | class ____(AbstractPrinter):
ARGUMENT = "require"
HELP = "Print the require and assert calls of each function"
WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#require"
@staticmethod
def _convert(l):
return "\n".join(l)
def output(self, _filename):
""... | RequireOrAssert |
python | realpython__materials | django-pagination/terms/views.py | {
"start": 194,
"end": 287
} | class ____(ListView):
model = Keyword
template_name = "terms/base.html"
| AllKeywordsView |
python | walkccc__LeetCode | solutions/1014. Best Sightseeing Pair/1014.py | {
"start": 0,
"end": 231
} | class ____:
def maxScoreSightseeingPair(self, values: list[int]) -> int:
ans = 0
bestPrev = 0
for value in values:
ans = max(ans, value + bestPrev)
bestPrev = max(bestPrev, value) - 1
return ans
| Solution |
python | langchain-ai__langchain | libs/langchain/langchain_classic/chains/transform.py | {
"start": 422,
"end": 2286
} | class ____(Chain):
"""Chain that transforms the chain output.
Example:
```python
from langchain_classic.chains import TransformChain
transform_chain = TransformChain(input_variables=["text"],
output_variables["entities"], transform=func())
```
"""
input_variab... | TransformChain |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 302652,
"end": 305641
} | class ____:
def test_inner_type_mismatch(self):
c = 1.
A = np.array((1, 1), dtype='i,i')
assert_raises(TypeError, np.inner, c, A)
assert_raises(TypeError, np.inner, A, c)
def test_inner_scalar_and_vector(self):
for dt in np.typecodes['AllInteger'] + np.typecodes['AllFl... | TestInner |
python | walkccc__LeetCode | solutions/3425. Longest Special Path/3425.py | {
"start": 0,
"end": 1083
} | class ____:
def longestSpecialPath(
self,
edges: list[list[int]],
nums: list[int]
) -> list[int]:
maxLength = 0
minNodes = 1
graph = [[] for _ in range(len(nums))]
for u, v, w in edges:
graph[u].append((v, w))
graph[v].append((u, w))
prefix = [0]
lastSeenDepth... | Solution |
python | getsentry__sentry-python | tests/test_basics.py | {
"start": 29903,
"end": 36573
} | class ____:
@staticmethod
def static(arg):
return arg
@classmethod
def class_(cls, arg):
return cls, arg
# We need to fork here because the test modifies tests.test_basics.TracingTestClass
@pytest.mark.forked
def test_staticmethod_class_tracing(sentry_init, capture_events):
sentry... | TracingTestClass |
python | getsentry__sentry | tests/sentry/incidents/models/test_alert_rule.py | {
"start": 11326,
"end": 12510
} | class ____(TestCase):
@pytest.fixture(autouse=True)
def _setup_metric_patch(self) -> Generator[None]:
with mock.patch("sentry.incidents.models.alert_rule.metrics") as self.metrics:
yield
def setUp(self) -> None:
self.suspended_registry = TemporaryAlertRuleTriggerActionRegistry.s... | AlertRuleTriggerActionActivateTest |
python | crytic__slither | slither/core/scope/scope.py | {
"start": 1123,
"end": 8585
} | class ____:
def __init__(self, filename: Filename) -> None:
self.filename = filename
self.accessible_scopes: List[FileScope] = []
self.exported_symbols: Set[int] = set()
self.contracts: Dict[str, Contract] = {}
# Custom error are a list instead of a dict
# Because we... | FileScope |
python | huggingface__transformers | src/transformers/models/biogpt/modeling_biogpt.py | {
"start": 24956,
"end": 29180
} | class ____(BioGptPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.biogpt = BioGptModel(config)
if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
classifier_dropout = config.c... | BioGptForTokenClassification |
python | sqlalchemy__sqlalchemy | test/orm/test_descriptor.py | {
"start": 953,
"end": 3785
} | class ____(fixtures.ORMTest):
def _fixture(self):
Base = declarative_base()
class Foo(Base):
__tablename__ = "foo"
id = Column(Integer, primary_key=True)
return Foo
def test_fixture(self):
Foo = self._fixture()
d = MockDescriptor(Foo, "foo")
... | DescriptorInstrumentationTest |
python | tornadoweb__tornado | tornado/web.py | {
"start": 103196,
"end": 125171
} | class ____(RequestHandler):
"""A simple handler that can serve static content from a directory.
A `StaticFileHandler` is configured automatically if you pass the
``static_path`` keyword argument to `Application`. This handler
can be customized with the ``static_url_prefix``, ``static_handler_class``,
... | StaticFileHandler |
python | django__django | tests/template_tests/utils.py | {
"start": 2301,
"end": 2370
} | class ____(Exception):
silent_variable_failure = True
| SomeException |
python | pytorch__pytorch | test/distributed/checkpoint/test_fsspec.py | {
"start": 2140,
"end": 2554
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.net1 = nn.Sequential(nn.Linear(8, 16), nn.ReLU())
self.net2 = nn.Sequential(nn.Linear(16, 32), nn.ReLU())
self.net3 = nn.Linear(32, 64)
self.net4 = nn.Sequential(nn.ReLU(), nn.Linear(64, 8))
... | MyTestModule |
python | fastai__fastai | fastai/callback/tracker.py | {
"start": 2473,
"end": 3835
} | class ____(TrackerCallback):
"A `TrackerCallback` that terminates training when monitored quantity stops improving."
order=TrackerCallback.order+3
def __init__(self,
monitor='valid_loss', # value (usually loss or metric) being monitored.
comp=None, # numpy comparison operator; np.less if mo... | EarlyStoppingCallback |
python | PrefectHQ__prefect | tests/server/models/test_orm.py | {
"start": 8427,
"end": 14029
} | class ____:
async def test_task_run_state_relationship_retrieves_current_state(
self, many_task_run_states, session, db
):
# efficient query for most recent state without knowing its ID
# by getting the state with the most recent timestamp
frs_alias = sa.orm.aliased(db.TaskRunSta... | TestTaskRun |
python | cython__cython | Cython/Debugger/libpython.py | {
"start": 26447,
"end": 27792
} | class ____(PyObjectPtr):
_typename = 'PyLongObject'
def proxyval(self, visited):
'''
Python's Include/longobjrep.h has this declaration:
struct _longobject {
PyObject_VAR_HEAD
digit ob_digit[1];
};
with this description:
T... | PyLongObjectPtr |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 93057,
"end": 93290
} | class ____(_PrintableStructure):
_fields_ = [
('version', c_uint),
('vgpuCount', c_uint),
('vgpuInstances', POINTER(c_uint)),
]
nvmlActiveVgpuInstanceInfo_v1 = 0x1000010
| c_nvmlActiveVgpuInstanceInfo_v1_t |
python | cython__cython | tests/run/pure_mode_cmethod_inheritance_T583.py | {
"start": 0,
"end": 327
} | class ____(object):
'''
>>> base = Base()
>>> print(base.noargs())
Base
>>> print(base.int_arg(1))
Base
>>> print(base._class())
Base
'''
def noargs(self):
return "Base"
def int_arg(self, i):
return "Base"
@classmethod
def _class(tp):
return "B... | Base |
python | PrefectHQ__prefect | src/prefect/server/database/configurations.py | {
"start": 3523,
"end": 6738
} | class ____(ABC):
"""
Abstract base class used to inject database connection configuration into Prefect.
This configuration is responsible for defining how Prefect REST API creates and manages
database connections and sessions.
"""
def __init__(
self,
connection_url: str,
... | BaseDatabaseConfiguration |
python | numba__numba | numba/tests/test_listobject.py | {
"start": 30425,
"end": 31183
} | class ____(MemoryLeakMixin, TestCase):
"""Test list clear. """
def test_list_clear_empty(self):
@njit
def foo():
l = listobject.new_list(int32)
l.clear()
return len(l)
self.assertEqual(foo(), 0)
def test_list_clear_singleton(self):
@njit... | TestClear |
python | Lightning-AI__lightning | tests/tests_pytorch/callbacks/test_model_checkpoint_edge_cases.py | {
"start": 837,
"end": 1747
} | class ____(LightningModule):
"""Logs a validation metric on every validation run, even if validation is run multiple times per epoch."""
def __init__(self, val_scores: list[float]):
super().__init__()
self.layer = nn.Linear(1, 1)
self._val_scores = [float(s) for s in val_scores]
... | MultiValPerEpochModule |
python | wandb__wandb | wandb/automations/events.py | {
"start": 3938,
"end": 5358
} | class ____(GQLBase): # from: TriggeringRunMetricEvent
run: Annotated[
JsonEncoded[MongoLikeFilter],
AfterValidator(wrap_run_event_run_filter),
Field(alias="run_filter"),
] = And()
"""Filters that must match any runs that will trigger this event."""
metric: Annotated[
Un... | RunMetricFilter |
python | apache__airflow | task-sdk/src/airflow/sdk/exceptions.py | {
"start": 8891,
"end": 9559
} | class ____(AirflowException):
"""Raise when an XCom reference is being resolved against a non-existent XCom."""
def __init__(self, dag_id: str, task_id: str, key: str) -> None:
super().__init__()
self.dag_id = dag_id
self.task_id = task_id
self.key = key
def __str__(self) -... | XComNotFound |
python | huggingface__transformers | src/transformers/models/starcoder2/modeling_starcoder2.py | {
"start": 11847,
"end": 12397
} | class ____(PreTrainedModel):
config: Starcoder2Config
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["Starcoder2DecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn ... | Starcoder2PreTrainedModel |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 34321,
"end": 34516
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("BILLING", "MIGRATING", "MOVING", "RENAME")
| RepositoryLockReason |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py | {
"start": 5266,
"end": 5340
} | class ____(Qwen3VLMoeVisionConfig):
pass
| Qwen3OmniMoeVisionEncoderConfig |
python | milvus-io__pymilvus | pymilvus/client/embedding_list.py | {
"start": 243,
"end": 11045
} | class ____:
"""
A container for multiple embeddings that can be used directly in Milvus searches.
Represents a single query containing multiple vectors for array-of-vector fields.
This is particularly useful for searching struct array fields that contain vectors,
enabling array-of-vector to array-o... | EmbeddingList |
python | scipy__scipy | scipy/fftpack/tests/test_real_transforms.py | {
"start": 15047,
"end": 15186
} | class ____(_TestDSTBase):
def setup_method(self):
self.rdt = np.float32
self.dec = 6
self.type = 2
| TestDSTIIFloat |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 7487,
"end": 9252
} | class ____(GeneratedAirbyteSource):
@public
def __init__(
self,
name: str,
host: str,
port: int,
database: str,
user: str,
password: str,
auth_source: str,
replica_set: Optional[str] = None,
ssl: Optional[bool] = None,
):
... | MongodbSource |
python | donnemartin__interactive-coding-challenges | online_judges/sentence_screen_fit/test_count_sentence_fit.py | {
"start": 18,
"end": 1033
} | class ____(unittest.TestCase):
def test_count_sentence_fit(self):
solution = Solution()
self.assertRaises(TypeError, solution.count_sentence_fit,
None, None, None)
self.assertRaises(ValueError, solution.count_sentence_fit,
'abc', rows=-1, cols=-... | TestSolution |
python | ray-project__ray | python/ray/tune/tests/test_actor_reuse.py | {
"start": 1044,
"end": 1191
} | class ____(FIFOScheduler):
def on_trial_result(self, tune_controller, trial, result):
return TrialScheduler.PAUSE
| FrequentPausesScheduler |
python | kubernetes-client__python | kubernetes/client/models/v1beta2_exact_device_request.py | {
"start": 383,
"end": 14190
} | 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... | V1beta2ExactDeviceRequest |
python | huggingface__transformers | tests/models/encoder_decoder/test_modeling_encoder_decoder.py | {
"start": 40796,
"end": 46336
} | class ____(EncoderDecoderMixin, unittest.TestCase):
def get_pretrained_model(self):
return EncoderDecoderModel.from_encoder_decoder_pretrained(
"google/bert_for_seq_generation_L-24_bbc_encoder", "google/bert_for_seq_generation_L-24_bbc_encoder"
)
def get_encoder_decoder_model(self, ... | BertGenerationEncoderDecoderModelTest |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_cond_format02.py | {
"start": 315,
"end": 1121
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("cond_format02.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with conditional formatting."""
... | TestCompareXLSXFiles |
python | getsentry__sentry | src/sentry/pipeline/views/nested.py | {
"start": 272,
"end": 1957
} | class ____[P1: Pipeline[Any, Any], P2: Pipeline[Any, Any]]:
"""
A NestedPipelineView can be used within other pipelines to process another
pipeline within a pipeline. Note that the nested pipelines finish_pipeline
will NOT be called, instead it's data will be bound into the parent
pipeline and the p... | NestedPipelineView |
python | django__django | tests/gis_tests/relatedapp/models.py | {
"start": 1196,
"end": 1339
} | class ____(SimpleModel):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, models.CASCADE, unique=True)
| Article |
python | wandb__wandb | wandb/sdk/artifacts/_generated/add_aliases.py | {
"start": 180,
"end": 250
} | class ____(GQLResult):
result: Optional[AddAliasesResult]
| AddAliases |
python | etianen__django-reversion | tests/test_app/tests/test_models.py | {
"start": 10586,
"end": 10927
} | class ____(TestBase):
def testFieldDictFieldFields(self):
reversion.register(TestModel, fields=("name",))
with reversion.create_revision():
obj = TestModel.objects.create()
self.assertEqual(Version.objects.get_for_object(obj).get().field_dict, {
"name": "v1",
... | FieldDictFieldsTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/elements.py | {
"start": 64246,
"end": 64396
} | class ____(ColumnElement[_T]):
"""ColumnElement where ``.key`` is non-None."""
_is_keyed_column_element = True
key: str
| KeyedColumnElement |
python | viewflow__viewflow | tests/json/test_json__integer.py | {
"start": 95,
"end": 295
} | class ____(models.Model):
data = models.JSONField(default=dict)
integer_field = jsonstore.IntegerField(null=True)
default_integer_field = jsonstore.IntegerField(default=42)
| IntegerFieldModel |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType20.py | {
"start": 199,
"end": 242
} | class ____(Generic[T]):
y: type[T]
| Parent |
python | google__pytype | pytype/tests/test_cmp1.py | {
"start": 6975,
"end": 7599
} | class ____(test_base.BaseTest):
"""Test for "x != y". Also test overloading."""
def test_concrete(self):
self.Check("""
def f(x, y):
return x != y
assert_type(f(1, 2), bool)
assert_type(f(1, "a"), bool)
assert_type(f(object(), "x"), bool)
""")
def test_overloaded(self):
... | NeTest |
python | EpistasisLab__tpot | tpot/builtin_modules/passthrough.py | {
"start": 1938,
"end": 2379
} | class ____(TransformerMixin,BaseEstimator):
"""
A transformer returns an empty array. When combined with FeatureUnion, it can be used to skip a branch.
"""
def fit(self, X=None, y=None):
"""
Nothing to fit, just returns self.
"""
return self
def transform(self, X):
... | SkipTransformer |
python | spack__spack | lib/spack/spack/test/utilities.py | {
"start": 227,
"end": 1018
} | class ____:
"""Use this to get an Args object like what is passed into
a command.
Useful for emulating args in unit tests that want to check
helper functions in Spack commands. Ensures that you get all
the default arg values established by the parser.
Example usage::
install_args = Sp... | SpackCommandArgs |
python | Textualize__rich | rich/markdown.py | {
"start": 2236,
"end": 2434
} | class ____(MarkdownElement):
"""An unknown element.
Hopefully there will be no unknown elements, and we will have a MarkdownElement for
everything in the document.
"""
| UnknownElement |
python | TheAlgorithms__Python | maths/polynomials/single_indeterminate_operations.py | {
"start": 237,
"end": 5833
} | class ____:
def __init__(self, degree: int, coefficients: MutableSequence[float]) -> None:
"""
The coefficients should be in order of degree, from smallest to largest.
>>> p = Polynomial(2, [1, 2, 3])
>>> p = Polynomial(2, [1, 2, 3, 4])
Traceback (most recent call last):
... | Polynomial |
python | huggingface__transformers | src/transformers/models/data2vec/modeling_data2vec_vision.py | {
"start": 31345,
"end": 34451
} | class ____(Data2VecVisionPreTrainedModel):
def __init__(self, config: Data2VecVisionConfig, add_pooling_layer: bool = False) -> None:
r"""
add_pooling_layer (bool, *optional*, defaults to `False`):
Whether to add a pooling layer
"""
super().__init__(config)
self.c... | Data2VecVisionModel |
python | chroma-core__chroma | chromadb/api/types.py | {
"start": 59355,
"end": 59504
} | class ____:
fts_index: Optional[FtsIndexType] = None
string_inverted_index: Optional[StringInvertedIndexType] = None
@dataclass
| StringValueType |
python | encode__starlette | starlette/schemas.py | {
"start": 934,
"end": 4468
} | class ____:
def get_schema(self, routes: list[BaseRoute]) -> dict[str, Any]:
raise NotImplementedError() # pragma: no cover
def get_endpoints(self, routes: list[BaseRoute]) -> list[EndpointInfo]:
"""
Given the routes, yields the following information:
- path
eg: /u... | BaseSchemaGenerator |
python | keras-team__keras | keras/src/backend/tests/compute_output_spec_test.py | {
"start": 421,
"end": 4056
} | class ____(unittest.TestCase):
def test_dynamic_batch_size(self):
x = KerasTensor(shape=(None, 3, 5))
y = backend.compute_output_spec(single_arg_test_fn, x)
self.assertEqual(y.shape, (None, 3, 10))
x1 = KerasTensor(shape=(None, 3, 5))
x2 = KerasTensor(shape=(None, 3, 5))
... | ComputeOutputSpecTest |
python | gevent__gevent | src/gevent/tests/test__issue467.py | {
"start": 416,
"end": 1205
} | class ____(greentest.TestCase):
def test(self):
finished = 0
# Wait on a group that includes one that will already be
# done, plus some that will finish as we watch
done_worker = gevent.spawn(worker, "done")
gevent.joinall((done_worker,))
workers = [gevent.spawn(work... | Test |
python | readthedocs__readthedocs.org | readthedocs/oauth/services/__init__.py | {
"start": 443,
"end": 579
} | class ____(SettingsOverrideObject):
_default_class = github.GitHubService
_override_setting = "OAUTH_GITHUB_SERVICE"
| GitHubService |
python | django__django | django/utils/html.py | {
"start": 5609,
"end": 8464
} | class ____(HTMLParser):
def __init__(self):
super().__init__(convert_charrefs=False)
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def handle_entityref(self, name):
self.fed.append("&%s;" % name)
def handle_charref(self, name):
... | MLStripper |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dlp.py | {
"start": 87479,
"end": 91207
} | class ____(GoogleCloudBaseOperator):
"""
Lists job triggers.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudDLPListJobTriggersOperator`
:param project_id: (Optional) Google Cloud project ID where the
DLP Instan... | CloudDLPListJobTriggersOperator |
python | pypa__setuptools | setuptools/command/test.py | {
"start": 724,
"end": 1400
} | class ____(Command):
"""
Stub to warn when test command is referenced or used.
"""
description = "stub for old test command (do not use)"
user_options = [
('test-module=', 'm', "Run 'test_suite' in specified module"),
(
'test-suite=',
's',
"Run s... | _test |
python | django__django | tests/migration_test_data_persistence/models.py | {
"start": 31,
"end": 104
} | class ____(models.Model):
title = models.CharField(max_length=100)
| Book |
python | aimacode__aima-python | games.py | {
"start": 10408,
"end": 11089
} | class ____(Game):
"""Similar to Fig52Game but bigger. Useful for visualisation"""
succs = {i: dict(l=i * 3 + 1, m=i * 3 + 2, r=i * 3 + 3) for i in range(13)}
utils = dict()
def actions(self, state):
return sorted(list(self.succs.get(state, {}).keys()))
def result(self, state, move):
... | Fig52Extended |
python | kamyu104__LeetCode-Solutions | Python/maximize-the-distance-between-points-on-a-square.py | {
"start": 111,
"end": 1680
} | class ____(object):
def maxDistance(self, side, points, k):
"""
:type side: int
:type points: List[List[int]]
:type k: int
:rtype: int
"""
def binary_search_right(left, right, check):
while left <= right:
mid = left + (right-left)//... | Solution |
python | PrefectHQ__prefect | src/prefect/logging/loggers.py | {
"start": 917,
"end": 11268
} | class ____(LoggingAdapter):
"""
Adapter that ensures extra kwargs are passed through correctly; without this
the `extra` fields set on the adapter would overshadow any provided on a
log-by-log basis.
See https://bugs.python.org/issue32732 — the Python team has declared that this is
not a bug in... | PrefectLogAdapter |
python | tqdm__tqdm | tqdm/utils.py | {
"start": 5435,
"end": 6874
} | class ____(ObjectWrapper):
"""
Disable the given `tqdm_instance` upon `write()` or `flush()` errors.
"""
@staticmethod
def disable_on_exception(tqdm_instance, func):
"""
Quietly set `tqdm_instance.miniters=inf` if `func` raises `errno=5`.
"""
tqdm_instance = proxy(tqd... | DisableOnWriteError |
python | pytorch__pytorch | test/package/package_a/fake_interface.py | {
"start": 61,
"end": 173
} | class ____(torch.nn.Module):
def one(self, inp1: Tensor, inp2: Tensor) -> Tensor:
pass
| ModuleInterface |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/ROI.py | {
"start": 69518,
"end": 69957
} | class ____(ROI):
def __init__(self, pos, size, **args):
ROI.__init__(self, pos, size, **args)
self.addTranslateHandle([0.5, 0.5])
self.addScaleHandle([1, 1], [0, 0])
self.addScaleHandle([0, 0], [1, 1])
self.addScaleRotateHandle([1, 0.5], [0.5, 0.5])
self.addScaleHandl... | TestROI |
python | Textualize__textual | src/textual/widgets/_markdown.py | {
"start": 25419,
"end": 45386
} | class ____(Widget):
DEFAULT_CSS = """
Markdown {
height: auto;
padding: 0 2 0 2;
layout: vertical;
color: $foreground;
overflow-y: hidden;
MarkdownBlock {
&:dark > .code_inline {
background: $warning 10%;
color: $text-w... | Markdown |
python | sanic-org__sanic | sanic/logging/filter.py | {
"start": 17,
"end": 298
} | class ____(logging.Filter):
"""
Filter log records based on verbosity level.
"""
verbosity: int = 0
def filter(self, record: logging.LogRecord) -> bool:
verbosity = getattr(record, "verbosity", 0)
return verbosity <= self.verbosity
| VerbosityFilter |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_version_slug.py | {
"start": 225,
"end": 891
} | class ____(TestCase):
pattern = re.compile("^{pattern}$".format(pattern=VERSION_SLUG_REGEX))
def test_single_char(self):
self.assertTrue(self.pattern.match("v"))
self.assertFalse(self.pattern.match("."))
def test_trailing_punctuation(self):
self.assertTrue(self.pattern.match("with_... | VersionSlugPatternTests |
python | django-extensions__django-extensions | django_extensions/management/jobs.py | {
"start": 567,
"end": 613
} | class ____(BaseJob):
when = "daily"
| DailyJob |
python | Textualize__textual | tests/css/test_parse.py | {
"start": 27293,
"end": 27881
} | class ____:
def test_valid_layout_name(self):
css = "#some-widget { layout: vertical; }"
stylesheet = Stylesheet()
stylesheet.add_source(css)
styles = stylesheet.rules[0].styles
assert isinstance(styles.layout, VerticalLayout)
def test_invalid_layout_name(self):
... | TestParseLayout |
python | huggingface__transformers | src/transformers/models/jamba/modeling_jamba.py | {
"start": 36606,
"end": 44094
} | class ____(JambaPreTrainedModel):
def __init__(self, config: JambaConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
decoder_la... | JambaModel |
python | matplotlib__matplotlib | lib/matplotlib/_mathtext.py | {
"start": 41138,
"end": 41953
} | class ____(Char):
"""
The font metrics need to be dealt with differently for accents,
since they are already offset correctly from the baseline in
TrueType fonts.
"""
def _update_metrics(self) -> None:
metrics = self._metrics = self.fontset.get_metrics(
self.font, self.font_c... | Accent |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 984581,
"end": 985552
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for Repository."""
__schema__ = github_schema
__field_names__ = ("edges", "is_over_limit", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("StarredRepositoryEdge"), graphql_name="edges")
"""A list of... | StarredRepositoryConnection |
python | PyCQA__pyflakes | pyflakes/messages.py | {
"start": 9487,
"end": 9797
} | class ____(Message):
message = "'...' %% ... has %d placeholder(s) but %d substitution(s)"
def __init__(self, filename, loc, n_placeholders, n_substitutions):
Message.__init__(self, filename, loc)
self.message_args = (n_placeholders, n_substitutions)
| PercentFormatPositionalCountMismatch |
python | tensorflow__tensorflow | tensorflow/python/data/ops/from_sparse_tensor_slices_op.py | {
"start": 1208,
"end": 2464
} | class ____(dataset_ops.DatasetSource):
"""A `Dataset` that splits a rank-N `tf.sparse.SparseTensor` into its rows."""
def __init__(self, sparse_tensor):
"""See `Dataset.from_sparse_tensor_slices()` for details."""
if not isinstance(sparse_tensor, sparse_tensor_lib.SparseTensor):
raise TypeError(f"Inv... | _SparseTensorSliceDataset |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 144915,
"end": 147259
} | class ____(GeneratedAirbyteSource):
class Unencrypted:
@public
def __init__(
self,
):
self.encryption_method = "unencrypted"
class TLSEncryptedVerifyCertificate:
@public
def __init__(self, ssl_certificate: str, key_store_password: Optional[str] = ... | Db2Source |
python | euske__pdfminer | pdfminer/pdffont.py | {
"start": 22358,
"end": 23237
} | class ____(PDFSimpleFont):
def __init__(self, rsrcmgr, spec):
firstchar = int_value(spec.get('FirstChar', 0))
#lastchar = int_value(spec.get('LastChar', 0))
widths = list_value(spec.get('Widths', [0]*256))
widths = dict((i+firstchar, w) for (i, w) in enumerate(widths))
if 'F... | PDFType3Font |
python | openai__openai-python | src/openai/types/beta/realtime/session_update_event_param.py | {
"start": 4770,
"end": 10428
} | class ____(TypedDict, total=False):
client_secret: SessionClientSecret
"""Configuration options for the generated client secret."""
input_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"]
"""The format of input audio.
Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, input audi... | Session |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.