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 | doocs__leetcode | solution/1500-1599/1554.Strings Differ by One Character/Solution.py | {
"start": 0,
"end": 307
} | class ____:
def differByOne(self, dict: List[str]) -> bool:
s = set()
for word in dict:
for i in range(len(word)):
t = word[:i] + "*" + word[i + 1 :]
if t in s:
return True
s.add(t)
return False
| Solution |
python | keras-team__keras | keras/src/metrics/accuracy_metrics.py | {
"start": 534,
"end": 2448
} | class ____(reduction_metrics.MeanMetricWrapper):
"""Calculates how often predictions equal labels.
This metric creates two local variables, `total` and `count` that are used
to compute the frequency with which `y_pred` matches `y_true`. This
frequency is ultimately returned as `binary accuracy`: an ide... | Accuracy |
python | vyperlang__vyper | vyper/semantics/analysis/base.py | {
"start": 5485,
"end": 7612
} | class ____:
"""
VarInfo are objects that represent the type of a variable,
plus associated metadata like location and modifiability attributes
Object Attributes
-----------------
location: DataLocation of this variable
modifiability: Modifiability of this variable
"""
typ: VyperTyp... | VarInfo |
python | fluentpython__example-code | 20-descriptor/descriptorkinds.py | {
"start": 5408,
"end": 5579
} | class ____: # <4>
"""a.k.a. non-data or shadowable descriptor"""
def __get__(self, instance, owner):
print_args('get', self, instance, owner)
| NonOverriding |
python | kamyu104__LeetCode-Solutions | Python/find-words-containing-character.py | {
"start": 42,
"end": 271
} | class ____(object):
def findWordsContaining(self, words, x):
"""
:type words: List[str]
:type x: str
:rtype: List[int]
"""
return [i for i, w in enumerate(words) if x in w]
| Solution |
python | openai__gym | gym/error.py | {
"start": 3970,
"end": 4029
} | class ____(Error):
"""Unused error."""
| VideoRecorderError |
python | pytorch__pytorch | test/test_testing.py | {
"start": 44030,
"end": 46562
} | class ____(TestCase):
def test_matching(self):
crow_indices = (0, 1, 2)
col_indices = (1, 0)
values = (1, 2)
actual = torch.sparse_csr_tensor(crow_indices, col_indices, values, size=(2, 2))
expected = actual.clone()
for fn in assert_close_with_inputs(actual, expected... | TestAssertCloseSparseCSR |
python | numba__numba | numba/tests/test_interpreter.py | {
"start": 15412,
"end": 29481
} | class ____(TestCase, MemoryLeakMixin):
"""
gh #7894
Tests that check a peephole optimization for constant
dictionaries in Python 3.10. The bytecode changes when
number of elements > 15, which splits the constant dictionary
into multiple dictionaries that are joined by a DICT_UPDATE
bytecode... | TestLargeConstDict |
python | google__jax | tests/lax_metal_test.py | {
"start": 220608,
"end": 228668
} | class ____(jtu.JaxTestCase):
def dispatchOn(self, args, func, device=jax.devices('cpu')[0]):
deviceArgs = []
for arg in args:
deviceArgs.append(jax.device_put(arg, device))
return func(*deviceArgs)
@staticmethod
def compile_and_exec(module, args, run_on_cpu=False):
from jax.extend.backend ... | ReportedIssuesTests |
python | zarr-developers__zarr-python | tests/test_dtype/test_npy/test_float.py | {
"start": 179,
"end": 885
} | class ____(BaseTestZDType):
def scalar_equals(self, scalar1: object, scalar2: object) -> bool:
if np.isnan(scalar1) and np.isnan(scalar2): # type: ignore[call-overload]
return True
return super().scalar_equals(scalar1, scalar2)
hex_string_params: tuple[tuple[str, float], ...] = ()
... | _BaseTestFloat |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/exc.py | {
"start": 9972,
"end": 10132
} | class ____(InvalidRequestError):
"""A subject passed to :func:`sqlalchemy.inspection.inspect` produced
no context for inspection."""
| NoInspectionAvailable |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 533651,
"end": 533988
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field(PullRequestChangedFile, graphql_name="node")
| PullRequestChangedFileEdge |
python | getsentry__sentry | tests/sentry/incidents/endpoints/serializers/test_incident.py | {
"start": 1381,
"end": 3051
} | class ____(TestCase):
def test_error_alert_rule(self) -> None:
query = "test query"
incident = self.create_incident(query=query)
serializer = DetailedIncidentSerializer()
result = serialize(incident, serializer=serializer)
alert_rule_serializer = DetailedAlertRuleSerializer(... | DetailedIncidentSerializerTest |
python | numba__numba | numba/tests/test_sort.py | {
"start": 16275,
"end": 16442
} | class ____(BaseTimsortTest, TestCase):
timsort = py_list_timsort
# Much faster than a Numpy array in pure Python
array_factory = list
| TestTimsortPurePython |
python | huggingface__transformers | src/transformers/models/groupvit/modeling_groupvit.py | {
"start": 23693,
"end": 28913
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.num_heads = config.num_attention_heads
self.head_dim = self.embed_dim /... | GroupViTAttention |
python | walkccc__LeetCode | solutions/2447. Number of Subarrays With GCD Equal to K/2447.py | {
"start": 0,
"end": 510
} | class ____:
def subarrayGCD(self, nums: list[int], k: int) -> int:
ans = 0
gcds = collections.Counter()
for num in nums:
if num % k == 0:
nextGcds = collections.defaultdict(int)
nextGcds[num] += 1
for prevGcd, count in gcds.items():
nextGcds[math.gcd(prevGcd, num)]... | Solution |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/oracle/oracledb.py | {
"start": 31544,
"end": 32137
} | class ____(OracleDialect_oracledb):
is_async = True
supports_server_side_cursors = True
supports_statement_cache = True
execution_ctx_cls = OracleExecutionContextAsync_oracledb
_min_version = (2,)
# thick_mode mode is not supported by asyncio, oracledb will raise
@classmethod
def impor... | OracleDialectAsync_oracledb |
python | joblib__joblib | joblib/_utils.py | {
"start": 2679,
"end": 3248
} | class ____:
"""Protect function call and return error with traceback."""
def __init__(self, func):
self.func = func
def __call__(self, **kwargs):
try:
return self.func(**kwargs)
except BaseException as e:
return _ExceptionWithTraceback(e)
def _retrieve_tra... | _TracebackCapturingWrapper |
python | HIPS__autograd | examples/convnet.py | {
"start": 4033,
"end": 4810
} | class ____:
def __init__(self, size):
self.size = size
def build_weights_dict(self, input_shape):
# Input shape is anything (all flattened)
input_size = np.prod(input_shape, dtype=int)
self.parser = WeightsParser()
self.parser.add_weights("params", (input_size, self.size... | full_layer |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/ragged_tensor_supported_values_test.py | {
"start": 2394,
"end": 3991
} | class ____(dispatch.GlobalOpDispatcher):
"""Global op dispatcher for WrappedTensor."""
# For these ops, just return plain Tensors (not WrappedTensors).
OPS_THAT_RETURN_UNTRACED_RESULTS = (array_ops.shape, array_ops.shape_v2,
check_ops.assert_rank_at_least)
def call_op(sel... | WrappedTensorOpDispatcher |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/recursiveTypeAlias8.py | {
"start": 280,
"end": 330
} | class ____(ClassA):
id: int
name: str
| ClassB |
python | pennersr__django-allauth | allauth/idp/oidc/migrations/0003_client_allow_uri_wildcards.py | {
"start": 43,
"end": 600
} | class ____(migrations.Migration):
dependencies = [
("allauth_idp_oidc", "0002_client_default_scopes"),
]
operations = [
migrations.AddField(
model_name="client",
name="allow_uri_wildcards",
field=models.BooleanField(
default=False,
... | Migration |
python | pydata__xarray | xarray/tests/test_concat.py | {
"start": 61111,
"end": 68105
} | class ____:
def test_concat_datatree_along_existing_dim(self):
dt1 = DataTree.from_dict(data={"/a": ("x", [1]), "/b": 3}, coords={"/x": [0]})
dt2 = DataTree.from_dict(data={"/a": ("x", [2]), "/b": 3}, coords={"/x": [1]})
expected = DataTree.from_dict(
data={"/a": ("x", [1, 2]), "... | TestConcatDataTree |
python | SmileyChris__easy-thumbnails | easy_thumbnails/management/commands/thumbnail_cleanup.py | {
"start": 398,
"end": 5216
} | class ____:
"""
Remove thumbnails and DB references to non-existing source images.
"""
sources = 0
thumbnails = 0
thumbnails_deleted = 0
source_refs_deleted = 0
execution_time = 0
def __init__(self, stdout, stderr):
self.stdout = stdout
self.stderr = stderr
def ... | ThumbnailCollectionCleaner |
python | coleifer__peewee | tests/postgres.py | {
"start": 20368,
"end": 21027
} | class ____(BaseJsonFieldTestCase, ModelTestCase):
M = JsonModel
N = Normal
database = db
requires = [JsonModel, Normal, JsonModelNull]
def test_json_null(self):
tjn = JsonModelNull.create(data=None)
tj = JsonModelNull.create(data={'k1': 'v1'})
results = JsonModelNull.select... | TestJsonField |
python | huggingface__transformers | src/transformers/models/phi3/modeling_phi3.py | {
"start": 23889,
"end": 23992
} | class ____(GenericForSequenceClassification, Phi3PreTrainedModel):
pass
| Phi3ForSequenceClassification |
python | scikit-learn__scikit-learn | sklearn/utils/_bunch.py | {
"start": 98,
"end": 2176
} | class ____(dict):
"""Container object exposing keys as attributes.
Bunch objects are sometimes used as an output for functions and methods.
They extend dictionaries by enabling values to be accessed by key,
`bunch["value_key"]`, or by an attribute, `bunch.value_key`.
Examples
--------
>>> ... | Bunch |
python | cython__cython | Cython/Debugger/libpython.py | {
"start": 16865,
"end": 19242
} | class ____(PyObjectPtr):
_typename = 'PyObject'
def get_attr_dict(self):
'''
Get the PyDictObject ptr representing the attribute dictionary
(or None if there's a problem)
'''
try:
typeobj = self.type()
dictoffset = int_from_int(typeobj.field('tp_d... | HeapTypeObjectPtr |
python | PrefectHQ__prefect | src/integrations/prefect-gcp/tests/test_bigquery.py | {
"start": 4392,
"end": 9871
} | class ____:
@pytest.fixture
def mock_connection(self):
mock_cursor = MagicMock()
results = iter([0, 1, 2, 3, 4])
mock_cursor.fetchone.side_effect = lambda: (next(results),)
mock_cursor.fetchmany.side_effect = lambda size: list(
(next(results),) for i in range(size)
... | TestBigQueryWarehouse |
python | dask__distributed | distributed/worker_state_machine.py | {
"start": 25379,
"end": 27272
} | class ____(ExecuteDoneEvent):
run_id: int # FIXME: Utilize the run ID in all ExecuteDoneEvents
start: float | None
stop: float | None
exception: Serialize
traceback: Serialize | None
exception_text: str
traceback_text: str
__slots__ = tuple(__annotations__)
def _after_from_dict(sel... | ExecuteFailureEvent |
python | numba__numba | numba/tests/test_obj_lifetime.py | {
"start": 5063,
"end": 10919
} | class ____(TestCase):
"""
Test lifetime of Python objects inside jit-compiled functions.
"""
def compile(self, pyfunc):
# Note: looplift must be disabled. The test require the function
# control-flow to be unchanged.
cfunc = jit((types.pyobject,), forceobj=True, looplift=F... | TestObjLifetime |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_background03.py | {
"start": 315,
"end": 913
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("background03.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with a background image."""
workbook = ... | TestCompareXLSXFiles |
python | sympy__sympy | sympy/matrices/dense.py | {
"start": 3616,
"end": 30815
} | class ____(DenseMatrix, MutableRepMatrix):
# The simplify method for mutable mattrices is inconsistent with the
# one for immutable matrices.
def simplify(self, **kwargs) -> None: # type: ignore
"""Applies simplify to the elements of a matrix in place.
This is a shortcut for M.applyfunc(l... | MutableDenseMatrix |
python | jina-ai__jina | tests/unit/orchestrate/flow/flow-construct/test_slow_executor_shutdown.py | {
"start": 78,
"end": 586
} | class ____(Executor):
def close(self) -> None:
with open(
os.path.join(self.metas.workspace, 'test'), 'w', encoding='utf-8'
) as f:
time.sleep(10)
f.write('x')
@pytest.mark.slow
def test_slow_executor_close(tmpdir):
with Deployment(protocol='http',
u... | SlowExecutor |
python | cython__cython | tests/compile/builtinbuffer.py | {
"start": 46,
"end": 104
} | class ____:
cython.declare(pybuf = 'Py_buffer')
| BuiltinRef |
python | getsentry__sentry | tests/sentry/workflow_engine/handlers/condition/test_event_frequency_handlers.py | {
"start": 11979,
"end": 12767
} | class ____(TestEventFrequencyCountCondition):
def setUp(self) -> None:
super().setUp()
self.condition = Condition.PERCENT_SESSIONS_COUNT
self.payload: dict[str, str | int | float] = {
"interval": "30m", # only percent sessions allows 30m
"id": EventFrequencyPercentCo... | TestPercentSessionsCountCondition |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 746390,
"end": 747722
} | class ____(Geometry):
"""
MultiLineString schema wrapper.
MultiLineString geometry object. https://tools.ietf.org/html/rfc7946#section-3.1.5
Parameters
----------
coordinates : Sequence[Sequence[Sequence[float], :class:`Position`]]
type : Literal['MultiLineString']
Specifies the t... | MultiLineString |
python | pytorch__pytorch | test/export/random_dag.py | {
"start": 523,
"end": 1162
} | class ____:
"""
Util to generate a block of Python-formatted code.
"""
def __init__(self):
self._code = []
def __repr__(self):
return "".join(self._code)
def new_line(self, line: str):
"""
Add a new line of code. The line is automatically suffixed
with ... | Block |
python | ray-project__ray | python/ray/tune/search/sample.py | {
"start": 5521,
"end": 10707
} | class ____(Domain):
class _Uniform(Uniform):
def sample(
self,
domain: "Float",
config: Optional[Union[List[Dict], Dict]] = None,
size: int = 1,
random_state: "RandomState" = None,
):
if not isinstance(random_state, _BackwardsCo... | Float |
python | imageio__imageio | imageio/plugins/_freeimage.py | {
"start": 10888,
"end": 12523
} | class ____(object):
FIDT_BYTE = 1 # 8-bit unsigned integer
FIDT_ASCII = 2 # 8-bit bytes w/ last byte null
FIDT_SHORT = 3 # 16-bit unsigned integer
FIDT_LONG = 4 # 32-bit unsigned integer
FIDT_RATIONAL = 5 # 64-bit unsigned fraction
FIDT_SBYTE = 6 # 8-bit signed integer
FIDT_UNDEFINED =... | METADATA_DATATYPE |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 299472,
"end": 300196
} | class ____(MatmulCommon):
import operator
matmul = operator.matmul
def test_array_priority_override(self):
class A:
__array_priority__ = 1000
def __matmul__(self, other):
return "A"
def __rmatmul__(self, other):
return "A"
... | TestMatmulOperator |
python | pypa__hatch | src/hatch/config/constants.py | {
"start": 0,
"end": 327
} | class ____:
ENV = "HATCH_ENV"
ENV_ACTIVE = "HATCH_ENV_ACTIVE"
ENV_OPTION_PREFIX = "HATCH_ENV_TYPE_"
QUIET = "HATCH_QUIET"
VERBOSE = "HATCH_VERBOSE"
INTERACTIVE = "HATCH_INTERACTIVE"
PYTHON = "HATCH_PYTHON"
# https://no-color.org
NO_COLOR = "NO_COLOR"
FORCE_COLOR = "FORCE_COLOR"
... | AppEnvVars |
python | doocs__leetcode | solution/1800-1899/1825.Finding MK Average/Solution2.py | {
"start": 0,
"end": 1285
} | class ____:
def __init__(self, m: int, k: int):
self.m = m
self.k = k
self.sl = SortedList()
self.q = deque()
self.s = 0
def addElement(self, num: int) -> None:
self.q.append(num)
if len(self.q) == self.m:
self.sl = SortedList(self.q)
... | MKAverage |
python | huggingface__transformers | src/transformers/models/rt_detr/modeling_rt_detr_resnet.py | {
"start": 4720,
"end": 6288
} | class ____(nn.Module):
"""
A classic ResNet's residual layer composed by two `3x3` convolutions.
See https://github.com/lyuwenyu/RT-DETR/blob/5b628eaa0a2fc25bdafec7e6148d5296b144af85/rtdetr_pytorch/src/nn/backbone/presnet.py#L34.
"""
def __init__(
self,
config: RTDetrResNetConfig,
... | RTDetrResNetBasicLayer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-ads/source_google_ads/components.py | {
"start": 33345,
"end": 33404
} | class ____:
depth: int = 0
@dataclass
| TopLevelObjectState |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 538788,
"end": 539273
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of CreateLinkedBranch"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "linked_branch")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing t... | CreateLinkedBranchPayload |
python | readthedocs__readthedocs.org | readthedocs/builds/tests/test_views.py | {
"start": 4074,
"end": 5212
} | class ____(TestCase):
def setUp(self):
self.user = get(User, username="test")
self.project = get(Project, users=[self.user])
self.version = get(Version, project=self.project)
self.build = get(
Build,
project=self.project,
version=self.version,
... | BuildViewsTests |
python | pytorch__pytorch | torch/storage.py | {
"start": 50959,
"end": 51308
} | class ____(type):
dtype: torch.dtype
def __instancecheck__(cls, instance):
if type(instance) is TypedStorage:
cls_device = _get_device_from_module(cls.__module__)
return (cls_device == instance.device.type) and (
cls.dtype == instance.dtype
)
... | _LegacyStorageMeta |
python | numba__numba | numba/core/types/containers.py | {
"start": 5802,
"end": 6841
} | class ____(BaseAnonymousTuple, _HomogeneousTuple, Sequence):
"""
Type class for homogeneous tuples.
"""
def __init__(self, dtype, count):
self.dtype = dtype
self.count = count
name = "%s(%s x %d)" % (self.__class__.__name__, dtype, count,)
super(UniTuple, self).__init__(... | UniTuple |
python | django__django | tests/sessions_tests/tests.py | {
"start": 31396,
"end": 33522
} | class ____(SessionTestsMixin, TestCase):
backend = CacheDBSession
def test_exists_searches_cache_first(self):
self.session.save()
with self.assertNumQueries(0):
self.assertIs(self.session.exists(self.session.session_key), True)
# Some backends might issue a warning
@ignore_... | CacheDBSessionTests |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 398135,
"end": 399746
} | class ____(sgqlc.types.Interface):
"""Entities that have members who can set status messages."""
__schema__ = github_schema
__field_names__ = ("member_statuses",)
member_statuses = sgqlc.types.Field(
sgqlc.types.non_null("UserStatusConnection"),
graphql_name="memberStatuses",
ar... | MemberStatusable |
python | kamyu104__LeetCode-Solutions | Python/partition-to-k-equal-sum-subsets.py | {
"start": 35,
"end": 882
} | class ____(object):
def canPartitionKSubsets(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
def dfs(nums, target, used, todo, lookup):
if lookup[used] is None:
targ = (todo-1)%target + 1
lookup[used]... | Solution |
python | bokeh__bokeh | src/bokeh/models/annotations/geometry.py | {
"start": 14692,
"end": 16025
} | class ____(Annotation):
""" Render a sloped line as an annotation.
See :ref:`ug_basic_annotations_slope` for information on plotting slopes.
"""
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
gra... | Slope |
python | apache__thrift | lib/py/test/thrift_TBinaryProtocol.py | {
"start": 5324,
"end": 10547
} | class ____(unittest.TestCase):
def test_TBinaryProtocol_write_read(self):
try:
testNaked('Byte', 123)
for i in range(0, 128):
self.assertEqual(i, testField('Byte', i))
self.assertEqual(-i, testField('Byte', -i))
self.assertEqual(0, testNa... | TestTBinaryProtocol |
python | getsentry__sentry | tests/sentry/users/api/endpoints/test_user_authenticators_index.py | {
"start": 275,
"end": 1463
} | class ____(APITestCase):
def test_simple(self) -> None:
user = self.create_user(email="a@example.com", is_superuser=True)
Authenticator.objects.create(
type=3, # u2f
user=user,
config={
"devices": [
{
"b... | AuthenticatorIndex |
python | python-pillow__Pillow | Tests/test_image_resample.py | {
"start": 14223,
"end": 15841
} | class ____:
@contextmanager
def count(self, diff: int) -> Generator[None, None, None]:
count = Image.core.get_stats()["new_count"]
yield
assert Image.core.get_stats()["new_count"] - count == diff
def test_horizontal(self) -> None:
im = hopper("L")
with self.count(1):... | TestCoreResamplePasses |
python | paramiko__paramiko | paramiko/ssh_exception.py | {
"start": 3181,
"end": 4001
} | class ____(SSHException):
"""
The host key given by the SSH server did not match what we were expecting.
:param str hostname: the hostname of the SSH server
:param PKey got_key: the host key presented by the server
:param PKey expected_key: the host key expected
.. versionadded:: 1.6
"""
... | BadHostKeyException |
python | pdm-project__pdm | src/pdm/cli/commands/base.py | {
"start": 289,
"end": 2310
} | class ____:
"""A CLI subcommand"""
# The subcommand's name
name: str | None = None
# The subcommand's help string, if not given, __doc__ will be used.
description: str | None = None
# A list of pre-defined options which will be loaded on initializing
# Rewrite this if you don't want the def... | BaseCommand |
python | pypa__pip | src/pip/_internal/network/session.py | {
"start": 7125,
"end": 8510
} | class ____(BaseAdapter):
def send(
self,
request: PreparedRequest,
stream: bool = False,
timeout: float | tuple[float, float] | None = None,
verify: bool | str = True,
cert: str | tuple[str, str] | None = None,
proxies: Mapping[str, str] | None = None,
) -... | LocalFSAdapter |
python | pytorch__pytorch | torch/_higher_order_ops/wrap.py | {
"start": 2243,
"end": 2979
} | class ____(HigherOrderOperator):
def __init__(self) -> None:
super().__init__("wrap_with_set_grad_enabled")
def __call__(self, enable_grad, wrapped_func, *args, **kwargs):
# Dynamo already traces the body of HigherOrderOp beforehand when it
# so no need to trace into it.
import ... | WrapWithSetGradEnabled |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarTuple11.py | {
"start": 445,
"end": 1888
} | class ____(Generic[*Shape]):
def __init__(self, *shape: *Shape):
self.shape = shape
def __abs__(self) -> "Array[*Shape]": ...
def __add__(self, other: "Array[*Shape]") -> "Array[*Shape]": ...
Height = NewType("Height", int)
Width = NewType("Width", int)
x: Array[Height, Width] = Array(Height(480... | Array |
python | pytorch__pytorch | test/inductor/test_indexing.py | {
"start": 11994,
"end": 19775
} | class ____(InductorTestCase):
def test_print_pow(self):
s1 = sympy.Symbol("foo", integer=True)
s2 = sympy.Symbol("bar", integer=True)
common_cases = [
# expr, result
# Test Pow directly.
(
sympy.Pow(s1 + s2, 0),
lambda _, L... | ExprPrinterTests |
python | joke2k__faker | faker/providers/internet/zh_CN/__init__.py | {
"start": 127,
"end": 2550
} | class ____(InternetProvider):
user_name_formats = (
"{{last_romanized_name}}.{{first_romanized_name}}",
"{{first_romanized_name}}.{{last_romanized_name}}",
"{{first_romanized_name}}##",
"?{{last_romanized_name}}",
)
tlds = OrderedDict(
(
("cn", 0.8),
... | Provider |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 222489,
"end": 222780
} | class ____(VegaLiteSchema):
"""ConditionalAxisPropertynumberArraynull schema wrapper."""
_schema = {"$ref": "#/definitions/ConditionalAxisProperty<(number[]|null)>"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| ConditionalAxisPropertynumberArraynull |
python | joblib__joblib | joblib/numpy_pickle.py | {
"start": 11368,
"end": 14729
} | class ____(Pickler):
"""A pickler to persist big data efficiently.
The main features of this object are:
* persistence of numpy arrays in a single file.
* optional compression with a special care on avoiding memory copies.
Attributes
----------
fp: file
File object handle used for ... | NumpyPickler |
python | getsentry__sentry | tests/sentry/integrations/utils/test_lifecycle_metrics.py | {
"start": 294,
"end": 354
} | class ____(Exception):
pass
@no_silo_test
| ExampleException |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_nbagg.py | {
"start": 7919,
"end": 8026
} | class ____(_Backend):
FigureCanvas = FigureCanvasNbAgg
FigureManager = FigureManagerNbAgg
| _BackendNbAgg |
python | joke2k__faker | faker/providers/currency/sv_SE/__init__.py | {
"start": 101,
"end": 5829
} | class ____(CurrencyProvider):
# Format: (code, name)
currencies = (
("AED", "UAE Dirham"),
("AFN", "Afghani"),
("ALL", "Lek"),
("AMD", "Armenisk Dram"),
("ANG", "Gulden från Nederländska Antillerna"),
("AOA", "Kwanza"),
("ARS", "Argentinsk Peso"),
... | Provider |
python | huggingface__transformers | tests/models/imagegpt/test_image_processing_imagegpt.py | {
"start": 15582,
"end": 16492
} | class ____(unittest.TestCase):
@slow
def test_image(self):
image_processing = ImageGPTImageProcessor.from_pretrained("openai/imagegpt-small")
images = prepare_images()
# test non-batched
encoding = image_processing(images[0], return_tensors="pt")
self.assertIsInstance(... | ImageGPTImageProcessorIntegrationTest |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 59284,
"end": 60434
} | class ____:
def test_dateCoreFunctionality(self):
dt = arrow.Arrow(2015, 4, 11, 17, 30, 00)
assert self.locale.month_name(dt.month) == "एप्रिल"
assert self.locale.month_abbreviation(dt.month) == "एप्रि"
assert self.locale.day_name(dt.isoweekday()) == "शनिवार"
assert self.loca... | TestMarathiLocale |
python | urllib3__urllib3 | src/urllib3/connection.py | {
"start": 2329,
"end": 23417
} | class ____(_HTTPConnection):
"""
Based on :class:`http.client.HTTPConnection` but provides an extra constructor
backwards-compatibility layer between older and newer Pythons.
Additional keyword parameters are used to configure attributes of the connection.
Accepted parameters include:
- ``sour... | HTTPConnection |
python | dask__distributed | distributed/cluster_dump.py | {
"start": 3473,
"end": 10995
} | class ____(Mapping):
"""
Utility class for inspecting the state of a cluster dump
.. code-block:: python
dump = DumpArtefact.from_url("dump.msgpack.gz")
memory_tasks = dump.scheduler_tasks("memory")
executing_tasks = dump.worker_tasks("executing")
"""
def __init__(self, st... | DumpArtefact |
python | pytorch__pytorch | test/distributed/_composable/fsdp/test_fully_shard_comm.py | {
"start": 67323,
"end": 68312
} | class ____(FSDPTestMultiThread):
@property
def world_size(self) -> int:
return 2
@skip_if_lt_x_gpu(1)
def test_unshard_no_param_group(self):
# Check that we can call `unshard()` on a module with no parameter
# group / no managed parameters without erroring
model = nn.Seq... | TestFullyShardUnshardMultiThread |
python | ray-project__ray | rllib/offline/wis_estimator.py | {
"start": 290,
"end": 370
} | class ____(WeightedImportanceSampling):
pass
| WeightedImportanceSamplingEstimator |
python | ray-project__ray | python/ray/data/_internal/datasource/bigquery_datasource.py | {
"start": 1026,
"end": 5024
} | class ____(Datasource):
def __init__(
self,
project_id: str,
dataset: Optional[str] = None,
query: Optional[str] = None,
):
_check_import(self, module="google.cloud", package="bigquery")
_check_import(self, module="google.cloud", package="bigquery_storage")
... | BigQueryDatasource |
python | python-openxml__python-docx | tests/image/test_png.py | {
"start": 13639,
"end": 14647
} | class ____:
def it_can_construct_from_a_stream_and_offset(self, from_offset_fixture):
stream_rdr, offset = from_offset_fixture[:2]
horz_px_per_unit, vert_px_per_unit = from_offset_fixture[2:4]
units_specifier = from_offset_fixture[4]
pHYs_chunk = _pHYsChunk.from_offset(None, stream_r... | Describe_pHYsChunk |
python | apache__airflow | providers/databricks/tests/unit/databricks/triggers/test_databricks.py | {
"start": 3715,
"end": 9733
} | class ____:
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
Connection(
conn_id=DEFAULT_CONN_ID,
conn_type="databricks",
host=HOST,
login=LOGIN,
... | TestDatabricksExecutionTrigger |
python | psf__black | tests/data/cases/torture.py | {
"start": 1448,
"end": 2279
} | class ____:
def foo(self):
for _ in range(10):
aaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbb.cccccccccc(
xxxxxxxxxxxx
) # pylint: disable=no-member
def test(self, othr):
return 1 == 2 and (
name,
description,
self.default,
self.selected,... | A |
python | redis__redis-py | redis/commands/search/hybrid_result.py | {
"start": 89,
"end": 382
} | class ____:
"""
Represents the result of a hybrid search query execution
Returned by the `hybrid_search` command, when using RESP version 2.
"""
total_results: int
results: List[Dict[str, Any]]
warnings: List[Union[str, bytes]]
execution_time: float
| HybridResult |
python | python-poetry__poetry | src/poetry/mixology/failure.py | {
"start": 354,
"end": 661
} | class ____(Exception):
def __init__(self, incompatibility: Incompatibility) -> None:
self._incompatibility = incompatibility
@property
def message(self) -> str:
return str(self)
def __str__(self) -> str:
return _Writer(self._incompatibility).write()
| SolveFailureError |
python | ray-project__ray | python/ray/serve/metrics.py | {
"start": 2613,
"end": 5108
} | class ____(metrics.Counter):
"""A serve cumulative metric that is monotonically increasing.
This corresponds to Prometheus' counter metric:
https://prometheus.io/docs/concepts/metric_types/#counter
Serve-related tags ("deployment", "replica", "application", "route")
are added automatically if not ... | Counter |
python | django-extensions__django-extensions | django_extensions/management/commands/set_fake_passwords.py | {
"start": 477,
"end": 1805
} | class ____(BaseCommand):
help = 'DEBUG only: sets all user passwords to a common value ("%s" by default)' % (
DEFAULT_FAKE_PASSWORD,
)
requires_system_checks: List[str] = []
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
"--prompt... | Command |
python | great-expectations__great_expectations | great_expectations/expectations/core/expect_column_pair_values_a_to_be_greater_than_b.py | {
"start": 2221,
"end": 15696
} | class ____(ColumnPairMapExpectation):
__doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION}
ExpectColumnPairValuesAToBeGreaterThanB is a \
Column Pair Map Expectation.
Column Pair Map Expectations are evaluated for a pair of columns and ask a yes/no question about the row-wise relationship between those two c... | ExpectColumnPairValuesAToBeGreaterThanB |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-rki-covid/source_rki_covid/source.py | {
"start": 392,
"end": 1369
} | class ____(HttpStream, ABC):
url_base = "https://api.corona-zahlen.org/"
def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]:
return None
def request_params(
self, stream_state: Mapping[str, Any], stream_slice: Mapping[str, any] = None, next_page_token: Ma... | RkiCovidStream |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 60380,
"end": 61117
} | class ____(sgqlc.types.Enum):
"""GitHub-provided templates for Projects
Enumeration Choices:
* `AUTOMATED_KANBAN_V2`: Create a board with v2 triggers to
automatically move cards across To do, In progress and Done
columns.
* `AUTOMATED_REVIEWS_KANBAN`: Create a board with triggers to
... | ProjectTemplate |
python | jupyterlab__jupyterlab | jupyterlab/labextensions.py | {
"start": 14226,
"end": 14847
} | class ____(BaseExtensionApp):
description = "Enable labextension(s) by name"
aliases = enable_aliases
level = Unicode("sys_prefix", help="Level at which to enable: sys_prefix, user, system").tag(
config=True
)
def run_task(self):
app_options = AppOptions(
app_dir=self.a... | EnableLabExtensionsApp |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 595885,
"end": 596543
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("RepositoryInvitationEdge"), graphql_name="edges"
)
nodes ... | RepositoryInvitationConnection |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_points03.py | {
"start": 350,
"end": 1372
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_points03.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with point formatting."""
workbook = ... | TestCompareXLSXFiles |
python | run-llama__llama_index | llama-index-core/llama_index/core/llama_dataset/simple.py | {
"start": 325,
"end": 942
} | class ____(BaseLlamaExamplePrediction):
"""
RAG example prediction class.
Args:
response (str): The response generated by the LLM.
contexts (Optional[List[str]]): The retrieved context (text) for generating
response.
"""
label: str = Field(
... | SimpleExamplePrediction |
python | fluentpython__example-code-2e | 18-with-match/lispy/original/lispy.py | {
"start": 1257,
"end": 4290
} | class ____:
"An input port. Retains a line of chars."
tokenizer = r"""\s*(,@|[('`,)]|"(?:[\\].|[^\\"])*"|;.*|[^\s('"`,;)]*)(.*)"""
def __init__(self, file):
self.file = file; self.line = ''
def next_token(self):
"Return the next token, reading new text into line buffer if needed."
... | InPort |
python | huggingface__transformers | src/transformers/models/vitdet/modeling_vitdet.py | {
"start": 8664,
"end": 12061
} | class ____(nn.Module):
"""Multi-head Attention block with relative position embeddings."""
def __init__(self, config, input_size=None):
"""
Args:
config (`VitDetConfig`):
Model configuration.
input_size (`tuple[int]`, *optional*):
Input re... | VitDetAttention |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py | {
"start": 55564,
"end": 56257
} | class ____(BaseModel):
type: Literal["Spec"]
connection_specification: Dict[str, Any] = Field(
...,
description="A connection specification describing how a the connector can be configured.",
title="Connection Specification",
)
documentation_url: Optional[str] = Field(
No... | Spec |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/errors.py | {
"start": 729,
"end": 798
} | class ____(Exception):
"""Base class for all exceptions."""
| PyCTError |
python | facebookresearch__faiss | demos/offline_ivf/tests/testing_utils.py | {
"start": 569,
"end": 6170
} | class ____:
def __init__(
self,
tempdir: str,
dimension: int,
data_type: np.dtype,
index_factory: Optional[List] = ["OPQ4,IVF256,PQ4"],
training_sample: Optional[int] = 9984,
index_shard_size: Optional[int] = 1000,
query_batch_size: Optional[int] = 100... | TestDataCreator |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/einsum_op_test.py | {
"start": 11963,
"end": 16378
} | class ____(test.TestCase):
def _check_gradient(self, s, *input_shapes):
with self.cached_session():
r = np.random.RandomState(seed=0)
for dtype in (np.float32, np.float64, np.complex64, np.complex128):
with self.subTest(s=s, dtype=dtype):
tol = 10 * np.sqrt(np.finfo(dtype).resolutio... | EinsumGradTest |
python | jpadilla__pyjwt | jwt/exceptions.py | {
"start": 776,
"end": 914
} | class ____(InvalidTokenError):
"""Raised when a token's ``iss`` claim does not match the expected issuer"""
pass
| InvalidIssuerError |
python | spyder-ide__spyder | external-deps/qtconsole/qtconsole/kernel_mixins.py | {
"start": 628,
"end": 1813
} | class ____(MetaQObjectHasTraits('NewBase', (HasTraits, SuperQObject), {})):
""" A KernelClient that provides signals and slots.
"""
# Emitted when the kernel client has started listening.
started_channels = QtCore.Signal()
# Emitted when the kernel client has stopped listening.
stopped_channel... | QtKernelClientMixin |
python | spyder-ide__spyder | spyder/plugins/updatemanager/widgets/update.py | {
"start": 21492,
"end": 22160
} | class ____(MessageCheckBox):
def __init__(self, icon=None, text=None, parent=None):
super().__init__(icon=icon, text=text, parent=parent)
self.setTextFormat(Qt.RichText)
self._parent = parent
self.set_checkbox_text(_("Check for updates at startup"))
self.option = 'check_updat... | UpdateMessageCheckBox |
python | pypa__setuptools | setuptools/_distutils/tests/test_extension.py | {
"start": 211,
"end": 3670
} | class ____:
def test_read_setup_file(self):
# trying to read a Setup file
# (sample extracted from the PyGame project)
setup = os.path.join(os.path.dirname(__file__), 'Setup.sample')
exts = read_setup_file(setup)
names = [ext.name for ext in exts]
names.sort()
... | TestExtension |
python | openai__openai-python | src/openai/types/beta/threads/file_citation_delta_annotation.py | {
"start": 249,
"end": 451
} | class ____(BaseModel):
file_id: Optional[str] = None
"""The ID of the specific File the citation is from."""
quote: Optional[str] = None
"""The specific quote in the file."""
| FileCitation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.