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 | huggingface__transformers | src/transformers/models/splinter/modeling_splinter.py | {
"start": 9809,
"end": 11300
} | class ____(GradientCheckpointingLayer):
def __init__(self, config):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = SplinterAttention(config)
self.intermediate = SplinterIntermediate(config)
self.o... | SplinterLayer |
python | modin-project__modin | modin/core/computation/ops.py | {
"start": 8740,
"end": 13345
} | class ____(Op):
"""
Hold a binary operator and its operands.
Parameters
----------
op : str
lhs : Term or Op
rhs : Term or Op
"""
def __init__(self, op: str, lhs, rhs) -> None:
super().__init__(op, (lhs, rhs))
self.lhs = lhs
self.rhs = rhs
self._dis... | BinOp |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-linnworks/source_linnworks/streams.py | {
"start": 1654,
"end": 2355
} | class ____(ABC):
# https://apps.linnworks.net/Api/Class/linnworks-spa-commondata-Generic-GenericPagedResult
@abstractmethod
def paged_result(self, response: requests.Response) -> Mapping[str, Any]:
pass
def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]:
... | LinnworksGenericPagedResult |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 42472,
"end": 43058
} | class ____(DelegatingLexer):
"""
Subclass of the `DjangoLexer` that highlights unlexed data with the
`XmlLexer`.
"""
name = 'XML+Django/Jinja'
aliases = ['xml+django', 'xml+jinja']
alias_filenames = ['*.xml']
mimetypes = ['application/xml+django', 'application/xml+jinja']
def __ini... | XmlDjangoLexer |
python | kamyu104__LeetCode-Solutions | Python/minimum-deletions-to-make-character-frequencies-unique.py | {
"start": 63,
"end": 505
} | class ____(object):
def minDeletions(self, s):
"""
:type s: str
:rtype: int
"""
count = collections.Counter(s)
result = 0
lookup = set()
for c in string.ascii_lowercase:
for i in reversed(xrange(1, count[c]+1)):
if i not in ... | Solution |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_multiarray.py | {
"start": 216303,
"end": 224338
} | class ____(TestCase):
class RaiseOnBool:
def __bool__(self):
raise ValueError
# true_vals = [True, np._CopyMode.ALWAYS, np.True_]
# false_vals = [False, np._CopyMode.IF_NEEDED, np.False_]
true_vals = [True, 1, np.True_]
false_vals = [False, 0, np.False_]
def test_scalars(se... | TestArrayCreationCopyArgument |
python | mahmoud__glom | glom/core.py | {
"start": 28618,
"end": 33060
} | class ____:
"""Coalesce objects specify fallback behavior for a list of
subspecs.
Subspecs are passed as positional arguments, and keyword arguments
control defaults. Each subspec is evaluated in turn, and if none
match, a :exc:`CoalesceError` is raised, or a default is returned,
depending on t... | Coalesce |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/engine/interfaces.py | {
"start": 7768,
"end": 8879
} | class ____(TypedDict):
"""represent the reflected IDENTITY structure of a column, corresponding
to the :class:`_schema.Identity` construct.
The :class:`.ReflectedIdentity` structure is part of the
:class:`.ReflectedColumn` structure, which is returned by the
:meth:`.Inspector.get_columns` method.
... | ReflectedIdentity |
python | ansible__ansible | test/units/executor/test_task_result.py | {
"start": 846,
"end": 6517
} | class ____(unittest.TestCase):
def test_task_result_basic(self):
mock_host = MagicMock()
mock_task = MagicMock()
# test loading a result with a dict
tr = _RawTaskResult(mock_host, mock_task, {}, {})
def test_task_result_is_changed(self):
mock_host = MagicMock()
... | TestRawTaskResult |
python | doocs__leetcode | solution/0900-0999/0998.Maximum Binary Tree II/Solution.py | {
"start": 192,
"end": 476
} | class ____:
def insertIntoMaxTree(
self, root: Optional[TreeNode], val: int
) -> Optional[TreeNode]:
if root is None or root.val < val:
return TreeNode(val, root)
root.right = self.insertIntoMaxTree(root.right, val)
return root
| Solution |
python | pydata__xarray | xarray/tests/test_groupby.py | {
"start": 118057,
"end": 137199
} | class ____:
def test_season_to_month_tuple(self):
assert season_to_month_tuple(["JF", "MAM", "JJAS", "OND"]) == (
(1, 2),
(3, 4, 5),
(6, 7, 8, 9),
(10, 11, 12),
)
assert season_to_month_tuple(["DJFM", "AM", "JJAS", "ON"]) == (
(12, ... | TestSeasonGrouperAndResampler |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefaultClass3.py | {
"start": 3213,
"end": 3613
} | class ____[T1 = str, *Ts2 = Unpack[tuple[T1, ...]]]: ...
tc1 = ClassTC()
reveal_type(tc1, expected_text="ClassTC[str, *tuple[str, ...]]")
tc2 = ClassTC[int]()
reveal_type(tc2, expected_text="ClassTC[int, *tuple[int, ...]]")
tc3 = ClassTC[int, *tuple[()]]()
reveal_type(tc3, expected_text="ClassTC[int]")
tc4 = Class... | ClassTC |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 23546,
"end": 23671
} | class ____(RequestHandler):
def get(self):
self.render("linkify.html", message="http://example.com")
| LinkifyHandler |
python | django-extensions__django-extensions | tests/management/commands/test_syncdata.py | {
"start": 396,
"end": 2125
} | class ____(TestCase):
"""Tests for SyncData command exceptions."""
def test_should_return_SyncDataError_when_unknown_fixture_format(self):
with pytest.raises(
CommandError,
match="Problem installing fixture 'foo': jpeg is not a known serialization format.",
):
... | SyncDataExceptionsTests |
python | h5py__h5py | h5py/tests/test_vds/test_lowlevel_vds.py | {
"start": 3074,
"end": 4133
} | class ____:
FEM_PIXELS_PER_CHIP_X = 256
FEM_PIXELS_PER_CHIP_Y = 256
FEM_CHIPS_PER_STRIPE_X = 8
FEM_CHIPS_PER_STRIPE_Y = 1
FEM_STRIPES_PER_MODULE = 2
@property
def sensor_module_dimensions(self):
x_pixels = self.FEM_PIXELS_PER_CHIP_X * self.FEM_CHIPS_PER_STRIPE_X
y_pixels = s... | ExcaliburData |
python | Pylons__pyramid | tests/test_predicates.py | {
"start": 865,
"end": 2098
} | class ____(unittest.TestCase):
def _makeOne(self, val):
from pyramid.predicates import RequestMethodPredicate
return RequestMethodPredicate(val, None)
def test_ctor_get_but_no_head(self):
inst = self._makeOne('GET')
self.assertEqual(inst.val, ('GET', 'HEAD'))
def test___ca... | TestRequestMethodPredicate |
python | walkccc__LeetCode | solutions/654. Maximum Binary Tree/654.py | {
"start": 0,
"end": 417
} | class ____:
def constructMaximumBinaryTree(self, nums: list[int]) -> TreeNode | None:
def build(i: int, j: int) -> TreeNode | None:
if i > j:
return None
maxNum = max(nums[i:j + 1])
maxIndex = nums.index(maxNum)
root = TreeNode(maxNum)
root.left = build(i, maxIndex - 1)
... | Solution |
python | openai__openai-python | src/openai/resources/realtime/calls.py | {
"start": 30690,
"end": 31293
} | class ____:
def __init__(self, calls: Calls) -> None:
self._calls = calls
self.create = _legacy_response.to_raw_response_wrapper(
calls.create,
)
self.accept = _legacy_response.to_raw_response_wrapper(
calls.accept,
)
self.hangup = _legacy_res... | CallsWithRawResponse |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_kubernetes_engine.py | {
"start": 48567,
"end": 49806
} | class ____:
def test_template_fields(self):
assert set(GKEDeleteJobOperator.template_fields) == set(GKEOperatorMixin.template_fields) | set(
KubernetesDeleteJobOperator.template_fields
)
def test_gcp_conn_id_required(self):
with pytest.raises(AirflowException):
G... | TestGKEDeleteJobOperator |
python | huggingface__transformers | src/transformers/models/sam3_tracker_video/modular_sam3_tracker_video.py | {
"start": 19088,
"end": 19174
} | class ____(Sam2VideoMaskDownSamplerLayer):
pass
| Sam3TrackerVideoMaskDownSamplerLayer |
python | keras-team__keras | keras/src/layers/rnn/gru.py | {
"start": 13820,
"end": 28784
} | class ____(RNN):
"""Gated Recurrent Unit - Cho et al. 2014.
Based on available runtime hardware and constraints, this layer
will choose different implementations (cuDNN-based or backend-native)
to maximize the performance. If a GPU is available and all
the arguments to the layer meet the requiremen... | GRU |
python | sympy__sympy | sympy/sets/fancysets.py | {
"start": 923,
"end": 2079
} | class ____(Set, metaclass=Singleton):
"""
Represents the rational numbers. This set is also available as
the singleton ``S.Rationals``.
Examples
========
>>> from sympy import S
>>> S.Half in S.Rationals
True
>>> iterable = iter(S.Rationals)
>>> [next(iterable) for i in range(1... | Rationals |
python | paramiko__paramiko | tests/test_client.py | {
"start": 3774,
"end": 8714
} | class ____(unittest.TestCase):
def setUp(self):
self.sockl = socket.socket()
self.sockl.bind(("localhost", 0))
self.sockl.listen(1)
self.addr, self.port = self.sockl.getsockname()
self.connect_kwargs = dict(
hostname=self.addr,
port=self.port,
... | ClientTest |
python | patrys__httmock | tests.py | {
"start": 5596,
"end": 6293
} | class ____(unittest.TestCase):
@all_requests
def response_content(self, url, request):
return {'status_code': 200, 'content': 'Oh hai'}
def test_all_requests_response(self):
with HTTMock(self.response_content):
r = requests.get('https://example.com/')
self.assertEqual(r.... | AllRequestsMethodDecoratorTest |
python | django__django | django/contrib/gis/gdal/field.py | {
"start": 4809,
"end": 4884
} | class ____(Field):
pass
# OFTDate, OFTTime, OFTDateTime fields.
| OFTBinary |
python | apache__airflow | providers/fab/src/airflow/providers/fab/auth_manager/api_fastapi/datamodels/roles.py | {
"start": 924,
"end": 1040
} | class ____(BaseModel):
"""Outgoing representation of an action (permission name)."""
name: str
| ActionResponse |
python | pytest-dev__pytest-cov | src/pytest_cov/engine.py | {
"start": 9621,
"end": 11238
} | class ____(CovController):
"""Implementation for centralised operation."""
@_ensure_topdir
def start(self):
self.cov = coverage.Coverage(
source=self.cov_source,
branch=self.cov_branch,
data_suffix=True,
config_file=self.cov_config,
)
... | Central |
python | bokeh__bokeh | src/bokeh/embed/util.py | {
"start": 2162,
"end": 6114
} | class ____:
''' This class merely provides a non-None default value for ``theme``
arguments, since ``None`` itself is a meaningful value for users to pass.
'''
pass
@contextmanager
def OutputDocumentFor(objs: Sequence[Model], apply_theme: Theme | type[FromCurdoc] | None = None,
always_new: boo... | FromCurdoc |
python | pypa__setuptools | setuptools/tests/test_namespaces.py | {
"start": 107,
"end": 4515
} | class ____:
def test_mixed_site_and_non_site(self, tmpdir):
"""
Installing two packages sharing the same namespace, one installed
to a site dir and the other installed just to a path on PYTHONPATH
should leave the namespace in tact and both packages reachable by
import.
... | TestNamespaces |
python | walkccc__LeetCode | solutions/1918. Kth Smallest Subarray Sum/1918.py | {
"start": 0,
"end": 412
} | class ____:
def kthSmallestSubarraySum(self, nums: list[int], k: int) -> int:
def numSubarrayLessThan(m: int) -> int:
res = 0
summ = 0
l = 0
for r, num in enumerate(nums):
summ += num
while summ > m:
summ -= nums[l]
l += 1
res += r - l + 1
... | Solution |
python | walkccc__LeetCode | solutions/2746. Decremental String Concatenation/2746.py | {
"start": 0,
"end": 706
} | class ____:
def minimizeConcatenatedLength(self, words: list[str]) -> int:
@functools.lru_cache(None)
def dp(i: int, first: str, last: str) -> int:
"""
Returns the minimum concatenated length of the first i words starting with
`first` and ending in `last`.
"""
if i == len(words):... | Solution |
python | django__django | tests/template_tests/filter_tests/test_slugify.py | {
"start": 206,
"end": 1000
} | class ____(SimpleTestCase):
"""
Running slugify on a pre-escaped string leads to odd behavior,
but the result is still safe.
"""
@setup(
{
"slugify01": (
"{% autoescape off %}{{ a|slugify }} {{ b|slugify }}{% endautoescape %}"
)
}
)
de... | SlugifyTests |
python | getsentry__sentry | src/sentry/notifications/types.py | {
"start": 2154,
"end": 2390
} | class ____(StrEnum):
ALERTS = "alerts"
APPROVAL = "approval"
DEPLOY = "deploy"
EMAIL = "email"
QUOTA = "quota"
REPORTS = "reports"
WORKFLOW = "workflow"
SPIKE_PROTECTION = "spikeProtection"
| FineTuningAPIKey |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramInference1.py | {
"start": 906,
"end": 1206
} | class ____:
pass
Undefined = _Undefined()
def func4(a=1, b=None, c=Undefined, d=lambda x: x):
reveal_type(a, expected_text="int")
reveal_type(b, expected_text="Unknown | None")
reveal_type(c, expected_text="_Undefined | Unknown")
reveal_type(d, expected_text="Unknown")
| _Undefined |
python | getsentry__sentry | tests/sentry/issue_detection/test_large_http_payload_detector.py | {
"start": 714,
"end": 14525
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self._settings = get_detection_settings()
def find_problems(self, event: dict[str, Any]) -> list[PerformanceProblem]:
detector = LargeHTTPPayloadDetector(self._settings, event)
run_detector_on_data(detector, event)
... | LargeHTTPPayloadDetectorTest |
python | milvus-io__pymilvus | tests/test_bulk_writer_stage.py | {
"start": 691,
"end": 6013
} | class ____:
"""Test stage RESTful API functions."""
@pytest.fixture
def mock_response(self) -> Mock:
"""Create a mock response object."""
response = Mock(spec=requests.Response)
response.status_code = 200
response.json.return_value = {"code": 0, "message": "success", "data":... | TestStageRestful |
python | pandas-dev__pandas | asv_bench/benchmarks/rolling.py | {
"start": 9975,
"end": 10461
} | class ____:
# https://github.com/pandas-dev/pandas/issues/38038
# specific example where the rolling operation on a larger dataframe
# is relatively cheap (few but large groups), but creation of
# MultiIndex of result can be expensive
def setup(self):
N = 100000
self.df = pd.DataFra... | GroupbyLargeGroups |
python | tensorflow__tensorflow | tensorflow/python/eager/context.py | {
"start": 83694,
"end": 106860
} | class ____(object):
"""Context-manager forcing placement of ops and Tensors on a device."""
__slots__ = ["_device_name", "_ctx", "_stack"]
def __init__(self, ctx, device_name):
self._device_name = device_name
self._ctx = ctx
self._stack = []
# TODO(b/189233748): Consolidate the device string pars... | _EagerDeviceContext |
python | joke2k__faker | faker/providers/company/ro_RO/__init__.py | {
"start": 45,
"end": 687
} | class ____(CompanyProvider):
formats = (
"{{last_name}} {{company_suffix}}",
"{{last_name}} {{last_name}} {{company_suffix}}",
"{{last_name}}",
)
company_prefixes = ("S.C.", "S.S.I.", "A.D.")
company_suffixes = (
"SRL",
"SA",
"SCA",
"SNC",
... | Provider |
python | sphinx-doc__sphinx | sphinx/util/inspect.py | {
"start": 22480,
"end": 38488
} | class ____(Mapping[str, Any]):
"""Pseudo namespace class for :confval:`autodoc_type_aliases`.
Useful for looking up nested objects via ``namespace.foo.bar.Class``.
"""
def __init__(self, mapping: Mapping[str, str]) -> None:
super().__init__()
self.__mapping = mapping
def __getitem... | TypeAliasNamespace |
python | sphinx-doc__sphinx | sphinx/pycode/parser.py | {
"start": 5959,
"end": 7631
} | class ____(TokenProcessor):
"""Python source code parser to pick up comments after assignments.
This parser takes code which starts with an assignment statement,
and returns the comment for the variable if one exists.
"""
def __init__(self, lines: list[str]) -> None:
super().__init__(lines... | AfterCommentParser |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/sparse_ops/sparse_slice_op_test.py | {
"start": 1157,
"end": 17862
} | class ____(test.TestCase):
def _SparseTensor_4x6(self, val_dtype=np.int64):
# [0 | |2 | |4 |5 ]
# [ |11| |13|14| ]
# [20| | |23| |25]
# [30| |32|33| |35]
ind = np.array([[0, 0], [0, 2], [0, 4], [0, 5], [1, 1], [1, 3], [1,
... | SparseSliceOpTest |
python | streamlit__streamlit | lib/streamlit/runtime/caching/cache_errors.py | {
"start": 3025,
"end": 3885
} | class ____(StreamlitAPIException):
def __init__(
self,
cache_type: CacheType,
cached_func: Callable[..., Any],
) -> None:
func_name = get_cached_func_name_md(cached_func)
decorator_name = get_decorator_api_name(cache_type)
msg = (
f"""
While running {... | CacheReplayClosureError |
python | getsentry__sentry | tests/sentry/overwatch/endpoints/test_overwatch_rpc.py | {
"start": 1056,
"end": 10899
} | class ____(APITestCase):
def _auth_header_for_get(self, url: str, params: dict[str, str], secret: str) -> str:
# For GET we sign an empty JSON array body per Rpcsignature rpc0
message = b"[]"
signature = hmac.new(secret.encode(), message, hashlib.sha256).hexdigest()
return f"Rpcsigna... | TestPreventPrReviewResolvedConfigsEndpoint |
python | encode__django-rest-framework | tests/test_fields.py | {
"start": 35711,
"end": 36299
} | class ____(FieldValues):
"""
Valid and invalid values for `IntegerField` with min and max limits.
"""
valid_inputs = {
'1': 1,
'3': 3,
1: 1,
3: 3,
}
invalid_inputs = {
0: ['Ensure this value is greater than or equal to 1.'],
4: ['Ensure this value ... | TestMinMaxIntegerField |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol40.py | {
"start": 315,
"end": 362
} | class ____(P1Parent[S], Protocol[S]): ...
| P1Child |
python | PyCQA__pylint | doc/data/messages/i/invalid-slots-object/good.py | {
"start": 0,
"end": 50
} | class ____:
__slots__ = ("name", "surname")
| Person |
python | pytorch__pytorch | torch/_inductor/ops_handler.py | {
"start": 25421,
"end": 26139
} | class ____(DefaultHandler):
name = "NoopHandler"
def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
return None
@staticmethod
def masked(mask, body, other) -> None:
return None
@staticmethod
def frexp(x) -> tuple[None, None]:
return (N... | NoopHandler |
python | doocs__leetcode | solution/0400-0499/0475.Heaters/Solution.py | {
"start": 0,
"end": 808
} | class ____:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
houses.sort()
heaters.sort()
def check(r):
m, n = len(houses), len(heaters)
i = j = 0
while i < m:
if j >= n:
return False
... | Solution |
python | protocolbuffers__protobuf | python/google/protobuf/internal/unknown_fields_test.py | {
"start": 13177,
"end": 16921
} | class ____(unittest.TestCase):
def setUp(self):
self.descriptor = missing_enum_values_pb2.TestEnumValues.DESCRIPTOR
self.message = missing_enum_values_pb2.TestEnumValues()
# TestEnumValues.ZERO = 0, but does not exist in the other NestedEnum.
self.message.optional_nested_enum = (
missing_enu... | UnknownEnumValuesTest |
python | Lightning-AI__lightning | src/lightning/pytorch/core/hooks.py | {
"start": 13127,
"end": 25213
} | class ____:
"""Hooks to be used for data related stuff."""
def __init__(self) -> None:
"""
Attributes:
prepare_data_per_node:
If True, each LOCAL_RANK=0 will call prepare data.
Otherwise only NODE_RANK=0, LOCAL_RANK=0 will prepare data.
al... | DataHooks |
python | kamyu104__LeetCode-Solutions | Python/largest-number-after-mutating-substring.py | {
"start": 29,
"end": 525
} | class ____(object):
def maximumNumber(self, num, change):
"""
:type num: str
:type change: List[int]
:rtype: str
"""
mutated = False
result = map(int, list(num))
for i, d in enumerate(result):
if change[d] < d:
if mutated:
... | Solution |
python | django__django | django/views/generic/dates.py | {
"start": 18564,
"end": 19903
} | class ____(YearMixin, MonthMixin, DayMixin, BaseDateListView):
"""
Base view for a list of objects published on a given day.
This requires subclassing to provide a response mixin.
"""
def get_dated_items(self):
"""Return (date_list, items, extra_context) for this request."""
year =... | BaseDayArchiveView |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/solver36.py | {
"start": 247,
"end": 582
} | class ____(BaseContainer[P]):
def __init__(self, obj: P) -> None:
self.item = obj
def func1(obj: BaseContainer[T]) -> T:
return obj.item
func1(Container(1))
func1(Container(1.0))
# This should generate an error because str isn't compatible with
# the bound of the TypeVar in Container.
func1(Conta... | Container |
python | networkx__networkx | networkx/algorithms/centrality/tests/test_betweenness_centrality.py | {
"start": 414,
"end": 16088
} | class ____:
def test_K5(self):
"""Betweenness centrality: K5"""
G = nx.complete_graph(5)
b = nx.betweenness_centrality(G, weight=None, normalized=False)
b_answer = {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}
for n in sorted(G):
assert b[n] == pytest.approx(b_answer[n... | TestBetweennessCentrality |
python | scipy__scipy | scipy/fftpack/tests/test_real_transforms.py | {
"start": 11752,
"end": 11884
} | class ____(_TestIDCTBase):
def setup_method(self):
self.rdt = int
self.dec = 5
self.type = 2
| TestIDCTIIInt |
python | walkccc__LeetCode | solutions/244. Shortest Word Distance II/244.py | {
"start": 0,
"end": 575
} | class ____:
def __init__(self, wordsDict: list[str]):
self.wordToIndices = collections.defaultdict(list)
for i, word in enumerate(wordsDict):
self.wordToIndices[word].append(i)
def shortest(self, word1: str, word2: str) -> int:
indices1 = self.wordToIndices[word1]
indices2 = self.wordToIndice... | WordDistance |
python | PyCQA__pylint | tests/functional/u/useless/useless_parent_delegation.py | {
"start": 13521,
"end": 13710
} | class ____(NotUselessSuperPy3):
def not_passing_keyword_only(self, first, *, second="second"):
return super().not_passing_keyword_only(first, second=second)
| AlsoNotUselessSuperPy3 |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/streams/streams.py | {
"start": 12454,
"end": 12558
} | class ____(AdsInsights):
breakdowns = []
action_breakdowns = ["action_type"]
| AdsInsightsActionType |
python | django__django | tests/admin_inlines/models.py | {
"start": 1908,
"end": 1972
} | class ____(models.Model):
dummy = models.IntegerField()
| Holder |
python | huggingface__transformers | src/transformers/quantizers/base.py | {
"start": 3569,
"end": 17446
} | class ____(ABC):
"""
Abstract class of the HuggingFace quantizer. Supports for now quantizing HF transformers models for inference and/or quantization.
This class is used only for transformers.PreTrainedModel.from_pretrained and cannot be easily used outside the scope of that method
yet.
Attributes... | HfQuantizer |
python | python__mypy | mypy/stubutil.py | {
"start": 7715,
"end": 11718
} | class ____(TypeStrVisitor):
"""Visitor used to print existing annotations in a file.
The main difference from TypeStrVisitor is a better treatment of
unbound types.
Notes:
* This visitor doesn't add imports necessary for annotations, this is done separately
by ImportTracker.
* It can pri... | AnnotationPrinter |
python | apache__airflow | providers/fab/tests/unit/fab/www/test_auth.py | {
"start": 4908,
"end": 6685
} | class ____:
def setup_method(self):
mock_call.reset_mock()
def method_test(self, _view, arg):
mock_call()
return True
@patch("airflow.providers.fab.www.auth.get_auth_manager")
def test_has_access_with_details_when_authorized(
self, mock_get_auth_manager, decorator_name,... | TestHasAccessWithDetails |
python | networkx__networkx | networkx/algorithms/tests/test_cluster.py | {
"start": 4673,
"end": 6314
} | class ____:
def test_clustering(self):
G = nx.DiGraph()
assert list(nx.clustering(G).values()) == []
assert nx.clustering(G) == {}
def test_path(self):
G = nx.path_graph(10, create_using=nx.DiGraph())
assert list(nx.clustering(G).values()) == [
0,
... | TestDirectedClustering |
python | psf__black | tests/data/cases/preview_long_strings__regression.py | {
"start": 26833,
"end": 27187
} | class ____:
def foo():
some_func_call(
"xxxxxxxxxx",
"xx {xxxxxxxxxxx}/xxxxxxxxxxx.xxx xxxx.xxx && xxxxxx -x "
'"xxxx xxxxxxx xxxxxx xxxx; xxxx xxxxxx_xxxxx xxxxxx xxxx; '
"xxxx.xxxx_xxxxxx(['xxxx.xxx'], xxxx.xxxxxxx().xxxxxxxxxx)\" ",
None,
... | A |
python | google__jax | jax/_src/pallas/cost_estimate.py | {
"start": 1854,
"end": 8360
} | class ____:
avals_in: Sequence[Any]
avals_out: Sequence[Any]
def cost_estimate_jaxpr(
jaxpr: jax_core.ClosedJaxpr,
) -> pallas_core.CostEstimate:
"""Returns the cost estimate for the given Jaxpr."""
jaxpr, _ = jaxpr.jaxpr, jaxpr.consts
total_cost = CostEstimate(flops=0, transcendentals=0, bytes_accessed=... | Context |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 152238,
"end": 152831
} | class ____(ExprNode):
subexprs = []
def __init__(self, pos, type=None, cname=None):
ExprNode.__init__(self, pos, type=type)
if cname is not None:
self.cname = cname
def analyse_types(self, env):
return self
def set_cname(self, cname):
self.cname = cname
... | RawCNameExprNode |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-salesforce/unit_tests/integration/test_source.py | {
"start": 1046,
"end": 5944
} | class ____(TestCase):
def setUp(self) -> None:
self._config = ConfigBuilder().client_id(_CLIENT_ID).client_secret(_CLIENT_SECRET).refresh_token(_REFRESH_TOKEN).build()
self._source = SourceSalesforce(
CatalogBuilder().with_stream(_STREAM_NAME, SyncMode.full_refresh).build(), self._config... | StreamGenerationTest |
python | pydata__xarray | asv_bench/benchmarks/indexing.py | {
"start": 5252,
"end": 5616
} | class ____:
# https://github.com/pydata/xarray/issues/2227
def setup(self):
self.ds = xr.Dataset(
{"a": ("time", np.arange(10_000_000))},
coords={"time": np.arange(10_000_000)},
)
self.time_filter = self.ds.time > 50_000
def time_indexing(self):
self.... | BooleanIndexing |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 444295,
"end": 444833
} | class ____(DictNode):
# CyFunction's __kwdefaults__ dict
def __init__(self, pos, defaults, defaults_struct):
items = []
for arg in defaults:
name = IdentifierStringNode(arg.pos, value=arg.name)
if not arg.default.is_literal:
arg = DefaultNonLiteralArgNode... | DefaultsKwDictNode |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_memorystore.py | {
"start": 5209,
"end": 6421
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.cloud_memorystore.CloudMemorystoreHook")
def test_assert_valid_hook_call(self, mock_hook):
task = CloudMemorystoreExportInstanceOperator(
task_id=TEST_TASK_ID,
location=TEST_LOCATION,
instance=TEST_INST... | TestCloudMemorystoreExportInstanceOperator |
python | django__django | django/contrib/contenttypes/management/__init__.py | {
"start": 134,
"end": 4665
} | class ____(migrations.RunPython):
def __init__(self, app_label, old_model, new_model):
self.app_label = app_label
self.old_model = old_model
self.new_model = new_model
super().__init__(self.rename_forward, self.rename_backward)
def _rename(self, apps, schema_editor, old_model, n... | RenameContentType |
python | huggingface__transformers | src/transformers/models/deepseek_v3/modeling_deepseek_v3.py | {
"start": 24235,
"end": 25268
} | class ____(PreTrainedModel):
config: DeepseekV3Config
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["DeepseekV3DecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn ... | DeepseekV3PreTrainedModel |
python | lazyprogrammer__machine_learning_examples | unsupervised_class3/dcgan_tf.py | {
"start": 3672,
"end": 4543
} | class ____(object):
def __init__(self, name, M1, M2, apply_batch_norm, f=tf.nn.relu):
self.W = tf.get_variable(
"W_%s" % name,
shape=(M1, M2),
initializer=tf.random_normal_initializer(stddev=0.02),
)
self.b = tf.get_variable(
"b_%s" % name,
shape=(M2,),
initializer=tf.z... | DenseLayer |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 67746,
"end": 71873
} | class ____(CStructOrUnionDefNode, BlockNode):
# name string
# cname string or None
# visibility "extern"
# in_pxd boolean
# attributes [CVarDefNode] or None
# entry Entry
# base_classes [CBaseTypeNode]
# templates [(string, bool)] or No... | CppClassNode |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 31022,
"end": 31201
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("ALPHABETICAL", "TAG_COMMIT_DATE")
| RefOrderField |
python | RaRe-Technologies__gensim | gensim/models/rpmodel.py | {
"start": 1362,
"end": 6020
} | class ____(interfaces.TransformationABC):
def __init__(self, corpus, id2word=None, num_topics=300):
"""
Parameters
----------
corpus : iterable of iterable of (int, int)
Input corpus.
id2word : {dict of (int, str), :class:`~gensim.corpora.dictionary.Dictionary`... | RpModel |
python | celery__celery | t/smoke/tests/quorum_queues/test_quorum_queues.py | {
"start": 1035,
"end": 1669
} | class ____:
def test_signature(self, celery_setup: CeleryTestSetup):
sig = identity.si("test_signature").set(queue=celery_setup.worker.worker_queue)
assert sig.delay().get(timeout=RESULT_TIMEOUT) == "test_signature"
def test_group(self, celery_setup: CeleryTestSetup):
sig = group(
... | test_quorum_queues |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 16974,
"end": 17794
} | class ____(VOTableChangeWarning):
"""
In order to name the columns of the Numpy record array, each
``FIELD`` element must have either an ``ID`` or ``name`` attribute
to derive a name from. Strictly speaking, according to the
VOTable schema, the ``name`` attribute is required. However, if
``nam... | W12 |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/strategies/_internal/random.py | {
"start": 4394,
"end": 11767
} | class ____(HypothesisRandom):
VERSION = 10**6
def __init__(self, *, note_method_calls: bool, data: ConjectureData) -> None:
super().__init__(note_method_calls=note_method_calls)
self.__data = data
self.__state = RandomState()
def __repr__(self) -> str:
return "HypothesisRan... | ArtificialRandom |
python | automl__auto-sklearn | autosklearn/metalearning/metafeatures/metafeature.py | {
"start": 1113,
"end": 1258
} | class ____(AbstractMetaFeature):
def __init__(self):
super(MetaFeature, self).__init__()
self.type_ = "METAFEATURE"
| MetaFeature |
python | openai__openai-python | src/openai/types/beta/chatkit/chatkit_thread.py | {
"start": 700,
"end": 1058
} | class ____(BaseModel):
reason: Optional[str] = None
"""Reason that the thread was closed. Defaults to null when no reason is recorded."""
type: Literal["closed"]
"""Status discriminator that is always `closed`."""
Status: TypeAlias = Annotated[Union[StatusActive, StatusLocked, StatusClosed], Property... | StatusClosed |
python | ray-project__ray | python/ray/tune/tests/execution/test_controller_callback_integration.py | {
"start": 721,
"end": 2142
} | class ____(Callback):
CKPT_FILE_TMPL = "test-callback-state-{}.json"
def __init__(self):
self.counter = 0
def on_trial_result(self, iteration, trials, trial, result, **info):
self.counter += 1
def get_state(self) -> Optional[Dict]:
return {"counter": self.counter}
def set... | StatefulCallback |
python | python-poetry__poetry | tests/installation/test_installer.py | {
"start": 1759,
"end": 1958
} | class ____(InstalledRepository):
@classmethod
def load(
cls, env: Env, with_dependencies: bool = False
) -> CustomInstalledRepository:
return cls()
| CustomInstalledRepository |
python | readthedocs__readthedocs.org | readthedocs/payments/tests/test_utils.py | {
"start": 174,
"end": 723
} | class ____(PaymentMixin, TestCase):
@requests_mock.Mocker(kw="mock_request")
def test_cancel_subscription(self, mock_request):
subscription_id = "sub_1234567890"
delete_request = mock_request.delete(
f"https://api.stripe.com/v1/subscriptions/{subscription_id}",
json={
... | TestUtils |
python | donnemartin__interactive-coding-challenges | graphs_trees/graph_path_exists/test_path_exists.py | {
"start": 18,
"end": 843
} | class ____(unittest.TestCase):
def test_path_exists(self):
nodes = []
graph = GraphPathExists()
for id in range(0, 6):
nodes.append(graph.add_node(id))
graph.add_edge(0, 1, 5)
graph.add_edge(0, 4, 3)
graph.add_edge(0, 5, 2)
graph.add_edge(1, 3, 5)... | TestPathExists |
python | huggingface__transformers | tests/models/qwen2/test_modeling_qwen2.py | {
"start": 2002,
"end": 54148
} | class ____(unittest.TestCase):
@slow
def test_model_450m_logits(self):
input_ids = [1, 306, 4658, 278, 6593, 310, 2834, 338]
model = Qwen2ForCausalLM.from_pretrained("Qwen/Qwen2-0.5B", device_map="auto")
input_ids = torch.tensor([input_ids]).to(model.model.embed_tokens.weight.device)
... | Qwen2IntegrationTest |
python | ray-project__ray | python/ray/_private/test_utils.py | {
"start": 36955,
"end": 45459
} | class ____(_QueueActor):
async def get_batch(self, batch_size=None, total_timeout=None, first_timeout=None):
start = timeit.default_timer()
try:
first = await asyncio.wait_for(self.queue.get(), first_timeout)
batch = [first]
if total_timeout:
end =... | _BatchQueueActor |
python | scipy__scipy | scipy/special/tests/test_basic.py | {
"start": 165832,
"end": 167290
} | class ____:
def test_laguerre(self):
lag0 = special.laguerre(0)
lag1 = special.laguerre(1)
lag2 = special.laguerre(2)
lag3 = special.laguerre(3)
lag4 = special.laguerre(4)
lag5 = special.laguerre(5)
assert_allclose(lag0.c, [1], atol=1.5e-13, rtol=0)
as... | TestLaguerre |
python | plotly__plotly.py | plotly/graph_objs/volume/_stream.py | {
"start": 233,
"end": 3494
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "volume"
_path_str = "volume.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, ... | Stream |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/key_binding/key_processor.py | {
"start": 944,
"end": 1935
} | class ____:
"""
:param key: A `Keys` instance or text (one character).
:param data: The received string on stdin. (Often vt100 escape codes.)
"""
def __init__(self, key: Keys | str, data: str | None = None) -> None:
assert isinstance(key, Keys) or len(key) == 1
if data is None:
... | KeyPress |
python | pyca__cryptography | tests/hazmat/primitives/test_hash_vectors.py | {
"start": 3341,
"end": 3706
} | class ____:
test_b2b = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "blake2"),
["blake2b.txt"],
hashes.BLAKE2b(digest_size=64),
)
@pytest.mark.supported(
only_if=lambda backend: backend.hash_supported(
hashes.BLAKE2s(digest_size=32)
),
skip_... | TestBLAKE2b |
python | ijl__orjson | test/test_dataclass.py | {
"start": 852,
"end": 1014
} | class ____:
__slots__ = ("_c", "a", "b", "d")
a: str
b: int
_c: str
d: InitVar[str]
cls_var: ClassVar[str] = "cls"
@dataclass
| Slotsdataclass |
python | cloudpipe__cloudpickle | cloudpickle/cloudpickle.py | {
"start": 19484,
"end": 43984
} | class ____:
"""Sentinel for empty closures."""
@classmethod
def __reduce__(cls):
return cls.__name__
def _make_function(code, globals, name, argdefs, closure):
# Setting __builtins__ in globals is needed for nogil CPython.
globals["__builtins__"] = __builtins__
return types.FunctionTy... | _empty_cell_value |
python | django__django | tests/custom_managers/models.py | {
"start": 5146,
"end": 5381
} | class ____(models.Model):
name = models.CharField(max_length=10)
mileage = models.IntegerField()
top_speed = models.IntegerField(help_text="In miles per hour.")
cars = models.Manager()
fast_cars = FastCarManager()
| Car |
python | getsentry__sentry | src/sentry/integrations/api/serializers/rest_framework/data_forwarder.py | {
"start": 876,
"end": 1170
} | class ____(TypedDict, total=False):
instance_url: str
index: str
source: str
token: str
SQS_REQUIRED_KEYS = ["queue_url", "region", "access_key", "secret_key"]
SEGMENT_REQUIRED_KEYS = ["write_key"]
SPLUNK_REQUIRED_KEYS = ["instance_url", "index", "source", "token"]
| SplunkConfig |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 258981,
"end": 264378
} | class ____(
ValueChannelMixin, core.ValueDefWithConditionMarkPropFieldOrDatumDefnumber
):
"""
FillOpacityValue schema wrapper.
Parameters
----------
condition : dict, :class:`ConditionalValueDefnumberExprRef`, :class:`ConditionalMarkPropFieldOrDatumDef`, :class:`ConditionalParameterValueDefnumb... | FillOpacityValue |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-siliconflow/tests/test_embeddings_siliconflow.py | {
"start": 253,
"end": 3936
} | class ____:
def __init__(self, json_data) -> None:
self._json_data = json_data
def raise_for_status(self) -> None: ...
async def __aenter__(self) -> "MockAsyncResponse":
return self
async def __aexit__(
self,
exc_type: Optional[Type[BaseException]],
exc: Option... | MockAsyncResponse |
python | pypa__setuptools | setuptools/wheel.py | {
"start": 2398,
"end": 9532
} | class ____:
def __init__(self, filename) -> None:
match = WHEEL_NAME(os.path.basename(filename))
if match is None:
raise ValueError(f'invalid wheel name: {filename!r}')
self.filename = filename
for k, v in match.groupdict().items():
setattr(self, k, v)
de... | Wheel |
python | Netflix__metaflow | metaflow/_vendor/click/formatting.py | {
"start": 2817,
"end": 9281
} | class ____(object):
"""This class helps with formatting text-based help pages. It's
usually just needed for very special internal cases, but it's also
exposed so that developers can write their own fancy outputs.
At present, it always writes into memory.
:param indent_increment: the additional in... | HelpFormatter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.