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 | TheAlgorithms__Python | conversions/prefix_conversions_string.py | {
"start": 539,
"end": 686
} | class ____(Enum):
yotta = 80
zetta = 70
exa = 60
peta = 50
tera = 40
giga = 30
mega = 20
kilo = 10
@unique
| BinaryUnit |
python | apache__airflow | airflow-core/tests/unit/utils/test_process_utils.py | {
"start": 7953,
"end": 8807
} | class ____:
def test_ok_if_no_file(self):
check_if_pidfile_process_is_running("some/pid/file", process_name="test")
def test_remove_if_no_process(self, tmp_path):
path = tmp_path / "testfile"
# limit pid as max of int32, otherwise this test could fail on some platform
path.write... | TestCheckIfPidfileProcessIsRunning |
python | numpy__numpy | numpy/polynomial/tests/test_polynomial.py | {
"start": 4536,
"end": 10271
} | class ____:
# coefficients of 1 + 2*x + 3*x**2
c1d = np.array([1., 2., 3.])
c2d = np.einsum('i,j->ij', c1d, c1d)
c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)
# some random values in [-1, 1)
x = np.random.random((3, 5)) * 2 - 1
y = poly.polyval(x, [1., 2., 3.])
def test_polyval(self):
... | TestEvaluation |
python | run-llama__llama_index | llama-index-integrations/postprocessor/llama-index-postprocessor-flashrank-rerank/llama_index/postprocessor/flashrank_rerank/base.py | {
"start": 833,
"end": 981
} | class ____(BaseEvent):
"""FlashRerankEndEvent."""
nodes: list[NodeWithScore] = Field(..., description="Nodes to rerank.")
| FlashRerankEndEvent |
python | bokeh__bokeh | src/bokeh/models/tools.py | {
"start": 9042,
"end": 9304
} | class ____(GestureTool):
''' A base class for tools that respond to tap/click events.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@abstract
| Tap |
python | numpy__numpy | numpy/linalg/tests/test_linalg.py | {
"start": 72492,
"end": 77886
} | class ____:
def test_basic_function_with_three_arguments(self):
# multi_dot with three arguments uses a fast hand coded algorithm to
# determine the optimal order. Therefore test it separately.
A = np.random.random((6, 2))
B = np.random.random((2, 6))
C = np.random.random((6... | TestMultiDot |
python | ray-project__ray | rllib/algorithms/sac/torch/sac_torch_learner.py | {
"start": 965,
"end": 17621
} | class ____(DQNTorchLearner, SACLearner):
"""Implements `torch`-specific SAC loss logic on top of `SACLearner`
This ' Learner' class implements the loss in its
`self.compute_loss_for_module()` method. In addition, it updates
the target networks of the RLModule(s).
"""
def build(self) -> None:
... | SACTorchLearner |
python | pennersr__django-allauth | allauth/socialaccount/providers/edmodo/views.py | {
"start": 181,
"end": 909
} | class ____(OAuth2Adapter):
provider_id = "edmodo"
access_token_url = "https://api.edmodo.com/oauth/token" # nosec
authorize_url = "https://api.edmodo.com/oauth/authorize"
profile_url = "https://api.edmodo.com/users/me"
def complete_login(self, request, app, token, **kwargs):
resp = (
... | EdmodoOAuth2Adapter |
python | pandas-dev__pandas | asv_bench/benchmarks/rolling.py | {
"start": 7384,
"end": 8097
} | class ____:
params = (
["DataFrame", "Series"],
[10, 1000],
["int", "float"],
[True, False],
[True, False],
["min", "max", "average"],
)
param_names = [
"constructor",
"window",
"dtype",
"percentile",
"ascending",
... | Rank |
python | python__mypy | mypy/nodes.py | {
"start": 6348,
"end": 6544
} | class ____(Node):
"""A statement node."""
__slots__ = ()
def accept(self, visitor: StatementVisitor[T]) -> T:
raise RuntimeError("Not implemented", type(self))
@trait
| Statement |
python | allegroai__clearml | clearml/backend_api/services/v2_23/frames.py | {
"start": 109597,
"end": 109850
} | class ____(Response):
"""
Response of frames.clear_get_next_state endpoint.
"""
_service = "frames"
_action = "clear_get_next_state"
_version = "2.23"
_schema = {"definitions": {}, "type": "object"}
| ClearGetNextStateResponse |
python | has2k1__plotnine | plotnine/_mpl/layout_manager/_spaces.py | {
"start": 8668,
"end": 14170
} | class ____(_side_spaces):
"""
Space in the figure for artists on the left of the panel area
Ordered from the edge of the figure and going inwards
"""
plot_margin: float = 0
tag_alignment: float = 0
"""
Space added to align the tag in this plot with others in a composition
This val... | left_spaces |
python | PyCQA__pylint | tests/functional/c/class_members_py30.py | {
"start": 572,
"end": 739
} | class ____:
"""access to undefined members should be ignored in mixin classes by
default
"""
def __init__(self):
print(self.nonexistent)
| XYZMixin |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/ui/structure.py | {
"start": 984,
"end": 1177
} | class ____(BaseEdgeResponse):
"""Edge serializer for responses."""
is_setup_teardown: bool | None = None
label: str | None = None
is_source_asset: bool | None = None
| EdgeResponse |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_isbn13.py | {
"start": 579,
"end": 1566
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_isbn13"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls... | ColumnValuesToBeValidIsbn13 |
python | TheAlgorithms__Python | machine_learning/automatic_differentiation.py | {
"start": 411,
"end": 628
} | class ____(Enum):
"""
Class represents list of supported operations on Variable for gradient calculation.
"""
ADD = 0
SUB = 1
MUL = 2
DIV = 3
MATMUL = 4
POWER = 5
NOOP = 6
| OpType |
python | getsentry__sentry | src/sentry/web/frontend/auth_logout.py | {
"start": 378,
"end": 1019
} | class ____(BaseView):
auth_required = False
def _redirect(self, request: HttpRequest) -> HttpResponseBase:
next_url = request.GET.get(REDIRECT_FIELD_NAME, "")
if not url_has_allowed_host_and_scheme(next_url, allowed_hosts=(request.get_host(),)):
next_url = auth.get_login_url()
... | AuthLogoutView |
python | pdm-project__pdm | src/pdm/termui.py | {
"start": 4226,
"end": 4920
} | class ____:
"""A wrapper for IO that truncates output after certain length."""
def __init__(self, wrapped: IO[str], max_length: int = 100 * 1024 * 1024) -> None:
self.max_length = max_length
self._fp = wrapped
self._truncated = False
def write(self, s: str) -> int:
if self.... | TruncatedIO |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/partition_sets.py | {
"start": 4990,
"end": 5408
} | class ____(graphene.ObjectType):
class Meta:
name = "AssetPartitionsStatusCounts"
assetKey = graphene.NonNull(GrapheneAssetKey)
numPartitionsTargeted = graphene.NonNull(graphene.Int)
numPartitionsInProgress = graphene.NonNull(graphene.Int)
numPartitionsMaterialized = graphene.NonNull(graphe... | GrapheneAssetPartitionsStatusCounts |
python | pytorch__pytorch | test/inductor/test_torchbind.py | {
"start": 753,
"end": 17600
} | class ____(TestCase):
def setUp(self):
super().setUp()
init_torchbind_implementations()
def get_dummy_exported_model(self):
"""
Returns the ExportedProgram, example inputs, and result from calling the
eager model with those inputs
"""
class M(torch.nn.Mo... | TestTorchbind |
python | getsentry__sentry | src/sentry/search/eap/columns.py | {
"start": 4621,
"end": 5000
} | class ____:
# The public alias for the default arg, the SearchResolver will resolve this value
default_arg: str | None = None
# Validator to check if the value is allowed for this argument
validator: Callable[[str], bool] | None = None
# Whether this argument is completely ignored, used for `count()... | BaseArgumentDefinition |
python | cherrypy__cherrypy | cherrypy/_cprequest.py | {
"start": 352,
"end": 2493
} | class ____(object):
"""A callback and its metadata: failsafe, priority, and kwargs."""
callback = None
"""
The bare callable that this Hook object is wrapping, which will
be called when the Hook is called."""
failsafe = False
"""
If True, the callback is guaranteed to run even if other... | Hook |
python | walkccc__LeetCode | solutions/451. Sort Characters By Frequency/451.py | {
"start": 0,
"end": 331
} | class ____:
def frequencySort(self, s: str) -> str:
ans = []
buckets = [[] for _ in range(len(s) + 1)]
for c, freq in collections.Counter(s).items():
buckets[freq].append(c)
for freq in reversed(range(len(buckets))):
for c in buckets[freq]:
ans.append(c * freq)
return ''.joi... | Solution |
python | django__django | tests/filtered_relation/models.py | {
"start": 668,
"end": 1357
} | class ____(models.Model):
AVAILABLE = "available"
RESERVED = "reserved"
RENTED = "rented"
STATES = (
(AVAILABLE, "Available"),
(RESERVED, "reserved"),
(RENTED, "Rented"),
)
title = models.CharField(max_length=255)
author = models.ForeignKey(
Author,
mo... | Book |
python | getsentry__sentry | src/sentry/api/endpoints/organization_events_spans_performance.py | {
"start": 3281,
"end": 4516
} | class ____(OrganizationEventsV2EndpointBase):
def get_snuba_params(
self,
request: Request,
organization: Organization,
quantize_date_params: bool = True,
) -> SnubaParams:
snuba_params = super().get_snuba_params(
request,
organization,
... | OrganizationEventsSpansEndpointBase |
python | getsentry__sentry | src/sentry/core/endpoints/organization_details.py | {
"start": 24384,
"end": 28115
} | class ____(OrganizationSerializer):
defaultRole = serializers.ChoiceField(choices=roles.get_choices())
cancelDeletion = serializers.BooleanField(required=False)
idempotencyKey = serializers.CharField(max_length=IDEMPOTENCY_KEY_LENGTH, required=False)
def save(self, *args, **kwargs):
org = self.... | OwnerOrganizationSerializer |
python | huggingface__transformers | src/transformers/models/ernie4_5_moe/modeling_ernie4_5_moe.py | {
"start": 3668,
"end": 10323
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: Ernie4_5_MoeConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
... | Ernie4_5_MoeRotaryEmbedding |
python | apache__airflow | task-sdk/src/airflow/sdk/api/client.py | {
"start": 15810,
"end": 21938
} | class ____:
__slots__ = ("client",)
def __init__(self, client: Client):
self.client = client
def head(self, dag_id: str, run_id: str, task_id: str, key: str) -> XComCountResponse:
"""Get the number of mapped XCom values."""
resp = self.client.head(f"xcoms/{dag_id}/{run_id}/{task_id... | XComOperations |
python | kamyu104__LeetCode-Solutions | Python/sliding-puzzle.py | {
"start": 2282,
"end": 4029
} | class ____(object):
def slidingPuzzle(self, board):
"""
:type board: List[List[int]]
:rtype: int
"""
def heuristic_estimate(board, R, C, expected):
result = 0
for i in xrange(R):
for j in xrange(C):
val = board[C*i +... | Solution2 |
python | lxml__lxml | src/lxml/tests/test_etree.py | {
"start": 1476,
"end": 175309
} | class ____(HelperTestCase):
"""Tests only for etree, not ElementTree"""
etree = etree
def test_version(self):
self.assertTrue(isinstance(etree.__version__, str))
self.assertTrue(isinstance(etree.LXML_VERSION, tuple))
self.assertEqual(len(etree.LXML_VERSION), 4)
self.assertTr... | ETreeOnlyTestCase |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py | {
"start": 163108,
"end": 164569
} | class ____(nn.Module):
"""
A modified Snake function which uses separate parameters for the magnitude of the periodic components
Shape:
- Input: (B, C, T)
- Output: (B, C, T), same shape as the input
Parameters:
- alpha - trainable parameter that controls frequency
- beta... | SnakeBeta |
python | kamyu104__LeetCode-Solutions | Python/minimum-subarrays-in-a-valid-split.py | {
"start": 58,
"end": 626
} | class ____(object):
def validSubarraySplit(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def gcd(a, b):
while b:
a, b = b, a%b
return a
dp = [float("inf")]*(len(nums)+1) # dp[i]: min number of subarrays in nums[:i]
... | Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_table22.py | {
"start": 315,
"end": 981
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("table22.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with tables."""
workbook = Workbook(se... | TestCompareXLSXFiles |
python | pytorch__pytorch | torch/_export/serde/schema.py | {
"start": 13057,
"end": 13604
} | class ____:
# the path of the payload in the archive file, e.g. "weight_0"
path_name: Annotated[str, 10]
is_param: Annotated[bool, 20]
# whether the payload is serialized using pickle.
# Only custom objects and tensor subclasses that are not fake tensors
# are serialized using pickle.
use_pi... | PayloadMeta |
python | Textualize__textual | src/textual/color.py | {
"start": 2365,
"end": 3454
} | class ____(NamedTuple):
"""A color in CIE-L*ab format."""
L: float
"""Lightness in range 0 to 100."""
a: float
"""A axis in range -127 to 128."""
b: float
"""B axis in range -127 to 128."""
RE_COLOR = re.compile(
rf"""^
\#([0-9a-fA-F]{{3}})$|
\#([0-9a-fA-F]{{4}})$|
\#([0-9a-fA-F]{{6}}... | Lab |
python | pytorch__pytorch | tools/gdb/pytorch-gdb.py | {
"start": 1866,
"end": 2597
} | class ____(gdb.Command): # type: ignore[misc, no-any-unimported]
"""
Print human readable representation of c10::IntArrayRef
"""
def __init__(self) -> None:
gdb.Command.__init__(
self, "torch-int-array-ref-repr", gdb.COMMAND_USER, gdb.COMPLETE_EXPRESSION
)
def invoke(s... | IntArrayRefRepr |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_misc.py | {
"start": 37934,
"end": 43606
} | class ____(FSDPTestMultiThread):
@property
def world_size(self) -> int:
return 1
@skip_if_lt_x_gpu(1)
def test_world_size_1_sharding_strategy_warning(self):
"""
Tests that FSDP issues a warning when it switches to using ``NO_SHARD``
when the world size is 1.
"""
... | TestFSDPMiscWorldSize1 |
python | Lightning-AI__lightning | src/lightning/pytorch/utilities/exceptions.py | {
"start": 684,
"end": 1179
} | class ____(SystemExit):
"""Exception used when a :class:`signal.SIGTERM` is sent to a process.
This exception is raised by the loops at specific points. It can be used to write custom logic in the
:meth:`lightning.pytorch.callbacks.callback.Callback.on_exception` method.
For example, you could use the... | SIGTERMException |
python | huggingface__transformers | tests/models/groupvit/test_modeling_groupvit.py | {
"start": 15733,
"end": 17287
} | class ____(ModelTesterMixin, unittest.TestCase):
all_model_classes = (GroupViTTextModel,) if is_torch_available() else ()
def setUp(self):
self.model_tester = GroupViTTextModelTester(self)
self.config_tester = ConfigTester(self, config_class=GroupViTTextConfig, hidden_size=37)
def test_con... | GroupViTTextModelTest |
python | streamlit__streamlit | lib/streamlit/elements/empty.py | {
"start": 954,
"end": 4613
} | class ____:
@gather_metrics("empty")
def empty(self) -> DeltaGenerator:
"""Insert a single-element container.
Inserts a container into your app that can be used to hold a single element.
This allows you to, for example, remove elements at any point, or replace
several elements a... | EmptyMixin |
python | scikit-learn__scikit-learn | sklearn/covariance/_graph_lasso.py | {
"start": 14239,
"end": 25102
} | class ____(BaseGraphicalLasso):
"""Sparse inverse covariance estimation with an l1-penalized estimator.
For a usage example see
:ref:`sphx_glr_auto_examples_applications_plot_stock_market.py`.
Read more in the :ref:`User Guide <sparse_inverse_covariance>`.
.. versionchanged:: v0.20
GraphL... | GraphicalLasso |
python | pypa__pip | src/pip/_vendor/pygments/lexers/python.py | {
"start": 31955,
"end": 34196
} | class ____(RegexLexer):
"""
For Python 3.x tracebacks, with support for chained exceptions.
.. versionchanged:: 2.5
This is now the default ``PythonTracebackLexer``. It is still available
as the alias ``Python3TracebackLexer``.
"""
name = 'Python Traceback'
aliases = ['pytb', 'p... | PythonTracebackLexer |
python | Textualize__textual | src/textual/widgets/_markdown.py | {
"start": 11750,
"end": 12013
} | class ____(MarkdownHeader):
"""An H2 Markdown header."""
LEVEL = 2
DEFAULT_CSS = """
MarkdownH2 {
color: $markdown-h2-color;
background: $markdown-h2-background;
text-style: $markdown-h2-text-style;
}
"""
| MarkdownH2 |
python | numba__numba | numba/cuda/stubs.py | {
"start": 7751,
"end": 7850
} | class ____(Stub):
"""
fma(a, b, c)
Perform the fused multiply-add operation.
"""
| fma |
python | plotly__plotly.py | plotly/graph_objs/layout/slider/currentvalue/_font.py | {
"start": 235,
"end": 9950
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.slider.currentvalue"
_path_str = "layout.slider.currentvalue.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"w... | Font |
python | walkccc__LeetCode | solutions/405. Convert a Number to Hexadecimal/405.py | {
"start": 0,
"end": 460
} | class ____:
def toHex(self, num: int) -> str:
if num == 0:
return '0'
hex = '0123456789abcdef'
ans = []
# Handling negative numbers by using 32-bit unsigned representation Python's
# bitwise operation works on signed numbers, so we convert to 32-bit
# unsigned for negative numbers.
... | Solution |
python | pytorch__pytorch | test/distributed/fsdp/test_shard_utils.py | {
"start": 1519,
"end": 2490
} | class ____(DTensorTestBase):
@property
def world_size(self):
return 2
def _create_tensor(self, *size):
# Keep everything deterministic.
torch.manual_seed(0)
return torch.rand(*size).to(device=device_type)
@with_comms
@skip_if_lt_x_gpu(2)
def test_create_chunk_dt... | TestShardUtilsDistributedDTensor |
python | astropy__astropy | astropy/modeling/tests/test_models.py | {
"start": 5035,
"end": 13818
} | class ____:
"""
Test class for all two dimensional parametric models.
Test values have to be defined in example_models.py. It currently test the
model with different input types, evaluates the model at different
positions and assures that it gives the correct values. And tests if the
model work... | Fittable2DModelTester |
python | explosion__spaCy | spacy/lang/vi/__init__.py | {
"start": 5416,
"end": 5521
} | class ____(Language):
lang = "vi"
Defaults = VietnameseDefaults
__all__ = ["Vietnamese"]
| Vietnamese |
python | prabhupant__python-ds | data_structures/graphs/adjacency_list.py | {
"start": 100,
"end": 914
} | class ____:
def __init__(self, vertices):
self.V = vertices
self.graph = [None] * self.V
# adding in undirected graph
def add_edge(self, src, dest):
# adding node to the source node
node = AdjNode(dest)
node.next = self.graph[src]
self.graph[src] = node
... | Graph |
python | keon__algorithms | tests/test_matrix.py | {
"start": 1900,
"end": 3362
} | class ____(unittest.TestCase):
"""[summary]
Test for the file crout_matrix_decomposition.py
Arguments:
unittest {[type]} -- [description]
"""
def test_crout_matrix_decomposition(self):
self.assertEqual(([[9.0, 0.0], [7.0, 0.0]],
[[1.0, 1.0], [0.0, 1.0]]),
... | TestCroutMatrixDecomposition |
python | django__django | tests/delete/models.py | {
"start": 5766,
"end": 5874
} | class ____(models.Model):
base = models.ForeignKey(Base, models.DO_NOTHING, related_name="rels")
| RelToBase |
python | pypa__pip | src/pip/_internal/network/auth.py | {
"start": 1031,
"end": 1338
} | class ____(ABC):
"""Keyring base provider interface"""
has_keyring: bool
@abstractmethod
def get_auth_info(self, url: str, username: str | None) -> AuthInfo | None: ...
@abstractmethod
def save_auth_info(self, url: str, username: str, password: str) -> None: ...
| KeyRingBaseProvider |
python | wntrblm__nox | nox/_option_set.py | {
"start": 3411,
"end": 8564
} | class ____:
"""A single option that can be specified via command-line or configuration
file.
Args:
name (str): The name used to refer to the option in the final namespace
object.
flags (Sequence[str]): The list of flags used by argparse. Effectively
the ``*args`` for... | Option |
python | tornadoweb__tornado | tornado/test/websocket_test.py | {
"start": 24686,
"end": 24816
} | class ____(UncompressedTestMixin):
pass
# If only one side tries to compress, the extension is not negotiated.
| NoCompressionTest |
python | yaml__pyyaml | lib/yaml/nodes.py | {
"start": 1045,
"end": 1328
} | class ____(Node):
def __init__(self, tag, value,
start_mark=None, end_mark=None, flow_style=None):
self.tag = tag
self.value = value
self.start_mark = start_mark
self.end_mark = end_mark
self.flow_style = flow_style
| CollectionNode |
python | coleifer__peewee | playhouse/pool.py | {
"start": 1924,
"end": 2111
} | class ____(ValueError): pass
PoolConnection = namedtuple('PoolConnection', ('timestamp', 'connection',
'checked_out'))
| MaxConnectionsExceeded |
python | scipy__scipy | scipy/sparse/linalg/_interface.py | {
"start": 19848,
"end": 21317
} | class ____(LinearOperator):
"""Linear operator defined in terms of user-specified operations."""
def __init__(self, shape, matvec, rmatvec=None, matmat=None,
dtype=None, rmatmat=None):
super().__init__(dtype, shape)
self.args = ()
self.__matvec_impl = matvec
s... | _CustomLinearOperator |
python | astropy__astropy | astropy/cosmology/_src/tests/flrw/test_flrw.py | {
"start": 511,
"end": 589
} | class ____(FLRW):
def w(self, z):
return super().w(z)
@final
| SubFLRW |
python | django__django | tests/serializers/models/data.py | {
"start": 5015,
"end": 5097
} | class ____(models.Model):
data = models.EmailField(primary_key=True)
| EmailPKData |
python | walkccc__LeetCode | solutions/1531. String Compression II/1531.py | {
"start": 0,
"end": 1116
} | class ____:
def getLengthOfOptimalCompression(self, s: str, k: int) -> int:
def getLength(maxFreq: int) -> int:
"""Returns the length to compress `maxFreq`."""
if maxFreq == 1:
return 1 # c
if maxFreq < 10:
return 2 # [1-9]c
if maxFreq < 100:
return 3 # [1-9][0-9... | Solution |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/ndb/entities/snippets.py | {
"start": 615,
"end": 3156
} | class ____(ndb.Model):
username = ndb.StringProperty()
userid = ndb.IntegerProperty()
email = ndb.StringProperty()
def create_entity_using_keyword_arguments():
sandy = Account(username="Sandy", userid=123, email="sandy@example.com")
return sandy
def create_entity_using_attributes():
sandy = ... | Account |
python | falconry__falcon | falcon/errors.py | {
"start": 28813,
"end": 32061
} | class ____(HTTPError):
"""410 Gone.
The target resource is no longer available at the origin server and
this condition is likely to be permanent.
If the origin server does not know, or has no facility to determine,
whether or not the condition is permanent, the status code 404 Not
Found ought ... | HTTPGone |
python | getsentry__sentry | src/sentry/notifications/services/model.py | {
"start": 337,
"end": 750
} | class ____(RpcModel):
id: int = -1
team_id: int | None = None
user_id: int | None = None
organization_id: int = -1
integration_id: int = -1
provider: int = int(ExternalProviders.UNUSED_GH.value)
# The display name i.e. username, team name, channel name.
external_name: str = ""
# The... | RpcExternalActor |
python | spyder-ide__spyder | spyder/plugins/remoteclient/api/modules/base.py | {
"start": 6235,
"end": 9715
} | class ____(SpyderBaseJupyterAPI):
base_url = "api"
def __init__(self, manager: SpyderRemoteAPIManagerBase, verify_ssl=True):
"""
For JupyterAPI, the manager.server_url is expected to be the notebook
URL.
"""
super().__init__(manager)
self.verify_ssl = verify_ssl
... | JupyterAPI |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/garply/package.py | {
"start": 473,
"end": 5146
} | class ____
{
private:
static const int version_major;
static const int version_minor;
public:
Garply();
int get_version() const;
int garplinate() const;
};
#endif // GARPLY_H_
"""
garply_cc = """#include "garply.h"
#include "garply_version.h"
#include <iostream>
const int Garply::version_... | Garply |
python | realpython__materials | arcade-platformer/arcade_platformer/14_enemies.py | {
"start": 839,
"end": 2148
} | class ____(arcade.AnimatedWalkingSprite):
"""An enemy sprite with basic walking movement"""
def __init__(self, pos_x: int, pos_y: int) -> None:
super().__init__(center_x=pos_x, center_y=pos_y)
# Where are the player images stored?
texture_path = ASSETS_PATH / "images" / "enemies"
... | Enemy |
python | readthedocs__sphinx_rtd_theme | setup.py | {
"start": 126,
"end": 591
} | class ____(distutils.cmd.Command):
description = "Generate static assets"
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
if not 'CI' in os.environ and not 'TOX_ENV_NAME' in os.environ:
subprocess.run(['npm... | WebpackBuildCommand |
python | tornadoweb__tornado | tornado/simple_httpclient.py | {
"start": 954,
"end": 1363
} | class ____(HTTPError):
"""Error raised by SimpleAsyncHTTPClient on timeout.
For historical reasons, this is a subclass of `.HTTPClientError`
which simulates a response code of 599.
.. versionadded:: 5.1
"""
def __init__(self, message: str) -> None:
super().__init__(599, message=messag... | HTTPTimeoutError |
python | pandas-dev__pandas | pandas/io/pytables.py | {
"start": 179899,
"end": 184126
} | class ____:
"""
Carries out a selection operation on a tables.Table object.
Parameters
----------
table : a Table object
where : list of Terms (or convertible to)
start, stop: indices to start and/or stop selection
"""
def __init__(
self,
table: Table,
wher... | Selection |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 49082,
"end": 50335
} | class ____(GeneratedAirbyteSource):
@public
def __init__(
self,
name: str,
token: str,
key: str,
start_date: str,
survey_ids: Optional[list[str]] = None,
):
"""Airbyte Source for Qualaroo.
Documentation can be found at https://docs.airbyte.com... | QualarooSource |
python | mlflow__mlflow | mlflow/types/responses_helpers.py | {
"start": 5132,
"end": 5454
} | class ____(BaseModel):
reason: str | None = None
@model_validator(mode="after")
def check_reason(self) -> "IncompleteDetails":
if self.reason and self.reason not in {"max_output_tokens", "content_filter"}:
warnings.warn(f"Invalid reason: {self.reason}")
return self
| IncompleteDetails |
python | pytorch__pytorch | torch/_inductor/codegen/cpp_flex_attention_template.py | {
"start": 26679,
"end": 41411
} | class ____(CppTemplate):
def __init__(
self,
input_nodes,
layout: ir.Layout,
scale,
score_mod,
mask_mod,
kv_block_size,
q_block_size,
has_other_buffer,
no_full_kv_block,
fake_buffers,
len_score_other,
len_mask_ot... | CppFlexAttentionTemplate |
python | pydantic__pydantic | tests/mypy/modules/plugin_success.py | {
"start": 1696,
"end": 1883
} | class ____(KwargsNoMutationModel, frozen=False, from_attributes=True):
a: int = 1
KwargsMutationModel(x=1).x = 2
KwargsMutationModel.model_validate(model.__dict__)
| KwargsMutationModel |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/docstring_signature.py | {
"start": 477,
"end": 672
} | class ____:
def __init__(self):
"""F(foo: int, bar: int, baz: int) -> None
F(foo: str, bar: str, baz: str) -> None
F(foo: float, bar: float, baz: float)""" # NoQA: D209
| F |
python | scipy__scipy | scipy/optimize/tests/test_cobyla.py | {
"start": 5691,
"end": 6822
} | class ____:
# Test cobyla support for bounds (only when used via `minimize`)
# Invalid bounds is tested in
# test_optimize.TestOptimizeSimple.test_minimize_invalid_bounds
def test_basic(self):
def f(x):
return np.sum(x**2)
lb = [-1, None, 1, None, -0.5]
ub = [-0.5, ... | TestBounds |
python | django-debug-toolbar__django-debug-toolbar | debug_toolbar/_stubs.py | {
"start": 177,
"end": 378
} | class ____(NamedTuple):
frame: Any
filename: str
lineno: int
function: str
code_context: str
index: int
TidyStackTrace = list[tuple[str, int, str, str, Any | None]]
| InspectStack |
python | cython__cython | Cython/Compiler/PyrexTypes.py | {
"start": 111510,
"end": 112265
} | class ____(BaseType):
is_fake_reference = 0
# Common base type for C reference and C++ rvalue reference types.
subtypes = ['ref_base_type']
def __init__(self, base_type):
self.ref_base_type = base_type
def __repr__(self):
return "<%r %s>" % (self.__class__.__name__, self.ref_bas... | CReferenceBaseType |
python | google__jax | jax/experimental/source_mapper/common.py | {
"start": 853,
"end": 1017
} | class ____:
"""A container for a source map and the paired generated code."""
source_map: sourcemap.SourceMap
generated_code: str
pass_name: str
| SourceMapDump |
python | pytorch__pytorch | torch/ao/quantization/backend_config/backend_config.py | {
"start": 3838,
"end": 11140
} | class ____:
"""
Config object that specifies the supported data types passed as arguments to
quantize ops in the reference model spec, for input and output activations,
weights, and biases.
For example, consider the following reference model:
quant1 - [dequant1 - fp32_linear - quant2] - dequ... | DTypeConfig |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 185671,
"end": 186217
} | class ____:
_col_type = TSRANGE
_col_str = "TSRANGE"
def _data_str(self):
return "[2013-03-23 14:30:00,2013-03-30 23:30:00)"
def _data_obj(self):
return Range(
datetime.datetime(2013, 3, 23, 14, 30),
datetime.datetime(2013, 3, 30, 23, 30),
)
_epsilo... | _DateTimeRangeTests |
python | django__django | tests/i18n/patterns/tests.py | {
"start": 13918,
"end": 14740
} | class ____(URLTestCaseBase):
"""
Tests the redirect when the requested URL doesn't end with a slash
(`settings.APPEND_SLASH=False`).
"""
@override_settings(APPEND_SLASH=False)
def test_not_prefixed_redirect(self):
response = self.client.get("/not-prefixed", headers={"accept-language": "... | URLRedirectWithoutTrailingSlashSettingTests |
python | getsentry__sentry | src/sentry/integrations/api/endpoints/external_user_index.py | {
"start": 1034,
"end": 2376
} | class ____(OrganizationEndpoint, ExternalActorEndpointMixin):
owner = ApiOwner.ECOSYSTEM
permission_classes = (ExternalUserPermission,)
publish_status = {
"POST": ApiPublishStatus.PUBLIC,
}
@extend_schema(
operation_id="Create an External User",
parameters=[GlobalParams.ORG_... | ExternalUserEndpoint |
python | tensorflow__tensorflow | tensorflow/dtensor/python/tests/config_test.py | {
"start": 1102,
"end": 3497
} | class ____(tf_test.TestCase):
def setUp(self):
super().setUp()
test_util.reset_logical_devices('CPU', 2)
if test_util.is_gpu_present():
test_util.reset_logical_devices('GPU', 2)
def tearDown(self):
os.environ.pop(config._DT_JOBS, [])
super().tearDown()
def test_env_vars(self):
sel... | ConfigTest |
python | apache__airflow | providers/openfaas/src/airflow/providers/openfaas/hooks/openfaas.py | {
"start": 993,
"end": 5210
} | class ____(BaseHook):
"""
Interact with OpenFaaS to query, deploy, invoke and update function.
:param function_name: Name of the function, Defaults to None
:param conn_id: OpenFaaS connection to use, defaults to ``open_faas_default``
for example host : http://openfaas.faas.com
"""
conn... | OpenFaasHook |
python | ray-project__ray | rllib/connectors/connector.py | {
"start": 11287,
"end": 16043
} | class ____(abc.ABC):
"""Utility class for quick manipulation of a connector pipeline."""
def __init__(self, ctx: ConnectorContext, connectors: List[Connector]):
self.connectors = connectors
def in_training(self):
for c in self.connectors:
c.in_training()
def in_eval(self):... | ConnectorPipeline |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/nodes.py | {
"start": 2249,
"end": 2785
} | class ____(Node):
"""
styles:
? -> set() ? key, no value
" -> double quoted
' -> single quoted
| -> literal style
> -> folding style
"""
__slots__ = ('style',)
id = 'scalar'
def __init__(
self, tag, value, start_mark=None, end_mark=None, style=None, commen... | ScalarNode |
python | doocs__leetcode | solution/0300-0399/0365.Water and Jug Problem/Solution.py | {
"start": 0,
"end": 539
} | class ____:
def canMeasureWater(self, x: int, y: int, z: int) -> bool:
def dfs(i: int, j: int) -> bool:
if (i, j) in vis:
return False
vis.add((i, j))
if i == z or j == z or i + j == z:
return True
if dfs(x, j) or dfs(i, y) or d... | Solution |
python | plotly__plotly.py | plotly/graph_objs/pie/_stream.py | {
"start": 233,
"end": 3479
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "pie"
_path_str = "pie.stream"
_valid_props = {"maxpoints", "token"}
@property
def maxpoints(self):
"""
Sets the maximum number of points to keep on the plots from an
incoming stream. If `maxpoints` is set to 50, only t... | Stream |
python | google__pytype | pytype/pytd/visitors.py | {
"start": 5864,
"end": 7228
} | class ____(Visitor):
"""Change all NamedType objects to ClassType objects."""
def VisitNamedType(self, node):
"""Converts a named type to a class type, to be filled in later.
Args:
node: The NamedType. This type only has a name.
Returns:
A ClassType. This ClassType will (temporarily) only... | NamedTypeToClassType |
python | PyCQA__pylint | tests/functional/n/not_context_manager.py | {
"start": 551,
"end": 1460
} | class ____:
pass
with NotAManager(): #[not-context-manager]
pass
# Tests contextlib.contextmanager usage is recognized as correct.
from contextlib import contextmanager
@contextmanager
def dec():
yield
with dec(): # valid use
pass
# Tests a message is produced when a contextlib.contextmanager
# dec... | NotAManager |
python | walkccc__LeetCode | solutions/2108. Find First Palindromic String in the Array/2108.py | {
"start": 0,
"end": 324
} | class ____:
def firstPalindrome(self, words: list[str]) -> str:
def isPalindrome(s: str) -> bool:
i = 0
j = len(s) - 1
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
return next((word for word in words if isPalindrome(word)), '')
| Solution |
python | mlflow__mlflow | mlflow/mistral/autolog.py | {
"start": 1439,
"end": 4513
} | class ____:
"""Context manager for handling MLflow spans in both sync and async contexts."""
def __init__(self, original, instance, args, kwargs):
self.original = original
self.instance = instance
self.inputs = _construct_full_inputs(original, instance, *args, **kwargs)
# These... | TracingSession |
python | gevent__gevent | src/gevent/_tblib.py | {
"start": 1807,
"end": 2030
} | class ____(dict):
__slots__ = ()
def __getattr__(self, name):
try:
return self[name]
except KeyError:
raise AttributeError(name) from None
# noinspection PyPep8Naming
| _AttrDict |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/match1.py | {
"start": 3869,
"end": 4650
} | class ____:
def __init__(self, x: int, y: int) -> None:
self.x = x
self.y = y
def func6(subj: Any):
match subj:
# This should generate an error because a is used twice in the same pattern.
case [a, *a]:
pass
case ([c, d] as f) | ([d, c] as f):
... | Point |
python | google__pytype | pytype/pytd/codegen/function.py | {
"start": 394,
"end": 665
} | class ____(Exception):
"""Inconsistent property decorators on an overloaded function."""
def __init__(self, name, explanation):
msg = f"Invalid property decorators for '{name}': {explanation}"
super().__init__(msg)
@dataclasses.dataclass
| PropertyDecoratorError |
python | numba__numba | numba/tests/test_typedlist.py | {
"start": 18740,
"end": 21954
} | class ____(MemoryLeakMixin, TestCase):
def test_append_none(self):
@njit
def impl():
l = List()
l.append(None)
return l
self.assertEqual(impl.py_func(), impl())
def test_len_none(self):
@njit
def impl():
l = List()
... | TestNoneType |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 86909,
"end": 88260
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"sponsorable_id",
"sponsorable_login",
"amount",
"is_recurring",
"repository_id",
"repository_owner_login",
"repository_name"... | CreateSponsorsTierInput |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/context/metadata_logging.py | {
"start": 409,
"end": 2511
} | class ____:
per_output_metadata: Mapping[
Union[OutputMetadataHandle, AssetMetadataHandle], Mapping[str, Any]
]
@staticmethod
def empty() -> "OutputMetadataAccumulator":
return OutputMetadataAccumulator(per_output_metadata={})
def get_output_metadata(
self, output_name: str... | OutputMetadataAccumulator |
python | getsentry__sentry | src/sentry/grouping/enhancer/actions.py | {
"start": 1099,
"end": 2462
} | class ____:
# True if this action updates a frame's `category` or `in_app` value
is_classifier: bool
# True if this action updates the `contributes` value of either a frame or the stacktrace
sets_contributes: bool
def apply_modifications_to_frame(
self,
frames: Sequence[dict[str, An... | EnhancementAction |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.