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 | django__django | tests/template_tests/filter_tests/test_dictsort.py | {
"start": 309,
"end": 4167
} | class ____(SimpleTestCase):
def test_property_resolver(self):
user = User()
dict_data = {
"a": {
"b1": {"c": "result1"},
"b2": user,
"b3": {"0": "result2"},
"b4": [0, 1, 2],
}
}
list_data = ["a", ... | FunctionTests |
python | getsentry__sentry | tests/sentry/issues/endpoints/test_group_details.py | {
"start": 11910,
"end": 29988
} | class ____(APITestCase):
def test_resolve(self) -> None:
self.login_as(user=self.user)
group = self.create_group()
url = f"/api/0/issues/{group.id}/"
response = self.client.put(url, data={"status": "resolved"}, format="json")
assert response.status_code == 200, response.co... | GroupUpdateTest |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 16512,
"end": 16667
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("AAD",)
| OIDCProviderType |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_numeric.py | {
"start": 94417,
"end": 97120
} | class ____(TestCase):
# expected shape indexed by (axis, start) for array of
# shape (1, 2, 3, 4)
tgtshape = {
(0, 0): (1, 2, 3, 4),
(0, 1): (1, 2, 3, 4),
(0, 2): (2, 1, 3, 4),
(0, 3): (2, 3, 1, 4),
(0, 4): (2, 3, 4, 1),
(1, 0): (2, 1, 3, 4),
(1, 1): (... | TestRollaxis |
python | huggingface__transformers | src/transformers/models/glm4v_moe/modeling_glm4v_moe.py | {
"start": 4154,
"end": 14522
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: Glm4vMoeTextConfig, device=None, layer_type=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_em... | Glm4vMoeTextRotaryEmbedding |
python | scipy__scipy | scipy/sparse/_dia.py | {
"start": 19308,
"end": 21466
} | class ____(_dia_base, sparray):
"""
Sparse array with DIAgonal storage.
This can be instantiated in several ways:
dia_array(D)
where D is a 2-D ndarray
dia_array(S)
with another sparse array or matrix S (equivalent to S.todia())
dia_array((M, N), [dtype])
... | dia_array |
python | walkccc__LeetCode | solutions/1325. Delete Leaves With a Given Value/1325.py | {
"start": 0,
"end": 440
} | class ____:
def removeLeafNodes(
self,
root: TreeNode | None,
target: int,
) -> TreeNode | None:
if not root:
return None
root.left = self.removeLeafNodes(root.left, target)
root.right = self.removeLeafNodes(root.right, target)
return None if self._isLeaf(root) and root.val =... | Solution |
python | pytorch__pytorch | test/torch_np/numpy_tests/linalg/test_linalg.py | {
"start": 77369,
"end": 78144
} | class ____(TestCase):
@parametrize(
"a, axes",
[
(np.ones((4, 6, 8, 2)), None),
(np.ones((3, 3, 2)), (0, 2)),
],
)
def test_non_square_handling(self, a, axes):
with assert_raises((LinAlgError, RuntimeError)):
b = np.ones(a.shape[:2])
... | TestTensorsolve |
python | crytic__slither | slither/detectors/variables/could_be_immutable.py | {
"start": 370,
"end": 2037
} | class ____(AbstractDetector):
"""
State variables that could be declared immutable.
# Immutable attribute available in Solidity 0.6.5 and above
# https://blog.soliditylang.org/2020/04/06/solidity-0.6.5-release-announcement/
"""
# VULNERABLE_SOLC_VERSIONS =
ARGUMENT = "immutable-states"
... | CouldBeImmutable |
python | rapidsai__cudf | python/cudf/cudf/core/dtypes.py | {
"start": 18492,
"end": 26288
} | class ____(_BaseDtype):
"""
Type to represent a struct data.
Parameters
----------
fields : dict
A mapping of field names to dtypes, the dtypes can themselves
be of ``StructDtype`` too.
Attributes
----------
fields
itemsize
Methods
-------
from_arrow
... | StructDtype |
python | scipy__scipy | scipy/interpolate/tests/test_interpolate.py | {
"start": 47061,
"end": 52478
} | class ____:
# test basic functionality for PPoly and BPoly
def test_sort_check(self, xp):
c = xp.asarray([[1, 4], [2, 5], [3, 6]])
x = xp.asarray([0, 1, 0.5])
assert_raises(ValueError, PPoly, c, x)
assert_raises(ValueError, BPoly, c, x)
def test_ctor_c(self):
# wrong... | TestPPolyCommon |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/metaclass3.py | {
"start": 149,
"end": 190
} | class ____(metaclass=Meta1):
pass
| Base1 |
python | davidhalter__jedi | test/completion/decorators.py | {
"start": 1152,
"end": 1504
} | class ____(object):
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
return self.func(1, *args, **kwargs)
@Decorator
def nothing(a,b,c):
return a,b,c
#? int()
nothing("")[0]
#? str()
nothing("")[1]
@same_func
@Decorator
def nothing(a,b,c):
return a,b,c... | Decorator |
python | kamyu104__LeetCode-Solutions | Python/check-if-a-string-can-break-another-string.py | {
"start": 1001,
"end": 1323
} | class ____(object):
def checkIfCanBreak(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
s1, s2 = sorted(s1), sorted(s2)
return all(a >= b for a, b in itertools.izip(s1, s2)) or \
all(a <= b for a, b in itertools.izip(s1, s2))
| Solution3 |
python | encode__django-rest-framework | tests/test_lazy_hyperlinks.py | {
"start": 290,
"end": 469
} | class ____(models.Model):
text = models.CharField(max_length=100)
def __str__(self):
global str_called
str_called = True
return 'An example'
| Example |
python | matplotlib__matplotlib | lib/matplotlib/patches.py | {
"start": 156093,
"end": 166013
} | class ____(FancyArrowPatch):
"""A patch that connects two points (possibly in different Axes)."""
def __str__(self):
return "ConnectionPatch((%g, %g), (%g, %g))" % \
(self.xy1[0], self.xy1[1], self.xy2[0], self.xy2[1])
@_docstring.interpd
def __init__(self, xyA, xyB, coordsA, co... | ConnectionPatch |
python | scrapy__scrapy | tests/test_downloader_handler_twisted_http2.py | {
"start": 7158,
"end": 7252
} | class ____(H2DownloadHandlerMixin, TestHttpsCustomCiphersBase):
pass
| TestHttps2CustomCiphers |
python | Pylons__pyramid | docs/quick_tutorial/routing/tutorial/views.py | {
"start": 105,
"end": 454
} | class ____:
def __init__(self, request):
self.request = request
@view_config(route_name='home')
def home(self):
first = self.request.matchdict['first']
last = self.request.matchdict['last']
return {
'name': 'Home View',
'first': first,
'la... | TutorialViews |
python | numpy__numpy | numpy/_core/tests/test_unicode.py | {
"start": 6084,
"end": 8098
} | class ____:
"""Check the assignment of unicode arrays with values"""
def content_check(self, ua, ua_scalar, nbytes):
# Check the length of the unicode base type
assert_(int(ua.dtype.str[2:]) == self.ulen)
# Check the length of the data buffer
assert_(buffer_length(ua) == nbytes... | AssignValues |
python | huggingface__transformers | src/transformers/models/whisper/tokenization_whisper.py | {
"start": 3883,
"end": 59613
} | class ____(TokenizersBackend):
"""
Construct a "fast" Whisper tokenizer (backed by HuggingFace's *tokenizers* library).
This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
refer to this superclass for more information regarding those methods.
... | WhisperTokenizer |
python | google__pytype | pytype/tests/test_pyi2.py | {
"start": 109,
"end": 4097
} | class ____(test_base.BaseTest):
"""Tests for PYI."""
def test_unnecessary_any_import(self):
ty = self.Infer("""
import typing
def foo(**kwargs: typing.Any) -> int: return 1
def bar(*args: typing.Any) -> int: return 2
""")
self.assertTypesMatchPytd(
ty,
"""
... | PYITest |
python | tensorflow__tensorflow | tensorflow/python/distribute/values_test.py | {
"start": 2633,
"end": 11386
} | class ____(test.TestCase, parameterized.TestCase):
@combinations.generate(
combinations.combine(
distribution=(strategy_combinations.all_strategies_minus_default +
strategy_combinations.multiworker_strategies),
mode=["eager"]
))
def testMakeDistributedValueFr... | DistributedValuesTest |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_clustered01.py | {
"start": 315,
"end": 2199
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_clustered01.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self... | TestCompareXLSXFiles |
python | pytorch__pytorch | torchgen/api/types/types_base.py | {
"start": 5731,
"end": 7137
} | class ____:
name: str
nctype: NamedCType
argument: Argument | TensorOptionsArguments | SelfArgument
# TODO: maybe don't represent default here
default: str | None = None
def rename(self, name: str) -> Binding:
return Binding(
name=name,
nctype=self.nctype,
... | Binding |
python | django__django | tests/apps/two_configs_one_default_app/apps.py | {
"start": 36,
"end": 131
} | class ____(AppConfig):
default = True
name = "apps.two_configs_one_default_app"
| TwoConfig |
python | langchain-ai__langchain | libs/core/tests/unit_tests/test_tools.py | {
"start": 47298,
"end": 84475
} | class ____(BaseTool):
name: str = "foo"
description: str = "foo."
args_schema: type[BaseModel] = fooSchema
@override
def _run(self, x: int, y: str) -> Any:
return y
@tool("foo", args_schema=fooSchema)
def injected_tool_with_schema(x: int, y: str) -> str:
return y
@pytest.mark.parame... | InjectedToolWithSchema |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_slots/SLOT001.py | {
"start": 216,
"end": 302
} | class ____(Tuple[str, int, float]): # OK
__slots__ = ("foo",)
import builtins
| Good |
python | doocs__leetcode | solution/0000-0099/0090.Subsets II/Solution2.py | {
"start": 0,
"end": 537
} | class ____:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
nums.sort()
n = len(nums)
ans = []
for mask in range(1 << n):
ok = True
t = []
for i in range(n):
if mask >> i & 1:
if i and (mask >> (i -... | Solution |
python | openai__openai-python | src/openai/resources/containers/files/files.py | {
"start": 18476,
"end": 19111
} | class ____:
def __init__(self, files: Files) -> None:
self._files = files
self.create = _legacy_response.to_raw_response_wrapper(
files.create,
)
self.retrieve = _legacy_response.to_raw_response_wrapper(
files.retrieve,
)
self.list = _legacy_r... | FilesWithRawResponse |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_function_base.py | {
"start": 66218,
"end": 66749
} | class ____(TestCase):
def test_simple(self):
x = np.array([4, 3, 2, 1, 1, 2, 3, 4, 0])
assert_(np.all(unique(x) == [0, 1, 2, 3, 4]))
assert_(unique(np.array([1, 1, 1, 1, 1])) == np.array([1]))
@xpassIfTorchDynamo_np # (reason="unique not implemented for 'ComplexDouble'")
def test_... | TestUnique |
python | pytorch__pytorch | torch/serialization.py | {
"start": 5953,
"end": 9455
} | class ____:
"""
Context manager or function to set default mmap options for :func:`torch.load` with ``mmap=True`` to flags.
For now, only either ``mmap.MAP_PRIVATE`` or ``mmap.MAP_SHARED`` are supported.
Please open an issue if you need any other option to be added here.
.. note::
This fea... | set_default_mmap_options |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_iso_languages.py | {
"start": 871,
"end": 1873
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_iso_languages"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pan... | ColumnValuesToBeIsoLanguages |
python | bokeh__bokeh | src/bokeh/events.py | {
"start": 14657,
"end": 15039
} | class ____(PointEvent):
''' Announce a tap or click event on a Bokeh plot.
Attributes:
sx (float) : x-coordinate of the event in *screen* space
sy (float) : y-coordinate of the event in *screen* space
x (float) : x-coordinate of the event in *data* space
y (float) : y-coordinate... | Tap |
python | jazzband__django-oauth-toolkit | tests/test_rest_framework.py | {
"start": 1471,
"end": 1617
} | class ____(OAuth2View):
permission_classes = [permissions.IsAuthenticated, TokenHasScope]
required_scopes = ["scope1", "another"]
| ScopedView |
python | kamyu104__LeetCode-Solutions | Python/transpose-matrix.py | {
"start": 34,
"end": 406
} | class ____(object):
def transpose(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
result = [[None] * len(A) for _ in xrange(len(A[0]))]
for r, row in enumerate(A):
for c, val in enumerate(row):
result[c][r] = val
... | Solution |
python | pyqtgraph__pyqtgraph | pyqtgraph/flowchart/Flowchart.py | {
"start": 691,
"end": 21603
} | class ____(Node):
sigFileLoaded = QtCore.Signal(object)
sigFileSaved = QtCore.Signal(object)
#sigOutputChanged = QtCore.Signal() ## inherited from Node
sigChartLoaded = QtCore.Signal()
sigStateChanged = QtCore.Signal() # called when output is expected to have changed
sigChartChanged =... | Flowchart |
python | sqlalchemy__sqlalchemy | test/engine/test_pool.py | {
"start": 64761,
"end": 67319
} | class ____(PoolTestBase):
@testing.requires.threading_with_mock
def test_cleanup(self):
self._test_cleanup(False)
# TODO: the SingletonThreadPool cleanup method
# has an unfixed race condition within the "cleanup" system that
# leads to this test being off by one connection under load... | SingletonThreadPoolTest |
python | mlflow__mlflow | mlflow/server/handlers.py | {
"start": 8352,
"end": 149799
} | class ____(ModelRegistryStoreRegistry):
def __init__(self):
super().__init__()
self.register("", self._get_file_store)
self.register("file", self._get_file_store)
for scheme in DATABASE_ENGINES:
self.register(scheme, self._get_sqlalchemy_store)
# Add support for D... | ModelRegistryStoreRegistryWrapper |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_shape_base_.py | {
"start": 27321,
"end": 28189
} | class ____(TestCase):
def test_basic(self):
d = np.ones((50, 60))
d2 = np.ones((30, 60, 6))
assert_(np.may_share_memory(d, d))
assert_(np.may_share_memory(d, d[::-1]))
assert_(np.may_share_memory(d, d[::2]))
assert_(np.may_share_memory(d, d[1:, ::-1]))
assert... | TestMayShareMemory |
python | doocs__leetcode | lcof/面试题07. 重建二叉树/Solution.py | {
"start": 164,
"end": 642
} | class ____:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
def dfs(i, j, n):
if n < 1:
return None
root = TreeNode(preorder[i])
k = d[preorder[i]]
l = k - j
root.left = dfs(i + 1, j, l)
root.ri... | Solution |
python | joke2k__faker | faker/providers/lorem/fil_PH/__init__.py | {
"start": 68,
"end": 11351
} | class ____(LoremProvider):
"""Implement lorem provider for ``fil_PH`` locale.
Word list is based on the source(s) below with some filtering,
de-conjugating, and additional common words.
Sources:
- https://1000mostcommonwords.com/1000-most-common-filipino-words/
"""
word_list = (
... | Provider |
python | ansible__ansible | lib/ansible/vars/hostvars.py | {
"start": 1147,
"end": 3090
} | class ____(c.Mapping):
"""A read-only wrapper to enable on-demand templating of a specific host's variables under that host's variable context."""
def __init__(self, inventory: InventoryManager, variable_manager: VariableManager, loader: DataLoader) -> None:
self._inventory = inventory
self._loa... | HostVars |
python | walkccc__LeetCode | solutions/3414. Maximum Score of Non-overlapping Intervals/3414.py | {
"start": 60,
"end": 177
} | class ____:
weight: int
selected: tuple[int]
def __iter__(self):
yield self.weight
yield self.selected
| T |
python | encode__django-rest-framework | tests/test_serializer_bulk_update.py | {
"start": 140,
"end": 3802
} | class ____(TestCase):
"""
Creating multiple instances using serializers.
"""
def setUp(self):
class BookSerializer(serializers.Serializer):
id = serializers.IntegerField()
title = serializers.CharField(max_length=100)
author = serializers.CharField(max_length... | BulkCreateSerializerTests |
python | google__pytype | pytype/abstract/abstract_test.py | {
"start": 42317,
"end": 48689
} | class ____(AbstractTestBase):
def test_interpreter_class_official_name(self):
cls = abstract.InterpreterClass("X", [], {}, None, None, (), self._ctx)
cls.update_official_name("Z")
self.assertEqual(cls.official_name, "Z")
cls.update_official_name("A") # takes effect because A < Z
self.assertEqual... | AbstractTest |
python | bokeh__bokeh | tests/unit/bokeh/embed/test_util__embed.py | {
"start": 25181,
"end": 28449
} | class ____:
def test_is_tex_string(self) -> None:
assert beu.is_tex_string("$$test$$") is True
assert beu.is_tex_string("$$test$$ ") is False
assert beu.is_tex_string(" $$test$$") is False
assert beu.is_tex_string(" $$test$$ ") is False
assert beu.is_tex_string("\\[test\\... | Test__tex_helpers |
python | astropy__astropy | astropy/utils/iers/iers.py | {
"start": 25039,
"end": 27974
} | class ____(IERS):
"""IERS Table class targeted to IERS B, provided by IERS itself.
These are final values; see https://www.iers.org/IERS/EN/Home/home_node.html
Notes
-----
If the package IERS B file (``iers.IERS_B_FILE``) is out of date, a new
version can be downloaded from ``iers.IERS_B_URL``... | IERS_B |
python | huggingface__transformers | src/transformers/models/mm_grounding_dino/modular_mm_grounding_dino.py | {
"start": 15215,
"end": 15519
} | class ____(GroundingDinoPreTrainedModel):
@torch.no_grad()
def _init_weights(self, module):
super()._init_weights(module)
if isinstance(module, MMGroundingDinoContrastiveEmbedding):
init.constant_(module.bias, -math.log((1 - 0.01) / 0.01))
| MMGroundingDinoPreTrainedModel |
python | pallets__click | src/click/types.py | {
"start": 19264,
"end": 20018
} | class ____(_NumberRangeBase, IntParamType):
"""Restrict an :data:`click.INT` value to a range of accepted
values. See :ref:`ranges`.
If ``min`` or ``max`` are not passed, any value is accepted in that
direction. If ``min_open`` or ``max_open`` are enabled, the
corresponding boundary is not included... | IntRange |
python | HIPS__autograd | autograd/core.py | {
"start": 859,
"end": 3663
} | class ____(Node):
__slots__ = ["parents", "vjp"]
def __init__(self, value, fun, args, kwargs, parent_argnums, parents):
self.parents = parents
try:
vjpmaker = primitive_vjps[fun]
except KeyError:
fun_name = getattr(fun, "__name__", fun)
raise NotImple... | VJPNode |
python | Netflix__metaflow | metaflow/_vendor/click/types.py | {
"start": 8472,
"end": 10304
} | class ____(IntParamType):
"""A parameter that works similar to :data:`click.INT` but restricts
the value to fit into a range. The default behavior is to fail if the
value falls outside the range, but it can also be silently clamped
between the two edges.
See :ref:`ranges` for an example.
"""
... | IntRange |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-vectorx/llama_index/vector_stores/vectorx/base.py | {
"start": 2360,
"end": 13934
} | class ____(BasePydanticVectorStore):
stores_text: bool = True
flat_metadata: bool = False
api_token: Optional[str]
encryption_key: Optional[str]
index_name: Optional[str]
space_type: Optional[str]
dimension: Optional[int]
insert_kwargs: Optional[Dict]
add_sparse_vector: bool
tex... | VectorXVectorStore |
python | fluentpython__example-code-2e | 21-async/mojifinder/bottle.py | {
"start": 73841,
"end": 76783
} | class ____(DictMixin):
""" This dict stores multiple values per key, but behaves exactly like a
normal dict in that it returns only the newest value for any given key.
There are special methods available to access the full list of values.
"""
def __init__(self, *a, **k):
self.dict =... | MultiDict |
python | pytorch__pytorch | test/dynamo/test_ctx_manager.py | {
"start": 45864,
"end": 47457
} | class ____(torch.nn.Module):
def forward(self):
_saved_tensors_hooks_disable = torch._C._autograd._saved_tensors_hooks_disable('This is not supported'); _saved_tensors_hooks_disable = None
x: "f32[1]" = torch.ones(1)
y: "f32[1]" = torch.zeros(1)
add: "f32[1]" = x + y; x = y = No... | GraphModule |
python | django__django | django/db/models/functions/mixins.py | {
"start": 133,
"end": 929
} | class ____:
def as_postgresql(self, compiler, connection, **extra_context):
# Cast FloatField to DecimalField as PostgreSQL doesn't support the
# following function signatures:
# - LOG(double, double)
# - MOD(double, double)
output_field = DecimalField(decimal_places=sys.floa... | FixDecimalInputMixin |
python | django__django | tests/admin_changelist/models.py | {
"start": 1858,
"end": 1891
} | class ____(Group):
pass
| Quartet |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-kyriba/source_kyriba/source.py | {
"start": 10435,
"end": 11775
} | class ____(AbstractSource):
def gateway_url(self, config: Mapping[str, Any]) -> str:
return f"https://{config['domain']}/gateway"
def check_connection(self, logger, config) -> Tuple[bool, any]:
try:
client = KyribaClient(config["username"], config["password"], self.gateway_url(confi... | SourceKyriba |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/remote_origin.py | {
"start": 17540,
"end": 18523
} | class ____(LegacyNamedTupleMixin):
"""Serializable representation of an ExternalJob that can be used to
uniquely it or reload it in across process boundaries.
"""
repository_origin: RemoteRepositoryOrigin
instigator_name: str
def get_selector(self) -> "InstigatorSelector":
from dagster... | RemoteInstigatorOrigin |
python | ethereum__web3.py | web3/providers/rpc/rpc.py | {
"start": 830,
"end": 6001
} | class ____(JSONBaseProvider):
logger = logging.getLogger("web3.providers.HTTPProvider")
endpoint_uri = None
_request_kwargs = None
def __init__(
self,
endpoint_uri: URI | str | None = None,
request_kwargs: Any | None = None,
session: Any | None = None,
exception_... | HTTPProvider |
python | jmcnamara__XlsxWriter | xlsxwriter/test/drawing/test_drawing_chart01.py | {
"start": 368,
"end": 3229
} | class ____(unittest.TestCase):
"""
Test assembling a complete Drawing file.
"""
def test_assemble_xml_file(self):
"""Test writing a drawing with no cell data."""
self.maxDiff = None
fh = StringIO()
drawing = Drawing()
drawing._set_filehandle(fh)
dimens... | TestAssembleDrawing |
python | run-llama__llama_index | llama-index-core/llama_index/core/llama_dataset/base.py | {
"start": 1469,
"end": 1686
} | class ____(BaseModel):
"""Base llama dataset example class."""
@property
@abstractmethod
def class_name(self) -> str:
"""Class name."""
return "BaseLlamaDataExample"
| BaseLlamaDataExample |
python | walkccc__LeetCode | solutions/769. Max Chunks To Make Sorted/769.py | {
"start": 0,
"end": 207
} | class ____:
def maxChunksToSorted(self, arr: list[int]) -> int:
ans = 0
mx = -math.inf
for i, a in enumerate(arr):
mx = max(mx, a)
if mx == i:
ans += 1
return ans
| Solution |
python | docker__docker-py | tests/unit/models_images_test.py | {
"start": 210,
"end": 4155
} | class ____(unittest.TestCase):
def test_build(self):
client = make_fake_client()
image = client.images.build()
client.api.build.assert_called_with()
client.api.inspect_image.assert_called_with(FAKE_IMAGE_ID)
assert isinstance(image, Image)
assert image.id == FAKE_IMAG... | ImageCollectionTest |
python | django__django | tests/many_to_many/models.py | {
"start": 619,
"end": 762
} | class ____(models.Manager):
def get_queryset(self):
return super().get_queryset().exclude(headline="deleted")
| NoDeletedArticleManager |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/bounding_boxes/validation_test.py | {
"start": 338,
"end": 2788
} | class ____(test_case.TestCase):
def test_densify_ragged_bounding_boxes_batched(self):
ragged_boxes = tf.ragged.constant(
[
[[0.1, 0.1, 0.2, 0.2], [0.3, 0.3, 0.4, 0.4]],
[[0.5, 0.5, 0.6, 0.6]],
],
dtype=tf.float32,
)
ragged_l... | DensifyBoundingBoxesTest |
python | huggingface__transformers | src/transformers/models/splinter/modeling_splinter.py | {
"start": 9099,
"end": 9809
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forwa... | SplinterOutput |
python | pytorch__pytorch | test/quantization/fx/test_numeric_suite_fx.py | {
"start": 3523,
"end": 3866
} | class ____(nn.Module):
def __init__(self) -> None:
super().__init__()
self.w1 = nn.Parameter(torch.empty(4, 4))
self.b1 = nn.Parameter(torch.zeros(4))
torch.nn.init.kaiming_uniform_(self.w1, a=math.sqrt(5))
def forward(self, x):
x = F.linear(x, self.w1, self.b1)
... | LinearFunctional |
python | pappasam__jedi-language-server | tests/test_data/hover/somemodule.py | {
"start": 104,
"end": 276
} | class ____:
"""Class doc string for testing."""
def some_method(self):
"""Method doc string for testing."""
def some_method2(self):
pass
| SomeClass |
python | huggingface__transformers | src/transformers/models/zoedepth/image_processing_zoedepth_fast.py | {
"start": 1526,
"end": 12149
} | class ____(BaseImageProcessorFast):
do_pad = True
do_rescale = True
do_normalize = True
image_mean = IMAGENET_STANDARD_MEAN
image_std = IMAGENET_STANDARD_STD
do_resize = True
size = {"height": 384, "width": 512}
resample = PILImageResampling.BILINEAR
keep_aspect_ratio = True
ensu... | ZoeDepthImageProcessorFast |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_cond_format06.py | {
"start": 315,
"end": 1280
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("cond_format06.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with conditional formatting."""
... | TestCompareXLSXFiles |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_cloud_run.py | {
"start": 10286,
"end": 10956
} | class ____:
@pytest.mark.asyncio
async def test_get_operation(self):
hook = CloudRunAsyncHook()
hook.get_conn = mock.AsyncMock()
await hook.get_operation(operation_name=OPERATION_NAME)
hook.get_conn.return_value.get_operation.assert_called_once_with(
operations_pb2.Ge... | TestCloudRunAsyncHook |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingTypedDict2.py | {
"start": 1380,
"end": 1436
} | class ____(TypedDict):
name: Literal["A"]
a: str
| A |
python | pytorch__pytorch | torch/_inductor/template_heuristics/cutedsl.py | {
"start": 339,
"end": 4453
} | class ____:
TILE_M: int = 128
TILE_N: int = 192
CLUSTER_M: int = 2
CLUSTER_N: int = 1
USE_2_CTA: bool = False
TENSORMAP_UPDATE_MODE: TensorMapUpdateMode = TensorMapUpdateMode.SMEM
def get_exhaustive_groupgemm_configs() -> list[CuTeGemmConfig]:
"""
Returns the exhaustive configuration s... | CuTeGemmConfig |
python | docker__docker-py | docker/types/services.py | {
"start": 19384,
"end": 19530
} | class ____:
_values = (
'none',
'on-failure',
'any',
)
NONE, ON_FAILURE, ANY = _values
| RestartConditionTypesEnum |
python | huggingface__transformers | src/transformers/models/switch_transformers/modular_switch_transformers.py | {
"start": 7865,
"end": 7932
} | class ____(T5DenseActDense):
pass
| SwitchTransformersDenseActDense |
python | matplotlib__matplotlib | lib/matplotlib/_mathtext.py | {
"start": 54188,
"end": 55615
} | class ____(Hlist):
"""
A character as close to the given height and depth as possible.
When using a font with multiple height versions of some characters (such as
the BaKoMa fonts), the correct glyph will be selected, otherwise this will
always just return a scaled version of the glyph.
"""
... | AutoHeightChar |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_optimize04.py | {
"start": 315,
"end": 1089
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("optimize04.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(
... | TestCompareXLSXFiles |
python | huggingface__transformers | src/transformers/models/got_ocr2/modeling_got_ocr2.py | {
"start": 1911,
"end": 2427
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.lin1 = nn.Linear(config.hidden_size, config.mlp_dim)
self.lin2 = nn.Linear(config.mlp_dim, config.hidden_size)
self.act = ACT2FN[config.hidden_act]
def forward(self, hidden_states: torch.Tensor) -> torch.... | GotOcr2MLPBlock |
python | celery__celery | t/unit/conftest.py | {
"start": 15985,
"end": 22727
} | class ____:
def __init__(self, monkeypatch, request):
self.monkeypatch = monkeypatch
self.request = request
def __getattr__(self, name):
return getattr(self.monkeypatch, name)
def __call__(self, path, value=SENTINEL, name=None,
new=MagicMock, **kwargs):
va... | _patching |
python | huggingface__transformers | src/transformers/models/phi4_multimodal/modular_phi4_multimodal.py | {
"start": 24624,
"end": 26895
} | class ____(SiglipPreTrainedModel):
config: Phi4MultimodalVisionConfig
base_model_prefix = "phi4_vision"
input_modalities = ("image",)
supports_gradient_checkpointing = True
_no_split_modules = ["Phi4MultimodalVisionEncoderLayer"]
_supports_flash_attn = True
_supports_sdpa = True
_suppor... | Phi4MultimodalVisionPreTrainedModel |
python | walkccc__LeetCode | solutions/925. Long Pressed Name/925.py | {
"start": 0,
"end": 267
} | class ____:
def isLongPressedName(self, name: str, typed: str) -> bool:
i = 0
for j, t in enumerate(typed):
if i < len(name) and name[i] == t:
i += 1
elif j == 0 or t != typed[j - 1]:
return False
return i == len(name)
| Solution |
python | getsentry__sentry | src/sentry/types/grouphash_metadata.py | {
"start": 4296,
"end": 4465
} | class ____(TemplateHashingMetadata, FingerprintHashingMetadata):
"""
Data from template-based bybrid fingerprinting
"""
pass
| SaltedTemplateHashingMetadata |
python | astropy__astropy | astropy/modeling/functional_models.py | {
"start": 90380,
"end": 92621
} | class ____(Fittable2DModel):
"""
Two dimensional Ricker Wavelet model (sometimes known as a "Mexican Hat"
model).
.. note::
See https://github.com/astropy/astropy/pull/9445 for discussions
related to renaming of this model.
Parameters
----------
amplitude : float
A... | RickerWavelet2D |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/engine/cursor.py | {
"start": 50232,
"end": 52567
} | class ____(CursorFetchStrategy):
"""A cursor strategy that buffers rows fully upon creation.
Used for operations where a result is to be delivered
after the database conversation can not be continued,
such as MSSQL INSERT...OUTPUT after an autocommit.
"""
__slots__ = ("_rowbuffer", "alternate... | FullyBufferedCursorFetchStrategy |
python | ansible__ansible | lib/ansible/module_utils/_internal/_patches/_socket_patch.py | {
"start": 160,
"end": 252
} | class ____(int):
"""Wrapper around `int` to test if subclasses are accepted."""
| _CustomInt |
python | dagster-io__dagster | python_modules/automation/automation_tests/dagster_docs_tests/test_exclude_lists_audit.py | {
"start": 9340,
"end": 11540
} | class ____:
"""Test that audit functions call the validator with correct parameters."""
def test_audit_missing_public_calls_validator_correctly(self):
"""Test that _audit_exclude_missing_public calls validator with correct parameters."""
mock_validator = Mock()
mock_validator.find_publi... | TestAuditFunctionsCallValidator |
python | redis__redis-py | redis/asyncio/multidb/failover.py | {
"start": 1276,
"end": 1833
} | class ____(AsyncFailoverStrategy):
"""
Failover strategy based on database weights.
"""
def __init__(self):
self._databases = WeightedList()
async def database(self) -> AsyncDatabase:
for database, _ in self._databases:
if database.circuit.state == CBState.CLOSED:
... | WeightBasedFailoverStrategy |
python | huggingface__transformers | tests/models/umt5/test_modeling_umt5.py | {
"start": 20988,
"end": 24315
} | class ____(unittest.TestCase):
@slow
@unittest.skip(
"Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged"
)
def test_small_integra... | Umt5IntegrationTest |
python | doocs__leetcode | solution/3300-3399/3381.Maximum Subarray Sum With Length Divisible by K/Solution.py | {
"start": 0,
"end": 297
} | class ____:
def maxSubarraySum(self, nums: List[int], k: int) -> int:
f = [inf] * k
ans = -inf
s = f[-1] = 0
for i, x in enumerate(nums):
s += x
ans = max(ans, s - f[i % k])
f[i % k] = min(f[i % k], s)
return ans
| Solution |
python | ansible__ansible | lib/ansible/executor/module_common.py | {
"start": 41211,
"end": 41550
} | class ____:
"""Payload required to execute an Ansible module, along with information required to do so."""
b_module_data: bytes
module_style: t.Literal['binary', 'new', 'non_native_want_json', 'old']
shebang: str | None
serialization_profile: str
@dataclasses.dataclass(kw_only=True, slots=True, fr... | _BuiltModule |
python | tensorflow__tensorflow | tensorflow/python/tpu/feature_column_v2_test.py | {
"start": 2576,
"end": 8005
} | class ____(test.TestCase, parameterized.TestCase):
def test_defaults(self):
categorical_column = fc_lib.categorical_column_with_identity(
key='aaa', num_buckets=3)
embedding_dimension = 2
embedding_column = tpu_fc.embedding_column_v2(
categorical_column, dimension=embedding_dimension)
... | EmbeddingColumnTestV2 |
python | wandb__wandb | tools/local_wandb_server.py | {
"start": 7757,
"end": 7896
} | class ____(pydantic.BaseModel):
servers: dict[str, _ServerInfo] = {}
"""Map from server names to information about them."""
| _InfoFile |
python | pytorch__pytorch | test/test_custom_ops.py | {
"start": 169603,
"end": 176476
} | class ____(TestCase):
def get_sample_op_profile(self, opname) -> dict[str, set[OpProfile]]:
return {
opname: {
OpProfile(
args_profile=(
TensorMetadata(
rank=2,
dtype=torch.float32... | TestOpProfiles |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/completion/base.py | {
"start": 10745,
"end": 11053
} | class ____(Completer):
"""
A completer that doesn't return any completion.
"""
def get_completions(
self, document: Document, complete_event: CompleteEvent
) -> Iterable[Completion]:
return []
def __repr__(self) -> str:
return "DummyCompleter()"
| DummyCompleter |
python | tensorflow__tensorflow | tensorflow/python/types/core.py | {
"start": 2318,
"end": 2581
} | class ____(Tensor):
"""Tensor that can be associated with a value (aka "eager tensor").
These objects represent the (usually future) output of executing an op
immediately.
"""
def numpy(self):
pass
@tf_export("types.experimental.FunctionType")
| Value |
python | google__flatbuffers | python/flatbuffers/builder.py | {
"start": 1695,
"end": 1837
} | class ____(RuntimeError):
"""Error caused by causing a Builder to exceed the hardcoded limit of 2
gigabytes.
"""
pass
| BuilderSizeError |
python | getsentry__sentry | src/sentry/deletions/defaults/querysubscription.py | {
"start": 133,
"end": 1138
} | class ____(ModelDeletionTask[QuerySubscription]):
def delete_instance(self, instance: QuerySubscription) -> None:
from sentry.incidents.models.incident import Incident
# Clear the foreign key as the schema was created without a cascade clause
Incident.objects.filter(subscription_id=instance... | QuerySubscriptionDeletionTask |
python | huggingface__transformers | src/transformers/models/roformer/modeling_roformer.py | {
"start": 39001,
"end": 43475
} | class ____(RoFormerPreTrainedModel, GenerationMixin):
_tied_weights_keys = {
"cls.predictions.decoder.bias": "cls.predictions.bias",
"cls.predictions.decoder.weight": "roformer.embeddings.word_embeddings.weight",
}
def __init__(self, config):
super().__init__(config)
if not... | RoFormerForCausalLM |
python | wandb__wandb | wandb/sdk/lib/wb_logging.py | {
"start": 4139,
"end": 4896
} | class ____:
"""Filters out messages logged for a different run."""
def __init__(self, run_id: str) -> None:
"""Create a _RunIDFilter.
Args:
run_id: Allows messages when the run ID is this or None.
"""
self._run_id = run_id
def filter(self, record: logging.LogRe... | _RunIDFilter |
python | getsentry__sentry | src/sentry/sentry_apps/metrics.py | {
"start": 1310,
"end": 1798
} | class ____(StrEnum):
"""Reasons why sentry app webhooks can fail"""
# Preparation fail
MISSING_SENTRY_APP = "missing_sentry_app"
MISSING_INSTALLATION = "missing_installation"
MISSING_EVENT = "missing_event"
INVALID_EVENT = "invalid_event"
MISSING_SERVICEHOOK = "missing_servicehook"
EVEN... | SentryAppWebhookFailureReason |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.