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 | readthedocs__readthedocs.org | readthedocs/gold/forms.py | {
"start": 469,
"end": 1848
} | class ____(forms.Form):
"""Gold users form to select projects to remove ads from."""
project = forms.ChoiceField(
required=True,
help_text="Select a project.",
)
def __init__(self, active_user, *args, **kwargs):
self.user = kwargs.pop("user", None)
self.projects = kwarg... | GoldProjectForm |
python | run-llama__llama_index | llama-index-core/llama_index/core/node_parser/relational/unstructured_element.py | {
"start": 494,
"end": 5469
} | class ____(BaseElementNodeParser):
"""
Unstructured element node parser.
Splits a document into Text Nodes and Index Nodes corresponding to embedded objects
(e.g. tables).
"""
partitioning_parameters: Optional[Dict[str, Any]] = Field(
default={},
description="Extra dictionary ... | UnstructuredElementNodeParser |
python | pytorch__pytorch | torch/testing/_internal/opinfo/core.py | {
"start": 25633,
"end": 65204
} | class ____:
"""Operator information and helper functions for acquiring it."""
# the string name of the function
name: str
# An optional reference function that accepts ndarrays (AKA "NumPy arrays").
# If given, the op will be compared with its reference on each of its sample inputs.
ref: Optio... | OpInfo |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 14841,
"end": 15463
} | class ____(BaseModel):
"""
Serializer for External View Plugin responses.
"""
model_config = ConfigDict(
extra="allow",
)
name: Annotated[str, Field(title="Name")]
icon: Annotated[str | None, Field(title="Icon")] = None
icon_dark_mode: Annotated[str | None, Field(title="Icon Dar... | ExternalViewResponse |
python | numpy__numpy | numpy/lib/tests/test_arraysetops.py | {
"start": 23000,
"end": 47678
} | class ____:
def check_all(self, a, b, i1, i2, c, dt):
base_msg = 'check {0} failed for type {1}'
msg = base_msg.format('values', dt)
v = unique(a)
assert_array_equal(v, b, msg)
assert type(v) == type(b)
msg = base_msg.format('return_index', dt)
v, j = uniqu... | TestUnique |
python | getsentry__sentry | src/sentry/workflow_engine/handlers/condition/new_high_priority_issue_handler.py | {
"start": 454,
"end": 859
} | class ____(DataConditionHandler[WorkflowEventData]):
group = DataConditionHandler.Group.WORKFLOW_TRIGGER
comparison_json_schema = {"type": "boolean"}
@staticmethod
def evaluate_value(event_data: WorkflowEventData, comparison: Any) -> bool:
is_new = is_new_event(event_data)
return is_new... | NewHighPriorityIssueConditionHandler |
python | ray-project__ray | release/ray_release/exception.py | {
"start": 14,
"end": 947
} | class ____(enum.Enum):
# If you change these, also change the `retry` section
# in `build_pipeline.py` and the `reason()` function in `run_e2e.sh`
SUCCESS = 0 # Do not set/return this manually
UNCAUGHT = 1 # Do not set/return this manually
UNSPECIFIED = 2
UNKNOWN = 3
# Hard infra errors ... | ExitCode |
python | django__django | tests/backends/models.py | {
"start": 172,
"end": 372
} | class ____(models.Model):
root = models.IntegerField()
square = models.PositiveIntegerField(db_default=9)
def __str__(self):
return "%s ** 2 == %s" % (self.root, self.square)
| Square |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/declarative_automation_tests/scenario_utils/base_scenario.py | {
"start": 2483,
"end": 3842
} | class ____(NamedTuple):
asset_key: str
rule_evaluations: Sequence[tuple[AutoMaterializeRuleEvaluation, Optional[Iterable[str]]]]
num_requested: int = 0
num_skipped: int = 0
num_discarded: int = 0
@staticmethod
def empty(asset_key: str) -> "AssetEvaluationSpec":
return AssetEvaluatio... | AssetEvaluationSpec |
python | pypa__pip | src/pip/_vendor/urllib3/connectionpool.py | {
"start": 33197,
"end": 40408
} | class ____(HTTPConnectionPool):
"""
Same as :class:`.HTTPConnectionPool`, but HTTPS.
:class:`.HTTPSConnection` uses one of ``assert_fingerprint``,
``assert_hostname`` and ``host`` in this order to verify connections.
If ``assert_hostname`` is False, no verification is done.
The ``key_file``, `... | HTTPSConnectionPool |
python | vyperlang__vyper | vyper/exceptions.py | {
"start": 6605,
"end": 6659
} | class ____(_BaseVyperException):
pass
| VyperException |
python | spack__spack | lib/spack/spack/util/unparse/unparser.py | {
"start": 3625,
"end": 45307
} | class ____(NodeVisitor):
"""Methods in this class recursively traverse an AST and
output source code for the abstract syntax; original formatting
is disregarded."""
def __init__(self, py_ver_consistent=False, _avoid_backslashes=False):
self._source = []
self._precedences = {}
se... | Unparser |
python | dask__distributed | distributed/deploy/tests/test_spec_cluster.py | {
"start": 12400,
"end": 17011
} | class ____(Worker, ProcessInterface):
def __init__(self, *args, n=1, name=None, nthreads=None, **kwargs):
self.workers = [
Worker(
*args, name=str(name) + "-" + str(i), nthreads=nthreads // n, **kwargs
)
for i in range(n)
]
self._startup_lo... | MultiWorker |
python | gevent__gevent | src/greentest/3.14/test_httpservers.py | {
"start": 46327,
"end": 46946
} | class ____(SimpleHTTPRequestHandler):
def __init__(self, directory=None):
request = mock.Mock()
request.makefile.return_value = BytesIO()
super().__init__(request, None, None, directory=directory)
self.get_called = False
self.protocol_version = "HTTP/1.1"
def do_GET(sel... | SocketlessRequestHandler |
python | pypa__warehouse | tests/unit/helpdesk/test_services.py | {
"start": 6850,
"end": 7621
} | class ____:
"""Common tests for the service interface."""
def test_verify_service_class(self, service_class):
assert verifyClass(IAdminNotificationService, service_class)
def test_create_service(self, service_class):
context = None
request = pretend.stub(
http=pretend.s... | TestAdminNotificationService |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1138871,
"end": 1140334
} | class ____(sgqlc.types.Type, Node, RepositoryNode):
"""A category for discussions in a repository."""
__schema__ = github_schema
__field_names__ = ("created_at", "description", "emoji", "emoji_html", "is_answerable", "name", "slug", "updated_at")
created_at = sgqlc.types.Field(sgqlc.types.non_null(Date... | DiscussionCategory |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/kubernetes_engine.py | {
"start": 6789,
"end": 12058
} | class ____(GKEOperatorMixin, GoogleCloudBaseOperator):
"""
Deletes the cluster, including the Kubernetes endpoint and all worker nodes.
To delete a certain cluster, you must specify the ``project_id``, the ``cluster_name``
of the cluster, the ``location`` that the cluster is in, and the ``task_id``.
... | GKEDeleteClusterOperator |
python | spyder-ide__spyder | spyder/plugins/remoteclient/api/__init__.py | {
"start": 511,
"end": 583
} | class ____:
ManageConnections = "manage connections"
| RemoteClientActions |
python | encode__django-rest-framework | rest_framework/mixins.py | {
"start": 1712,
"end": 2613
} | class ____:
"""
Update a model instance.
"""
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=... | UpdateModelMixin |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_automation_rules.py | {
"start": 13303,
"end": 20927
} | class ____:
@pytest.fixture(autouse=True)
def setup_method(self):
self.project = get(Project)
self.rule_5 = self._add_rule("Five")
self.rule_4 = self._add_rule("Four")
self.rule_3 = self._add_rule("Three")
self.rule_2 = self._add_rule("Two")
self.rule_1 = self._ad... | TestAutomationRuleMove |
python | pandas-dev__pandas | asv_bench/benchmarks/series_methods.py | {
"start": 9694,
"end": 10725
} | class ____:
param_names = ["num_to_replace"]
params = [100, 1000]
def setup(self, num_to_replace):
N = 1_000_000
self.arr = np.random.randn(N)
self.arr1 = self.arr.copy()
np.random.shuffle(self.arr1)
self.ser = Series(self.arr)
self.to_replace_list = np.rand... | Replace |
python | Pylons__pyramid | tests/test_testing.py | {
"start": 18699,
"end": 19463
} | class ____(unittest.TestCase):
def setUp(self):
from pyramid.testing import skip_on
self.os_name = skip_on.os_name
skip_on.os_name = 'wrong'
def tearDown(self):
from pyramid.testing import skip_on
skip_on.os_name = self.os_name
def _callFUT(self, *platforms):
... | Test_skip_on |
python | pytorch__pytorch | test/distributed/test_device_mesh.py | {
"start": 2601,
"end": 4981
} | class ____(DTensorTestBase):
@property
def world_size(self):
return 4
@skip_if_lt_x_gpu(4)
def test_manual_set_device(self):
mesh_tensor = torch.arange(4).reshape(2, 2)
self.assertTrue(not is_initialized())
# Set the device on each process before DeviceMesh constructor,... | DeviceMeshSetDeviceTest |
python | zostera__django-bootstrap4 | example/app/forms.py | {
"start": 3450,
"end": 3731
} | class ____(forms.Form):
title = forms.CharField()
pub_date = forms.DateField()
def clean(self):
cleaned_data = super().clean()
raise forms.ValidationError("This error was added to show the non field errors styling.")
return cleaned_data
| ArticleForm |
python | sqlalchemy__sqlalchemy | test/orm/test_session_state_change.py | {
"start": 296,
"end": 12331
} | class ____(fixtures.TestBase):
def test_single_change(self):
"""test single method that declares and invokes a state change"""
_NO_CHANGE = state_changes._StateChangeStates.NO_CHANGE
class Machine(state_changes._StateChange):
@state_changes._StateChange.declare_states(
... | StateMachineTest |
python | facebook__pyre-check | tools/upgrade/filesystem.py | {
"start": 8301,
"end": 9427
} | class ____:
def list(
self, root: str, patterns: List[str], exclude: Optional[List[str]] = None
) -> List[str]:
"""
Return the list of files that match any of the patterns within root.
If exclude is provided, files that match an exclude pattern are omitted.
Note: The `fi... | Filesystem |
python | pandas-dev__pandas | pandas/tests/indexes/datetimes/methods/test_to_period.py | {
"start": 407,
"end": 7754
} | class ____:
def test_dti_to_period(self):
dti = date_range(start="1/1/2005", end="12/1/2005", freq="ME")
pi1 = dti.to_period()
pi2 = dti.to_period(freq="D")
pi3 = dti.to_period(freq="3D")
assert pi1[0] == Period("Jan 2005", freq="M")
assert pi2[0] == Period("1/31/200... | TestToPeriod |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli/cli/plus/deploy/configure/utils.py | {
"start": 6582,
"end": 10054
} | class ____(NamedTuple):
name: str
match: Callable[[str], bool]
fragment: Path
secrets_hints: list[str]
def _matches_ecr(url: str) -> bool:
"""Check if URL is an AWS ECR registry.
ECR URLs follow the format: <account-id>.dkr.ecr.<region>.amazonaws.com
"""
parsed = urlparse(url if "://"... | ContainerRegistryInfo |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 28417,
"end": 29894
} | class ____(Interface):
"""
WSGI application which routes requests to 'view' code based on
a view registry.
"""
registry = Attribute(
"""Component architecture registry local to this application."""
)
def request_context(environ):
"""
Create a new request context fr... | IRouter |
python | pypa__setuptools | setuptools/_vendor/typeguard/_utils.py | {
"start": 5163,
"end": 5270
} | class ____:
__slots__ = ()
def __repr__(self) -> str:
return "<unset>"
unset = Unset()
| Unset |
python | django__django | tests/db_functions/text/test_lower.py | {
"start": 194,
"end": 1459
} | class ____(TestCase):
def test_basic(self):
Author.objects.create(name="John Smith", alias="smithj")
Author.objects.create(name="Rhonda")
authors = Author.objects.annotate(lower_name=Lower("name"))
self.assertQuerySetEqual(
authors.order_by("name"), ["john smith", "rhonda... | LowerTests |
python | pdm-project__pdm | src/pdm/models/caches.py | {
"start": 2860,
"end": 6168
} | class ____:
"""Caches hashes of PyPI artifacts so we do not need to re-download them.
Hashes are only cached when the URL appears to contain a hash in it and the
cache key includes the hash value returned from the server). This ought to
avoid issues where the location on the server changes.
"""
... | HashCache |
python | pytorch__pytorch | test/distributed/checkpoint/test_dtensor_checkpoint.py | {
"start": 585,
"end": 2138
} | class ____(torch.nn.Module):
def __init__(
self,
sdt: DTensor,
rdt: DTensor,
submesh_sdt: DTensor,
submesh_rdt: DTensor,
extra_state: int = 1,
extra_state_tensor: torch.Tensor = torch.zeros(1),
) -> None:
super().__init__()
self.sdt = torch... | MyTestModule |
python | spyder-ide__spyder | spyder/utils/stylesheet.py | {
"start": 2225,
"end": 3756
} | class ____:
"""Base class for Spyder stylesheets."""
SET_STYLESHEET_AT_INIT = True
"""
Decide if the stylesheet must be set when the class is initialized.
Notes
-----
There are some stylesheets for which this is not possible (e.g. the ones
that need to access our fonts).
"""
d... | SpyderStyleSheet |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 106018,
"end": 107888
} | class ____(GeneratedAirbyteSource):
class Disabled:
@public
def __init__(
self,
):
self.deletion_mode = "ignore"
class Enabled:
@public
def __init__(self, column: str):
self.deletion_mode = "deleted_field"
self.column = che... | FaunaSource |
python | readthedocs__readthedocs.org | readthedocs/profiles/views.py | {
"start": 6666,
"end": 7091
} | class ____(TokenMixin, CreateView):
"""Simple view to generate a Token object for the logged in User."""
http_method_names = ["post"]
def post(self, request, *args, **kwargs):
_, created = Token.objects.get_or_create(user=self.request.user)
if created:
messages.info(request, "A... | TokenCreateView |
python | numba__numba | numba/core/untyped_passes.py | {
"start": 22829,
"end": 29853
} | class ____(FunctionPass):
""" This pass spots a `literal_unroll([<constant values>])` and rewrites it
as a `literal_unroll(tuple(<constant values>))`.
"""
_name = "transform_literal_unroll_const_list_to_tuple"
_accepted_types = (types.BaseTuple, types.LiteralList)
def __init__(self):
F... | TransformLiteralUnrollConstListToTuple |
python | django__django | django/db/models/sql/compiler.py | {
"start": 86147,
"end": 94621
} | class ____(SQLCompiler):
returning_fields = None
returning_params = ()
def as_sql(self):
"""
Create the SQL for this query. Return the SQL string and list of
parameters.
"""
self.pre_sql_setup()
if not self.query.values:
return "", ()
qn =... | SQLUpdateCompiler |
python | apache__airflow | providers/fab/src/airflow/providers/fab/www/session.py | {
"start": 1438,
"end": 1904
} | class ____:
"""Exempt certain blueprints/paths from autogenerated sessions."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.serializer = _LazySafeSerializer()
def save_session(self, *args, **kwargs):
"""Prevent creating session from REST API and healt... | SessionExemptMixin |
python | ansible__ansible | lib/ansible/module_utils/facts/system/distribution.py | {
"start": 23197,
"end": 33010
} | class ____(object):
"""
This subclass of Facts fills the distribution, distribution_version and distribution_release variables
To do so it checks the existence and content of typical files in /etc containing distribution information
This is unit tested. Please extend the tests to cover all distributio... | Distribution |
python | walkccc__LeetCode | solutions/3117. Minimum Sum of Values by Dividing Array/3117.py | {
"start": 0,
"end": 867
} | class ____:
def minimumValueSum(self, nums: list[int], andValues: list[int]) -> int:
n = len(nums)
m = len(andValues)
@functools.lru_cache(None)
def dp(i: int, j: int, mask: int) -> int:
"""
Returns the minimum value sum of nums[i..n) and andValues[j..m), where
`mask` is the running... | Solution |
python | tensorflow__tensorflow | tensorflow/python/distribute/experimental/mirrored_strategy_test.py | {
"start": 1779,
"end": 19762
} | class ____(test_util.DTensorBaseTest):
def setUp(self):
super().setUp()
global_ids = test_util.create_device_ids_array((2,))
local_ids = np.ravel(global_ids).tolist()
mesh_dict = {
device: layout.Mesh(['batch'], global_ids, local_ids,
test_util.create_device_list((... | StrategyBaseTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/asyncmy.py | {
"start": 5099,
"end": 6627
} | class ____(MySQLDialect_pymysql):
driver = "asyncmy"
supports_statement_cache = True
supports_server_side_cursors = True
_sscursor = AsyncAdapt_asyncmy_ss_cursor
is_async = True
has_terminate = True
@classmethod
def import_dbapi(cls) -> DBAPIModule:
return AsyncAdapt_asyncmy_d... | MySQLDialect_asyncmy |
python | streamlit__streamlit | lib/tests/streamlit/elements/media_test.py | {
"start": 1254,
"end": 9192
} | class ____(DeltaGeneratorTestCase):
@parameterized.expand(
[
("foo.wav", "audio/wav", MockMediaKind.AUDIO, False),
(Path("foo.wav"), "audio/wav", MockMediaKind.AUDIO, False),
("path/to/foo.wav", "audio/wav", MockMediaKind.AUDIO, False),
(Path("path/to/foo.wav"... | MediaTest |
python | huggingface__transformers | src/transformers/models/diffllama/modeling_diffllama.py | {
"start": 28936,
"end": 32087
} | class ____(DiffLlamaPreTrainedModel):
def __init__(self, config: DiffLlamaConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
se... | DiffLlamaModel |
python | openai__gym | gym/wrappers/transform_observation.py | {
"start": 92,
"end": 1672
} | class ____(gym.ObservationWrapper):
"""Transform the observation via an arbitrary function :attr:`f`.
The function :attr:`f` should be defined on the observation space of the base environment, ``env``, and should, ideally, return values in the same space.
If the transformation you wish to apply to observa... | TransformObservation |
python | numpy__numpy | benchmarks/benchmarks/bench_itemselection.py | {
"start": 487,
"end": 1201
} | class ____(Benchmark):
params = [
[True, False],
TYPES1 + ["O", "i,O"]]
param_names = ["values_is_scalar", "dtype"]
def setup(self, values_is_scalar, dtype):
if values_is_scalar:
self.vals = np.array(1., dtype=dtype)
else:
self.vals = np.ones(1000, dt... | PutMask |
python | allegroai__clearml | clearml/backend_api/services/v2_23/datasets.py | {
"start": 12088,
"end": 15540
} | class ____(NonStrictDataModel):
"""
:param uri: Data URI
:type uri: str
:param content_type: Content type (e.g. 'image/jpeg', 'image/png')
:type content_type: str
:param width: Width in pixels
:type width: int
:param height: Height in pixels
:type height: int
:param timestamp: Ti... | Preview |
python | astropy__astropy | astropy/coordinates/builtin_frames/gcrs.py | {
"start": 4314,
"end": 5289
} | class ____(BaseRADecFrame):
"""
A coordinate frame defined in a similar manner as GCRS, but precessed to a
requested (mean) equinox. Note that this does *not* end up the same as
regular GCRS even for J2000 equinox, because the GCRS orientation is fixed
to that of ICRS, which is not quite the same a... | PrecessedGeocentric |
python | matplotlib__matplotlib | lib/mpl_toolkits/axisartist/axis_artist.py | {
"start": 3261,
"end": 3725
} | class ____:
def get_ref_artist(self):
"""
Return the underlying artist that actually defines some properties
(e.g., color) of this artist.
"""
raise RuntimeError("get_ref_artist must overridden")
def get_attribute_from_ref_artist(self, attr_name):
getter = method... | AttributeCopier |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol53.py | {
"start": 1666,
"end": 2402
} | class ____(Proto_CoGeneric):
# This should generate a reportIncompatibleMethodOverride error
# but does not currently.
def m(self) -> Impl_CoSelf: ...
x01: Proto_CoRecurs = Impl_CoRecurs()
x02: Proto_CoRecurs = Impl_CoSelf()
x03: Proto_CoRecurs = Impl_CoGeneric()
x04: Proto_CoRecurs = Impl_CoOther()
x11:... | Impl_CoOtherExplicit3 |
python | kamyu104__LeetCode-Solutions | Python/maximum-deletions-on-a-string.py | {
"start": 706,
"end": 1726
} | class ____(object):
def deleteString(self, s):
"""
:type s: str
:rtype: int
"""
def getPrefix(pattern, start):
prefix = [-1]*(len(pattern)-start)
j = -1
for i in xrange(1, len(pattern)-start):
while j != -1 and pattern[start... | Solution2 |
python | getsentry__sentry-python | tests/test_ai_monitoring.py | {
"start": 6336,
"end": 8983
} | class ____:
def test_no_truncation_needed(self, sample_messages):
"""Test that messages under the limit are not truncated"""
result, truncation_index = truncate_messages_by_size(
sample_messages, max_bytes=MAX_GEN_AI_MESSAGE_BYTES
)
assert len(result) == len(sample_messag... | TestTruncateMessagesBySize |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_set.py | {
"start": 58878,
"end": 59099
} | class ____(_TestCopying, __TestCase):
def setUp(self):
self.set = set([((1, 2), (3, 4))])
super().setUp()
#==============================================================================
| TestCopyingNested |
python | getsentry__sentry | tests/sentry/web/frontend/test_organization_avatar.py | {
"start": 265,
"end": 1684
} | class ____(TestCase):
def test_headers(self) -> None:
org = self.create_organization()
photo = File.objects.create(name="test.png", type="avatar.file")
photo.putfile(BytesIO(b"test"))
avatar = OrganizationAvatar.objects.create(organization=org, file_id=photo.id)
url = reverse... | OrganizationAvatarTest |
python | walkccc__LeetCode | solutions/2678. Number of Senior Citizens/2678.py | {
"start": 0,
"end": 131
} | class ____:
def countSeniors(self, details: list[str]) -> int:
return sum(int(detail[11:13]) > 60 for detail in details)
| Solution |
python | django__django | tests/model_forms/tests.py | {
"start": 4594,
"end": 28749
} | class ____(TestCase):
def test_base_form(self):
self.assertEqual(list(BaseCategoryForm.base_fields), ["name", "slug", "url"])
def test_no_model_class(self):
class NoModelModelForm(forms.ModelForm):
pass
with self.assertRaisesMessage(
ValueError, "ModelForm has n... | ModelFormBaseTest |
python | pytorch__pytorch | test/dynamo/test_fx_graph_runnable.py | {
"start": 2564,
"end": 3133
} | class ____(torch.nn.Module):
def __init__(self, input_size=10, hidden_size=20, output_size=5):
super().__init__()
self.linear1 = torch.nn.Linear(input_size, hidden_size)
self.linear2 = torch.nn.Linear(hidden_size, output_size)
self.relu = torch.nn.ReLU()
self.dropout = torch.... | ToyModel |
python | viewflow__viewflow | viewflow/jsonstore.py | {
"start": 6763,
"end": 6831
} | class ____(JSONFieldMixin, fields.IntegerField):
pass
| IntegerField |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF012.py | {
"start": 2079,
"end": 2187
} | class ____(V1BaseModel):
mutable_default: list[int] = []
from pydantic.v1.generics import GenericModel
| I |
python | apache__airflow | providers/microsoft/psrp/tests/unit/microsoft/psrp/hooks/test_psrp.py | {
"start": 1360,
"end": 3928
} | class ____(MagicMock):
had_errors = False
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.state = PSInvocationState.NOT_STARTED
def poll_invoke(self, timeout=None):
self.state = PSInvocationState.COMPLETED
self.output.append("output")
de... | MockPowerShell |
python | google__jax | tests/jaxpr_effects_test.py | {
"start": 3690,
"end": 5023
} | class ____(jtu.JaxTestCase):
def test_trivial_jaxpr_has_no_effects(self):
def f(x):
return x + 1.
jaxpr = jax.make_jaxpr(f)(2.)
self.assertEqual(core.no_effects, jaxpr.effects)
def test_effectful_primitive_in_jaxpr_creates_effects(self):
def f(x):
effect_p.bind(effect=foo_effect)
... | JaxprEffectsTest |
python | h5py__h5py | h5py/h5py_warnings.py | {
"start": 471,
"end": 523
} | class ____(H5pyWarning):
pass
| H5pyDeprecationWarning |
python | pytorch__pytorch | torch/_guards.py | {
"start": 2269,
"end": 4228
} | class ____:
frame_id: int | None
# This id is per-frame, and counts how many times we've compiled this
# frame. This could have been a global id but having this be per-frame
# gives you a better intuitive sense for how many recompiles have occurred
# so far.
frame_compile_id: int | None
# ... | CompileId |
python | ansible__ansible | test/units/cli/test_cli.py | {
"start": 1363,
"end": 3880
} | class ____(unittest.TestCase):
def setUp(self):
self.tty_patcher = patch('ansible.cli.sys.stdin.isatty', return_value=True)
self.mock_isatty = self.tty_patcher.start()
def tearDown(self):
self.tty_patcher.stop()
def test(self):
res = cli.CLI.build_vault_ids(['foo@bar'])
... | TestCliBuildVaultIds |
python | tensorflow__tensorflow | tensorflow/python/ops/parallel_for/control_flow_ops_test.py | {
"start": 54325,
"end": 54726
} | class ____(PForTestCase):
def test_optional_from_value(self):
def loop_fn(i):
o = gen_optional_ops.optional_from_value(
[i, i + 1, constant_op.constant(3)]
)
gen_optional_ops.optional_none()
return gen_optional_ops.optional_get_value(
o, [dtypes.int32, dtypes.int32, d... | OptionalTest |
python | apache__airflow | providers/google/tests/unit/google/cloud/triggers/test_gcs.py | {
"start": 6143,
"end": 9460
} | class ____:
TRIGGER = GCSPrefixBlobTrigger(
bucket=TEST_BUCKET,
prefix=TEST_PREFIX,
poke_interval=TEST_POLLING_INTERVAL,
google_cloud_conn_id=TEST_GCP_CONN_ID,
hook_params=TEST_HOOK_PARAMS,
)
def test_gcs_prefix_blob_trigger_serialization(self):
"""
A... | TestGCSPrefixBlobTrigger |
python | pydantic__pydantic | pydantic/networks.py | {
"start": 22439,
"end": 22680
} | class ____(AnyUrl):
"""A type that will accept any ws or wss URL.
* TLD not required
* Host not required
* Max length 2083
"""
_constraints = UrlConstraints(max_length=2083, allowed_schemes=['ws', 'wss'])
| WebsocketUrl |
python | tensorflow__tensorflow | tensorflow/python/autograph/converters/logical_expressions.py | {
"start": 1562,
"end": 4381
} | class ____(converter.Base):
"""Converts logical expressions to corresponding TF calls."""
def _overload_of(self, operator):
op_type = type(operator)
if op_type in LOGICAL_OPERATORS:
return LOGICAL_OPERATORS[op_type]
if self.ctx.user.options.uses(converter.Feature.EQUALITY_OPERATORS):
if op_... | LogicalExpressionTransformer |
python | getsentry__sentry | src/sentry/integrations/discord/message_builder/base/embed/image.py | {
"start": 231,
"end": 955
} | class ____:
def __init__(
self,
url: str,
proxy_url: str | None = None,
height: int | None = None,
width: int | None = None,
) -> None:
self.url = url
self.proxy_url = proxy_url
self.height = height
self.width = width
def build(self) -... | DiscordMessageEmbedImage |
python | kamyu104__LeetCode-Solutions | Python/final-array-state-after-k-multiplication-operations-i.py | {
"start": 3979,
"end": 4548
} | class ____(object):
def getFinalState(self, nums, k, multiplier):
"""
:type nums: List[int]
:type k: int
:type multiplier: int
:rtype: List[int]
"""
if multiplier == 1:
return nums
min_heap = [(x, i) for i, x in enumerate(nums)]
hea... | Solution4 |
python | jazzband__django-pipeline | pipeline/compressors/__init__.py | {
"start": 14306,
"end": 15171
} | class ____(CompressorBase):
def execute_command(self, command, content):
argument_list = []
for flattening_arg in command:
if isinstance(flattening_arg, (str,)):
argument_list.append(flattening_arg)
else:
argument_list.extend(flattening_arg)
... | SubProcessCompressor |
python | getsentry__sentry | src/sentry/lang/native/utils.py | {
"start": 5189,
"end": 5925
} | class ____:
"""
Creates a new exponential backoff.
"""
def __init__(self, initial, max):
"""
:param initial: The initial backoff time in seconds.
:param max: The maximum backoff time in seconds.
"""
self.initial = initial
self.max = max
self._curr... | Backoff |
python | allegroai__clearml | clearml/backend_api/services/v2_13/models.py | {
"start": 21098,
"end": 22323
} | class ____(Response):
"""
Response of models.add_or_update_metadata endpoint.
:param updated: Number of models updated (0 or 1)
:type updated: int
"""
_service = "models"
_action = "add_or_update_metadata"
_version = "2.13"
_schema = {
"definitions": {},
"properties... | AddOrUpdateMetadataResponse |
python | OmkarPathak__pygorithm | pygorithm/data_structures/linked_list.py | {
"start": 154,
"end": 679
} | class ____(object):
"""
Node class for creating a node
for linked list.
Each node has its data and a pointer that
points to next node in the Linked l_list
"""
def __init__(self, data, next_node=None):
"""
constructor
:param data:
:param next_node:
"""
... | Node |
python | huggingface__transformers | src/transformers/models/sew/modeling_sew.py | {
"start": 7685,
"end": 10065
} | class ____(nn.Module):
"""Construct the features from raw audio waveform"""
def __init__(self, config):
super().__init__()
if config.feat_extract_norm == "group":
conv_layers = [SEWGroupNormConvLayer(config, layer_id=0)] + [
SEWNoLayerNormConvLayer(config, layer_id=... | SEWFeatureEncoder |
python | walkccc__LeetCode | solutions/354. Russian Doll Envelopes/354.py | {
"start": 0,
"end": 511
} | class ____:
def maxEnvelopes(self, envelopes: list[list[int]]) -> int:
envelopes.sort(key=lambda x: (x[0], -x[1]))
return self._lengthOfLIS(envelopes)
def _lengthOfLIS(self, envelopes: list[list[int]]) -> int:
# tails[i] := the minimum tails of all the increasing subsequences having
# length i + 1
... | Solution |
python | kamyu104__LeetCode-Solutions | Python/multiply-strings.py | {
"start": 37,
"end": 653
} | class ____(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
result = [0]*(len(num1)+len(num2))
for i in reversed(xrange(len(num1))):
for j in reversed(xrange(len(num2))):
result[i+j+1] += ... | Solution |
python | cython__cython | Cython/Shadow.py | {
"start": 19209,
"end": 19821
} | class ____:
def __init__(self):
import threading
self._l = threading.Lock()
def acquire(self):
return self._l.acquire()
def release(self):
return self._l.release()
def locked(self):
return self._l.locked()
def can_check_locked(self):
"""Check if lo... | pymutex |
python | crytic__slither | slither/detectors/functions/out_of_order_retryable.py | {
"start": 313,
"end": 5424
} | class ____(AbstractDetector):
ARGUMENT = "out-of-order-retryable"
HELP = "Out-of-order retryable transactions"
IMPACT = DetectorClassification.MEDIUM
CONFIDENCE = DetectorClassification.MEDIUM
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#out-of-order-retryable-transactions... | OutOfOrderRetryable |
python | pytorch__pytorch | torch/testing/_internal/opinfo/utils.py | {
"start": 1195,
"end": 8780
} | class ____(_dispatch_dtypes):
# Class to tag the dynamically generated types.
pass
def get_supported_dtypes(op, sample_inputs_fn, device_type):
# Returns the supported dtypes for the given operator and device_type pair.
assert device_type in ["cpu", "cuda"]
if not TEST_CUDA and device_type == "cud... | _dynamic_dispatch_dtypes |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 4046,
"end": 4360
} | class ____(AbstractTemplate):
"""
Given a heterogeneous pair, return the first element.
"""
key = "pair_first"
def generic(self, args, kws):
assert not kws
[pair] = args
if isinstance(pair, types.Pair):
return signature(pair.first_type, pair)
@infer
| PairFirst |
python | MorvanZhou__Reinforcement-learning-with-tensorflow | experiments/Solve_BipedalWalker/DDPG.py | {
"start": 7579,
"end": 10478
} | class ____(object):
"""
This SumTree code is modified version and the original code is from:
https://github.com/jaara/AI-blog/blob/master/SumTree.py
Story the data with it priority in tree and data frameworks.
"""
data_pointer = 0
def __init__(self, capacity):
self.capacity = capac... | SumTree |
python | walkccc__LeetCode | solutions/377. Combination Sum IV/377.py | {
"start": 0,
"end": 343
} | class ____:
def combinationSum4(self, nums: list[int], target: int) -> int:
dp = [1] + [-1] * target
def dfs(target: int) -> int:
if target < 0:
return 0
if dp[target] != -1:
return dp[target]
dp[target] = sum(dfs(target - num) for num in nums)
return dp[target]
... | Solution |
python | pytest-dev__pytest | testing/test_doctest.py | {
"start": 28112,
"end": 35139
} | class ____:
@pytest.mark.parametrize("config_mode", ["ini", "comment"])
def test_allow_unicode(self, pytester, config_mode):
"""Test that doctests which output unicode work in all python versions
tested by pytest when the ALLOW_UNICODE option is used (either in
the configuration file or ... | TestLiterals |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 311044,
"end": 311502
} | class ____(sgqlc.types.Input):
"""Ways in which team connections can be ordered."""
__schema__ = github_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(sgqlc.types.non_null(TeamOrderField), graphql_name="field")
"""The field in which to order nodes by."""
direction = ... | TeamOrder |
python | apache__airflow | providers/snowflake/src/airflow/providers/snowflake/operators/snowpark.py | {
"start": 1170,
"end": 5815
} | class ____(PythonOperator):
"""
Executes a Python function with Snowpark Python code.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:SnowparkOperator`
:param snowflake_conn_id: Reference to
:ref:`Snowflake connectio... | SnowparkOperator |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP037_0.py | {
"start": 1064,
"end": 1764
} | class ____(TypedDict):
E: TypedDict("E")
x: Annotated[()]
x: DefaultNamedArg(name="name", quox="str")
x: DefaultNamedArg(name="name")
x: NamedTuple("X", [("foo",), ("bar",)])
x: NamedTuple("X", ["foo", "bar"])
x: NamedTuple()
x: Literal["foo", "bar"]
x = cast(x, "str")
def foo(x, *args, **kwargs):
..... | D |
python | pytorch__pytorch | torch/_export/serde/schema.py | {
"start": 10423,
"end": 10543
} | class ____:
min_val: Annotated[Optional[int], 10]
max_val: Annotated[Optional[int], 20]
@dataclass
| RangeConstraint |
python | pytorch__pytorch | test/inductor/test_ordered_set.py | {
"start": 54214,
"end": 54448
} | class ____(TestCopying, TestCase):
def setUp(self):
super().setUp()
self.OrderedSet = OrderedSet(["zero", 0, None])
# ------------------------------------------------------------------------------
| TestCopyingTriple |
python | huggingface__transformers | src/transformers/models/got_ocr2/modular_got_ocr2.py | {
"start": 9395,
"end": 9456
} | class ____(SamVisionAttention):
pass
| GotOcr2VisionAttention |
python | sympy__sympy | sympy/physics/biomechanics/activation.py | {
"start": 14269,
"end": 25522
} | class ____(ActivationBase):
r"""First-order activation dynamics based on De Groote et al., 2016 [1]_.
Explanation
===========
Gives the first-order activation dynamics equation for the rate of change
of activation with respect to time as a function of excitation and
activation.
The functi... | FirstOrderActivationDeGroote2016 |
python | oauthlib__oauthlib | oauthlib/oauth2/rfc8628/endpoints/pre_configured.py | {
"start": 221,
"end": 1403
} | class ____(DeviceAuthorizationEndpoint):
"""An all-in-one endpoint featuring Authorization code grant and Bearer tokens."""
def __init__(
self,
request_validator: RequestValidator,
verification_uri: str,
interval: int = 5,
verification_uri_complete: Optional[str] = None,... | DeviceApplicationServer |
python | walkccc__LeetCode | solutions/3001. Minimum Moves to Capture The Queen/3001.py | {
"start": 0,
"end": 913
} | class ____:
def minMovesToCaptureTheQueen(
self, a: int, b: int, c: int, d: int, e: int, f: int,
) -> int:
# The rook is in the same row as the queen.
if a == e:
# The bishop blocks the rook or not.
return 2 if c == a and (b < d < f or b > d > f) else 1
# The rook is in the same column... | Solution |
python | apache__airflow | providers/google/tests/unit/google/common/hooks/test_base_google.py | {
"start": 2653,
"end": 3723
} | class ____:
def test_do_nothing_on_non_error(self):
result = _retryable_test_with_temporary_quota_retry(lambda: 42)
assert result == 42
def test_retry_on_exception(self):
message = "POST https://translation.googleapis.com/language/translate/v2: User Rate Limit Exceeded"
errors =... | TestQuotaRetry |
python | sqlalchemy__sqlalchemy | test/ext/asyncio/test_engine.py | {
"start": 38153,
"end": 51434
} | class ____(EngineFixture):
__backend__ = True
__requires__ = ("server_side_cursors", "async_dialect")
@async_test
async def test_no_ss_cursor_w_execute(self, async_engine):
users = self.tables.users
async with async_engine.connect() as conn:
conn = await conn.execution_optio... | AsyncResultTest |
python | mlflow__mlflow | examples/pydanticai/tracing.py | {
"start": 1100,
"end": 2551
} | class ____(BaseModel):
support_advice: str = Field(description="Advice returned to the customer")
block_card: bool = Field(description="Whether to block their card or not")
risk: int = Field(description="Risk level of query", ge=0, le=10)
support_agent = Agent(
"openai:gpt-4o",
deps_type=SupportDe... | SupportOutput |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 31275,
"end": 32218
} | class ____(PrefectOperatorFilterBaseModel):
"""Filter by `TaskRun.type` and `TaskRun.name`."""
type: Optional[TaskRunFilterStateType] = Field(
default=None, description="Filter criteria for `TaskRun.state_type`"
)
name: Optional[TaskRunFilterStateName] = Field(
default=None, description... | TaskRunFilterState |
python | pydantic__pydantic | pydantic/networks.py | {
"start": 4147,
"end": 11644
} | class ____:
_constraints: ClassVar[UrlConstraints] = UrlConstraints()
_url: _CoreUrl
def __init__(self, url: str | _CoreUrl | _BaseUrl) -> None:
self._url = _build_type_adapter(self.__class__).validate_python(url)._url
@property
def scheme(self) -> str:
"""The scheme part of the UR... | _BaseUrl |
python | coleifer__peewee | tests/shortcuts.py | {
"start": 27742,
"end": 29929
} | class ____(BaseTestCase):
def setUp(self):
super(TestThreadSafeDatabaseMetadata, self).setUp()
ts_database.create_tables([TSReg])
def test_threadsafe_database_metadata(self):
self.assertTrue(isinstance(TSReg._meta, ThreadSafeDatabaseMetadata))
self.assertEqual(TSReg._meta.databa... | TestThreadSafeDatabaseMetadata |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.