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 | bokeh__bokeh | src/bokeh/models/transforms.py | {
"start": 7975,
"end": 8309
} | class ____(Interpolator):
''' Compute a linear interpolation between the control points provided through
the ``x``, ``y``, and ``data`` parameters.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
| LinearInterpolator |
python | gevent__gevent | src/gevent/tests/test__socket_dns.py | {
"start": 33589,
"end": 34172
} | class ____(TestCase):
def test(self):
self._test('getnameinfo', ('127.0.0.1', 80), 0)
def test_DGRAM(self):
self._test('getnameinfo', ('127.0.0.1', 779), 0)
self._test('getnameinfo', ('127.0.0.1', 779), socket.NI_DGRAM)
def test_NOFQDN(self):
# I get ('localhost', 'www') w... | Test_getnameinfo_127001 |
python | python__mypy | test-data/unit/plugins/descriptor.py | {
"start": 200,
"end": 1352
} | class ____(Plugin):
def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:
if fullname == "__main__.Desc.__get__":
return get_hook
return None
def get_method_signature_hook(
self, fullname: str
) -> Callable[[MethodSigContext], CallableType] ... | DescriptorPlugin |
python | numba__numba | numba/cuda/deviceufunc.py | {
"start": 10835,
"end": 13132
} | class ____(_BaseUFuncBuilder):
def __init__(self, func, identity=None, cache=False, targetoptions=None):
if targetoptions is None:
targetoptions = {}
if cache:
raise TypeError("caching is not supported")
for opt in targetoptions:
if opt == 'nopython':
... | DeviceVectorize |
python | davidhalter__jedi | test/completion/recursion.py | {
"start": 801,
"end": 1240
} | class ____:
def b(self):
self.a1 = 1
self.a2 = 1
def c(self):
self.a2 = ''
def x(self):
self.b()
if self.a1 == 1:
self.a1 = self.a1 + 1
if self.a2 == UNDEFINED:
self.a2 = self.a2 + 1
#? int()
self.a1
#? int()... | InstanceAttributeIfs |
python | mwaskom__seaborn | tests/test_relational.py | {
"start": 1167,
"end": 1782
} | class ____:
@pytest.fixture
def levels(self, long_df):
return {var: categorical_order(long_df[var]) for var in ["a", "b"]}
def scatter_rgbs(self, collections):
rgbs = []
for col in collections:
rgb = tuple(col.get_facecolor().squeeze()[:3])
rgbs.append(rgb)
... | Helpers |
python | Lightning-AI__lightning | tests/tests_pytorch/callbacks/test_model_checkpoint_manual_opt.py | {
"start": 312,
"end": 883
} | class ____(Dataset):
def __init__(self):
self.data = [torch.randn(3) for _ in range(4)]
self.labels = [torch.randint(0, 2, (1,)) for _ in range(4)]
def __len__(self):
return 4
def __getitem__(self, idx):
return self.data[idx], self.labels[idx]
def save_model(model: torch.... | FakeDataset |
python | walkccc__LeetCode | solutions/2868. The Wording Game/2868.py | {
"start": 0,
"end": 1168
} | class ____:
def canAliceWin(self, a: list[str], b: list[str]) -> bool:
# words[0][i] := the biggest word starting with ('a' + i) for Alice
# words[1][i] := the biggest word starting with ('a' + i) for Bob
words = [[''] * 26 for _ in range(2)]
# For each letter, only the biggest word is useful.
fo... | Solution |
python | pytorch__pytorch | torch/_inductor/codegen/cutedsl/cutedsl_scheduling.py | {
"start": 666,
"end": 5310
} | class ____(BaseScheduling):
"""
Scheduling implementation for CuteDSL (CUTLASS Python DSL) kernels.
This class is intended to be used in combination with other schedulers,
and delegated to by CUDACombinedScheduling.
"""
@classmethod
def get_backend_features(cls, device) -> OrderedSet[Backen... | CuteDSLScheduling |
python | dask__dask | dask/dataframe/tseries/resample.py | {
"start": 6979,
"end": 9635
} | class ____:
"""Aggregate using one or more operations
The purpose of this class is to expose an API similar
to Pandas' `Resampler` for dask-expr
"""
def __init__(self, obj, rule, **kwargs):
if obj.divisions[0] is None:
msg = (
"Can only resample dataframes with ... | Resampler |
python | huggingface__transformers | src/transformers/models/bert/modeling_bert.py | {
"start": 15826,
"end": 18574
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, layer_idx=None):
super().__init__()
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.attention = BertAttention(config, is_causal=config.is_decoder, layer_idx=layer_idx)
s... | BertLayer |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDictClosed4.py | {
"start": 780,
"end": 854
} | class ____(TypedDict, extra_items=ReadOnly[str | int]):
name: str
| Movie3 |
python | more-itertools__more-itertools | tests/test_recipes.py | {
"start": 11110,
"end": 11667
} | class ____(TestCase):
"""Tests for ``roundrobin()``"""
def test_even_groups(self):
"""Ensure ordered output from evenly populated iterables"""
self.assertEqual(
list(mi.roundrobin('ABC', [1, 2, 3], range(3))),
['A', 1, 0, 'B', 2, 1, 'C', 3, 2],
)
def test_un... | RoundrobinTests |
python | doocs__leetcode | solution/1100-1199/1124.Longest Well-Performing Interval/Solution.py | {
"start": 0,
"end": 381
} | class ____:
def longestWPI(self, hours: List[int]) -> int:
ans = s = 0
pos = {}
for i, x in enumerate(hours):
s += 1 if x > 8 else -1
if s > 0:
ans = i + 1
elif s - 1 in pos:
ans = max(ans, i - pos[s - 1])
if s n... | Solution |
python | dask__dask | dask/array/_array_expr/_expr.py | {
"start": 7832,
"end": 8310
} | class ____(FinalizeCompute, ArrayExpr):
_parameters = ["arr"]
def chunks(self):
return (self.arr.shape,)
def _simplify_down(self):
if self.arr.numblocks in ((), (1,)):
return self.arr
else:
from dask.array._array_expr._rechunk import Rechunk
ret... | FinalizeComputeArray |
python | huggingface__transformers | src/transformers/models/clvp/modeling_clvp.py | {
"start": 9667,
"end": 10388
} | class ____(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""
ClvpRMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states):
input_d... | ClvpRMSNorm |
python | google__jax | tests/pallas/mgpu_ragged_dot_test.py | {
"start": 5760,
"end": 7873
} | class ____(jtu.JaxTestCase):
def setUp(self):
super().setUp()
if blackwell_ragged_dot_mgpu is None:
self.skipTest("Mosaic GPU not available.")
if (not jtu.test_device_matches(["cuda"]) or
not jtu.is_cuda_compute_capability_equal("10.0")):
self.skipTest("Only works on GPU with capabili... | RaggedDotSm100aTestCase |
python | neetcode-gh__leetcode | python/2402-meeting-rooms-iii.py | {
"start": 0,
"end": 711
} | class ____:
def mostBooked(self, n: int, meetings: List[List[int]]) -> int:
meetings.sort()
available = [i for i in range(n)]
used = []
count = [0] * n
for start, end in meetings:
while used and start >= used[0][0]:
_, room = heapq.heappop(used)
... | Solution |
python | Lightning-AI__lightning | tests/tests_pytorch/checkpointing/test_model_checkpoint.py | {
"start": 37501,
"end": 37716
} | class ____(BoringModel):
def on_validation_model_train(self):
if not self.trainer.sanity_checking and self.current_epoch == 1:
raise RuntimeError("Trouble!")
| TroubledModelOnValidationModelTrain |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/transfers/test_s3_to_sftp.py | {
"start": 1630,
"end": 9662
} | class ____:
def setup_method(self):
hook = SSHHook(ssh_conn_id="ssh_default")
hook.no_host_key_check = True
dag = DAG(
f"{TEST_DAG_ID}test_schedule_dag_once",
start_date=DEFAULT_DATE,
schedule="@once",
)
self.hook = hook
self.ssh_... | TestS3ToSFTPOperator |
python | readthedocs__readthedocs.org | readthedocs/builds/migrations/0031_add_version_fields_to_build.py | {
"start": 149,
"end": 1306
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("builds", "0030_add_automation_rule_matches"),
]
operations = [
migrations.AddField(
model_name="build",
name="version_name",
field=models.CharField(
blank=... | Migration |
python | pytorch__pytorch | test/distributed/test_c10d_nccl.py | {
"start": 244290,
"end": 246753
} | class ____(NCCLTraceTestDumpOnTimeoutBase):
@check_if_test_is_skipped
def _check_return_codes(self, elapsed_time):
# the base test infra assumes processes exit with matching return codes,
# but we want rank0 to abort and rank1 to exit cleanly in this test
self.assertEqual(self.processes[... | NCCLTraceTestTimeoutDumpOnStuckRanks |
python | spyder-ide__spyder | spyder/plugins/ipythonconsole/utils/kernel_handler.py | {
"start": 2445,
"end": 2710
} | class ____:
SpyderKernelWaitComm = "spyder_kernel_wait_comm"
SpyderKernelReady = "spyder_kernel_ready"
IpykernelReady = "ipykernel_ready"
Connecting = "connecting"
Error = "error"
Closed = "closed"
Crashed = "crashed"
| KernelConnectionState |
python | great-expectations__great_expectations | great_expectations/profile/base.py | {
"start": 3447,
"end": 3628
} | class ____(Enum):
DATETIME = "DATETIME"
NUMERIC = "NUMERIC"
STRING = "STRING"
VALUE_SET = "VALUE_SET"
BOOLEAN = "BOOLEAN"
OTHER = "OTHER"
| ProfilerSemanticTypes |
python | kamyu104__LeetCode-Solutions | Python/maximum-element-sum-of-a-complete-subset-of-indices.py | {
"start": 166,
"end": 415
} | class ____(object):
def maximumSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return max(sum(nums[i*x**2-1] for x in xrange(1, int((len(nums)//i)**0.5)+1)) for i in xrange(1, len(nums)+1))
| Solution |
python | davidhalter__parso | parso/python/tree.py | {
"start": 20715,
"end": 20764
} | class ____(PythonBaseNode):
__slots__ = ()
| Flow |
python | gevent__gevent | src/gevent/libuv/watcher.py | {
"start": 27906,
"end": 28313
} | class ____(_base.SignalMixin, watcher):
_watcher_callback_name = '_gevent_signal_callback1'
def _watcher_ffi_init(self, args):
self._watcher_init(self.loop.ptr, self._watcher)
self.ref = False # libev doesn't ref these by default
def _watcher_ffi_start(self):
self._watcher_start(s... | signal |
python | ethereum__web3.py | web3/_utils/abi.py | {
"start": 7771,
"end": 7880
} | class ____(AcceptsHexStrEncoder):
subencoder_cls = encoding.BytesEncoder
is_strict = False
| BytesEncoder |
python | tiangolo__fastapi | tests/test_dependency_yield_scope_websockets.py | {
"start": 819,
"end": 6219
} | class ____:
def __init__(self, name: str = "default") -> None:
self.name = name
self.open = True
def get_named_session(session: SessionRequestDep, session_b: SessionDefaultDep) -> Any:
assert session is session_b
named_session = NamedSession(name="named")
yield named_session, session_b... | NamedSession |
python | plotly__plotly.py | plotly/graph_objs/funnel/_stream.py | {
"start": 233,
"end": 3494
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "funnel"
_path_str = "funnel.stream"
_valid_props = {"maxpoints", "token"}
@property
def maxpoints(self):
"""
Sets the maximum number of points to keep on the plots from an
incoming stream. If `maxpoints` is set to 50, ... | Stream |
python | mlflow__mlflow | mlflow/store/artifact/dbfs_artifact_repo.py | {
"start": 1660,
"end": 11587
} | class ____(ArtifactRepository):
"""
Stores artifacts on DBFS using the DBFS REST API.
This repository is used with URIs of the form ``dbfs:/<path>``. The repository can only be used
together with the RestStore.
"""
def __init__(
self, artifact_uri: str, tracking_uri: str | None = None,... | DbfsRestArtifactRepository |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/skills/version_delete_response.py | {
"start": 160,
"end": 465
} | class ____(BaseModel):
id: str
"""Version identifier for the skill.
Each version is identified by a Unix epoch timestamp (e.g., "1759178010641129").
"""
type: str
"""Deleted object type.
For Skill Versions, this is always `"skill_version_deleted"`.
"""
| VersionDeleteResponse |
python | pytorch__pytorch | test/dynamo/test_model_output.py | {
"start": 8767,
"end": 12251
} | class ____(TestCase):
@maybe_skip
def test_HF_bert_model_output(self, device):
class BertPooler(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.dense = torch.nn.Linear(768, 768).to(device)
self.activation = torch.nn.Tanh()... | TestModelOutputBert |
python | google__jax | jax/_src/interpreters/mlir.py | {
"start": 44577,
"end": 60245
} | class ____(NamedTuple):
contains_unconstrained: bool
all_unconstrained: bool
def _get_unconstrained_variants(s, aval) -> UnconstrainedVariants:
us = contains_unconstrained(s)
return UnconstrainedVariants(
contains_unconstrained=us, all_unconstrained=all_unconstrained(s, aval))
def check_jaxpr_constants... | UnconstrainedVariants |
python | doocs__leetcode | solution/1600-1699/1656.Design an Ordered Stream/Solution.py | {
"start": 0,
"end": 507
} | class ____:
def __init__(self, n: int):
self.ptr = 1
self.data = [None] * (n + 1)
def insert(self, idKey: int, value: str) -> List[str]:
self.data[idKey] = value
ans = []
while self.ptr < len(self.data) and self.data[self.ptr]:
ans.append(self.data[self.ptr])... | OrderedStream |
python | tensorflow__tensorflow | tensorflow/python/ops/numpy_ops/tests/np_indexing_test.py | {
"start": 33916,
"end": 42330
} | class ____(jtu.TestCase):
@parameterized.named_parameters(jtu.cases_from_list({ # pylint: disable=g-complex-comprehension
"testcase_name": "_{}_{}_{}_{}".format(
jtu.format_shape_dtype_string(shape, dtype), indexer,
jtu.format_shape_dtype_string(update_shape, update_dtype), op.name),
... | IndexedUpdateTest |
python | django__django | django/contrib/postgres/search.py | {
"start": 12213,
"end": 12473
} | class ____(Func):
output_field = FloatField()
def __init__(self, string, expression, **extra):
if not hasattr(string, "resolve_expression"):
string = Value(string)
super().__init__(string, expression, **extra)
| TrigramWordBase |
python | kubernetes-client__python | kubernetes/client/models/v1beta1_parent_reference.py | {
"start": 383,
"end": 6319
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1beta1ParentReference |
python | bokeh__bokeh | tests/unit/bokeh/core/test_has_props.py | {
"start": 15213,
"end": 20138
} | class ____(hp.HasProps, hp.Local):
f0 = Required(Int)
f1 = Int()
f2 = Int(default=1)
def test_HasProps_properties_with_values_maintains_order() -> None:
v0 = Some3HasProps()
assert list(v0.properties_with_values(include_defaults=False).items()) == []
assert list(v0.properties_with_values(includ... | Some4HasProps |
python | facebook__pyre-check | tools/generate_taint_models/tests/function_tainter_test.py | {
"start": 536,
"end": 620
} | class ____:
x1: str
y: int
@final
@dataclass(frozen=True)
| TestRequestDataclass |
python | walkccc__LeetCode | solutions/767. Reorganize String/767.py | {
"start": 0,
"end": 666
} | class ____:
def reorganizeString(self, s: str) -> str:
count = collections.Counter(s)
if max(count.values()) > (len(s) + 1) // 2:
return ''
ans = []
maxHeap = [(-freq, c) for c, freq in count.items()]
heapq.heapify(maxHeap)
prevFreq = 0
prevChar = '@'
while maxHeap:
# Get... | Solution |
python | pennersr__django-allauth | allauth/socialaccount/migrations/0006_alter_socialaccount_extra_data.py | {
"start": 93,
"end": 435
} | class ____(migrations.Migration):
dependencies = [
("socialaccount", "0005_socialtoken_nullable_app"),
]
operations = [
migrations.AlterField(
model_name="socialaccount",
name="extra_data",
field=models.JSONField(default=dict, verbose_name="extra data"),
... | Migration |
python | donnemartin__interactive-coding-challenges | graphs_trees/trie/test_trie.py | {
"start": 18,
"end": 2160
} | class ____(unittest.TestCase):
def test_trie(self):
trie = Trie()
print('Test: Insert')
words = ['a', 'at', 'has', 'hat', 'he',
'me', 'men', 'mens', 'met']
for word in words:
trie.insert(word)
for word in trie.list_words():
se... | TestTrie |
python | PyCQA__pylint | tests/functional/ext/docparams/return/missing_return_doc_Numpy.py | {
"start": 2111,
"end": 2455
} | class ____:
"""test_ignores_return_in_abstract_method_numpy_2
Example of a method documenting the return type that an
implementation should return."""
def foo(self, arg):
"""docstring ...
Parameters
----------
arg : int
An argument.
"""
raise... | Foo |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/components_tests/test_component_scaffolding.py | {
"start": 455,
"end": 564
} | class ____(BaseModel):
name: Optional[str] = None
age: Optional[int] = None
| TestParamsModelWithDefaults |
python | chroma-core__chroma | chromadb/types.py | {
"start": 1125,
"end": 1199
} | class ____(Enum):
FLOAT32 = "FLOAT32"
INT32 = "INT32"
| ScalarEncoding |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_releases.py | {
"start": 2106,
"end": 34575
} | class ____(APITestCase, BaseMetricsTestCase):
endpoint = "sentry-api-0-organization-releases"
def assert_expected_versions(self, response, expected):
assert [item["version"] for item in response.data] == [e.version for e in expected]
def test_simple(self) -> None:
user = self.create_user(i... | OrganizationReleaseListTest |
python | tensorflow__tensorflow | tensorflow/tools/common/traverse_test.py | {
"start": 1096,
"end": 2467
} | class ____(googletest.TestCase):
def test_cycle(self):
class Cyclist(object):
pass
Cyclist.cycle = Cyclist
visitor = TestVisitor()
traverse.traverse(Cyclist, visitor)
# We simply want to make sure we terminate.
def test_module(self):
visitor = TestVisitor()
traverse.traverse(te... | TraverseTest |
python | getsentry__sentry | src/sentry/integrations/client.py | {
"start": 78,
"end": 315
} | class ____(BaseApiClient):
integration_type = "integration"
metrics_prefix = "integrations"
logger = logging.getLogger("sentry.integrations.client")
# Used in metrics and logging.
integration_name = "undefined"
| ApiClient |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/strategies.py | {
"start": 11640,
"end": 17560
} | class ____(LoaderStrategy):
"""Provide loading behavior for a deferred :class:`.ColumnProperty`."""
__slots__ = "columns", "group", "raiseload"
def __init__(self, parent, strategy_key):
super().__init__(parent, strategy_key)
if hasattr(self.parent_property, "composite_class"):
... | _DeferredColumnLoader |
python | pypa__pipenv | pipenv/vendor/click/formatting.py | {
"start": 3082,
"end": 9706
} | class ____:
"""This class helps with formatting text-based help pages. It's
usually just needed for very special internal cases, but it's also
exposed so that developers can write their own fancy outputs.
At present, it always writes into memory.
:param indent_increment: the additional increment ... | HelpFormatter |
python | joke2k__faker | tests/providers/test_date_time.py | {
"start": 25726,
"end": 26203
} | class ____(unittest.TestCase):
"""Tests date_time in the hy_AM locale"""
def setUp(self):
self.fake = Faker("hy_AM")
Faker.seed(0)
def test_day(self):
day = self.fake.day_of_week()
assert isinstance(day, str)
assert day in HyAmProvider.DAY_NAMES.values()
def te... | TestHyAm |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/matchValue1.py | {
"start": 2275,
"end": 3030
} | class ____(Enum):
red = 1
blue = 2
green = 3
def test_enum_narrowing(m: Medal | Color | int):
match m:
case Medal.gold as a1:
reveal_type(a1, expected_text="Literal[Medal.gold]")
reveal_type(m, expected_text="Literal[Medal.gold]")
case Medal.silver as b1:
... | Color |
python | Netflix__metaflow | test/core/tests/basic_log.py | {
"start": 67,
"end": 1882
} | class ____(MetaflowTest):
"""
Test that log messages emitted in the first step
are saved and readable.
"""
PRIORITY = 0
SKIP_GRAPHS = [
"simple_switch",
"nested_switch",
"branch_in_switch",
"foreach_in_switch",
"switch_in_branch",
"switch_in_forea... | BasicLogTest |
python | google__jax | jax/_src/test_util.py | {
"start": 8433,
"end": 20620
} | class ____(threading.local):
def __init__(self):
self.counts = {} # Mapping from string name to count.
self.nested_device_put_count = 0 # Number of recursive calls to device_put
# Per-function counts
self.infer_params_fun_counts = None
self.lower_jaxpr_to_fun_counts = None
self.collect_low... | EventThreadLocalState |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride1.py | {
"start": 13296,
"end": 13352
} | class ____[T]:
def method1(self, x: T) -> T: ...
| Base8 |
python | scipy__scipy | benchmarks/benchmarks/lsq_problems.py | {
"start": 5147,
"end": 9563
} | class ____(LSQBenchmarkProblem):
"""Coating thickness standardization problem, [1]_.
Number of variables --- 134, number of residuals --- 252, no bounds.
.. [1] Brett M. Averick et al. "The MINPACK-2 Test Problem Collection",
p. 25
"""
INITIAL_GUESSES = [
np.hstack(([-8.0, 13.0... | CoatingThickness |
python | pytorch__pytorch | test/distributed/elastic/multiprocessing/errors/api_test.py | {
"start": 370,
"end": 1305
} | class ____(Exception):
# exists so that we can validate that
# the correct error is raised and propagated
pass
@record
def raise_exception_fn():
raise SentinelError("foobar")
@record
def raise_system_exit_exception_fn(exit_code: int = 1):
exp = SystemExit()
exp.code = exit_code
raise exp... | SentinelError |
python | apache__airflow | airflow-core/tests/unit/callbacks/test_callback_requests.py | {
"start": 6912,
"end": 10690
} | class ____:
def test_dag_callback_request_with_context_from_server(self):
"""Test DagCallbackRequest with context_from_server field"""
current_time = timezone.utcnow()
dag_run_data = DRDataModel(
dag_id="test_dag",
run_id="test_run",
logical_date=current_t... | TestDagCallbackRequestWithContext |
python | sqlalchemy__sqlalchemy | test/sql/test_metadata.py | {
"start": 164247,
"end": 168068
} | class ____(fixtures.RemovesEvents, fixtures.TestBase):
def test_all_events(self):
canary = []
def before_attach(obj, parent):
canary.append(
"%s->%s" % (obj.__class__.__name__, parent.__class__.__name__)
)
def after_attach(obj, parent):
c... | CatchAllEventsTest |
python | huggingface__transformers | src/transformers/models/helium/modeling_helium.py | {
"start": 15353,
"end": 18486
} | class ____(HeliumPreTrainedModel):
def __init__(self, config: HeliumConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.lay... | HeliumModel |
python | google__jax | tests/pallas/mosaic_gpu_test.py | {
"start": 3696,
"end": 5608
} | class ____(jtu.JaxTestCase, metaclass=PallasTestMetaclass):
LOWERING_SEMANTICS: ClassVar[plgpu.LoweringSemantics]
def setUp(self):
if not jtu.is_cuda_compute_capability_at_least("9.0"):
self.skipTest("Only works on a GPU with capability >= sm90")
self.enter_context(pallas_call._PALLAS_USE_MOSAIC_GPU(... | PallasTest |
python | huggingface__transformers | src/transformers/models/albert/modeling_albert.py | {
"start": 14032,
"end": 16772
} | class ____(AlbertPreTrainedModel):
config_class = AlbertConfig
base_model_prefix = "albert"
def __init__(self, config: AlbertConfig, add_pooling_layer: bool = True):
r"""
add_pooling_layer (bool, *optional*, defaults to `True`):
Whether to add a pooling layer
"""
... | AlbertModel |
python | PyCQA__pylint | tests/functional/s/superfluous_parens.py | {
"start": 1704,
"end": 2491
} | class ____:
keys = []
def __iter__(self):
return ((k, getattr(self, k)) for k in self.keys)
if (A == 2) is not (B == 2):
pass
K = ("Test " + "String") # [superfluous-parens]
M = A is not (A <= H)
M = True is not (M == K)
M = True is not (True is not False) # pylint: disable=comparison-of-consta... | ClassA |
python | openai__openai-python | src/openai/types/evals/run_cancel_response.py | {
"start": 12962,
"end": 14527
} | class ____(BaseModel):
id: str
"""Unique identifier for the evaluation run."""
created_at: int
"""Unix timestamp (in seconds) when the evaluation run was created."""
data_source: DataSource
"""Information about the run's data source."""
error: EvalAPIError
"""An object representing an... | RunCancelResponse |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/strategies.py | {
"start": 100555,
"end": 120052
} | class ____(_PostLoader, util.MemoizedSlots):
__slots__ = (
"join_depth",
"omit_join",
"_parent_alias",
"_query_info",
"_fallback_query_info",
)
query_info = collections.namedtuple(
"queryinfo",
[
"load_only_child",
"load_with_j... | _SelectInLoader |
python | apache__airflow | providers/fab/src/airflow/providers/fab/auth_manager/schemas/role_and_permission_schema.py | {
"start": 1473,
"end": 1637
} | class ____(Schema):
"""Permissions list schema."""
actions = fields.List(fields.Nested(ActionSchema))
total_entries = fields.Int()
| ActionCollectionSchema |
python | pytorch__pytorch | torch/ao/quantization/observer.py | {
"start": 63521,
"end": 63906
} | class ____(Enum):
"""
Placeholder for dtypes that do not exist in PyTorch core yet.
"""
# torch.int1 to torch.int7 will be added to PyTorch 2.6
# These will remain here for BC with older PyTorch versions
INT1 = auto()
INT2 = auto()
INT3 = auto()
INT4 = auto()
INT5 = auto()
I... | TorchAODType |
python | pallets__jinja | src/jinja2/lexer.py | {
"start": 8503,
"end": 9013
} | class ____:
"""The iterator for tokenstreams. Iterate over the stream
until the eof token is reached.
"""
def __init__(self, stream: "TokenStream") -> None:
self.stream = stream
def __iter__(self) -> "TokenStreamIterator":
return self
def __next__(self) -> Token:
toke... | TokenStreamIterator |
python | tensorflow__tensorflow | tensorflow/compiler/tests/image_ops_test.py | {
"start": 1531,
"end": 4249
} | class ____(xla_test.XLATestCase):
def testBatch(self):
# Build an arbitrary RGB image
np.random.seed(7)
batch_size = 5
shape = (batch_size, 2, 7, 3)
for nptype in self.float_types:
inp = _generate_numpy_random_rgb(shape).astype(nptype)
# Convert to HSV and back, as a batch and indiv... | RGBToHSVTest |
python | google__jax | jax/_src/pallas/mosaic/pipeline.py | {
"start": 9117,
"end": 13990
} | class ____:
"""Abstract interface for BufferedRefs."""
@property
def spec(self) -> pl.BlockSpec:
raise NotImplementedError()
@property
def buffer_type(self) -> BufferType:
raise NotImplementedError()
@property
def is_buffered(self) -> bool:
return False
@property
def is_input(self):
... | BufferedRefBase |
python | Farama-Foundation__Gymnasium | gymnasium/error.py | {
"start": 44,
"end": 120
} | class ____(Exception):
"""Error superclass."""
# Registration errors
| Error |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/metaclass5.py | {
"start": 137,
"end": 293
} | class ____(type):
def __eq__(self, a: "type[ClassA]") -> str:
return "hi"
def __add__(self, a: "type[ClassA]") -> int:
return 0
| MetaA |
python | rapidsai__cudf | python/cudf/cudf/core/udf/masked_typing.py | {
"start": 13529,
"end": 14016
} | class ____(AbstractTemplate):
"""
Typing for int(Masked)
returns the result of calling "int" on the input
TODO: retains the validity of the input rather than
raising as in int(pd.NA)
"""
def generic(self, args, kws):
if isinstance(args[0], MaskedType):
# following numpy ... | MaskedScalarIntCast |
python | GoogleCloudPlatform__python-docs-samples | datastore/cloud-ndb/flask_app.py | {
"start": 978,
"end": 1174
} | class ____(ndb.Model):
title = ndb.StringProperty()
@app.route("/")
def list_books():
books = Book.query()
return str([book.to_dict() for book in books])
# [END datastore_ndb_flask]
| Book |
python | PrefectHQ__prefect | src/integrations/prefect-dask/prefect_dask/client.py | {
"start": 374,
"end": 5281
} | class ____(Client):
def submit(
self,
func,
*args,
key=None,
workers=None,
resources=None,
retries=None,
priority=0,
fifo_timeout="100 ms",
allow_other_workers=False,
actor=False,
actors=False,
pure=True,
... | PrefectDaskClient |
python | doocs__leetcode | solution/0200-0299/0253.Meeting Rooms II/Solution2.py | {
"start": 0,
"end": 313
} | class ____:
def minMeetingRooms(self, intervals: List[List[int]]) -> int:
d = defaultdict(int)
for l, r in intervals:
d[l] += 1
d[r] -= 1
ans = s = 0
for _, v in sorted(d.items()):
s += v
ans = max(ans, s)
return ans
| Solution |
python | numba__numba | numba/core/typing/npdatetime.py | {
"start": 5660,
"end": 6462
} | class ____(AbstractTemplate):
key = operator.add
def generic(self, args, kws):
if len(args) == 1:
# Guard against unary +
return
left, right = args
if isinstance(right, types.NPTimedelta):
dt = left
td = right
elif isinstance(left,... | DatetimePlusTimedelta |
python | langchain-ai__langchain | libs/core/langchain_core/runnables/utils.py | {
"start": 14792,
"end": 15832
} | class ____(Protocol[_T_contra, _T_co]):
"""Protocol for objects that support addition."""
def __add__(self, x: _T_contra, /) -> _T_co:
"""Add the object to another object."""
Addable = TypeVar("Addable", bound=SupportsAdd[Any, Any])
def add(addables: Iterable[Addable]) -> Addable | None:
"""Add... | SupportsAdd |
python | huggingface__transformers | src/transformers/models/swin2sr/modeling_swin2sr.py | {
"start": 1406,
"end": 3389
} | class ____(ModelOutput):
last_hidden_state: Optional[torch.FloatTensor] = None
hidden_states: Optional[tuple[torch.FloatTensor]] = None
attentions: Optional[tuple[torch.FloatTensor]] = None
# Copied from transformers.models.swin.modeling_swin.window_partition
def window_partition(input_feature, window_siz... | Swin2SREncoderOutput |
python | huggingface__transformers | tests/models/layoutlmv3/test_processing_layoutlmv3.py | {
"start": 2855,
"end": 19171
} | class ____(unittest.TestCase):
@cached_property
def get_images(self):
# we verify our implementation on 2 document images from the DocVQA dataset
from datasets import load_dataset
ds = load_dataset("hf-internal-testing/fixtures_docvqa", split="test")
return ds[0]["image"].conver... | LayoutLMv3ProcessorIntegrationTests |
python | kamyu104__LeetCode-Solutions | Python/design-hashmap.py | {
"start": 29,
"end": 185
} | class ____(object):
def __init__(self, key, val):
self.val = val
self.key = key
self.next = None
self.prev = None
| ListNode |
python | wandb__wandb | wandb/vendor/pygments/lexers/robotframework.py | {
"start": 11673,
"end": 12207
} | class ____(_Table):
_tokenizer_class = Setting
def __init__(self, template_setter, prev_tokenizer=None):
_Table.__init__(self, prev_tokenizer)
self._template_setter = template_setter
def _tokenize(self, value, index):
if index == 0 and normalize(value) == 'testtemplate':
... | SettingTable |
python | PrefectHQ__prefect | src/integrations/prefect-kubernetes/tests/test_worker.py | {
"start": 53474,
"end": 63236
} | class ____:
@pytest.fixture
def flow_run(self):
return FlowRun(flow_id=uuid.uuid4(), name="my-flow-run-name")
@pytest.fixture
def deployment(self):
return DeploymentResponse(name="my-deployment-name", flow_id=uuid.uuid4())
@pytest.fixture
def work_pool(self):
return Wor... | TestKubernetesWorkerJobConfiguration |
python | bokeh__bokeh | tests/unit/bokeh/colors/test_util__colors.py | {
"start": 1432,
"end": 3889
} | class ____:
def test_init(self) -> None:
c = bcu.NamedColor("aliceblue", 240, 248, 255)
assert c.name == "aliceblue"
def test_repr(self) -> None:
c = bcu.NamedColor("aliceblue", 240, 248, 255)
assert repr(c) == c.to_css()
def test_to_css(self) -> None:
c = bcu.N... | Test_NamedColor |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI059.py | {
"start": 1349,
"end": 1516
} | class ____(Generic[T]): # Only one generic
pass
# syntax errors with starred and keyword arguments from
# https://github.com/astral-sh/ruff/issues/18602
| SomeGeneric |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/legacy_rnn/rnn_cell_impl.py | {
"start": 16254,
"end": 19919
} | class ____(LayerRNNCell):
"""The most basic RNN cell.
Note that this cell is not optimized for performance. Please use
`tf.contrib.cudnn_rnn.CudnnRNNTanh` for better performance on GPU.
Args:
num_units: int, The number of units in the RNN cell.
activation: Nonlinearity to use. Default: `tanh`. It cou... | BasicRNNCell |
python | PyCQA__pycodestyle | testing/data/E30not.py | {
"start": 979,
"end": 1459
} | class ____():
"""Class Foo"""
def b():
pass
# comment
def c():
pass
# comment
def d():
pass
# This is a
# ... multi-line comment
# And this one is
# ... a second paragraph
# ... which spans on 3 lines
# Function `e` is below
# NOTE: Hey this is a testcase
def e():
pass
def a()... | Foo |
python | ray-project__ray | python/ray/serve/_private/deployment_info.py | {
"start": 335,
"end": 6232
} | class ____:
def __init__(
self,
deployment_config: DeploymentConfig,
replica_config: ReplicaConfig,
start_time_ms: int,
deployer_job_id: str,
actor_name: Optional[str] = None,
version: Optional[str] = None,
end_time_ms: Optional[int] = None,
ro... | DeploymentInfo |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 160792,
"end": 162517
} | class ____(Response):
"""
Response of tasks.close endpoint.
:param updated: Number of tasks updated (0 or 1)
:type updated: int
:param fields: Updated fields names and values
:type fields: dict
"""
_service = "tasks"
_action = "close"
_version = "2.23"
_schema = {
... | CloseResponse |
python | automl__auto-sklearn | autosklearn/pipeline/implementations/CategoryShift.py | {
"start": 141,
"end": 1516
} | class ____(BaseEstimator, TransformerMixin):
"""Add 3 to every category."""
def __init__(self, random_state=None):
self.random_state = random_state
def _convert_and_check_X(self, X):
X_data = X.data if sparse.issparse(X) else X
# Check if data is numeric and positive
if X_... | CategoryShift |
python | mlflow__mlflow | mlflow/types/llm.py | {
"start": 21347,
"end": 22656
} | class ____(_BaseDataclass):
"""
Message content token with log probability information.
Args:
token: The token.
logprob: The log probability of this token, if it is within the top
20 most likely tokens. Otherwise, the value -9999.0 is used to
signify that the token i... | TokenLogProb |
python | lxml__lxml | src/lxml/tests/test_threading.py | {
"start": 252,
"end": 13541
} | class ____(HelperTestCase):
"""Threading tests"""
etree = etree
def _run_thread(self, func):
thread = threading.Thread(target=func)
thread.start()
thread.join()
def _run_threads(self, count, func, main_func=None):
sync = threading.Event()
lock = threading.Lock()... | ThreadingTestCase |
python | django__django | django/contrib/postgres/lookups.py | {
"start": 1034,
"end": 1125
} | class ____(HasKeys):
lookup_name = "has_any_keys"
postgres_operator = "?|"
| HasAnyKeys |
python | huggingface__transformers | src/transformers/models/bros/modeling_bros.py | {
"start": 28225,
"end": 32626
} | class ____(BrosPreTrainedModel):
_keys_to_ignore_on_load_unexpected = [r"pooler"]
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.bros = BrosModel(config)
classifier_dropout = (
config.classifier_dropout if hasattr(confi... | BrosForTokenClassification |
python | getsentry__sentry | src/sentry/notifications/platform/target.py | {
"start": 534,
"end": 730
} | class ____(Exception):
pass
INTEGRATION_PROVIDER_KEYS = [
NotificationProviderKey.SLACK,
NotificationProviderKey.DISCORD,
NotificationProviderKey.MSTEAMS,
]
| NotificationTargetError |
python | aio-libs__aiohttp | aiohttp/compression_utils.py | {
"start": 814,
"end": 962
} | class ____(Protocol):
def compress(self, data: Buffer) -> bytes: ...
def flush(self, mode: int = ..., /) -> bytes: ...
| ZLibCompressObjProtocol |
python | getsentry__sentry | tests/sentry/integrations/vsts/test_provider.py | {
"start": 10827,
"end": 12541
} | class ____(TestCase):
client_secret = "12345678"
def setUp(self) -> None:
self.identity_provider_model = self.create_identity_provider(type="vsts")
self.identity = Identity.objects.create(
idp=self.identity_provider_model,
user=self.user,
external_id="vsts_id... | VstsIdentityProviderTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride1.py | {
"start": 11871,
"end": 11953
} | class ____:
def case(self, value: Any) -> Iterable[Any]:
return []
| Base3 |
python | pyca__cryptography | src/cryptography/x509/extensions.py | {
"start": 34776,
"end": 39109
} | class ____(ExtensionType):
oid = ExtensionOID.KEY_USAGE
def __init__(
self,
digital_signature: bool,
content_commitment: bool,
key_encipherment: bool,
data_encipherment: bool,
key_agreement: bool,
key_cert_sign: bool,
crl_sign: bool,
encip... | KeyUsage |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.