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 | airbytehq__airbyte | airbyte-integrations/connectors/source-hubspot/components.py | {
"start": 12112,
"end": 13195
} | class ____(RecordTransformation):
"""
Custom transformation that takes in a record that represents a map of all dynamic properties retrieved
from the Hubspot properties endpoint. This mapping nests all of these fields under a sub-object called
`properties` and updates all the property field names at the... | HubspotRenamePropertiesTransformation |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/log.py | {
"start": 1570,
"end": 1679
} | class ____(BaseModel):
"""Response for the external log URL endpoint."""
url: str
| ExternalLogUrlResponse |
python | tiangolo__fastapi | docs_src/response_model/tutorial001_01_py310.py | {
"start": 78,
"end": 469
} | class ____(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
tags: list[str] = []
@app.post("/items/")
async def create_item(item: Item) -> Item:
return item
@app.get("/items/")
async def read_items() -> list[Item]:
return [
Item(name="Por... | Item |
python | getsentry__sentry | src/sentry/deletions/defaults/organization.py | {
"start": 436,
"end": 3860
} | class ____(ModelDeletionTask[Organization]):
def should_proceed(self, instance: Organization) -> bool:
"""
Only delete organizations that haven't been undeleted.
"""
return instance.status in {
OrganizationStatus.PENDING_DELETION,
OrganizationStatus.DELETION_I... | OrganizationDeletionTask |
python | openai__gym | gym/envs/box2d/bipedal_walker.py | {
"start": 27451,
"end": 31174
} | class ____:
def __init__(self):
raise error.Error(
"Error initializing BipedalWalkerHardcore Environment.\n"
"Currently, we do not support initializing this mode of environment by calling the class directly.\n"
"To use this environment, instead create it by specifying the... | BipedalWalkerHardcore |
python | facebook__pyre-check | client/commands/incremental.py | {
"start": 1418,
"end": 7490
} | class ____:
exit_code: commands.ExitCode
connected_to: ServerStatus
def parse_type_error_response_json(response_json: object) -> TypeErrors:
try:
# The response JSON is expected to have one of the following form:
# `["TypeErrors", [error_json0, error_json1, ...]]` (legacy form)
# `... | ExitStatus |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/spacetobatch_op_test.py | {
"start": 22129,
"end": 23619
} | class ____(test.TestCase):
# Check the gradients.
def _checkGrad(self, x, block_shape, paddings):
block_shape = np.array(block_shape)
paddings = np.array(paddings).reshape((len(block_shape), 2))
with self.cached_session():
tf_x = ops.convert_to_tensor(x)
tf_y = array_ops.space_to_batch_nd(t... | SpaceToBatchNDGradientTest |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/win32_types.py | {
"start": 3905,
"end": 4197
} | class ____(Structure):
"""struct in wincon.h."""
if TYPE_CHECKING:
Left: int
Top: int
Right: int
Bottom: int
_fields_ = [
("Left", c_short),
("Top", c_short),
("Right", c_short),
("Bottom", c_short),
]
| SMALL_RECT |
python | jazzband__django-waffle | test_app/views.py | {
"start": 3358,
"end": 3443
} | class ____(WaffleSampleMixin, BaseWaffleView):
waffle_sample = '!foo'
| SampleOffView |
python | huggingface__transformers | src/transformers/models/oneformer/convert_to_hf_oneformer.py | {
"start": 9145,
"end": 50477
} | class ____:
def __init__(self, original_model: nn.Module, config: OneFormerConfig):
self.original_model = original_model
self.config = config
def pop_all(self, renamed_keys: list[tuple[str, str]], dst_state_dict: StateDict, src_state_dict: StateDict):
for src_key, dst_key in renamed_key... | OriginalOneFormerCheckpointToOursConverter |
python | tensorflow__tensorflow | tensorflow/lite/python/metrics/metrics_nonportable.py | {
"start": 2545,
"end": 4398
} | class ____(metrics_interface.TFLiteMetricsInterface):
"""TFLite metrics helper for prod (borg) environment.
Attributes:
model_hash: A string containing the hash of the model binary.
model_path: A string containing the path of the model for debugging
purposes.
"""
def __init__(self,
... | TFLiteMetrics |
python | getsentry__sentry | src/sentry/replays/lib/storage.py | {
"start": 2171,
"end": 2712
} | class ____(ABC):
@abstractmethod
def delete(self, segment: RecordingSegmentStorageMeta) -> None:
"""Remove a blob from remote storage."""
raise NotImplementedError
@abstractmethod
def get(self, segment: RecordingSegmentStorageMeta) -> bytes | None:
"""Return blob from remote sto... | Blob |
python | getsentry__sentry | src/sentry/explore/models.py | {
"start": 1606,
"end": 2386
} | class ____(DefaultFieldsModel):
__relocation_scope__ = RelocationScope.Organization
user_id = HybridCloudForeignKey("sentry.User", on_delete="CASCADE")
organization = FlexibleForeignKey("sentry.Organization")
explore_saved_query = FlexibleForeignKey("explore.ExploreSavedQuery")
last_visited = mode... | ExploreSavedQueryLastVisited |
python | tornadoweb__tornado | tornado/httpclient.py | {
"start": 30195,
"end": 31897
} | class ____:
"""Combines an object with a dictionary of defaults.
Used internally by AsyncHTTPClient implementations.
"""
def __init__(
self, request: HTTPRequest, defaults: Optional[Dict[str, Any]]
) -> None:
self.request = request
self.defaults = defaults
def __getatt... | _RequestProxy |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/workspace/workspace.py | {
"start": 727,
"end": 830
} | class ____(Enum):
CODE_SERVER = "CODE_SERVER"
CONNECTION = "CONNECTION"
@record
| DefinitionsSource |
python | tensorflow__tensorflow | tensorflow/python/distribute/central_storage_strategy.py | {
"start": 1060,
"end": 8789
} | class ____(distribute_lib.Strategy):
"""A one-machine strategy that puts all variables on a single device.
Variables are assigned to local CPU or the only GPU. If there is more
than one GPU, compute operations (other than variable update operations)
will be replicated across all GPUs.
For Example:
```
s... | CentralStorageStrategy |
python | pytorch__pytorch | torch/testing/_internal/distributed/rpc/dist_optimizer_test.py | {
"start": 1235,
"end": 2719
} | class ____(optim.Optimizer):
def __init__(self, params):
super().__init__(params, {})
raise ValueError("Error creating optimizer.")
def step(self, closure=None):
raise NotImplementedError
def _call_method(method, obj_rref, *args, **kwargs):
return method(obj_rref.local_value(), *a... | OptimizerFailingOnConstructor |
python | pennersr__django-allauth | allauth/account/views.py | {
"start": 38174,
"end": 38782
} | class ____(BaseReauthenticateView):
form_class = ReauthenticateForm
template_name = "account/reauthenticate." + app_settings.TEMPLATE_EXTENSION
def get_form_class(self):
return get_form_class(app_settings.FORMS, "reauthenticate", self.form_class)
def get_form_kwargs(self):
ret = super(... | ReauthenticateView |
python | pytorch__pytorch | test/inductor/test_segmented_tree.py | {
"start": 965,
"end": 9037
} | class ____(TestCase):
# Basic construction and initialization tests
def test_basic_construction(self):
values = [1, 3, 5, 7, 9]
tree = SegmentedTree(values, add_op, max_op, 0)
assert tree.summarize_range(0, 4) == 9
def test_empty_array(self):
with self.assertRaises(ValueErro... | TestSegmentedTree |
python | langchain-ai__langchain | libs/langchain/langchain_classic/chains/openai_functions/openapi.py | {
"start": 7510,
"end": 15412
} | class ____(Chain):
"""Chain for making a simple request to an API endpoint."""
request_method: Callable
"""Method to use for making the request."""
output_key: str = "response"
"""Key to use for the output of the request."""
input_key: str = "function"
"""Key to use for the input of the req... | SimpleRequestChain |
python | chroma-core__chroma | chromadb/test/configurations/test_collection_configuration.py | {
"start": 894,
"end": 1135
} | class ____(EmbeddingFunction[Embeddable]):
def __init__(self) -> None:
pass
def __call__(self, input: Embeddable) -> Embeddings:
return cast(Embeddings, np.array([[1.0, 2.0]], dtype=np.float32))
| LegacyEmbeddingFunction |
python | pypa__warehouse | tests/unit/email/test_init.py | {
"start": 198119,
"end": 201408
} | class ____:
@pytest.mark.parametrize(
("action", "method", "pretty_method"),
[
("added", "totp", "TOTP"),
("removed", "totp", "TOTP"),
("added", "webauthn", "WebAuthn"),
("removed", "webauthn", "WebAuthn"),
],
)
def test_two_factor_emai... | TestTwoFactorEmail |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/guides/dagster/development_to_production/resources/resources_v2.py | {
"start": 64,
"end": 734
} | class ____:
"""Hacker News Client that returns fake data."""
def __init__(self):
self.data = {
1: {
"id": 1,
"type": "comment",
"title": "the first comment",
"by": "user1",
},
2: {"id": 2, "type": "story... | StubHNClient |
python | PrefectHQ__prefect | src/prefect/exceptions.py | {
"start": 6595,
"end": 6950
} | class ____(PrefectException):
"""
Raised when the client receives a 403 (forbidden) from the API due to reaching an object limit (e.g. maximum number of deployments).
"""
def __init__(self, http_exc: Exception, *args: Any, **kwargs: Any) -> None:
self.http_exc = http_exc
super().__init_... | ObjectLimitReached |
python | pyca__cryptography | src/cryptography/hazmat/primitives/serialization/pkcs12.py | {
"start": 1147,
"end": 5104
} | class ____:
def __init__(
self,
key: PrivateKeyTypes | None,
cert: PKCS12Certificate | None,
additional_certs: list[PKCS12Certificate],
):
if key is not None and not isinstance(
key,
(
rsa.RSAPrivateKey,
dsa.DSAPriva... | PKCS12KeyAndCertificates |
python | doocs__leetcode | lcof2/剑指 Offer II 118. 多余的边/Solution.py | {
"start": 0,
"end": 371
} | class ____:
def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
def find(x):
if p[x] != x:
p[x] = find(p[x])
return p[x]
p = list(range(1010))
for a, b in edges:
if find(a) == find(b):
return [a, b]
... | Solution |
python | sympy__sympy | sympy/physics/quantum/state.py | {
"start": 7555,
"end": 9602
} | class ____(StateBase):
"""Base class for Kets.
This class defines the dual property and the brackets for printing. This is
an abstract base class and you should not instantiate it directly, instead
use Ket.
"""
kind = KetKind
lbracket = _straight_bracket
rbracket = _rbracket
lbrac... | KetBase |
python | kubernetes-client__python | kubernetes/client/models/v1_api_group.py | {
"start": 383,
"end": 10450
} | 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... | V1APIGroup |
python | jazzband__prettytable | tests/test_prettytable.py | {
"start": 40506,
"end": 41021
} | class ____:
def test_unbordered(self, unpadded_pt: PrettyTable) -> None:
unpadded_pt.border = False
result = unpadded_pt.get_string()
expected = """
abc
def
g..
"""
assert result.strip() == expected.strip()
def test_bordered(self, unpadded_pt: PrettyTable) -> None:
unpad... | TestUnpaddedTable |
python | ray-project__ray | python/ray/serve/_private/benchmarks/common.py | {
"start": 4767,
"end": 5018
} | class ____:
def __init__(self, child):
logging.getLogger("ray.serve").setLevel(logging.WARNING)
self._child = child
async def __call__(self, *args, **kwargs):
return await self._child.remote()
@serve.deployment
| ModelComp |
python | google__pytype | pytype/overlays/flax_overlay.py | {
"start": 2245,
"end": 3590
} | class ____(dataclass_overlay.Dataclass):
"""Dataclass with automatic 'name' and 'parent' members."""
def _add_implicit_field(self, node, cls_locals, key, typ):
if key in cls_locals:
self.ctx.errorlog.invalid_annotation(
self.ctx.vm.frames,
None,
name=key,
details=f... | ModuleDataclass |
python | doocs__leetcode | solution/0000-0099/0058.Length of Last Word/Solution.py | {
"start": 0,
"end": 235
} | class ____:
def lengthOfLastWord(self, s: str) -> int:
i = len(s) - 1
while i >= 0 and s[i] == ' ':
i -= 1
j = i
while j >= 0 and s[j] != ' ':
j -= 1
return i - j
| Solution |
python | paramiko__paramiko | paramiko/kex_group14.py | {
"start": 1731,
"end": 1833
} | class ____(KexGroup14):
name = "diffie-hellman-group14-sha256"
hash_algo = sha256
| KexGroup14SHA256 |
python | mlflow__mlflow | .claude/hooks/lint.py | {
"start": 365,
"end": 560
} | class ____:
file: Path
line: int
column: int
message: str
def __str__(self) -> str:
return f"{self.file}:{self.line}:{self.column}: {self.message}"
@dataclass
| LintError |
python | pytorch__pytorch | torch/onnx/_internal/exporter/_registration.py | {
"start": 6066,
"end": 12631
} | class ____:
"""Registry for ONNX functions.
The registry maintains a mapping from qualified names to symbolic functions under a
fixed opset version. It supports registering custom onnx-script functions and for
dispatcher to dispatch calls to the appropriate function.
"""
def __init__(self) ->... | ONNXRegistry |
python | graphql-python__graphene | graphene/types/json.py | {
"start": 123,
"end": 851
} | class ____(Scalar):
"""
Allows use of a JSON String for input / output from the GraphQL schema.
Use of this type is *not recommended* as you lose the benefits of having a defined, static
schema (one of the key benefits of GraphQL).
"""
@staticmethod
def serialize(dt):
return json.d... | JSONString |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_json__property.py | {
"start": 1288,
"end": 2979
} | class ____:
def test_valid(self) -> None:
prop = bcpj.JSON()
assert prop.is_valid('[]')
assert prop.is_valid('[{"foo": 10}]')
def test_invalid(self) -> None:
prop = bcpj.JSON()
assert not prop.is_valid(None)
assert not prop.is_valid("")
assert not prop.... | Test_JSON |
python | ray-project__ray | rllib/algorithms/dreamerv3/torch/models/components/reward_predictor_layer.py | {
"start": 407,
"end": 4482
} | class ____(nn.Module):
"""A layer outputting reward predictions using K bins and two-hot encoding.
This layer is used in two models in DreamerV3: The reward predictor of the world
model and the value function. K is 255 by default (see [1]) and doesn't change
with the model size.
Possible predicted... | RewardPredictorLayer |
python | getsentry__sentry | tests/sentry/monitors/test_validators.py | {
"start": 1293,
"end": 12437
} | class ____(MonitorTestCase):
def setUp(self) -> None:
super().setUp()
self.login_as(self.user)
self.request = RequestFactory().get("/")
self.request.user = self.user
access = MagicMock()
access.has_any_project_scope.return_value = True
self.request.access = ... | MonitorValidatorCreateTest |
python | sqlalchemy__sqlalchemy | test/engine/test_transaction.py | {
"start": 39639,
"end": 51683
} | class ____(fixtures.TestBase):
"""see also sqlalchemy/testing/suite/test_dialect.py::IsolationLevelTest
this suite has sparse_backend so wont take place
for every dbdriver under a nox run. the suite test should cover
that end of it
"""
__requires__ = ("isolation_level",)
__sparse_driver... | IsolationLevelTest |
python | gevent__gevent | src/gevent/tests/test__queue.py | {
"start": 16035,
"end": 16111
} | class ____(TestGetInterrupt):
kind = queue.Channel
| TestGetInterruptChannel |
python | django__django | tests/files/tests.py | {
"start": 10522,
"end": 12160
} | class ____(unittest.TestCase):
"""
get_image_dimensions() properly closes files (#8817)
"""
@unittest.skipUnless(Image, "Pillow not installed")
def test_not_closing_of_files(self):
"""
Open files passed into get_image_dimensions() should stay opened.
"""
empty_io = B... | DimensionClosingBug |
python | joke2k__faker | tests/providers/test_job.py | {
"start": 2833,
"end": 3022
} | class ____:
"""Test fr_FR job provider"""
def test_job(self, faker, num_samples):
for _ in range(num_samples):
assert faker.job() in FrFrJobProvider.jobs
| TestFrFr |
python | mitmproxy__pdoc | pdoc/__init__.py | {
"start": 10568,
"end": 10635
} | class ____(BaseModel):
a: int
"""Docs for field a."""
| OtherFoo |
python | getsentry__sentry | src/sentry/api/bases/organization.py | {
"start": 4879,
"end": 5283
} | class ____(OrganizationPermission):
scope_map = {
"GET": ["project:read", "project:write", "project:admin", "project:releases", "org:ci"],
"POST": ["project:write", "project:admin", "project:releases", "org:ci"],
"PUT": ["project:write", "project:admin", "project:releases", "org:ci"],
... | OrganizationReleasePermission |
python | mlflow__mlflow | mlflow/genai/scorers/base.py | {
"start": 1575,
"end": 1843
} | class ____:
"""Configuration for registered scorer sampling."""
sample_rate: float | None = None
filter_string: str | None = None
AggregationFunc = Callable[[list[float]], float] # List of per-row value -> aggregated value
@dataclass
| ScorerSamplingConfig |
python | django__django | django/core/serializers/pyyaml.py | {
"start": 594,
"end": 1245
} | class ____(SafeDumper):
def represent_decimal(self, data):
return self.represent_scalar("tag:yaml.org,2002:str", str(data))
def represent_ordered_dict(self, data):
return self.represent_mapping("tag:yaml.org,2002:map", data.items())
DjangoSafeDumper.add_representer(decimal.Decimal, DjangoSafe... | DjangoSafeDumper |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeAlias18.py | {
"start": 334,
"end": 512
} | class ____(Generic[T1]):
pass
A_Alias_1: TypeAlias = A[T2]
A_Alias_2: TypeAlias = A_Alias_1[T2 | int]
# This should generate an error because the variance is incompatible.
| A |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_header03.py | {
"start": 315,
"end": 993
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("header03.xlsx")
self.ignore_elements = {
"xl/worksheets/sheet1.xml": ["<pageMargins", "<pageSetup"]
}
def test_create_... | TestCompareXLSXFiles |
python | jazzband__tablib | src/tablib/formats/_rst.py | {
"start": 633,
"end": 9226
} | class ____:
title = 'rst'
extensions = ('rst',)
MAX_TABLE_WIDTH = 80 # Roughly. It may be wider to avoid breaking words.
@classmethod
def _get_column_string_lengths(cls, dataset):
"""
Returns a list of string lengths of each column, and a list of
maximum word lengths.
... | ReSTFormat |
python | huggingface__transformers | src/transformers/models/rt_detr/modeling_rt_detr.py | {
"start": 32588,
"end": 37329
} | class ____(nn.Module):
"""
Multiscale deformable attention as proposed in Deformable DETR.
"""
def __init__(self, config: RTDetrConfig, num_heads: int, n_points: int):
super().__init__()
self.attn = MultiScaleDeformableAttention()
if config.d_model % num_heads != 0:
... | RTDetrMultiscaleDeformableAttention |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_florida_zip.py | {
"start": 1743,
"end": 4078
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid Florida zipcodes.
See https://pypi.org/project/zipcodes/ for more information.
"""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
... | ExpectColumnValuesToBeValidFloridaZip |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/legacy_storage.py | {
"start": 14755,
"end": 31384
} | class ____(EventLogStorage, ConfigurableClass):
def __init__(self, storage: DagsterStorage, inst_data: Optional[ConfigurableClassData] = None):
self._storage = check.inst_param(storage, "storage", DagsterStorage)
self._inst_data = check.opt_inst_param(inst_data, "inst_data", ConfigurableClassData)
... | LegacyEventLogStorage |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/inputs.py | {
"start": 12573,
"end": 13168
} | class ____(graphene.InputObjectType):
parentRunId = graphene.NonNull(graphene.String)
strategy = graphene.NonNull(GrapheneReexecutionStrategy)
extraTags = graphene.List(
graphene.NonNull(GrapheneExecutionTag),
description="""When re-executing a single run, pass new tags which will upsert ove... | GrapheneReexecutionParams |
python | pytorch__pytorch | torch/fx/experimental/symbolic_shapes.py | {
"start": 69382,
"end": 70878
} | class ____(Constraint):
"""
For clients: no explicit constraint; constraint is whatever is implicitly
inferred by guards from tracing.
For backends: there must exist at least TWO possible values for the
size at this dimension which satisfy the guards for this dimension.
In other words, this co... | RelaxedUnspecConstraint |
python | scipy__scipy | scipy/sparse/tests/test_sputils.py | {
"start": 294,
"end": 16486
} | class ____:
def test_upcast(self):
assert_equal(sputils.upcast('intc'), np.intc)
assert_equal(sputils.upcast('int32', 'float32'), np.float64)
assert_equal(sputils.upcast('bool', complex, float), np.complex128)
assert_equal(sputils.upcast('i', 'd'), np.float64)
def test_getdtype... | TestSparseUtils |
python | huggingface__transformers | src/transformers/trainer_utils.py | {
"start": 5045,
"end": 6310
} | class ____:
"""
Evaluation output (always contains labels), to be used to compute metrics.
Parameters:
predictions (`np.ndarray`): Predictions of the model.
label_ids (`np.ndarray`): Targets to be matched.
inputs (`np.ndarray`, *optional*): Input data passed to the model.
lo... | EvalPrediction |
python | qdrant__qdrant-client | qdrant_client/embed/embedder.py | {
"start": 480,
"end": 652
} | class ____(BaseModel, Generic[T], arbitrary_types_allowed=True): # type: ignore[call-arg]
model: T
options: dict[str, Any]
deprecated: bool = False
| ModelInstance |
python | django-compressor__django-compressor | compressor/tests/test_offline.py | {
"start": 28380,
"end": 29456
} | class ____(OfflineTestCaseMixin, TestCase):
templates_dir = "test_complex"
additional_test_settings = {
"COMPRESS_OFFLINE_CONTEXT": {
"condition": "OK!",
# Django templating does not allow definition of tuples in the
# templates.
# Make sure this is same a... | OfflineCompressComplexTestCase |
python | mkdocs__mkdocs | mkdocs/config/config_options.py | {
"start": 15349,
"end": 16271
} | class ____(OptionallyRequired[_IpAddressValue]):
"""
IpAddress Config Option.
Validate that an IP address is in an appropriate format
"""
def run_validation(self, value: object) -> _IpAddressValue:
if not isinstance(value, str) or ':' not in value:
raise ValidationError("Must b... | IpAddress |
python | pytorch__pytorch | torch/distributed/algorithms/_checkpoint/checkpoint_wrapper.py | {
"start": 561,
"end": 640
} | class ____(Enum):
REENTRANT = auto()
NO_REENTRANT = auto()
| CheckpointImpl |
python | django-extensions__django-extensions | tests/management/commands/test_show_permissions.py | {
"start": 148,
"end": 3989
} | class ____(TestCase):
def _run_command(self, *args, **kwargs):
"""
Utility to run the command and return captured output.
"""
out = StringIO()
sys_stdout = sys.stdout
sys.stdout = out
try:
call_command("show_permissions", *args, **kwargs)
f... | ShowPermissionsTests |
python | django__django | tests/annotations/models.py | {
"start": 1632,
"end": 1922
} | class ____(models.Model):
name = models.CharField(max_length=200)
motto = models.CharField(max_length=200, null=True, blank=True)
ticker_name = models.CharField(max_length=10, null=True, blank=True)
description = models.CharField(max_length=200, null=True, blank=True)
| Company |
python | ansible__ansible | test/units/parsing/vault/test_vault.py | {
"start": 15135,
"end": 16615
} | class ____(unittest.TestCase):
def test_file(self):
password = 'some password'
tmp_file = tempfile.NamedTemporaryFile(delete=False)
tmp_file.write(to_bytes(password))
tmp_file.close()
fake_loader = DictDataLoader({tmp_file.name: 'sdfadf'})
secret = vault.get_file_v... | TestGetFileVaultSecret |
python | cherrypy__cherrypy | cherrypy/_cpnative_server.py | {
"start": 264,
"end": 4661
} | class ____(cheroot.server.Gateway):
"""Native gateway implementation allowing to bypass WSGI."""
recursive = False
def respond(self):
"""Obtain response from CherryPy machinery and then send it."""
req = self.req
try:
# Obtain a Request object from CherryPy
... | NativeGateway |
python | great-expectations__great_expectations | great_expectations/expectations/expectation.py | {
"start": 73343,
"end": 80079
} | class ____(Expectation, ABC):
"""Base class for BatchExpectations.
BatchExpectations answer a semantic question about a Batch of data.
For example, `expect_table_column_count_to_equal` and `expect_table_row_count_to_equal` answer
how many columns and rows are in your table.
BatchExpectations must... | BatchExpectation |
python | pydata__xarray | xarray/backends/netCDF4_.py | {
"start": 11995,
"end": 12141
} | class ____:
"""Pickleable equivalent of `lambda: value`."""
value: Any
def __call__(self):
return self.value
@dataclass
| _Thunk |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 978333,
"end": 987984
} | class ____(FieldChannelMixin, core.SecondaryFieldDef):
r"""
X2 schema wrapper.
A field definition of a secondary channel that shares a scale with another primary channel.
For example, ``x2``, ``xError`` and ``xError2`` share the same scale with ``x``.
Parameters
----------
shorthand : str,... | X2 |
python | tornadoweb__tornado | demos/file_upload/file_receiver.py | {
"start": 407,
"end": 872
} | class ____(tornado.web.RequestHandler):
def post(self):
for field_name, files in self.request.files.items():
for info in files:
filename, content_type = info["filename"], info["content_type"]
body = info["body"]
logging.info(
'P... | POSTHandler |
python | plotly__plotly.py | plotly/graph_objs/isosurface/slices/_z.py | {
"start": 233,
"end": 5303
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "isosurface.slices"
_path_str = "isosurface.slices.z"
_valid_props = {"fill", "locations", "locationssrc", "show"}
@property
def fill(self):
"""
Sets the fill ratio of the `slices`. The default fill value of
the `slices... | Z |
python | kamyu104__LeetCode-Solutions | Python/unique-binary-search-trees-ii.py | {
"start": 755,
"end": 1385
} | class ____(object):
# @return a list of tree node
def generateTrees(self, n):
return self.generateTreesRecu(1, n)
def generateTreesRecu(self, low, high):
result = []
if low > high:
result.append(None)
for i in xrange(low, high + 1):
left = self.genera... | Solution |
python | huggingface__transformers | src/transformers/models/shieldgemma2/configuration_shieldgemma2.py | {
"start": 806,
"end": 4805
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`ShieldGemma2ForImageClassification`]. It is used to instantiate an
ShieldGemma2ForImageClassification according to the specified arguments, defining the model architecture. Instantiating a configuration
... | ShieldGemma2Config |
python | pyqtgraph__pyqtgraph | pyqtgraph/opengl/items/GLBoxItem.py | {
"start": 189,
"end": 2513
} | class ____(GLGraphicsItem):
"""
**Bases:** :class:`GLGraphicsItem <pyqtgraph.opengl.GLGraphicsItem>`
Displays a wire-frame box.
"""
def __init__(self, size=None, color=None, glOptions='translucent', parentItem=None):
super().__init__()
self.lineplot = None # mark that we are... | GLBoxItem |
python | pypa__warehouse | tests/unit/cache/origin/test_init.py | {
"start": 2198,
"end": 4721
} | class ____:
def test_no_cache_key(self):
response = pretend.stub()
@origin.origin_cache(1)
def view(context, request):
return response
def raiser(iface):
raise LookupError
context = pretend.stub()
request = pretend.stub(registry={"cache_keys... | TestOriginCache |
python | coleifer__peewee | bench.py | {
"start": 322,
"end": 370
} | class ____(Base):
name = TextField()
| Collection |
python | walkccc__LeetCode | solutions/2143. Choose Numbers From Two Arrays in Range/2143.py | {
"start": 0,
"end": 643
} | class ____:
def countSubranges(self, nums1: list[int], nums2: list[int]) -> int:
MOD = 1_000_000_007
ans = 0
# {sum, count}, add if choose from nums1, minus if choose from nums2
dp = collections.Counter()
for a, b in zip(nums1, nums2):
newDp = collections.Counter()
newDp[a] += 1
... | Solution |
python | kamyu104__LeetCode-Solutions | Python/number-of-longest-increasing-subsequence.py | {
"start": 31,
"end": 772
} | class ____(object):
def findNumberOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result, max_len = 0, 0
dp = [[1, 1] for _ in xrange(len(nums))] # {length, number} pair
for i in xrange(len(nums)):
for j in xrange(i):
... | Solution |
python | huggingface__transformers | src/transformers/models/plbart/modeling_plbart.py | {
"start": 2752,
"end": 3058
} | class ____(PreTrainedModel):
config: PLBartConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["PLBartDecoderLayer", "PLBartEncoderLayer"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
| PLBartPreTrainedModel |
python | getsentry__sentry | src/sentry/overwatch_webhooks/webhook_forwarder.py | {
"start": 1229,
"end": 1610
} | class ____:
organization_integration: OrganizationIntegration
organization_mapping: OrganizationMapping
logger = logging.getLogger("sentry.overwatch_webhook_forwarder")
def verbose_log(msg: str, *, extra: dict | None = None) -> None:
if bool(options.get("overwatch.forward-webhooks.verbose", False)):
... | OverwatchOrganizationContext |
python | openai__openai-python | src/openai/types/beta/assistant_stream_event.py | {
"start": 4921,
"end": 5146
} | class ____(BaseModel):
data: Message
"""
Represents a message within a
[thread](https://platform.openai.com/docs/api-reference/threads).
"""
event: Literal["thread.message.created"]
| ThreadMessageCreated |
python | django__django | django/urls/resolvers.py | {
"start": 17436,
"end": 32046
} | class ____:
def __init__(
self, pattern, urlconf_name, default_kwargs=None, app_name=None, namespace=None
):
self.pattern = pattern
# urlconf_name is the dotted Python path to the module defining
# urlpatterns. It may also be an object with an urlpatterns attribute
# or u... | URLResolver |
python | pandas-dev__pandas | asv_bench/benchmarks/io/json.py | {
"start": 9004,
"end": 9705
} | class ____:
def setup_cache(self):
df = DataFrame([[1]])
df2 = DataFrame(range(8), date_range("1/1/2000", periods=8, freq="min"))
frames = {"int": df, "float": df.astype(float), "datetime": df2}
return frames
def peakmem_int(self, frames):
df = frames["int"]
for... | ToJSONMem |
python | ipython__ipython | tests/test_process.py | {
"start": 2669,
"end": 6091
} | class ____(tt.TempFileMixin):
def setUp(self):
"""Make a valid python temp file."""
lines = [
"import sys",
"print('on stdout', end='', file=sys.stdout)",
"print('on stderr', end='', file=sys.stderr)",
"sys.stdout.flush()",
"sys.stderr.flus... | SubProcessTestCase |
python | walkccc__LeetCode | solutions/3174. Clear Digits/3174.py | {
"start": 0,
"end": 340
} | class ____:
def clearDigits(self, s: str) -> str:
ans = []
for c in s:
if c.isdigit():
# Since `ans` only contains non-digit characters, removing the last
# character is equivalent to deleting the closest non-digit character.
ans.pop()
else:
ans.append(c)
retu... | Solution |
python | python-visualization__folium | folium/map.py | {
"start": 20432,
"end": 22064
} | class ____(MacroElement):
"""Fit the map to contain a bounding box with the
maximum zoom level possible.
Parameters
----------
bounds: list of (latitude, longitude) points
Bounding box specified as two points [southwest, northeast]
padding_top_left: (x, y) point, default None
Pa... | FitBounds |
python | django__django | tests/fixtures/models.py | {
"start": 1860,
"end": 1974
} | class ____(models.Manager):
def get_by_natural_key(self, name):
return self.get(name=name)
| PersonManager |
python | apache__airflow | providers/imap/tests/unit/imap/sensors/test_imap_attachment.py | {
"start": 959,
"end": 2076
} | class ____:
def setup_method(self):
self.kwargs = dict(
attachment_name="test_file",
check_regex=False,
mail_folder="INBOX",
mail_filter="All",
task_id="test_task",
dag=None,
)
@pytest.mark.parametrize("has_attachment_retur... | TestImapAttachmentSensor |
python | walkccc__LeetCode | solutions/2876. Count Visited Nodes in a Directed Graph/2876.py | {
"start": 0,
"end": 1174
} | class ____:
def countVisitedNodes(self, edges: list[int]) -> list[int]:
n = len(edges)
ans = [0] * n
inDegrees = [0] * n
seen = [False] * n
stack = []
for v in edges:
inDegrees[v] += 1
# Perform topological sorting.
q = collections.deque([i for i, d in enumerate(inDegrees) if d... | Solution |
python | cython__cython | Cython/Tempita/_looper.py | {
"start": 1310,
"end": 3975
} | class ____:
def __init__(self, seq, pos):
self.seq = seq
self.pos = pos
def __repr__(self):
return '<loop pos=%r at %r>' % (
self.seq[self.pos], self.pos)
def index(self):
return self.pos
index = property(index)
def number(self):
return self.po... | loop_pos |
python | neetcode-gh__leetcode | python/0904_fruit_into_baskets.py | {
"start": 0,
"end": 510
} | class ____:
def totalFruit(self, fruits: List[int]) -> int:
tr = {}
l = r = 0
res = 0
while r < len(fruits):
if fruits[r] not in tr:
tr[fruits[r]] = 1
else:
tr[fruits[r]] += 1
while len(tr) > 2:
tr[fr... | Solution |
python | sqlalchemy__sqlalchemy | test/engine/test_ddlevents.py | {
"start": 18664,
"end": 27845
} | class ____(AssertsCompiledSQL, fixtures.TestBase):
def setup_test(self):
self.engine = engines.mock_engine()
self.metadata = MetaData()
self.users = Table(
"users",
self.metadata,
Column("user_id", Integer, primary_key=True),
Column("user_name"... | DDLExecutionTest |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_memorystore.py | {
"start": 7667,
"end": 8854
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.cloud_memorystore.CloudMemorystoreHook")
def test_assert_valid_hook_call(self, mock_hook):
task = CloudMemorystoreGetInstanceOperator(
task_id=TEST_TASK_ID,
location=TEST_LOCATION,
instance=TEST_INSTANC... | TestCloudMemorystoreGetInstanceOperator |
python | google__pytype | pytype/tools/traces/traces_test.py | {
"start": 567,
"end": 677
} | class ____(traces.MatchAstVisitor):
def visit_Module(self, node):
self.match(node)
| _NotImplementedVisitor |
python | openai__openai-python | src/openai/types/realtime/realtime_conversation_item_assistant_message.py | {
"start": 947,
"end": 1715
} | class ____(BaseModel):
content: List[Content]
"""The content of the message."""
role: Literal["assistant"]
"""The role of the message sender. Always `assistant`."""
type: Literal["message"]
"""The type of the item. Always `message`."""
id: Optional[str] = None
"""The unique ID of the ... | RealtimeConversationItemAssistantMessage |
python | kamyu104__LeetCode-Solutions | Python/number-of-bit-changes-to-make-two-integers-equal.py | {
"start": 357,
"end": 616
} | class ____(object):
def minChanges(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
def popcount(x):
return bin(x).count('1')
return popcount(n^k) if n|(n^k) == n else -1
| Solution2 |
python | ray-project__ray | rllib/core/testing/torch/bc_module.py | {
"start": 1699,
"end": 3888
} | class ____(TorchRLModule):
"""An example of an RLModule that uses an encoder shared with other things.
For example, we could consider a multi-agent case where for inference each agent
needs to know the global state of the environment, as well as the local state of
itself. For better representation lear... | BCTorchRLModuleWithSharedGlobalEncoder |
python | huggingface__transformers | src/transformers/models/parakeet/modeling_parakeet.py | {
"start": 27649,
"end": 29439
} | class ____(ModelOutput):
"""
Outputs of Parakeet models.
Args:
sequences (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
if all batches finished early du... | ParakeetGenerateOutput |
python | scipy__scipy | scipy/interpolate/tests/test_interpolate.py | {
"start": 53713,
"end": 71721
} | class ____:
def test_simple(self, xp):
c = xp.asarray([[1, 4], [2, 5], [3, 6]])
x = xp.asarray([0, 0.5, 1])
p = PPoly(c, x)
xp_assert_close(p(0.3), xp.asarray(1*0.3**2 + 2*0.3 + 3, dtype=xp.float64))
xp_assert_close(
p(0.7), xp.asarray(4*(0.7-0.5)**2 + 5*(0.7-0.5)... | TestPPoly |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/dynamic.py | {
"start": 2371,
"end": 3450
} | class ____(_WriteOnlyAttributeImpl):
_supports_dynamic_iteration = True
collection_history_cls = DynamicCollectionHistory[Any]
query_class: Type[_AppenderMixin[Any]] # type: ignore[assignment]
def __init__(
self,
class_: Union[Type[Any], AliasedClass[Any]],
key: str,
di... | _DynamicAttributeImpl |
python | pandas-dev__pandas | pandas/tests/indexes/categorical/test_indexing.py | {
"start": 220,
"end": 4991
} | class ____:
def test_take_fill_value(self):
# GH 12631
# numeric category
idx = CategoricalIndex([1, 2, 3], name="xxx")
result = idx.take(np.array([1, 0, -1]))
expected = CategoricalIndex([2, 1, 3], name="xxx")
tm.assert_index_equal(result, expected)
tm.asser... | TestTake |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.