language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | getsentry__sentry | tests/sentry/workflow_engine/migration_helpers/test_issue_alert_dual_write.py | {
"start": 4043,
"end": 12807
} | class ____(RuleMigrationHelpersTestBase):
def test_rule_snooze_updates_workflow(self) -> None:
IssueAlertMigrator(self.issue_alert, self.user.id).run()
rule_snooze = RuleSnooze.objects.create(rule=self.issue_alert)
issue_alert_workflow = AlertRuleWorkflow.objects.get(rule_id=self.issue_aler... | IssueAlertDualWriteUpdateTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/super2.py | {
"start": 1137,
"end": 1261
} | class ____(CChild, D):
def __init__(self, name: str, num: int) -> None:
super(C, self).__init__(name, num)
| DChild1 |
python | ray-project__ray | rllib/core/models/torch/encoder.py | {
"start": 6931,
"end": 10095
} | class ____(TorchModel, Encoder):
"""A recurrent LSTM encoder.
This encoder has...
- Zero or one tokenizers.
- One or more LSTM layers.
"""
def __init__(self, config: RecurrentEncoderConfig) -> None:
TorchModel.__init__(self, config)
# Maybe create a tokenizer
if config... | TorchLSTMEncoder |
python | sympy__sympy | sympy/physics/quantum/tests/test_operator.py | {
"start": 1056,
"end": 1147
} | class ____(Ket):
@classmethod
def default_args(self):
return ("t",)
| CustomKet |
python | apache__airflow | providers/apache/hive/src/airflow/providers/apache/hive/transfers/hive_to_samba.py | {
"start": 1301,
"end": 3003
} | class ____(BaseOperator):
"""
Execute hql code in a specific Hive database and load the results as a csv to a Samba location.
:param hql: the hql to be exported. (templated)
:param destination_filepath: the file path to where the file will be pushed onto samba
:param samba_conn_id: reference to the... | HiveToSambaOperator |
python | doocs__leetcode | lcof2/剑指 Offer II 075. 数组相对排序/Solution2.py | {
"start": 0,
"end": 354
} | class ____:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
cnt = Counter(arr1)
ans = []
for x in arr2:
ans.extend([x] * cnt[x])
cnt.pop(x)
mi, mx = min(arr1), max(arr1)
for x in range(mi, mx + 1):
ans.extend([x]... | Solution |
python | huggingface__transformers | src/transformers/models/poolformer/modeling_poolformer.py | {
"start": 11605,
"end": 12003
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
def forward(self, hidden_states):
output = self.dense(hidden_states)
return output
@auto_docstring(
custom_intro="""
PoolFormer Model tr... | PoolFormerFinalPooler |
python | ipython__ipython | IPython/terminal/shortcuts/__init__.py | {
"start": 1247,
"end": 18584
} | class ____(BaseBinding):
# while filter could be created by referencing variables directly (rather
# than created from strings), by using strings we ensure that users will
# be able to create filters in configuration (e.g. JSON) files too, which
# also benefits the documentation by enforcing human-reada... | Binding |
python | ray-project__ray | rllib/examples/learners/classes/intrinsic_curiosity_learners.py | {
"start": 1067,
"end": 3664
} | class ____(PPOTorchLearner):
def build(self) -> None:
super().build()
add_intrinsic_curiosity_connectors(self)
def add_intrinsic_curiosity_connectors(torch_learner: TorchLearner) -> None:
"""Adds two connector pieces to the Learner pipeline, needed for ICM training.
- The `AddNextObservat... | PPOTorchLearnerWithCuriosity |
python | walkccc__LeetCode | solutions/2815. Max Pair Sum in an Array/2815.py | {
"start": 0,
"end": 518
} | class ____:
def maxSum(self, nums: list[int]) -> int:
ans = 0
# maxNum[i] := the maximum num we met so far with the maximum digit i
maxNum = [0] * 10
def getMaxDigit(num: int) -> int:
maxDigit = 0
while num > 0:
maxDigit = max(maxDigit, num % 10)
num //= 10
return ma... | Solution |
python | conda__conda | conda/plugins/prefix_data_loaders/pypi/pkg_format.py | {
"start": 2127,
"end": 15087
} | class ____:
"""Base object describing a python distribution based on path to anchor file."""
MANIFEST_FILES = () # Only one is used, but many names available
REQUIRES_FILES = () # Only one is used, but many names available
MANDATORY_FILES = ()
ENTRY_POINTS_FILES = ("entry_points.txt",)
@stat... | PythonDistribution |
python | huggingface__transformers | tests/models/lightglue/test_modeling_lightglue.py | {
"start": 4443,
"end": 11984
} | class ____(ModelTesterMixin, unittest.TestCase):
all_model_classes = (LightGlueForKeypointMatching,) if is_torch_available() else ()
all_generative_model_classes = () if is_torch_available() else ()
test_resize_embeddings = False
has_attentions = True
def setUp(self):
self.model_tester = L... | LightGlueModelTest |
python | django__django | django/contrib/auth/management/commands/createsuperuser.py | {
"start": 514,
"end": 598
} | class ____(Exception):
pass
PASSWORD_FIELD = "password"
| NotRunningInTTYException |
python | scikit-learn__scikit-learn | sklearn/decomposition/_nmf.py | {
"start": 36004,
"end": 42285
} | class ____(ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator, ABC):
"""Base class for NMF and MiniBatchNMF."""
_parameter_constraints: dict = {
"n_components": [
Interval(Integral, 1, None, closed="left"),
None,
StrOptions({"auto"}),
],
... | _BaseNMF |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1408009,
"end": 1408307
} | class ____(
sgqlc.types.Type, Node, AuditEntry, OrganizationAuditEntryData, RepositoryAuditEntryData
):
"""Audit log entry for a repo.config.enable_sockpuppet_disallowed
event.
"""
__schema__ = github_schema
__field_names__ = ()
| RepoConfigEnableSockpuppetDisallowedAuditEntry |
python | airbytehq__airbyte | airbyte-ci/connectors/connectors_qa/tests/unit_tests/test_checks/test_packaging.py | {
"start": 216,
"end": 2206
} | class ____:
def test_fail_when_pyproject_toml_file_does_not_exist(self, tmp_path, mocker):
# Arrange
connector = mocker.MagicMock(code_directory=tmp_path)
# Act
result = packaging.CheckConnectorUsesPoetry()._run(connector)
# Assert
assert result.status == CheckStatu... | TestCheckConnectorUsesPoetry |
python | plotly__plotly.py | plotly/graph_objs/scatter/_error_y.py | {
"start": 233,
"end": 14387
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter"
_path_str = "scatter.error_y"
_valid_props = {
"array",
"arrayminus",
"arrayminussrc",
"arraysrc",
"color",
"symmetric",
"thickness",
"traceref",
"tracerefminus",
... | ErrorY |
python | kamyu104__LeetCode-Solutions | Python/minimum-number-of-work-sessions-to-finish-the-tasks.py | {
"start": 874,
"end": 1798
} | class ____(object):
def minSessions(self, tasks, sessionTime):
"""
:type tasks: List[int]
:type sessionTime: int
:rtype: int
"""
# dp[mask][0]: min number of sessions by choosing tasks in mask bitset
# dp[mask][1]: min used time of last session by choosing tas... | Solution2 |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1264258,
"end": 1264438
} | class ____(VegaLiteSchema):
"""StepFor schema wrapper."""
_schema = {"$ref": "#/definitions/StepFor"}
def __init__(self, *args):
super().__init__(*args)
| StepFor |
python | python-pillow__Pillow | Tests/test_font_pcf_charsets.py | {
"start": 338,
"end": 3385
} | class ____(TypedDict):
glyph_count: int
message: str
image1: str
charsets: dict[str, Charset] = {
"iso8859-1": {
"glyph_count": 223,
"message": "hello, world",
"image1": "Tests/images/test_draw_pbm_ter_en_target.png",
},
"iso8859-2": {
"glyph_count": 223,
... | Charset |
python | jazzband__django-simple-history | simple_history/tests/tests/test_models.py | {
"start": 78634,
"end": 80790
} | class ____(TestCase):
def setUp(self):
self.model = PollWithManyToManyWithIPAddress
self.places = (
Place.objects.create(name="London"),
Place.objects.create(name="Paris"),
)
self.poll = self.model.objects.create(question="what's up?", pub_date=today)
... | ManyToManyWithSignalsTest |
python | weaviate__weaviate-python-client | weaviate/collections/batch/base.py | {
"start": 5676,
"end": 5764
} | class ____:
batch_size: int
concurrent_requests: int
@dataclass
| _FixedSizeBatching |
python | google__pytype | pytype/pytd/pytd.py | {
"start": 11832,
"end": 11911
} | class ____(Node):
"""ParamSpec.args special form."""
name: str
| ParamSpecArgs |
python | optuna__optuna | optuna/importance/_ped_anova/evaluator.py | {
"start": 739,
"end": 2393
} | class ____:
def __init__(
self,
quantile: float,
is_lower_better: bool,
min_n_top_trials: int,
target: Callable[[FrozenTrial], float] | None,
):
assert 0 <= quantile <= 1, "quantile must be in [0, 1]."
assert min_n_top_trials > 0, "min_n_top_trials must be... | _QuantileFilter |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 166172,
"end": 166889
} | class ____(sgqlc.types.Input):
"""Parameters to be used for the committer_email_pattern rule"""
__schema__ = github_schema
__field_names__ = ("name", "negate", "operator", "pattern")
name = sgqlc.types.Field(String, graphql_name="name")
"""How this rule will appear to users."""
negate = sgqlc.... | CommitterEmailPatternParametersInput |
python | huggingface__transformers | examples/modular-transformers/configuration_my_new_model.py | {
"start": 723,
"end": 12281
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`MyNewModelModel`]. It is used to instantiate an MyNewModel
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a simila... | MyNewModelConfig |
python | realpython__materials | queue/src/async_queues.py | {
"start": 204,
"end": 2672
} | class ____(NamedTuple):
url: str
depth: int = 1
def __lt__(self, other):
if isinstance(other, Job):
return len(self.url) < len(other.url)
async def main(args):
session = aiohttp.ClientSession()
try:
links = Counter()
queue = asyncio.Queue()
# queue = as... | Job |
python | pypa__setuptools | setuptools/_vendor/backports/tarfile/__init__.py | {
"start": 24427,
"end": 24606
} | class ____(FilterError):
def __init__(self, tarinfo):
self.tarinfo = tarinfo
super().__init__(f'{tarinfo.name!r} is a link to an absolute path')
| AbsoluteLinkError |
python | pytorch__pytorch | torch/_inductor/codegen/cpp_wrapper_mps.py | {
"start": 325,
"end": 12297
} | class ____(CppWrapperGpu):
"""
Generates cpp wrapper for running on MPS and calls metal kernels
"""
def __init__(self) -> None:
super().__init__()
self._used_kernel_names: OrderedSet[str] = OrderedSet()
self._lambda_counter: int = 0
@staticmethod
def create(
is_... | CppWrapperMps |
python | PyCQA__pylint | tests/functional/ext/docparams/raise/missing_raises_doc_Google.py | {
"start": 3866,
"end": 4551
} | class ____:
"""test_finds_missing_raises_from_setter_google_2
Example of a setter having missing raises documentation in
its own Google style docstring of the property.
"""
@property
def foo_method(self):
"""int: docstring ...
Raises:
RuntimeError: Always
""... | Foo |
python | ansible__ansible | lib/ansible/_internal/_templating/_engine.py | {
"start": 2261,
"end": 2734
} | class ____:
DEFAULT: t.ClassVar[t.Self]
value_for_omit: object = Omit
escape_backslashes: bool = True
preserve_trailing_newlines: bool = True
# DTFIX-FUTURE: these aren't really overrides anymore, rename the dataclass and this field
# also mention in docstring this has no effect ... | TemplateOptions |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/managed_kafka.py | {
"start": 22505,
"end": 25978
} | class ____(ManagedKafkaBaseOperator):
"""
Create a new topic in a given project and location.
: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: Req... | ManagedKafkaCreateTopicOperator |
python | google__pytype | pytype/abstract/abstract_test.py | {
"start": 48689,
"end": 50462
} | class ____(AbstractTestBase):
"""Tests for abstract.function.Signature."""
def test_prepend_to_paramspec(self):
paramspec = abstract.ParamSpec("P", self._ctx)
# Callable[P, Any]
in_sig = function.Signature(
name="f",
param_names=("x",),
posonly_count=0,
varargs_name=None... | SignatureTest |
python | jazzband__django-oauth-toolkit | tests/test_authorization_code.py | {
"start": 28637,
"end": 71967
} | class ____(BaseAuthorizationCodeTokenView):
def test_basic_auth(self):
"""
Request an access token using basic authentication for client authentication
"""
self.client.login(username="test_user", password="123456")
authorization_code = self.get_auth()
token_request_d... | TestAuthorizationCodeTokenView |
python | conda__conda | conda/common/configuration.py | {
"start": 32937,
"end": 35992
} | class ____(metaclass=ABCMeta):
# (type) describes the type of parameter
_type = None
# (Parameter or type) if the Parameter is holds a collection, describes the element held in
# the collection. if not, describes the primitive type held by the Parameter.
_element_type = None
def __init__(self, ... | Parameter |
python | pallets__itsdangerous | src/itsdangerous/exc.py | {
"start": 1788,
"end": 2561
} | class ____(BadSignature):
"""Raised if a signed header is invalid in some form. This only
happens for serializers that have a header that goes with the
signature.
.. versionadded:: 0.24
"""
def __init__(
self,
message: str,
payload: t.Any | None = None,
header: ... | BadHeader |
python | tensorflow__tensorflow | tensorflow/python/distribute/test_util_test.py | {
"start": 3124,
"end": 4343
} | class ____(test.TestCase):
def test1(self):
@def_function.function
def f():
a = array_ops.identity(1., name='a')
b = a + 1
c = array_ops.identity(2., name='c')
d = array_ops.identity(a + c, name='d')
with ops.control_dependencies([b]):
e = array_ops.identity(3., name='e... | AssertSequentailExecutionTest |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_container.py | {
"start": 250,
"end": 522
} | class ____(BaseModel):
id: str
"""Identifier for the container used in this request"""
expires_at: datetime
"""The time at which the container will expire."""
skills: Optional[List[BetaSkill]] = None
"""Skills loaded in the container"""
| BetaContainer |
python | getsentry__sentry | tests/sentry/api/serializers/test_release.py | {
"start": 1240,
"end": 36915
} | class ____(TestCase, SnubaTestCase):
def test_simple(self) -> None:
user = self.create_user()
project = self.create_project()
project2 = self.create_project(organization=project.organization)
release_version = uuid4().hex
release = Release.objects.create(
organiz... | ReleaseSerializerTest |
python | pallets__click | src/click/core.py | {
"start": 57885,
"end": 74961
} | class ____(Command):
"""A group is a command that nests other commands (or more groups).
:param name: The name of the group command.
:param commands: Map names to :class:`Command` objects. Can be a list, which
will use :attr:`Command.name` as the keys.
:param invoke_without_command: Invoke the ... | Group |
python | walkccc__LeetCode | solutions/3332. Maximum Points Tourist Can Earn/3332.py | {
"start": 0,
"end": 657
} | class ____:
def maxScore(
self,
n: int,
k: int,
stayScore: list[list[int]],
travelScore: list[list[int]]
) -> int:
# dp[i][j] := the maximum score after i days being at city j
dp = [[0] * n for _ in range(k + 1)]
for i in range(1, k + 1):
for dest in range(n):
... | Solution |
python | tiangolo__fastapi | scripts/mkdocs_hooks.py | {
"start": 1034,
"end": 5721
} | class ____(File):
pass
def on_config(config: MkDocsConfig, **kwargs: Any) -> MkDocsConfig:
available_langs = get_mkdocs_material_langs()
dir_path = Path(config.docs_dir)
lang = dir_path.parent.name
if lang in available_langs:
config.theme["language"] = lang
if not (config.site_url or "... | EnFile |
python | pytorch__pytorch | test/jit/test_backends.py | {
"start": 5202,
"end": 6847
} | class ____(JitBackendTestCase):
"""
Tests for BasicModule with a backend that is not available.
Fundamentally:
* _jit_to_backend is successful.
* Execution fails with an exception.
* Saving is successful.
* Loading fails with an exception.
"""
def setUp(self):
super(... | BasicModuleUnavailableTest |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/tool_call_limit.py | {
"start": 3679,
"end": 4892
} | class ____(Exception):
"""Exception raised when tool call limits are exceeded.
This exception is raised when the configured exit behavior is `'error'` and either
the thread or run tool call limit has been exceeded.
"""
def __init__(
self,
thread_count: int,
run_count: int,
... | ToolCallLimitExceededError |
python | tensorflow__tensorflow | tensorflow/python/ops/init_ops_v2.py | {
"start": 18448,
"end": 22952
} | class ____(Initializer):
"""Initializer capable of adapting its scale to the shape of weights tensors.
Initializers allow you to pre-specify an initialization strategy, encoded in
the Initializer object, without knowing the shape and dtype of the variable
being initialized.
With `distribution="truncated_nor... | VarianceScaling |
python | scipy__scipy | scipy/spatial/tests/test_kdtree.py | {
"start": 5580,
"end": 5743
} | class ____(_Test_small):
def setup_method(self):
super().setup_method()
self.kdtree = self.kdtree_type(self.data, leafsize=1)
| _Test_small_nonleaf |
python | fastapi__sqlmodel | docs_src/tutorial/fastapi/app_testing/tutorial001_py310/main.py | {
"start": 267,
"end": 362
} | class ____(HeroBase, table=True):
id: int | None = Field(default=None, primary_key=True)
| Hero |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-rki-covid/source_rki_covid/source.py | {
"start": 16757,
"end": 17195
} | class ____(RkiCovidStream, ABC):
def parse_response(self, response: requests.Response, **kwargs) -> Iterable[Mapping]:
if response.json().get("data"):
for key, value in response.json().get("data").items():
for record in value.get("history"):
record.update({"na... | ByStateRkiCovidStream |
python | tensorflow__tensorflow | tensorflow/python/data/ops/load_op.py | {
"start": 6094,
"end": 7087
} | class ____(dataset_ops.DatasetSource):
"""A dataset that loads previously saved dataset."""
def __init__(
self,
path: str,
element_spec: Any,
compression: str,
reader_func: Callable[[dataset_ops.Dataset], dataset_ops.Dataset]):
self._path = path
self._element_spec = element_sp... | _LoadDataset |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/writeonly.py | {
"start": 18443,
"end": 22635
} | class ____(_AbstractCollectionWriter[_T]):
"""Write-only collection which can synchronize changes into the
attribute event system.
The :class:`.WriteOnlyCollection` is used in a mapping by
using the ``"write_only"`` lazy loading strategy with
:func:`_orm.relationship`. For background on this co... | WriteOnlyCollection |
python | mlflow__mlflow | mlflow/genai/label_schemas/label_schemas.py | {
"start": 3875,
"end": 4720
} | class ____(InputType):
"""A free-form text box for collecting assessments from stakeholders.
.. note::
This functionality is only available in Databricks. Please run
`pip install mlflow[databricks]` to use it.
"""
max_length: int | None = None
"""Maximum character length for the te... | InputText |
python | huggingface__transformers | src/transformers/models/blenderbot_small/modeling_blenderbot_small.py | {
"start": 4439,
"end": 10176
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
embed_dim: int,
num_heads: int,
dropout: float = 0.0,
is_decoder: bool = False,
bias: bool = True,
is_causal: bool = False,
config: Opti... | BlenderbotSmallAttention |
python | huggingface__transformers | tests/models/mobilebert/test_modeling_mobilebert.py | {
"start": 1554,
"end": 10667
} | class ____:
def __init__(
self,
parent,
batch_size=13,
seq_length=7,
is_training=True,
use_input_mask=True,
use_token_type_ids=True,
use_labels=True,
vocab_size=99,
hidden_size=64,
embedding_size=32,
num_hidden_layers=2,... | MobileBertModelTester |
python | pydantic__pydantic | tests/mypy/outputs/mypy-plugin-strict_ini/plugin_fail.py | {
"start": 2326,
"end": 2599
} | class ____(BaseModel):
model_config = ConfigDict(from_attributes=list) # type: ignore[typeddict-item]
# MYPY: error: Invalid value for "Config.from_attributes" [pydantic-config]
# MYPY: note: Error code "pydantic-config" not covered by "type: ignore" comment
| BadConfig2 |
python | keras-team__keras | keras/src/layers/core/identity_test.py | {
"start": 145,
"end": 1125
} | class ____(testing.TestCase):
@parameterized.named_parameters(
[
{"testcase_name": "dense", "sparse": False},
{"testcase_name": "sparse", "sparse": True},
]
)
@pytest.mark.requires_trainable_backend
def test_identity_basics(self, sparse):
if sparse and not... | IdentityTest |
python | Netflix__metaflow | metaflow/tutorials/05-hello-cloud/hello-cloud.py | {
"start": 57,
"end": 1596
} | class ____(FlowSpec):
"""
A flow where Metaflow prints 'Metaflow says Hi from the cloud!'
Run this flow to validate your Kubernetes configuration.
"""
@step
def start(self):
"""
The 'start' step is a regular step, so runs locally on the machine from
which the flow is e... | HelloCloudFlow |
python | pallets__flask | src/flask/testing.py | {
"start": 642,
"end": 3374
} | class ____(werkzeug.test.EnvironBuilder):
"""An :class:`~werkzeug.test.EnvironBuilder`, that takes defaults from the
application.
:param app: The Flask application to configure the environment from.
:param path: URL path being requested.
:param base_url: Base URL where the app is being served, whic... | EnvironBuilder |
python | numba__numba | setup.py | {
"start": 1938,
"end": 16996
} | class ____(build_ext):
user_options = build_ext.user_options + numba_be_user_options
boolean_options = build_ext.boolean_options + ['werror', 'wall', 'noopt']
def initialize_options(self):
super().initialize_options()
self.werror = 0
self.wall = 0
self.noopt = 0
def ru... | NumbaBuildExt |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 68724,
"end": 68913
} | class ____(BaseModel, extra="forbid"):
"""
Full-text phrase match of the string.
"""
phrase: str = Field(..., description="Full-text phrase match of the string.")
| MatchPhrase |
python | django__django | tests/migrations/test_migrations_no_changes/0003_third.py | {
"start": 43,
"end": 1256
} | class ____(migrations.Migration):
dependencies = [
("migrations", "0002_second"),
]
operations = [
migrations.CreateModel(
name="ModelWithCustomBase",
fields=[
(
"id",
models.BigAutoField(
... | Migration |
python | crytic__slither | slither/detectors/abstract_detector.py | {
"start": 652,
"end": 1921
} | class ____(ComparableEnum):
HIGH = 0
MEDIUM = 1
LOW = 2
INFORMATIONAL = 3
OPTIMIZATION = 4
UNIMPLEMENTED = 999
classification_colors: Dict[DetectorClassification, Callable[[str], str]] = {
DetectorClassification.INFORMATIONAL: green,
DetectorClassification.OPTIMIZATION: green,
Det... | DetectorClassification |
python | ray-project__ray | python/ray/util/client/server/server.py | {
"start": 3431,
"end": 38964
} | class ____(ray_client_pb2_grpc.RayletDriverServicer):
def __init__(self, ray_connect_handler: Callable):
"""Construct a raylet service
Args:
ray_connect_handler: Function to connect to ray cluster
"""
# Stores client_id -> (ref_id -> ObjectRef)
self.object_refs: D... | RayletServicer |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_alias.py | {
"start": 1470,
"end": 2304
} | class ____:
def test_create_default(self) -> None:
alias = bcpa.DeprecatedAlias("width", since=(3, 1, 0), help="Object's width")
assert alias.aliased_name == "width"
assert alias.since == (3, 1, 0)
assert alias.help == "Object's width"
#----------------------------------------------... | Test_DeprecatedAlias |
python | ray-project__ray | doc/source/tune/doc_code/trial_checkpoint.py | {
"start": 2142,
"end": 4409
} | class ____:
def state_dict(self) -> dict:
return {}
def load_state_dict(self, state_dict):
pass
# __function_api_checkpointing_from_dir_start__
import os
import tempfile
from ray import tune
from ray.tune import Checkpoint
def train_func(config):
start = 1
my_model = MyModel()
... | MyModel |
python | django__django | tests/admin_docs/models.py | {
"start": 312,
"end": 773
} | class ____(models.Model):
"""
Links with different link text.
This is a line with tag :tag:`extends <built_in-extends>`
This is a line with model :model:`Family <myapp.Family>`
This is a line with view :view:`Index <myapp.views.Index>`
This is a line with template :template:`index template <Ind... | Family |
python | doocs__leetcode | solution/1700-1799/1730.Shortest Path to Get Food/Solution.py | {
"start": 0,
"end": 752
} | class ____:
def getFood(self, grid: List[List[str]]) -> int:
m, n = len(grid), len(grid[0])
i, j = next((i, j) for i in range(m) for j in range(n) if grid[i][j] == '*')
q = deque([(i, j)])
dirs = (-1, 0, 1, 0, -1)
ans = 0
while q:
ans += 1
for ... | Solution |
python | huggingface__transformers | src/transformers/models/efficientnet/modeling_efficientnet.py | {
"start": 15647,
"end": 17997
} | class ____(EfficientNetPreTrainedModel):
def __init__(self, config: EfficientNetConfig):
super().__init__(config)
self.config = config
self.embeddings = EfficientNetEmbeddings(config)
self.encoder = EfficientNetEncoder(config)
# Final pooling layer
if config.pooling_... | EfficientNetModel |
python | allegroai__clearml | clearml/backend_api/services/v2_13/models.py | {
"start": 59548,
"end": 61400
} | class ____(Response):
"""
Response of models.edit endpoint.
:param updated: Number of models updated (0 or 1)
:type updated: int
:param fields: Updated fields names and values
:type fields: dict
"""
_service = "models"
_action = "edit"
_version = "2.13"
_schema = {
... | EditResponse |
python | joke2k__faker | tests/providers/test_date_time.py | {
"start": 31280,
"end": 31393
} | class ____(TestFilPh):
def setup_faker(self):
self.fake = Faker("tl_PH")
Faker.seed(0)
| TestTlPh |
python | pydantic__pydantic | pydantic-core/tests/validators/test_uuid.py | {
"start": 183,
"end": 12986
} | class ____(str): ...
@pytest.mark.parametrize(
'input_value,expected',
[
# Valid UUIDs
('12345678-1234-1234-1234-567812345678', UUID('12345678-1234-1234-1234-567812345678')),
('550e8400-e29b-41d4-a716-446655440000', UUID('550e8400-e29b-41d4-a716-446655440000')),
('f47ac10b-58cc... | MyStr |
python | pytorch__pytorch | test/distributed/_composable/fsdp/test_fully_shard_compile.py | {
"start": 3913,
"end": 47417
} | class ____(FSDPTest):
fake_pg = not at_least_x_gpu(2)
# This method is an override of the base class.
# Tests in this class requires bf16 support, so SM arch must be 80 or
# higher.
def skipTestForOldSm(self):
# Assumption: This test class is only run on GPU. See `HAS_GPU` check at
... | TestFullyShardCompile |
python | tornadoweb__tornado | tornado/test/httpclient_test.py | {
"start": 30791,
"end": 31110
} | class ____(unittest.TestCase):
def test_str(self):
response = HTTPResponse( # type: ignore
HTTPRequest("http://example.com"), 200, buffer=BytesIO()
)
s = str(response)
self.assertTrue(s.startswith("HTTPResponse("))
self.assertIn("code=200", s)
| HTTPResponseTestCase |
python | tiangolo__fastapi | tests/test_generate_unique_id_function.py | {
"start": 493,
"end": 68299
} | class ____(BaseModel):
title: str
description: str
def test_top_level_generate_unique_id():
app = FastAPI(generate_unique_id_function=custom_generate_unique_id)
router = APIRouter()
@app.post("/", response_model=List[Item], responses={404: {"model": List[Message]}})
def post_root(item1: Item,... | Message |
python | ansible__ansible | test/units/plugins/action/test_gather_facts.py | {
"start": 1121,
"end": 3775
} | class ____(unittest.TestCase):
task = MagicMock(Task)
play_context = MagicMock()
play_context.check_mode = False
connection = MagicMock()
fake_loader = DictDataLoader({
})
templar = TemplateEngine(loader=fake_loader)
def setUp(self):
pass
def tearDown(self):
pass
... | TestNetworkFacts |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/layout/containers.py | {
"start": 14705,
"end": 23903
} | class ____(_Split):
"""
Several layouts, one stacked left/right of the other. ::
+---------+----------+
| | |
| | |
+---------+----------+
By default, this doesn't display a vertical line between the children, but
if this is something y... | VSplit |
python | getsentry__sentry | tests/apidocs/endpoints/teams/test_index.py | {
"start": 136,
"end": 856
} | class ____(APIDocsTestCase):
def setUp(self) -> None:
self.create_team(organization=self.organization)
self.url = reverse(
"sentry-api-0-organization-teams",
kwargs={"organization_id_or_slug": self.organization.slug},
)
self.login_as(user=self.user)
def... | TeamsIndexDocs |
python | kamyu104__LeetCode-Solutions | Python/sum-of-imbalance-numbers-of-all-subarrays.py | {
"start": 850,
"end": 1375
} | class ____(object):
def sumImbalanceNumbers(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 0
for right in xrange(len(nums)):
lookup = {nums[right]}
curr = 0
for left in reversed(xrange(right)):
if nu... | Solution2 |
python | django__django | django/views/generic/base.py | {
"start": 5925,
"end": 7224
} | class ____:
"""A mixin that can be used to render a template."""
template_name = None
template_engine = None
response_class = TemplateResponse
content_type = None
def render_to_response(self, context, **response_kwargs):
"""
Return a response, using the `response_class` for thi... | TemplateResponseMixin |
python | Farama-Foundation__Gymnasium | gymnasium/wrappers/vector/array_conversion.py | {
"start": 489,
"end": 5072
} | class ____(VectorWrapper, gym.utils.RecordConstructorArgs):
"""Wraps a vector environment returning Array API compatible arrays so that it can be interacted with through a specific framework.
Popular Array API frameworks include ``numpy``, ``torch``, ``jax.numpy``, ``cupy`` etc. With this wrapper, you can conv... | ArrayConversion |
python | pytorch__pytorch | torch/nn/modules/activation.py | {
"start": 791,
"end": 2409
} | class ____(Module):
r"""Thresholds each element of the input Tensor.
Threshold is defined as:
.. math::
y =
\begin{cases}
x, &\text{ if } x > \text{threshold} \\
\text{value}, &\text{ otherwise }
\end{cases}
Args:
threshold: The value to threshold at
... | Threshold |
python | sphinx-doc__sphinx | sphinx/util/logging.py | {
"start": 18106,
"end": 19746
} | class ____:
"""Stream writer storing last 10 messages in memory to save trackback"""
def __init__(self, app: Sphinx, stream: IO[str]) -> None:
self._app = app
def write(self, data: str) -> None:
self._app.messagelog.append(data)
def setup(
app: Sphinx, status: IO[str], warning: IO[st... | LastMessagesWriter |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 850780,
"end": 851239
} | class ____(sgqlc.types.Type):
"""The value of a milestone field in a Project item."""
__schema__ = github_schema
__field_names__ = ("field", "milestone")
field = sgqlc.types.Field(sgqlc.types.non_null("ProjectV2FieldConfiguration"), graphql_name="field")
"""The field that contains this value."""
... | ProjectV2ItemFieldMilestoneValue |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/unit_tests/integration/request_builder.py | {
"start": 1014,
"end": 5471
} | class ____:
@classmethod
def get_ad_endpoint(cls, access_token: str, account_id: str) -> RequestBuilder:
return cls(access_token=access_token, resource="ads").with_account_id(account_id)
@classmethod
def get_campaign_endpoint(cls, access_token: str, account_id: str) -> RequestBuilder:
r... | RequestBuilder |
python | tensorflow__tensorflow | tensorflow/python/framework/device.py | {
"start": 2962,
"end": 5961
} | class ____(object):
"""Wraps a device specification (DeviceSpec or str) with merge functionality.
When called, this class will merge a node_def with its own spec. It also
exposes a `shortcut_string_merge` method which can significantly improve
performance of device placement.
"""
__slots__ = ["_spec"]
... | MergeDevice |
python | kamyu104__LeetCode-Solutions | Python/largest-1-bordered-square.py | {
"start": 33,
"end": 930
} | class ____(object):
def largest1BorderedSquare(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
top, left = [a[:] for a in grid], [a[:] for a in grid]
for i in xrange(len(grid)):
for j in xrange(len(grid[0])):
if not grid[i][j]:... | Solution |
python | PrefectHQ__prefect | tests/server/models/test_deployments.py | {
"start": 482,
"end": 15185
} | class ____:
async def test_create_deployment_succeeds(self, session, flow):
deployment = await models.deployments.create_deployment(
session=session,
deployment=schemas.core.Deployment(
name="My Deployment",
flow_id=flow.id,
parameters=... | TestCreateDeployment |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 3810,
"end": 3940
} | class ____(PydanticTypeError):
code = 'none.not_allowed'
msg_template = 'none is not an allowed value'
| NoneIsNotAllowedError |
python | Lightning-AI__lightning | src/lightning/pytorch/trainer/connectors/signal_connector.py | {
"start": 637,
"end": 1211
} | class ____:
def __init__(self, signal_handlers: Union[list[_HANDLER], _HANDLER]) -> None:
if not isinstance(signal_handlers, list):
signal_handlers = [signal_handlers]
self.signal_handlers = signal_handlers
def __call__(self, signum: _SIGNUM, frame: FrameType) -> None:
for s... | _HandlersCompose |
python | huggingface__transformers | src/transformers/models/video_llama_3/modular_video_llama_3.py | {
"start": 10470,
"end": 14304
} | class ____(SiglipAttention):
def __init__(self, config):
super().__init__(config)
self.num_key_value_groups = 1
self.scaling = self.head_dim**-0.5
self.attention_dropout = config.attention_dropout
del self.scale
del self.dropout
def forward(
self,
... | VideoLlama3VisionAttention |
python | huggingface__transformers | src/transformers/models/olmo3/modeling_olmo3.py | {
"start": 19460,
"end": 22558
} | class ____(Olmo3PreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
_tp_plan = {"lm_head": "colwise_rep"}
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
def __init__(self, config):
super().__init__(config)
self.model = Olmo3Mo... | Olmo3ForCausalLM |
python | pytorch__pytorch | test/torch_np/numpy_tests/linalg/test_linalg.py | {
"start": 23348,
"end": 23438
} | class ____(SVDHermitianCases, SVDBaseTests, TestCase):
hermitian = True
| TestSVDHermitian |
python | pypa__pip | src/pip/_internal/models/index.py | {
"start": 22,
"end": 1030
} | class ____:
"""Represents a Package Index and provides easier access to endpoints"""
__slots__ = ["url", "netloc", "simple_url", "pypi_url", "file_storage_domain"]
def __init__(self, url: str, file_storage_domain: str) -> None:
super().__init__()
self.url = url
self.netloc = urllib... | PackageIndex |
python | django__django | tests/db_functions/text/test_replace.py | {
"start": 157,
"end": 2604
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.create(name="George R. R. Martin")
Author.objects.create(name="J. R. R. Tolkien")
def test_replace_with_empty_string(self):
qs = Author.objects.annotate(
without_middlename=Replace(F("name"), Value... | ReplaceTests |
python | walkccc__LeetCode | solutions/1208. Get Equal Substrings Within Budget/1208.py | {
"start": 0,
"end": 269
} | class ____:
def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
j = 0
for i in range(len(s)):
maxCost -= abs(ord(s[i]) - ord(t[i]))
if maxCost < 0:
maxCost += abs(ord(s[j]) - ord(t[j]))
j += 1
return len(s) - j
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 860660,
"end": 861052
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field(ProjectV2SortBy, graphql_n... | ProjectV2SortByEdge |
python | scikit-image__scikit-image | src/skimage/transform/_geometric.py | {
"start": 53606,
"end": 61705
} | class ____(_GeometricTransform):
"""Piecewise affine transformation.
Control points are used to define the mapping. The transform is based on
a Delaunay triangulation of the points to form a mesh. Each triangle is
used to find a local affine transform.
Attributes
----------
affines : list ... | PiecewiseAffineTransform |
python | ansible__ansible | test/units/parsing/vault/test_vault.py | {
"start": 2794,
"end": 4529
} | class ____(unittest.TestCase):
def test(self):
vaulttext_envelope = u"""$ANSIBLE_VAULT;1.1;AES256
33363965326261303234626463623963633531343539616138316433353830356566396130353436
3562643163366231316662386565383735653432386435610a306664636137376132643732393835
633830383837303066393532343266306665393462333763... | TestParseVaulttext |
python | django__django | tests/model_fields/models.py | {
"start": 1267,
"end": 1587
} | class ____(models.Model):
CHOICES = {
"Group 1": {
1: "First",
2: "Second",
},
"Group 2": (
(3, "Third"),
(4, "Fourth"),
),
0: "Other",
5: _("translated"),
}
c = models.IntegerField(choices=CHOICES, null=True)
| Whiz |
python | jina-ai__jina | tests/docker_compose/multiprotocol-gateway/multiprotocol_gateway.py | {
"start": 308,
"end": 365
} | class ____(BaseModel):
protocol: str
| DummyResponseModel |
python | Textualize__rich | benchmarks/benchmarks.py | {
"start": 3921,
"end": 4486
} | class ____:
def setup(self):
self.console = Console(
file=StringIO(), color_system="truecolor", legacy_windows=False, width=100
)
def time_pretty(self):
pretty = Pretty(snippets.PYTHON_DICT)
self.console.print(pretty)
def time_pretty_indent_guides(self):
... | PrettySuite |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.