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 | encode__django-rest-framework | tests/test_validators.py | {
"start": 6332,
"end": 21136
} | class ____(TestCase):
def setUp(self):
self.instance = UniquenessTogetherModel.objects.create(
race_name='example',
position=1
)
UniquenessTogetherModel.objects.create(
race_name='example',
position=2
)
UniquenessTogetherModel.o... | TestUniquenessTogetherValidation |
python | ray-project__ray | python/ray/autoscaler/v2/instance_manager/node_provider.py | {
"start": 8660,
"end": 8943
} | class ____:
"""
The arguments to launch a node.
"""
# The node type to launch.
node_type: NodeType
# Number of nodes to launch.
count: int
# A unique id that identifies the request.
request_id: str
@dataclass(frozen=True)
| CloudInstanceLaunchRequest |
python | sqlalchemy__sqlalchemy | test/orm/test_deprecations.py | {
"start": 52424,
"end": 53848
} | class ____(CacheKeyFixture, _poly_fixtures._Polymorphic):
run_setup_mappers = "once"
run_inserts = None
run_deletes = None
def _stmt_20(self, *elements):
return tuple(
elem._statement_20() if isinstance(elem, sa.orm.Query) else elem
for elem in elements
)
de... | PolyCacheKeyTest |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/executor/child_process_executor.py | {
"start": 1185,
"end": 1643
} | class ____(ABC):
"""Inherit from this class in order to use this library.
The object must be picklable; instantiate it and pass it to _execute_command_in_child_process.
"""
@abstractmethod
def execute(self) -> Iterator[Union[ChildProcessEvent, "DagsterEvent"]]:
"""This method is invoked in... | ChildProcessCommand |
python | openai__openai-python | tests/test_models.py | {
"start": 437,
"end": 27204
} | class ____(BaseModel):
foo: str
@pytest.mark.parametrize("value", ["hello", 1], ids=["correct type", "mismatched"])
def test_basic(value: object) -> None:
m = BasicModel.construct(foo=value)
assert m.foo == value
def test_directly_nested_model() -> None:
class NestedModel(BaseModel):
nested:... | BasicModel |
python | spyder-ide__spyder | spyder/plugins/findinfiles/widgets/main_widget.py | {
"start": 2619,
"end": 29862
} | class ____(PluginMainWidget):
"""
Find in files main widget.
"""
# PluginMainWidget constants
ENABLE_SPINNER = True
MARGIN_TOP = AppStyle.MarginSize + 5
SHOW_MESSAGE_WHEN_EMPTY = True
IMAGE_WHEN_EMPTY = "find_empty"
MESSAGE_WHEN_EMPTY = _("Nothing searched for yet")
DESCRIPTION_... | FindInFilesWidget |
python | PyCQA__pylint | pylint/config/callback_actions.py | {
"start": 7527,
"end": 8116
} | class ____(_AccessRunObjectAction):
"""Turn on errors-only mode.
Error mode:
* disable all but error messages
* disable the 'miscellaneous' checker which can be safely deactivated in
debug
* disable reports
* do not save execution information
"""
def __call__(... | _ErrorsOnlyModeAction |
python | vyperlang__vyper | vyper/ast/pre_parser.py | {
"start": 4273,
"end": 4619
} | class ____(enum.Enum):
NOT_RUNNING = enum.auto()
START_SOON = enum.auto()
RUNNING = enum.auto()
# a simple state machine which allows us to handle loop variable annotations
# (which are rejected by the python parser due to pep-526, so we scoop up the
# tokens between `:` and `in` and parse them and add th... | ParserState |
python | pydantic__pydantic | pydantic/_internal/_decorators.py | {
"start": 5142,
"end": 6088
} | class ____:
"""A container for data from `@model_validator` so that we can access it
while building the pydantic-core schema.
Attributes:
decorator_repr: A class variable representing the decorator string, '@model_validator'.
mode: The proposed serializer mode.
"""
decorator_repr: ... | ModelValidatorDecoratorInfo |
python | python__mypy | mypy/fswatcher.py | {
"start": 309,
"end": 3985
} | class ____:
"""Watcher for file system changes among specific paths.
All file system access is performed using FileSystemCache. We
detect changed files by stat()ing them all and comparing hashes
of potentially changed files. If a file has both size and mtime
unmodified, the file is assumed to be un... | FileSystemWatcher |
python | wandb__wandb | wandb/sdk/artifacts/_generated/project_artifact_types.py | {
"start": 277,
"end": 369
} | class ____(GQLResult):
project: Optional[ProjectArtifactTypesProject]
| ProjectArtifactTypes |
python | facebookresearch__faiss | tests/test_extra_distances.py | {
"start": 436,
"end": 8242
} | class ____(unittest.TestCase):
""" check wrt. the scipy implementation """
def make_example(self):
rs = np.random.RandomState(123)
x = rs.rand(5, 32).astype('float32')
y = rs.rand(3, 32).astype('float32')
return x, y
def run_simple_dis_test(self, ref_func, metric_type):
... | TestExtraDistances |
python | langchain-ai__langchain | libs/langchain/langchain_classic/agents/agent_toolkits/vectorstore/toolkit.py | {
"start": 309,
"end": 553
} | class ____(BaseModel):
"""Information about a `VectorStore`."""
vectorstore: VectorStore = Field(exclude=True)
name: str
description: str
model_config = ConfigDict(
arbitrary_types_allowed=True,
)
| VectorStoreInfo |
python | ansible__ansible | test/lib/ansible_test/_internal/completion.py | {
"start": 978,
"end": 1289
} | class ____(metaclass=abc.ABCMeta):
"""Base class for completion configuration."""
name: str
@property
@abc.abstractmethod
def is_default(self) -> bool:
"""True if the completion entry is only used for defaults, otherwise False."""
@dataclasses.dataclass(frozen=True)
| CompletionConfig |
python | django-extensions__django-extensions | tests/management/commands/test_show_urls.py | {
"start": 1972,
"end": 7700
} | class ____(TestCase):
@patch("sys.stdout", new_callable=StringIO)
def test_should_show_urls_unsorted_but_same_order_as_found_in_url_patterns(
self, m_stdout
):
call_command("show_urls", "-u", verbosity=3)
lines = m_stdout.getvalue().splitlines()
self.assertIn(
"/... | ShowUrlsTests |
python | jina-ai__jina | tests/integration/reduce/test_reduce.py | {
"start": 3671,
"end": 3834
} | class ____(Executor):
@requests
def endpoint(self, docs: DocumentArray, **kwargs):
for doc in docs:
doc.embedding = np.zeros(3)
| Executor3 |
python | tensorflow__tensorflow | tensorflow/python/framework/error_interpolation_test.py | {
"start": 11323,
"end": 11924
} | class ____(test.TestCase):
def testAllowsUnitTests(self):
self.assertFalse(
error_interpolation._is_framework_filename(
error_interpolation._FRAMEWORK_PATH_PREFIXES[0] + "foobar_test.py"
)
)
def testFrameworkPythonFile(self):
self.assertTrue(
error_interpolation._is... | IsFrameworkFilenameTest |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_image51.py | {
"start": 381,
"end": 1735
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("image51.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workbook(... | TestCompareXLSXFiles |
python | bokeh__bokeh | src/bokeh/core/serialization.py | {
"start": 2546,
"end": 2653
} | class ____(TypedDict):
type: Literal["number"]
value: Literal["nan", "-inf", "+inf"] | float
| NumberRep |
python | pola-rs__polars | py-polars/src/polars/_utils/cache.py | {
"start": 561,
"end": 5927
} | class ____(MutableMapping[K, V]):
def __init__(self, maxsize: int) -> None:
"""
Initialize an LRU (Least Recently Used) cache with a specified maximum size.
Parameters
----------
maxsize : int
The maximum number of items the cache can hold.
Examples
... | LRUCache |
python | ipython__ipython | tests/test_pretty.py | {
"start": 1127,
"end": 1176
} | class ____(Dummy1):
_repr_pretty_ = None
| Dummy2 |
python | jazzband__django-oauth-toolkit | oauth2_provider/migrations/0003_auto_20201211_1314.py | {
"start": 92,
"end": 386
} | class ____(migrations.Migration):
dependencies = [
('oauth2_provider', '0002_auto_20190406_1805'),
]
operations = [
migrations.AlterField(
model_name='grant',
name='redirect_uri',
field=models.TextField(),
),
]
| Migration |
python | google__pytype | pytype/overlays/flax_overlay.py | {
"start": 3590,
"end": 5247
} | class ____(abstract.PyTDClass):
"""Construct a dataclass for any class inheriting from Module."""
IMPLICIT_FIELDS = ("name", "parent")
# 'Module' can also be imported through an alias in flax.linen, but we always
# want to use its full, unaliased name.
_MODULE = "flax.linen.module"
def __init__(self, ctx... | Module |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/cache_key.py | {
"start": 1454,
"end": 1667
} | class ____(enum.Enum):
NO_CACHE = 0
PARAMS = 1
NO_CACHE: Final = CacheConst.NO_CACHE
_CacheKeyTraversalType = Union[
"_TraverseInternalsType", Literal[CacheConst.NO_CACHE], Literal[None]
]
| CacheConst |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/uninitializedVariable2.py | {
"start": 428,
"end": 466
} | class ____(Abstract1):
pass
@final
| B |
python | conda__conda | conda/cli/actions.py | {
"start": 640,
"end": 1558
} | class ____(Action):
"""
A derivative of _AppendConstAction and Python 3.8's _ExtendAction
"""
def __init__(
self,
option_strings,
dest,
const,
default=None,
type=None,
choices=None,
required=False,
help=None,
metavar=None,
... | ExtendConstAction |
python | apache__avro | lang/py/avro/compatibility.py | {
"start": 1491,
"end": 1646
} | class ____(Enum):
compatible = "compatible"
incompatible = "incompatible"
recursion_in_progress = "recursion_in_progress"
| SchemaCompatibilityType |
python | tensorflow__tensorflow | tensorflow/core/function/trace_type/trace_type_builder.py | {
"start": 4122,
"end": 7512
} | class ____(trace.CastContext):
"""Default casting behaviors."""
def __init__(self, allow_specs=False):
self._allow_specs = allow_specs
@property
def allow_specs(self) -> bool:
"""Allow TypeSpecs to be casted (instead of the actual CompositeTensors)."""
# Public APIs like get_concrete_function allo... | InternalCastContext |
python | apache__airflow | providers/google/tests/unit/google/suite/hooks/test_sheets.py | {
"start": 1535,
"end": 14352
} | class ____:
def setup_method(self):
with mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__",
new=mock_base_gcp_hook_default_project_id,
):
self.hook = GSheetsHook(gcp_conn_id=GCP_CONN_ID)
@mock.patch("airflow.providers.goo... | TestGSheetsHook |
python | pytorch__pytorch | test/dynamo/test_autograd_function.py | {
"start": 4802,
"end": 4922
} | class ____(torch.nn.Module):
def forward(self, foo):
return CustomFuncSaveForBwd().apply(foo)
| SaveForBwdModule |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-gitbook/tests/test_simple_gitbook_reader.py | {
"start": 390,
"end": 2428
} | class ____:
"""Mock class that simulates the GitBook API client."""
def __init__(self, api_token: str, api_url: Optional[str] = None):
self.pages_data = [
{
"id": "page1",
"title": "Getting Started",
"path": "/getting-started",
... | MockGitbookClient |
python | PyCQA__pylint | doc/data/messages/t/too-many-public-methods/bad.py | {
"start": 0,
"end": 528
} | class ____: # [too-many-public-methods]
def __init__(self):
pass
def fire_laser_beam(self):
pass
def deploy_shield(self):
pass
def launch_missile(self):
pass
def activate_super_laser(self):
pass
def summon_mothership(self):
pass
def dest... | SpaceInvaders |
python | getsentry__sentry | src/sentry/db/deletion.py | {
"start": 397,
"end": 4221
} | class ____:
def __init__(
self,
model: type[BaseModel],
project_id: int | None = None,
organization_id: int | None = None,
dtfield: str | None = None,
days: int | None = None,
order_by: str | None = None,
):
self.model = model
self.project_... | BulkDeleteQuery |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 48898,
"end": 50954
} | class ____(BaseModel, extra="forbid"):
m: Optional[int] = Field(
default=None,
description="Number of edges per node in the index graph. Larger the value - more accurate the search, more space required.",
)
ef_construct: Optional[int] = Field(
default=None,
description="Numbe... | HnswConfigDiff |
python | google__pytype | pytype/pyc/opcodes.py | {
"start": 13206,
"end": 13324
} | class ____(OpcodeWithArg): # Loads local variable number
_FLAGS = HAS_LOCAL | HAS_ARGUMENT
__slots__ = ()
| LOAD_FAST |
python | pytorch__pytorch | torch/optim/adamw.py | {
"start": 307,
"end": 7477
} | class ____(Adam):
def __init__(
self,
params: ParamsT,
lr: Union[float, Tensor] = 1e-3,
betas: tuple[Union[float, Tensor], Union[float, Tensor]] = (0.9, 0.999),
eps: float = 1e-8,
weight_decay: float = 1e-2,
amsgrad: bool = False,
*,
maximize: ... | AdamW |
python | gevent__gevent | src/gevent/_fileobjectcommon.py | {
"start": 759,
"end": 1931
} | class ____(io.TextIOWrapper):
"""
Uses TextWrapper to decode universal newlines, but returns the
results as bytes.
This is for Python 2 where the 'rU' mode did that.
"""
mode = None
def __init__(self, fobj, line_buffering):
# latin-1 has the ability to round-trip arbitrary bytes.
... | UniversalNewlineBytesWrapper |
python | doocs__leetcode | solution/1600-1699/1628.Design an Expression Tree With Evaluate Function/Solution.py | {
"start": 972,
"end": 1443
} | class ____(object):
def buildTree(self, postfix: List[str]) -> 'Node':
stk = []
for s in postfix:
node = MyNode(s)
if not s.isdigit():
node.right = stk.pop()
node.left = stk.pop()
stk.append(node)
return stk[-1]
"""
Your T... | TreeBuilder |
python | encode__django-rest-framework | tests/test_serializer_lists.py | {
"start": 287,
"end": 761
} | class ____:
"""
A mock object for testing serializer save behavior.
"""
def __init__(self, **kwargs):
self._data = kwargs
for key, value in kwargs.items():
setattr(self, key, value)
def __eq__(self, other):
if self._data.keys() != other._data.keys():
... | BasicObject |
python | chroma-core__chroma | chromadb/segment/__init__.py | {
"start": 1796,
"end": 2358
} | class ____(SegmentImplementation):
"""Embedding Metadata segment interface"""
@abstractmethod
def get_metadata(
self,
request_version_context: RequestVersionContext,
where: Optional[Where] = None,
where_document: Optional[WhereDocument] = None,
ids: Optional[Sequence... | MetadataReader |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/sensors/glue.py | {
"start": 6156,
"end": 11590
} | class ____(AwsBaseSensor[GlueDataQualityHook]):
"""
Waits for an AWS Glue data quality ruleset evaluation run to reach any of the status below.
'FAILED', 'STOPPED', 'STOPPING', 'TIMEOUT', 'SUCCEEDED'
.. seealso::
For more information on how to use this sensor, take a look at the guide:
... | GlueDataQualityRuleSetEvaluationRunSensor |
python | cython__cython | Cython/Coverage.py | {
"start": 16907,
"end": 18783
} | class ____(FileReporter):
"""
Provide detailed trace information for one source file to coverage.py.
"""
def __init__(self, c_file, source_file, rel_file_path, code, excluded_lines):
super().__init__(source_file)
self.name = rel_file_path
self.c_file = c_file
self._code =... | CythonModuleReporter |
python | jazzband__django-waffle | waffle/tests/test_testutils.py | {
"start": 11046,
"end": 11253
} | class ____(OverrideSampleOnClassTestsMixin,
TestCase):
"""
Run tests with Django TestCase
"""
@override_sample('foo', active=False)
| OverrideSampleOnClassTestCase |
python | doocs__leetcode | solution/1900-1999/1931.Painting a Grid With Three Different Colors/Solution.py | {
"start": 0,
"end": 992
} | class ____:
def colorTheGrid(self, m: int, n: int) -> int:
def f1(x: int) -> bool:
last = -1
for _ in range(m):
if x % 3 == last:
return False
last = x % 3
x //= 3
return True
def f2(x: int, y: i... | Solution |
python | getsentry__sentry | tests/flagpole/test_flagpole_eval.py | {
"start": 319,
"end": 2876
} | class ____:
"""Test get_arguments() function for parsing command line arguments and context."""
@mock.patch("flagpole.flagpole_eval.sys.argv", ["script.py", "--flag-name", "test-flag"])
def test_get_arguments_with_flag_name_only(self):
"""Test get_arguments returns correct dict with only flag name.... | TestGetArguments |
python | astropy__astropy | astropy/time/__init__.py | {
"start": 104,
"end": 1710
} | class ____(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.time`.
"""
use_fast_parser = _config.ConfigItem(
["True", "False", "force"],
"Use fast C parser for supported time strings formats, including ISO, "
"ISOT, and YearDayTime. Allowed values are the 'Fal... | Conf |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI034.py | {
"start": 7222,
"end": 7583
} | class ____(EnumMeta):
def __new__(cls) -> MetaclassInWhichSelfCannotBeUsed2: ...
def __enter__(self) -> MetaclassInWhichSelfCannotBeUsed2: ...
async def __aenter__(self) -> MetaclassInWhichSelfCannotBeUsed2: ...
def __isub__(self, other: MetaclassInWhichSelfCannotBeUsed2) -> MetaclassInWhichSelfCannotBe... | MetaclassInWhichSelfCannotBeUsed2 |
python | scrapy__scrapy | tests/test_webclient.py | {
"start": 6747,
"end": 6932
} | class ____(resource.Resource):
def render(self, request):
return b"nolength"
@pytest.mark.filterwarnings("ignore::scrapy.exceptions.ScrapyDeprecationWarning")
| NoLengthResource |
python | wandb__wandb | wandb/sdk/lib/service/service_connection.py | {
"start": 2198,
"end": 10169
} | class ____:
"""A connection to the W&B internal service process.
None of the synchronous methods may be called in an asyncio context.
"""
def __init__(
self,
asyncer: asyncio_manager.AsyncioManager,
client: ServiceClient,
proc: service_process.ServiceProcess | None,
... | ServiceConnection |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 72272,
"end": 75041
} | class ____:
def test_year_full(self):
assert self.locale.year_full(2015) == "2558"
def test_year_abbreviation(self):
assert self.locale.year_abbreviation(2015) == "58"
def test_format_relative_now(self):
result = self.locale._format_relative("ขณะนี้", "now", 0)
assert resul... | TestThaiLocale |
python | FactoryBoy__factory_boy | tests/alchemyapp/models.py | {
"start": 382,
"end": 528
} | class ____(Base):
__tablename__ = 'StandardModelTable'
id = Column(Integer(), primary_key=True)
foo = Column(Unicode(20))
| StandardModel |
python | getsentry__sentry | src/sentry/sentry_apps/services/app/model.py | {
"start": 4519,
"end": 4753
} | class ____(RpcModel):
success: bool
message: str
error_type: SentryAppErrorType | None
webhook_context: dict[str, Any] | None
public_context: dict[str, Any] | None
status_code: int | None
| RpcAlertRuleActionResult |
python | boto__boto3 | boto3/docs/collection.py | {
"start": 985,
"end": 11296
} | class ____(NestedDocumenter):
def document_collections(self, section):
collections = self._resource.meta.resource_model.collections
collections_list = []
add_resource_type_overview(
section=section,
resource_type='Collections',
description=(
... | CollectionDocumenter |
python | django__django | tests/select_related/models.py | {
"start": 855,
"end": 982
} | class ____(models.Model):
name = models.CharField(max_length=50)
phylum = models.ForeignKey(Phylum, models.CASCADE)
| Klass |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/fmt_skip/decorators.py | {
"start": 601,
"end": 761
} | class ____: # fmt: skip
pass
# Regression test for https://github.com/astral-sh/ruff/issues/7735
@decorator1
@decorator2
def foo(): # fmt: skip
pass
| Foo |
python | zarr-developers__zarr-python | src/zarr/core/dtype/wrapper.py | {
"start": 2311,
"end": 9725
} | class ____(ABC, Generic[TDType_co, TScalar_co]):
"""
Abstract base class for wrapping native array data types, e.g. numpy dtypes
Attributes
----------
dtype_cls : ClassVar[type[TDType]]
The wrapped dtype class. This is a class variable.
_zarr_v3_name : ClassVar[str]
The name giv... | ZDType |
python | dagster-io__dagster | python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/core/workspace.py | {
"start": 629,
"end": 1210
} | class ____:
# pex_tag is a string like 'deps-234y4384.pex:source-39y3474.pex' that idenfies
# the pex files to execute
pex_tag: str
# python_version determines which pex base docker image to use
# only one of PexMetadata.python_version or CodeLocationDeployData.image should be specified
python_v... | PexMetadata |
python | ray-project__ray | python/ray/serve/schema.py | {
"start": 27900,
"end": 32187
} | class ____(BaseModel):
"""
Multi-application config for deploying a list of Serve applications to the Ray
cluster.
This is the request JSON schema for the v2 REST API
`PUT "/api/serve/applications/"`.
NOTE: This config allows extra parameters to make it forward-compatible (ie
older v... | ServeDeploySchema |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/ui/dashboard.py | {
"start": 1169,
"end": 1512
} | class ____(BaseModel):
"""TaskInstance serializer for responses."""
no_status: int
removed: int
scheduled: int
queued: int
running: int
success: int
restarting: int
failed: int
up_for_retry: int
up_for_reschedule: int
upstream_failed: int
skipped: int
deferred: i... | TaskInstanceStateCount |
python | python-openxml__python-docx | src/docx/oxml/simpletypes.py | {
"start": 12785,
"end": 13019
} | class ____(XsdStringEnumeration):
"""Valid values for `w:vertAlign/@val`."""
BASELINE = "baseline"
SUPERSCRIPT = "superscript"
SUBSCRIPT = "subscript"
_members = (BASELINE, SUPERSCRIPT, SUBSCRIPT)
| ST_VerticalAlignRun |
python | getsentry__sentry | src/sentry/spans/grouping/api.py | {
"start": 147,
"end": 622
} | class ____(LookupError):
pass
def load_span_grouping_config(config: Any | None = None) -> SpanGroupingConfig:
if config is None:
config_id = DEFAULT_CONFIG_ID
else:
if "id" not in config:
raise ValueError("Malformed configuration: missing 'id'")
config_id = config["id"... | SpanGroupingConfigNotFound |
python | plotly__plotly.py | plotly/graph_objs/volume/_caps.py | {
"start": 233,
"end": 3771
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "volume"
_path_str = "volume.caps"
_valid_props = {"x", "y", "z"}
@property
def x(self):
"""
The 'x' property is an instance of X
that may be specified as:
- An instance of :class:`plotly.graph_objs.volume.cap... | Caps |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1187524,
"end": 1188169
} | class ____(sgqlc.types.Type, Node):
"""Represents a 'head_ref_restored' event on a given pull request."""
__schema__ = github_schema
__field_names__ = ("actor", "created_at", "pull_request")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
"""Identifies the actor who performed the event."""
... | HeadRefRestoredEvent |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 85728,
"end": 86013
} | class ____:
xlPhoneticAlignCenter = 2 # from enum XlPhoneticAlignment
xlPhoneticAlignDistributed = 3 # from enum XlPhoneticAlignment
xlPhoneticAlignLeft = 1 # from enum XlPhoneticAlignment
xlPhoneticAlignNoControl = 0 # from enum XlPhoneticAlignment
| PhoneticAlignment |
python | sanic-org__sanic | sanic/models/asgi.py | {
"start": 469,
"end": 1423
} | class ____: # no cov
def __init__(self, transport: "MockTransport", loop):
self.transport = transport
self._not_paused = asyncio.Event()
self._not_paused.set()
self._complete = asyncio.Event()
def pause_writing(self) -> None:
self._not_paused.clear()
def resume_wri... | MockProtocol |
python | doocs__leetcode | solution/0600-0699/0611.Valid Triangle Number/Solution.py | {
"start": 0,
"end": 312
} | class ____:
def triangleNumber(self, nums: List[int]) -> int:
nums.sort()
ans, n = 0, len(nums)
for i in range(n - 2):
for j in range(i + 1, n - 1):
k = bisect_left(nums, nums[i] + nums[j], lo=j + 1) - 1
ans += k - j
return ans
| Solution |
python | eventlet__eventlet | tests/greenthread_test.py | {
"start": 3533,
"end": 4506
} | class ____(LimitedTestCase, Asserts):
def setUp(self):
super().setUp()
self.lst = [1]
def test_timer_fired(self):
def func():
greenthread.spawn_after_local(0.1, self.lst.pop)
greenthread.sleep(0.2)
greenthread.spawn(func)
assert self.lst == [1], ... | SpawnAfterLocal |
python | realpython__materials | python-protocol/person.py | {
"start": 0,
"end": 258
} | class ____:
def __init__(self, name):
self.name = name
def eat(self):
print(f"{self.name} is eating.")
def drink(self):
print(f"{self.name} is drinking.")
def talk(self):
print(f"{self.name} is talking.")
| Person |
python | kamyu104__LeetCode-Solutions | Python/cinema-seat-allocation.py | {
"start": 50,
"end": 819
} | class ____(object):
def maxNumberOfFamilies(self, n, reservedSeats):
"""
:type n: int
:type reservedSeats: List[List[int]]
:rtype: int
"""
lookup = collections.defaultdict(lambda: [False]*3)
for r, c in reservedSeats:
if 2 <= c <= 5:
... | Solution |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/models/secrets.py | {
"start": 4023,
"end": 4507
} | class ____(SecretStore):
def __init__(self) -> None:
self._store: Dict[str, str] = {}
def add_secret(self, name: str, value: str) -> Secret:
self._store[name] = value
return Secret(name, self)
def _fetch_secret(self, name: str) -> str:
try:
return self._store[na... | InMemorySecretStore |
python | PrefectHQ__prefect | tests/server/schemas/test_schedules.py | {
"start": 12622,
"end": 15993
} | class ____:
every_day = "0 0 * * *"
every_hour = "0 * * * *"
async def test_every_day(self):
clock = CronSchedule(cron=self.every_day)
dates = await clock.get_dates(
n=5, start=datetime(2021, 1, 1, tzinfo=ZoneInfo("UTC"))
)
assert dates == [
datetime(... | TestCronSchedule |
python | Textualize__textual | tests/command_palette/test_command_source_environment.py | {
"start": 577,
"end": 1247
} | class ____(App[None]):
COMMANDS = {SimpleSource}
def compose(self) -> ComposeResult:
yield Input()
def on_mount(self) -> None:
self.action_command_palette()
async def test_command_source_environment() -> None:
"""The command source should see the app and default screen."""
async ... | CommandPaletteApp |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 178336,
"end": 179056
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"draft_issue_id",
"title",
"body",
"assignee_ids",
"client_mutation_id",
)
draft_issue_id = sgqlc.types.Field(
sgqlc.types.no... | UpdateProjectDraftIssueInput |
python | wandb__wandb | wandb/vendor/pygments/lexers/igor.py | {
"start": 372,
"end": 19994
} | class ____(RegexLexer):
"""
Pygments Lexer for Igor Pro procedure files (.ipf).
See http://www.wavemetrics.com/ and http://www.igorexchange.com/.
.. versionadded:: 2.0
"""
name = 'Igor'
aliases = ['igor', 'igorpro']
filenames = ['*.ipf']
mimetypes = ['text/ipf']
flags = re.IGN... | IgorLexer |
python | jd__tenacity | tenacity/wait.py | {
"start": 779,
"end": 1458
} | class ____(abc.ABC):
"""Abstract base class for wait strategies."""
@abc.abstractmethod
def __call__(self, retry_state: "RetryCallState") -> float:
pass
def __add__(self, other: "wait_base") -> "wait_combine":
return wait_combine(self, other)
def __radd__(self, other: "wait_base")... | wait_base |
python | lepture__authlib | tests/flask/test_oauth2/test_jwt_bearer_grant.py | {
"start": 257,
"end": 4360
} | class ____(_JWTBearerGrant):
def resolve_issuer_client(self, issuer):
return Client.query.filter_by(client_id=issuer).first()
def resolve_client_key(self, client, headers, payload):
keys = {"1": "foo", "2": "bar"}
return keys[headers["kid"]]
def authenticate_user(self, subject):
... | JWTBearerGrant |
python | psf__black | tests/data/cases/stub.py | {
"start": 1868,
"end": 2281
} | class ____:
def f(self): ...
if sys.version_info >= (3, 8):
def g(self): ...
else:
def g(self): ...
def h(self): ...
def i(self): ...
if sys.version_info >= (3, 8):
def j(self): ...
def k(self): ...
if sys.version_info >= (3, 8):
class A: ...
cla... | Conditional |
python | google__pytype | pytype/rewrite/overlays/special_builtins_test.py | {
"start": 108,
"end": 362
} | class ____(test_utils.ContextfulTestBase):
def load_builtin_function(self, name: str) -> abstract.PytdFunction:
func = self.ctx.abstract_loader.load_builtin(name)
assert isinstance(func, abstract.PytdFunction)
return func
| SpecialBuiltinsTest |
python | Pylons__pyramid | tests/test_integration.py | {
"start": 16879,
"end": 17654
} | class ____(IntegrationBase, unittest.TestCase):
package = 'tests.pkgs.notfoundview'
def test_it(self):
res = self.testapp.get('/wontbefound', status=200)
self.assertTrue(b'generic_notfound' in res.body)
res = self.testapp.get('/bar', status=307)
self.assertEqual(res.location, 'h... | TestNotFoundView |
python | getsentry__sentry | tests/sentry/api/serializers/test_group.py | {
"start": 18530,
"end": 19718
} | class ____(TestCase):
def test_simple_group_serializer(self) -> None:
group = self.create_group()
serialized = serialize(group, self.user, SimpleGroupSerializer())
assert serialized["id"] == str(group.id)
assert serialized["title"] == group.title
assert serialized["culprit"] ... | SimpleGroupSerializerTest |
python | great-expectations__great_expectations | great_expectations/expectations/core/expect_column_values_to_be_between.py | {
"start": 2671,
"end": 17965
} | class ____(ColumnMapExpectation):
__doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION}
ExpectColumnValuesToBeBetween is a \
Column Map Expectation
Column Map Expectations are one of the most common types of Expectation.
They are evaluated for a single column and ask a yes/no question for every row in tha... | ExpectColumnValuesToBeBetween |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 553833,
"end": 554310
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of DeleteDiscussion"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "discussion")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mu... | DeleteDiscussionPayload |
python | numpy__numpy | numpy/_core/tests/test_umath.py | {
"start": 166900,
"end": 168350
} | class ____:
def test_object_direct(self):
""" test direct implementation of these magic methods """
class C:
def __floor__(self):
return 1
def __ceil__(self):
return 2
def __trunc__(self):
return 3
arr = ... | TestRoundingFunctions |
python | pytest-dev__pytest | testing/test_config.py | {
"start": 85582,
"end": 86351
} | class ____:
def test_pytest_setup_cfg_unsupported(self, pytester: Pytester) -> None:
pytester.makefile(
".cfg",
setup="""
[pytest]
addopts = --verbose
""",
)
with pytest.raises(pytest.fail.Exception):
pytester.runpytest()
... | TestSetupCfg |
python | huggingface__transformers | src/transformers/models/pix2struct/modeling_pix2struct.py | {
"start": 1848,
"end": 3350
} | class ____(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""
Construct a layernorm module in the T5 style. No bias and no subtraction of mean.
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forw... | Pix2StructLayerNorm |
python | facelessuser__soupsieve | soupsieve/css_types.py | {
"start": 4252,
"end": 4942
} | class ____(ImmutableDict):
"""Custom selectors."""
def __init__(self, arg: dict[str, str] | Iterable[tuple[str, str]]) -> None:
"""Initialize."""
super().__init__(arg)
def _validate(self, arg: dict[str, str] | Iterable[tuple[str, str]]) -> None:
"""Validate arguments."""
... | CustomSelectors |
python | django__django | tests/admin_inlines/models.py | {
"start": 5642,
"end": 5845
} | class ____(models.Model):
text = models.CharField(max_length=40)
poll = models.ForeignKey(Poll, models.CASCADE)
def clean(self):
raise ValidationError("Always invalid model.")
| Question |
python | nedbat__coveragepy | tests/test_misc.py | {
"start": 3738,
"end": 6019
} | class ____(CoverageTest):
"""Test import_third_party."""
run_in_temp_dir = False
def test_success(self) -> None:
# Make sure we don't have pytest in sys.modules before we start.
del sys.modules["pytest"]
# Import pytest
mod, has = import_third_party("pytest")
assert... | ImportThirdPartyTest |
python | plotly__plotly.py | plotly/graph_objs/layout/scene/yaxis/title/_font.py | {
"start": 235,
"end": 9921
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.scene.yaxis.title"
_path_str = "layout.scene.yaxis.title.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weigh... | Font |
python | explosion__spaCy | spacy/scorer.py | {
"start": 1892,
"end": 2818
} | class ____:
"""An AUC ROC score. This is only defined for binary classification.
Use the method is_binary before calculating the score, otherwise it
may throw an error."""
def __init__(self) -> None:
self.golds: List[Any] = []
self.cands: List[Any] = []
self.saved_score = 0.0
... | ROCAUCScore |
python | apache__airflow | providers/opensearch/tests/unit/opensearch/operators/test_opensearch.py | {
"start": 2576,
"end": 3203
} | class ____:
# This test does not test execute logic because there is only a redirect to the OpenSearch
# client.
def setup_method(self, dag_setup):
self.dag = dag_setup
self.open_search = OpenSearchCreateIndexOperator(
task_id="test_opensearch_query_operator", index_name="test_i... | TestOpenSearchCreateIndexOperator |
python | django__django | tests/admin_widgets/tests.py | {
"start": 34476,
"end": 39790
} | class ____(SimpleTestCase):
def test_no_can_add_related(self):
rel = Individual._meta.get_field("parent").remote_field
w = widgets.AdminRadioSelect()
# Used to fail with a name error.
w = widgets.RelatedFieldWidgetWrapper(w, rel, widget_admin_site)
self.assertFalse(w.can_add_... | RelatedFieldWidgetWrapperTests |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 638763,
"end": 639228
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node", "starred_at")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field(sgqlc.types.non_null("Repository"), gr... | StarredRepositoryEdge |
python | apache__airflow | task-sdk/src/airflow/sdk/exceptions.py | {
"start": 3185,
"end": 4281
} | class ____(AirflowFailException):
main_message: str
def __init__(self, inactive_asset_keys: Collection[AssetUniqueKey | AssetNameRef | AssetUriRef]) -> None:
self.inactive_asset_keys = inactive_asset_keys
@staticmethod
def _render_asset_key(key: AssetUniqueKey | AssetNameRef | AssetUriRef) -> ... | _AirflowExecuteWithInactiveAssetExecption |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride2.py | {
"start": 1919,
"end": 2084
} | class ____(Generic[P, R]):
def method1(self, *args: P.args, **kwargs: P.kwargs) -> R: ...
def method2(self, *args: P.args, **kwargs: P.kwargs) -> R: ...
| Base2 |
python | google__pytype | pytype/tools/merge_pyi/merge_pyi.py | {
"start": 384,
"end": 816
} | class ____(Exception):
"""Wrap exceptions thrown while merging files."""
def _merge_csts(*, py_tree, pyi_tree):
context = codemod.CodemodContext()
vis = visitors.ApplyTypeAnnotationsVisitor
vis.store_stub_in_context(context, pyi_tree)
return vis(
context,
overwrite_existing_annotations=False,
... | MergeError |
python | getsentry__sentry | src/sentry/users/models/useremail.py | {
"start": 2096,
"end": 6635
} | class ____(ControlOutboxProducingModel):
__relocation_scope__ = RelocationScope.User
__relocation_dependencies__ = {"sentry.Email"}
__relocation_custom_ordinal__ = ["user", "email"]
user = FlexibleForeignKey(settings.AUTH_USER_MODEL, related_name="emails")
email = models.EmailField(_("email address... | UserEmail |
python | PyCQA__pylint | tests/functional/m/method_hidden.py | {
"start": 2204,
"end": 2271
} | class ____(ParentTwo):
def __private(self):
pass
| ChildTwo |
python | spack__spack | lib/spack/spack/detection/common.py | {
"start": 9406,
"end": 10892
} | class ____:
@staticmethod
def find_windows_compiler_root_paths() -> List[str]:
"""Helper for Windows compiler installation root discovery
At the moment simply returns location of VS install paths from VSWhere
But should be extended to include more information as relevant"""
retu... | WindowsCompilerExternalPaths |
python | huggingface__transformers | src/transformers/tokenization_utils_base.py | {
"start": 5322,
"end": 5602
} | class ____(NamedTuple):
"""
Token span in an encoded string (list of tokens).
Args:
start (`int`): Index of the first token in the span.
end (`int`): Index of the token following the last token in the span.
"""
start: int
end: int
| TokenSpan |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.