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 | django__django | django/core/servers/basehttp.py | {
"start": 3729,
"end": 6327
} | class ____(simple_server.ServerHandler):
http_version = "1.1"
def __init__(self, stdin, stdout, stderr, environ, **kwargs):
"""
Use a LimitedStream so that unread request data will be ignored at
the end of the request. WSGIRequest uses a LimitedStream but it
shouldn't discard th... | ServerHandler |
python | google__jax | jax/experimental/array_serialization/serialization_test.py | {
"start": 28901,
"end": 28984
} | class ____:
a: int
c: str
d: int
@jax.tree_util.register_static
| CustomDataclass |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/fields_on_correct_type.py | {
"start": 999,
"end": 1054
} | class ____(Counter, OrderedDict):
pass
| OrderedCounter |
python | google__pytype | pytype/tests/test_unpack.py | {
"start": 96,
"end": 9247
} | class ____(test_base.BaseTest):
"""Test unpacking of sequences via *xs."""
def test_build_with_unpack_indefinite(self):
ty = self.Infer("""
from typing import List
class A: pass
a: List[A] = []
b: List[str] = []
c = [*a, *b, 1]
d = {*a, *b, 1}
e = (*a, *b, 1)
""")
... | TestUnpack |
python | bokeh__bokeh | examples/advanced/extensions/parallel_plot/parallel_reset.py | {
"start": 38,
"end": 185
} | class ____(ActionTool):
""" Tool to reset only plot axes and not selections
"""
__implementation__ = 'parallel_reset.ts'
| ParallelResetTool |
python | ray-project__ray | python/ray/train/torch/config.py | {
"start": 810,
"end": 1226
} | class ____:
def __enter__(self):
# Set default cuda device
if torch.cuda.is_available():
device = ray.train.torch.get_device()
if device.type == "cuda":
torch.cuda.set_device(device)
def __exit__(self, type, value, traceback):
# Propagate exceptio... | TorchConfigContextManager |
python | davidhalter__jedi | jedi/api/environment.py | {
"start": 1623,
"end": 4243
} | class ____(_BaseEnvironment):
"""
This class is supposed to be created by internal Jedi architecture. You
should not create it directly. Please use create_environment or the other
functions instead. It is then returned by that function.
"""
_subprocess = None
def __init__(self, executable, ... | Environment |
python | ray-project__ray | python/ray/autoscaler/_private/event_system.py | {
"start": 1623,
"end": 3870
} | class ____:
"""Event system that handles storing and calling callbacks for events.
Attributes:
callback_map (Dict[str, List[Callable]]) : Stores list of callbacks
for events when registered.
"""
def __init__(self):
self.callback_map = {}
def add_callback_handler(
... | _EventSystem |
python | huggingface__transformers | src/transformers/models/zamba/modeling_zamba.py | {
"start": 2614,
"end": 4011
} | class ____(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""
ZambaRMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states):
input_... | ZambaRMSNorm |
python | ray-project__ray | python/ray/serve/_private/deployment_scheduler.py | {
"start": 1048,
"end": 3946
} | class ____(dict):
# Custom resource priority from environment variable
CUSTOM_PRIORITY: List[str] = RAY_SERVE_HIGH_PRIORITY_CUSTOM_RESOURCES
EPSILON = 1e-9
def get(self, key: str):
val = super().get(key)
if val is not None:
return val
# Implicit resources by default... | Resources |
python | h5py__h5py | h5py/tests/test_vds/test_highlevel_vds.py | {
"start": 15398,
"end": 15887
} | class ____(RelativeLinkTestCase):
# Test a link to the same file with the virtual dataset created by
# File.build_virtual_dataset()
def make_vds(self, f):
with f.build_virtual_dataset('virtual', (2, 10), dtype='f4') as layout:
layout[0] = h5.VirtualSource(self.f1, 'data', shape=(10,))
... | RelativeLinkBuildVDSTestCase |
python | tensorflow__tensorflow | third_party/xla/xla/backends/gpu/codegen/tools/ncu_rep_test.py | {
"start": 767,
"end": 4618
} | class ____(absltest.TestCase):
def test_get_metrics_by_kernel(self):
# That is a typical format of ncu-rep CSV output.
by_kernel = ncu_rep_lib.get_metrics_by_kernel([
["Kernel Name", "Metric 1", "Metric 2"],
["", "s", "Gb"],
["kernel1", "1", "2"],
["kernel2", "3", "4"],
])... | NcuRepTest |
python | PrefectHQ__prefect | src/prefect/_internal/concurrency/waiters.py | {
"start": 4787,
"end": 9442
} | class ____(Waiter[T]):
# Implementation of `Waiter` for use in asynchronous contexts
def __init__(self, call: Call[T]) -> None:
super().__init__(call=call)
# Delay instantiating loop and queue as there may not be a loop present yet
self._loop: Optional[asyncio.AbstractEventLoop] = None... | AsyncWaiter |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_us_state.py | {
"start": 765,
"end": 1787
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_us_state"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(c... | ColumnValuesToBeValidUSState |
python | Textualize__textual | src/textual/_compositor.py | {
"start": 1724,
"end": 2151
} | class ____:
"""An update generated by the compositor, which also doubles as console renderables."""
def render_segments(self, console: Console) -> str:
"""Render the update to raw data, suitable for writing to terminal.
Args:
console: Console instance.
Returns:
... | CompositorUpdate |
python | wireservice__csvkit | csvkit/utilities/csvsort.py | {
"start": 336,
"end": 2836
} | class ____(CSVKitUtility):
description = 'Sort CSV files. Like the Unix "sort" command, but for tabular data.'
def add_arguments(self):
self.argparser.add_argument(
'-n', '--names', dest='names_only', action='store_true',
help='Display column names and indices from the input CSV... | CSVSort |
python | getsentry__sentry | tests/sentry/workflow_engine/test_base.py | {
"start": 3805,
"end": 5396
} | class ____:
patches: list = []
def setup_condition_mocks(
self,
evaluate_value: Callable[[int, Any], DataConditionResult],
module_paths: list[str],
):
"""
Sets up a mock handler for a DataCondition. This method mocks out the registry of the class, and will
al... | DataConditionHandlerMixin |
python | pandas-dev__pandas | asv_bench/benchmarks/io/sql.py | {
"start": 180,
"end": 1533
} | class ____:
params = ["sqlalchemy", "sqlite"]
param_names = ["connection"]
def setup(self, connection):
N = 10000
con = {
"sqlalchemy": create_engine("sqlite:///:memory:"),
"sqlite": sqlite3.connect(":memory:"),
}
self.table_name = "test_type"
... | SQL |
python | apache__airflow | shared/secrets_masker/tests/secrets_masker/test_secrets_masker.py | {
"start": 1881,
"end": 2943
} | class ____(str, Enum):
testname = "testvalue"
testname2 = "testvalue2"
@pytest.fixture
def logger(caplog):
logging.config.dictConfig(
{
"version": 1,
"handlers": {
__name__: {
# Reset later
"class": "logging.StreamHand... | MyEnum |
python | matplotlib__matplotlib | lib/matplotlib/cbook.py | {
"start": 25597,
"end": 29241
} | class ____:
"""
A disjoint-set data structure.
Objects can be joined using :meth:`join`, tested for connectedness
using :meth:`joined`, and all disjoint sets can be retrieved by
using the object as an iterator.
The objects being joined must be hashable and weak-referenceable.
Examples
... | Grouper |
python | walkccc__LeetCode | solutions/2740. Find the Value of the Partition/2740.py | {
"start": 0,
"end": 141
} | class ____:
def findValueOfPartition(self, nums: list[int]) -> int:
return min(b - a for a, b in itertools.pairwise(sorted(nums)))
| Solution |
python | pypa__hatch | tests/cli/run/test_run.py | {
"start": 72003,
"end": 81221
} | class ____:
@pytest.mark.requires_internet
def test_not_file(self, hatch, helpers, temp_dir):
project_name = "My.App"
with temp_dir.as_cwd():
result = hatch("new", project_name)
assert result.exit_code == 0, result.output
project_path = temp_dir / "my-app"
... | TestScriptRunner |
python | pypa__pipenv | pipenv/vendor/click/_compat.py | {
"start": 1283,
"end": 2000
} | class ____(io.TextIOWrapper):
def __init__(
self,
stream: t.BinaryIO,
encoding: t.Optional[str],
errors: t.Optional[str],
force_readable: bool = False,
force_writable: bool = False,
**extra: t.Any,
) -> None:
self._stream = stream = t.cast(
... | _NonClosingTextIOWrapper |
python | plotly__plotly.py | plotly/graph_objs/funnel/_legendgrouptitle.py | {
"start": 233,
"end": 2932
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "funnel"
_path_str = "funnel.legendgrouptitle"
_valid_props = {"font", "text"}
@property
def font(self):
"""
Sets this legend group's title font.
The 'font' property is an instance of Font
that may be specified... | Legendgrouptitle |
python | patrick-kidger__equinox | equinox/internal/_omega.py | {
"start": 5058,
"end": 5273
} | class ____ωUpdateHelper:
def __init__(self, value, is_leaf):
self.value = value
self.is_leaf = is_leaf
def __getitem__(self, item):
return _ωUpdateRef(self.value, item, self.is_leaf)
| _ |
python | scipy__scipy | benchmarks/benchmarks/special.py | {
"start": 1346,
"end": 1576
} | class ____(Benchmark):
def setup(self):
n, x = np.arange(50, 500), np.logspace(0, 20, 100)
n, x = np.meshgrid(n, x)
self.n, self.x = n, x
def time_expn_large_n(self):
expn(self.n, self.x)
| Expn |
python | pytorch__pytorch | test/distributed/_composable/fsdp/test_fully_shard_comm.py | {
"start": 11777,
"end": 23632
} | class ____(FSDPTest):
@property
def world_size(self) -> int:
return min(4, torch.get_device_module(device_type).device_count())
@skip_if_lt_x_gpu(2)
def test_fully_shard_communication_count(self):
"""
Tests that FSDP issues the expected number of all-gathers and
reduce-s... | TestFullyShardCommunication |
python | jmcnamara__XlsxWriter | xlsxwriter/test/workbook/test_write_workbook_view.py | {
"start": 299,
"end": 4990
} | class ____(unittest.TestCase):
"""
Test the Workbook _write_workbook_view() method.
"""
def setUp(self):
self.fh = StringIO()
self.workbook = Workbook()
self.workbook._set_filehandle(self.fh)
def test_write_workbook_view1(self):
"""Test the _write_workbook_view() m... | TestWriteWorkbookView |
python | django__django | tests/i18n/tests.py | {
"start": 63840,
"end": 76147
} | class ____(SimpleTestCase):
rf = RequestFactory()
@override_settings(LANGUAGE_CODE="de")
def test_english_fallback(self):
"""
With a non-English LANGUAGE_CODE and if the active language is English
or one of its variants, the untranslated string should be returned
(instead of... | MiscTests |
python | great-expectations__great_expectations | tests/core/test__docs_decorators.py | {
"start": 642,
"end": 4036
} | class ____:
@pytest.mark.unit
def test_public_api_decorator_full_docstring(self):
normalized_docstring = inspect.cleandoc(_func_full_docstring_public_api.__doc__ or "")
assert normalized_docstring == inspect.cleandoc(
"--Public API--My docstring.\n"
"\n"
" ... | TestPublicAPI |
python | sympy__sympy | sympy/codegen/fnodes.py | {
"start": 5210,
"end": 6361
} | class ____(Token):
""" Represents a Do loop in in Fortran.
Examples
========
>>> from sympy import fcode, symbols
>>> from sympy.codegen.ast import aug_assign, Print
>>> from sympy.codegen.fnodes import Do
>>> i, n = symbols('i n', integer=True)
>>> r = symbols('r', real=True)
>>> ... | Do |
python | pandas-dev__pandas | pandas/tests/frame/methods/test_asof.py | {
"start": 530,
"end": 6248
} | class ____:
def test_basic(self, date_range_frame):
# Explicitly cast to float to avoid implicit cast when setting np.nan
df = date_range_frame.astype({"A": "float"})
N = 50
df.loc[df.index[15:30], "A"] = np.nan
dates = date_range("1/1/1990", periods=N * 3, freq="25s")
... | TestFrameAsof |
python | ray-project__ray | python/ray/serve/_private/test_utils.py | {
"start": 18139,
"end": 19248
} | class ____:
def __init__(self, name: str = None, tag_keys: Tuple[str] = None):
self.name = name
self.values = dict()
self.tags = tag_keys or ()
self.default_tags = dict()
def set_default_tags(self, tags: Dict[str, str]):
for key, tag in tags.items():
assert ... | FakeGauge |
python | scrapy__scrapy | scrapy/utils/python.py | {
"start": 9309,
"end": 9828
} | class ____(AsyncIterator[_T]):
"""
Similar to MutableChain but for async iterables
"""
def __init__(self, *args: Iterable[_T] | AsyncIterator[_T]):
self.data: AsyncIterator[_T] = _async_chain(*args)
def extend(self, *iterables: Iterable[_T] | AsyncIterator[_T]) -> None:
self.data =... | MutableAsyncChain |
python | getsentry__sentry | src/sentry/rules/registry.py | {
"start": 152,
"end": 969
} | class ____:
def __init__(self) -> None:
self._rules: dict[str, list[type[RuleBase]]] = defaultdict(list)
self._map: dict[str, type[RuleBase]] = {}
def __contains__(self, rule_id: str) -> bool:
return rule_id in self._map
def __iter__(self) -> Generator[tuple[str, type[RuleBase]]]:
... | RuleRegistry |
python | jazzband__tablib | src/tablib/formats/_yaml.py | {
"start": 61,
"end": 1512
} | class ____:
title = 'yaml'
extensions = ('yaml', 'yml')
@classmethod
def export_set(cls, dataset):
"""Returns YAML representation of Dataset."""
return yaml.safe_dump(
dataset._package(), default_flow_style=None, allow_unicode=True
)
@classmethod
def export_... | YAMLFormat |
python | conda__conda | tests/plugins/test_auth_handlers.py | {
"start": 434,
"end": 606
} | class ____(HTTPBasicAuth):
def __init__(self):
username = "user_two"
password = "pass_two"
super().__init__(username, password)
| CustomAltCondaAuth |
python | pandas-dev__pandas | pandas/tests/indexes/period/test_constructors.py | {
"start": 24850,
"end": 25525
} | class ____:
def test_shallow_copy_empty(self):
# GH#13067
idx = PeriodIndex([], freq="M")
result = idx._view()
expected = idx
tm.assert_index_equal(result, expected)
def test_shallow_copy_disallow_i8(self):
# GH#24391
pi = period_range("2018-01-01", peri... | TestShallowCopy |
python | getsentry__sentry | src/sentry/replays/endpoints/project_replay_jobs_delete.py | {
"start": 2102,
"end": 4576
} | class ____(ProjectEndpoint):
owner = ApiOwner.REPLAY
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
"POST": ApiPublishStatus.PRIVATE,
}
permission_classes = (ReplayDeletionJobPermission,)
def get(self, request: Request, project) -> Response:
"""
Retrieve a colle... | ProjectReplayDeletionJobsIndexEndpoint |
python | pytorch__pytorch | torch/_inductor/template_heuristics/params.py | {
"start": 633,
"end": 1257
} | class ____(KernelTemplateParams):
"""Simple implementation that wraps a kwargs dict"""
# NOTE: this is a compatibility layer, until every template
# has time to define their own params class, with meaningful
# defaults etc.
def __init__(self, kwargs: dict[str, Any]):
self.kwargs = kwargs
... | DictKernelTemplateParams |
python | doocs__leetcode | solution/0800-0899/0850.Rectangle Area II/Solution.py | {
"start": 1230,
"end": 1875
} | class ____:
def rectangleArea(self, rectangles: List[List[int]]) -> int:
segs = []
alls = set()
for x1, y1, x2, y2 in rectangles:
segs.append((x1, y1, y2, 1))
segs.append((x2, y1, y2, -1))
alls.update([y1, y2])
segs.sort()
alls = sorted(al... | Solution |
python | pypa__pip | src/pip/_internal/resolution/resolvelib/requirements.py | {
"start": 1513,
"end": 4102
} | class ____(Requirement):
def __init__(self, ireq: InstallRequirement) -> None:
assert ireq.link is None, "This is a link, not a specifier"
self._ireq = ireq
self._equal_cache: str | None = None
self._hash: int | None = None
self._extras = frozenset(canonicalize_name(e) for e ... | SpecifierRequirement |
python | pytorch__pytorch | test/onnx/model_defs/op_test.py | {
"start": 906,
"end": 1187
} | class ____(nn.Module):
def __init__(self) -> None:
super().__init__()
self.fake_quant = torch.ao.quantization.FakeQuantize()
self.fake_quant.disable_observer()
def forward(self, x):
output = self.fake_quant(x)
return output
| FakeQuantNet |
python | tornadoweb__tornado | tornado/test/util_test.py | {
"start": 1963,
"end": 6330
} | class ____(unittest.TestCase):
def setUp(self):
self.saved = TestConfigurable._save_configuration()
self.saved3 = TestConfig3._save_configuration()
def tearDown(self):
TestConfigurable._restore_configuration(self.saved)
TestConfig3._restore_configuration(self.saved3)
def ch... | ConfigurableTest |
python | pytorch__pytorch | torch/_inductor/ops_handler.py | {
"start": 31692,
"end": 31833
} | class ____(NamedTuple):
num_ops: int
used_ops: OrderedSet[str]
read_buffers: list[str]
nontrivial_read_count: int
| OpCountResult |
python | pandas-dev__pandas | asv_bench/benchmarks/io/csv.py | {
"start": 11210,
"end": 12298
} | class ____(StringIORewind):
params = ([",", ";"], [".", "_"], [None, "high", "round_trip"])
param_names = ["sep", "decimal", "float_precision"]
def setup(self, sep, decimal, float_precision):
floats = [
"".join([random.choice(string.digits) for _ in range(28)])
for _ in rang... | ReadCSVFloatPrecision |
python | vyperlang__vyper | vyper/compiler/settings.py | {
"start": 1403,
"end": 6047
} | class ____:
compiler_version: Optional[str] = None
optimize: Optional[OptimizationLevel] = None
evm_version: Optional[str] = None
experimental_codegen: Optional[bool] = None
debug: Optional[bool] = None
enable_decimals: Optional[bool] = None
nonreentrancy_by_default: Optional[bool] = None
... | Settings |
python | scikit-learn__scikit-learn | sklearn/externals/_numpydoc/docscrape.py | {
"start": 19307,
"end": 23691
} | class ____(NumpyDocString):
extra_public_methods = ["__call__"]
def __init__(self, cls, doc=None, modulename="", func_doc=FunctionDoc, config=None):
if not inspect.isclass(cls) and cls is not None:
raise ValueError(f"Expected a class or None, but got {cls!r}")
self._cls = cls
... | ClassDoc |
python | pytorch__pytorch | test/mobile/model_test/nn_ops.py | {
"start": 7374,
"end": 8222
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.transformers = nn.ModuleList(
[
nn.Transformer(
d_model=2, nhead=2, num_encoder_layers=1, num_decoder_layers=1
),
nn.TransformerEncoder(
... | NNTransformerModule |
python | matplotlib__matplotlib | lib/matplotlib/backend_tools.py | {
"start": 11897,
"end": 12501
} | class ____(ToolBase):
"""Tool to toggle the major grids of the figure."""
description = 'Toggle major grids'
default_keymap = property(lambda self: mpl.rcParams['keymap.grid'])
def trigger(self, sender, event, data=None):
sentinel = str(uuid.uuid4())
# Trigger grid switching by tempora... | ToolGrid |
python | sphinx-doc__sphinx | sphinx/roles.py | {
"start": 11420,
"end": 13537
} | class ____(ReferenceRole):
def run(self) -> tuple[list[Node], list[system_message]]:
target_id = 'index-%s' % self.env.new_serialno('index')
formatted_target = _format_rfc_target(self.target)
entries = [('single', f'RFC; {formatted_target}', target_id, '', None)]
index = addnodes.in... | RFC |
python | sqlalchemy__sqlalchemy | test/engine/test_reconnect.py | {
"start": 45674,
"end": 51068
} | class ____(fixtures.TestBase):
"""Test for the reconnect recipe given at doc/build/faq/connections.rst.
Make sure the above document is updated if changes are made here.
"""
# this recipe works on PostgreSQL also but only if the connection
# is cut off from the server side, otherwise the connecti... | ReconnectRecipeTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 547241,
"end": 548031
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for CreatedIssueContribution."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("CreatedIssueContributionEdge"), graphql_name="edges")
"""A lis... | CreatedIssueContributionConnection |
python | sympy__sympy | sympy/utilities/matchpy_connector.py | {
"start": 6336,
"end": 11948
} | class ____:
"""
Replacer object to perform multiple pattern matching and subexpression
replacements in SymPy expressions.
Examples
========
Example to construct a simple first degree equation solver:
>>> from sympy.utilities.matchpy_connector import WildDot, Replacer
>>> from sympy im... | Replacer |
python | facebookresearch__faiss | tests/test_build_blocks.py | {
"start": 3515,
"end": 4256
} | class ____(unittest.TestCase):
def test_1(self):
# try with dimensions that are multiples of 16 or not
rs = np.random.RandomState(123)
swig_ptr = faiss.swig_ptr
for dim in 16, 32, 20, 25:
for _repeat in 1, 2, 3, 4, 5:
a = rs.rand(dim).astype('float32')
... | TestMAdd |
python | facebook__pyre-check | client/tests/coverage_data_tests.py | {
"start": 41757,
"end": 44744
} | class ____(testslide.TestCase):
def test_find_module_paths__basic(self) -> None:
with tempfile.TemporaryDirectory() as root:
root_path = Path(root)
setup.ensure_files_exist(
root_path,
["s0.py", "a/s1.py", "b/s2.py", "b/c/s3.py", "b/s4.txt", "b/__s5.py... | ModuleFindingHelpersTest |
python | run-llama__llama_index | llama-index-instrumentation/src/llama_index_instrumentation/span_handlers/base.py | {
"start": 1197,
"end": 5725
} | class ____(BaseModel, Generic[T]):
model_config = ConfigDict(arbitrary_types_allowed=True)
open_spans: Dict[str, T] = Field(
default_factory=dict, description="Dictionary of open spans."
)
completed_spans: List[T] = Field(
default_factory=list, description="List of completed spans."
... | BaseSpanHandler |
python | getsentry__sentry | src/sentry/users/services/user/model.py | {
"start": 3886,
"end": 3958
} | class ____(RpcModel):
user: RpcUser
created: bool
| UserCreateResult |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-s3/source_s3/source_files_abstract/formats/jsonl_spec.py | {
"start": 128,
"end": 238
} | class ____(str, Enum):
ignore = "ignore"
infer = "infer"
error = "error"
| UnexpectedFieldBehaviorEnum |
python | getsentry__sentry | src/sentry/preprod/api/bases/preprod_artifact_endpoint.py | {
"start": 847,
"end": 1249
} | class ____(ProjectPermission):
scope_map = {
"GET": ["project:read", "project:write", "project:admin"],
# Some simple actions, like triggering comparisons, should be allowed
"POST": ["project:read", "project:write", "project:admin"],
"PUT": ["project:read", "project:write", "project:... | ProjectPreprodArtifactPermission |
python | readthedocs__readthedocs.org | readthedocs/projects/views/base.py | {
"start": 2915,
"end": 3948
} | class ____:
"""
Protects views for spammy projects.
It shows a ``Project marked as spam`` page and return 410 GONE if the
project's dashboard is denied.
"""
def is_show_dashboard_denied_wrapper(self):
"""
Determine if the project has reached dashboard denied treshold.
... | ProjectSpamMixin |
python | kubernetes-client__python | kubernetes/client/models/v1_limit_range.py | {
"start": 383,
"end": 6534
} | 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... | V1LimitRange |
python | kamyu104__LeetCode-Solutions | Python/flip-game-ii.py | {
"start": 235,
"end": 1183
} | class ____(object):
def canWin(self, s):
g, g_final = [0], 0
for p in itertools.imap(len, re.split('-+', s)):
while len(g) <= p:
# Theorem 2: g[game] = g[subgame1]^g[subgame2]^g[subgame3]...
# and find first missing number.
g += min(set(xra... | Solution |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_lookup.py | {
"start": 31950,
"end": 32486
} | class ____(typing.Generic[_ValueType]):
value: _ValueType # the same name we have in `__init__`
def __init__(self, value: int) -> None:
"""By this example we show, that ``int`` is more important than ``_ValueType``."""
assert isinstance(value, int)
@given(st.data())
def test_constructor_is_m... | AnnotatedConstructor |
python | networkx__networkx | networkx/classes/tests/test_reportviews.py | {
"start": 21651,
"end": 27621
} | class ____(TestEdgeView):
@classmethod
def setup_class(cls):
cls.G = nx.path_graph(9, nx.MultiGraph())
cls.G.add_edge(1, 2, key=3, foo="bar")
cls.eview = nx.reportviews.MultiEdgeView
def modify_edge(self, G, e, **kwds):
if len(e) == 2:
e = e + (0,)
G._adj... | TestMultiEdgeView |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/dataclass_taint.py | {
"start": 1953,
"end": 2634
} | class ____:
bad: int
benign: str
def test_class_attr_model_tainted_directly() -> None:
# not an issue
DataClassWithClassAttributeTaintedDirectly(bad=1, benign=_test_source())
# should be an issue, properly raised.
DataClassWithClassAttributeTaintedDirectly(bad=_test_source(), benign="1")
#... | DataClassWithClassAttributeTaintedDirectly |
python | huggingface__transformers | src/transformers/models/qwen3_vl_moe/modeling_qwen3_vl_moe.py | {
"start": 15587,
"end": 17669
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: Qwen3VLMoeTextConfig, layer_idx: int):
super().__init__()
self.self_attn = Qwen3VLMoeTextAttention(config, layer_idx)
if (layer_idx not in config.mlp_only_layers) and (
config.num_experts > 0 and (layer_idx + 1) %... | Qwen3VLMoeTextDecoderLayer |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_gen_ai.py | {
"start": 7819,
"end": 8821
} | class ____:
@mock.patch(GEN_AI_PATH.format("GenAIGenerativeModelHook"))
def test_execute(self, mock_hook):
op = GenAIGenerateContentOperator(
task_id=TASK_ID,
project_id=GCP_PROJECT,
location=GCP_LOCATION,
model=GEMINI_MODEL,
contents=CONTENTS,... | TestGenAIGenerateFromCachedContentOperator |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_function_base.py | {
"start": 137993,
"end": 138973
} | class ____(TestCase):
@parametrize(
"type_in, type_out",
[
("l", "D"),
("h", "F"),
("H", "F"),
("b", "F"),
("B", "F"),
("g", "G"),
],
)
def test_sort_real(self, type_in, type_out):
# sort_complex() type c... | TestSortComplex |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 71846,
"end": 72142
} | class ____(BaseModel):
"""
TaskInstanceHistory Collection serializer for responses.
"""
task_instances: Annotated[list[TaskInstanceHistoryResponse], Field(title="Task Instances")]
total_entries: Annotated[int, Field(title="Total Entries")]
| TaskInstanceHistoryCollectionResponse |
python | celery__celery | t/unit/app/test_beat.py | {
"start": 31923,
"end": 32959
} | class ____:
def xxx_start_stop_process(self):
pytest.importorskip('_multiprocessing')
from billiard.process import Process
s = beat.EmbeddedService(self.app)
assert isinstance(s, Process)
assert isinstance(s.service, beat.Service)
s.service = MockService()
... | test_EmbeddedService |
python | matplotlib__matplotlib | lib/matplotlib/tests/test_category.py | {
"start": 1836,
"end": 1912
} | class ____:
def __init__(self, units):
self.units = units
| FakeAxis |
python | kamyu104__LeetCode-Solutions | Python/harshad-number.py | {
"start": 39,
"end": 330
} | class ____(object):
def sumOfTheDigitsOfHarshadNumber(self, x):
"""
:type x: int
:rtype: int
"""
result = 0
y = x
while y:
y, r = divmod(y, 10)
result += r
return result if x%result == 0 else -1
| Solution |
python | gevent__gevent | src/gevent/tests/test__socket.py | {
"start": 2056,
"end": 17842
} | class ____(greentest.TestCase):
__timeout__ = None
TIMEOUT_ERROR = socket.timeout
long_data = ", ".join([str(x) for x in range(20000)])
if not isinstance(long_data, bytes):
long_data = long_data.encode('ascii')
def setUp(self):
super(TestTCP, self).setUp()
if '-v' in sys.arg... | TestTCP |
python | kamyu104__LeetCode-Solutions | Python/partition-array-to-minimize-xor.py | {
"start": 52,
"end": 800
} | class ____(object):
def minXor(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
INF = float("inf")
prefix = [0]*(len(nums)+1)
for i in xrange(len(nums)):
prefix[i+1] = prefix[i]^nums[i]
dp = prefix[:]
d... | Solution |
python | sqlalchemy__sqlalchemy | test/sql/test_returning.py | {
"start": 36430,
"end": 41212
} | class ____(fixtures.TablesTest):
__requires__ = ("insert_executemany_returning",)
run_define_tables = "each"
__sparse_driver_backend__ = True
define_tables = InsertReturnDefaultsTest.define_tables
def test_insert_executemany_no_defaults_passed(self, connection):
t1 = self.tables.t1
... | InsertManyReturnDefaultsTest |
python | pytest-dev__pytest | src/_pytest/warning_types.py | {
"start": 496,
"end": 642
} | class ____(PytestWarning):
"""Warning emitted by the cache plugin in various situations."""
__module__ = "pytest"
@final
| PytestCacheWarning |
python | pypa__pip | src/pip/_vendor/packaging/_elffile.py | {
"start": 460,
"end": 515
} | class ____(enum.IntEnum):
C32 = 1
C64 = 2
| EIClass |
python | OmkarPathak__pygorithm | tests/test_sorting.py | {
"start": 3020,
"end": 3226
} | class ____(unittest.TestCase, TestSortingAlgorithm):
inplace = False
alph_support = True
@staticmethod
def sort(arr):
return merge_sort.sorti(arr, verbose=False)
| TestMergeSortIterative |
python | huggingface__transformers | src/transformers/models/roberta/modeling_roberta.py | {
"start": 38117,
"end": 38991
} | class ____(nn.Module):
"""Roberta Head for masked language modeling."""
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.decoder = nn.... | RobertaLMHead |
python | sqlalchemy__sqlalchemy | test/orm/test_versioning.py | {
"start": 59654,
"end": 61035
} | class ____(fixtures.MappedTest):
"""test for #8056"""
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"version_table",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
... | QuotedBindVersioningTest |
python | joke2k__faker | tests/providers/test_person.py | {
"start": 54628,
"end": 56690
} | class ____(unittest.TestCase):
"""Tests person in the ru_RU locale"""
def setUp(self):
self.fake = Faker("ru_RU")
Faker.seed(0)
def test_translit(self):
assert translit("Александр Сергеевич Пушкин") == "Aleksandr Sergeevich Pushkin"
assert translit("Анна Андреевна Ахматова"... | TestRuRU |
python | pytorch__pytorch | torch/_inductor/codegen/simd_kernel_features.py | {
"start": 14460,
"end": 15312
} | class ____:
"""Tracks the memory usage of a single loop in the generated kernel"""
reads: dict[str, OrderedSet[MemoryDep]] = dataclasses.field(
default_factory=functools.partial(collections.defaultdict, OrderedSet)
)
writes: dict[str, OrderedSet[MemoryDep]] = dataclasses.field(
default_... | MemoryEstimate |
python | pytorch__pytorch | torch/_dynamo/variables/user_defined.py | {
"start": 87148,
"end": 88620
} | class ____(UserDefinedObjectVariable):
"""
Represents user defined objects that are subclasses of lists.
Internally, it uses a ListVariable to represent the list part of the
variable tracker. For everything else, it falls back to
UserDefinedObjectVariable.
"""
def __init__(self, value, lis... | UserDefinedListVariable |
python | huggingface__transformers | tests/quantization/bnb/test_mixed_int8.py | {
"start": 26256,
"end": 28448
} | class ____(BaseMixedInt8Test):
def setUp(self):
super().setUp()
def test_multi_gpu_loading(self):
r"""
This tests that the model has been loaded and can be used correctly on a multi-GPU setup.
Let's just try to load a model on 2 GPUs and see if it works. The model we test has ~2... | MixedInt8TestMultiGpu |
python | streamlit__streamlit | lib/streamlit/elements/exception.py | {
"start": 1890,
"end": 12330
} | class ____:
@gather_metrics("exception")
def exception(
self, exception: BaseException, width: WidthWithoutContent = "stretch"
) -> DeltaGenerator:
"""Display an exception.
When accessing the app through ``localhost``, in the lower-right corner
of the exception, Streamlit di... | ExceptionMixin |
python | doocs__leetcode | solution/0000-0099/0057.Insert Interval/Solution.py | {
"start": 0,
"end": 532
} | class ____:
def insert(
self, intervals: List[List[int]], newInterval: List[int]
) -> List[List[int]]:
def merge(intervals: List[List[int]]) -> List[List[int]]:
intervals.sort()
ans = [intervals[0]]
for s, e in intervals[1:]:
if ans[-1][1] < s:... | Solution |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/comms.py | {
"start": 27117,
"end": 27221
} | class ____(BaseModel):
conn_id: str
type: Literal["GetConnection"] = "GetConnection"
| GetConnection |
python | bokeh__bokeh | src/bokeh/models/mappers.py | {
"start": 10755,
"end": 11149
} | class ____(ColorMapper):
''' Abstract base class for color mappers that operate on ``ImageStack``
glyphs.
These map 3D data arrays of shape ``(ny, nx, nstack)`` to 2D RGBA images
of shape ``(ny, nx)``.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwa... | StackColorMapper |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/triggers/test_dms.py | {
"start": 4148,
"end": 5462
} | class ____(TestBaseDmsTrigger):
EXPECTED_WAITER_NAME = "replication_config_deleted"
REPLICATION_CONFIG_ARN = "arn:aws:dms:region:account:config"
def test_serialization(self):
trigger = DmsReplicationConfigDeletedTrigger(replication_config_arn=self.REPLICATION_CONFIG_ARN)
classpath, kwargs ... | TestDmsReplicationConfigDeletedTrigger |
python | PyCQA__pylint | tests/functional/t/too/too_few_public_methods_37.py | {
"start": 481,
"end": 556
} | class ____:
date = None
@dataclass(frozen=True)
| ScheduledTxSearchModelOne |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_numeric.py | {
"start": 77841,
"end": 79787
} | class ____(TestCase):
# Test ones, zeros, empty and full.
def setUp(self):
super().setUp()
dtypes = {np.dtype(tp) for tp in "efdFDBbhil?"}
self.dtypes = dtypes
self.orders = {
"C": "c_contiguous"
} # XXX: reeenable when implemented, 'F': 'f_contiguous'}
... | TestCreationFuncs |
python | allegroai__clearml | clearml/backend_api/services/v2_20/projects.py | {
"start": 122927,
"end": 125167
} | class ____(Response):
"""
Response of projects.get_task_parents endpoint.
:param parents: The list of unique task parents sorted by their names
:type parents: Sequence[dict]
"""
_service = "projects"
_action = "get_task_parents"
_version = "2.20"
_schema = {
"definitions": ... | GetTaskParentsResponse |
python | pytorch__pytorch | test/dynamo/test_guard_manager.py | {
"start": 1564,
"end": 30365
} | class ____(torch._dynamo.test_case.TestCase):
def test_global_state_guard(self):
root = RootGuardManager()
guard = guards.GLOBAL_STATE(root, ["global_state_check"])
self.assertTrue(guard(None))
with set_default_dtype(torch.double):
self.assertFalse(guard(None))
... | GuardManagerTests |
python | google__flatbuffers | tests/py_test.py | {
"start": 88979,
"end": 92513
} | class ____(unittest.TestCase):
def test_nested_union_tables(self):
nestUnion = MyGame.Example.NestedUnion.NestedUnionTest.NestedUnionTestT()
nestUnion.name = 'testUnion1'
nestUnion.id = 1
nestUnion.data = MyGame.Example.NestedUnion.Vec3.Vec3T()
nestUnion.dataType = MyGame.Example.NestedUnion.Any.... | TestNestedUnionTables |
python | scrapy__scrapy | tests/test_pipeline_media.py | {
"start": 17686,
"end": 17880
} | class ____(MockedMediaPipeline):
def media_failed(self, failure, request, info):
self._mockcalled.append("media_failed")
return failure # deprecated
| MediaFailedFailurePipeline |
python | pandas-dev__pandas | pandas/tests/extension/test_datetime.py | {
"start": 4622,
"end": 4678
} | class ____(base.NDArrayBacked2DTests):
pass
| Test2DCompat |
python | openai__openai-python | src/openai/types/responses/apply_patch_tool.py | {
"start": 191,
"end": 311
} | class ____(BaseModel):
type: Literal["apply_patch"]
"""The type of the tool. Always `apply_patch`."""
| ApplyPatchTool |
python | joke2k__faker | tests/providers/test_lorem.py | {
"start": 9167,
"end": 11988
} | class ____:
"""Test cs_CZ lorem provider"""
word_list = [word.lower() for word in CsCzLoremProvider.word_list]
def test_paragraph(self, faker, num_samples):
num_sentences = 10
for _ in range(num_samples):
paragraph = faker.paragraph(nb_sentences=num_sentences)
asser... | TestCsCz |
python | django__django | django/views/generic/dates.py | {
"start": 3768,
"end": 5143
} | class ____:
"""Mixin for views manipulating day-based data."""
day_format = "%d"
day = None
def get_day_format(self):
"""
Get a day format string in strptime syntax to be used to parse the day
from url variables.
"""
return self.day_format
def get_day(self)... | DayMixin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.