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 | scipy__scipy | scipy/fftpack/tests/test_basic.py | {
"start": 12099,
"end": 14596
} | class ____:
def setup_method(self):
np.random.seed(1234)
def test_definition(self):
x = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
y = fftn(np.array(x, np.float32))
assert_(y.dtype == np.complex64,
msg="double precision output with single precisi... | TestFftnSingle |
python | django__django | tests/apps/tests.py | {
"start": 15460,
"end": 15545
} | class ____:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
| Stub |
python | tensorflow__tensorflow | tensorflow/python/ops/linalg/linear_operator_addition.py | {
"start": 12253,
"end": 15681
} | class ____(_Adder):
""""Handles additions resulting in a `LinearOperatorFullMatrix`."""
def can_add(self, op1, op2): # pylint: disable=unused-argument
return isinstance(op1, linear_operator.LinearOperator) and isinstance(
op2, linear_operator.LinearOperator)
def _add(self, op1, op2, operator_name, ... | _AddAndReturnMatrix |
python | django-import-export__django-import-export | tests/core/tests/test_base_formats.py | {
"start": 8318,
"end": 8596
} | class ____(TestCase):
def setUp(self):
self.format = base_formats.TextFormat()
def test_get_read_mode(self):
self.assertEqual("r", self.format.get_read_mode())
def test_is_binary(self):
self.assertFalse(self.format.is_binary())
| TextFormatTest |
python | tornadoweb__tornado | tornado/test/concurrent_test.py | {
"start": 1005,
"end": 1548
} | class ____(AsyncTestCase):
def test_future_set_result_unless_cancelled(self):
fut = Future() # type: Future[int]
future_set_result_unless_cancelled(fut, 42)
self.assertEqual(fut.result(), 42)
self.assertFalse(fut.cancelled())
fut = Future()
fut.cancel()
is_c... | MiscFutureTest |
python | numba__numba | numba/core/datamodel/testing.py | {
"start": 111,
"end": 3125
} | class ____(unittest.TestCase):
"""
Test the implementation of a DataModel for a frontend type.
"""
fe_type = NotImplemented
def setUp(self):
self.module = ir.Module()
self.datamodel = datamodel.default_manager[self.fe_type]
def test_as_arg(self):
"""
- Is as_arg... | DataModelTester |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 31833,
"end": 32159
} | class ____(StringEnum):
training = "training"
testing = "testing"
inference = "inference"
data_processing = "data_processing"
application = "application"
monitor = "monitor"
controller = "controller"
optimizer = "optimizer"
service = "service"
qc = "qc"
custom = "custom"
| TaskTypeEnum |
python | tensorflow__tensorflow | tensorflow/compiler/tests/sharding_util_ops_test.py | {
"start": 24445,
"end": 28638
} | class ____(xla_test.XLATestCase, parameterized.TestCase):
@parameterized.named_parameters(
('1Tensor', create_tensor_roundtrip_graph, 1),
('2Tensor', create_tensor_roundtrip_graph, 2),
('3Tensor', create_tensor_roundtrip_graph, 3),
('4Tensor', create_tensor_roundtrip_graph, 4),
('5Tenso... | XlaSplitConcatNDTest |
python | pytorch__pytorch | test/distributed/fsdp/test_hsdp_dtensor_state_dict.py | {
"start": 1059,
"end": 1670
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
torch.manual_seed(0)
self.net1 = nn.Sequential(nn.Linear(8, 16), nn.ReLU())
self.net2 = nn.Sequential(nn.Linear(16, 32), nn.ReLU())
self.net3 = nn.Sequential(nn.Linear(32, 64), nn.ReLU())
self... | DenseModel |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_logging_sink.py | {
"start": 11443,
"end": 15107
} | class ____:
def test_template_fields(self):
operator = CloudLoggingDeleteSinkOperator(
task_id=TASK_ID,
sink_name=SINK_NAME,
project_id=PROJECT_ID,
)
assert "sink_name" in operator.template_fields
_assert_common_template_fields(operator.template_fi... | TestCloudLoggingDeleteSinkOperator |
python | walkccc__LeetCode | solutions/2923. Find Champion I/2923-2.py | {
"start": 0,
"end": 133
} | class ____:
def findChampion(self, grid: list[list[int]]) -> int:
return max(range(len(grid)), key=lambda x: sum(grid[x]))
| Solution |
python | pytest-dev__pytest | testing/test_assertion.py | {
"start": 53093,
"end": 70695
} | class ____:
@pytest.mark.parametrize("op", [">=", ">", "<=", "<", "=="])
def test_set_extra_item(self, op, pytester: Pytester) -> None:
pytester.makepyfile(
f"""
def test_hello():
x = set("hello x")
y = set("hello y")
assert x {op} ... | TestSetAssertions |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-iterable/source_iterable/streams.py | {
"start": 12687,
"end": 12992
} | class ____(IterableExportStreamAdjustableRange, ABC):
def get_json_schema(self) -> Mapping[str, Any]:
"""All child stream share the same 'events' schema"""
return ResourceSchemaLoader(package_name_from_class(self.__class__)).get_schema("events")
| IterableExportEventsStreamAdjustableRange |
python | qdrant__qdrant-client | qdrant_client/local/json_path_parser.py | {
"start": 84,
"end": 195
} | class ____(str, Enum):
KEY = "key"
INDEX = "index"
WILDCARD_INDEX = "wildcard_index"
| JsonPathItemType |
python | pytorch__pytorch | test/test_mps.py | {
"start": 396062,
"end": 401567
} | class ____(TestCaseMPS):
def test_constant_pad(self):
m = torch.nn.ConstantPad2d((-2, -2, -2, -2), 3.5)
input_cpu = torch.randn(1, 16, 16, 16)
input_mps = input_cpu.detach().clone().to("mps")
r_cpu = m(input_cpu)
r_mps = m(input_mps)
self.assertEqual(r_cpu, r_mps.to("... | TestPad |
python | huggingface__transformers | tests/models/mvp/test_modeling_mvp.py | {
"start": 23349,
"end": 31153
} | class ____:
def __init__(
self,
parent,
vocab_size=99,
batch_size=13,
d_model=16,
decoder_seq_length=7,
is_training=True,
is_decoder=True,
use_attention_mask=True,
use_cache=False,
use_labels=True,
decoder_start_token_id... | MvpStandaloneDecoderModelTester |
python | Lightning-AI__lightning | tests/tests_pytorch/callbacks/test_finetuning_callback.py | {
"start": 8274,
"end": 10524
} | class ____(BaseFinetuning):
def freeze_before_training(self, pl_module: LightningModule):
self.freeze(pl_module.layer)
def finetune_function(self, pl_module: LightningModule, epoch: int, optimizer: Optimizer):
self.unfreeze_and_add_param_group(pl_module.layer[epoch + 1], optimizer)
def test_b... | OnEpochLayerFinetuning |
python | pandas-dev__pandas | asv_bench/benchmarks/arithmetic.py | {
"start": 10903,
"end": 11405
} | class ____:
params = offsets
param_names = ["offset"]
def setup(self, offset):
N = 10000
rng = date_range(start="1/1/2000", periods=N, freq="min")
self.rng = rng
self.ser = Series(rng)
def time_add_series_offset(self, offset):
with warnings.catch_warnings(record... | OffsetArrayArithmetic |
python | tensorflow__tensorflow | tensorflow/python/distribute/cross_device_ops_test.py | {
"start": 5789,
"end": 58309
} | class ____(test.TestCase, parameterized.TestCase):
def setUp(self):
super().setUp()
# Enabling collectives can be done in "setUpClass", but requires using
# different collective_keys in different tests as collectives are reused
# across tests. Always resetting collective ops before each test offers
... | CollectiveOpsTest |
python | getsentry__sentry | tests/snuba/rules/conditions/test_event_frequency.py | {
"start": 23386,
"end": 31122
} | class ____(SnubaTestCase, RuleTestCase, PerformanceIssueTestCase):
__test__ = Abstract(__module__, __qualname__)
def add_event(self, data, project_id, timestamp):
raise NotImplementedError
def increment(self, event, count, environment=None, timestamp=None):
raise NotImplementedError
d... | StandardIntervalTestBase |
python | ipython__ipython | IPython/utils/tokenutil.py | {
"start": 329,
"end": 6552
} | class ____(NamedTuple):
token: int
text: str
start: int
end: int
line: str
def generate_tokens(readline) -> Generator[TokenInfo, None, None]:
"""wrap generate_tkens to catch EOF errors"""
try:
yield from tokenize.generate_tokens(readline)
except tokenize.TokenError:
# c... | Token |
python | pytorch__pytorch | torch/autograd/graph.py | {
"start": 16608,
"end": 23459
} | class ____(RemovableHandle):
handles: tuple[RemovableHandle, ...]
def __init__(self, handles: tuple[RemovableHandle, ...]) -> None:
self.handles = handles
def remove(self) -> None:
for handle in self.handles:
handle.remove()
def __getstate__(self) -> tuple[RemovableHandle,... | _MultiHandle |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/callbackProtocol10.py | {
"start": 520,
"end": 628
} | class ____(Protocol[P]):
def __call__(self, a: int, *args: P.args, **kwargs: P.kwargs) -> None: ...
| Proto4 |
python | celery__celery | celery/contrib/sphinx.py | {
"start": 2265,
"end": 3391
} | class ____(PyFunction):
"""Sphinx task directive."""
def get_signature_prefix(self, sig):
return [nodes.Text(self.env.config.celery_task_prefix)]
def autodoc_skip_member_handler(app, what, name, obj, skip, options):
"""Handler for autodoc-skip-member event."""
# Celery tasks created with the ... | TaskDirective |
python | pypa__warehouse | warehouse/integrations/secrets/utils.py | {
"start": 2484,
"end": 3106
} | class ____(TokenLeakMatcher):
name = "pypi_api_token"
# Macaroons are urlsafe_b64 encodeded so non-alphanumeric chars are - and _
# https://github.com/ecordell/pymacaroons/blob/06b55110eda2fb192c130dee0bcedf8b124d1056/pymacaroons/serializers/binary_serializer.py#L32
pattern = re.compile(r"pypi-[A-Za-z0-... | PlainTextTokenLeakMatcher |
python | astropy__astropy | astropy/coordinates/tests/test_intermediate_transformations.py | {
"start": 41651,
"end": 43919
} | class ____:
# TETE and CIRS use get_location_gcrs to get obsgeoloc and obsgeovel
# with knowledge of some of the matrices. Check that this is consistent
# with a direct transformation.
def setup_class(cls):
cls.loc = loc = EarthLocation.from_geodetic(
np.linspace(0, 360, 6) * u.deg, ... | TestGetLocationGCRS |
python | wandb__wandb | wandb/vendor/pygments/style.py | {
"start": 4554,
"end": 4807
} | class ____(object):
#: overall background color (``None`` means transparent)
background_color = '#ffffff'
#: highlight background color
highlight_color = '#ffffcc'
#: Style definitions for individual token types.
styles = {}
| Style |
python | facelessuser__pymdown-extensions | pymdownx/tabbed.py | {
"start": 11414,
"end": 14955
} | class ____(Treeprocessor):
"""Tab tree processor."""
def __init__(self, md, config):
"""Initialize."""
super().__init__(md)
self.slugify = config["slugify"]
self.alternate = config["alternate_style"]
self.sep = config["separator"]
self.combine_header_slug = con... | TabbedTreeprocessor |
python | plotly__plotly.py | plotly/graph_objs/barpolar/unselected/_textfont.py | {
"start": 233,
"end": 2587
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "barpolar.unselected"
_path_str = "barpolar.unselected.textfont"
_valid_props = {"color"}
@property
def color(self):
"""
Sets the text font color of unselected points, applied only
when a selection exists.
The ... | Textfont |
python | euske__pdfminer | setup.py | {
"start": 132,
"end": 2266
} | class ____(install):
def run(self):
import os.path
import pdfminer
from pdfminer.cmapdb import convert_cmap
outdir = os.path.join(os.path.join(self.install_lib, 'pdfminer'), 'cmap')
print('installing cmap: %r...' % outdir)
os.makedirs(outdir, exist_ok=True)
c... | install_cmap |
python | pytorch__pytorch | torch/_higher_order_ops/flex_attention.py | {
"start": 21572,
"end": 44560
} | class ____(torch.autograd.Function):
@staticmethod
# pyrefly: ignore [bad-override]
def forward(
ctx: Any,
query: Tensor,
key: Tensor,
value: Tensor,
fw_graph: Callable,
joint_graph: Callable,
block_mask: tuple[Any, ...],
scale: float,
... | FlexAttentionAutogradOp |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mssql/base.py | {
"start": 37620,
"end": 37971
} | class ____(sqltypes.REAL):
"""the SQL Server REAL datatype."""
def __init__(self, **kw):
# REAL is a synonym for FLOAT(24) on SQL server.
# it is only accepted as the word "REAL" in DDL, the numeric
# precision value is not allowed to be present
kw.setdefault("precision", 24)
... | REAL |
python | pandas-dev__pandas | pandas/tests/indexes/interval/test_constructors.py | {
"start": 528,
"end": 7757
} | class ____:
"""
Common tests for all variations of IntervalIndex construction. Input data
to be supplied in breaks format, then converted by the subclass method
get_kwargs_from_breaks to the expected format.
"""
@pytest.mark.parametrize(
"breaks_and_expected_subtype",
[
... | ConstructorTests |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_internal/models/wheel.py | {
"start": 259,
"end": 3601
} | class ____:
"""A wheel file"""
wheel_file_re = re.compile(
r"""^(?P<namever>(?P<name>[^\s-]+?)-(?P<ver>[^\s-]*?))
((-(?P<build>\d[^-]*?))?-(?P<pyver>[^\s-]+?)-(?P<abi>[^\s-]+?)-(?P<plat>[^\s-]+?)
\.whl|\.dist-info)$""",
re.VERBOSE,
)
def __init__(self, filename: str) ->... | Wheel |
python | neetcode-gh__leetcode | python/0042-trapping-rain-water.py | {
"start": 0,
"end": 534
} | class ____:
def trap(self, height: List[int]) -> int:
if not height:
return 0
l, r = 0, len(height) - 1
leftMax, rightMax = height[l], height[r]
res = 0
while l < r:
if leftMax < rightMax:
l += 1
leftMax = max(leftMax, ... | Solution |
python | sqlalchemy__sqlalchemy | test/orm/test_session.py | {
"start": 13135,
"end": 20725
} | class ____(_fixtures.FixtureTest):
run_inserts = None
def test_close_all_sessions(self):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
s1 = fixture_session()
u1 = User()
s1.add(u1)
s2 = fixture_session()
... | SessionUtilTest |
python | django__django | tests/m2m_regress/models.py | {
"start": 570,
"end": 857
} | class ____(Tag):
tags = models.ManyToManyField(Tag, related_name="tag_collections")
def __str__(self):
return self.name
# A related_name is required on one of the ManyToManyField entries here because
# they are both addressable as reverse relations from Tag.
| TagCollection |
python | arrow-py__arrow | arrow/locales.py | {
"start": 42436,
"end": 44648
} | class ____(SlavicBaseLocale):
names = ["mk-latn", "mk-mk-latn"]
past = "pred {0}"
future = "za {0}"
timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = {
"now": "sega",
"second": "edna sekunda",
"seconds": {
"singular": "{0} sekunda",
... | MacedonianLatinLocale |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_webagg_core.py | {
"start": 3746,
"end": 4690
} | class ____(backend_bases.TimerBase):
def __init__(self, *args, **kwargs):
self._task = None
super().__init__(*args, **kwargs)
async def _timer_task(self, interval):
while True:
try:
await asyncio.sleep(interval)
self._on_timer()
... | TimerAsyncio |
python | getsentry__sentry | src/sentry/issues/endpoints/organization_group_suspect_flags.py | {
"start": 631,
"end": 780
} | class ____(TypedDict):
flag: str
score: float
baseline_percent: float
distribution: Distribution
is_filtered: bool
| ResponseDataItem |
python | huggingface__transformers | src/transformers/models/minimax/modular_minimax.py | {
"start": 28838,
"end": 28917
} | class ____(MixtralForTokenClassification):
pass
| MiniMaxForTokenClassification |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/sensors/test_bedrock.py | {
"start": 5638,
"end": 7858
} | class ____:
SENSOR = BedrockKnowledgeBaseActiveSensor
def setup_method(self):
self.default_op_kwargs = dict(
task_id="test_bedrock_knowledge_base_active_sensor",
knowledge_base_id="knowledge_base_id",
poke_interval=5,
max_retries=1,
)
self... | TestBedrockKnowledgeBaseActiveSensor |
python | huggingface__transformers | tests/models/mobilevit/test_modeling_mobilevit.py | {
"start": 1391,
"end": 1751
} | class ____(ConfigTester):
def create_and_test_config_common_properties(self):
config = self.config_class(**self.inputs_dict)
self.parent.assertTrue(hasattr(config, "hidden_sizes"))
self.parent.assertTrue(hasattr(config, "neck_hidden_sizes"))
self.parent.assertTrue(hasattr(config, "nu... | MobileViTConfigTester |
python | python-openxml__python-docx | src/docx/oxml/coreprops.py | {
"start": 442,
"end": 10768
} | class ____(BaseOxmlElement):
"""`<cp:coreProperties>` element, the root element of the Core Properties part.
Stored as `/docProps/core.xml`. Implements many of the Dublin Core document metadata
elements. String elements resolve to an empty string ("") if the element is not
present in the XML. String el... | CT_CoreProperties |
python | scikit-learn__scikit-learn | sklearn/externals/_arff.py | {
"start": 20361,
"end": 21753
} | class ____:
def decode_rows(self, stream, conversors):
for row in stream:
values = _parse_values(row)
if not isinstance(values, dict):
raise BadLayout()
try:
yield {key: None if value is None else conversors[key](value)
... | LODGeneratorData |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/ui/dashboard.py | {
"start": 1029,
"end": 1169
} | class ____(BaseModel):
"""DAG Run States for responses."""
queued: int
running: int
success: int
failed: int
| DAGRunStates |
python | pypa__hatch | src/hatch/project/frontend/core.py | {
"start": 332,
"end": 5430
} | class ____:
def __init__(self, project: Project, env: EnvironmentInterface) -> None:
self.__project = project
self.__env = env
self.__scripts = StandardBuildFrontendScripts(self.__project, self.__env)
self.__hatch = HatchBuildFrontend(self.__project, self.__env)
@property
de... | BuildFrontend |
python | django-guardian__django-guardian | guardian/testapp/tests/test_indexes.py | {
"start": 604,
"end": 7292
} | class ____(TransactionTestCase):
"""Test database indexes for Guardian models."""
def setUp(self):
"""Set up test data."""
self.user = User.objects.create_user(username="testuser", email="test@example.com")
self.group = Group.objects.create(name="testgroup")
self.project = Proje... | IndexTestCase |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/base.py | {
"start": 115860,
"end": 202175
} | class ____(default.DefaultDialect):
name = "postgresql"
supports_statement_cache = True
supports_alter = True
max_identifier_length = 63
supports_sane_rowcount = True
bind_typing = interfaces.BindTyping.RENDER_CASTS
supports_native_enum = True
supports_native_boolean = True
support... | PGDialect |
python | streamlit__streamlit | lib/streamlit/watcher/polling_path_watcher.py | {
"start": 1157,
"end": 4402
} | class ____:
"""Watches a path on disk via a polling loop."""
_executor = ThreadPoolExecutor(max_workers=_MAX_WORKERS)
@staticmethod
def close_all() -> None:
"""Close top-level watcher object.
This is a no-op, and exists for interface parity with
EventBasedPathWatcher.
... | PollingPathWatcher |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/coercions.py | {
"start": 33287,
"end": 34190
} | class ____(_CoerceLiterals, RoleImpl):
__slots__ = ()
def _post_coercion(
self, resolved, *, original_element, argname=None, **kw
):
if resolved is not original_element and not isinstance(
original_element, str
):
# use same method as Connection uses
... | StatementImpl |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/decorator4.py | {
"start": 183,
"end": 406
} | class ____:
pass
def decorator1(fn):
# This decorator returns a value that is
# inferred to be a union containing an Unknown type.
if fn:
return my_module.unknown
return Class2
@decorator1
| Class2 |
python | pikepdf__pikepdf | src/pikepdf/_methods.py | {
"start": 27229,
"end": 27707
} | class ____:
def keys(self):
return KeysView(self._as_map())
def values(self):
return ValuesView(self._as_map())
def items(self):
return ItemsView(self._as_map())
get = MutableMapping.get
pop = MutableMapping.pop
popitem = MutableMapping.popitem
clear = MutableMappi... | Extend_NameTree |
python | allegroai__clearml | clearml/task.py | {
"start": 4643,
"end": 256599
} | class ____(_Task):
"""
The ``Task`` class is a code template for a Task object which, together with its connected experiment components,
represents the current running experiment. These connected components include hyperparameters, loggers,
configuration, label enumeration, models, and other artifacts.
... | Task |
python | allegroai__clearml | clearml/backend_api/services/v2_9/tasks.py | {
"start": 322670,
"end": 324298
} | class ____(Response):
"""
Response of tasks.validate endpoint.
"""
_service = "tasks"
_action = "validate"
_version = "2.9"
_schema = {"additionalProperties": False, "definitions": {}, "type": "object"}
response_mapping = {
GetByIdRequest: GetByIdResponse,
GetAllRequest: GetAllRe... | ValidateResponse |
python | scipy__scipy | scipy/stats/tests/test_stats.py | {
"start": 288089,
"end": 293095
} | class ____:
def pmean_reference(a, p):
return (np.sum(a**p) / a.size)**(1/p)
def wpmean_reference(a, p, weights):
return (np.sum(weights * a**p) / np.sum(weights))**(1/p)
def test_bad_exponent(self, xp):
with pytest.raises(ValueError, match='Power mean only defined for'):
... | TestPMean |
python | huggingface__transformers | src/transformers/models/time_series_transformer/modeling_time_series_transformer.py | {
"start": 2973,
"end": 4729
} | class ____(nn.Module):
"""
Standardize features by calculating the mean and scaling along the first dimension, and then normalizes it by
subtracting from the mean and dividing by the standard deviation.
"""
def __init__(self, config: TimeSeriesTransformerConfig):
super().__init__()
... | TimeSeriesStdScaler |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/orchestrator/orchestrator/logging/publish_connector_lifecycle.py | {
"start": 1082,
"end": 3360
} | class ____:
"""
This class is used to log the lifecycle of a publishing a connector to the registries.
It is used to log to the logger and slack (if enabled).
This is nessesary as this lifecycle is not a single job, asset, resource, schedule, or sensor.
"""
@staticmethod
def stage_to_log_... | PublishConnectorLifecycle |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/internal/conjecture/data.py | {
"start": 3340,
"end": 3536
} | class ____(IntEnum):
OVERRUN = 0
INVALID = 1
VALID = 2
INTERESTING = 3
def __repr__(self) -> str:
return f"Status.{self.name}"
@dataclass(slots=True, frozen=True)
| Status |
python | numba__numba | numba/cuda/vectorizers.py | {
"start": 7246,
"end": 8177
} | class ____(deviceufunc.DeviceVectorize):
def _compile_core(self, sig):
cudevfn = cuda.jit(sig, device=True, inline=True)(self.pyfunc)
return cudevfn, cudevfn.overloads[sig.args].signature.return_type
def _get_globals(self, corefn):
glbl = self.pyfunc.__globals__.copy()
glbl.upda... | CUDAVectorize |
python | walkccc__LeetCode | solutions/275. H-Index II/275.py | {
"start": 0,
"end": 201
} | class ____:
def hIndex(self, citations: list[int]) -> int:
n = len(citations)
return n - bisect.bisect_left(range(n), n,
key=lambda m: citations[m] + m)
| Solution |
python | spyder-ide__spyder | spyder/plugins/findinfiles/plugin.py | {
"start": 940,
"end": 7146
} | class ____(SpyderDockablePlugin):
"""
Find in files DockWidget.
"""
NAME = 'find_in_files'
REQUIRES = []
OPTIONAL = [
Plugins.Editor,
Plugins.Projects,
Plugins.MainMenu,
Plugins.WorkingDirectory,
]
TABIFY = [Plugins.VariableExplorer]
WIDGET_CLASS = Fin... | FindInFiles |
python | google__flatbuffers | grpc/examples/python/greeter/greeter_grpc.fb.py | {
"start": 179,
"end": 529
} | class ____(object):
"""Interface exported by the server."""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.SayHello = channel.unary_unary(method='/models.Greeter/SayHello')
self.SayManyHellos = channel.unary_stream(
method='/models.Greeter/... | GreeterStub |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/exc.py | {
"start": 12848,
"end": 12976
} | class ____(InvalidRequestError):
"""SQL was attempted without a database connection to execute it on."""
| UnboundExecutionError |
python | kamyu104__LeetCode-Solutions | Python/binary-tree-level-order-traversal.py | {
"start": 154,
"end": 747
} | class ____(object):
# @param root, a tree node
# @return a list of lists of integers
def levelOrder(self, root):
if root is None:
return []
result, current = [], [root]
while current:
next_level, vals = [], []
for node in current:
v... | Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/syntax_errors/return_outside_function.py | {
"start": 134,
"end": 215
} | class ____:
return 1 # error
def f():
class C:
return 1 # error
| C |
python | imageio__imageio | imageio/plugins/_swf.py | {
"start": 9461,
"end": 9666
} | class ____(ControlTag):
def __init__(self):
ControlTag.__init__(self)
self.tagtype = 69
def process_tag(self):
self.bytes = "\x00".encode("ascii") * (1 + 3)
| FileAttributesTag |
python | pandas-dev__pandas | pandas/tests/frame/methods/test_set_index.py | {
"start": 1469,
"end": 19586
} | class ____:
def test_set_index_multiindex(self):
# segfault in GH#3308
d = {"t1": [2, 2.5, 3], "t2": [4, 5, 6]}
df = DataFrame(d)
tuples = [(0, 1), (0, 2), (1, 2)]
df["tuples"] = tuples
index = MultiIndex.from_tuples(df["tuples"])
# it works!
df.set_i... | TestSetIndex |
python | django__django | tests/fixtures_regress/models.py | {
"start": 7015,
"end": 7123
} | class ____(BaseNKModel):
b_set = models.ManyToManyField("M2MComplexB", through="M2MThroughAB")
| M2MComplexA |
python | openai__openai-python | src/openai/types/realtime/realtime_audio_input_turn_detection.py | {
"start": 328,
"end": 2381
} | class ____(BaseModel):
type: Literal["server_vad"]
"""Type of turn detection, `server_vad` to turn on simple Server VAD."""
create_response: Optional[bool] = None
"""
Whether or not to automatically generate a response when a VAD stop event
occurs.
"""
idle_timeout_ms: Optional[int] = ... | ServerVad |
python | dagster-io__dagster | python_modules/dagster-test/dagster_test/components/simple_pipes_script_asset.py | {
"start": 706,
"end": 854
} | class ____(BaseModel):
asset_key: str
filename: str
# Same schema used for file generation and defs generation
| SimplePipesScriptScaffoldParams |
python | gevent__gevent | src/gevent/tests/test__server.py | {
"start": 15978,
"end": 17632
} | class ____(TestDefaultSpawn):
def get_spawn(self):
return 2
@greentest.skipIf(greentest.EXPECT_POOR_TIMER_RESOLUTION,
"If we have bad timer resolution and hence increase timeouts, "
"it can be hard to sleep for a correct amount of time that lets "
... | TestPoolSpawn |
python | python__mypy | mypy/literals.py | {
"start": 4180,
"end": 9303
} | class ____(ExpressionVisitor[Key | None]):
def visit_int_expr(self, e: IntExpr) -> Key:
return ("Literal", e.value)
def visit_str_expr(self, e: StrExpr) -> Key:
return ("Literal", e.value)
def visit_bytes_expr(self, e: BytesExpr) -> Key:
return ("Literal", e.value)
def visit_f... | _Hasher |
python | PrefectHQ__prefect | src/prefect/server/events/actions.py | {
"start": 37123,
"end": 37584
} | class ____(DeploymentCommandAction):
"""Resumes the given Deployment"""
type: Literal["resume-deployment"] = "resume-deployment"
_action_description: ClassVar[str] = "Resuming deployment"
async def command(
self,
orchestration: "OrchestrationClient",
deployment_id: UUID,
... | ResumeDeployment |
python | great-expectations__great_expectations | great_expectations/_docs_decorators.py | {
"start": 854,
"end": 12775
} | class ____:
_public_api: dict[str, list[_PublicApiInfo]] = {}
# Only used for testing
_class_registry: dict[str, set[str]] = defaultdict(set)
_docstring_violations: set[str] = set()
# This is a special key that is used to indicate that a class definition
# is being added to the registry.
C... | _PublicApiIntrospector |
python | sqlalchemy__sqlalchemy | test/dialect/sqlite/test_dialect.py | {
"start": 1610,
"end": 5964
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
__only_on__ = "sqlite"
__backend__ = True
def test_default_reflection(self, connection, metadata):
specs = [
(String(3), '"foo"'),
(sqltypes.NUMERIC(10, 2), "100.50"),
(Integer, "5"),
(Boolean, "False... | DefaultsTest |
python | astropy__astropy | astropy/utils/masked/tests/test_table.py | {
"start": 450,
"end": 820
} | class ____:
@classmethod
def setup_arrays(cls):
cls.a = np.array([3.0, 5.0, 0.0])
cls.mask_a = np.array([True, False, False])
@classmethod
def setup_class(cls):
cls.setup_arrays()
cls.ma = Masked(cls.a, mask=cls.mask_a)
cls.ma.info.format = ".1f"
cls.t = ... | MaskedArrayTableSetup |
python | astropy__astropy | astropy/timeseries/tests/test_common.py | {
"start": 528,
"end": 2355
} | class ____:
def test_stacking(self):
ts = vstack([self.series, self.series])
assert isinstance(ts, self.series.__class__)
def test_row_slicing(self):
ts = self.series[:2]
assert isinstance(ts, self.series.__class__)
def test_row_indexing(self):
assert self.series[1]... | CommonTimeSeriesTests |
python | huggingface__transformers | tests/models/kosmos2_5/test_modeling_kosmos2_5.py | {
"start": 9612,
"end": 19637
} | class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (Kosmos2_5Model, Kosmos2_5ForConditionalGeneration) if is_torch_available() else ()
all_generative_model_classes = (Kosmos2_5ForConditionalGeneration,) if is_torch_available() else ()
pipeline_mo... | Kosmos2_5ModelTest |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_comm_hooks.py | {
"start": 2302,
"end": 2506
} | class ____:
__slots__ = ["process_group", "noise"]
def __init__(self, process_group: dist.ProcessGroup, noise: int):
self.process_group = process_group
self.noise = noise
| DummyState |
python | bokeh__bokeh | src/bokeh/util/compiler.py | {
"start": 4843,
"end": 4989
} | class ____(Inline):
''' An implementation of a Less CSS style sheet.
'''
@property
def lang(self) -> str:
return "less"
| Less |
python | pennersr__django-allauth | allauth/socialaccount/providers/twitter/views.py | {
"start": 562,
"end": 1373
} | class ____(OAuthAdapter):
provider_id = "twitter"
request_token_url = "https://api.x.com/oauth/request_token" # nosec
access_token_url = "https://api.x.com/oauth/access_token" # nosec
# Issue #42 -- this one authenticates over and over again...
# authorize_url = 'https://api.twitter.com/oauth/auth... | TwitterOAuthAdapter |
python | sympy__sympy | sympy/integrals/integrals.py | {
"start": 1531,
"end": 65075
} | class ____(AddWithLimits):
"""Represents unevaluated integral."""
__slots__ = ()
args: tuple[Expr, Tuple] # type: ignore
def __new__(cls, function, *symbols, **assumptions) -> Integral:
"""Create an unevaluated integral.
Explanation
===========
Arguments are an integ... | Integral |
python | great-expectations__great_expectations | great_expectations/util.py | {
"start": 2305,
"end": 49347
} | class ____(dict):
"""
Bi-directional hashmap: https://stackoverflow.com/a/21894086
"""
def __init__(self, *args: List[Any], **kwargs: Dict[str, Any]) -> None:
super().__init__(*args, **kwargs)
self.inverse: Dict = {}
for key, value in self.items():
self.inverse.setde... | bidict |
python | streamlit__streamlit | lib/tests/streamlit/elements/text_test.py | {
"start": 888,
"end": 3545
} | class ____(DeltaGeneratorTestCase):
"""Test st.text API."""
def test_st_text(self):
"""Test st.text."""
st.text("some text")
el = self.get_delta_from_queue().new_element
assert el.text.body == "some text"
def test_st_text_with_help(self):
"""Test st.text with help.... | StTextAPITest |
python | great-expectations__great_expectations | contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/rule_based_profiler/data_assistant_result/data_profiler_structured_data_assistant_result.py | {
"start": 243,
"end": 1117
} | class ____(DataAssistantResult):
"""
Note (10/18/2022): Plotting functionality is not implemented.
"""
@property
def metric_expectation_map(self) -> Dict[Union[str, Tuple[str]], str]:
"""
A mapping is defined for which metrics to plot and their associated expectations.
"""
... | DataProfilerStructuredDataAssistantResult |
python | ray-project__ray | python/ray/train/xgboost/_xgboost_utils.py | {
"start": 5267,
"end": 8873
} | class ____(RayReportCallback):
"""XGBoost callback to save checkpoints and report metrics.
Args:
metrics: Metrics to report. If this is a list,
each item describes the metric key reported to XGBoost,
and it will be reported under the same name.
This can also be a dic... | RayTrainReportCallback |
python | pytorch__pytorch | test/onnx/model_defs/op_test.py | {
"start": 559,
"end": 661
} | class ____(nn.Module):
def forward(self, input):
return input.permute(2, 3, 0, 1)
| PermuteNet |
python | getsentry__sentry | src/sentry/workflow_engine/models/action_alertruletriggeraction.py | {
"start": 202,
"end": 533
} | class ____(DefaultFieldsModel):
"""
A lookup model for Actions (new) and AlertRuleTriggerActions (legacy)
"""
__relocation_scope__ = RelocationScope.Excluded
alert_rule_trigger_action_id = BoundedBigIntegerField(db_index=True)
action = FlexibleForeignKey("workflow_engine.Action")
| ActionAlertRuleTriggerAction |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B004.py | {
"start": 956,
"end": 1839
} | class ____:
def __init__(self): self.__call__ = None
assert hasattr(A(), "__call__")
assert callable(A()) is False
# https://github.com/astral-sh/ruff/issues/20440
def test_invalid_hasattr_calls():
hasattr(0, "__call__", 0) # 3 args - invalid
hasattr(0, "__call__", x=0) # keyword arg - invalid
hasa... | A |
python | run-llama__llama_index | llama-index-integrations/storage/kvstore/llama-index-storage-kvstore-duckdb/tests/test_storage_kvstore_duckdb.py | {
"start": 1491,
"end": 4897
} | class ____:
@pytest.fixture
def kv_store(self, persistent: str) -> DuckDBKVStore:
if persistent == "memory":
return memory_store()
return disk_store()
def test_put(self, kv_store: DuckDBKVStore):
key = "id_1"
value = {"name": "John Doe", "text": "Hello, world!"}... | TestStore |
python | python__mypy | mypy/server/aststrip.py | {
"start": 3410,
"end": 11278
} | class ____(TraverserVisitor):
def __init__(self, saved_class_attrs: SavedAttributes) -> None:
# The current active class.
self.type: TypeInfo | None = None
# This is True at class scope, but not in methods.
self.is_class_body = False
# By default, process function definitions... | NodeStripVisitor |
python | wandb__wandb | wandb/vendor/pygments/styles/murphy.py | {
"start": 383,
"end": 2751
} | class ____(Style):
"""
Murphy's style from CodeRay.
"""
default_style = ""
styles = {
Whitespace: "#bbbbbb",
Comment: "#666 italic",
Comment.Preproc: "#579 noitalic",
Comment.Special: "#c00 bold",
Keyword... | MurphyStyle |
python | tensorflow__tensorflow | tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py | {
"start": 40039,
"end": 42613
} | class ____(test.TestCase):
def _testOneHot(
self, truth, use_gpu=False, expected_err_re=None, raises=None, **inputs
):
with self.cached_session(use_gpu=use_gpu):
if raises is not None:
with self.assertRaises(raises):
array_ops.one_hot(**inputs)
else:
ans = array_ops.... | OneHotTest |
python | crytic__slither | slither/printers/functions/cfg.py | {
"start": 104,
"end": 1285
} | class ____(AbstractPrinter):
ARGUMENT = "cfg"
HELP = "Export the CFG of each functions"
WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#cfg"
def output(self, filename: str) -> Output:
"""
_filename is not used
Args:
_filename(string)
... | CFG |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_gradient08.py | {
"start": 315,
"end": 1440
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_gradient08.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.... | TestCompareXLSXFiles |
python | spack__spack | var/spack/test_repos/spack_repo/duplicates_test/packages/cycle_b/package.py | {
"start": 216,
"end": 578
} | class ____(Package):
"""Package that would lead to cycles if default variant values are used"""
homepage = "http://www.example.com"
url = "http://www.example.com/tdep-1.0.tar.gz"
version("2.0", md5="0123456789abcdef0123456789abcdef")
variant("cycle", default=True, description="activate cycles")
... | CycleB |
python | xlwings__xlwings | xlwings/main.py | {
"start": 148217,
"end": 150109
} | class ____(Collection):
"""
A collection of all :meth:`sheet <Sheet>` objects:
>>> import xlwings as xw
>>> xw.sheets # active book
Sheets([<Sheet [Book1]Sheet1>, <Sheet [Book1]Sheet2>])
>>> xw.Book('Book1').sheets # specific book
Sheets([<Sheet [Book1]Sheet1>, <Sheet [Book1]Sheet2>])
... | Sheets |
python | kamyu104__LeetCode-Solutions | Python/closest-nodes-queries-in-a-binary-search-tree.py | {
"start": 53,
"end": 177
} | class ____(object):
def __init__(self, val=0, left=None, right=None):
pass
# iterative dfs, binary search
| TreeNode |
python | dask__distributed | distributed/metrics.py | {
"start": 11163,
"end": 14464
} | class ____:
"""Add-on to :class:`ContextMeter` that helps in the case where:
- The code to be metered is not easily expressed as a self-contained code block
e.g. you want to measure latency in the asyncio event loop before and after
running a task
- You want to alter the metrics depending on ho... | DelayedMetricsLedger |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.