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 | joke2k__faker | faker/providers/color/az_AZ/__init__.py | {
"start": 80,
"end": 2034
} | class ____(ColorProvider):
"""Implement color provider for ``az_AZ`` locale."""
all_colors = OrderedDict(
(
("Akuamarin", "#7FFFD4"),
("Azure", "#F0FFFF"),
("Bej", "#F5F5DC"),
("Qara", "#000000"),
("Mavi", "#0000FF"),
("Mavi-bənövş... | Provider |
python | altair-viz__altair | altair/vegalite/v6/schema/_config.py | {
"start": 101999,
"end": 103011
} | class ____(TypedDict, total=False):
"""
:class:`altair.GeometryCollection` ``TypedDict`` wrapper.
Parameters
----------
geometries
type
Specifies the type of GeoJSON object.
bbox
Bounding box of the coordinate range of the object's Geometries, Features, or
Feature C... | GeometryCollectionKwds |
python | fsspec__filesystem_spec | fsspec/implementations/reference.py | {
"start": 1566,
"end": 2076
} | class ____(collections.abc.ValuesView):
def __iter__(self):
for val in self._mapping.zmetadata.values():
yield json.dumps(val).encode()
yield from self._mapping._items.values()
for field in self._mapping.listdir():
chunk_sizes = self._mapping._get_chunk_sizes(field)
... | RefsValuesView |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/sqltypes.py | {
"start": 26286,
"end": 28621
} | class ____(
_RenderISO8601NoT, HasExpressionLookup, TypeEngine[dt.datetime]
):
"""A type for ``datetime.datetime()`` objects.
Date and time types return objects from the Python ``datetime``
module. Most DBAPIs have built in support for the datetime
module, with the noted exception of SQLite. In t... | DateTime |
python | tox-dev__tox | src/tox/journal/main.py | {
"start": 190,
"end": 1404
} | class ____:
"""The result of a tox session."""
def __init__(self, enabled: bool) -> None: # noqa: FBT001
self._enabled = enabled
self._content: dict[str, Any] = {}
self._env: dict[str, EnvJournal] = {}
if self._enabled:
self._content.update(
{
... | Journal |
python | google__jax | tests/pallas/gpu_paged_attention_test.py | {
"start": 7420,
"end": 7577
} | class ____(PagedAttentionKernelTest):
INTERPRET = True
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
| PagedAttentionInterpretTest |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/tabbed_content_style_leak_test.py | {
"start": 116,
"end": 537
} | class ____(App[None]):
def compose(self) -> ComposeResult:
with TabbedContent():
with TabPane("Leak Test"):
yield Label("This label should come first")
yield Button("This button should come second")
yield Tabs("These", "Tabs", "Should", "Come", "L... | TabbedContentStyleLeakTestApp |
python | kamyu104__LeetCode-Solutions | Python/min-stack.py | {
"start": 29,
"end": 792
} | class ____(object):
def __init__(self):
self.min = None
self.stack = []
# @param x, an integer
# @return an integer
def push(self, x):
if not self.stack:
self.stack.append(0)
self.min = x
else:
self.stack.append(x - self.min)
... | MinStack |
python | huggingface__transformers | src/transformers/models/lfm2/modeling_lfm2.py | {
"start": 2263,
"end": 2984
} | class ____(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""
Lfm2RMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states):
input_d... | Lfm2RMSNorm |
python | getsentry__sentry | src/sentry/issues/endpoints/team_groups_old.py | {
"start": 621,
"end": 1772
} | class ____(TeamEndpoint):
owner = ApiOwner.ISSUES
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
def get(self, request: Request, team: Team) -> Response:
"""
Return the oldest issues owned by a team
"""
limit = min(100, int(request.GET.get("limit", 10)))
... | TeamGroupsOldEndpoint |
python | allegroai__clearml | clearml/backend_api/services/v2_20/events.py | {
"start": 88520,
"end": 89664
} | class ____(Response):
"""
Response of events.get_plot_sample endpoint.
"""
_service = "events"
_action = "get_plot_sample"
_version = "2.20"
_schema = {
"$ref": "#/definitions/plot_sample_response",
"definitions": {
"plot_sample_response": {
"pro... | GetPlotSampleResponse |
python | PyCQA__pycodestyle | testing/data/python3.py | {
"start": 211,
"end": 925
} | class ____:
# Camel-caes
cls_var: ClassVar[str]
for_var: ClassVar[str]
while_var: ClassVar[str]
def_var: ClassVar[str]
if_var: ClassVar[str]
elif_var: ClassVar[str]
else_var: ClassVar[str]
try_var: ClassVar[str]
except_var: ClassVar[str]
finally_var: ClassVar[str]
with_va... | Class |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/dataproc.py | {
"start": 4449,
"end": 5546
} | class ____(BaseOperatorLink):
"""
Helper class for constructing list of Dataproc resources link.
.. warning::
This link is deprecated.
"""
name = "Dataproc resources"
key = "list_conf"
@staticmethod
def persist(
context: Context,
url: str,
project_id: st... | DataprocListLink |
python | wandb__wandb | wandb/sdk/artifacts/_generated/registry_user_members.py | {
"start": 237,
"end": 327
} | class ____(GQLResult):
project: Optional[RegistryUserMembersProject]
| RegistryUserMembers |
python | encode__httpx | httpx/_decoders.py | {
"start": 735,
"end": 946
} | class ____:
def decode(self, data: bytes) -> bytes:
raise NotImplementedError() # pragma: no cover
def flush(self) -> bytes:
raise NotImplementedError() # pragma: no cover
| ContentDecoder |
python | facebook__pyre-check | client/commands/subscription.py | {
"start": 969,
"end": 1750
} | class ____:
kind: str
message: Optional[str] = None
def _parse_status_update_subscription(response: object) -> StatusUpdate:
if not isinstance(response, list) or len(response) == 0:
raise incremental.InvalidServerResponse(
f"Status update subscription must be a nonempty list. Got {resp... | StatusUpdate |
python | astropy__astropy | astropy/utils/exceptions.py | {
"start": 1493,
"end": 1642
} | class ____(AstropyWarning):
"""
A warning class indicating a representation name was already registered.
"""
| DuplicateRepresentationWarning |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess14.py | {
"start": 1039,
"end": 1174
} | class ____(Generic[T]):
def __init__(self, data: T) -> None: ...
@cached_slot_property("_prop")
def prop(self) -> int: ...
| C |
python | joke2k__faker | faker/providers/color/th_TH/__init__.py | {
"start": 98,
"end": 1234
} | class ____(ColorProvider):
"""Implement color provider for ``th_TH`` locale.
Sources:
- https://th.wikipedia.org/wiki/รายชื่อสี
"""
all_colors = OrderedDict(
(
("สีดำ", "#000000"),
("สีน้ำเงินเขียว", "#0095B6"),
("สีน้ำเงินม่วง", "#8A2BE2"),
... | Provider |
python | google__flatbuffers | python/flatbuffers/reflection/EnumVal.py | {
"start": 179,
"end": 4894
} | class ____(object):
__slots__ = ['_tab']
@classmethod
def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
x = EnumVal()
x.Init(buf, n + offset)
return x
@classmethod
def GetRootAsEnumVal(cls, buf, offset=0):
... | EnumVal |
python | huggingface__transformers | src/transformers/models/owlv2/configuration_owlv2.py | {
"start": 10026,
"end": 12809
} | class ____(PreTrainedConfig):
r"""
[`Owlv2Config`] is the configuration class to store the configuration of an [`Owlv2Model`]. It is used to
instantiate an OWLv2 model according to the specified arguments, defining the text model and vision model
configs. Instantiating a configuration with the defaults ... | Owlv2Config |
python | davidhalter__jedi | test/completion/classes.py | {
"start": 8018,
"end": 8127
} | class ____():
def foo(self):
return 1
# Somehow overwriting the same name caused problems (#1044)
| Foo |
python | python-openxml__python-docx | src/docx/enum/section.py | {
"start": 108,
"end": 888
} | class ____(BaseXmlEnum):
"""Alias: **WD_HEADER_FOOTER**
Specifies one of the three possible header/footer definitions for a section.
For internal use only; not part of the python-docx API.
MS API name: `WdHeaderFooterIndex`
URL: https://docs.microsoft.com/en-us/office/vba/api/word.wdheaderfooteri... | WD_HEADER_FOOTER_INDEX |
python | pytorch__pytorch | torch/package/find_file_dependencies.py | {
"start": 107,
"end": 3979
} | class ____(ast.NodeVisitor):
"""
Extract the list of global variables a block of code will read and write
"""
@classmethod
def run(cls, src: str, package: str) -> list[tuple[str, Optional[str]]]:
visitor = cls(package)
tree = ast.parse(src)
visitor.visit(tree)
return... | _ExtractModuleReferences |
python | doocs__leetcode | solution/2600-2699/2604.Minimum Time to Eat All Grains/Solution.py | {
"start": 0,
"end": 882
} | class ____:
def minimumTime(self, hens: List[int], grains: List[int]) -> int:
def check(t):
j = 0
for x in hens:
if j == m:
return True
y = grains[j]
if y <= x:
d = x - y
if d ... | Solution |
python | sqlalchemy__sqlalchemy | test/dialect/mysql/test_compiler.py | {
"start": 22927,
"end": 27992
} | class ____(
fixtures.TestBase, AssertsCompiledSQL, fixtures.CacheKeySuite
):
__dialect__ = "mysql"
@fixtures.CacheKeySuite.run_suite_tests
def test_insert_on_duplicate_key_cache_key(self):
table = Table(
"foos",
MetaData(),
Column("id", Integer, primary_key=T... | CustomExtensionTest |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/databricks_sql_datasource.py | {
"start": 2149,
"end": 2377
} | class ____(pydantic.UrlError):
"""
Custom Pydantic error for missing catalog in DatabricksDsn query.
"""
code = "url.query.catalog"
msg_template = "'catalog' query param is invalid or missing"
| _UrlCatalogError |
python | python-pillow__Pillow | src/PIL/ImageDraw.py | {
"start": 1847,
"end": 36274
} | class ____:
font: (
ImageFont.ImageFont | ImageFont.FreeTypeFont | ImageFont.TransposedFont | None
) = None
def __init__(self, im: Image.Image, mode: str | None = None) -> None:
"""
Create a drawing instance.
:param im: The image to draw in.
:param mode: Optional mo... | ImageDraw |
python | conda__conda | conda/core/package_cache_data.py | {
"start": 23293,
"end": 39985
} | class ____:
@staticmethod
def make_actions_for_record(pref_or_spec):
if pref_or_spec is None:
raise TypeError("`pref_or_spec` cannot be None.")
# returns a cache_action and extract_action
# if the pref or spec has an md5 value
# look in all caches for package cache r... | ProgressiveFetchExtract |
python | conda__conda | conda/auxlib/entity.py | {
"start": 31357,
"end": 31828
} | class ____(Entity):
def __setattr__(self, attribute, value):
if self._initd:
raise AttributeError(
f"Assignment not allowed. {self.__class__.__name__} is immutable."
)
super().__setattr__(attribute, value)
def __delattr__(self, item):
if self._in... | ImmutableEntity |
python | huggingface__transformers | examples/pytorch/image-pretraining/run_mim.py | {
"start": 4331,
"end": 7384
} | class ____:
"""
Arguments pertaining to which model/config/image processor we are going to pre-train.
"""
model_name_or_path: str = field(
default=None,
metadata={
"help": (
"The model checkpoint for weights initialization. Can be a local path to a pytorch_mo... | ModelArguments |
python | astropy__astropy | astropy/time/tests/test_corrs.py | {
"start": 324,
"end": 3040
} | class ____:
"""
Verify time offsets to the solar system barycentre and the heliocentre.
Uses the WHT observing site.
Tests are against values returned at time of initial creation of these
routines. They agree to an independent SLALIB based implementation
to 20 microseconds.
"""
@class... | TestHelioBaryCentric |
python | pytorch__pytorch | torch/distributed/checkpoint/filesystem.py | {
"start": 15562,
"end": 16521
} | class ____(ABC):
@contextmanager
@abstractmethod
def create_stream(
self, path: Union[str, os.PathLike], mode: str
) -> Generator[io.IOBase, None, None]: ...
@abstractmethod
def concat_path(
self, path: Union[str, os.PathLike], suffix: str
) -> Union[str, os.PathLike]: ...
... | FileSystemBase |
python | sqlalchemy__sqlalchemy | test/dialect/mssql/test_types.py | {
"start": 47392,
"end": 47787
} | class ____(types.TypeDecorator):
impl = PickleType
cache_ok = True
def process_bind_param(self, value, dialect):
if value:
value = pickleable.Foo(value.moredata, stuff="BIND" + value.stuff)
return value
def process_result_value(self, value, dialect):
if value:
... | MyPickleType |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/enum1.py | {
"start": 6919,
"end": 7105
} | class ____(IntEnum):
def __new__(cls, val: int, doc: str) -> Self:
obj = int.__new__(cls, val)
obj._value_ = val
obj.__doc__ = doc
return obj
| TestEnum17 |
python | pypa__setuptools | setuptools/_distutils/command/bdist.py | {
"start": 1299,
"end": 5854
} | class ____(Command):
description = "create a built (binary) distribution"
user_options = [
('bdist-base=', 'b', "temporary directory for creating built distributions"),
(
'plat-name=',
'p',
"platform name to embed in generated filenames "
f"[defau... | bdist |
python | walkccc__LeetCode | solutions/3206. Alternating Groups I/3206.py | {
"start": 0,
"end": 229
} | class ____:
def numberOfAlternatingGroups(self, colors: list[int]) -> int:
n = len(colors)
return sum(colors[i] != colors[i - 1] and
colors[i] != colors[(i + 1) % n]
for i in range(n))
| Solution |
python | getsentry__sentry | src/sentry/integrations/slack/utils/auth.py | {
"start": 588,
"end": 1067
} | class ____(TypedDict):
HTTP_X_SLACK_REQUEST_TIMESTAMP: str
HTTP_X_SLACK_SIGNATURE: str
def set_signing_secret(secret: str, data: bytes) -> SigningSecretKwargs:
"""Note: this is currently only used in tests."""
timestamp = str(int(time.mktime(datetime.utcnow().timetuple())))
signature = _encode_dat... | SigningSecretKwargs |
python | mwaskom__seaborn | tests/test_statistics.py | {
"start": 19664,
"end": 21315
} | class ____:
@pytest.fixture
def x(self, rng):
return pd.Series(rng.standard_t(10, 10_000))
def test_levels(self, x):
res = LetterValues(k_depth="tukey", outlier_prop=0, trust_alpha=0)(x)
k = res["k"]
expected = np.concatenate([np.arange(k), np.arange(k - 1)[::-1]])
... | TestLetterValues |
python | nedbat__coveragepy | tests/test_execfile.py | {
"start": 9365,
"end": 11323
} | class ____(UsingModulesMixin, CoverageTest):
"""Test run_python_module."""
run_in_temp_dir = False
def test_runmod1(self) -> None:
run_python_module(["runmod1", "hello"])
out, err = self.stdouterr()
assert out == "runmod1: passed hello\n"
assert err == ""
def test_runm... | RunModuleTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-milvus/destination_milvus/config.py | {
"start": 296,
"end": 864
} | class ____(BaseModel):
mode: Literal["username_password"] = Field("username_password", const=True)
username: str = Field(..., title="Username", description="Username for the Milvus instance", order=1)
password: str = Field(..., title="Password", description="Password for the Milvus instance", airbyte_secret... | UsernamePasswordAuth |
python | openai__openai-python | src/openai/resources/beta/realtime/realtime.py | {
"start": 21968,
"end": 22110
} | class ____:
def __init__(self, connection: RealtimeConnection) -> None:
self._connection = connection
| BaseRealtimeConnectionResource |
python | scipy__scipy | scipy/stats/tests/test_morestats.py | {
"start": 145354,
"end": 148842
} | class ____:
def test_input_validation(self, xp):
message = "`ps` must include only numbers between 0 and 1"
with pytest.raises(ValueError, match=message):
stats.false_discovery_control(xp.asarray([-1, 0.5, 0.7]))
with pytest.raises(ValueError, match=message):
stats.fa... | TestFDRControl |
python | google__jax | tests/random_lax_test.py | {
"start": 58964,
"end": 63146
} | class ____(CommonRandomTest):
def make_key(self, seed):
return random.PRNGKey(seed, impl='rbg')
def test_split_shape(self):
key = self.make_key(73)
keys = random.split(key, 10)
self.assertEqual(keys.shape, (10, *key.shape))
@jax.debug_key_reuse(False)
def test_vmap_fold_in_shape(self):
# b... | RBGPRNGTest |
python | PyCQA__pylint | tests/functional/a/assigning/assigning_non_slot.py | {
"start": 338,
"end": 370
} | class ____:
""" empty """
| Empty |
python | pytorch__pytorch | torch/cuda/__init__.py | {
"start": 57644,
"end": 57866
} | class ____(_CudaLegacyStorage):
@classproperty
def dtype(self):
_warn_typed_storage_removal()
return self._dtype
@classproperty
def _dtype(self):
return torch.bfloat16
| BFloat16Storage |
python | getsentry__sentry | src/sentry/cache/redis.py | {
"start": 2034,
"end": 2326
} | class ____(CommonRedisCache):
def __init__(self, cluster_id: str, **options: object) -> None:
client = redis_clusters.get(cluster_id)
raw_client = redis_clusters.get_binary(cluster_id)
super().__init__(client=client, raw_client=raw_client, **options)
| RedisClusterCache |
python | google__pytype | pytype/tests/test_unions.py | {
"start": 103,
"end": 2318
} | class ____(test_base.BaseTest):
"""Tests for union types."""
def test_if_else(self):
ty = self.Infer("""
def id(x):
return x
def f(b, x, y):
return id(1 if b else 1.0)
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import Any, TypeVar, Union
... | UnionTest |
python | astropy__astropy | astropy/cosmology/_src/funcs/optimize.py | {
"start": 778,
"end": 1181
} | class ____(Protocol):
"""Protocol for custom :mod:`scipy.optimize.minimize_scalar` methods.
See :mod:`scipy.optimize.minimize_scalar` for details.
"""
def __call__(
self, fun: Callable[..., Any], args: tuple[Any, ...], **kwargs: Any
) -> "scipy.optimize.OptimizeResult": ...
_BracketSingl... | _CustomSolverCallable |
python | PrefectHQ__prefect | tests/test_flows.py | {
"start": 61381,
"end": 64721
} | class ____:
async def test_user_logs_are_sent_to_orion(self, prefect_client):
@flow
def my_flow():
logger = get_run_logger()
logger.info("Hello world!")
my_flow()
await _wait_for_logs(prefect_client, expected_num_logs=3)
logs = await prefect_client.r... | TestFlowRunLogs |
python | neetcode-gh__leetcode | python/1011-capacity-to-ship-packages-within-d-days.py | {
"start": 0,
"end": 626
} | class ____:
def shipWithinDays(self, weights: List[int], days: int) -> int:
l, r = max(weights), sum(weights)
min_cap = r
def canShip(cap):
ships, curCap = 1, cap
for w in weights:
if curCap - w < 0:
ships += 1
... | Solution |
python | weaviate__weaviate-python-client | weaviate/collections/classes/grpc.py | {
"start": 5001,
"end": 5175
} | class ____(_WeaviateInput):
"""Define how the query's group-by operation should be performed."""
prop: str
objects_per_group: int
number_of_groups: int
| GroupBy |
python | scipy__scipy | scipy/linalg/tests/test_matfuncs.py | {
"start": 3106,
"end": 10458
} | class ____:
@pytest.mark.filterwarnings("ignore:.*inaccurate.*:RuntimeWarning")
def test_nils(self):
a = array([[-2., 25., 0., 0., 0., 0., 0.],
[0., -3., 10., 3., 3., 3., 0.],
[0., 0., 2., 15., 3., 3., 0.],
[0., 0., 0., 0., 15., 3., 0.],
... | TestLogM |
python | PyCQA__pylint | tests/functional/u/undefined/undefined_variable_py312.py | {
"start": 187,
"end": 280
} | class ____[T, *Ts, **P]:
def __init__(self, value: T):
self.value = value
| SomeClass |
python | astral-sh__uv | crates/uv-virtualenv/src/_virtualenv.py | {
"start": 1575,
"end": 4342
} | class ____:
"""A meta path finder that allows patching the imported distutils modules."""
fullname = None
# lock[0] is threading.Lock(), but initialized lazily to avoid importing threading very early at startup,
# because there are gevent-based applications that need to be first to import threading by... | _Finder |
python | scrapy__scrapy | tests/test_command_genspider.py | {
"start": 6880,
"end": 8771
} | class ____:
def test_generate_standalone_spider(self, tmp_path: Path) -> None:
call("genspider", "example", "example.com", cwd=tmp_path)
assert Path(tmp_path, "example.py").exists()
@pytest.mark.parametrize("force", [True, False])
def test_same_name_as_existing_file(self, force: bool, tmp_p... | TestGenspiderStandaloneCommand |
python | openai__openai-python | src/openai/resources/containers/containers.py | {
"start": 17904,
"end": 18551
} | class ____:
def __init__(self, containers: Containers) -> None:
self._containers = containers
self.create = to_streamed_response_wrapper(
containers.create,
)
self.retrieve = to_streamed_response_wrapper(
containers.retrieve,
)
self.list = to_... | ContainersWithStreamingResponse |
python | scipy__scipy | scipy/sparse/linalg/tests/test_matfuncs.py | {
"start": 21072,
"end": 22021
} | class ____:
def test_product_operator(self):
random.seed(1234)
n = 5
k = 2
nsamples = 10
for i in range(nsamples):
A = np.random.randn(n, n)
B = np.random.randn(n, n)
C = np.random.randn(n, n)
D = np.random.randn(n, k)
... | TestOperators |
python | run-llama__llama_index | llama-index-core/llama_index/core/indices/struct_store/pandas.py | {
"start": 153,
"end": 711
} | class ____:
def __init__(
self,
*args: Any,
**kwargs: Any,
) -> None:
raise DeprecationWarning(
"PandasQueryEngine has been moved to `llama-index-experimental`.\n"
"`pip install llama-index-experimental`\n"
"`from llama_index.experimental.query... | PandasIndex |
python | Lightning-AI__lightning | tests/tests_pytorch/models/test_hparams.py | {
"start": 18140,
"end": 18989
} | class ____(BoringModel):
"""This model has the save_hyperparameters() call at the end."""
def __init__(self, arg1, arg2, *args, **kwargs):
super().__init__(*args, **kwargs)
self.argument1 = arg1 # arg2 intentionally not set
arg1 = "overwritten"
local_var = 1234 # noqa: F841
... | LocalVariableModelSuperFirst |
python | doocs__leetcode | solution/3000-3099/3065.Minimum Operations to Exceed Threshold Value I/Solution.py | {
"start": 0,
"end": 117
} | class ____:
def minOperations(self, nums: List[int], k: int) -> int:
return sum(x < k for x in nums)
| Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/workbook/test_write_calc_pr.py | {
"start": 299,
"end": 2013
} | class ____(unittest.TestCase):
"""
Test the Workbook _write_calc_pr() method.
"""
def setUp(self):
self.fh = StringIO()
self.workbook = Workbook()
self.workbook._set_filehandle(self.fh)
def test_write_calc_pr(self):
"""Test the _write_calc_pr() method."""
... | TestWriteCalcPr |
python | redis__redis-py | tests/test_cache.py | {
"start": 27932,
"end": 32417
} | class ____:
@pytest.mark.parametrize(
"r",
[
{
"cache": DefaultCache(CacheConfig(max_size=128)),
"ssl": True,
},
{
"cache": DefaultCache(CacheConfig(max_size=128)),
"ssl": True,
"decod... | TestSSLCache |
python | django__django | tests/admin_scripts/tests.py | {
"start": 58980,
"end": 67392
} | class ____(SimpleTestCase):
def setUp(self):
def monkey_run(*args, **options):
return
self.output = StringIO()
self.cmd = RunserverCommand(stdout=self.output)
self.cmd.run = monkey_run
def assertServerSettings(self, addr, port, ipv6=False, raw_ipv6=False):
s... | ManageRunserver |
python | ray-project__ray | python/ray/data/aggregate.py | {
"start": 5075,
"end": 11229
} | class ____(AggregateFn, abc.ABC, Generic[AccumulatorType, AggOutputType]):
"""Provides an interface to implement efficient aggregations to be applied
to the dataset.
`AggregateFnV2` instances are passed to a Dataset's ``.aggregate(...)`` method to
perform distributed aggregations. To create a custom ag... | AggregateFnV2 |
python | mlflow__mlflow | dev/clint/src/clint/rules/mock_patch_dict_environ.py | {
"start": 84,
"end": 1482
} | class ____(Rule):
def _message(self) -> str:
return (
"Do not use `mock.patch.dict` to modify `os.environ` in tests; "
"use pytest's monkeypatch fixture (monkeypatch.setenv / monkeypatch.delenv) instead."
)
@staticmethod
def check(node: ast.Call, resolver: Resolver) ... | MockPatchDictEnviron |
python | keras-team__keras | keras/src/optimizers/schedules/learning_rate_schedule.py | {
"start": 11071,
"end": 16794
} | class ____(LearningRateSchedule):
"""A `LearningRateSchedule` that uses a polynomial decay schedule.
It is commonly observed that a monotonically decreasing learning rate, whose
degree of change is carefully chosen, results in a better performing model.
This schedule applies a polynomial decay function... | PolynomialDecay |
python | encode__django-rest-framework | rest_framework/validators.py | {
"start": 12604,
"end": 13074
} | class ____(BaseUniqueForValidator):
message = _('This field must be unique for the "{date_field}" month.')
def filter_queryset(self, attrs, queryset, field_name, date_field_name):
value = attrs[self.field]
date = attrs[self.date_field]
filter_kwargs = {}
filter_kwargs[field_nam... | UniqueForMonthValidator |
python | Netflix__metaflow | metaflow/plugins/aws/secrets_manager/aws_secrets_manager_secrets_provider.py | {
"start": 594,
"end": 753
} | class ____(MetaflowException):
"""Raised when the SecretString response from AWS Secrets Manager is not valid JSON"""
| MetaflowAWSSecretsManagerJSONParseError |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol24.py | {
"start": 1097,
"end": 1146
} | class ____:
attr1: ClassVar[int] = 1
| ConcreteG1 |
python | pytorch__pytorch | test/onnx/model_defs/word_language_model.py | {
"start": 199,
"end": 3269
} | class ____(nn.Module):
"""Container module with an encoder, a recurrent module, and a decoder."""
def __init__(
self,
rnn_type,
ntoken,
ninp,
nhid,
nlayers,
dropout=0.5,
tie_weights=False,
batchsize=2,
):
super().__init__()
... | RNNModel |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py | {
"start": 5234,
"end": 5496
} | class ____(graphene.ObjectType):
secondsToWait = graphene.Field(graphene.Int)
class Meta:
interfaces = (GrapheneMessageEvent, GrapheneStepEvent, GrapheneErrorEvent)
name = "ExecutionStepUpForRetryEvent"
| GrapheneExecutionStepUpForRetryEvent |
python | pytorch__pytorch | test/distributed/pipelining/model_registry.py | {
"start": 7858,
"end": 10311
} | class ____(torch.nn.Module):
def __init__(self, d_hid: int):
super().__init__()
self.fc1_weight = torch.nn.Parameter(torch.randn(d_hid, d_hid))
self.fc1_bias = torch.nn.Parameter(torch.randn(d_hid))
self.fc2_weight = torch.nn.Parameter(torch.randn(d_hid, d_hid))
self.fc2_bias... | MLPModuleWithDw |
python | numba__numba | numba/tests/test_dictobject.py | {
"start": 58313,
"end": 71361
} | class ____(MemoryLeakMixin, TestCase):
""" Tests for dictionaries with string keys that can map to anything!"""
def test_basic_const_lowering_boxing(self):
@njit
def foo():
ld = {'a': 1, 'b': 2j, 'c': 'd'}
return (ld['a'], ld['b'], ld['c'])
self.assertEqual(foo(... | TestLiteralStrKeyDict |
python | walkccc__LeetCode | solutions/2047. Number of Valid Words in a Sentence/2047-2.py | {
"start": 0,
"end": 230
} | class ____:
def countValidWords(self, sentence: str) -> int:
pattern = re.compile(r'^[a-z]*([a-z]-[a-z])?[a-z]*[!,.]?$')
return sum(pattern.search(token) != None for token in
sentence.strip().split())
| Solution |
python | ray-project__ray | doc/source/tune/doc_code/pytorch_optuna.py | {
"start": 1933,
"end": 3388
} | class ____(nn.Module):
def __init__(self):
super(ConvNet, self).__init__()
self.conv1 = nn.Conv2d(1, 3, kernel_size=3)
self.fc = nn.Linear(192, 10)
def forward(self, x):
x = F.relu(F.max_pool2d(self.conv1(x), 3))
x = x.view(-1, 192)
x = self.fc(x)
return ... | ConvNet |
python | numba__numba | numba/cpython/hashing.py | {
"start": 13720,
"end": 13826
} | class ____(Structure):
_fields_ = [
('prefix', c_size_t),
('suffix', c_size_t)
]
| FNV |
python | dask__distributed | distributed/http/health.py | {
"start": 62,
"end": 273
} | class ____(web.RequestHandler):
def get(self):
self.write("ok")
self.set_header("Content-Type", "text/plain; charset=utf-8")
routes: list[tuple] = [("/health", HealthHandler, {})]
| HealthHandler |
python | pytorch__pytorch | torch/cuda/graphs.py | {
"start": 1822,
"end": 7897
} | class ____(torch._C._CUDAGraph):
r"""Wrapper around a CUDA graph.
Arguments:
keep_graph (bool, optional): If ``keep_graph=False``, the
cudaGraphExec_t will be instantiated on GPU at the end of
``capture_end`` and the underlying cudaGraph_t will be
destroyed. Users wh... | CUDAGraph |
python | huggingface__transformers | src/transformers/models/align/modeling_align.py | {
"start": 31762,
"end": 33187
} | class ____(PreTrainedModel):
config: AlignConfig
base_model_prefix = "align"
input_modalities = ("image", "text")
supports_gradient_checkpointing = True
@torch.no_grad()
def _init_weights(self, module: nn.Module):
"""Initialize the weights"""
std = self.config.initializer_range
... | AlignPreTrainedModel |
python | google__jax | jax/_src/numpy/index_tricks.py | {
"start": 8735,
"end": 10034
} | class ____(_AxisConcat):
"""Concatenate slices, scalars and array-like objects along the last axis.
LAX-backend implementation of :obj:`numpy.c_`.
See Also:
``jnp.r_``: Concatenates slices, scalars and array-like objects along the first axis.
Examples:
>>> a = jnp.arange(6).reshape((2,3))
>>> jn... | CClass |
python | spack__spack | lib/spack/spack/binary_distribution.py | {
"start": 102924,
"end": 104843
} | class ____(IndexFetcher):
"""Fetcher for buildcache index, cache invalidation via manifest contents"""
def __init__(self, url_and_version: MirrorURLAndVersion, local_hash, urlopen=web_util.urlopen):
self.url = url_and_version.url
self.layout_version = url_and_version.version
self.local_... | DefaultIndexFetcher |
python | pennersr__django-allauth | allauth/socialaccount/providers/apple/views.py | {
"start": 718,
"end": 5319
} | class ____(OAuth2Adapter):
client_class = AppleOAuth2Client
provider_id = "apple"
access_token_url = "https://appleid.apple.com/auth/token" # nosec
authorize_url = "https://appleid.apple.com/auth/authorize"
public_key_url = "https://appleid.apple.com/auth/keys"
@classmethod
def get_verifie... | AppleOAuth2Adapter |
python | getsentry__sentry | src/sentry/preprod/models.py | {
"start": 13076,
"end": 17415
} | class ____(DefaultFieldsModel):
"""
Metrics about the size analysis of a pre-production artifact. Each PreprodArtifact can have 0 or many
size metrics.
"""
class MetricsArtifactType(IntEnum):
MAIN_ARTIFACT = 0
"""The main artifact."""
WATCH_ARTIFACT = 1
"""An embedde... | PreprodArtifactSizeMetrics |
python | numba__numba | numba/core/typing/npdatetime.py | {
"start": 7101,
"end": 7607
} | class ____(AbstractTemplate):
key = operator.sub
def generic(self, args, kws):
if len(args) == 1:
# Guard against unary -
return
left, right = args
if isinstance(left, types.NPDatetime) and isinstance(right,
... | DatetimeMinusDatetime |
python | getsentry__sentry | src/bitfield/types.py | {
"start": 46,
"end": 2657
} | class ____:
def __init__(self, number, is_set=True):
self.number = number
self.is_set = bool(is_set)
self.mask = 2 ** int(number)
self.children = []
if not self.is_set:
self.mask = ~self.mask
def __repr__(self) -> str:
return "<%s: number=%d, is_set=%... | Bit |
python | pennersr__django-allauth | allauth/socialaccount/providers/dummy/provider.py | {
"start": 431,
"end": 2798
} | class ____(Provider):
id = "dummy"
name = "Dummy"
account_class = DummyAccount
uses_apps = False
supports_redirect = True
supports_token_authentication = True
def get_login_url(self, request, **kwargs):
url = reverse("dummy_login")
if kwargs:
url = url + "?" + ur... | DummyProvider |
python | django__django | tests/admin_widgets/models.py | {
"start": 2166,
"end": 2615
} | class ____(models.Model):
barcode = models.PositiveIntegerField(unique=True)
parent = models.ForeignKey(
"self", models.SET_NULL, to_field="barcode", blank=True, null=True
)
name = models.CharField(blank=False, max_length=20)
hidden = models.BooleanField(default=False)
# see #9258
d... | Inventory |
python | pypa__warehouse | tests/unit/email/test_init.py | {
"start": 129322,
"end": 133306
} | class ____:
def test_collaborator_removed_email(self, db_request, pyramid_config, monkeypatch):
removed_user = UserFactory.create()
EmailFactory.create(primary=True, verified=True, public=True, user=removed_user)
submitter_user = UserFactory.create()
EmailFactory.create(
... | TestCollaboratorRemovedEmail |
python | matplotlib__matplotlib | lib/matplotlib/tests/test_ticker.py | {
"start": 48912,
"end": 55161
} | class ____:
@staticmethod
def logit_deformatter(string):
r"""
Parser to convert string as r'$\mathdefault{1.41\cdot10^{-4}}$' in
float 1.41e-4, as '0.5' or as r'$\mathdefault{\frac{1}{2}}$' in float
0.5,
"""
match = re.match(
r"[^\d]*"
r"(?... | TestLogitFormatter |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 11593,
"end": 12253
} | class ____(BaseModel):
params: "CollectionParams" = Field(..., description="")
hnsw_config: "HnswConfig" = Field(..., description="")
optimizer_config: "OptimizersConfig" = Field(..., description="")
wal_config: "WalConfig" = Field(..., description="")
quantization_config: Optional["QuantizationConf... | CollectionConfigTelemetry |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDictClosed3.py | {
"start": 794,
"end": 891
} | class ____(TypedDict, extra_items=Never):
a: int
# This should generate an error.
| ParentClosed2 |
python | huggingface__transformers | src/transformers/models/whisper/modeling_whisper.py | {
"start": 22861,
"end": 23996
} | class ____(PreTrainedModel):
config: WhisperConfig
base_model_prefix = "model"
main_input_name = "input_features"
input_modalities = ("audio", "text")
supports_gradient_checkpointing = True
_no_split_modules = ["WhisperEncoderLayer", "WhisperDecoderLayer"]
_supports_flash_attn = True
_su... | WhisperPreTrainedModel |
python | readthedocs__readthedocs.org | readthedocs/proxito/views/hosting.py | {
"start": 10235,
"end": 28254
} | class ____:
def get(
self,
addons_version,
project,
request,
version=None,
build=None,
filename=None,
url=None,
):
"""
Unique entry point to get the proper API response.
It will evaluate the ``addons_version`` passed and de... | AddonsResponseBase |
python | doocs__leetcode | solution/0100-0199/0140.Word Break II/Solution.py | {
"start": 0,
"end": 607
} | class ____:
def __init__(self):
self.children = [None] * 26
self.is_end = False
def insert(self, word):
node = self
for c in word:
idx = ord(c) - ord('a')
if node.children[idx] is None:
node.children[idx] = Trie()
node = node.c... | Trie |
python | arrow-py__arrow | tests/test_arrow.py | {
"start": 105153,
"end": 108663
} | class ____:
def test_start_before_end(self):
target = arrow.Arrow.fromdatetime(datetime(2013, 5, 7))
start = arrow.Arrow.fromdatetime(datetime(2013, 5, 8))
end = arrow.Arrow.fromdatetime(datetime(2013, 5, 5))
assert not target.is_between(start, end)
def test_exclusive_exclusive_... | TestArrowIsBetween |
python | huggingface__transformers | src/transformers/models/instructblip/modeling_instructblip.py | {
"start": 14790,
"end": 16569
} | class ____(InstructBlipPreTrainedModel):
main_input_name = "pixel_values"
input_modalities = ("image",)
config: InstructBlipVisionConfig
_can_record_outputs = {
"hidden_states": InstructBlipEncoderLayer,
"attentions": InstructBlipAttention,
}
def __init__(self, config: InstructB... | InstructBlipVisionModel |
python | scrapy__scrapy | tests/test_downloadermiddleware_downloadtimeout.py | {
"start": 193,
"end": 1597
} | class ____:
def get_request_spider_mw(self, settings=None):
crawler = get_crawler(Spider, settings)
spider = crawler._create_spider("foo")
request = Request("http://scrapytest.org/")
return request, spider, DownloadTimeoutMiddleware.from_crawler(crawler)
def test_default_downloa... | TestDownloadTimeoutMiddleware |
python | boto__boto3 | boto3/dynamodb/conditions.py | {
"start": 5138,
"end": 5207
} | class ____(ComparisonCondition):
expression_operator = '<'
| LessThan |
python | django__django | tests/db_functions/text/test_sha224.py | {
"start": 264,
"end": 2151
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
Author.objects.bulk_create(
[
Author(alias="John Smith"),
Author(alias="Jordan Élena"),
Author(alias="皇帝"),
Author(alias=""),
Author(alias=None),
... | SHA224Tests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.