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 | pytorch__pytorch | test/dynamo/cpython/3_13/test_ordered_dict.py | {
"start": 31399,
"end": 31989
} | class ____(__TestCase):
"""Builtin dict preserves insertion order.
Reuse some of tests in OrderedDict selectively.
"""
module = builtins
OrderedDict = dict
for method in (
"test_init test_update test_abc test_clear test_delitem " +
"test_setitem test_detect_deletion_during_iteration " +
... | CPythonBuiltinDictTests |
python | kamyu104__LeetCode-Solutions | Python/count-the-number-of-powerful-integers.py | {
"start": 1058,
"end": 1789
} | class ____(object):
def numberOfPowerfulInt(self, start, finish, limit, s):
"""
:type start: int
:type finish: int
:type limit: int
:type s: str
:rtype: int
"""
def count(x):
result = 0
str_x = str(x)
l = len(str_x)-... | Solution2 |
python | scipy__scipy | scipy/sparse/linalg/tests/test_special_sparse_arrays.py | {
"start": 6954,
"end": 9517
} | class ____:
"""
Sakurai tests
"""
def test_specific_shape(self):
sak = Sakurai(6)
assert_array_equal(sak.toarray(), sak(np.eye(6)))
a = np.array(
[
[ 5, -4, 1, 0, 0, 0],
[-4, 6, -4, 1, 0, 0],
[ 1, -4, 6, -4, 1... | TestSakurai |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_dot_address.py | {
"start": 1891,
"end": 4688
} | class ____(ColumnMapExpectation):
"""Expect column values to be valid Polkadot addresses."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"all_valid": [
... | ExpectColumnValuesToBeValidDotAddress |
python | readthedocs__readthedocs.org | readthedocs/builds/models.py | {
"start": 34897,
"end": 35722
} | class ____:
"""
Mixin for common command result methods/properties.
Shared methods between the database model :py:class:`BuildCommandResult` and
non-model representations of build command results from the API
"""
@property
def successful(self):
"""Did the command exit with a succes... | BuildCommandResultMixin |
python | python-openxml__python-docx | src/docx/opc/rel.py | {
"start": 223,
"end": 4469
} | class ____(Dict[str, "_Relationship"]):
"""Collection object for |_Relationship| instances, having list semantics."""
def __init__(self, baseURI: str):
super(Relationships, self).__init__()
self._baseURI = baseURI
self._target_parts_by_rId: dict[str, Any] = {}
def add_relationship(... | Relationships |
python | google__jax | jax/experimental/jax2tf/tests/flax_models/transformer_lm1b.py | {
"start": 10907,
"end": 12578
} | class ____(nn.Module):
"""Transformer pure decoder stack for language modelling.
Args:
config: TransformerConfig dataclass containing hyperparameters.
"""
config: TransformerConfig
@nn.compact
def __call__(self,
inputs,
inputs_positions=None,
inputs_segment... | TransformerLM |
python | gevent__gevent | src/greentest/3.10/test_asyncore.py | {
"start": 9721,
"end": 9876
} | class ____(asyncore.dispatcher_with_send):
def readable(self):
return False
def handle_connect(self):
pass
| dispatcherwithsend_noread |
python | doocs__leetcode | solution/0600-0699/0685.Redundant Connection II/Solution.py | {
"start": 0,
"end": 889
} | class ____:
def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]:
def find(x: int) -> int:
if p[x] != x:
p[x] = find(p[x])
return p[x]
n = len(edges)
ind = [0] * n
for _, v in edges:
ind[v - 1] += 1
... | Solution |
python | wntrblm__nox | nox/_version.py | {
"start": 1057,
"end": 3835
} | class ____(Exception):
"""The ``nox.needs_version`` specifier cannot be parsed."""
def get_nox_version() -> str:
"""Return the version of the installed Nox package."""
return metadata.version("nox")
def _parse_string_constant(node: ast.AST) -> str | None: # pragma: no cover
"""Return the value of a... | InvalidVersionSpecifier |
python | ansible__ansible | lib/ansible/modules/hostname.py | {
"start": 25208,
"end": 25321
} | class ____(Hostname):
platform = 'Linux'
distribution = 'Uos'
strategy_class = FileStrategy
| UosHostname |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataplex.py | {
"start": 93257,
"end": 95884
} | class ____(GoogleCloudBaseOperator):
"""
Base class for all Dataplex Catalog operators.
:param project_id: Required. The ID of the Google Cloud project where the service is used.
:param location: Required. The ID of the Google Cloud region where the service is used.
:param gcp_conn_id: Optional. Th... | DataplexCatalogBaseOperator |
python | pytorch__pytorch | test/distributed/tensor/debug/test_debug_mode.py | {
"start": 1057,
"end": 24819
} | class ____(TestCase):
def tearDown(self):
super().tearDown()
dist.destroy_process_group()
def setUp(self):
super().setUp()
self.world_size = 8
store = FakeStore()
dist.init_process_group(
backend="fake", rank=0, world_size=self.world_size, store=store... | TestDTensorDebugMode |
python | kubernetes-client__python | kubernetes/client/models/v1beta1_allocation_result.py | {
"start": 383,
"end": 5868
} | 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... | V1beta1AllocationResult |
python | scipy__scipy | scipy/optimize/tests/test_optimize.py | {
"start": 72756,
"end": 75212
} | class ____:
def setup_method(self):
self.bounds = ((1, None), (None, None))
self.solution = (1, 0)
def fun(self, x, p=2.0):
return 1.0 / p * (x[0]**p + x[1]**p)
def jac(self, x, p=2.0):
return x**(p - 1)
def fj(self, x, p=2.0):
return self.fun(x, p), self.jac(x... | TestLBFGSBBounds |
python | pytorch__pytorch | torch/_inductor/template_heuristics/triton.py | {
"start": 93577,
"end": 94237
} | class ____(INT8MMTemplateConfigMixin, XPUConfigHeuristic):
"""Int8 MM template heuristic for XPU"""
def __init__(self) -> None:
super().__init__()
# Override mm_configs to use int8_mm_configs
self.mm_configs = self.int8_mm_configs
# NOTE: overriding exhaustive configs here to be... | XPUInt8MMTemplateConfigHeuristic |
python | astropy__astropy | astropy/utils/console.py | {
"start": 32287,
"end": 32446
} | class ____:
def __init__(self):
import msvcrt # noqa: F401
def __call__(self):
import msvcrt
return msvcrt.getch()
| _GetchWindows |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_wxagg.py | {
"start": 227,
"end": 1398
} | class ____(FigureCanvasAgg, _FigureCanvasWxBase):
def draw(self, drawDC=None):
"""
Render the figure using agg.
"""
FigureCanvasAgg.draw(self)
self.bitmap = self._create_bitmap()
self._isDrawn = True
self.gui_repaint(drawDC=drawDC)
def blit(self, bbox=Non... | FigureCanvasWxAgg |
python | apache__airflow | providers/google/src/airflow/providers/google/marketing_platform/operators/analytics_admin.py | {
"start": 5130,
"end": 8274
} | class ____(GoogleCloudBaseOperator):
"""
Creates property.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:GoogleAnalyticsAdminCreatePropertyOperator`
:param analytics_property: The property to create. Note: the supplied pro... | GoogleAnalyticsAdminCreatePropertyOperator |
python | dagster-io__dagster | python_modules/dagster/dagster/components/core/component_tree.py | {
"start": 21781,
"end": 23222
} | class ____(ComponentTree):
"""ComponentTree variant which terminates autoloading of defs on the keyword
files `definitions.py` and `component.py`. This should only be used for legacy
test and load_defs codepaths.
"""
@property
def decl_load_context(self):
return ComponentDeclLoadContext... | LegacyAutoloadingComponentTree |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-nvidia/tests/test_structured_output.py | {
"start": 726,
"end": 824
} | class ____(BaseModel):
"""Data model for a song."""
title: str
length_seconds: int
| Song |
python | davidhalter__jedi | test/completion/pep0484_generic_parameters.py | {
"start": 7676,
"end": 7972
} | class ____(Mapping[str, T]):
pass
custom_partial1_instance: CustomPartialGeneric1[int] = NotImplemented
#? str()
first(custom_partial1_instance)
custom_partial1_unbound_instance: CustomPartialGeneric1 = NotImplemented
#? str()
first(custom_partial1_unbound_instance)
| CustomPartialGeneric1 |
python | python-attrs__attrs | tests/test_dunders.py | {
"start": 13074,
"end": 21157
} | class ____:
"""
Tests for `_add_hash`.
"""
def test_enforces_type(self):
"""
The `hash` argument to both attrs and attrib must be None, True, or
False.
"""
exc_args = ("Invalid value for hash. Must be True, False, or None.",)
with pytest.raises(TypeErro... | TestAddHash |
python | plotly__plotly.py | plotly/graph_objs/scatter/_unselected.py | {
"start": 233,
"end": 3352
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter"
_path_str = "scatter.unselected"
_valid_props = {"marker", "textfont"}
@property
def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class... | Unselected |
python | lazyprogrammer__machine_learning_examples | ann_class2/batch_norm_tf.py | {
"start": 2256,
"end": 5711
} | class ____(object):
def __init__(self, hidden_layer_sizes):
self.hidden_layer_sizes = hidden_layer_sizes
def set_session(self, session):
self.session = session
def fit(self, X, Y, Xtest, Ytest, activation=tf.nn.relu, learning_rate=1e-2, epochs=15, batch_sz=100, print_period=100, show_fig=True):
X = ... | ANN |
python | django__django | django/db/migrations/graph.py | {
"start": 1544,
"end": 13085
} | class ____:
"""
Represent the digraph of all migrations in a project.
Each migration is a node, and each dependency is an edge. There are
no implicit dependencies between numbered migrations - the numbering is
merely a convention to aid file listing. Every new numbered migration
has a declared ... | MigrationGraph |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/output/win32.py | {
"start": 19181,
"end": 22639
} | class ____:
"""
Inspired by pygments/formatters/terminal256.py
"""
def __init__(self) -> None:
self._win32_colors = self._build_color_table()
# Cache (map color string to foreground and background code).
self.best_match: dict[str, tuple[int, int]] = {}
@staticmethod
de... | ColorLookupTable |
python | sympy__sympy | sympy/stats/symbolic_probability.py | {
"start": 1198,
"end": 4705
} | class ____(Expr):
"""
Symbolic expression for the probability.
Examples
========
>>> from sympy.stats import Probability, Normal
>>> from sympy import Integral
>>> X = Normal("X", 0, 1)
>>> prob = Probability(X > 1)
>>> prob
Probability(X > 1)
Integral representation:
... | Probability |
python | ray-project__ray | python/ray/train/lightning/_lightning_utils.py | {
"start": 2382,
"end": 5073
} | class ____(FSDPStrategy): # noqa: F821
"""Subclass of FSDPStrategy to ensure compatibility with Ray orchestration.
For a full list of initialization arguments, please refer to:
https://lightning.ai/docs/pytorch/stable/api/lightning.pytorch.strategies.FSDPStrategy.html
.. note::
It is recommen... | RayFSDPStrategy |
python | getsentry__sentry | src/sentry/integrations/slack/webhooks/options_load.py | {
"start": 882,
"end": 4095
} | class ____(Endpoint):
owner = ApiOwner.ECOSYSTEM
publish_status = {
"POST": ApiPublishStatus.PRIVATE,
}
authentication_classes = ()
permission_classes = ()
slack_request_class = SlackOptionsLoadRequest
def is_substring(self, string, substring):
# in case either have special ... | SlackOptionsLoadEndpoint |
python | tensorflow__tensorflow | tensorflow/python/keras/testing_utils.py | {
"start": 18712,
"end": 19771
} | class ____(models.Model):
"""A Keras subclass model."""
def __init__(self, model_layers, *args, **kwargs):
"""Instantiate a model.
Args:
model_layers: a list of layers to be added to the model.
*args: Model's args
**kwargs: Model's keyword args, at most one of input_tensor -> the input
... | _SubclassModel |
python | doocs__leetcode | solution/1700-1799/1744.Can You Eat Your Favorite Candy on Your Favorite Day/Solution.py | {
"start": 0,
"end": 331
} | class ____:
def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:
s = list(accumulate(candiesCount, initial=0))
ans = []
for t, day, mx in queries:
least, most = day, (day + 1) * mx
ans.append(least < s[t + 1] and most > s[t])
retu... | Solution |
python | huggingface__transformers | src/transformers/models/fastspeech2_conformer/modeling_fastspeech2_conformer.py | {
"start": 14049,
"end": 19599
} | class ____(nn.Module):
"""
Multi-Head attention layer with relative position encoding. Details can be found in
https://github.com/espnet/espnet/pull/2816. Paper: https://huggingface.co/papers/1901.02860.
"""
def __init__(self, config: FastSpeech2ConformerConfig, module_config):
"""Construct... | FastSpeech2ConformerAttention |
python | encode__django-rest-framework | tests/test_response.py | {
"start": 3718,
"end": 7761
} | class ____(TestCase):
"""
End-to-end testing of renderers using an ResponseMixin on a generic view.
"""
def test_default_renderer_serializes_content(self):
"""If the Accept header is not set the default renderer should serialize the response."""
resp = self.client.get('/')
self.a... | RendererIntegrationTests |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_raise.py | {
"start": 5404,
"end": 7735
} | class ____(__TestCase):
def testCauseSyntax(self):
try:
try:
try:
raise TypeError
except Exception:
raise ValueError from None
except ValueError as exc:
self.assertIsNone(exc.__cause__)
... | TestCause |
python | getsentry__sentry | tests/sentry/integrations/utils/test_issue_summary_for_alerts.py | {
"start": 350,
"end": 9808
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.organization = self.create_organization()
self.project = self.create_project(organization=self.organization)
# Create an error group with the proper type
self.group = self.create_group(project=self.project, t... | FetchIssueSummaryTest |
python | numba__numba | numba/cuda/dispatcher.py | {
"start": 18402,
"end": 19839
} | class ____:
def __init__(self, dispatcher, griddim, blockdim, stream, sharedmem):
self.dispatcher = dispatcher
self.griddim = griddim
self.blockdim = blockdim
self.stream = stream
self.sharedmem = sharedmem
if config.CUDA_LOW_OCCUPANCY_WARNINGS:
# Warn wh... | _LaunchConfiguration |
python | spack__spack | var/spack/test_repos/spack_repo/tutorial/packages/netlib_lapack/package.py | {
"start": 220,
"end": 7429
} | class ____(CMakePackage):
"""LAPACK version 3.X is a comprehensive FORTRAN library that does
linear algebra operations including matrix inversions, least squared
solutions to linear sets of equations, eigenvector analysis, singular
value decomposition, etc. It is a very comprehensive and reputable
p... | NetlibLapack |
python | tensorflow__tensorflow | tensorflow/python/keras/utils/object_identity.py | {
"start": 2594,
"end": 3135
} | class ____(_ObjectIdentityWrapper):
"""Reference that refers an object.
```python
x = [1]
y = [1]
x_ref1 = Reference(x)
x_ref2 = Reference(x)
y_ref2 = Reference(y)
print(x_ref1 == x_ref2)
==> True
print(x_ref1 == y)
==> False
```
"""
__slots__ = ()
# Disabling super class' unwrapped ... | Reference |
python | gevent__gevent | src/gevent/tests/lock_tests.py | {
"start": 482,
"end": 1507
} | class ____(object):
"""
A bunch of threads.
"""
def __init__(self, f, n, wait_before_exit=False):
"""
Construct a bunch of `n` threads running the same function `f`.
If `wait_before_exit` is True, the threads won't terminate until
do_finish() is called.
"""
... | Bunch |
python | pytorch__pytorch | torch/nn/modules/adaptive.py | {
"start": 393,
"end": 12606
} | class ____(Module):
(
"""Efficient softmax approximation.
As described in
`Efficient softmax approximation for GPUs by Edouard Grave, Armand Joulin,
Moustapha Ciss\u00e9, David Grangier, and Herv\u00e9 J\u00e9gou
<https://arxiv.org/abs/1609.04309>`__.
"""
r"""
Adaptive softmax i... | AdaptiveLogSoftmaxWithLoss |
python | kamyu104__LeetCode-Solutions | Python/extract-kth-character-from-the-rope-tree.py | {
"start": 190,
"end": 621
} | class ____(object):
def getKthCharacter(self, root, k):
"""
:type root: Optional[RopeTreeNode]
:type k: int
:rtype: str
"""
while root.len:
l = max(root.left.len, len(root.left.val)) if root.left else 0
if k <= l:
root = root.le... | Solution |
python | apache__airflow | providers/standard/tests/unit/standard/decorators/test_external_python.py | {
"start": 2646,
"end": 10683
} | class ____:
@pytest.mark.parametrize(
"serializer",
[
pytest.param("dill", marks=DILL_MARKER, id="dill"),
pytest.param("cloudpickle", marks=CLOUDPICKLE_MARKER, id="cloudpickle"),
],
)
def test_with_serializer_works(self, serializer, dag_maker, venv_python_with... | TestExternalPythonDecorator |
python | kamyu104__LeetCode-Solutions | Python/count-subtrees-with-max-distance-between-cities.py | {
"start": 2242,
"end": 3673
} | class ____(object):
def countSubgraphsForEachDiameter(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: List[int]
"""
def popcount(mask):
count = 0
while mask:
mask &= mask-1
count += 1
... | Solution2 |
python | pyqtgraph__pyqtgraph | pyqtgraph/flowchart/Flowchart.py | {
"start": 21603,
"end": 22781
} | class ____(GraphicsObject):
def __init__(self, chart):
GraphicsObject.__init__(self)
self.chart = chart ## chart is an instance of Flowchart()
self.updateTerminals()
def updateTerminals(self):
self.terminals = {}
bounds = self.boundingRect()
inp = se... | FlowchartGraphicsItem |
python | huggingface__transformers | src/transformers/models/plbart/modular_plbart.py | {
"start": 17240,
"end": 18678
} | class ____(BartForCausalLM):
@auto_docstring
def forward(**super_kwargs):
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size... | PLBartForCausalLM |
python | realpython__materials | inheritance-and-composition/inheritance/productivity.py | {
"start": 409,
"end": 523
} | class ____:
def work(self, hours):
return f"expends {hours} hours doing office paperwork."
| SecretaryRole |
python | PyCQA__pylint | tests/functional/b/base_init_vars.py | {
"start": 100,
"end": 309
} | class ____:
"""A simple base class
"""
def __init__(self):
self.base_var = {}
def met(self):
"""yo"""
def meeting(self, with_):
"""ye"""
return with_
| BaseClass |
python | sympy__sympy | sympy/stats/joint_rv_types.py | {
"start": 10551,
"end": 12400
} | class ____(JointDistribution):
_argnames = ('mu', 'shape_mat', 'dof')
is_Continuous=True
@property
def set(self):
k = self.mu.shape[0]
return S.Reals**k
@staticmethod
def check(mu, sigma, v):
_value_check(mu.shape[0] == sigma.shape[0],
"Size of the ... | MultivariateTDistribution |
python | keon__algorithms | tests/test_dp.py | {
"start": 5262,
"end": 5846
} | class ____(unittest.TestCase):
def test_kfactor(self):
# Test 1
n1 = 4
k1 = 1
self.assertEqual(find_k_factor(n1, k1), 1)
# Test 2
n2 = 7
k2 = 1
self.assertEqual(find_k_factor(n2, k2), 70302)
# Test 3
n3 = 10
k3 = 2
sel... | Test_dp_K_Factor |
python | pypa__setuptools | setuptools/_vendor/backports/tarfile/__init__.py | {
"start": 10300,
"end": 10389
} | class ____(HeaderError):
"""Exception for invalid headers."""
pass
| InvalidHeaderError |
python | huggingface__transformers | src/transformers/models/sew/modular_sew.py | {
"start": 1582,
"end": 1650
} | class ____(Wav2Vec2LayerNormConvLayer):
pass
| SEWLayerNormConvLayer |
python | walkccc__LeetCode | solutions/1589. Maximum Sum Obtained of Any Permutation/1589.py | {
"start": 0,
"end": 514
} | class ____:
def maxSumRangeQuery(self, nums: list[int], requests: list[list[int]]) -> int:
MOD = 1_000_000_007
ans = 0
# count[i] := the number of times nums[i] has been requested
count = [0] * len(nums)
for start, end in requests:
count[start] += 1
if end + 1 < len(nums):
cou... | Solution |
python | gevent__gevent | src/greentest/3.10/test_httplib.py | {
"start": 56182,
"end": 57411
} | class ____(TestCase):
def setUp(self):
self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.port = socket_helper.bind_port(self.serv)
self.source_port = socket_helper.find_unused_port()
self.serv.listen()
self.conn = None
def tearDown(self):
if self... | SourceAddressTest |
python | aimacode__aima-python | deep_learning4e.py | {
"start": 2257,
"end": 2420
} | class ____(Activation):
def function(self, x):
return np.exp(x) / np.sum(np.exp(x))
def derivative(self, x):
return np.ones_like(x)
| SoftMax |
python | Textualize__textual | src/textual/command.py | {
"start": 14631,
"end": 14911
} | class ____(Input):
"""The command palette input control."""
DEFAULT_CSS = """
CommandInput, CommandInput:focus {
border: blank;
width: 1fr;
padding-left: 0;
background: transparent;
background-tint: 0%;
}
"""
| CommandInput |
python | tornadoweb__tornado | tornado/test/httpclient_test.py | {
"start": 1408,
"end": 1642
} | class ____(RequestHandler):
def prepare(self):
self.write("redirects can have bodies too")
self.redirect(
self.get_argument("url"), status=int(self.get_argument("status", "302"))
)
| RedirectHandler |
python | ipython__ipython | IPython/core/completer.py | {
"start": 47365,
"end": 63607
} | class ____(enum.Flag):
"""Represent state of the key match in context of other possible matches.
- given `d1 = {'a': 1}` completion on `d1['<tab>` will yield `{'a': END_OF_ITEM}` as there is no tuple.
- given `d2 = {('a', 'b'): 1}`: `d2['a', '<tab>` will yield `{'b': END_OF_TUPLE}` as there is no tuple mem... | _DictKeyState |
python | run-llama__llama_index | llama-index-core/llama_index/core/data_structs/data_structs.py | {
"start": 451,
"end": 974
} | class ____(DataClassJsonMixin):
"""A base data struct for a LlamaIndex."""
index_id: str = field(default_factory=lambda: str(uuid.uuid4()))
summary: Optional[str] = None
def get_summary(self) -> str:
"""Get text summary."""
if self.summary is None:
raise ValueError("summary... | IndexStruct |
python | prompt-toolkit__python-prompt-toolkit | examples/prompts/multiline-autosuggest.py | {
"start": 2768,
"end": 5955
} | class ____(Processor):
def __init__(self, style: str = "class:auto-suggestion") -> None:
self.style = style
def apply_transformation(self, ti: TransformationInput) -> Transformation:
# a convenient noop transformation that does nothing.
noop = Transformation(fragments=ti.fragments)
... | AppendMultilineAutoSuggestionInAnyLine |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1084568,
"end": 1089353
} | class ____(sgqlc.types.Type, Node, UniformResourceLocatable, RequirableByPullRequest):
"""A check run."""
__schema__ = github_schema
__field_names__ = (
"annotations",
"check_suite",
"completed_at",
"conclusion",
"database_id",
"deployment",
"details_... | CheckRun |
python | keras-team__keras | keras/src/backend/common/symbolic_scope.py | {
"start": 135,
"end": 683
} | class ____:
"""Scope to indicate the symbolic stage."""
def __enter__(self):
self.original_scope = get_symbolic_scope()
global_state.set_global_attribute("symbolic_scope", self)
return self
def __exit__(self, *args, **kwargs):
global_state.set_global_attribute("symbolic_sco... | SymbolicScope |
python | pypa__packaging | src/packaging/specifiers.py | {
"start": 1818,
"end": 3537
} | class ____(metaclass=abc.ABCMeta):
__slots__ = ()
@abc.abstractmethod
def __str__(self) -> str:
"""
Returns the str representation of this Specifier-like object. This
should be representative of the Specifier itself.
"""
@abc.abstractmethod
def __hash__(self) -> int... | BaseSpecifier |
python | django__django | tests/forms_tests/field_tests/test_charfield.py | {
"start": 216,
"end": 6444
} | class ____(FormFieldAssertionsMixin, SimpleTestCase):
def test_charfield_1(self):
f = CharField()
self.assertEqual("1", f.clean(1))
self.assertEqual("hello", f.clean("hello"))
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
... | CharFieldTest |
python | catalyst-team__catalyst | catalyst/contrib/layers/curricularface.py | {
"start": 82,
"end": 3902
} | class ____(nn.Module):
"""Implementation of
`CurricularFace: Adaptive Curriculum Learning\
Loss for Deep Face Recognition`_.
.. _CurricularFace\: Adaptive Curriculum Learning\
Loss for Deep Face Recognition:
https://arxiv.org/abs/2004.00288
Official `pytorch implementation`_.
... | CurricularFace |
python | langchain-ai__langchain | libs/core/langchain_core/prompt_values.py | {
"start": 2007,
"end": 2699
} | class ____(PromptValue):
"""Chat prompt value.
A type of a prompt value that is built from messages.
"""
messages: Sequence[BaseMessage]
"""List of messages."""
def to_string(self) -> str:
"""Return prompt as string."""
return get_buffer_string(self.messages)
def to_messa... | ChatPromptValue |
python | pytorch__pytorch | test/test_jit_disabled.py | {
"start": 1818,
"end": 2113
} | class ____(torch.jit.ScriptModule):
@torch.jit.script_method
def forward(self, input):
pass
AModule()
print("Didn't throw exception")
"""
self.compare_enabled_disabled(_program_string)
def test_recursive_script(self):
_program_string = """
import torch
| AModule |
python | pytorch__pytorch | .ci/pytorch/smoke_test/smoke_test.py | {
"start": 1237,
"end": 18412
} | class ____(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.fc1 = nn.Linear(9216, 1)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = F.max_pool2d(x, 2)
x... | Net |
python | doocs__leetcode | lcci/05.06.Convert Integer/Solution.py | {
"start": 0,
"end": 152
} | class ____:
def convertInteger(self, A: int, B: int) -> int:
A &= 0xFFFFFFFF
B &= 0xFFFFFFFF
return (A ^ B).bit_count()
| Solution |
python | python-pillow__Pillow | src/PIL/ImageShow.py | {
"start": 8343,
"end": 9568
} | class ____(UnixViewer):
"""
The X Viewer ``xv`` command.
This viewer supports the ``title`` parameter.
"""
def get_command_ex(
self, file: str, title: str | None = None, **options: Any
) -> tuple[str, str]:
# note: xv is pretty outdated. most modern systems have
# image... | XVViewer |
python | getsentry__sentry | tests/sentry/incidents/serializers/test_workflow_engine_incident.py | {
"start": 783,
"end": 5125
} | class ____(TestWorkflowEngineSerializer):
def setUp(self) -> None:
super().setUp()
self.add_warning_trigger()
self.add_incident_data()
self.incident_identifier = str(self.incident_group_open_period.incident_identifier)
self.incident_expected = {
"id": str(self.inc... | TestIncidentSerializer |
python | getsentry__sentry | tests/sentry_plugins/amazon_sqs/test_plugin.py | {
"start": 401,
"end": 5219
} | class ____(PluginTestCase):
@cached_property
def plugin(self) -> AmazonSQSPlugin:
return AmazonSQSPlugin()
def run_test(self) -> Event:
self.plugin.set_option("access_key", "access-key", self.project)
self.plugin.set_option("secret_key", "secret-key", self.project)
self.plug... | AmazonSQSPluginTest |
python | coleifer__peewee | peewee.py | {
"start": 13731,
"end": 15013
} | class ____(object):
__slots__ = ('_counter', '_current_index', '_mapping')
def __init__(self):
# A list of dictionaries containing mappings at various depths.
self._counter = 0
self._current_index = 0
self._mapping = []
self.push()
@property
def mapping(self):
... | AliasManager |
python | qdrant__qdrant-client | qdrant_client/embed/builtin_embedder.py | {
"start": 127,
"end": 3190
} | class ____:
_SUPPORTED_MODELS = ("Qdrant/Bm25",)
def __init__(self, **kwargs: Any) -> None:
pass
def embed(
self,
model_name: str,
texts: Optional[list[str]] = None,
options: Optional[dict[str, Any]] = None,
**kwargs: Any,
) -> NumericVector:
if ... | BuiltinEmbedder |
python | getsentry__sentry | src/sentry/db/postgres/schema.py | {
"start": 2238,
"end": 2885
} | class ____(PostgresDatabaseSchemaEditor):
"""workaround for https://code.djangoproject.com/ticket/36374"""
def create_model(self, model: type[Model]) -> None:
if any(isinstance(c, ExclusionConstraint) for c in model._meta.constraints):
self.execute("CREATE EXTENSION IF NOT EXISTS btree_gist... | MakeBtreeGistSchemaEditor |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 47188,
"end": 56369
} | class ____(_ConfigUpdateModel):
description: Optional[str] = Field(default=None)
property_descriptions: Optional[Dict[str, str]] = Field(default=None)
invertedIndexConfig: Optional[_InvertedIndexConfigUpdate] = Field(
default=None, alias="inverted_index_config"
)
replicationConfig: Optional[... | _CollectionConfigUpdate |
python | falconry__falcon | examples/recipes/multipart_mixed_main.py | {
"start": 36,
"end": 595
} | class ____:
def on_post(self, req, resp):
example = {}
for part in req.media:
if part.content_type.startswith('multipart/mixed'):
for nested in part.media:
example[nested.filename] = nested.text
resp.media = example
parser = falcon.media.Mul... | Forms |
python | doocs__leetcode | solution/1600-1699/1650.Lowest Common Ancestor of a Binary Tree III/Solution.py | {
"start": 177,
"end": 474
} | class ____:
def lowestCommonAncestor(self, p: "Node", q: "Node") -> "Node":
vis = set()
node = p
while node:
vis.add(node)
node = node.parent
node = q
while node not in vis:
node = node.parent
return node
| Solution |
python | realpython__materials | duck-typing-python/queues.py | {
"start": 32,
"end": 506
} | class ____:
def __init__(self):
self._elements = deque()
def enqueue(self, element):
self._elements.append(element)
def dequeue(self):
return self._elements.popleft()
def __iter__(self):
return iter(self._elements)
def __len__(self):
return len(self._eleme... | Queue |
python | plotly__plotly.py | plotly/graph_objs/surface/contours/x/_project.py | {
"start": 233,
"end": 5178
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "surface.contours.x"
_path_str = "surface.contours.x.project"
_valid_props = {"x", "y", "z"}
@property
def x(self):
"""
Determines whether or not these contour lines are projected on
the x plane. If `highlight` is set t... | Project |
python | pallets__flask | src/flask/testing.py | {
"start": 3374,
"end": 8823
} | class ____(Client):
"""Works like a regular Werkzeug test client, with additional behavior for
Flask. Can defer the cleanup of the request context until the end of a
``with`` block. For general information about how to use this class refer to
:class:`werkzeug.test.Client`.
.. versionchanged:: 0.12
... | FlaskClient |
python | sqlalchemy__sqlalchemy | examples/association/dict_of_sets_with_default.py | {
"start": 1205,
"end": 1290
} | class ____(DeclarativeBase):
id: Mapped[int] = mapped_column(primary_key=True)
| Base |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/self_assigning_variable.py | {
"start": 770,
"end": 809
} | class ____:
foo = foo
bar = bar
| Foo |
python | coleifer__peewee | tests/models.py | {
"start": 63507,
"end": 65585
} | class ____(ModelTestCase):
database = get_in_memory_db()
requires = [AutoCounter]
def tearDown(self):
super(TestDefaultDirtyBehavior, self).tearDown()
AutoCounter._meta.only_save_dirty = False
def test_default_dirty(self):
AutoCounter._meta.only_save_dirty = True
ac = ... | TestDefaultDirtyBehavior |
python | protocolbuffers__protobuf | python/google/protobuf/internal/descriptor_test.py | {
"start": 26054,
"end": 36092
} | class ____(unittest.TestCase):
"""Tests for the properties of descriptors in generated code."""
def CheckMessageDescriptor(self, message_descriptor):
# Basic properties
self.assertEqual(message_descriptor.name, 'TestAllTypes')
self.assertEqual(message_descriptor.full_name,
'proto2_... | GeneratedDescriptorTest |
python | Pylons__pyramid | src/pyramid/csrf.py | {
"start": 2862,
"end": 12965
} | class ____:
"""An alternative CSRF implementation that stores its information in
unauthenticated cookies, known as the 'Double Submit Cookie' method in the
`OWASP CSRF guidelines
<https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#double-submit-cookie>`... | CookieCSRFStoragePolicy |
python | fsspec__filesystem_spec | fsspec/caching.py | {
"start": 15924,
"end": 19479
} | class ____(BaseCache):
"""Cache which holds data in a in-memory bytes object
Implements read-ahead by the block size, for semi-random reads progressing
through the file.
Parameters
----------
trim: bool
As we read more data, whether to discard the start of the buffer when
we ar... | BytesCache |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_glue.py | {
"start": 27521,
"end": 32905
} | class ____:
RUN_ID = "1234567890"
DATA_SOURCE = {"GlueTable": {"DatabaseName": "TestDB", "TableName": "TestTable"}}
ROLE = "role_arn"
@pytest.fixture
def mock_conn(self) -> Generator[BaseAwsConnection, None, None]:
with mock.patch.object(GlueDataQualityHook, "conn") as _conn:
_c... | TestGlueDataQualityRuleRecommendationRunOperator |
python | getsentry__sentry | src/sentry/sentry_apps/api/endpoints/sentry_app_webhook_requests.py | {
"start": 1110,
"end": 2158
} | class ____(serializers.Serializer):
date_format = "%Y-%m-%d %H:%M:%S"
eventType = serializers.ChoiceField(
choices=EXTENDED_VALID_EVENTS,
required=False,
)
errorsOnly = serializers.BooleanField(default=False, required=False)
organizationSlug = serializers.CharField(required=False)
... | IncomingRequestSerializer |
python | sympy__sympy | sympy/geometry/entity.py | {
"start": 1746,
"end": 16828
} | class ____(Basic, EvalfMixin):
"""The base class for all geometrical entities.
This class does not represent any particular geometric entity, it only
provides the implementation of some methods common to all subclasses.
"""
__slots__: tuple[str, ...] = ()
def __contains__(self, other):
... | GeometryEntity |
python | realpython__materials | python-mutable-immutable/immutable.py | {
"start": 0,
"end": 299
} | class ____:
def __init__(self, value):
super().__setattr__("value", value)
def __setattr__(self, name, attr_value):
raise AttributeError(f"can't set attribute '{name}'")
def __delattr__(self, name):
raise AttributeError(f"can't delete attribute '{name}'")
| Immutable |
python | pytest-dev__pytest | testing/test_recwarn.py | {
"start": 4335,
"end": 8751
} | class ____:
"""test pytest.deprecated_call()"""
def dep(self, i: int, j: int | None = None) -> int:
if i == 0:
warnings.warn("is deprecated", DeprecationWarning, stacklevel=1)
return 42
def dep_explicit(self, i: int) -> None:
if i == 0:
warnings.warn_explici... | TestDeprecatedCall |
python | keras-team__keras | keras/src/ops/operation_test.py | {
"start": 2649,
"end": 3056
} | class ____(operation.Operation):
def __init__(self, alpha, **kwargs):
super().__init__(**kwargs)
self.alpha = alpha
def call(self, x):
return self.alpha * x
def compute_output_spec(self, x):
return keras_tensor.KerasTensor(x.shape, x.dtype)
def get_config(self):
... | OpWithKwargsInConstructorGetConfig |
python | HIPS__autograd | autograd/builtins.py | {
"start": 5816,
"end": 6257
} | class ____(ContainerVSpace):
def _values(self, x):
return x.values()
def _kv_pairs(self, x):
return x.items()
def _map(self, f, *args):
return {k: f(vs, *[x[k] for x in args]) for k, vs in self.shape.items()}
def _subval(self, xs, idx, x):
d = dict(xs.items())
... | DictVSpace |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py | {
"start": 99706,
"end": 104510
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("hyperparameter_tuning_job.types.HyperparameterTuningJob.to_dict"))
@mock.patch(VERTEX_AI_PATH.format("hyperparameter_tuning_job.HyperparameterTuningJobHook"))
def test_execute(self, mock_hook, to_dict_mock):
op = CreateHyperparameterTuningJobOperator(
... | TestVertexAICreateHyperparameterTuningJobOperator |
python | ray-project__ray | release/llm_tests/serve/probes/query_utils.py | {
"start": 4849,
"end": 5398
} | class ____:
def __init__(
self,
client: openai.AsyncClient,
retryable_error_types: Sequence[Type[APIStatusError]] = None,
):
assert not client or isinstance(
client, openai.AsyncClient
), "Async OpenAI client is expected!"
self.client: openai.AsyncClie... | BaseProbe |
python | sqlalchemy__sqlalchemy | test/aaa_profiling/test_memusage.py | {
"start": 47008,
"end": 48651
} | class ____(fixtures.TestBase):
@testing.fixture
def user_fixture(self, decl_base):
class User(decl_base):
__tablename__ = "user"
id = Column(Integer, primary_key=True)
name = Column(String(50))
decl_base.metadata.create_all(testing.db)
yield User
... | MiscMemoryIntensiveTests |
python | django__django | django/db/models/query_utils.py | {
"start": 1188,
"end": 8518
} | class ____(tree.Node):
"""
Encapsulate filters as objects that can then be combined logically (using
`&` and `|`).
"""
# Connection types
AND = "AND"
OR = "OR"
XOR = "XOR"
default = AND
conditional = True
connectors = (None, AND, OR, XOR)
def __init__(self, *args, _conn... | Q |
python | pennersr__django-allauth | allauth/idp/oidc/app_settings.py | {
"start": 0,
"end": 2052
} | class ____:
def __init__(self, prefix):
self.prefix = prefix
def _setting(self, name, dflt):
from allauth.utils import get_setting
return get_setting(self.prefix + name, dflt)
@property
def ADAPTER(self):
return self._setting(
"ADAPTER",
"allaut... | AppSettings |
python | python__mypy | mypyc/ir/ops.py | {
"start": 4512,
"end": 5304
} | class ____:
"""Abstract base class for all IR values.
These include references to registers, literals, and all
operations (Ops), such as assignments, calls and branches.
Values are often used as inputs of Ops. Register can be used as an
assignment target.
A Value is part of the IR being compi... | Value |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.