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/address/zh_CN/__init__.py | {
"start": 45,
"end": 7296
} | class ____(AddressProvider):
city_suffixes = ("市", "县")
city_formats = ("{{city_name}}{{city_suffix}}", "{{first_name}}{{city_suffix}}")
district_formats = ("{{district}}区",)
building_number_formats = ("?座",)
postcode_formats = ("%#####",)
street_suffixes = ("街", "路")
street_name_formats ... | Provider |
python | ray-project__ray | release/ray_release/exception.py | {
"start": 1438,
"end": 1524
} | class ____(RayWheelsError):
exit_code = ExitCode.CLI_ERROR
| RayWheelsUnspecifiedError |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/overloadOverlap1.py | {
"start": 6691,
"end": 6711
} | class ____(E1): ...
| E4 |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/metaclass9.py | {
"start": 118,
"end": 360
} | class ____(type):
def __new__(
cls: type[T],
cls_name: str,
bases: tuple[type, ...],
attrs: dict[str, Any],
*,
param1: int,
param2: str,
param3: str = "",
) -> T: ...
| Meta1 |
python | gevent__gevent | src/gevent/tests/test__fileobject.py | {
"start": 13757,
"end": 15018
} | class ____(ConcurrentFileObjectMixin, # pylint:disable=too-many-ancestors
TestFileObjectBlock):
def _getTargetClass(self):
return fileobject.FileObjectThread
def test_del_noclose(self):
# In the past, we used os.fdopen() when given a file descriptor,
# and th... | TestFileObjectThread |
python | kamyu104__LeetCode-Solutions | Python/maximum-subarray-sum-with-length-divisible-by-k.py | {
"start": 46,
"end": 470
} | class ____(object):
def maxSubarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
dp = [float("inf")]*k
dp[-1] = 0
curr = 0
result = float("-inf")
for i, x in enumerate(nums):
curr += x
... | Solution |
python | gevent__gevent | src/gevent/tests/lock_tests.py | {
"start": 4022,
"end": 5019
} | class ____(BaseLockTests): # pylint:disable=abstract-method
"""
Tests for non-recursive, weak locks
(which can be acquired and released from different threads).
"""
def test_reacquire(self):
# Lock needs to be released before re-acquiring.
lock = self.locktype()
phase = []
... | LockTests |
python | facebook__pyre-check | client/commands/tests/infer_test.py | {
"start": 1760,
"end": 14390
} | class ____(testslide.TestCase):
maxDiff = 2000
def test_create_infer_arguments(self) -> None:
with tempfile.TemporaryDirectory() as root:
root_path = Path(root).resolve()
setup.ensure_directories_exists(
root_path,
[".pyre", "blocks", "ignores", "... | InferTest |
python | astropy__astropy | astropy/time/formats.py | {
"start": 20694,
"end": 21080
} | class ____(TimeNumeric):
"""
Julian Date time format.
This represents the number of days since the beginning of
the Julian Period.
For example, 2451544.5 in JD is midnight on January 1, 2000.
"""
name = "jd"
def set_jds(self, val1, val2):
self._check_scale(self._scale) # Vali... | TimeJD |
python | getsentry__sentry | src/sentry/models/activity.py | {
"start": 7793,
"end": 8170
} | class ____(Enum):
"""Used in the Activity data column to define an acting integration"""
CODEOWNERS = "codeowners"
PROJECT_OWNERSHIP = "projectOwnership"
SLACK = IntegrationProviderSlug.SLACK.value
MSTEAMS = IntegrationProviderSlug.MSTEAMS.value
DISCORD = IntegrationProviderSlug.DISCORD.value
... | ActivityIntegration |
python | bokeh__bokeh | tests/unit/bokeh/models/test_ranges.py | {
"start": 6503,
"end": 9713
} | class ____:
def test_basic(self) -> None:
r = FactorRange()
check_properties_existence(r, [
"factors",
"factor_padding",
"group_padding",
"subgroup_padding",
"range_padding",
"range_padding_units",
"start",
... | Test_FactorRange |
python | encode__django-rest-framework | tests/test_serializer_lists.py | {
"start": 22680,
"end": 23588
} | class ____:
"""
Tests the behavior of ListSerializers when there is no data passed to it
"""
def setup_method(self):
class ExampleListSerializer(serializers.ListSerializer):
child = serializers.IntegerField()
self.Serializer = ExampleListSerializer
def test_nested_seri... | TestEmptyListSerializer |
python | getsentry__sentry | tests/sentry/analytics/test_event.py | {
"start": 366,
"end": 466
} | class ____(Event):
id: int
map: dict | DummyType
optional: bool | None = None
| ExampleEvent |
python | openai__gym | gym/envs/mujoco/hopper_v3.py | {
"start": 281,
"end": 5316
} | class ____(MuJocoPyEnv, utils.EzPickle):
metadata = {
"render_modes": [
"human",
"rgb_array",
"depth_array",
],
"render_fps": 125,
}
def __init__(
self,
xml_file="hopper.xml",
forward_reward_weight=1.0,
ctrl_cost_we... | HopperEnv |
python | psf__requests | src/requests/exceptions.py | {
"start": 1866,
"end": 1937
} | class ____(RequestException):
"""An HTTP error occurred."""
| HTTPError |
python | PyCQA__pylint | tests/pyreverse/functional/class_diagrams/annotations/line_breaks.py | {
"start": 62,
"end": 243
} | class ____:
p: int | None
def f(self,
x: (str | None) | (list[A] | list[int]),
y: A | (int | str) | None,
) -> int | str | list[A | int]:
pass
| A |
python | crytic__slither | slither/detectors/compiler_bugs/storage_signed_integer_array.py | {
"start": 833,
"end": 5740
} | class ____(AbstractDetector):
"""
Storage signed integer array
"""
ARGUMENT = "storage-array"
HELP = "Signed storage integer array compiler bug"
IMPACT = DetectorClassification.HIGH
CONFIDENCE = DetectorClassification.MEDIUM
WIKI = (
"https://github.com/crytic/slither/wiki/Dete... | StorageSignedIntegerArray |
python | walkccc__LeetCode | solutions/2748. Number of Beautiful Pairs/2748.py | {
"start": 0,
"end": 342
} | class ____:
def countBeautifulPairs(self, nums: list[int]) -> int:
def firstDigit(num: int) -> int:
return int(str(num)[0])
def lastDigit(num: int) -> int:
return num % 10
return sum(math.gcd(firstDigit(nums[i]), lastDigit(nums[j])) == 1
for i, j in itertools.combinations(rang... | Solution |
python | google__pytype | pytype/tools/xref/indexer_test.py | {
"start": 2006,
"end": 9370
} | class ____(test_base.BaseTest, IndexerTestMixin):
"""Tests for the indexer."""
def test_param_reuse(self):
ix = self.index_code("""
def f(x):
x = 1 # reuse param variable
""".lstrip("\n"))
self.assertDef(ix, "module.f", "f", "FunctionDef")
self.assertDef(ix, "module.f.x", "x", "Pa... | IndexerTest |
python | tensorflow__tensorflow | tensorflow/python/keras/optimizer_v1.py | {
"start": 23136,
"end": 26784
} | class ____(Optimizer):
"""Nesterov Adam optimizer.
Much like Adam is essentially RMSprop with momentum,
Nadam is Adam RMSprop with Nesterov momentum.
Default parameters follow those provided in the paper.
It is recommended to leave the parameters of this optimizer
at their default values.
Args:
lr:... | Nadam |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/compute_ssh.py | {
"start": 1865,
"end": 2813
} | class ____(paramiko.SSHClient):
"""SSH Client that maintains the context for gcloud authorization during the connection."""
def __init__(self, google_hook, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ssh_client = paramiko.SSHClient()
self.google_hook = google_hook
s... | _GCloudAuthorizedSSHClient |
python | django-compressor__django-compressor | compressor/filters/cssmin/__init__.py | {
"start": 340,
"end": 558
} | class ____(CallbackOutputFilter):
callback = "rcssmin.cssmin"
dependencies = ["rcssmin"]
kwargs = {"keep_bang_comments": True}
# This is for backwards compatibility.
CSSMinFilter = rCSSMinFilter
| rCSSMinFilter |
python | huggingface__transformers | src/transformers/models/donut/modeling_donut_swin.py | {
"start": 12415,
"end": 15441
} | class ____(nn.Module):
"""
Patch Merging Layer.
Args:
input_resolution (`tuple[int]`):
Resolution of input feature.
dim (`int`):
Number of input channels.
norm_layer (`nn.Module`, *optional*, defaults to `nn.LayerNorm`):
Normalization layer class.... | DonutSwinPatchMerging |
python | doocs__leetcode | solution/0600-0699/0638.Shopping Offers/Solution.py | {
"start": 0,
"end": 737
} | class ____:
def shoppingOffers(
self, price: List[int], special: List[List[int]], needs: List[int]
) -> int:
@cache
def dfs(cur: int) -> int:
ans = sum(p * (cur >> (i * bits) & 0xF) for i, p in enumerate(price))
for offer in special:
nxt = cur
... | Solution |
python | spack__spack | lib/spack/spack/vendor/jinja2/loaders.py | {
"start": 14242,
"end": 15051
} | class ____(BaseLoader):
"""Loads a template from a Python dict mapping template names to
template source. This loader is useful for unittesting:
>>> loader = DictLoader({'index.html': 'source here'})
Because auto reloading is rarely useful this is disabled per default.
"""
def __init__(self,... | DictLoader |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 62522,
"end": 63817
} | class ____(fixtures.TestBase):
__only_on__ = "postgresql"
__backend__ = True
def test_reflection(self, metadata, connection):
t1 = Table(
"t1",
metadata,
Column("c1", postgresql.TIME()),
Column("c2", postgresql.TIME(precision=5)),
Column("... | TimePrecisionTest |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_float.py | {
"start": 3291,
"end": 3329
} | class ____(float):
pass
| FloatSubclass |
python | huggingface__transformers | src/transformers/models/longt5/modeling_longt5.py | {
"start": 74435,
"end": 81429
} | class ____(LongT5PreTrainedModel):
_keys_to_ignore_on_load_unexpected = [
r"decoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weight",
]
_tied_weights_keys = {
"encoder.embed_tokens.weight": "shared.weight",
"decoder.embed_tokens.weight": "shared.weight",
}
def... | LongT5Model |
python | django__django | tests/many_to_one/models.py | {
"start": 2789,
"end": 2878
} | class ____(models.Model):
category = models.ForeignKey(Category, models.CASCADE)
| Record |
python | paramiko__paramiko | paramiko/pipe.py | {
"start": 3197,
"end": 3902
} | class ____:
def __init__(self, pipe):
self._set = False
self._partner = None
self._pipe = pipe
def set(self):
self._set = True
if not self._partner._set:
self._pipe.set()
def clear(self):
self._set = False
if not self._partner._set:
... | OrPipe |
python | skorch-dev__skorch | skorch/tests/test_history.py | {
"start": 14041,
"end": 18572
} | class ____:
"""Testing DistributedHistory with multiprocessing
This is not a proper test for how DistributedHistory should be used in the
wild, which would be in a multi-GPU setting using DDP (possibly through
accelerate). However, since we cannot test this setting in CI, this is the
next best appr... | TestDistributedHistoryMultiprocessing |
python | pypa__warehouse | tests/unit/admin/views/test_users.py | {
"start": 844,
"end": 3775
} | class ____:
def test_no_query(self, db_request):
users = sorted(UserFactory.create_batch(30), key=lambda u: u.username.lower())
result = views.user_list(db_request)
assert result == {"users": users[:25], "query": None}
def test_with_page(self, db_request):
users = sorted(UserFa... | TestUserList |
python | Textualize__textual | docs/examples/widgets/radio_set_changed.py | {
"start": 188,
"end": 1703
} | class ____(App[None]):
CSS_PATH = "radio_set_changed.tcss"
def compose(self) -> ComposeResult:
with VerticalScroll():
with Horizontal():
with RadioSet(id="focus_me"):
yield RadioButton("Battlestar Galactica")
yield RadioButton("Dune 19... | RadioSetChangedApp |
python | getsentry__sentry | tests/sentry/incidents/endpoints/test_organization_alert_rule_details.py | {
"start": 91863,
"end": 98487
} | class ____(AlertRuleDetailsBase):
method = "delete"
def test_simple(self) -> None:
self.create_member(
user=self.user, organization=self.organization, role="owner", teams=[self.team]
)
self.login_as(self.user)
with self.feature("organizations:incidents"), outbox_run... | AlertRuleDetailsDeleteEndpointTest |
python | langchain-ai__langchain | libs/langchain/langchain_classic/agents/agent_iterator.py | {
"start": 949,
"end": 16938
} | class ____:
"""Iterator for AgentExecutor."""
def __init__(
self,
agent_executor: AgentExecutor,
inputs: Any,
callbacks: Callbacks = None,
*,
tags: list[str] | None = None,
metadata: dict[str, Any] | None = None,
run_name: str | None = None,
... | AgentExecutorIterator |
python | allegroai__clearml | clearml/utilities/locks/utils.py | {
"start": 1865,
"end": 7388
} | class ____(object):
def __init__(
self,
filename: str,
mode: str = "a",
timeout: float = DEFAULT_TIMEOUT,
check_interval: float = DEFAULT_CHECK_INTERVAL,
fail_when_locked: bool = False,
flags: int = LOCK_METHOD,
**file_open_kwargs: Any,
) -> None:
... | Lock |
python | doocs__leetcode | solution/1800-1899/1865.Finding Pairs With a Certain Sum/Solution.py | {
"start": 0,
"end": 583
} | class ____:
def __init__(self, nums1: List[int], nums2: List[int]):
self.cnt = Counter(nums2)
self.nums1 = nums1
self.nums2 = nums2
def add(self, index: int, val: int) -> None:
self.cnt[self.nums2[index]] -= 1
self.nums2[index] += val
self.cnt[self.nums2[index]] ... | FindSumPairs |
python | keon__algorithms | tests/test_array.py | {
"start": 2602,
"end": 4244
} | class ____(unittest.TestCase):
def test_flatten(self):
nested_list = [2, 1, [3, [4, 5], 6], 7, [8]]
flattened = flatten(nested_list)
self.assertEqual(flattened, [2, 1, 3, 4, 5, 6, 7, 8])
nested_list = [[3, [4, 5], 6], 7, [8]]
flattened = flatten(nested_list)
self.a... | TestFlatten |
python | pytorch__pytorch | torch/nn/modules/upsampling.py | {
"start": 298,
"end": 8335
} | class ____(Module):
r"""Upsamples a given multi-channel 1D (temporal), 2D (spatial) or 3D (volumetric) data.
The input data is assumed to be of the form
`minibatch x channels x [optional depth] x [optional height] x width`.
Hence, for spatial inputs, we expect a 4D Tensor and for volumetric inputs, we ... | Upsample |
python | Farama-Foundation__Gymnasium | gymnasium/envs/mujoco/pusher_v4.py | {
"start": 215,
"end": 2913
} | class ____(MujocoEnv, utils.EzPickle):
metadata = {
"render_modes": [
"human",
"rgb_array",
"depth_array",
"rgbd_tuple",
],
"render_fps": 20,
}
def __init__(self, **kwargs):
if mujoco.__version__ >= "3.0.0":
raise I... | PusherEnv |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 26635,
"end": 27106
} | class ____(BaseModel, extra="forbid"):
type: "DatetimeIndexType" = Field(..., description="")
is_principal: Optional[bool] = Field(
default=None,
description="If true - use this key to organize storage of the collection data. This option assumes that this key will be used in majority of filtered... | DatetimeIndexParams |
python | pytorch__pytorch | test/distributed/test_serialization.py | {
"start": 595,
"end": 5613
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
# disable debug asserts
self._old_debug = os.environ.get(DEBUG_ENV)
os.environ[DEBUG_ENV] = "0"
def tearDown(self):
if self._old_debug is not None:
os.environ[DEBUG_ENV] = self._old_debug
def... | TestSerialization |
python | numba__llvmlite | llvmlite/ir/builder.py | {
"start": 5448,
"end": 33628
} | class ____(object):
def __init__(self, block=None):
self._block = block
self._anchor = len(block.instructions) if block else 0
self.debug_metadata = None
@property
def block(self):
"""
The current basic block.
"""
return self._block
basic_block =... | IRBuilder |
python | matplotlib__matplotlib | galleries/examples/text_labels_and_annotations/line_with_text.py | {
"start": 370,
"end": 2548
} | class ____(lines.Line2D):
def __init__(self, *args, **kwargs):
# we'll update the position when the line data is set
self.text = mtext.Text(0, 0, '')
super().__init__(*args, **kwargs)
# we can't access the label attr until *after* the line is
# initiated
self.text.se... | MyLine |
python | doocs__leetcode | solution/2300-2399/2334.Subarray With Elements Greater Than Varying Threshold/Solution.py | {
"start": 0,
"end": 808
} | class ____:
def validSubarraySize(self, nums: List[int], threshold: int) -> int:
def find(x):
if p[x] != x:
p[x] = find(p[x])
return p[x]
def merge(a, b):
pa, pb = find(a), find(b)
if pa == pb:
return
p[pa] ... | Solution |
python | fluentpython__example-code-2e | 24-class-metaprog/metabunch/original/bunch_test.py | {
"start": 44,
"end": 866
} | class ____(MetaBunch):
""" A point has x and y coordinates, defaulting to 0.0,
and a color, defaulting to 'gray'—and nothing more,
except what Python and the metaclass conspire to add,
such as __init__ and __repr__
"""
x = 0.0
y = 0.0
color = 'gray'
def test_init_defaults()... | Point |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 14404,
"end": 14529
} | class ____(PydanticTypeError):
code = 'json'
msg_template = 'JSON object must be str, bytes or bytearray'
| JsonTypeError |
python | FactoryBoy__factory_boy | tests/test_django.py | {
"start": 2203,
"end": 2303
} | class ____(AbstractBaseFactory):
class Meta:
model = models.ConcreteSon
| ConcreteSonFactory |
python | bokeh__bokeh | tests/unit/bokeh/document/test_modules.py | {
"start": 1359,
"end": 4045
} | class ____:
def test_basic(self) -> None:
d = Document()
dm = bdm.DocumentModuleManager(d)
assert len(dm) == 0
# module manager should only hold a weak ref
assert len(gc.get_referrers(d)) == 0
def test_add(self) -> None:
d = Document()
dm = bdm.Document... | TestDocumentModuleManager |
python | nedbat__coveragepy | coverage/collector.py | {
"start": 920,
"end": 18541
} | class ____:
"""Collects trace data.
Creates a Tracer object for each thread, since they track stack
information. Each Tracer points to the same shared data, contributing
traced data points.
When the Collector is started, it creates a Tracer for the current thread,
and installs a function to c... | Collector |
python | spack__spack | lib/spack/spack/tokenize.py | {
"start": 797,
"end": 2653
} | class ____:
"""Represents tokens; generated from input by lexer and fed to parse()."""
__slots__ = "kind", "value", "start", "end", "subvalues"
def __init__(self, kind: TokenBase, value: str, start: int = 0, end: int = 0, **kwargs):
self.kind = kind
self.value = value
self.start = ... | Token |
python | openai__openai-python | src/openai/types/responses/response_input_item.py | {
"start": 7587,
"end": 8300
} | class ____(BaseModel):
call_id: str
"""The unique ID of the function shell tool call generated by the model."""
output: List[ResponseFunctionShellCallOutputContent]
"""
Captured chunks of stdout and stderr output, along with their associated
outcomes.
"""
type: Literal["shell_call_outp... | ShellCallOutput |
python | realpython__materials | python-all-attribute/vehicles.py | {
"start": 216,
"end": 409
} | class ____:
def start(self):
print("The truck is starting")
def drive(self):
print("The truck is driving")
def stop(self):
print("The truck is stopping")
| Truck |
python | kamyu104__LeetCode-Solutions | Python/count-substrings-divisible-by-last-digit.py | {
"start": 64,
"end": 1745
} | class ____(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
result = 0
# digit 1, 2, 5
for i in xrange(len(s)):
if s[i] in ('1', '2', '5'):
result += i+1
# digit 3, 6
remain = 0
cnt = [... | Solution |
python | astropy__astropy | astropy/table/tests/test_init_table.py | {
"start": 9194,
"end": 9710
} | class ____(TestInitFromListOfDicts):
"""Test that init from a Mapping that is not a dict subclass works"""
def _setup(self, table_type):
self.data = [DictLike(a=1, b=2, c=3), DictLike(a=3, b=4, c=5)]
self.data_ragged = [DictLike(a=1, b=2), DictLike(a=2, c=4)]
self.data_acb = [DictLike(a... | TestInitFromListOfMapping |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/oracle/types.py | {
"start": 3085,
"end": 3511
} | class ____(sqltypes.Double):
"""Implement the Oracle ``BINARY_DOUBLE`` datatype.
This datatype differs from the Oracle ``DOUBLE`` datatype in that it
delivers a true 8-byte FP value. The datatype may be combined with a
generic :class:`.Double` datatype using :meth:`.TypeEngine.with_variant`.
.. ... | BINARY_DOUBLE |
python | modin-project__modin | modin/core/execution/ray/implementations/pandas_on_ray/partitioning/partition_manager.py | {
"start": 1464,
"end": 6344
} | class ____(GenericRayDataframePartitionManager):
"""The class implements the interface in `PandasDataframePartitionManager`."""
# This object uses RayRemotePartition objects as the underlying store.
_partition_class = PandasOnRayDataframePartition
_column_partitions_class = PandasOnRayDataframeColumnPa... | PandasOnRayDataframePartitionManager |
python | getsentry__sentry | src/sentry/taskworker/task.py | {
"start": 919,
"end": 8902
} | class ____(Generic[P, R]):
def __init__(
self,
name: str,
func: Callable[P, R],
namespace: TaskNamespace,
retry: Retry | None = None,
expires: int | datetime.timedelta | None = None,
processing_deadline_duration: int | datetime.timedelta | None = None,
... | Task |
python | wandb__wandb | wandb/vendor/pygments/lexers/nimrod.py | {
"start": 467,
"end": 5174
} | class ____(RegexLexer):
"""
For `Nim <http://nim-lang.org/>`_ source code.
.. versionadded:: 1.5
"""
name = 'Nimrod'
aliases = ['nim', 'nimrod']
filenames = ['*.nim', '*.nimrod']
mimetypes = ['text/x-nim']
flags = re.MULTILINE | re.IGNORECASE | re.UNICODE
def underscorize(wor... | NimrodLexer |
python | dask__distributed | distributed/shuffle/_core.py | {
"start": 16974,
"end": 19436
} | class ____(Generic[_T_partition_id]):
run_spec: ShuffleRunSpec
participating_workers: set[str]
_archived_by: str | None = field(default=None, init=False)
_failed: bool = False
@property
def id(self) -> ShuffleId:
return self.run_spec.id
@property
def run_id(self) -> int:
... | SchedulerShuffleState |
python | apache__airflow | airflow-core/src/airflow/lineage/hook.py | {
"start": 1663,
"end": 2030
} | class ____:
"""
Holds lineage information for a single asset.
This class represents the lineage information for a single asset, including the asset itself,
the count of how many times it has been encountered, and the context in which it was encountered.
"""
asset: Asset
count: int
cont... | AssetLineageInfo |
python | marshmallow-code__marshmallow | src/marshmallow/fields.py | {
"start": 49503,
"end": 50401
} | class ____(_TemporalField[dt.date]):
"""ISO8601-formatted date string.
:param format: Either ``"iso"`` (for ISO8601) or a date format string.
If `None`, defaults to "iso".
:param kwargs: The same keyword arguments that :class:`Field` receives.
"""
#: Default error messages.
default_err... | Date |
python | run-llama__llama_index | llama-index-core/llama_index/core/response_synthesizers/generation.py | {
"start": 1001,
"end": 5977
} | class ____(BaseSynthesizer):
def __init__(
self,
llm: Optional[LLM] = None,
callback_manager: Optional[CallbackManager] = None,
prompt_helper: Optional[PromptHelper] = None,
simple_template: Optional[BasePromptTemplate] = None,
streaming: bool = False,
) -> None:
... | Generation |
python | run-llama__llama_index | llama-index-core/llama_index/core/instrumentation/events/chat_engine.py | {
"start": 69,
"end": 334
} | class ____(BaseEvent):
"""
StreamChatStartEvent.
Fired at the start of writing to the stream chat-engine queue.
"""
@classmethod
def class_name(cls) -> str:
"""Class name."""
return "StreamChatStartEvent"
| StreamChatStartEvent |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/autoVariance2.py | {
"start": 237,
"end": 304
} | class ____[T]:
left: Node[T]
right: Node[T]
value: T
| Node |
python | getsentry__sentry | src/sentry/integrations/msteams/card_builder/utils.py | {
"start": 1852,
"end": 3835
} | class ____:
MSTEAMS_CONFIGURE_URL = "/extensions/msteams/configure/?signed_params={signed_params}"
TEAM_INSTALLTION_TITLE = "Welcome to Sentry for Microsoft Teams"
TEAM_INSTALLATION_DESCRIPTION = "You can use Sentry for Microsoft Teams to get notifications that allow you to assign, ignore, or resolve direc... | InstallationMessages |
python | Lightning-AI__lightning | tests/tests_pytorch/helpers/datamodules.py | {
"start": 1925,
"end": 3576
} | class ____(LightningDataModule):
def __init__(self, sklearn_dataset, x_type, y_type, batch_size: int = 10):
if not _SKLEARN_AVAILABLE:
raise ImportError(str(_SKLEARN_AVAILABLE))
super().__init__()
self.batch_size = batch_size
self._x, self._y = sklearn_dataset
se... | SklearnDataModule |
python | google__jax | jax/_src/state/types.py | {
"start": 7452,
"end": 8299
} | class ____(Protocol):
def transform_shape(
self, shape: tuple[int | Array, ...] | None
) -> tuple[int | Array, ...] | None:
"""Transform the shape.
Can return None if the input shape is not known, but must return a concrete
result when the input shape is known.
"""
return shape
def tr... | Transform |
python | tensorflow__tensorflow | tensorflow/python/ops/variable_spec_test.py | {
"start": 1348,
"end": 11444
} | class ____(test.TestCase, parameterized.TestCase):
def test_properties(self):
spec = VariableSpec(shape=(None, None, None))
self.assertIsNone(spec.name)
self.assertAllEqual(spec.shape.as_list(), [None, None, None])
self.assertEqual(spec.dtype, dtypes.float32)
self.assertTrue(spec.trainable)
s... | VariableSpecTest |
python | getsentry__sentry | tests/sentry/incidents/endpoints/serializers/test_query_subscription.py | {
"start": 214,
"end": 2847
} | class ____(TestCase):
def test_serialize(self) -> None:
snuba_query = SnubaQuery.objects.create(
type=SnubaQuery.Type.ERROR.value,
dataset="events",
query="test query",
aggregate="count()",
time_window=60,
resolution=60,
env... | TestSnubaQuerySerializer |
python | ansible__ansible | lib/ansible/utils/_junit_xml.py | {
"start": 6451,
"end": 8671
} | class ____:
"""A collection of test suites."""
name: str | None = None
suites: list[TestSuite] = dataclasses.field(default_factory=list)
@property
def disabled(self) -> int:
"""The number of disabled test cases."""
return sum(suite.disabled for suite in self.suites)
@property... | TestSuites |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/with2.py | {
"start": 944,
"end": 1197
} | class ____:
async def __aenter__(self: _T1) -> _T1:
return self
async def test2():
a1 = Class4()
# This should generate an error because __aexit__
# needs to be used with async with.
async with a1 as foo:
pass
| Class4 |
python | kamyu104__LeetCode-Solutions | Python/minimum-time-to-remove-all-cars-containing-illegal-goods.py | {
"start": 398,
"end": 884
} | class ____(object):
def minimumTime(self, s):
"""
:type s: str
:rtype: int
"""
result, right = len(s), [0]*(len(s)+1)
for i in reversed(xrange(len(s))):
right[i] = min(right[i+1]+2*(s[i] == '1'), len(s)-i)
left = 0
result = left+right[0]
... | Solution2 |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 27974,
"end": 30537
} | class ____:
def __post_init__(self) -> None:
self.operation_name: Optional[str] = None
def get_device(self) -> Optional[torch.device]:
raise NotImplementedError
def get_origin_node(self) -> Optional[torch.fx.Node]:
assert hasattr(self, "origin_node")
return self.origin_node... | Operation |
python | huggingface__transformers | src/transformers/models/m2m_100/configuration_m2m_100.py | {
"start": 807,
"end": 7084
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`M2M100Model`]. It is used to instantiate an
M2M100 model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar config... | M2M100Config |
python | fsspec__filesystem_spec | fsspec/implementations/cached.py | {
"start": 1326,
"end": 19134
} | class ____(ChainedFileSystem):
"""Locally caching filesystem, layer over any other FS
This class implements chunk-wise local storage of remote files, for quick
access after the initial download. The files are stored in a given
directory with hashes of URLs for the filenames. If no directory is given,
... | CachingFileSystem |
python | apache__airflow | airflow-core/src/airflow/cli/cli_config.py | {
"start": 29869,
"end": 70328
} | class ____(NamedTuple):
"""ClI command with subcommands."""
name: str
help: str
subcommands: Iterable
description: str | None = None
epilog: str | None = None
CLICommand = ActionCommand | GroupCommand
ASSETS_COMMANDS = (
ActionCommand(
name="list",
help="List assets",
... | GroupCommand |
python | kamyu104__LeetCode-Solutions | Python/check-if-it-is-possible-to-split-array.py | {
"start": 55,
"end": 303
} | class ____(object):
def canSplitArray(self, nums, m):
"""
:type nums: List[int]
:type m: int
:rtype: bool
"""
return len(nums) <= 2 or any(nums[i]+nums[i+1] >= m for i in xrange(len(nums)-1))
| Solution |
python | coleifer__peewee | tests/pwiz_integration.py | {
"start": 4662,
"end": 6113
} | class ____(BasePwizTestCase):
header = ('from peewee import *\n\n'
'database = SqliteDatabase(\'peewee_test.db\')\n\n')
unknown = ('class UnknownField(object):\n'
' def __init__(self, *_, **__): pass\n\n')
basemodel = ('class BaseModel(Model):\n class Meta:\n'
... | TestPwizUnknownField |
python | getsentry__sentry | tests/sentry/search/events/test_filter.py | {
"start": 14144,
"end": 16465
} | class ____(BaseSemverConverterTest):
key = SEMVER_PACKAGE_ALIAS
def converter(self, *args, **kwargs):
return _semver_package_filter_converter(*args, **kwargs)
def test_invalid_params(self) -> None:
key = SEMVER_PACKAGE_ALIAS
filter = SearchFilter(SearchKey(key), "=", SearchValue("s... | SemverPackageFilterConverterTest |
python | sqlalchemy__sqlalchemy | test/ext/test_mutable.py | {
"start": 43051,
"end": 43175
} | class ____(MutableCompositesTest):
@classmethod
def _type_fixture(cls):
return DCPoint
| MutableDCCompositesTest |
python | numba__numba | numba/core/untyped_passes.py | {
"start": 5502,
"end": 6537
} | class ____(SSACompliantMixin, FunctionPass):
_name = "dead_branch_prune"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
"""
This prunes dead branches, a dead branch is one which is derivable as
not taken at compile time purely based on const/lite... | DeadBranchPrune |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 61738,
"end": 61931
} | class ____(_ConfigBase):
enabled: Optional[bool]
ksim: Optional[int]
dprojections: Optional[int]
repetitions: Optional[int]
MuveraConfig = _MuveraConfig
@dataclass
| _MuveraConfig |
python | python-openxml__python-docx | src/docx/oxml/section.py | {
"start": 14975,
"end": 15307
} | class ____(BaseOxmlElement):
"""``<w:sectType>`` element, defining the section start type."""
val: WD_SECTION_START | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
"w:val", WD_SECTION_START
)
# == HELPERS =======================================================================... | CT_SectType |
python | huggingface__transformers | src/transformers/models/t5gemma/modeling_t5gemma.py | {
"start": 10595,
"end": 14278
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: T5GemmaModuleConfig, layer_idx: int):
super().__init__()
self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
self.config = config... | T5GemmaSelfAttention |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 189650,
"end": 192003
} | class ____:
# verified with matlab and R
# From Demsar "Statistical Comparisons of Classifiers over Multiple Data Sets"
# 2006, Xf=9.28 (no tie handling, tie corrected Xf >=9.28)
x1 = [[0.763, 0.599, 0.954, 0.628, 0.882, 0.936, 0.661,
0.583, 0.775, 1.0, 0.94, 0.619, 0.972, 0.957],
[... | TestFriedmanChiSquare |
python | great-expectations__great_expectations | great_expectations/experimental/metric_repository/metric_list_metric_retriever.py | {
"start": 725,
"end": 9795
} | class ____(MetricRetriever):
def __init__(self, context: AbstractDataContext):
super().__init__(context=context)
self._validator: Validator | None = None
@override
def get_metrics(
self,
batch_request: BatchRequest,
metric_list: Optional[List[MetricTypes]] = None,
... | MetricListMetricRetriever |
python | miyuchina__mistletoe | test/test_block_token.py | {
"start": 26686,
"end": 28561
} | class ____(unittest.TestCase):
def setUp(self):
block_token.add_token(block_token.HtmlBlock)
self.addCleanup(block_token.reset_tokens)
def test_code_fence(self):
lines = ['```\n',
'line 1\n',
'line 2\n',
'```\n']
document = bloc... | TestLeafBlockTokenContentProperty |
python | miyuchina__mistletoe | mistletoe/contrib/scheme.py | {
"start": 1398,
"end": 1511
} | class ____(span_token.SpanToken):
parse_inner = False
def __new__(self, _):
return None
| Whitespace |
python | PrefectHQ__prefect | tests/server/services/test_loop_service.py | {
"start": 4115,
"end": 4960
} | class ____:
@pytest.mark.parametrize("sig", [signal.SIGTERM, signal.SIGINT])
async def test_can_handle_signals_to_shutdown(self, sig):
class MyService(ExampleService):
pass
service = MyService(handle_signals=True)
assert service._should_stop is False
signal.raise_sig... | TestSignalHandling |
python | milvus-io__pymilvus | pymilvus/bulk_writer/stage_file_manager.py | {
"start": 1625,
"end": 9535
} | class ____:
def __init__(
self,
cloud_endpoint: str,
api_key: str,
stage_name: str,
connect_type: ConnectType = ConnectType.AUTO,
):
"""
private preview feature. Please submit a request and contact us if you need it.
Args:
cloud_endpoi... | StageFileManager |
python | django__django | django/conf/__init__.py | {
"start": 636,
"end": 1014
} | class ____(str):
"""
String subclass which references a current settings value. It's treated as
the value in memory but serializes to a settings.NAME attribute reference.
"""
def __new__(self, value, setting_name):
return str.__new__(self, value)
def __init__(self, value, setting_name)... | SettingsReference |
python | getsentry__sentry | tests/sentry/integrations/repository/issue_alert/test_issue_alert_notification_message_repository.py | {
"start": 5385,
"end": 6613
} | class ____(BaseIssueAlertNotificationMessageRepositoryTest):
def test_simple(self) -> None:
message_identifier = "1a2b3c"
data = NewIssueAlertNotificationMessage(
rule_fire_history_id=self.rule_fire_history.id,
rule_action_uuid=str(uuid4()),
message_identifier=mes... | TestCreateNotificationMessage |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_dag_runs.py | {
"start": 4548,
"end": 6479
} | class ____:
def setup_method(self):
clear_db_runs()
def teardown_method(self):
clear_db_runs()
def test_dag_run_clear(self, client, session, dag_maker):
dag_id = "test_trigger_dag_run_clear"
run_id = "test_run_id"
with dag_maker(dag_id=dag_id, session=session, seri... | TestDagRunClear |
python | realpython__materials | python-guitar-synthesizer/source_code_final/src/digitar/stroke.py | {
"start": 205,
"end": 458
} | class ____:
direction: Direction
delay: Time
@classmethod
def down(cls, delay: Time) -> Self:
return cls(Direction.DOWN, delay)
@classmethod
def up(cls, delay: Time) -> Self:
return cls(Direction.UP, delay)
| Velocity |
python | falconry__falcon | examples/recipes/output_csv_stream_wsgi.py | {
"start": 28,
"end": 866
} | class ____:
class PseudoTextStream:
def __init__(self):
self.clear()
def clear(self):
self.result = []
def write(self, data):
self.result.append(data.encode())
def fibonacci_generator(self, n=1000):
stream = self.PseudoTextStream()
w... | Report |
python | apache__airflow | providers/elasticsearch/tests/unit/elasticsearch/hooks/test_elasticsearch.py | {
"start": 7572,
"end": 7718
} | class ____:
def __init__(self, data: dict):
self.data = data
def search(self, **kwargs):
return self.data
| MockElasticsearch |
python | pytorch__pytorch | torch/ao/nn/quantized/modules/activation.py | {
"start": 7293,
"end": 9365
} | class ____(torch.ao.nn.quantizable.MultiheadAttention):
# pyrefly: ignore [bad-override]
_FLOAT_MODULE = torch.ao.nn.quantizable.MultiheadAttention
def _get_name(self):
return "QuantizedMultiheadAttention"
@classmethod
def from_float(cls, other):
# The whole flow is float -> observ... | MultiheadAttention |
python | pytorch__pytorch | torch/nn/utils/prune.py | {
"start": 11682,
"end": 18213
} | class ____(BasePruningMethod):
"""Container holding a sequence of pruning methods for iterative pruning.
Keeps track of the order in which pruning methods are applied and handles
combining successive pruning calls.
Accepts as argument an instance of a BasePruningMethod or an iterable of
them.
... | PruningContainer |
python | huggingface__transformers | src/transformers/models/gpt_oss/modeling_gpt_oss.py | {
"start": 17846,
"end": 19729
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: GptOssConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = GptOssAttention(config=config, layer_idx=layer_idx)
self.mlp = GptOssMLP(config)
self.input_layernorm = ... | GptOssDecoderLayer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.