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 | getsentry__sentry | tests/sentry/api/endpoints/test_organization_sampling_project_span_counts.py | {
"start": 484,
"end": 7054
} | class ____(MetricsEnhancedPerformanceTestCase):
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.org = self.create_organization(owner=self.user)
self.project_1 = self.create_project(organization=self.org, name="project_1")
self.project_2 = self.crea... | OrganizationSamplingProjectSpanCountsTest |
python | Netflix__metaflow | metaflow/util.py | {
"start": 1277,
"end": 21035
} | class ____(object):
# Provide a temporary directory since Python 2.7 does not have it inbuilt
def __enter__(self):
self.name = tempfile.mkdtemp()
return self.name
def __exit__(self, exc_type, exc_value, traceback):
shutil.rmtree(self.name)
def cached_property(getter):
@wraps(g... | TempDir |
python | getsentry__sentry | tests/sentry/integrations/jira/test_sentry_issue_details.py | {
"start": 7282,
"end": 12457
} | class ____(APITestCase):
def setUp(self) -> None:
super().setUp()
self.first_seen = datetime(2015, 8, 13, 3, 8, 25, tzinfo=timezone.utc)
self.last_seen = datetime(2016, 1, 13, 3, 8, 25, tzinfo=timezone.utc)
self.issue_key = "APP-123"
self.path = (
absolute_uri(f"... | JiraIssueHookControlTest |
python | django-import-export__django-import-export | import_export/resources.py | {
"start": 45116,
"end": 53939
} | class ____(Resource, metaclass=ModelDeclarativeMetaclass):
"""
ModelResource is Resource subclass for handling Django models.
"""
DEFAULT_RESOURCE_FIELD = Field
WIDGETS_MAP = {
"ManyToManyField": "get_m2m_widget",
"OneToOneField": "get_fk_widget",
"ForeignKey": "get_fk_widg... | ModelResource |
python | crytic__slither | slither/detectors/statements/costly_operations_in_loop.py | {
"start": 1862,
"end": 4096
} | class ____(AbstractDetector):
ARGUMENT = "costly-loop"
HELP = "Costly operations in a loop"
IMPACT = DetectorClassification.INFORMATIONAL
# Overall the detector seems precise, but it does not take into account
# case where there are external calls or internal calls that might read the state
# v... | CostlyOperationsInLoop |
python | ray-project__ray | python/ray/serve/llm/request_router.py | {
"start": 226,
"end": 1797
} | class ____(_PrefixCacheAffinityRouter):
"""A request router that is aware of the KV cache.
This router optimizes request routing by considering KV cache locality,
directing requests with similar prefixes to the same replica to improve
cache hit rates.
The internal policy is this (it may change in ... | PrefixCacheAffinityRouter |
python | scikit-learn__scikit-learn | sklearn/externals/_packaging/_structures.py | {
"start": 1475,
"end": 2196
} | class ____:
def __repr__(self) -> str:
return "Infinity"
def __hash__(self) -> int:
return hash(repr(self))
def __lt__(self, other: object) -> bool:
return False
def __le__(self, other: object) -> bool:
return False
def __eq__(self, other: object) -> bool:
... | InfinityType |
python | mahmoud__glom | glom/reduction.py | {
"start": 4795,
"end": 8567
} | class ____(Fold):
"""The `Flatten` specifier type is used to combine iterables. By
default it flattens an iterable of iterables into a single list
containing items from all iterables.
>>> target = [[1], [2, 3]]
>>> glom(target, Flatten())
[1, 2, 3]
You can also set *init* to ``"lazy"``, wh... | Flatten |
python | great-expectations__great_expectations | great_expectations/core/expectation_validation_result.py | {
"start": 2239,
"end": 16686
} | class ____(SerializableDictDot):
"""An Expectation validation result.
Args:
success: Whether the Expectation validation was successful.
expectation_config: The configuration of the Expectation that was validated.
result: The result details that can take one of many result formats.
... | ExpectationValidationResult |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_image26.py | {
"start": 315,
"end": 1060
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("image26.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workbook(... | TestCompareXLSXFiles |
python | pennersr__django-allauth | allauth/socialaccount/providers/coinbase/provider.py | {
"start": 315,
"end": 865
} | class ____(OAuth2Provider):
id = "coinbase"
name = "Coinbase"
account_class = CoinbaseAccount
oauth2_adapter_class = CoinbaseOAuth2Adapter
def get_default_scope(self):
# See: https://coinbase.com/docs/api/permissions
return ["wallet:user:email"]
def extract_uid(self, data):
... | CoinbaseProvider |
python | spyder-ide__spyder | spyder/utils/installers.py | {
"start": 977,
"end": 1229
} | class ____(SpyderInstallerError):
"""Error for missing dependencies"""
def _msg(self, msg):
msg = msg.replace('<br>', '\n')
msg = 'Missing dependencies' + textwrap.indent(msg, ' ')
return msg
| InstallerMissingDependencies |
python | huggingface__transformers | tests/models/fsmt/test_modeling_fsmt.py | {
"start": 5094,
"end": 11652
} | class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (FSMTModel, FSMTForConditionalGeneration) if is_torch_available() else ()
pipeline_model_mapping = (
{
"feature-extraction": FSMTModel,
"summarization": FSMTForConditi... | FSMTModelTest |
python | cython__cython | Cython/Compiler/PyrexTypes.py | {
"start": 141610,
"end": 143429
} | class ____(BaseType):
# name string
# cname string
# type PyrexType
# pos source file position
# FIXME: is this the right setup? should None be allowed here?
not_none = False
or_none = False
accept_none = True
accept_builtin_subtypes = False
annotatio... | CFuncTypeArg |
python | getsentry__sentry | src/sentry/seer/models.py | {
"start": 1337,
"end": 1462
} | class ____(SpanInsight):
trace_id: str
suggestions: list[str]
reference_url: str | None = None
| PageWebVitalsInsight |
python | getsentry__sentry | src/sentry/issues/ownership/grammar.py | {
"start": 7560,
"end": 8017
} | class ____(NamedTuple):
"""
An Owner represents a User or Team who owns this Rule.
type is either `user` or `team`.
Examples:
foo@example.com
#team
"""
type: str
identifier: str
def dump(self) -> dict[str, str]:
return {"type": self.type, "identifier": self.id... | Owner |
python | tiangolo__fastapi | tests/test_jsonable_encoder.py | {
"start": 1369,
"end": 1438
} | class ____(BaseModel):
foo: str = Field(alias="Foo")
| ModelWithAlias |
python | dagster-io__dagster | python_modules/libraries/dagster-databricks/dagster_databricks/types.py | {
"start": 1211,
"end": 2463
} | class ____(NamedTuple):
"""Represents the state of a Databricks job run."""
life_cycle_state: Optional["DatabricksRunLifeCycleState"]
result_state: Optional["DatabricksRunResultState"]
state_message: Optional[str]
def has_terminated(self) -> bool:
"""Has the job terminated?"""
retu... | DatabricksRunState |
python | ray-project__ray | python/ray/serve/tests/unit/test_config.py | {
"start": 1239,
"end": 4428
} | class ____:
...
def test_autoscaling_config_validation():
# Check validation over publicly exposed options
with pytest.raises(ValidationError):
# min_replicas must be nonnegative
AutoscalingConfig(min_replicas=-1)
with pytest.raises(ValidationError):
# max_replicas must be po... | FakeRequestRouter |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_project.py | {
"start": 879,
"end": 1381
} | class ____:
fixtures = ["eric", "test_data"]
def setUp(self):
self.client.login(username="eric", password="test")
self.pip = Project.objects.get(slug="pip")
# Create a External Version. ie: pull/merge request Version.
self.external_version = get(
Version,
... | ProjectMixin |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/sqltypes.py | {
"start": 121182,
"end": 122093
} | class ____(DateTime):
"""The SQL TIMESTAMP type.
:class:`_types.TIMESTAMP` datatypes have support for timezone storage on
some backends, such as PostgreSQL and Oracle Database. Use the
:paramref:`~types.TIMESTAMP.timezone` argument in order to enable
"TIMESTAMP WITH TIMEZONE" for these backends.
... | TIMESTAMP |
python | getsentry__sentry | src/sentry/api/serializers/models/broadcast.py | {
"start": 1069,
"end": 1866
} | class ____(BroadcastSerializer):
def get_attrs(self, item_list, user, **kwargs):
attrs = super().get_attrs(item_list, user)
counts = dict(
BroadcastSeen.objects.filter(broadcast__in=item_list)
.values("broadcast")
.distinct()
.annotate(user_count=Count... | AdminBroadcastSerializer |
python | optuna__optuna | optuna/storages/journal/_storage.py | {
"start": 16481,
"end": 27767
} | class ____:
def __init__(self, worker_id_prefix: str) -> None:
self.log_number_read = 0
self._worker_id_prefix = worker_id_prefix
self._studies: dict[int, FrozenStudy] = {}
self._trials: dict[int, FrozenTrial] = {}
self._study_id_to_trial_ids: dict[int, list[int]] = {}
... | JournalStorageReplayResult |
python | pypa__hatch | tests/backend/utils/test_context.py | {
"start": 260,
"end": 576
} | class ____:
def test_directory_separator(self, isolation):
context = Context(isolation)
assert context.format("foo {/}") == f"foo {os.sep}"
def test_path_separator(self, isolation):
context = Context(isolation)
assert context.format("foo {;}") == f"foo {os.pathsep}"
| TestStatic |
python | scrapy__scrapy | scrapy/utils/reactor.py | {
"start": 1484,
"end": 8978
} | class ____(Generic[_T]):
"""Schedule a function to be called in the next reactor loop, but only if
it hasn't been already scheduled since the last time it ran.
"""
def __init__(self, func: Callable[_P, _T], *a: _P.args, **kw: _P.kwargs):
self._func: Callable[_P, _T] = func
self._a: tupl... | CallLaterOnce |
python | google__jax | jax/_src/pallas/mosaic_gpu/core.py | {
"start": 49608,
"end": 49917
} | class ____(SomeLayout):
layout: SomeLayout
axes: Sequence[int]
def to_mgpu(self) -> mgpu.FragmentedLayout:
layout = self.layout.to_mgpu()
if not isinstance(layout, mgpu.TiledLayout):
raise ValueError("Only TiledLayout supports reductions.")
return layout.reduce(self.axes)
| ReducedLayout |
python | walkccc__LeetCode | solutions/592. Fraction Addition and Subtraction/592.py | {
"start": 0,
"end": 324
} | class ____:
def fractionAddition(self, expression: str) -> str:
ints = list(map(int, re.findall('[+-]?[0-9]+', expression)))
A = 0
B = 1
for a, b in zip(ints[::2], ints[1::2]):
A = A * b + a * B
B *= b
g = math.gcd(A, B)
A //= g
B //= g
return str(A) + '/' + str(B)
| Solution |
python | numpy__numpy | numpy/_core/tests/test_numerictypes.py | {
"start": 12306,
"end": 12503
} | class ____(ReadValuesNested):
"""Check the values of heterogeneous arrays (nested, single row)"""
_descr = Ndescr
multiple_rows = False
_buffer = NbufferT[0]
| TestReadValuesNestedSingle |
python | numpy__numpy | benchmarks/benchmarks/bench_ma.py | {
"start": 9209,
"end": 9962
} | class ____(Benchmark):
param_names = ["size"]
params = [["small", "large"]]
def setup(self, size):
# Set the proportion of masked values.
prop_mask = 0.2
# Set up a "small" array with 10 vars and 10 obs.
rng = np.random.default_rng()
data = rng.random((10, 10), dtype... | Corrcoef |
python | spack__spack | lib/spack/spack/vendor/jinja2/nodes.py | {
"start": 34073,
"end": 34641
} | class ____(EvalContextModifier):
"""Modifies the eval context and reverts it later. Works exactly like
:class:`EvalContextModifier` but will only modify the
:class:`~spack.vendor.jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
"""
fields = ("body",)
body: t.List[Node]
# make sure no... | ScopedEvalContextModifier |
python | pyinstaller__pyinstaller | tests/functional/modules/pyi_testmod_dynamic.py | {
"start": 867,
"end": 1139
} | class ____(types.ModuleType):
__file__ = __file__
def __init__(self, name):
super().__init__(name)
self.foo = "A new value!"
# Replace module 'pyi_testmod_dynamic' by class DynamicModule.
sys.modules[__name__] = DynamicModule(__name__)
| DynamicModule |
python | anthropics__anthropic-sdk-python | src/anthropic/lib/foundry.py | {
"start": 1629,
"end": 1862
} | class ____(BetaMessages):
@cached_property
@override
def batches(self) -> None: # type: ignore[override]
"""Batches endpoint is not supported for Anthropic Foundry client."""
return None
| BetaFoundryMessages |
python | zarr-developers__zarr-python | tests/test_api/test_asynchronous.py | {
"start": 750,
"end": 3573
} | class ____(WithShape):
chunklen: int
@pytest.mark.parametrize(
("observed", "expected"),
[
({}, (None, None)),
(WithShape(shape=(1, 2)), ((1, 2), None)),
(WithChunks(shape=(1, 2), chunks=(1, 2)), ((1, 2), (1, 2))),
(WithChunkLen(shape=(10, 10), chunklen=1), ((10, 10), (1, 1... | WithChunkLen |
python | pandas-dev__pandas | pandas/tests/frame/test_nonunique_indexes.py | {
"start": 151,
"end": 11872
} | class ____:
def test_setattr_columns_vs_construct_with_columns(self):
# assignment
# GH 3687
arr = np.random.default_rng(2).standard_normal((3, 2))
idx = list(range(2))
df = DataFrame(arr, columns=["A", "A"])
df.columns = idx
expected = DataFrame(arr, columns=... | TestDataFrameNonuniqueIndexes |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor17.py | {
"start": 238,
"end": 353
} | class ____(Generic[T]):
def __new__(cls, *args, **kwargs):
return super().__new__(cls, *args, **kwargs)
| A |
python | google__jax | tests/scipy_fft_test.py | {
"start": 1409,
"end": 5378
} | class ____(jtu.JaxTestCase):
"""Tests for LAX-backed scipy.fft implementations"""
@jtu.sample_product(
dtype=real_dtypes,
shape=[(10,), (2, 5)],
n=[None, 1, 7, 13, 20],
axis=[-1, 0],
norm=[None, 'ortho', 'backward'],
)
def testDct(self, shape, dtype, n, axis, norm):
rng = jtu.rand_defau... | LaxBackedScipyFftTests |
python | chardet__chardet | chardet/chardistribution.py | {
"start": 8546,
"end": 9576
} | class ____(CharDistributionAnalysis):
def __init__(self) -> None:
super().__init__()
self._char_to_freq_order = JIS_CHAR_TO_FREQ_ORDER
self._table_size = JIS_TABLE_SIZE
self.typical_distribution_ratio = JIS_TYPICAL_DISTRIBUTION_RATIO
def get_order(self, byte_str: Union[bytes, by... | SJISDistributionAnalysis |
python | spyder-ide__spyder | external-deps/qtconsole/qtconsole/tests/test_frontend_widget.py | {
"start": 242,
"end": 3219
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
""" Create the application for the test case.
"""
cls._app = QtWidgets.QApplication.instance()
if cls._app is None:
cls._app = QtWidgets.QApplication([])
cls._app.setQuitOnLastWindowClosed(False... | TestFrontendWidget |
python | realpython__materials | python-contact-book/source_code_step_4/rpcontacts/views.py | {
"start": 277,
"end": 1524
} | class ____(QMainWindow):
"""Main Window."""
def __init__(self, parent=None):
"""Initializer."""
super().__init__(parent)
self.setWindowTitle("RP Contacts")
self.resize(550, 250)
self.centralWidget = QWidget()
self.setCentralWidget(self.centralWidget)
self... | Window |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/ScatterPlotItem.py | {
"start": 10646,
"end": 42440
} | class ____(GraphicsObject):
"""
Displays a set of x/y points. Instances of this class are created
automatically as part of PlotDataItem; these rarely need to be instantiated
directly.
The size, shape, pen, and fill brush may be set for each point individually
or for all points.
==========... | ScatterPlotItem |
python | huggingface__transformers | src/transformers/models/layoutlmv3/image_processing_layoutlmv3.py | {
"start": 1654,
"end": 4575
} | class ____(ImagesKwargs, total=False):
r"""
apply_ocr (`bool`, *optional*, defaults to `True`):
Whether to apply the Tesseract OCR engine to get words + normalized bounding boxes. Can be overridden by
the `apply_ocr` parameter in the `preprocess` method.
ocr_lang (`str`, *optional*):
... | LayoutLMv3ImageProcessorKwargs |
python | scrapy__scrapy | tests/test_contracts.py | {
"start": 984,
"end": 1154
} | class ____(Contract):
name = "custom_fail_contract"
def adjust_request_args(self, args):
raise TypeError("Error in adjust_request_args")
| CustomFailContract |
python | dagster-io__dagster | python_modules/dagster/dagster/_grpc/types.py | {
"start": 5462,
"end": 7013
} | class ____(
NamedTuple(
"_ResumeRunArgs",
[
# Deprecated, only needed for back-compat since it can be pulled from the DagsterRun
("job_origin", JobPythonOrigin),
("run_id", str),
("instance_ref", Optional[InstanceRef]),
("set_exit_code_on_f... | ResumeRunArgs |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_bigquery.py | {
"start": 2889,
"end": 34589
} | class ____(_BigQueryBaseTestClass):
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryConnection")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.BigQueryHook._authorize")
@mock.patch("airflow.providers.google.cloud.hooks.bigquery.build")
def test_bigquery_client_creation(se... | TestBigQueryHookMethods |
python | ipython__ipython | tests/test_oinspect.py | {
"start": 3242,
"end": 3531
} | class ____(object):
"""This is the class docstring."""
def __init__(self, x, y=1):
"""This is the constructor docstring."""
def __call__(self, *a, **kw):
"""This is the call docstring."""
def method(self, x, z=2):
"""Some method's docstring"""
| Call |
python | pypa__pipenv | pipenv/vendor/click/parser.py | {
"start": 6770,
"end": 7822
} | class ____:
def __init__(self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1):
self.dest = dest
self.nargs = nargs
self.obj = obj
def process(
self,
value: t.Union[t.Optional[str], t.Sequence[t.Optional[str]]],
state: "ParsingState",
) -> None:
... | Argument |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 129519,
"end": 130013
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("user_id", "organization_id", "client_mutation_id")
user_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="userId")
organization_id = sgqlc.types.Field(
... | RemoveOutsideCollaboratorInput |
python | getsentry__sentry | src/sentry/notifications/utils/__init__.py | {
"start": 18507,
"end": 21039
} | class ____(PerformanceProblemContext):
def to_dict(self) -> dict[str, Any]:
return {
"span_evidence_key_value": [
{"key": _("Transaction"), "value": self.transaction},
{"key": _("Starting Span"), "value": self.starting_span},
{
... | ConsecutiveDBQueriesProblemContext |
python | getsentry__sentry | src/sentry/api/event_search.py | {
"start": 26128,
"end": 64769
} | class ____(NodeVisitor[list[QueryToken]]):
# `tuple[...]` is used for the typing of `children` because there isn't
# a way to represent positional-heterogenous lists -- but they are
# actually lists
unwrapped_exceptions = (InvalidSearchQuery, IncompatibleMetricsQuery)
def __init__(
self,
... | SearchVisitor |
python | getsentry__sentry | tests/sentry/middleware/integrations/parsers/test_gitlab.py | {
"start": 1187,
"end": 10193
} | class ____(TestCase):
factory = RequestFactory()
path = f"{IntegrationClassification.integration_prefix}gitlab/webhook/"
def get_response(self, req: HttpRequest) -> HttpResponse:
return HttpResponse(status=200, content="passthrough")
def get_integration(self) -> Integration:
self.organ... | GitlabRequestParserTest |
python | Textualize__textual | docs/examples/guide/compound/byte03.py | {
"start": 314,
"end": 1468
} | class ____(Widget):
"""A Switch with a numeric label above it."""
DEFAULT_CSS = """
BitSwitch {
layout: vertical;
width: auto;
height: auto;
}
BitSwitch > Label {
text-align: center;
width: 100%;
}
"""
class BitChanged(Message):
"""Sent w... | BitSwitch |
python | sphinx-doc__sphinx | sphinx/util/cfamily.py | {
"start": 4798,
"end": 5402
} | class ____(ASTBaseBase):
def __init__(self, name: str, args: ASTBaseParenExprList | None) -> None:
self.name = name
self.args = args
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTGnuAttribute):
return NotImplemented
return self.name == other.na... | ASTGnuAttribute |
python | django__django | tests/forms_tests/widget_tests/test_textinput.py | {
"start": 130,
"end": 4118
} | class ____(WidgetTest):
widget = TextInput()
def test_render(self):
self.check_html(
self.widget, "email", "", html='<input type="text" name="email">'
)
def test_render_none(self):
self.check_html(
self.widget, "email", None, html='<input type="text" name="e... | TextInputTest |
python | gevent__gevent | src/gevent/tests/test__pywsgi.py | {
"start": 45926,
"end": 46445
} | class ____(TestCase):
@staticmethod
def application(env, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
yield b""
yield b""
def test_err(self):
chunks = []
with self.makefile() as fd:
fd.write('GET / HTTP/1.1\r\nHost: localh... | TestEmptyYield |
python | huggingface__transformers | src/transformers/models/blenderbot_small/modeling_blenderbot_small.py | {
"start": 2521,
"end": 4439
} | class ____(nn.Embedding):
"""
This module learns positional embeddings up to a fixed maximum size.
"""
def __init__(self, num_embeddings: int, embedding_dim: int):
super().__init__(num_embeddings, embedding_dim)
def forward(
self, input_ids_shape: torch.Size, past_key_values_length... | BlenderbotSmallLearnedPositionalEmbedding |
python | huggingface__transformers | src/transformers/models/auto/modeling_auto.py | {
"start": 82111,
"end": 82219
} | class ____(_BaseAutoModelClass):
_model_mapping = MODEL_FOR_TEXT_ENCODING_MAPPING
| AutoModelForTextEncoding |
python | sqlalchemy__sqlalchemy | test/perf/compiled_extensions/row.py | {
"start": 116,
"end": 1687
} | class ____(Case):
NUMBER = 2_000_000
@staticmethod
def python():
from sqlalchemy.engine import _util_cy
py_util = load_uncompiled_module(_util_cy)
assert not py_util._is_compiled()
return py_util.tuplegetter
@staticmethod
def cython():
from sqlalchemy.engin... | TupleGetter |
python | huggingface__transformers | src/transformers/data/processors/squad.py | {
"start": 28133,
"end": 28895
} | class ____:
"""
Constructs a SquadResult which can be used to evaluate a model's output on the SQuAD dataset.
Args:
unique_id: The unique identifier corresponding to that example.
start_logits: The logits corresponding to the start of the answer
end_logits: The logits corresponding ... | SquadResult |
python | apache__airflow | airflow-ctl/src/airflowctl/exceptions.py | {
"start": 1437,
"end": 1573
} | class ____(AirflowCtlException):
"""Raise when a connection error occurs while performing an operation."""
| AirflowCtlConnectionException |
python | huggingface__transformers | src/transformers/models/llama4/modeling_llama4.py | {
"start": 42610,
"end": 43935
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
idx = config.image_size // config.patch_size
img_idx = torch.arange(idx**2, dtype=torch.int32).reshape(idx**2, 1)
img_idx = torch.cat([img_idx, img_idx[:1]], dim=0)
img_idx[-1, -1] = -2 # ID_CLS_TOKEN
... | Llama4VisionRotaryEmbedding |
python | astropy__astropy | astropy/io/ascii/core.py | {
"start": 56049,
"end": 57210
} | class ____(BaseInputter):
"""Inputter where lines ending in ``continuation_char`` are joined with the subsequent line.
Example::
col1 col2 col3
1 \
2 3
4 5 \
6
"""
continuation_char = "\\"
replace_char = " "
# If no_continue is not None then lines matching this r... | ContinuationLinesInputter |
python | pytorch__pytorch | benchmarks/distributed/bench_nvshmem_tile_reduce.py | {
"start": 983,
"end": 6195
} | class ____(MultiProcContinuousTest):
def _init_device(self) -> None:
# TODO: relieve this (seems to hang if without)
device_module.set_device(self.device)
# Set NVSHMEM as SymmMem backend
symm_mem.set_backend("NVSHMEM")
@property
def device(self) -> torch.device:
ret... | NVSHMEMTileReduceBenchmark |
python | numba__numba | numba/tests/test_linalg.py | {
"start": 49719,
"end": 59972
} | class ____(TestLinalgSystems):
"""
Tests for np.linalg.lstsq.
"""
# NOTE: The testing of this routine is hard as it has to handle numpy
# using double precision routines on single precision input, this has
# a knock on effect especially in rank deficient cases and cases where
# conditioning... | TestLinalgLstsq |
python | pyinstaller__pyinstaller | bootloader/waflib/Tools/tex.py | {
"start": 10286,
"end": 10398
} | class ____(tex):
texfun, vars = Task.compile_fun('${XELATEX} ${XELATEXFLAGS} ${SRCFILE}', shell=False)
| xelatex |
python | pandas-dev__pandas | pandas/tests/series/indexing/test_setitem.py | {
"start": 47871,
"end": 48399
} | class ____(CoercionTest):
# previously test_setitem_series_datetime64tz in tests.indexing.test_coercion
@pytest.fixture
def obj(self):
tz = "US/Eastern"
return Series(date_range("2011-01-01", freq="D", periods=4, tz=tz, unit="ns"))
@pytest.fixture
def raises(self):
return Fa... | TestCoercionDatetime64TZ |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 98369,
"end": 98637
} | class ____:
xlProtectedViewWindowMaximized = 2 # from enum XlProtectedViewWindowState
xlProtectedViewWindowMinimized = 1 # from enum XlProtectedViewWindowState
xlProtectedViewWindowNormal = 0 # from enum XlProtectedViewWindowState
| ProtectedViewWindowState |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 29517,
"end": 29862
} | class ____(sgqlc.types.Enum):
"""The possible state reasons of a closed issue.
Enumeration Choices:
* `COMPLETED`: An issue that has been closed as completed
* `NOT_PLANNED`: An issue that has been closed as not planned
"""
__schema__ = github_schema
__choices__ = ("COMPLETED", "NOT_PLANN... | IssueClosedStateReason |
python | tqdm__tqdm | tqdm/rich.py | {
"start": 2328,
"end": 5021
} | class ____(std_tqdm): # pragma: no cover
"""Experimental rich.progress GUI version of tqdm!"""
# TODO: @classmethod: write()?
def __init__(self, *args, **kwargs):
"""
This class accepts the following parameters *in addition* to
the parameters accepted by `tqdm`.
Parameters
... | tqdm_rich |
python | kamyu104__LeetCode-Solutions | Python/count-the-number-of-incremovable-subarrays-i.py | {
"start": 44,
"end": 681
} | class ____(object):
def incremovableSubarrayCount(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for j in reversed(xrange(1, len(nums))):
if not nums[j-1] < nums[j]:
break
else:
return (len(nums)+1)*len(nums)//2
... | Solution |
python | tqdm__tqdm | tqdm/std.py | {
"start": 7811,
"end": 57461
} | class ____(Comparable):
"""
Decorate an iterable object, returning an iterator which acts exactly
like the original iterable, but prints a dynamically updating
progressbar every time a value is requested.
Parameters
----------
iterable : iterable, optional
Iterable to decorate with... | tqdm |
python | pypa__hatch | backend/src/hatchling/builders/binary.py | {
"start": 275,
"end": 3130
} | class ____(BuilderConfig):
SUPPORTED_VERSIONS = ("3.12", "3.11", "3.10", "3.9", "3.8", "3.7")
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.__scripts: list[str] | None = None
self.__python_version: str | None = None
self.__pyapp_v... | BinaryBuilderConfig |
python | crytic__slither | slither/visitors/expression/write_var.py | {
"start": 1474,
"end": 5914
} | class ____(ExpressionVisitor):
def __init__(self, expression: Expression) -> None:
self._result: Optional[List[Expression]] = None
super().__init__(expression)
def result(self) -> List[Any]:
if self._result is None:
self._result = list(set(get(self.expression)))
retu... | WriteVar |
python | getsentry__sentry | src/sentry/api/endpoints/project_performance_general_settings.py | {
"start": 595,
"end": 755
} | class ____(serializers.Serializer):
enable_images = serializers.BooleanField(required=False)
@region_silo_endpoint
| ProjectPerformanceGeneralSettingsSerializer |
python | django__django | django/template/loaders/filesystem.py | {
"start": 257,
"end": 1506
} | class ____(BaseLoader):
def __init__(self, engine, dirs=None):
super().__init__(engine)
self.dirs = dirs
def get_dirs(self):
return self.dirs if self.dirs is not None else self.engine.dirs
def get_contents(self, origin):
try:
with open(origin.name, encoding=self... | Loader |
python | paramiko__paramiko | paramiko/pkey.py | {
"start": 3106,
"end": 33863
} | class ____:
"""
Base class for public keys.
Also includes some "meta" level convenience constructors such as
`.from_type_string`.
"""
# known encryption types for private key files:
_CIPHER_TABLE = {
"AES-128-CBC": {
"cipher": algorithms.AES,
"keysize": 16,
... | PKey |
python | zostera__django-bootstrap4 | tests/test_formsets.py | {
"start": 218,
"end": 388
} | class ____(TestCase):
def test_illegal_formset(self):
with self.assertRaises(BootstrapError):
render_formset(formset="illegal")
| BootstrapFormSetTest |
python | getsentry__sentry | src/sentry/explore/endpoints/explore_saved_query_starred.py | {
"start": 1045,
"end": 3474
} | class ____(OrganizationEndpoint):
publish_status = {
"POST": ApiPublishStatus.EXPERIMENTAL,
}
owner = ApiOwner.EXPLORE
permission_classes = (MemberPermission,)
def has_feature(self, organization, request):
return features.has(
"organizations:visibility-explore-view", org... | ExploreSavedQueryStarredEndpoint |
python | apache__airflow | dev/breeze/tests/test_ui_commands.py | {
"start": 6378,
"end": 6667
} | class ____:
def test_locale_summary_creation(self):
summary = LocaleSummary(missing_keys={"de": ["key1", "key2"]}, extra_keys={"de": ["key3"]})
assert summary.missing_keys == {"de": ["key1", "key2"]}
assert summary.extra_keys == {"de": ["key3"]}
| TestLocaleSummary |
python | allegroai__clearml | clearml/backend_api/services/v2_23/datasets.py | {
"start": 186716,
"end": 187640
} | class ____(Request):
"""
Get labels' stats for a dataset version
:param version: Dataset version ID
:type version: str
"""
_service = "datasets"
_action = "get_stats"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"version": {"descripti... | GetStatsRequest |
python | langchain-ai__langchain | libs/core/langchain_core/prompt_values.py | {
"start": 2699,
"end": 3057
} | class ____(TypedDict, total=False):
"""Image URL."""
detail: Literal["auto", "low", "high"]
"""Specifies the detail level of the image.
Can be `'auto'`, `'low'`, or `'high'`.
This follows OpenAI's Chat Completion API's image URL format.
"""
url: str
"""Either a URL of the image or th... | ImageURL |
python | sympy__sympy | sympy/holonomic/recurrence.py | {
"start": 888,
"end": 2884
} | class ____:
"""
A Recurrence Operator Algebra is a set of noncommutative polynomials
in intermediate `Sn` and coefficients in a base ring A. It follows the
commutation rule:
Sn * a(n) = a(n + 1) * Sn
This class represents a Recurrence Operator Algebra and serves as the parent ring
for Recur... | RecurrenceOperatorAlgebra |
python | huggingface__transformers | tests/models/fsmt/test_tokenization_fsmt.py | {
"start": 1029,
"end": 6494
} | class ____(TokenizerTesterMixin, unittest.TestCase):
from_pretrained_id = "stas/tiny-wmt19-en-de"
tokenizer_class = FSMTTokenizer
test_rust_tokenizer = False
@classmethod
def setUpClass(cls):
super().setUpClass()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/... | FSMTTokenizationTest |
python | pytransitions__transitions | transitions/extensions/factory.py | {
"start": 2508,
"end": 3128
} | class ____(GraphMachine, LockedMachine):
"""
A threadsafe machine with graph support.
"""
@staticmethod
def format_references(func):
if isinstance(func, partial) and func.func.__name__.startswith('_locked_method'):
return "%s(%s)" % (
func.args[0].__name__,
... | LockedGraphMachine |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-steamship/llama_index/readers/steamship/base.py | {
"start": 199,
"end": 3450
} | class ____(BaseReader):
"""
Reads persistent Steamship Files and converts them to Documents.
Args:
api_key: Steamship API key. Defaults to STEAMSHIP_API_KEY value if not provided.
Note:
Requires install of `steamship` package and an active Steamship API Key.
To get a Steamship ... | SteamshipFileReader |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/oracle/types.py | {
"start": 3931,
"end": 3997
} | class ____(sqltypes.LargeBinary):
__visit_name__ = "BFILE"
| BFILE |
python | matplotlib__matplotlib | lib/matplotlib/image.py | {
"start": 8112,
"end": 32193
} | class ____(mcolorizer.ColorizingArtist):
"""
Base class for images.
*interpolation* and *cmap* default to their rc settings.
*cmap* is a `.colors.Colormap` instance.
*norm* is a `.colors.Normalize` instance to map luminance to 0-1.
*extent* is a ``(left, right, bottom, top)`` tuple in data co... | _ImageBase |
python | readthedocs__readthedocs.org | readthedocs/projects/views/private.py | {
"start": 21162,
"end": 22015
} | class ____(ProjectUsersMixin, GenericView):
success_message = _("User deleted")
http_method_names = ["post"]
def post(self, request, *args, **kwargs):
username = self.request.POST.get("username")
user = get_object_or_404(
self.get_queryset(),
username=username,
... | ProjectUsersDelete |
python | mahmoud__boltons | boltons/tbutils.py | {
"start": 8783,
"end": 13334
} | class ____:
"""The TracebackInfo class provides a basic representation of a stack
trace, be it from an exception being handled or just part of
normal execution. It is basically a wrapper around a list of
:class:`Callpoint` objects representing frames.
Args:
frames (list): A list of frame ob... | TracebackInfo |
python | ansible__ansible | test/integration/targets/ansible-test-integration-targets/test.py | {
"start": 1556,
"end": 2132
} | class ____(unittest.TestCase):
def test_prefixes(self):
try:
command = ['ansible-test', 'integration', '--list-targets']
something = subprocess.run([*command, 'something/'], text=True, capture_output=True, check=True)
self.assertEqual(something.stdout.splitlines(), ['on... | PrefixesTest |
python | sympy__sympy | sympy/functions/elementary/hyperbolic.py | {
"start": 53220,
"end": 57851
} | class ____(InverseHyperbolicFunction):
"""
``acoth(x)`` is the inverse hyperbolic cotangent of ``x``.
The inverse hyperbolic cotangent function.
Examples
========
>>> from sympy import acoth
>>> from sympy.abc import x
>>> acoth(x).diff(x)
1/(1 - x**2)
See Also
========
... | acoth |
python | python-attrs__attrs | typing-examples/baseline.py | {
"start": 607,
"end": 652
} | class ____:
a: int
D(1).a
@attrs.define
| D |
python | jina-ai__jina | jina/serve/runtimes/servers/composite.py | {
"start": 191,
"end": 3437
} | class ____(BaseServer):
"""Composite Base Server implementation from which u can inherit a specific custom composite one"""
servers: List['BaseServer']
logger: 'JinaLogger'
def __init__(
self,
**kwargs,
):
"""Initialize the gateway
:param kwargs: keyword args
... | CompositeBaseServer |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/errors.py | {
"start": 12917,
"end": 13135
} | class ____(graphene.ObjectType):
class Meta:
interfaces = (GrapheneError,)
name = "DagsterTypeNotFoundError"
dagster_type_name = graphene.NonNull(graphene.String)
| GrapheneDagsterTypeNotFoundError |
python | davidhalter__jedi | jedi/inference/value/function.py | {
"start": 14427,
"end": 15016
} | class ____(BaseFunctionExecutionContext):
def infer_annotations(self):
# I don't think inferring anonymous executions is a big thing.
# Anonymous contexts are mostly there for the user to work in. ~ dave
return NO_VALUES
def get_filters(self, until_position=None, origin_scope=None):
... | AnonymousFunctionExecution |
python | plotly__plotly.py | plotly/graph_objs/parcoords/_line.py | {
"start": 233,
"end": 20585
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "parcoords"
_path_str = "parcoords.line"
_valid_props = {
"autocolorscale",
"cauto",
"cmax",
"cmid",
"cmin",
"color",
"coloraxis",
"colorbar",
"colorscale",
"colorsrc",
... | Line |
python | spack__spack | lib/spack/spack/platforms/linux.py | {
"start": 232,
"end": 563
} | class ____(Platform):
priority = 90
def __init__(self):
super().__init__("linux")
linux_dist = LinuxDistro()
self.default_os = str(linux_dist)
self.add_operating_system(str(linux_dist), linux_dist)
@classmethod
def detect(cls):
return "linux" in platform.system(... | Linux |
python | ray-project__ray | python/ray/data/_internal/stats.py | {
"start": 43246,
"end": 53498
} | class ____:
operators_stats: List["OperatorStatsSummary"]
iter_stats: "IterStatsSummary"
parents: List["DatasetStatsSummary"]
number: int
dataset_uuid: str
time_total_s: float
base_name: str
extra_metrics: Dict[str, Any]
global_bytes_spilled: int
global_bytes_restored: int
da... | DatasetStatsSummary |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_type_check.py | {
"start": 6710,
"end": 7138
} | class ____(TestCase):
def test_basic(self):
z = np.array([-1, 0, 1])
assert_(not iscomplexobj(z))
z = np.array([-1j, 0, -1])
assert_(iscomplexobj(z))
def test_scalar(self):
assert_(not iscomplexobj(1.0))
assert_(iscomplexobj(1 + 0j))
def test_list(self):
... | TestIscomplexobj |
python | pypa__pip | tests/unit/test_exceptions.py | {
"start": 2296,
"end": 8320
} | class ____:
def test_complete(self) -> None:
err = DiagnosticPipError(
reference="test-diagnostic",
message="Oh no!\nIt broke. :(",
context="Something went wrong\nvery wrong.",
note_stmt="You did something wrong, which is what caused this error.",
... | TestDiagnosticPipErrorPresentation_ASCII |
python | getsentry__sentry | src/sentry/models/featureadoption.py | {
"start": 8968,
"end": 9774
} | class ____(Model):
__relocation_scope__ = RelocationScope.Excluded
organization = FlexibleForeignKey("sentry.Organization")
feature_id = models.PositiveIntegerField(choices=[(f.id, str(f.name)) for f in manager.all()])
date_completed = models.DateTimeField(default=timezone.now)
complete = models.Bo... | FeatureAdoption |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.