language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | huggingface__transformers | src/transformers/models/t5/modeling_t5.py | {
"start": 18865,
"end": 22688
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, has_relative_attention_bias=False, layer_idx: Optional[int] = None):
super().__init__()
self.is_decoder = config.is_decoder
self.layer = nn.ModuleList()
self.layer.append(
T5LayerSelfAttention(config, has_... | T5Block |
python | pytorch__pytorch | torch/_dynamo/variables/user_defined.py | {
"start": 36880,
"end": 37007
} | class ____(UserDefinedClassVariable):
@property
def fn(self):
return self.value
| UserDefinedExceptionClassVariable |
python | pandas-dev__pandas | pandas/tests/indexes/test_any_index.py | {
"start": 5041,
"end": 5535
} | class ____:
def test_argmax_axis_invalid(self, index):
# GH#23081
msg = r"`axis` must be fewer than the number of dimensions \(1\)"
with pytest.raises(ValueError, match=msg):
index.argmax(axis=1)
with pytest.raises(ValueError, match=msg):
index.argmin(axis=2)
... | TestReductions |
python | nedbat__coveragepy | tests/test_config.py | {
"start": 687,
"end": 22884
} | class ____(CoverageTest):
"""Tests of the different sources of configuration settings."""
def test_default_config(self) -> None:
# Just constructing a coverage() object gets the right defaults.
cov = coverage.Coverage()
assert not cov.config.timid
assert not cov.config.branch
... | ConfigTest |
python | TheAlgorithms__Python | data_structures/binary_tree/basic_binary_tree.py | {
"start": 700,
"end": 2678
} | class ____:
root: Node
def __iter__(self) -> Iterator[int]:
return iter(self.root)
def __len__(self) -> int:
return len(self.root)
@classmethod
def small_tree(cls) -> BinaryTree:
"""
Return a small binary tree with 3 nodes.
>>> binary_tree = BinaryTree.smal... | BinaryTree |
python | walkccc__LeetCode | solutions/2839. Check if Strings Can be Made Equal With Operations I/2839.py | {
"start": 0,
"end": 459
} | class ____:
def canBeEqual(self, s1: str, s2: str) -> bool:
def swappedStrings(s: str) -> list[str]:
chars = list(s)
return [chars,
''.join([chars[2], chars[1], chars[0], chars[3]]),
''.join([chars[0], chars[3], chars[2], chars[1]]),
''.join([chars[2], chars[3... | Solution |
python | prabhupant__python-ds | data_structures/linked_list/pair_swap.py | {
"start": 0,
"end": 428
} | class ____():
def __init__(self, val):
self.val = val
self.next = None
def pair_swap(head):
if head == None or head.next == None:
return head
root = head.next
curr = head
prev = Node(0)
while curr.next:
curr.next = curr.next.next
curr.next.next = curr
... | Node |
python | RaRe-Technologies__gensim | gensim/topic_coherence/text_analysis.py | {
"start": 4588,
"end": 6930
} | class ____(BaseAnalyzer):
"""A BaseAnalyzer that uses a Dictionary, hence can translate tokens to counts.
The standard BaseAnalyzer can only deal with token ids since it doesn't have the token2id
mapping.
Attributes
----------
relevant_words : set
Set of words that occurrences should be... | UsesDictionary |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/typing_extensions/test_backported_types.py | {
"start": 6230,
"end": 6697
} | class ____(TypedDict, total=False):
title: Required[str]
year: int
@given(from_type(OtherMovie))
def test_typeddict_required(value):
assert type(value) == dict
assert set(value).issubset({"title", "year"})
assert isinstance(value["title"], str)
if "year" in value:
assert isinstance(val... | OtherMovie |
python | run-llama__llama_index | llama-index-core/llama_index/core/tools/types.py | {
"start": 487,
"end": 594
} | class ____(BaseModel):
"""Default tool function Schema."""
input: str
@dataclass
| DefaultToolFnSchema |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/transformer.py | {
"start": 2579,
"end": 4193
} | class ____(object):
"""Templated context manager.
This class provides syntactic sugar for a stack of objects of known
type. It allows accessing attributes of the object at the top of the stack
directly against this object, which allows for very terse syntax.
For example, this code:
stack = _StateStack(... | _StateStack |
python | openai__openai-python | src/openai/types/beta/chatkit/chatkit_response_output_text.py | {
"start": 1316,
"end": 1607
} | class ____(BaseModel):
annotations: List[Annotation]
"""Ordered list of annotations attached to the response text."""
text: str
"""Assistant generated text."""
type: Literal["output_text"]
"""Type discriminator that is always `output_text`."""
| ChatKitResponseOutputText |
python | ray-project__ray | python/ray/dag/class_node.py | {
"start": 440,
"end": 3088
} | class ____(DAGNode):
"""Represents an actor creation in a Ray task DAG."""
def __init__(
self,
cls,
cls_args,
cls_kwargs,
cls_options,
other_args_to_resolve=None,
):
self._body = cls
self._last_call: Optional["ClassMethodNode"] = None
... | ClassNode |
python | django-import-export__django-import-export | tests/core/models.py | {
"start": 542,
"end": 1476
} | class ____(models.Model):
objects = AuthorManager()
name = models.CharField(max_length=100)
birthday = models.DateTimeField(default=timezone.now)
# issue 2106 - set up a name clash with admin integration form field names
resource = models.SmallIntegerField(null=True, blank=True)
def natural_k... | Author |
python | spack__spack | lib/spack/spack/vendor/attr/_make.py | {
"start": 1350,
"end": 1963
} | class ____:
"""
Sentinel class to indicate the lack of a value when ``None`` is ambiguous.
``_Nothing`` is a singleton. There is only ever one of it.
.. versionchanged:: 21.1.0 ``bool(NOTHING)`` is now False.
"""
_singleton = None
def __new__(cls):
if _Nothing._singleton is None:... | _Nothing |
python | django__django | tests/admin_views/models.py | {
"start": 26275,
"end": 26362
} | class ____(models.Model):
rname = models.CharField(max_length=20, unique=True)
| Recipe |
python | facebookresearch__faiss | tests/test_index.py | {
"start": 9235,
"end": 9758
} | class ____(unittest.TestCase):
def test_search_k1(self):
# verify codepath for k = 1 and k > 1
d = 64
nb = 0
nt = 1500
nq = 200
(xt, xb, xq) = get_dataset(d, nb, nt, nq)
miq = faiss.MultiIndexQuantizer(d, 2, 6)
miq.train(xt)
D1, I1 = miq... | TestMultiIndexQuantizer |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride1.py | {
"start": 13017,
"end": 13095
} | class ____(Generic[T]):
def method1(self, x: T) -> T:
return x
| Base7 |
python | tensorflow__tensorflow | tensorflow/python/training/basic_session_run_hooks_test.py | {
"start": 32157,
"end": 35825
} | class ____(test.TestCase):
def setUp(self):
self.model_dir = tempfile.mkdtemp()
self.graph = ops.Graph()
self.steps_per_run = 5
with self.graph.as_default():
self.scaffold = monitored_session.Scaffold()
self.global_step = training_util.get_or_create_global_step()
self.train_op = tra... | CheckpointSaverHookMultiStepTest |
python | keras-team__keras | keras/src/ops/math_test.py | {
"start": 38442,
"end": 39014
} | class ____(testing.TestCase):
def test_segment_sum_call(self):
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32)
segment_ids = np.array([0, 0, 1], dtype=np.int32)
num_segments = 2
sorted_segments = False
segment_sum_op = kmath.SegmentSum(
num_se... | SegmentSumTest |
python | huggingface__transformers | src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py | {
"start": 6379,
"end": 11251
} | class ____(ModelOutput):
r"""
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the decoder of the model.
If `past_key_values` is used only the last hidden-state of the sequences of shape `... | SeamlessM4Tv2TextToUnitOutput |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/asset_selection.py | {
"start": 35502,
"end": 35922
} | class ____(ChainedAssetSelection):
def resolve_inner(
self, asset_graph: BaseAssetGraph, allow_missing: bool
) -> AbstractSet[AssetKey]:
return {
asset_key
for asset_key in self.child.resolve_inner(asset_graph, allow_missing=allow_missing)
if asset_key in asse... | MaterializableAssetSelection |
python | gevent__gevent | src/greentest/3.10/test_httplib.py | {
"start": 1290,
"end": 2236
} | class ____:
def __init__(self, text, fileclass=io.BytesIO, host=None, port=None):
if isinstance(text, str):
text = text.encode("ascii")
self.text = text
self.fileclass = fileclass
self.data = b''
self.sendall_calls = 0
self.file_closed = False
self... | FakeSocket |
python | sympy__sympy | sympy/stats/matrix_distributions.py | {
"start": 14311,
"end": 17816
} | class ____(MatrixDistribution):
_argnames = ('location_matrix', 'scale_matrix_1', 'scale_matrix_2')
@staticmethod
def check(location_matrix, scale_matrix_1, scale_matrix_2):
if not isinstance(scale_matrix_1, MatrixSymbol):
_value_check(scale_matrix_1.is_positive_definite, "The shape "
... | MatrixNormalDistribution |
python | huggingface__transformers | src/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py | {
"start": 46276,
"end": 48854
} | class ____(XLMRobertaXLPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.roberta = XLMRobertaXLModel(config, add_pooling_layer=False)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropo... | XLMRobertaXLForTokenClassification |
python | ray-project__ray | doc/source/ray-core/doc_code/direct_transport_gloo.py | {
"start": 5668,
"end": 7175
} | class ____:
@ray.method(tensor_transport="gloo")
def random_tensor(self):
self.tensor = torch.randn(1000, 1000)
# After this function returns, Ray and this actor will both hold a
# reference to the same tensor.
return self.tensor
def increment_and_sum_stored_tensor(self):
... | MyActor |
python | PyCQA__pylint | tests/functional/u/useless/useless_parent_delegation_py38.py | {
"start": 84,
"end": 170
} | class ____:
def __init__(self, first: Any, /, second: Any) -> None:
pass
| Egg |
python | dask__dask | dask/dataframe/dask_expr/_shuffle.py | {
"start": 23604,
"end": 24755
} | class ____(Expr):
_is_length_preserving = True
def _divisions(self):
if "user_divisions" in self._parameters and self.user_divisions is not None:
return self.user_divisions
if self._npartitions_input == 1:
return (None, None)
if (
is_index_like(self.... | BaseSetIndexSortValues |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_embed_image02.py | {
"start": 315,
"end": 911
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("embed_image02.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Wo... | TestCompareXLSXFiles |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/common/parameters.py | {
"start": 2557,
"end": 3100
} | class ____(OrmClause[T], ABC):
"""Base class for path or query parameters with ORM transformation."""
def __init__(self, value: T | None = None, skip_none: bool = True) -> None:
super().__init__(value)
self.attribute: ColumnElement | InstrumentedAttribute | None = None
self.skip_none = ... | BaseParam |
python | realpython__materials | torchaudio/speech.py | {
"start": 571,
"end": 2517
} | class ____(NamedTuple):
waveform: Tensor
sample_rate: int
label: str
speaker_id: str
utterance_number: int
@property
def num_channels(self) -> int:
return self.waveform.size(0)
@property
def num_samples(self) -> int:
return self.waveform.size(1)
@property
d... | SpeechSample |
python | getsentry__sentry | src/sentry/tempest/models.py | {
"start": 420,
"end": 566
} | class ____(models.TextChoices):
ERROR = "error"
WARNING = "warning"
SUCCESS = "success"
INFO = "info"
@region_silo_model
| MessageType |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/classes5.py | {
"start": 5343,
"end": 5529
} | class ____(ParentClass3):
class Config1(ConfigBase): ...
# This should generate an error if reportIncompatibleVariableOverride
# is enabled.
class Config2: ...
| ChildClass3 |
python | kamyu104__LeetCode-Solutions | Python/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows.py | {
"start": 52,
"end": 966
} | class ____(object):
def kthSmallest(self, mat, k):
"""
:type mat: List[List[int]]
:type k: int
:rtype: int
"""
def kSmallestPairs(nums1, nums2, k):
result, min_heap = [], []
for c in xrange(min(len(nums1), k)):
heapq.heappush(mi... | Solution |
python | doocs__leetcode | solution/0100-0199/0100.Same Tree/Solution2.py | {
"start": 192,
"end": 954
} | class ____:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
if p == q:
return True
if p is None or q is None:
return False
q1, q2 = deque([p]), deque([q])
while q1 and q2:
a, b = q1.popleft(), q2.popleft()
if a.val != b.val:
... | Solution |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/settings.py | {
"start": 21492,
"end": 21885
} | class ____:
save_steps: int = 20000
team_change: int = attr.ib()
@team_change.default
def _team_change_default(self):
# Assign team_change to about 4x save_steps
return self.save_steps * 5
swap_steps: int = 2000
window: int = 10
play_against_latest_model_ratio: float = 0.5
... | SelfPlaySettings |
python | mlflow__mlflow | mlflow/store/model_registry/base_rest_store.py | {
"start": 191,
"end": 1341
} | class ____(AbstractStore):
"""
Base class client for a remote model registry server accessed via REST API calls
"""
__metaclass__ = ABCMeta
def __init__(self, get_host_creds):
super().__init__()
self.get_host_creds = get_host_creds
@abstractmethod
def _get_all_endpoints_fr... | BaseRestStore |
python | pytest-dev__pytest | testing/test_skipping.py | {
"start": 23893,
"end": 27263
} | class ____:
def test_skip_class(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.mark.skip
class TestSomething(object):
def test_foo(self):
pass
def test_bar(self):
... | TestSkip |
python | ray-project__ray | python/ray/tests/gcp/test_gcp_tpu_command_runner.py | {
"start": 504,
"end": 9501
} | class ____:
def __init__(self, num_workers: int = 1):
self.num_workers = num_workers
def get_internal_ip(self, worker_index: int) -> str:
return "0.0.0.0"
def get_external_ip(self, worker_index: int) -> str:
return "1.2.3.4"
def get(self, key) -> str:
if key == "name":... | MockTpuInstance |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/runs.py | {
"start": 4937,
"end": 5122
} | class ____(graphene.Union):
class Meta:
types = (GrapheneRunGroup, GrapheneRunGroupNotFoundError, GraphenePythonError)
name = "RunGroupOrError"
| GrapheneRunGroupOrError |
python | getsentry__sentry | tests/snuba/tsdb/test_tsdb_backend.py | {
"start": 1937,
"end": 21611
} | class ____(TestCase, SnubaTestCase):
def setUp(self) -> None:
super().setUp()
self.db = SnubaTSDB()
self.now = before_now(hours=4).replace(hour=0, minute=0, second=0, microsecond=0)
self.proj1 = self.create_project()
env1 = "test"
env2 = "dev"
defaultenv = ""... | SnubaTSDBTest |
python | huggingface__transformers | src/transformers/models/modernbert/modeling_modernbert.py | {
"start": 55895,
"end": 60067
} | class ____(ModernBertPreTrainedModel):
def __init__(self, config: ModernBertConfig):
super().__init__(config)
self.num_labels = config.num_labels
self.model = ModernBertModel(config)
self.head = ModernBertPredictionHead(config)
self.drop = torch.nn.Dropout(config.classifier_... | ModernBertForTokenClassification |
python | scrapy__scrapy | tests/test_exporters.py | {
"start": 904,
"end": 1025
} | class ____:
name: str
age: int = dataclasses.field(metadata={"serializer": custom_serializer})
| CustomFieldDataclass |
python | redis__redis-py | tests/test_maint_notifications_handling.py | {
"start": 6862,
"end": 15833
} | class ____:
"""Mock socket that simulates Redis protocol responses."""
def __init__(self):
self.connected = False
self.address = None
self.sent_data = []
self.closed = False
self.command_count = 0
self.pending_responses = []
# Track socket timeout changes... | MockSocket |
python | getsentry__sentry | src/sentry/conf/types/logging_config.py | {
"start": 170,
"end": 258
} | class ____(_DictConfigArgs):
default_level: str
overridable: list[str]
| LoggingConfig |
python | Lightning-AI__lightning | src/lightning/pytorch/loops/progress.py | {
"start": 2146,
"end": 3008
} | class ____(_ReadyCompletedTracker):
"""Track an event's progress.
Args:
ready: Intended to track the number of events ready to start.
started: Intended to be incremented after the event is started (e.g. after ``on_*_start`` runs).
completed: Intended to be incremented after the event co... | _StartedTracker |
python | PrefectHQ__prefect | tests/test_flow_engine.py | {
"start": 2624,
"end": 3570
} | class ____:
def test_basic_init(self):
engine = AsyncFlowRunEngine(flow=foo)
assert isinstance(engine.flow, Flow)
assert engine.flow.name == "foo"
assert engine.parameters == {}
def test_empty_init(self):
with pytest.raises(
TypeError, match="missing 1 requir... | TestAsyncFlowRunEngine |
python | ray-project__ray | python/ray/runtime_env/types/pip.py | {
"start": 71,
"end": 134
} | class ____:
packages: List[str]
pip_check: bool = False
| Pip |
python | jazzband__django-waffle | waffle/migrations/0002_auto_20161201_0958.py | {
"start": 92,
"end": 413
} | class ____(migrations.Migration):
dependencies = [
('waffle', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='switch',
name='active',
field=models.BooleanField(default=False, help_text='Is this switch active?'),
),
]
| Migration |
python | donnemartin__interactive-coding-challenges | arrays_strings/priority_queue/priority_queue.py | {
"start": 206,
"end": 932
} | class ____(object):
def __init__(self):
self.array = []
def __len__(self):
return len(self.array)
def insert(self, node):
self.array.append(node)
return self.array[-1]
def extract_min(self):
if not self.array:
return None
minimum = sys.maxs... | PriorityQueue |
python | wandb__wandb | wandb/sdk/launch/inputs/internal.py | {
"start": 2089,
"end": 9807
} | class ____:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = object.__new__(cls)
return cls._instance
def __init__(self) -> None:
if not hasattr(self, "_staged_inputs"):
self._staged_inputs: List[JobInputArguments] = []
def a... | StagedLaunchInputs |
python | PrefectHQ__prefect | src/prefect/blocks/notifications.py | {
"start": 2482,
"end": 3908
} | class ____(AbstractAppriseNotificationBlock, ABC):
"""
A base class for sending notifications using Apprise, through webhook URLs.
"""
_documentation_url = HttpUrl(
"https://docs.prefect.io/latest/automate/events/automations-triggers#sending-notifications-with-automations"
)
url: Secret... | AppriseNotificationBlock |
python | tensorflow__tensorflow | tensorflow/python/framework/convert_to_constants.py | {
"start": 14628,
"end": 16573
} | class ____(_Node):
"""Specialization of _Node to ResourceGather."""
def convert_variable_to_constant(self, incoming_edge, tensor_data):
# We currently skip the conversion if this is inside a function.
if self._function is not None:
return
if self._node.attr["batch_dims"].i != 0:
raise Value... | _ResourceGather |
python | ipython__ipython | tests/test_interactiveshell.py | {
"start": 22919,
"end": 24395
} | class ____(ExitCodeChecks):
def setUp(self):
super().setUp()
self.system = ip.system_raw
@onlyif_unicode_paths
def test_1(self):
"""Test system_raw with non-ascii cmd"""
cmd = """python -c "'åäö'" """
ip.system_raw(cmd)
@mock.patch("subprocess.call", side_effe... | TestSystemRaw |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py | {
"start": 157485,
"end": 163852
} | class ____(Qwen2_5OmniPreTrainedModel):
config: Qwen2_5OmniDiTConfig
input_modalities = "audio"
_no_split_modules = ["DiTDecoderLayer"]
def __init__(self, config: Qwen2_5OmniDiTConfig):
super().__init__(config)
self.mel_dim = config.mel_dim
self.repeats = config.repeats
... | Qwen2_5OmniToken2WavDiTModel |
python | pandas-dev__pandas | pandas/core/indexes/timedeltas.py | {
"start": 1378,
"end": 12362
} | class ____(DatetimeTimedeltaMixin):
"""
Immutable Index of timedelta64 data.
Represented internally as int64, and scalars returned Timedelta objects.
Parameters
----------
data : array-like (1-dimensional), optional
Optional timedelta-like data to construct index with.
freq : str o... | TimedeltaIndex |
python | pypa__warehouse | tests/unit/api/test_simple.py | {
"start": 1037,
"end": 2592
} | class ____:
@pytest.mark.parametrize("header", [None, "text/plain"])
def test_defaults_text_html(self, header):
"""
Ensures that, at least until we want to change the default, that we
default to text/html.
"""
request = DummyRequest(accept=header)
assert simple._s... | TestContentNegotiation |
python | apache__airflow | airflow-core/src/airflow/models/callback.py | {
"start": 8606,
"end": 9507
} | class ____(Callback):
"""Callbacks that run on the executor."""
__mapper_args__ = {"polymorphic_identity": CallbackType.EXECUTOR}
def __init__(
self, callback_def: ImportPathExecutorCallbackDefProtocol, fetch_method: CallbackFetchMethod, **kwargs
):
"""
Initialize an ExecutorCa... | ExecutorCallback |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_inlinehilite.py | {
"start": 17219,
"end": 17936
} | class ____(util.MdCase):
"""Test custom broken InlineHilite cases fails."""
extension = [
'pymdownx.highlight',
'pymdownx.inlinehilite',
]
extension_configs = {
'pymdownx.inlinehilite': {
'custom_inline': [
{
'name': 'test',
... | TestInlineHiliteCustomBrokenFormatterFail |
python | google__jax | jax/_src/core.py | {
"start": 3321,
"end": 8218
} | class ____:
__slots__ = ['__weakref__', '_constvars', '_invars', '_outvars', '_eqns',
'_effects', '_debug_info', '_is_high']
_constvars: list[Var]
_invars: list[Var]
_outvars: list[Atom]
_eqns: list[JaxprEqn]
_effects: Effects
_debug_info: DebugInfo
_is_high: bool
@property
def cons... | Jaxpr |
python | Netflix__metaflow | metaflow/plugins/cards/card_modules/basic.py | {
"start": 4889,
"end": 5432
} | class ____(DefaultComponent):
type = "image"
def __init__(self, src=None, label=None, title=None, subtitle=None):
super().__init__(title=title, subtitle=subtitle)
self._src = src
self._label = label
def render(self):
datadict = super().render()
img_dict = dict(
... | ImageComponent |
python | google__pytype | pytype/pytd/visitors_test.py | {
"start": 541,
"end": 34881
} | class ____(parser_test_base.ParserTest):
"""Tests the classes in parse/visitors."""
def test_lookup_classes(self):
src = textwrap.dedent("""
from typing import Union
class object:
pass
class A:
def a(self, a: A, b: B) -> Union[A, B]:
raise A()
... | TestVisitors |
python | kamyu104__LeetCode-Solutions | Python/shopping-offers.py | {
"start": 35,
"end": 892
} | class ____(object):
def shoppingOffers(self, price, special, needs):
"""
:type price: List[int]
:type special: List[List[int]]
:type needs: List[int]
:rtype: int
"""
def shoppingOffersHelper(price, special, needs, i):
if i == len(special):
... | Solution |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0020_add-api-project-proxy.py | {
"start": 120,
"end": 492
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0019_add-features"),
]
operations = [
migrations.CreateModel(
name="APIProject",
fields=[],
options={
"proxy": True,
},
... | Migration |
python | huggingface__transformers | tests/trainer/test_trainer_distributed_worker_seed.py | {
"start": 1455,
"end": 2640
} | class ____(TestCasePlus):
@run_first
@require_torch_multi_accelerator
def test_trainer(self):
device_count = backend_device_count(torch_device)
output_dir = self.get_auto_remove_tmp_dir()
distributed_args = f"""--nproc_per_node={device_count}
--master_port={get_torch_dist... | TestTrainerDistributedWorkerSeed |
python | getsentry__sentry | tests/sentry/uptime/subscriptions/test_tasks.py | {
"start": 10602,
"end": 11949
} | class ____(BaseUptimeSubscriptionTaskTest):
expected_status = UptimeSubscription.Status.DELETING
task = delete_remote_uptime_subscription
def test(self) -> None:
subscription_id = uuid4().hex
sub = self.create_subscription(
UptimeSubscription.Status.DELETING, subscription_id=sub... | DeleteUptimeSubscriptionTaskTest |
python | pytorch__pytorch | torch/distributions/dirichlet.py | {
"start": 1100,
"end": 4561
} | class ____(ExponentialFamily):
r"""
Creates a Dirichlet distribution parameterized by concentration :attr:`concentration`.
Example::
>>> # xdoctest: +IGNORE_WANT("non-deterministic")
>>> m = Dirichlet(torch.tensor([0.5, 0.5]))
>>> m.sample() # Dirichlet distributed with concentrat... | Dirichlet |
python | django__django | django/contrib/admin/options.py | {
"start": 90537,
"end": 99579
} | class ____(BaseModelAdmin):
"""
Options for inline editing of ``model`` instances.
Provide ``fk_name`` to specify the attribute name of the ``ForeignKey``
from ``model`` to its parent. This is required if ``model`` has more than
one ``ForeignKey`` to its parent.
"""
model = None
fk_nam... | InlineModelAdmin |
python | PyCQA__pylint | doc/data/messages/d/duplicate-code/good/orange.py | {
"start": 26,
"end": 214
} | class ____(Fruit):
def eaten_by_animal(self, animal):
if animal == "cat":
raise ValueError("A cat would never do that !")
super().eaten_by_animal(animal)
| Orange |
python | getsentry__sentry | src/sentry/api/serializers/models/team.py | {
"start": 11086,
"end": 11796
} | class ____(BaseTeamSerializer):
def serialize(
self,
obj: Team,
attrs: Mapping[str, Any],
user: User | RpcUser | AnonymousUser,
**kwargs: Any,
) -> TeamSerializerResponse:
result = super().serialize(obj, attrs, user, **kwargs)
opt: _TeamSerializerResponse... | TeamSerializer |
python | python__mypy | mypy/main.py | {
"start": 8252,
"end": 9647
} | class ____(argparse.RawDescriptionHelpFormatter):
def __init__(self, prog: str, **kwargs: Any) -> None:
super().__init__(prog=prog, max_help_position=28, **kwargs)
def _fill_text(self, text: str, width: int, indent: str) -> str:
if "\n" in text:
# Assume we want to manually format t... | AugmentedHelpFormatter |
python | ray-project__ray | python/ray/autoscaler/v2/tests/util.py | {
"start": 3893,
"end": 4056
} | class ____(abc.ABC):
@abstractmethod
def check(self, status: ClusterStatus):
pass
def __repr__(self) -> str:
return self.__str__()
| Check |
python | getlogbook__logbook | src/logbook/base.py | {
"start": 9692,
"end": 10402
} | class ____(ContextObject):
"""Can be pushed to a stack to inject additional information into
a log record as necessary::
def inject_ip(record):
record.extra["ip"] = "127.0.0.1"
with Processor(inject_ip):
...
"""
stack_manager = ContextStackManager()
def _... | Processor |
python | django__django | tests/auth_tests/test_hashers.py | {
"start": 30585,
"end": 33598
} | class ____(SimpleTestCase):
def test_scrypt(self):
encoded = make_password("lètmein", "seasalt", "scrypt")
self.assertEqual(
encoded,
"scrypt$16384$seasalt$8$5$ECMIUp+LMxMSK8xB/IVyba+KYGTI7FTnet025q/1f"
"/vBAVnnP3hdYqJuRi+mJn6ji6ze3Fbb7JEFPKGpuEf5vw==",
)
... | TestUtilsHashPassScrypt |
python | google__pytype | build_scripts/build_utils.py | {
"start": 5329,
"end": 8774
} | class ____:
"""A class to collect failures."""
def __init__(self):
self._failures = []
def add_failure(self, mod_name, log_file):
self._failures.append((mod_name, log_file))
def print_report(self, verbose):
num_failures = len(self._failures)
if num_failures == 0:
return
print("\n%d ... | FailCollector |
python | zarr-developers__zarr-python | src/zarr/core/indexing.py | {
"start": 25490,
"end": 31068
} | class ____:
"""Integer array selection against a single dimension."""
dim_len: int
dim_chunk_len: int
nchunks: int
nitems: int
order: Order
dim_sel: npt.NDArray[np.intp]
dim_out_sel: npt.NDArray[np.intp]
chunk_nitems: int
dim_chunk_ixs: npt.NDArray[np.intp]
chunk_nitems_cums... | IntArrayDimIndexer |
python | kamyu104__LeetCode-Solutions | Python/cat-and-mouse.py | {
"start": 54,
"end": 1767
} | class ____(object):
def catMouseGame(self, graph):
"""
:type graph: List[List[int]]
:rtype: int
"""
HOLE, MOUSE_START, CAT_START = range(3)
DRAW, MOUSE, CAT = range(3)
def parents(m, c, t):
if t == CAT:
for nm in graph[m]:
... | Solution |
python | etianen__django-reversion | tests/test_app/tests/test_commands.py | {
"start": 3773,
"end": 4021
} | class ____(TestModelMixin, TestBase):
def testDeleteRevisions(self):
with reversion.create_revision():
TestModel.objects.create()
self.callCommand("deleterevisions")
self.assertNoRevision()
| DeleteRevisionsTest |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/executor/multiprocess.py | {
"start": 2321,
"end": 4783
} | class ____(ChildProcessCommand):
def __init__(
self,
run_config: Mapping[str, object],
dagster_run: "DagsterRun",
step_key: str,
instance_ref: "InstanceRef",
term_event: Any,
recon_pipeline: ReconstructableJob,
retry_mode: RetryMode,
known_stat... | MultiprocessExecutorChildProcessCommand |
python | sympy__sympy | sympy/integrals/manualintegrate.py | {
"start": 16193,
"end": 16475
} | class ____(OrthogonalPolyRule):
def eval(self) -> Expr:
n, x = self.n, self.variable
return Piecewise(
((chebyshevt(n + 1, x)/(n + 1) -
chebyshevt(n - 1, x)/(n - 1))/2, Ne(Abs(n), 1)),
(x**2/2, True))
@dataclass
| ChebyshevTRule |
python | milvus-io__pymilvus | pymilvus/exceptions.py | {
"start": 3842,
"end": 11374
} | class ____:
NoHostPort = "connection configuration must contain 'host' and 'port'."
HostType = "Type of 'host' must be str."
PortType = "Type of 'port' must be str or int."
ConnDiffConf = (
"Alias of %r already creating connections, "
"but the configure is not the same as passed in."
... | ExceptionsMessage |
python | pytorch__pytorch | test/dynamo/test_reconstruct.py | {
"start": 495,
"end": 14056
} | class ____(torch._dynamo.test_case.TestCase):
@contextlib.contextmanager
def register_bytecode_hook(self, fn):
def hook(code, out_code):
fn(list(dis.get_instructions(out_code)))
return None
torch._dynamo.reset()
handle = torch._dynamo.convert_frame.register_bytec... | ReconstructTest |
python | dask__distributed | distributed/versions.py | {
"start": 4422,
"end": 4512
} | class ____(Warning):
"""Indicates version mismatch between nodes"""
| VersionMismatchWarning |
python | vyperlang__vyper | vyper/evm/assembler/instructions.py | {
"start": 3087,
"end": 3565
} | class ____:
def __init__(self, label: Label):
assert isinstance(label, Label), label
self.label = label
def __repr__(self):
return f"PUSHLABEL {self.label.label}"
def __eq__(self, other):
if not isinstance(other, PUSHLABEL):
return False
return self.labe... | PUSHLABEL |
python | getsentry__sentry | tests/sentry/rules/conditions/test_reappeared_event.py | {
"start": 209,
"end": 513
} | class ____(RuleTestCase):
rule_cls = ReappearedEventCondition
def test_applies_correctly(self) -> None:
rule = self.get_rule()
self.assertPasses(rule, self.event, has_escalated=True)
self.assertDoesNotPass(rule, self.event, has_escalated=False)
| ReappearedEventConditionTest |
python | plotly__plotly.py | plotly/graph_objs/_surface.py | {
"start": 215,
"end": 79001
} | class ____(_BaseTraceType):
_parent_path_str = ""
_path_str = "surface"
_valid_props = {
"autocolorscale",
"cauto",
"cmax",
"cmid",
"cmin",
"coloraxis",
"colorbar",
"colorscale",
"connectgaps",
"contours",
"customdata",
... | Surface |
python | python__mypy | mypyc/irbuild/for_helpers.py | {
"start": 44966,
"end": 48489
} | class ____(ForGenerator):
"""Generate IR for a for loop of form `for x, ... in zip(a, ...)`."""
def need_cleanup(self) -> bool:
# The wrapped for loops might need cleanup. We might generate a
# redundant cleanup block, but that's okay.
return True
def init(self, indexes: list[Lvalu... | ForZip |
python | gabrielfalcao__HTTPretty | httpretty/errors.py | {
"start": 1322,
"end": 2168
} | class ____(HTTPrettyError):
def __init__(self, message='Failed to handle network request', request=None, address=None):
hint = 'Tip: You could try setting (allow_net_connect=True) to allow unregistered requests through a real TCP connection in addition to (verbose=True) to debug the issue.'
if reque... | UnmockedError |
python | pypa__virtualenv | src/virtualenv/activation/bash/__init__.py | {
"start": 132,
"end": 648
} | class ____(ViaTemplateActivator):
def templates(self):
yield "activate.sh"
def as_name(self, template):
return Path(template).stem
def replacements(self, creator, dest):
data = super().replacements(creator, dest)
data.update({
"__TCL_LIBRARY__": getattr(creator.... | BashActivator |
python | fastai__fastai | fastai/callback/hook.py | {
"start": 4195,
"end": 9220
} | class ____(Callback):
"`Callback` that can be used to register hooks on `modules`"
_methods = ["hook"]
hook = noops
def __init__(self, modules=None, every=None, remove_end=True, is_forward=True, detach=True, cpu=True, include_paramless=False , **kwargs):
store_attr('modules,every,remove_end,is_f... | HookCallback |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/guides/operate/configuration/run_config/asset_example/resources.py | {
"start": 23,
"end": 208
} | class ____(dg.Config):
person_name: str
@dg.definitions
def resources() -> dg.Definitions:
return dg.Definitions(resources={"config": MyAssetConfig(person_name="")})
| MyAssetConfig |
python | pydata__xarray | xarray/coding/variables.py | {
"start": 23292,
"end": 24699
} | class ____(VariableCoder):
"""Encode NonString variables if dtypes differ."""
def encode(self, variable: Variable, name: T_Name = None) -> Variable:
if "dtype" in variable.encoding and variable.encoding["dtype"] not in (
"S1",
str,
):
dims, data, attrs, encod... | NonStringCoder |
python | getsentry__sentry | src/sentry/api/endpoints/organization_events_vitals.py | {
"start": 584,
"end": 4262
} | class ____(OrganizationEventsV2EndpointBase):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
VITALS = {
"measurements.lcp": {"thresholds": [0, 2500, 4000]},
"measurements.fid": {"thresholds": [0, 100, 300]},
"measurements.cls": {"thresholds": [0, 0.1, 0.25]},
"... | OrganizationEventsVitalsEndpoint |
python | spyder-ide__spyder | spyder/plugins/variableexplorer/widgets/importwizard.py | {
"start": 15685,
"end": 17686
} | class ____(QWidget):
"""Import wizard preview widget"""
def __init__(self, parent):
QWidget.__init__(self, parent)
vert_layout = QVBoxLayout()
# Type frame
type_layout = QHBoxLayout()
type_label = QLabel(_("Import as"))
type_layout.addWidget(type_label)
... | PreviewWidget |
python | pydata__xarray | xarray/namedarray/_typing.py | {
"start": 5057,
"end": 5833
} | class ____(_array[_ShapeType_co, _DType_co], Protocol[_ShapeType_co, _DType_co]):
"""
Duck array supporting NEP 47.
Corresponds to np.ndarray.
"""
def __getitem__(
self,
key: (
_IndexKeyLike | Any
), # TODO: Any should be _arrayapi[Any, _dtype[np.integer]]
... | _arrayapi |
python | explosion__spaCy | spacy/lang/th/__init__.py | {
"start": 468,
"end": 1090
} | class ____(DummyTokenizer):
def __init__(self, vocab: Vocab) -> None:
try:
from pythainlp.tokenize import word_tokenize
except ImportError:
raise ImportError(
"The Thai tokenizer requires the PyThaiNLP library: "
"https://github.com/PyThaiNLP/p... | ThaiTokenizer |
python | tensorflow__tensorflow | tensorflow/python/saved_model/model_utils/export_output.py | {
"start": 1077,
"end": 3249
} | class ____:
"""Represents an output of a model that can be served.
These typically correspond to model heads.
"""
__metaclass__ = abc.ABCMeta
_SEPARATOR_CHAR = '/'
@abc.abstractmethod
def as_signature_def(self, receiver_tensors):
"""Generate a SignatureDef proto for inclusion in a MetaGraphDef.
... | ExportOutput |
python | readthedocs__readthedocs.org | readthedocs/invitations/models.py | {
"start": 2627,
"end": 7257
} | class ____(TimeStampedModel):
"""
Invitation model.
An invitation can be attached to an existing user or to an email.
"""
# Generic foreign key.
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
object = GenericForeignKey(... | Invitation |
python | coleifer__peewee | tests/models.py | {
"start": 86076,
"end": 91689
} | class ____(ModelTestCase):
requires = [User, Tweet]
def setUp(self):
super(TestForUpdateIntegration, self).setUp()
self.alt_db = new_connection()
class AltUser(User):
class Meta:
database = self.alt_db
table_name = User._meta.table_name
... | TestForUpdateIntegration |
python | sqlalchemy__sqlalchemy | test/dialect/oracle/test_reflection.py | {
"start": 2200,
"end": 12118
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
__only_on__ = "oracle"
__sparse_driver_backend__ = True
@classmethod
def setup_test_class(cls):
# currently assuming full DBA privs for the user.
# don't really know how else to go here unless
# we connect as the other user.
... | MultiSchemaTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.