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
pallets__itsdangerous
src/itsdangerous/exc.py
{ "start": 882, "end": 1619 }
class ____(BadSignature): """Raised if a time-based signature is invalid. This is a subclass of :class:`BadSignature`. """ def __init__( self, message: str, payload: t.Any | None = None, date_signed: datetime | None = None, ): super().__init__(message, payloa...
BadTimeSignature
python
run-llama__llama_index
llama-index-integrations/selectors/llama-index-selectors-notdiamond/llama_index/selectors/notdiamond/base.py
{ "start": 523, "end": 987 }
class ____(SelectorResult): """A single selection of a choice provided by Not Diamond.""" class Config: arbitrary_types_allowed = True session_id: str llm: LLMConfig @classmethod def from_selector_result( cls, selector_result: SelectorResult, session_id: str, best_llm: LLMConf...
NotDiamondSelectorResult
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 165097, "end": 165395 }
class ____(RecvmsgIntoMixin, RFC3542AncillaryTest, SendrecvmsgUDP6TestBase): pass @unittest.skipUnless(HAVE_SOCKET_UDPLITE, 'UDPLITE sockets required for this test.')
RecvmsgIntoRFC3542AncillaryUDP6Test
python
walkccc__LeetCode
solutions/338. Counting Bits/338.py
{ "start": 0, "end": 240 }
class ____: def countBits(self, n: int) -> list[int]: # f(i) := i's number of 1s in bitmask # f(i) = f(i / 2) + i % 2 ans = [0] * (n + 1) for i in range(1, n + 1): ans[i] = ans[i // 2] + (i & 1) return ans
Solution
python
getsentry__sentry
tests/sentry/preprod/api/models/test_project_preprod_build_details_models.py
{ "start": 412, "end": 9094 }
class ____(TestCase): def test_to_size_info_none_input(self): """Test to_size_info returns None when given None input.""" result = to_size_info([]) assert result is None def test_to_size_info_pending_state(self): """Test to_size_info returns SizeInfoPending for PENDING state."""...
TestToSizeInfo
python
sphinx-doc__sphinx
sphinx/ext/autosummary/__init__.py
{ "start": 26862, "end": 32087 }
class ____(SphinxRole): """Smart linking role. Expands to ':obj:`text`' if `text` is an object that can be imported; otherwise expands to '*text*'. """ def run(self) -> tuple[list[Node], list[system_message]]: pyobj_role = self.env.domains.python_domain.role('obj') assert pyobj_rol...
AutoLink
python
cython__cython
Cython/Compiler/FlowControl.py
{ "start": 543, "end": 997 }
class ____(ExprNodes.ExprNode): # Used for declaring assignments of a specified type without a known entry. def __init__(self, type, may_be_none=None, pos=None): super().__init__(pos) self.type = type self._may_be_none = may_be_none def may_be_none(self): return self._may_be...
TypedExprNode
python
ray-project__ray
python/ray/serve/tests/test_config_files/test_dag/dir/subdir/a/add_and_sub.py
{ "start": 120, "end": 263 }
class ____(str, Enum): ADD = "ADD" SUBTRACT = "SUB" @serve.deployment( ray_actor_options={ "num_cpus": 0.1, } )
Operation
python
pytorch__pytorch
test/inductor/test_ordered_set.py
{ "start": 54672, "end": 54924 }
class ____(TestCopying, TestCase): def setUp(self): super().setUp() self.OrderedSet = OrderedSet([((1, 2), (3, 4))]) del TestCopying # ==============================================================================
TestCopyingNested
python
google__pytype
pytype/tests/test_typing_methods1.py
{ "start": 141, "end": 11514 }
class ____(test_base.BaseTest): """Tests for typing.py.""" def _check_call(self, t, expr): # pylint: disable=invalid-name with test_utils.Tempdir() as d: d.create_file( "foo.pyi", """ from typing import {type} def f() -> {type}: ... """.format(type=t), ) ...
TypingMethodsTest
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_data_labels49.py
{ "start": 315, "end": 1846 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_data_labels49.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(se...
TestCompareXLSXFiles
python
pandas-dev__pandas
scripts/tests/test_validate_docstrings.py
{ "start": 10406, "end": 10791 }
class ____: @pytest.mark.parametrize( "name", ["pandas.Series.str.isdecimal", "pandas.Series.str.islower"] ) def test_encode_content_write_to_file(self, name) -> None: # GH25466 docstr = validate_docstrings.PandasDocstring(name).validate_pep8() # the list of pep8 errors shoul...
TestPandasDocstringClass
python
great-expectations__great_expectations
contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_iowa_zip.py
{ "start": 727, "end": 1719 }
class ____(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.valid_iowa_zip" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _pandas(c...
ColumnValuesToBeValidIowaZip
python
getsentry__sentry
tests/sentry/uptime/autodetect/test_ranking.py
{ "start": 632, "end": 4610 }
class ____(UptimeTestCase): def assert_project_count( self, project: Project, count: int | None, expiry: int | None ) -> int | None: key = build_org_projects_key(project.organization) cluster = get_cluster() if count is None: assert not cluster.zscore(key, str(project...
AddBaseUrlToRankTest
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 212942, "end": 216999 }
class ____(BufferIndexNode): is_memview_index = True is_buffer_access = False def analyse_types(self, env, getting=True): # memoryviewslice indexing or slicing from . import MemoryView self.is_pythran_mode = has_np_pythran(env) indices = self.indices have_slices, i...
MemoryViewIndexNode
python
django__django
tests/multiple_database/routers.py
{ "start": 1721, "end": 1864 }
class ____: # A router that only expresses an opinion on writes def db_for_write(self, model, **hints): return "writer"
WriteRouter
python
streamlit__streamlit
lib/tests/streamlit/elements/button_group_test.py
{ "start": 13366, "end": 45263 }
class ____(DeltaGeneratorTestCase): @parameterized.expand( [ ( st.feedback, ("thumbs",), None, [":material/thumb_up:", ":material/thumb_down:"], "content_icon", ButtonGroupProto.Style.BORDERLESS, ...
ButtonGroupCommandTests
python
scrapy__scrapy
tests/test_downloadermiddleware_httpauth.py
{ "start": 483, "end": 737 }
class ____: def setup_method(self): self.spider = LegacySpider("foo") def test_auth(self): mw = HttpAuthMiddleware() with pytest.raises(AttributeError): mw.spider_opened(self.spider)
TestHttpAuthMiddlewareLegacy
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/selectable.py
{ "start": 76282, "end": 77063 }
class ____(NamedTuple): required_label_name: Optional[str] """ string label name, if non-None, must be rendered as a label, i.e. "AS <name>" """ proxy_key: Optional[str] """ proxy_key that is to be part of the result map for this col. this is also the key in a fromclause.c or s...
_ColumnsPlusNames
python
readthedocs__readthedocs.org
readthedocs/projects/filters.py
{ "start": 6527, "end": 8721 }
class ____(ModelFilterSet): """ Filter and sorting for project version listing page. This is used from the project versions list view page to provide filtering and sorting to the version list and search UI. It is normally instantiated with an included queryset, which provides user project authoriza...
ProjectVersionListFilterSet
python
getsentry__sentry
src/sentry/audit_log/events.py
{ "start": 3831, "end": 4221 }
class ____(AuditLogEvent): def __init__(self) -> None: super().__init__(event_id=10, name="ORG_ADD", api_name="org.create") def render(self, audit_log_entry: AuditLogEntry) -> str: if channel := audit_log_entry.data.get("channel"): return f"created the organization with {channel} in...
OrgAddAuditLogEvent
python
getsentry__sentry
src/sentry/release_health/base.py
{ "start": 4360, "end": 5059 }
class ____(TypedDict, total=False): adoption: float | None sessions_adoption: float | None total_users_24h: int | None total_project_users_24h: int | None total_sessions_24h: int | None total_project_sessions_24h: int | None total_sessions: int | None total_users: int | None has_heal...
ReleaseHealthOverview
python
Textualize__textual
docs/blog/snippets/2022-12-07-responsive-app-background-task/blocking02.py
{ "start": 260, "end": 460 }
class ____(Widget): def on_click(self) -> None: self.styles.background = Color( randint(1, 255), randint(1, 255), randint(1, 255), )
ColourChanger
python
doocs__leetcode
solution/0700-0799/0732.My Calendar III/Solution.py
{ "start": 1666, "end": 2020 }
class ____: def __init__(self): self.tree = SegmentTree() def book(self, start: int, end: int) -> int: self.tree.modify(start + 1, end, 1) return self.tree.query(1, int(1e9 + 1)) # Your MyCalendarThree object will be instantiated and called as such: # obj = MyCalendarThree() # param_1...
MyCalendarThree
python
pytorch__pytorch
test/nn/test_module_hooks.py
{ "start": 4388, "end": 4615 }
class ____: def __init__(self, inp): self.input = inp def __enter__(self, *args, **kwargs): self.input.append(2) def __exit__(self, *args, **kwargs): self.input.append(-1)
DummyContextManager
python
eventlet__eventlet
eventlet/websocket.py
{ "start": 1788, "end": 14024 }
class ____: """Wraps a websocket handler function in a WSGI application. Use it like this:: @websocket.WebSocketWSGI def my_handler(ws): from_browser = ws.wait() ws.send("from server") The single argument to the function will be an instance of :class:`WebSocket`. To c...
WebSocketWSGI
python
pallets__werkzeug
src/werkzeug/datastructures/structures.py
{ "start": 4212, "end": 18773 }
class ____(TypeConversionDict[K, V]): """A :class:`MultiDict` is a dictionary subclass customized to deal with multiple values for the same key which is for example used by the parsing functions in the wrappers. This is necessary because some HTML form elements pass multiple values for the same key. ...
MultiDict
python
getsentry__sentry-python
sentry_sdk/integrations/logging.py
{ "start": 9418, "end": 10498 }
class ____(_BaseHandler): """ A logging handler that records breadcrumbs for each log record. Note that you do not have to use this class if the logging integration is enabled, which it is by default. """ def emit(self, record): # type: (LogRecord) -> Any with capture_internal_exce...
BreadcrumbHandler
python
huggingface__transformers
tests/utils/test_convert_slow_tokenizer.py
{ "start": 194, "end": 245 }
class ____: vocab_file: str
FakeOriginalTokenizer
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_textbox15.py
{ "start": 315, "end": 899 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("textbox15.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with textbox(s).""" workbook = Workb...
TestCompareXLSXFiles
python
tensorflow__tensorflow
tensorflow/python/checkpoint/benchmarks_test.py
{ "start": 1197, "end": 1421 }
class ____(base.Trackable): def _serialize_to_tensors(self): return {base.VARIABLE_VALUE_KEY: array_ops.ones([])} def _restore_from_tensors(self, restored_tensors): return control_flow_ops.no_op()
_TrivialRestore
python
airbytehq__airbyte
airbyte-integrations/connectors/source-facebook-pages/source_facebook_pages/components.py
{ "start": 717, "end": 2490 }
class ____(NoAuth): config: Config page_id: Union[InterpolatedString, str] access_token: Union[InterpolatedString, str] def __post_init__(self, parameters: Mapping[str, Any]): self._page_id = InterpolatedString.create(self.page_id, parameters=parameters).eval(self.config) self._access_t...
AuthenticatorFacebookPageAccessToken
python
kubernetes-client__python
kubernetes/client/models/v1alpha1_storage_version.py
{ "start": 383, "end": 7932 }
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...
V1alpha1StorageVersion
python
pandas-dev__pandas
asv_bench/benchmarks/frame_methods.py
{ "start": 23533, "end": 24381 }
class ____: def setup(self): rng = np.random.default_rng() self.df = DataFrame(rng.uniform(size=(1_000_000, 10))) idx = rng.choice(range(1_000_000), size=1_000_000, replace=False) self.df_random = DataFrame(self.df, index=idx) idx = rng.choice(range(1_000_000), size=100_000...
Update
python
getsentry__sentry
src/sentry/notifications/notifications/strategies/owner_recipient_strategy.py
{ "start": 134, "end": 223 }
class ____(RoleBasedRecipientStrategy): role = roles.get_top_dog()
OwnerRecipientStrategy
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/integrations/pandera/example.py
{ "start": 454, "end": 1172 }
class ____(pa.DataFrameModel): """Open/close prices for one or more stocks by day.""" name: Series[str] = pa.Field(description="Ticker symbol of stock") date: Series[str] = pa.Field(description="Date of prices") open: Series[float] = pa.Field(ge=0, description="Price at market open") close: Series[...
StockPrices
python
falconry__falcon
falcon/_typing.py
{ "start": 6409, "end": 6729 }
class ____(Protocol[_ReqT, _RespT]): """WSGI Middleware with response handler.""" def process_response( self, req: _ReqT, resp: _RespT, resource: Resource | None, req_succeeded: bool, ) -> None: ... # ASGI lifespan middleware interface
WsgiMiddlewareWithProcessResponse
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_alloy_db.py
{ "start": 56208, "end": 64455 }
class ____: def setup_method(self): self.operator = AlloyDBCreateUserOperator( task_id=TEST_TASK_ID, user_id=TEST_USER_ID, user_configuration=TEST_USER, cluster_id=TEST_CLUSTER_ID, project_id=TEST_GCP_PROJECT, location=TEST_GCP_REGION, ...
TestAlloyDBCreateUserOperator
python
kamyu104__LeetCode-Solutions
Python/clone-graph.py
{ "start": 143, "end": 848 }
class ____(object): # @param node, a undirected graph node # @return a undirected graph node def cloneGraph(self, node): if node is None: return None cloned_node = UndirectedGraphNode(node.label) cloned, queue = {node:cloned_node}, [node] while queue: ...
Solution
python
openai__openai-python
src/openai/types/beta/threads/image_url_content_block.py
{ "start": 230, "end": 365 }
class ____(BaseModel): image_url: ImageURL type: Literal["image_url"] """The type of the content part."""
ImageURLContentBlock
python
dagster-io__dagster
helm/dagster/schema/schema/charts/dagster_user_deployments/subschema/user_deployments.py
{ "start": 127, "end": 344 }
class ____(BaseModel): enabled: bool ReadinessProbeWithEnabled = create_model( "ReadinessProbeWithEnabled", __base__=(kubernetes.ReadinessProbe), enabled=(bool, ...) )
UserDeploymentIncludeConfigInLaunchedRuns
python
astropy__astropy
astropy/modeling/projections.py
{ "start": 20988, "end": 21445 }
class ____(Pix2SkyProjection, Cylindrical): r""" Cylindrical equal area projection - pixel to sky. Corresponds to the ``CEA`` projection in FITS WCS. .. math:: \phi &= x \\ \theta &= \sin^{-1}\left(\frac{\pi}{180^{\circ}}\lambda y\right) Parameters ---------- lam : float ...
Pix2Sky_CylindricalEqualArea
python
scipy__scipy
scipy/interpolate/tests/test_interpolate.py
{ "start": 822, "end": 1017 }
class ____: def test_interp2d(self): y, x = mgrid[0:2:20j, 0:pi:21j] z = sin(x+0.5*y) with assert_raises(NotImplementedError): interp2d(x, y, z)
TestInterp2D
python
scipy__scipy
scipy/special/tests/test_iv_ratio.py
{ "start": 288, "end": 5612 }
class ____: @pytest.mark.parametrize('v,x,r', [ (0.5, 0.16666666666666666, 0.16514041292462933), (0.5, 0.3333333333333333, 0.32151273753163434), (0.5, 0.5, 0.46211715726000974), (0.5, 0.6666666666666666, 0.5827829453479101), (0.5, 0.8333333333333335, 0.6822617902381698), ...
TestIvRatio
python
apache__airflow
providers/standard/src/airflow/providers/standard/operators/python.py
{ "start": 14888, "end": 23845 }
class ____(PythonOperator, metaclass=ABCMeta): BASE_SERIALIZABLE_CONTEXT_KEYS = { "ds", "ds_nodash", "expanded_ti_count", "inlets", "outlets", "run_id", "task_instance_key_str", "test_mode", "ts", "ts_nodash", "ts_nodash_with_tz...
_BasePythonVirtualenvOperator
python
getsentry__sentry
src/sentry/workflow_engine/processors/delayed_workflow.py
{ "start": 8180, "end": 8829 }
class ____: """ Parameters to query a UniqueConditionQuery with in Snuba. """ group_ids: set[GroupId] = field(default_factory=set) timestamp: datetime | None = None def update(self, group_ids: set[GroupId], timestamp: datetime | None) -> None: """ Use the latest timestamp for a...
GroupQueryParams
python
langchain-ai__langchain
libs/core/langchain_core/runnables/utils.py
{ "start": 16990, "end": 17764 }
class ____(NamedTuple): """Field that can be configured by the user with multiple default values.""" id: str """The unique identifier of the field.""" options: Mapping[str, Any] """The options for the field.""" default: Sequence[str] """The default values for the field.""" name: str | N...
ConfigurableFieldMultiOption
python
google__pytype
pytype/tests/test_overriding.py
{ "start": 66, "end": 27883 }
class ____(test_base.BaseTest): """Tests for overridden and overriding methods signature match.""" # Positional-or-keyword -> positional-or-keyword, same name or underscore. def test_positional_or_keyword_match(self): self.Check(""" class Foo: def f(self, a: int, b: str) -> None: pass...
OverridingTest
python
MongoEngine__mongoengine
tests/test_signals.py
{ "start": 97, "end": 17748 }
class ____(unittest.TestCase): """ Testing signals before/after saving and deleting. """ def get_signal_output(self, fn, *args, **kwargs): # Flush any existing signal output global signal_output signal_output = [] fn(*args, **kwargs) return signal_output def...
TestSignal
python
jamielennox__requests-mock
requests_mock/mocker.py
{ "start": 2147, "end": 9163 }
class ____(object): """A wrapper around common mocking functions. Automate the process of mocking the requests library. This will keep the same general options available and prevent repeating code. """ _PROXY_FUNCS = { 'last_request', 'add_matcher', 'request_history', ...
MockerCore
python
getsentry__sentry
tests/sentry/api/test_authentication.py
{ "start": 10837, "end": 12360 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.auth = OrgAuthTokenAuthentication() self.org = self.create_organization(owner=self.user) self.token = "sntrys_abc123_xyz" self.org_auth_token = self.create_org_auth_token( name="Test Token 1", ...
TestOrgAuthTokenAuthentication
python
dagster-io__dagster
python_modules/libraries/dagster-fivetran/dagster_fivetran/translator.py
{ "start": 10449, "end": 10804 }
class ____(NamespacedMetadataSet): connector_id: Optional[str] = None connector_name: Optional[str] = None destination_id: Optional[str] = None destination_schema_name: Optional[str] = None destination_table_name: Optional[str] = None @classmethod def namespace(cls) -> str: return "...
FivetranMetadataSet
python
tensorflow__tensorflow
tensorflow/python/distribute/v1/input_lib.py
{ "start": 14666, "end": 16259 }
class ____(object): """Iterator for a single tensor-returning callable.""" def __init__(self, fn, worker, devices): self._fn = fn self._worker = worker self._devices = devices def get_next(self, device, name=None): """Get next element for the given device from the callable.""" del device, na...
_SingleWorkerCallableIterator
python
walkccc__LeetCode
solutions/2221. Find Triangular Sum of an Array/2221.py
{ "start": 0, "end": 202 }
class ____: def triangularSum(self, nums: list[int]) -> int: for sz in range(len(nums), 0, -1): for i in range(sz - 1): nums[i] = (nums[i] + nums[i + 1]) % 10 return nums[0]
Solution
python
pytorch__pytorch
test/distributed/checkpoint/test_pg_transport.py
{ "start": 6933, "end": 7646 }
class ____(MultiProcContinuousTest): world_size = 8 timeout: timedelta = timedelta(seconds=20) @classmethod def backend_str(cls) -> Optional[str]: return "gloo" @classmethod def device_type(cls) -> str: return "cpu" @property def device(self) -> torch.device: r...
PgTransportCPU
python
getsentry__sentry
tests/sentry/api/serializers/test_tagvalue.py
{ "start": 277, "end": 1434 }
class ____(TestCase): def test_with_user(self) -> None: user = self.create_user() tagvalue = TagValue( key="sentry:user", value="username:ted", times_seen=1, first_seen=datetime(2018, 1, 1), last_seen=datetime(2018, 1, 1), ) ...
TagValueSerializerTest
python
pypa__pip
src/pip/_vendor/rich/containers.py
{ "start": 1678, "end": 5502 }
class ____: """A list subclass which can render to the console.""" def __init__(self, lines: Iterable["Text"] = ()) -> None: self._lines: List["Text"] = list(lines) def __repr__(self) -> str: return f"Lines({self._lines!r})" def __iter__(self) -> Iterator["Text"]: return iter(...
Lines
python
bottlepy__bottle
bottle.py
{ "start": 7967, "end": 8080 }
class ____(RouteError): """ The route parser found something not supported by this router. """
RouteSyntaxError
python
huggingface__transformers
src/transformers/models/patchtst/modeling_patchtst.py
{ "start": 23614, "end": 25165 }
class ____(PreTrainedModel): config: PatchTSTConfig base_model_prefix = "model" main_input_name = "past_values" input_modalities = ("time",) supports_gradient_checkpointing = False @torch.no_grad() def _init_weights(self, module: nn.Module): """ Initialize weights ""...
PatchTSTPreTrainedModel
python
ansible__ansible
lib/ansible/plugins/lookup/list.py
{ "start": 865, "end": 1074 }
class ____(LookupBase): def run(self, terms, variables=None, **kwargs): if not isinstance(terms, Sequence): raise AnsibleError("with_list expects a list") return terms
LookupModule
python
PrefectHQ__prefect
src/prefect/client/schemas/objects.py
{ "start": 42251, "end": 43353 }
class ____(ObjectBaseModel): """An ORM representation of a block document reference.""" parent_block_document_id: UUID = Field( default=..., description="ID of block document the reference is nested within" ) parent_block_document: Optional[BlockDocument] = Field( default=None, descript...
BlockDocumentReference
python
django__django
django/contrib/gis/feeds.py
{ "start": 5455, "end": 5994 }
class ____(BaseFeed): """ This is a subclass of the `Feed` from `django.contrib.syndication`. This allows users to define a `geometry(obj)` and/or `item_geometry(item)` methods on their own subclasses so that geo-referenced information may placed in the feed. """ feed_type = GeoRSSFeed ...
Feed
python
Lightning-AI__lightning
src/lightning/pytorch/demos/boring_classes.py
{ "start": 8913, "end": 9602 }
class ____(LightningModule): """ .. warning:: This is meant for testing/debugging and is experimental. """ def __init__(self, out_dim: int = 10, learning_rate: float = 0.02): super().__init__() self.l1 = torch.nn.Linear(32, out_dim) self.learning_rate = learning_rate def f...
DemoModel
python
streamlit__streamlit
lib/streamlit/elements/widgets/checkbox.py
{ "start": 1596, "end": 1830 }
class ____: value: bool def serialize(self, v: bool) -> bool: return bool(v) def deserialize(self, ui_value: bool | None) -> bool: return bool(ui_value if ui_value is not None else self.value)
CheckboxSerde
python
joerick__pyinstrument
pyinstrument/renderers/speedscope.py
{ "start": 949, "end": 1229 }
class ____: """ Data class to store speedscope's concept of an "event", which corresponds to opening or closing stack frames as functions or methods are entered or exited. """ type: SpeedscopeEventType at: float frame: int @dataclass
SpeedscopeEvent
python
scrapy__scrapy
tests/AsyncCrawlerRunner/custom_loop_same.py
{ "start": 265, "end": 792 }
class ____(Spider): name = "no_request" custom_settings = { "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", "ASYNCIO_EVENT_LOOP": "uvloop.Loop", } async def start(self): return yield @deferred_f_from_coro_f async def main(reactor): con...
NoRequestsSpider
python
aio-libs__aiohttp
aiohttp/payload.py
{ "start": 1505, "end": 1889 }
class ____: def __init__(self, type: Any, *, order: Order = Order.normal) -> None: self.type = type self.order = order def __call__(self, factory: type["Payload"]) -> type["Payload"]: register_payload(factory, self.type, order=self.order) return factory PayloadType = type["Pay...
payload_type
python
run-llama__llama_index
llama-index-integrations/graph_stores/llama-index-graph-stores-ApertureDB/llama_index/graph_stores/ApertureDB/property_graph.py
{ "start": 2541, "end": 14657 }
class ____(PropertyGraphStore): """ ApertureDB graph store. Args: config (dict): Configuration for the graph store. **kwargs: Additional keyword arguments. """ flat_metadata: bool = True @property def client(self) -> Any: """Get client.""" return self._cli...
ApertureDBGraphStore
python
ansible__ansible
test/units/module_utils/basic/test_run_command.py
{ "start": 5765, "end": 6971 }
class ____: @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_prompt_bad_regex(self, rc_am): with pytest.raises(SystemExit): rc_am.run_command('foo', prompt_regex='[pP)assword:') assert rc_am.fail_json.called @pytest.mark.parametrize('stdin', [{}], indirect=['...
TestRunCommandPrompt
python
pallets__werkzeug
src/werkzeug/routing/exceptions.py
{ "start": 4580, "end": 4846 }
class ____(Exception): __slots__ = ("have_match_for", "websocket_mismatch") def __init__(self, have_match_for: set[str], websocket_mismatch: bool) -> None: self.have_match_for = have_match_for self.websocket_mismatch = websocket_mismatch
NoMatch
python
pypa__pip
src/pip/_vendor/rich/_win32_console.py
{ "start": 758, "end": 1544 }
class ____(NamedTuple): """Coordinates in the Windows Console API are (y, x), not (x, y). This class is intended to prevent that confusion. Rows and columns are indexed from 0. This class can be used in place of wintypes._COORD in arguments and argtypes. """ row: int col: int @classmet...
WindowsCoordinates
python
zarr-developers__zarr-python
tests/test_group.py
{ "start": 60519, "end": 60904 }
class ____: def test_from_dict_extra_fields(self): data = { "attributes": {"key": "value"}, "_nczarr_superblock": {"version": "2.0.0"}, "zarr_format": 2, } result = GroupMetadata.from_dict(data) expected = GroupMetadata(attributes={"key": "value"},...
TestGroupMetadata
python
pandas-dev__pandas
pandas/tests/indexes/string/test_indexing.py
{ "start": 5268, "end": 7850 }
class ____: @pytest.mark.parametrize( "in_slice,expected", [ # error: Slice index must be an integer or None (pd.IndexSlice[::-1], "yxdcb"), (pd.IndexSlice["b":"y":-1], ""), # type: ignore[misc] (pd.IndexSlice["b"::-1], "b"), # type: ignore[misc] ...
TestSliceLocs
python
PyCQA__pylint
tests/functional/r/regression/regression_4891.py
{ "start": 97, "end": 348 }
class ____: ''' class docstring ''' def __init__(self): self.data = {} def process(self): ''' another method is responsible for putting "static_key" ''' copy.copy(self.data['static_key'])
MyData
python
getsentry__sentry
src/sentry/seer/similarity/utils.py
{ "start": 3644, "end": 23471 }
class ____(TypedDict): frame_count: int html_frame_count: int # for a temporary metric has_no_filename: bool # for a temporary metric found_non_snipped_context_line: bool def get_stacktrace_string(data: dict[str, Any]) -> str: """Format a stacktrace string from the grouping information.""" a...
FramesMetrics
python
getsentry__sentry
src/sentry/testutils/helpers/notifications.py
{ "start": 739, "end": 2027 }
class ____(BaseNotification): group: Group template_path = "" metrics_key = "dummy" reference = None def get_subject(self, context: Mapping[str, Any] | None = None) -> str: return "My Subject" def determine_recipients(self) -> list[Actor]: return [] def build_attachment_t...
DummyNotification
python
dagster-io__dagster
python_modules/libraries/dagster-dg-cli/dagster_dg_cli/cli/scaffold/branch/ai.py
{ "start": 2305, "end": 2869 }
class ____(ABC): """Abstract base class for input types.""" @classmethod def matches(cls, user_input: str) -> bool: """Whether the user input matches this input type.""" raise NotImplementedError @classmethod def get_context(cls, user_input: str) -> str: """Fetches context ...
InputType
python
kubernetes-client__python
kubernetes/client/models/v1alpha1_volume_attributes_class.py
{ "start": 383, "end": 9717 }
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...
V1alpha1VolumeAttributesClass
python
kamyu104__LeetCode-Solutions
Python/count-palindromic-subsequences.py
{ "start": 1028, "end": 1649 }
class ____(object): def countPalindromes(self, s): """ :type s: str :rtype: int """ MOD = 10**9+7 result = 0 for i in xrange(10): for j in xrange(10): pattern = "%s%s*%s%s" % (i, j, j, i) dp = [0]*(5+1) ...
Solution2
python
huggingface__transformers
src/transformers/models/xglm/modeling_xglm.py
{ "start": 4301, "end": 11443 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__( self, embed_dim: int, num_heads: int, dropout: Optional[float] = 0.0, is_decoder: Optional[bool] = False, bias: Optional[bool] = True, layer_idx: Opti...
XGLMAttention
python
huggingface__transformers
tests/models/auto/test_image_processing_auto.py
{ "start": 1244, "end": 12857 }
class ____(unittest.TestCase): def setUp(self): transformers.dynamic_module_utils.TIME_OUT_REMOTE_CODE = 0 def test_image_processor_from_model_shortcut(self): config = AutoImageProcessor.from_pretrained("openai/clip-vit-base-patch32") self.assertIsInstance(config, CLIPImageProcessor) ...
AutoImageProcessorTest
python
getsentry__sentry
src/sentry/integrations/api/serializers/models/external_actor.py
{ "start": 549, "end": 711 }
class ____(ExternalActorResponseOptional): id: str provider: str externalName: str integrationId: str @register(ExternalActor)
ExternalActorResponse
python
dagster-io__dagster
python_modules/dagster/dagster/_grpc/types.py
{ "start": 26388, "end": 26964 }
class ____( NamedTuple( "_ShutdownServerResult", [("success", bool), ("serializable_error_info", Optional[SerializableErrorInfo])], ) ): def __new__(cls, success: bool, serializable_error_info: Optional[SerializableErrorInfo]): return super().__new__( cls, suc...
ShutdownServerResult
python
mlflow__mlflow
mlflow/genai/labeling/stores.py
{ "start": 876, "end": 1438 }
class ____(MlflowException): """Exception thrown when building a labeling store with an unsupported URI""" def __init__(self, unsupported_uri: str, supported_uri_schemes: list[str]) -> None: message = ( f"Labeling functionality is unavailable; got unsupported URI" f" '{unsupport...
UnsupportedLabelingStoreURIException
python
google__pytype
pytype/tools/traces/source_test.py
{ "start": 89, "end": 187 }
class ____: def __init__(self, name, line): self.name = name self.line = line
_FakeOpcode
python
RaRe-Technologies__gensim
gensim/test/test_probability_estimation.py
{ "start": 504, "end": 3052 }
class ____: class ProbabilityEstimationBase(unittest.TestCase): texts = [ ['human', 'interface', 'computer'], ['eps', 'user', 'interface', 'system'], ['system', 'human', 'system', 'eps'], ['user', 'response', 'time'], ['trees'], ['grap...
BaseTestCases
python
ansible__ansible
lib/ansible/_internal/_yaml/_constructor.py
{ "start": 1128, "end": 7758 }
class ____(_BaseConstructor): """Ansible constructor which supports Ansible custom behavior such as `Origin` tagging, but no Ansible-specific YAML tags.""" name: t.Any # provided by the YAML parser, which retrieves it from the stream def __init__(self, origin: Origin, trusted_as_template: bool) -> None: ...
AnsibleInstrumentedConstructor
python
kamyu104__LeetCode-Solutions
Python/longest-unequal-adjacent-groups-subsequence-ii.py
{ "start": 1734, "end": 2409 }
class ____(object): def getWordsInLongestSubsequence(self, n, words, groups): """ :type n: int :type words: List[str] :type groups: List[int] :rtype: List[str] """ def check(s1, s2): return len(s1) == len(s2) and sum(a != b for a, b in itertools.iz...
Solution3
python
coleifer__peewee
tests/signals.py
{ "start": 226, "end": 283 }
class ____(BaseSignalModel): b = TextField(default='')
B
python
mlflow__mlflow
mlflow/utils/autologging_utils/client.py
{ "start": 1663, "end": 3178 }
class ____: """ Represents a collection of operations on one or more MLflow Runs, such as run creation or metric logging. """ def __init__(self, operation_futures): self._operation_futures = operation_futures def await_completion(self): """ Blocks on completion of the M...
RunOperations
python
doocs__leetcode
solution/2200-2299/2276.Count Integers in Intervals/Solution.py
{ "start": 0, "end": 269 }
class ____: __slots__ = ("left", "right", "l", "r", "mid", "v", "add") def __init__(self, l, r): self.left = None self.right = None self.l = l self.r = r self.mid = (l + r) // 2 self.v = 0 self.add = 0
Node
python
PyCQA__pylint
tests/functional/r/regression_02/regression_4982.py
{ "start": 440, "end": 541 }
class ____(subclass): """Create a class from the __subclasses__ attribute of another class"""
Another
python
jmcnamara__XlsxWriter
xlsxwriter/test/chartsheet/test_initialisation.py
{ "start": 303, "end": 848 }
class ____(unittest.TestCase): """ Test initialisation of the Chartsheet class and call a method. """ def setUp(self): self.fh = StringIO() self.chartsheet = Chartsheet() self.chartsheet._set_filehandle(self.fh) def test_xml_declaration(self): """Test Chartsheet xm...
TestInitialisation
python
numpy__numpy
numpy/_core/tests/test_numerictypes.py
{ "start": 8023, "end": 8215 }
class ____(ReadValuesPlain): """Check the values of heterogeneous arrays (plain, multiple rows)""" _descr = Pdescr multiple_rows = 1 _buffer = PbufferT
TestReadValuesPlainMultiple
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/redefined_slots_in_subclass.py
{ "start": 172, "end": 210 }
class ____(Grandparent): pass
Parent
python
realpython__materials
hashtable/01_hashtable_prototype/06_get_the_key_value_pairs/hashtable.py
{ "start": 107, "end": 1014 }
class ____: def __init__(self, capacity): self.pairs = capacity * [None] def __len__(self): return len(self.pairs) def __delitem__(self, key): if key in self: self.pairs[self._index(key)] = None else: raise KeyError(key) def __setitem__(self, ke...
HashTable
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 56685, "end": 57579 }
class ____(Operation): def call(self, x, y): return backend.numpy.right_shift(x, y) def compute_output_spec(self, x, y): if isinstance(y, int): dtype = x.dtype else: dtype = dtypes.result_type(x.dtype, y.dtype) return KerasTensor(x.shape, dtype=dtype) @...
RightShift
python
great-expectations__great_expectations
tests/integration/fluent/test_snowflake_datasource.py
{ "start": 2380, "end": 5204 }
class ____: """Test column expectations for Snowflake datasources""" @parameterize_batch_for_data_sources( data_source_configs=[ SnowflakeDatasourceTestConfig(table_name=TEST_TABLE_NAME.lower()), ], data=pd.DataFrame({"unquoted_lower_col": ["test_value"]}), ) def tes...
TestSnowflakeColumnExpectations
python
encode__django-rest-framework
tests/test_fields.py
{ "start": 56033, "end": 56690 }
class ____(FieldValues): """ Valid and invalid values for `TimeField`. """ valid_inputs = { '13:00': datetime.time(13, 00), datetime.time(13, 00): datetime.time(13, 00), } invalid_inputs = { 'abc': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuu...
TestTimeField
python
django__django
tests/utils_tests/test_lazyobject.py
{ "start": 13655, "end": 15552 }
class ____(TestCase): """ Regression test for pickling a SimpleLazyObject wrapping a model (#25389). Also covers other classes with a custom __reduce__ method. """ def test_pickle_with_reduce(self): """ Test in a fairly synthetic setting. """ # Test every pickle prot...
SimpleLazyObjectPickleTestCase