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/data_export/endpoints/test_data_export.py | {
"start": 380,
"end": 30176
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-data-export"
method = "post"
def setUp(self) -> None:
self.user = self.create_user("user1@example.com")
self.org = self.create_organization(name="Test")
self.team = self.create_team(organization=self.org, name="Data Expo... | DataExportTest |
python | gevent__gevent | src/gevent/tests/test__util.py | {
"start": 10274,
"end": 10705
} | class ____(greentest.TestCase):
def test_clear_stack_frames(self):
import inspect
import threading
completed = []
def do_it():
util.clear_stack_frames(inspect.currentframe())
completed.append(1)
t = threading.Thread(target=do_it)
t.start()
... | TestFuncs |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/inputs.py | {
"start": 5707,
"end": 6074
} | class ____(graphene.InputObjectType):
partitionSetName = graphene.NonNull(graphene.String)
repositorySelector = graphene.NonNull(GrapheneRepositorySelector)
class Meta:
description = """This type represents the fields necessary to identify a
pipeline or pipeline subset."""
name = "P... | GraphenePartitionSetSelector |
python | pandas-dev__pandas | pandas/io/json/_json.py | {
"start": 7213,
"end": 7711
} | class ____(Writer):
_default_orient = "index"
@property
def obj_to_write(self) -> NDFrame | Mapping[IndexLabel, Any]:
if not self.index and self.orient == "split":
return {"name": self.obj.name, "data": self.obj.values}
else:
return self.obj
def _format_axes(sel... | SeriesWriter |
python | astropy__astropy | astropy/units/tests/test_quantity_array_methods.py | {
"start": 14959,
"end": 20340
} | class ____:
"""
Test array conversion methods
"""
def test_item(self):
q1 = u.Quantity(np.array([1, 2, 3]), u.m / u.km, dtype=int)
assert q1.item(1) == 2 * q1.unit
q1[1] = 1
assert q1[1] == 1000 * u.m / u.km
q1[1] = 100 * u.cm / u.km
assert q1[1] == 1 * ... | TestArrayConversion |
python | Textualize__textual | tests/test_markdown.py | {
"start": 850,
"end": 7049
} | class ____(App[None]):
def __init__(self, markdown: str) -> None:
super().__init__()
self._markdown = markdown
def compose(self) -> ComposeResult:
yield FussyMarkdown(self._markdown)
@pytest.mark.parametrize(
["document", "expected_nodes"],
[
# Basic markup.
("... | MarkdownApp |
python | squidfunk__mkdocs-material | material/plugins/blog/structure/__init__.py | {
"start": 11564,
"end": 13811
} | class ____(Link):
# Initialize reference - this is essentially a crossover of pages and links,
# as it inherits the metadata of the page and allows for anchors
def __init__(self, title: str, url: str):
super().__init__(title, url)
self.meta = {}
# ------------------------------------------... | Reference |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 100278,
"end": 100911
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"repository_vulnerability_alert_id",
"dismiss_reason",
"client_mutation_id",
)
repository_vulnerability_alert_id = sgqlc.types.Field(
sgqlc.t... | DismissRepositoryVulnerabilityAlertInput |
python | matplotlib__matplotlib | lib/mpl_toolkits/axisartist/grid_finder.py | {
"start": 11669,
"end": 11976
} | class ____:
def __init__(self, useMathText=True):
self._fmt = mticker.ScalarFormatter(
useMathText=useMathText, useOffset=False)
self._fmt.create_dummy_axis()
def __call__(self, direction, factor, values):
return self._fmt.format_ticks(values)
| FormatterPrettyPrint |
python | celery__celery | t/unit/backends/test_mongodb.py | {
"start": 27799,
"end": 30379
} | class ____:
@pytest.fixture(scope="function", autouse=True)
def fake_mongo_collection_patch(self, monkeypatch):
"""A fake collection with serialization experience close to MongoDB."""
bson = pytest.importorskip("bson")
class FakeMongoCollection:
def __init__(self):
... | test_MongoBackend_store_get_result |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 140401,
"end": 141031
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of AddReaction"""
__schema__ = github_schema
__field_names__ = ("subject_id", "content", "client_mutation_id")
subject_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="subjectId")
"""The Node ID of the subject to modify."""
... | AddReactionInput |
python | fastapi__sqlmodel | tests/test_enums_models.py | {
"start": 121,
"end": 178
} | class ____(str, enum.Enum):
C = "C"
D = "D"
| MyEnum2 |
python | nmslib__hnswlib | tests/python/bindings_test_resize.py | {
"start": 54,
"end": 2922
} | class ____(unittest.TestCase):
def testRandomSelf(self):
for idx in range(16):
print("\n**** Index resize test ****\n")
np.random.seed(idx)
dim = 16
num_elements = 10000
# Generating sample data
data = np.float32(np.random.random((num... | RandomSelfTestCase |
python | jamielennox__requests-mock | requests_mock/exceptions.py | {
"start": 914,
"end": 1013
} | class ____(MockException):
"""This call cannot be made under a mocked environment"""
| InvalidRequest |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 1399,
"end": 6345
} | class ____(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.io.votable.exceptions`.
"""
max_warnings = _config.ConfigItem(
10,
"Number of times the same type of warning is displayed before being suppressed",
cfgtype="integer",
)
conf = Conf()
def _form... | Conf |
python | huggingface__transformers | src/transformers/models/fuyu/modeling_fuyu.py | {
"start": 1661,
"end": 11021
} | class ____(FuyuPreTrainedModel):
_checkpoint_conversion_mapping = {"language_model.model": "language_model"}
def __init__(self, config: FuyuConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.text_config.vocab_size
self.language_mode... | FuyuModel |
python | great-expectations__great_expectations | tests/integration/test_utils/data_source_config/redshift.py | {
"start": 1323,
"end": 2127
} | class ____(DataSourceTestConfig):
@property
@override
def label(self) -> str:
return "redshift"
@property
@override
def pytest_mark(self) -> pytest.MarkDecorator:
return pytest.mark.redshift
@override
def create_batch_setup(
self,
request: pytest.Fixture... | RedshiftDatasourceTestConfig |
python | tensorflow__tensorflow | tensorflow/python/ops/image_ops_test.py | {
"start": 70875,
"end": 77673
} | class ____(test_util.TensorFlowTestCase):
def _assertShapeInference(self, pre_shape, fraction, post_shape):
image = array_ops.placeholder(dtypes.float32, shape=pre_shape)
y = image_ops.central_crop(image, fraction)
if post_shape is None:
self.assertEqual(y.get_shape().dims, None)
else:
se... | CentralCropTest |
python | sqlalchemy__sqlalchemy | test/orm/test_lambdas.py | {
"start": 11869,
"end": 14596
} | class ____(fixtures.MappedTest):
__sparse_driver_backend__ = True
run_setup_mappers = "once"
@classmethod
def define_tables(cls, metadata):
Table(
"users",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
... | UpdateDeleteTest |
python | allegroai__clearml | clearml/storage/callbacks.py | {
"start": 6892,
"end": 7799
} | class ____(ProgressReport):
def __init__(
self,
total_size: float,
verbose: bool,
remote_path: str,
log: logging.Logger,
report_chunk_size_mb: Optional[int] = None,
report_start: Optional[bool] = None,
) -> None:
report_chunk_size_mb = (
... | DownloadProgressReport |
python | pypa__setuptools | setuptools/_distutils/tests/test_log.py | {
"start": 79,
"end": 311
} | class ____:
def test_non_ascii(self, caplog):
caplog.set_level(logging.DEBUG)
log.debug('Dεbug\tMėssãge')
log.fatal('Fαtal\tÈrrōr')
assert caplog.messages == ['Dεbug\tMėssãge', 'Fαtal\tÈrrōr']
| TestLog |
python | python-openxml__python-docx | src/docx/shared.py | {
"start": 11858,
"end": 12517
} | class ____:
"""A document element within a story part.
Story parts include DocumentPart and Header/FooterPart and can contain block items
(paragraphs and tables). Items from the block-item subtree occasionally require an
ancestor object to provide access to part-level or package-level items like styles... | StoryChild |
python | django__django | django/db/models/fields/__init__.py | {
"start": 83024,
"end": 83392
} | class ____(PositiveIntegerRelDbTypeMixin, BigIntegerField):
description = _("Positive big integer")
def get_internal_type(self):
return "PositiveBigIntegerField"
def formfield(self, **kwargs):
return super().formfield(
**{
"min_value": 0,
**kwarg... | PositiveBigIntegerField |
python | PyCQA__pylint | doc/data/messages/r/return-in-init/good.py | {
"start": 0,
"end": 77
} | class ____:
def __init__(self, a, b) -> None:
self.result = a + b
| Sum |
python | tensorflow__tensorflow | tensorflow/python/checkpoint/checkpoint_with_v1_optimizers_test.py | {
"start": 11484,
"end": 13784
} | class ____(test.TestCase):
@test_util.run_in_graph_and_eager_modes
def test_trackable_save_restore(self):
def _templated():
v = variable_scope.get_variable(
"v", shape=[1], initializer=init_ops.zeros_initializer(),
use_resource=True)
v2 = variable_scope.get_variable(
... | TemplateTests |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 950429,
"end": 951470
} | class ____(sgqlc.types.Type):
"""Choose which status checks must pass before branches can be merged
into a branch that matches this rule. When enabled, commits must
first be pushed to another branch, then merged or pushed directly
to a branch that matches this rule after status checks have
passed.
... | RequiredStatusChecksParameters |
python | joke2k__faker | faker/providers/color/pt_BR/__init__.py | {
"start": 98,
"end": 9605
} | class ____(ColorProvider):
"""Implement color provider for ``pt_BR`` locale."""
all_colors = OrderedDict(
(
("Açafrão", "#F4C430"),
("Água-marinha média", "#66CDAA"),
("Água-marinha", "#7FFFD4"),
("Água", "#00FFFF"),
("Alizarina", "#E32636"),
... | Provider |
python | huggingface__transformers | src/transformers/modeling_outputs.py | {
"start": 44526,
"end": 47226
} | class ____(ModelOutput):
"""
Base class for causal language model (or autoregressive) outputs.
Args:
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss (for next-token prediction).
logits (`torch.FloatTensor` of sha... | CausalLMOutputWithCrossAttentions |
python | pytorch__pytorch | torch/_inductor/template_heuristics/triton.py | {
"start": 89285,
"end": 89487
} | class ____(AddMMConfigMixin, CPUMMTemplateConfigHeuristic):
"""Addmm specific mixin for CPU"""
@register_template_heuristic(mm_template.uid, "cpu", op_name="scaled_mm")
| CPUAddmmTemplateConfigHeuristic |
python | getsentry__sentry | src/sentry/sentry_apps/api/serializers/sentry_app_installation.py | {
"start": 628,
"end": 707
} | class ____(TypedDict):
uuid: str
slug: str
| SentryAppInstallationAppResult |
python | doocs__leetcode | solution/1800-1899/1894.Find the Student that Will Replace the Chalk/Solution.py | {
"start": 0,
"end": 220
} | class ____:
def chalkReplacer(self, chalk: List[int], k: int) -> int:
s = sum(chalk)
k %= s
for i, x in enumerate(chalk):
if k < x:
return i
k -= x
| Solution |
python | numba__numba | numba/core/untyped_passes.py | {
"start": 2329,
"end": 2792
} | class ____(FunctionPass):
_name = "extract_bytecode"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
"""
Extract bytecode from function
"""
func_id = state['func_id']
bc = bytecode.ByteCode(func_id)
if config.DUMP_BYTECODE:... | ExtractByteCode |
python | spack__spack | lib/spack/spack/environment/environment.py | {
"start": 107078,
"end": 119573
} | class ____(collections.abc.Mapping):
"""Manages the in-memory representation of a manifest file, and its synchronization
with the actual manifest on disk.
"""
@staticmethod
def from_lockfile(manifest_dir: Union[pathlib.Path, str]) -> "EnvironmentManifestFile":
"""Returns an environment mani... | EnvironmentManifestFile |
python | getsentry__sentry | src/sentry/integrations/github/webhook.py | {
"start": 8695,
"end": 12387
} | class ____(GitHubWebhook):
"""
Unlike other GitHub webhooks, installation webhooks are handled in control silo.
https://developer.github.com/v3/activity/events/types/#installationevent
"""
@property
def event_type(self) -> IntegrationWebhookEventType:
return IntegrationWebhookEventType... | InstallationEventWebhook |
python | kamyu104__LeetCode-Solutions | Python/validate-binary-tree-nodes.py | {
"start": 29,
"end": 763
} | class ____(object):
def validateBinaryTreeNodes(self, n, leftChild, rightChild):
"""
:type n: int
:type leftChild: List[int]
:type rightChild: List[int]
:rtype: bool
"""
roots = set(range(n)) - set(leftChild) - set(rightChild)
if len(roots) != 1:
... | Solution |
python | pytorch__pytorch | test/quantization/ao_migration/common.py | {
"start": 106,
"end": 2178
} | class ____(TestCase):
def _test_function_import(
self,
package_name: str,
function_list: list[str],
base: Optional[str] = None,
new_package_name: Optional[str] = None,
):
r"""Tests individual function list import by comparing the functions
and their hashes... | AOMigrationTestCase |
python | getsentry__sentry | src/sentry/api/serializers/rest_framework/dashboard.py | {
"start": 3558,
"end": 4593
} | class ____(serializers.Field):
REQUIRED_KEYS = {
"x",
"y",
"w",
"h",
"min_h",
}
def to_internal_value(self, data):
if data is None:
return None
missing_keys = self.REQUIRED_KEYS - set(data.keys())
if missing_keys:
miss... | LayoutField |
python | pyca__cryptography | tests/hazmat/primitives/decrepit/test_algorithms.py | {
"start": 4964,
"end": 5717
} | class ____:
@pytest.mark.parametrize(
("key", "keysize"),
[(b"0" * (keysize // 4), keysize) for keysize in range(40, 129, 8)],
)
def test_key_size(self, key, keysize):
cipher = CAST5(binascii.unhexlify(key))
assert cipher.key_size == keysize
def test_invalid_key_size(sel... | TestCAST5 |
python | streamlit__streamlit | lib/tests/streamlit/runtime/memory_media_file_storage_test.py | {
"start": 1067,
"end": 7167
} | class ____(unittest.TestCase):
def setUp(self):
super().setUp()
self.storage = MemoryMediaFileStorage(media_endpoint="/mock/media")
@mock.patch(
"streamlit.runtime.memory_media_file_storage.open",
mock_open(read_data=b"mock_bytes"),
)
def test_load_with_path(self):
... | MemoryMediaFileStorageTest |
python | django__django | django/contrib/sessions/exceptions.py | {
"start": 272,
"end": 359
} | class ____(BadRequest):
"""The session was interrupted."""
pass
| SessionInterrupted |
python | kubernetes-client__python | kubernetes/client/models/v1_device_allocation_configuration.py | {
"start": 383,
"end": 6196
} | 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... | V1DeviceAllocationConfiguration |
python | mkdocs__mkdocs | mkdocs/tests/cli_tests.py | {
"start": 165,
"end": 25528
} | class ____(unittest.TestCase):
def setUp(self):
self.runner = CliRunner()
@mock.patch('mkdocs.commands.serve.serve', autospec=True)
def test_serve_default(self, mock_serve):
result = self.runner.invoke(cli.cli, ["serve"], catch_exceptions=False)
self.assertEqual(result.exit_code, 0... | CLITests |
python | coleifer__peewee | tests/models.py | {
"start": 110788,
"end": 112379
} | class ____(ModelTestCase):
requires = [User]
def test_tuples(self):
ua, ub, uc = [User.create(username=username) for username in 'abc']
query = User.select().where(
Tuple(User.username, User.id) == ('b', ub.id))
self.assertSQL(query, (
'SELECT "t1"."id", "t1"."us... | TestTupleComparison |
python | dagster-io__dagster | python_modules/dagster/dagster/components/core/decl.py | {
"start": 7270,
"end": 8486
} | class ____(YamlBackedComponentDecl):
"""Declaration of a single component loaded from a YAML file."""
@staticmethod
def from_source_tree(
context: ComponentDeclLoadContext,
source_tree: ValueAndSourcePositionTree,
path: ComponentPath,
) -> "YamlDecl":
component_file_mode... | YamlDecl |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/decl_api.py | {
"start": 10465,
"end": 15576
} | class ____(interfaces._MappedAttribute[_T], _declared_attr_common):
"""Mark a class-level method as representing the definition of
a mapped property or Declarative directive.
:class:`_orm.declared_attr` is typically applied as a decorator to a class
level method, turning the attribute into a scalar-lik... | declared_attr |
python | pytorch__pytorch | tools/stats/utilization_stats_lib.py | {
"start": 2051,
"end": 2635
} | class ____:
created_at: int
repo: str
workflow_id: int
run_attempt: int
job_id: int
workflow_name: str
job_name: str
usage_collect_interval: float
data_model_version: str
gpu_count: int
cpu_count: int
gpu_type: str
start_at: int
end_at: int
segments: list[OssC... | OssCiUtilizationMetadataV1 |
python | pytorch__pytorch | torch/mtia/mtia_graph.py | {
"start": 1196,
"end": 2384
} | class ____:
default_capture_stream: Optional[torch.mtia.Stream] = None
def __init__(
self,
mtia_graph: MTIAGraph,
pool: Optional[_POOL_HANDLE] = None,
stream: Optional[torch.mtia.Stream] = None,
):
if self.__class__.default_capture_stream is None:
self.__... | graph |
python | tornadoweb__tornado | tornado/test/simple_httpclient_test.py | {
"start": 1478,
"end": 1893
} | class ____(RequestHandler):
def initialize(self, queue, wake_callback):
self.queue = queue
self.wake_callback = wake_callback
@gen.coroutine
def get(self):
logging.debug("queuing trigger")
event = Event()
self.queue.append(event.set)
if self.get_argument("wak... | TriggerHandler |
python | pyparsing__pyparsing | pyparsing/common.py | {
"start": 285,
"end": 15619
} | class ____:
"""Here are some common low-level expressions that may be useful in
jump-starting parser development:
- numeric forms (:class:`integers<integer>`, :class:`reals<real>`,
:class:`scientific notation<sci_real>`)
- common :class:`programming identifiers<identifier>`
- network addresse... | pyparsing_common |
python | tox-dev__tox | src/tox/tox_env/python/api.py | {
"start": 686,
"end": 1836
} | class ____:
implementation: str
version_info: VersionInfo
version: str
is_64: bool
platform: str
extra: dict[str, Any]
free_threaded: bool = False
@property
def version_no_dot(self) -> str:
return f"{self.version_info.major}{self.version_info.minor}"
@property
def i... | PythonInfo |
python | pypa__warehouse | warehouse/admin/views/sponsors.py | {
"start": 455,
"end": 7147
} | class ____(wtforms.Form):
name = wtforms.fields.StringField(
validators=[
wtforms.validators.Length(max=100),
wtforms.validators.InputRequired(),
],
)
service = wtforms.fields.StringField(
validators=[wtforms.validators.Length(max=256), wtforms.validators.Opti... | SponsorForm |
python | imageio__imageio | imageio/plugins/pillow.py | {
"start": 2225,
"end": 22409
} | class ____(PluginV3):
def __init__(self, request: Request) -> None:
"""Instantiate a new Pillow Plugin Object
Parameters
----------
request : {Request}
A request object representing the resource to be operated on.
"""
super().__init__(request)
... | PillowPlugin |
python | doocs__leetcode | solution/2500-2599/2573.Find the String with LCP/Solution.py | {
"start": 0,
"end": 829
} | class ____:
def findTheString(self, lcp: List[List[int]]) -> str:
n = len(lcp)
s = [""] * n
i = 0
for c in ascii_lowercase:
while i < n and s[i]:
i += 1
if i == n:
break
for j in range(i, n):
if lcp[i... | Solution |
python | scrapy__scrapy | tests/spiders.py | {
"start": 7060,
"end": 8072
} | class ____(SimpleSpider):
name = "asyncdef_asyncio_gen_complex"
initial_reqs = 4
following_reqs = 3
depth = 2
def _get_req(self, index, cb=None):
return Request(
self.mockserver.url(f"/status?n=200&request={index}"),
meta={"index": index},
dont_filter=Tru... | AsyncDefAsyncioGenComplexSpider |
python | matplotlib__matplotlib | lib/matplotlib/backends/_backend_gtk.py | {
"start": 9095,
"end": 10553
} | class ____(NavigationToolbar2):
# Must be implemented in GTK3/GTK4 backends:
# * __init__
# * save_figure
def set_message(self, s):
escaped = GLib.markup_escape_text(s)
self.message.set_markup(f'<small>{escaped}</small>')
def draw_rubberband(self, event, x0, y0, x1, y1):
he... | _NavigationToolbar2GTK |
python | python__mypy | mypyc/irbuild/builder.py | {
"start": 3612,
"end": 3690
} | class ____(ExpressionVisitor[Value], StatementVisitor[None]):
pass
| IRVisitor |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 92325,
"end": 94112
} | class ____(ASTDeclarator):
def __init__(self, declId: ASTNestedName, size: ASTExpression) -> None:
self.declId = declId
self.size = size
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTDeclaratorNameBitField):
return NotImplemented
return self.de... | ASTDeclaratorNameBitField |
python | pypa__pipenv | pipenv/vendor/tomlkit/exceptions.py | {
"start": 4411,
"end": 4658
} | class ____(TOMLKitError):
"""
An already present key was used.
"""
def __init__(self, key):
key = getattr(key, "key", key)
message = f'Key "{key}" already exists.'
super().__init__(message)
| KeyAlreadyPresent |
python | numba__numba | numba/cuda/tests/doc_examples/test_ufunc.py | {
"start": 201,
"end": 1418
} | class ____(CUDATestCase):
"""
Test calling a UFunc
"""
def setUp(self):
# Prevent output from this test showing
# up when running the test suite
self._captured_stdout = captured_stdout()
self._captured_stdout.__enter__()
super().setUp()
def tearDown(self):
... | TestUFunc |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/distlib/scripts.py | {
"start": 2928,
"end": 18777
} | class ____(object):
"""
A class to copy or create scripts from source scripts or callable
specifications.
"""
script_template = SCRIPT_TEMPLATE
executable = None # for shebangs
def __init__(self,
source_dir,
target_dir,
add_launchers=True... | ScriptMaker |
python | getsentry__sentry | src/sentry/models/files/abstractfileblob.py | {
"start": 1100,
"end": 9707
} | class ____(Model, _Parent[BlobOwnerType]):
__relocation_scope__ = RelocationScope.Excluded
path = models.TextField(null=True)
size = WrappingU32IntegerField(null=True)
checksum = models.CharField(max_length=40, unique=True)
timestamp = models.DateTimeField(default=timezone.now, db_index=True)
... | AbstractFileBlob |
python | kamyu104__LeetCode-Solutions | Python/find-the-minimum-area-to-cover-all-ones-ii.py | {
"start": 11771,
"end": 15617
} | class ____(object):
def minimumSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
def binary_search(left, right, check):
while left <= right:
mid = left + (right-left)//2
if check(mid):
right = mid-... | Solution4 |
python | milvus-io__pymilvus | pymilvus/client/types.py | {
"start": 2664,
"end": 3793
} | class ____(IntEnum):
"""
String of DataType is str of its value, e.g.: str(DataType.BOOL) == "1"
"""
NONE = 0 # schema_pb2.None, this is an invalid representation in python
BOOL = schema_pb2.Bool
INT8 = schema_pb2.Int8
INT16 = schema_pb2.Int16
INT32 = schema_pb2.Int32
INT64 = schem... | DataType |
python | kamyu104__LeetCode-Solutions | Python/paint-house-ii.py | {
"start": 442,
"end": 1336
} | class ____(object):
def minCostII(self, costs):
"""
:type costs: List[List[int]]
:rtype: int
"""
if not costs:
return 0
n = len(costs)
k = len(costs[0])
min_cost = [costs[0], [0] * k]
for i in xrange(1, n):
smallest, se... | Solution2 |
python | altair-viz__altair | altair/datasets/_exceptions.py | {
"start": 230,
"end": 3823
} | class ____(Exception):
@classmethod
def from_url(cls, meta: Metadata, /) -> AltairDatasetsError:
if meta["suffix"] == ".parquet":
msg = (
f"{_failed_url(meta)}"
f"{meta['suffix']!r} datasets require `vegafusion`.\n"
"See upstream issue for deta... | AltairDatasetsError |
python | tensorflow__tensorflow | tensorflow/python/framework/ops.py | {
"start": 65601,
"end": 67260
} | class ____(object):
"""A holder for statistics about an operator.
This class holds information about the resource requirements for an op,
including the size of its weight parameters on-disk and how many FLOPS it
requires to execute forward inference.
If you define a new operation, you can create a function ... | OpStats |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 745513,
"end": 745753
} | class ____(VegaLiteSchema):
"""MarkPropDefnumberArray schema wrapper."""
_schema = {"$ref": "#/definitions/MarkPropDef<number[]>"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| MarkPropDefnumberArray |
python | python-visualization__folium | folium/elements.py | {
"start": 5025,
"end": 5705
} | class ____(MacroElement):
"""Abstract class to add an element to another element."""
_template = Template(
"""
{% macro script(this, kwargs) %}
{{ this.target }}.{{ this.method }}(
{% for arg in this.args %}
{{ arg | tojavascript }},
... | MethodCall |
python | ray-project__ray | python/ray/air/tests/mocked_wandb_integration.py | {
"start": 746,
"end": 899
} | class ____:
def __init__(self):
self.config = {}
def update(self, config, *args, **kwargs):
self.config.update(config)
| _FakeConfig |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/lib/metadata_service/models/generated/ConnectorMetadataDefinitionV0.py | {
"start": 341,
"end": 1232
} | class ____(BaseModel):
class Config:
extra = Extra.forbid
title: str = Field(..., description="Display title for the documentation link")
url: AnyUrl = Field(..., description="URL to the external documentation")
type: Optional[
Literal[
"api_deprecations",
"api_r... | ExternalDocumentationUrl |
python | numba__numba | numba/tests/test_cfunc.py | {
"start": 2725,
"end": 5090
} | class ____(TestCase):
def test_basic(self):
"""
Basic usage and properties of a cfunc.
"""
f = cfunc(add_sig)(add_usecase)
self.assertEqual(f.__name__, "add_usecase")
self.assertEqual(f.__qualname__, "add_usecase")
self.assertIs(f.__wrapped__, add_usecase)
... | TestCFunc |
python | django__django | tests/select_related/models.py | {
"start": 982,
"end": 1107
} | class ____(models.Model):
name = models.CharField(max_length=50)
klass = models.ForeignKey(Klass, models.CASCADE)
| Order |
python | pypa__warehouse | tests/unit/search/test_tasks.py | {
"start": 5461,
"end": 5546
} | class ____:
def __init__(self):
self.indices = FakeESIndices()
| FakeESClient |
python | getsentry__sentry | src/sentry/integrations/github_enterprise/webhook.py | {
"start": 3067,
"end": 3486
} | class ____:
@property
def provider(self) -> str:
return IntegrationProviderSlug.GITHUB_ENTERPRISE.value
def get_external_id(self, username: str) -> str:
return f"github_enterprise:{username}"
def get_idp_external_id(self, integration: RpcIntegration, host: str | None = None) -> str:
... | GitHubEnterpriseWebhook |
python | ansible__ansible | test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/action/ios.py | {
"start": 240,
"end": 445
} | class ____(ActionBase):
def run(self, tmp=None, task_vars=None):
result = super(ActionModule, self).run(tmp, task_vars)
result['action_plugin'] = 'ios'
return result
| ActionModule |
python | mkdocstrings__mkdocstrings | src/mkdocstrings/_internal/handlers/base.py | {
"start": 1996,
"end": 2099
} | class ____(Exception):
"""An exception raised when some collection of data failed."""
| CollectionError |
python | gevent__gevent | src/greentest/3.9/test_ssl.py | {
"start": 119770,
"end": 193035
} | class ____(unittest.TestCase):
def test_echo(self):
"""Basic test of an SSL client connecting to a server"""
if support.verbose:
sys.stdout.write("\n")
for protocol in PROTOCOLS:
if protocol in {ssl.PROTOCOL_TLS_CLIENT, ssl.PROTOCOL_TLS_SERVER}:
conti... | ThreadedTests |
python | bokeh__bokeh | src/bokeh/models/renderers/renderer.py | {
"start": 3889,
"end": 4874
} | class ____(Renderer):
""" A renderer that allows attaching other renderers and DOM-based UIs.
"""
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
renderers = List(Instance(Renderer), default=[], help="... | CompositeRenderer |
python | huggingface__transformers | tests/models/bigbird_pegasus/test_modeling_bigbird_pegasus.py | {
"start": 101497,
"end": 109133
} | class ____:
def __init__(
self,
parent,
vocab_size=99,
batch_size=7,
d_model=32,
decoder_seq_length=7,
is_training=True,
is_decoder=True,
use_attention_mask=True,
use_cache=False,
use_labels=True,
decoder_start_token_id=... | BigBirdPegasusStandaloneDecoderModelTester |
python | langchain-ai__langchain | libs/core/langchain_core/tools/base.py | {
"start": 12126,
"end": 12547
} | class ____(Exception): # noqa: N818
"""Exception thrown when a tool execution error occurs.
This exception allows tools to signal errors without stopping the agent.
The error is handled according to the tool's handle_tool_error setting,
and the result is returned as an observation to the agent.
""... | ToolException |
python | hynek__structlog | src/structlog/testing.py | {
"start": 3760,
"end": 4141
} | class ____:
r"""
Produce and cache `ReturnLogger`\ s.
To be used with `structlog.configure`\ 's *logger_factory*.
Positional arguments are silently ignored.
.. versionadded:: 0.4.0
"""
def __init__(self) -> None:
self._logger = ReturnLogger()
def __call__(self, *args: Any) -... | ReturnLoggerFactory |
python | huggingface__transformers | src/transformers/models/luke/modeling_luke.py | {
"start": 64868,
"end": 72827
} | class ____(LukePreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.luke = LukeModel(config)
self.num_labels = config.num_labels
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.classifier = nn.Linear(config.hidden_size * 3, config.num_label... | LukeForEntitySpanClassification |
python | python__mypy | mypy/partially_defined.py | {
"start": 10694,
"end": 10771
} | class ____:
def __init__(self) -> None:
self.has_break = False
| Loop |
python | run-llama__llama_index | llama-index-core/llama_index/core/postprocessor/llm_rerank.py | {
"start": 691,
"end": 4095
} | class ____(BaseNodePostprocessor):
"""LLM-based reranker."""
top_n: int = Field(description="Top N nodes to return.")
choice_select_prompt: SerializeAsAny[BasePromptTemplate] = Field(
description="Choice select prompt."
)
choice_batch_size: int = Field(description="Batch size for choice sel... | LLMRerank |
python | django-extensions__django-extensions | tests/test_runscript.py | {
"start": 2595,
"end": 4451
} | class ____(RunScriptTests):
def test_prints_additional_info_on_nonexistent_script_by_default(self):
cmd = self.get_command()
with self.assertRaises(CommandError):
call_command(cmd, "non_existent_script")
self.assertIn(
"No (valid) module for script 'non_existent_scrip... | InvalidImportScriptsTests |
python | mkdocs__mkdocs | mkdocs/tests/config/config_options_tests.py | {
"start": 66783,
"end": 66938
} | class ____(Config):
foo = c.Type(str, default='default foo')
bar = c.Type(int, default=0)
dir = c.Optional(c.Dir(exists=False))
| _FakePluginConfig |
python | getsentry__sentry | src/sentry/integrations/discord/analytics.py | {
"start": 316,
"end": 471
} | class ____(analytics.Event):
command_name: str
@analytics.eventclass("integrations.discord.identity_linked")
| DiscordIntegrationCommandInteractionReceived |
python | openai__openai-python | src/openai/types/realtime/realtime_tools_config_union.py | {
"start": 617,
"end": 1134
} | class ____(BaseModel):
read_only: Optional[bool] = None
"""Indicates whether or not a tool modifies data or is read-only.
If an MCP server is
[annotated with `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint),
it will match this filter.
... | McpAllowedToolsMcpToolFilter |
python | ansible__ansible | lib/ansible/errors/__init__.py | {
"start": 8039,
"end": 8123
} | class ____(AnsibleRuntimeError):
"""A module failed somehow."""
| AnsibleModuleError |
python | huggingface__transformers | src/transformers/models/videomae/modeling_videomae.py | {
"start": 13563,
"end": 14900
} | class ____(GradientCheckpointingLayer):
"""This corresponds to the Block class in the timm implementation."""
def __init__(self, config: VideoMAEConfig):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = VideoM... | VideoMAELayer |
python | PrefectHQ__prefect | src/prefect/serializers.py | {
"start": 9225,
"end": 9512
} | class ____(CompressedSerializer[D]):
"""
A compressed serializer preconfigured to use the pickle serializer.
"""
type: str = Field(default="compressed/pickle", frozen=True)
serializer: Serializer[D] = Field(default_factory=PickleSerializer)
| CompressedPickleSerializer |
python | ray-project__ray | python/ray/serve/_private/benchmarks/microbenchmark.py | {
"start": 730,
"end": 5273
} | class ____:
def ready(self):
return "ok"
async def do_queries(self, num, data):
async with aiohttp.ClientSession() as session:
for _ in range(num):
await fetch(session, data)
def build_app(
intermediate_handles: bool,
num_replicas: int,
max_batch_size: ... | Client |
python | openai__openai-python | src/openai/types/evals/run_create_params.py | {
"start": 9283,
"end": 10076
} | class ____(TypedDict, total=False):
format: ResponseFormatTextConfigParam
"""An object specifying the format that the model must output.
Configuring `{ "type": "json_schema" }` enables Structured Outputs, which
ensures the model will match your supplied JSON schema. Learn more in the
[Structured Ou... | DataSourceCreateEvalResponsesRunDataSourceSamplingParamsText |
python | pytorch__pytorch | torch/fx/experimental/meta_tracer.py | {
"start": 3590,
"end": 4327
} | class ____(MetaProxy):
def __init__(self, root, attr: str):
self.root = root
self.attr = attr
self.tracer = root.tracer
self._node = None
@property
def node(self): # type: ignore[override]
# the node for attributes is added lazily, since most will just be method cal... | MetaAttribute |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/variables/variable_ops_test.py | {
"start": 1659,
"end": 12294
} | class ____(test.TestCase):
def _initFetch(self, x, tftype, use_gpu=None):
with self.test_session(use_gpu=use_gpu):
p = state_ops.variable_op(x.shape, tftype)
op = state_ops.assign(p, x)
op.op.run()
return self.evaluate(p)
def _testTypes(self, vals):
for dtype in [
np.float1... | VariableOpTest |
python | redis__redis-py | redis/event.py | {
"start": 634,
"end": 1211
} | class ____(ABC):
"""
Represents a dispatcher that dispatches events to listeners
associated with given event.
"""
@abstractmethod
def dispatch(self, event: object):
pass
@abstractmethod
async def dispatch_async(self, event: object):
pass
@abstractmethod
def reg... | EventDispatcherInterface |
python | django__django | tests/generic_relations_regress/models.py | {
"start": 1985,
"end": 2135
} | class ____(models.Model):
name = models.CharField(max_length=100)
tlinks = GenericRelation(TextLink)
# models for test_q_object_or:
| OddRelation2 |
python | pallets__click | src/click/types.py | {
"start": 13568,
"end": 15969
} | class ____(ParamType):
"""The DateTime type converts date strings into `datetime` objects.
The format strings which are checked are configurable, but default to some
common (non-timezone aware) ISO 8601 formats.
When specifying *DateTime* formats, you should only pass a list or a tuple.
Other iter... | DateTime |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/managed_kafka.py | {
"start": 1670,
"end": 1909
} | class ____(BaseGoogleLink):
"""Helper class for constructing Apache Kafka Clusters link."""
name = "Apache Kafka Cluster List"
key = "cluster_list_conf"
format_str = MANAGED_KAFKA_CLUSTER_LIST_LINK
| ApacheKafkaClusterListLink |
python | doocs__leetcode | solution/0600-0699/0678.Valid Parenthesis String/Solution.py | {
"start": 0,
"end": 559
} | class ____:
def checkValidString(self, s: str) -> bool:
n = len(s)
dp = [[False] * n for _ in range(n)]
for i, c in enumerate(s):
dp[i][i] = c == '*'
for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
dp[i][j] = (
s[i]... | Solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.