language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
django__django
django/contrib/postgres/forms/ranges.py
{ "start": 2939, "end": 3120 }
class ____(BaseRangeField): default_error_messages = {"invalid": _("Enter two whole numbers.")} base_field = forms.IntegerField range_type = NumericRange
IntegerRangeField
python
scrapy__scrapy
tests/test_command_startproject.py
{ "start": 397, "end": 3911 }
class ____: project_name = "testproject" @staticmethod def _assert_files_exist(project_dir: Path, project_name: str) -> None: assert (project_dir / "scrapy.cfg").exists() assert (project_dir / project_name).exists() assert (project_dir / project_name / "__init__.py").exists() ...
TestStartprojectCommand
python
openai__openai-python
src/openai/resources/fine_tuning/jobs/jobs.py
{ "start": 1268, "end": 17174 }
class ____(SyncAPIResource): @cached_property def checkpoints(self) -> Checkpoints: return Checkpoints(self._client) @cached_property def with_raw_response(self) -> JobsWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw ...
Jobs
python
huggingface__transformers
tests/models/qwen2_5_omni/test_processing_qwen2_5_omni.py
{ "start": 1227, "end": 14010 }
class ____(ProcessorTesterMixin, unittest.TestCase): processor_class = Qwen2_5OmniProcessor model_id = "Qwen/Qwen2.5-Omni-7B" @classmethod def _setup_image_processor(cls): image_processor_class = cls._get_component_class_from_processor("image_processor") return image_processor_class.fro...
Qwen2_5OmniProcessorTest
python
kamyu104__LeetCode-Solutions
Python/dungeon-game.py
{ "start": 636, "end": 2158 }
class ____(object): # @param dungeon, a list of lists of integers # @return a integer def calculateMinimumHP(self, dungeon): maximum_loses = 0 for rooms in dungeon: for room in rooms: if room < 0: maximum_loses += abs(room) return self...
Solution2
python
doocs__leetcode
solution/0000-0099/0024.Swap Nodes in Pairs/Solution.py
{ "start": 151, "end": 436 }
class ____: def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: if head is None or head.next is None: return head t = self.swapPairs(head.next.next) p = head.next p.next = head head.next = t return p
Solution
python
getsentry__sentry
tests/sentry_plugins/bitbucket/test_plugin.py
{ "start": 464, "end": 4294 }
class ____(PluginTestCase): @cached_property def plugin(self) -> BitbucketPlugin: return BitbucketPlugin() @cached_property def request(self) -> RequestFactory: return RequestFactory() def test_get_issue_label(self) -> None: group = self.create_group(message="Hello world", ...
BitbucketPluginTest
python
optuna__optuna
optuna/storages/_rdb/models.py
{ "start": 19134, "end": 19700 }
class ____(BaseModel): __tablename__ = "version_info" # setting check constraint to ensure the number of rows is at most 1 __table_args__: Any = (CheckConstraint("version_info_id=1"),) version_info_id = _Column(Integer, primary_key=True, autoincrement=False, default=1) schema_version = _Column(Integ...
VersionInfoModel
python
cython__cython
Cython/Compiler/ParseTreeTransforms.py
{ "start": 155663, "end": 157107 }
class ____(EnvTransform, SkipDeclarations): """ For temporary expression that are implemented using std::optional it's necessary the temps are assigned using `__pyx_t_x = value;` but accessed using `something = (*__pyx_t_x)`. This transform inserts a coercion node to take care of this, and runs absolute...
CoerceCppTemps
python
encode__django-rest-framework
tests/test_renderers.py
{ "start": 24537, "end": 25176 }
class ____(TestCase): """ Tests specific for Static HTML Renderer """ def setUp(self): self.renderer = StaticHTMLRenderer() def test_static_renderer(self): data = '<html><body>text</body></html>' result = self.renderer.render(data) assert result == data def test...
StaticHTMLRendererTests
python
scipy__scipy
scipy/ndimage/tests/test_interpolation.py
{ "start": 54503, "end": 61290 }
class ____: @pytest.mark.parametrize('order', range(0, 6)) def test_rotate01(self, order, xp): data = xp.asarray([[0, 0, 0, 0], [0, 1, 1, 0], [0, 0, 0, 0]], dtype=xp.float64) out = ndimage.rotate(data, 0, order=order) assert_array_al...
TestRotate
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/operators/emr.py
{ "start": 35327, "end": 38161 }
class ____(AwsBaseOperator[EmrHook]): """ An operator that modifies an existing EMR cluster. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:EmrModifyClusterOperator` :param cluster_id: cluster identifier :param step_con...
EmrModifyClusterOperator
python
rq__rq
rq/scheduler.py
{ "start": 746, "end": 854 }
class ____(str, Enum): STARTED = 'started' WORKING = 'working' STOPPED = 'stopped'
SchedulerStatus
python
Textualize__textual
src/textual/widgets/_markdown.py
{ "start": 22424, "end": 22497 }
class ____(MarkdownBlock): """A table row Markdown block."""
MarkdownTR
python
wandb__wandb
wandb/integration/weave/interface.py
{ "start": 301, "end": 1165 }
class ____: entity: str """The entity to which the run is logging. Never empty.""" project: str """The project to which the run is logging. Never empty.""" run_id: str """The run's ID. Never empty.""" def active_run_path() -> RunPath | None: """Returns the path of an initialized, unfinis...
RunPath
python
PrefectHQ__prefect
tests/server/database/test_dependencies.py
{ "start": 4359, "end": 7193 }
class ____: @pytest.fixture(autouse=True) def _setup(self): self.db: PrefectDBInterface = dependencies.provide_database_interface() def test_decorated_function(self): @dependencies.db_injector def function_with_injected_db( db: PrefectDBInterface, foo: int ) -> P...
TestDBInject
python
h5py__h5py
api_gen.py
{ "start": 1569, "end": 6235 }
class ____: """ Represents one line from the api_functions.txt file. Exists to provide the following attributes: nogil: String indicating if we should release the GIL to call this function. Any Python callbacks it could trigger must acquire the...
Line
python
huggingface__transformers
tests/models/falcon_mamba/test_modeling_falcon_mamba.py
{ "start": 1629, "end": 9463 }
class ____: def __init__( self, parent, batch_size=14, seq_length=7, is_training=True, use_labels=True, vocab_size=99, hidden_size=32, num_hidden_layers=2, intermediate_size=32, hidden_act="silu", hidden_dropout_prob=0.1...
FalconMambaModelTester
python
ansible__ansible
test/units/module_utils/basic/test_heuristic_log_sanitize.py
{ "start": 831, "end": 3638 }
class ____: def setup_method(self): self.URL_SECRET = 'http://username:pas:word@foo.com/data' self.SSH_SECRET = 'username:pas:word@foo.com/data' self.clean_data = repr(self._gen_data(3, True, True, 'no_secret_here')) self.url_data = repr(self._gen_data(3, True, True, self.URL_SECRET)...
TestHeuristicLogSanitize
python
readthedocs__readthedocs.org
readthedocs/embed/v3/views.py
{ "start": 16362, "end": 16436 }
class ____(SettingsOverrideObject): _default_class = EmbedAPIBase
EmbedAPI
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/pool_test.py
{ "start": 3583, "end": 4092 }
class ____(op_bench.TorchBenchmarkBase): def init(self, kernel, stride, N, C, D, H, W, device, op_func): self.inputs = {"input": torch.rand(N, C, D, H, W, device=device)} self.op_func = op_func(kernel, stride=stride) def forward(self, input): return self.op_func(input) op_bench.genera...
Pool3dBenchmark
python
walkccc__LeetCode
solutions/2126. Destroying Asteroids/2126.py
{ "start": 0, "end": 229 }
class ____: def asteroidsDestroyed(self, mass: int, asteroids: list[int]) -> bool: for asteroid in sorted(asteroids): if mass >= asteroid: mass += asteroid else: return False return True
Solution
python
numpy__numpy
numpy/_core/tests/test_shape_base.py
{ "start": 585, "end": 1813 }
class ____: def test_0D_array(self): a = array(1) b = array(2) res = [atleast_1d(a), atleast_1d(b)] desired = [array([1]), array([2])] assert_array_equal(res, desired) def test_1D_array(self): a = array([1, 2]) b = array([2, 3]) res = [atleast_1d(...
TestAtleast1d
python
kamyu104__LeetCode-Solutions
Python/correct-a-binary-tree.py
{ "start": 66, "end": 159 }
class ____(object): def __init__(self, val=0, left=None, right=None): pass
TreeNode
python
ApeWorX__ape
src/ape/utils/basemodel.py
{ "start": 1471, "end": 1743 }
class ____(property): _cache = None def __init__(self, fn): self.fn = fn def __get__(self, obj, owner) -> Any: # type: ignore[override] if self._cache is None: self._cache = self.fn(owner) return self._cache
manager_access
python
bokeh__bokeh
src/bokeh/core/has_props.py
{ "start": 9059, "end": 9135 }
class ____: """Resolve this class by a non-qualified name. """
NonQualified
python
aimacode__aima-python
utils.py
{ "start": 17768, "end": 18815 }
class ____: """Given 'P |'==>'| Q, first form PartialExpr('==>', P), then combine with Q.""" def __init__(self, op, lhs): self.op, self.lhs = op, lhs def __or__(self, rhs): return Expr(self.op, self.lhs, rhs) def __repr__(self): return "PartialExpr('{}', {})".format(self.op, s...
PartialExpr
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/connectors/asyncio.py
{ "start": 1219, "end": 1782 }
class ____(Protocol): """protocol representing an async adapted version of a :pep:`249` database connection. """ # note that async DBAPIs dont agree if close() should be awaitable, # so it is omitted here and picked up by the __getattr__ hook below async def commit(self) -> None: ... de...
AsyncIODBAPIConnection
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/ddl.py
{ "start": 15093, "end": 15274 }
class ____(_CreateDropBase[_SI]): def __init__(self, element: _SI, if_exists: bool = False) -> None: super().__init__(element) self.if_exists = if_exists
_DropBase
python
bokeh__bokeh
src/bokeh/application/handlers/handler.py
{ "start": 2554, "end": 7953 }
class ____: ''' Provide a mechanism for Bokeh applications to build up new Bokeh Documents. ''' _failed: bool _error: str | None _error_detail: str | None _static: str | None def __init__(self) -> None: self._failed = False self._error = None self._error_detail...
Handler
python
numpy__numpy
numpy/lib/_arraysetops_impl.py
{ "start": 14805, "end": 14944 }
class ____(NamedTuple): values: np.ndarray indices: np.ndarray inverse_indices: np.ndarray counts: np.ndarray
UniqueAllResult
python
tensorflow__tensorflow
tensorflow/python/framework/memory_checker.py
{ "start": 1373, "end": 4522 }
class ____(object): """Memory leak detection class. This is a utility class to detect Python and C++ memory leaks. It's intended for both testing and debugging. Basic usage: >>> # MemoryChecker() context manager tracks memory status inside its scope. >>> with MemoryChecker() as memory_checker: >>> tenso...
MemoryChecker
python
django__django
tests/syndication_tests/feeds.py
{ "start": 1684, "end": 2429 }
class ____(TestRss2Feed): class TimeToLive: @wraps_decorator def __call__(self): return 800 @staticmethod @wraps_decorator def feed_copyright(): return "Copyright (c) 2022, John Doe" ttl = TimeToLive() @staticmethod def categories(): return ("ja...
TestRss2FeedWithDecoratedMethod
python
getsentry__sentry
src/sentry/api/endpoints/organization_traces.py
{ "start": 4295, "end": 4501 }
class ____(OrganizationEventsV2EndpointBase): publish_status = { "GET": ApiPublishStatus.EXPERIMENTAL, } owner = ApiOwner.DATA_BROWSING @region_silo_endpoint
OrganizationTracesEndpointBase
python
pytorch__pytorch
test/inductor/test_remote_cache.py
{ "start": 577, "end": 618 }
class ____: fail: str = None
TestSample
python
doocs__leetcode
solution/0300-0399/0323.Number of Connected Components in an Undirected Graph/Solution2.py
{ "start": 563, "end": 751 }
class ____: def countComponents(self, n: int, edges: List[List[int]]) -> int: uf = UnionFind(n) for a, b in edges: n -= uf.union(a, b) return n
Solution
python
ray-project__ray
rllib/env/wrappers/pettingzoo_env.py
{ "start": 5232, "end": 6645 }
class ____(MultiAgentEnv): def __init__(self, env): super().__init__() self.par_env = env self.par_env.reset() self._agent_ids = set(self.par_env.agents) # If these important attributes are not set, try to infer them. if not self.agents: self.agents = lis...
ParallelPettingZooEnv
python
cython__cython
tests/run/pure_mode_cmethod_inheritance_T583.py
{ "start": 1108, "end": 1475 }
class ____(Base): ''' >>> derived = Derived2() >>> print(derived.noargs()) Derived2 >>> print(derived.int_arg(1)) Derived2 >>> print(derived._class()) Derived2 ''' def noargs(self): return "Derived2" def int_arg(self, i): return "Derived2" @classmethod ...
Derived2
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_pools.py
{ "start": 1841, "end": 2074 }
class ____: @pytest.fixture(autouse=True) def setup(self) -> None: clear_db_pools() def teardown_method(self) -> None: clear_db_pools() def create_pools(self): _create_pools()
TestPoolsEndpoint
python
eventlet__eventlet
tests/patcher_test.py
{ "start": 7661, "end": 9510 }
class ____(ProcessBase): TEST_TIMEOUT = 3 def test_simple(self): new_mod = """ import eventlet from eventlet import patcher patcher.monkey_patch() from eventlet import tpool print("newmod {0}".format(tpool.execute(len, "hi"))) print("newmod {0}".format(tpool.execute(len, "hi2"))) tpool.killall() """ ...
Tpool
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/inputs.py
{ "start": 14487, "end": 16097 }
class ____(graphene.InputObjectType): statuses = graphene.List( graphene.NonNull("dagster_graphql.schema.backfill.GrapheneBulkActionStatus") ) createdBefore = graphene.InputField(graphene.Float) createdAfter = graphene.InputField(graphene.Float) class Meta: description = """This typ...
GrapheneBulkActionsFilter
python
huggingface__transformers
src/transformers/models/patchtsmixer/modeling_patchtsmixer.py
{ "start": 68710, "end": 69606 }
class ____(ModelOutput): r""" loss (*optional*, returned when `y` is provided, `torch.FloatTensor` of shape `()`): Total loss. prediction_outputs (`torch.FloatTensor` of shape `(batch_size, num_labels)`): Prediction output from the classification head. last_hidden_state (`torch.FloatTens...
PatchTSMixerForTimeSeriesClassificationOutput
python
spyder-ide__spyder
spyder/app/tests/script_outline_3.py
{ "start": 326, "end": 431 }
class ____: E = 1 def five(self): return 5 def six(self): return 4
AnotherClass
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/sparse_ops/sparse_concat_op_test.py
{ "start": 1078, "end": 15232 }
class ____(test.TestCase): def _SparseTensor_UnknownShape(self, ind_shape=None, val_shape=None, shape_shape=None): return sparse_tensor.SparseTensor( array_ops.placeholder( dtypes.int64, shape=i...
SparseConcatTest
python
numpy__numpy
numpy/_core/tests/test_mem_overlap.py
{ "start": 18028, "end": 29317 }
class ____: """ Test ufunc call memory overlap handling """ def check_unary_fuzz(self, operation, get_out_axis_size, dtype=np.int16, count=5000): shapes = [7, 13, 8, 21, 29, 32] rng = np.random.RandomState(1234) for ndim in range(1, 6): ...
TestUFunc
python
coleifer__peewee
playhouse/psycopg3_ext.py
{ "start": 1952, "end": 4067 }
class ____(IndexedFieldMixin, Field): field_type = 'JSONB' _json_datatype = 'jsonb' __hash__ = Field.__hash__ def __init__(self, dumps=None, *args, **kwargs): self.dumps = dumps or json.dumps super(BinaryJSONField, self).__init__(*args, **kwargs) def db_value(self, value): ...
BinaryJSONField
python
PyCQA__pyflakes
pyflakes/messages.py
{ "start": 3805, "end": 3920 }
class ____(Message): message = 'from __future__ imports must occur at the beginning of the file'
LateFutureImport
python
pytorch__pytorch
test/export/test_verifier.py
{ "start": 519, "end": 7969 }
class ____(TestCase): def test_verifier_basic(self) -> None: class Foo(torch.nn.Module): def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: return x + y f = Foo() ep = export(f, (torch.randn(100), torch.randn(100)), strict=True) verifi...
TestVerifier
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/metrics_test.py
{ "start": 66188, "end": 82075 }
class ____(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() @test_util.run_deprecated_v1 def testVars(self): metrics.precision_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0, 0.5, 1.0]) _assert...
PrecisionRecallThresholdsTest
python
huggingface__transformers
tests/models/align/test_modeling_align.py
{ "start": 3841, "end": 7858 }
class ____(ModelTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as ALIGN does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = (AlignVisionModel,) if is_torch_available() else () test_resize_embed...
AlignVisionModelTest
python
altair-viz__altair
altair/vegalite/v6/schema/_config.py
{ "start": 225860, "end": 227312 }
class ____(TypedDict, total=False): """ :class:`altair.RadialGradient` ``TypedDict`` wrapper. Parameters ---------- gradient The type of gradient. Use ``"radial"`` for a radial gradient. stops An array of gradient stops defining the gradient color sequence. id r1 ...
RadialGradientKwds
python
getsentry__sentry
src/sentry/integrations/msteams/card_builder/block.py
{ "start": 2049, "end": 2136 }
class ____(_TextBlockNotRequired): type: Literal["TextBlock"] text: str
TextBlock
python
doocs__leetcode
solution/3100-3199/3125.Maximum Number That Makes Result of Bitwise AND Zero/Solution.py
{ "start": 0, "end": 103 }
class ____: def maxNumber(self, n: int) -> int: return (1 << (n.bit_length() - 1)) - 1
Solution
python
encode__httpx
tests/client/test_auth.py
{ "start": 2474, "end": 3348 }
class ____(httpx.Auth): """ A mock authentication scheme that requires clients to send the request a fixed number of times, and then send a last request containing an aggregation of nonces that the server sent in 'WWW-Authenticate' headers of intermediate responses. """ requires_request_bod...
RepeatAuth
python
getsentry__sentry
src/sentry/issues/endpoints/team_issue_breakdown.py
{ "start": 917, "end": 4759 }
class ____(TeamEndpoint): owner = ApiOwner.ISSUES publish_status = { "GET": ApiPublishStatus.PRIVATE, } def get(self, request: Request, team: Team) -> Response: """ Returns a dict of team projects, and a time-series dict of issue stat breakdowns for each. If a list of s...
TeamIssueBreakdownEndpoint
python
fastapi__sqlmodel
docs_src/tutorial/relationship_attributes/cascade_delete_relationships/tutorial002_py310.py
{ "start": 300, "end": 3335 }
class ____(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: int | None = Field(default=None, index=True) team_id: int | None = Field( default=None, foreign_key="team.id", ondelete="SET NULL" ) team: Tea...
Hero
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_redshift_data.py
{ "start": 2083, "end": 18560 }
class ____: def test_init(self): op = RedshiftDataOperator( task_id="fake_task_id", database="fake-db", sql="SELECT 1", aws_conn_id="fake-conn-id", region_name="eu-central-1", verify="/spam/egg.pem", botocore_config={"read_t...
TestRedshiftDataOperator
python
getsentry__sentry
tests/sentry/incidents/serializers/test_workflow_engine_data_condition.py
{ "start": 707, "end": 8047 }
class ____(TestWorkflowEngineSerializer): def setUp(self) -> None: super().setUp() self.add_warning_trigger() def create_rule_triggers_and_actions( self, ) -> tuple[ AlertRule, AlertRuleTrigger, AlertRuleTrigger, AlertRuleTriggerAction, AlertR...
TestDataConditionSerializer
python
ray-project__ray
python/ray/_common/formatters.py
{ "start": 3662, "end": 3939 }
class ____(AbstractFormatter): def format(self, record: logging.LogRecord) -> str: record_format_attrs = self.generate_record_format_attrs( record, exclude_default_standard_attrs=False ) return json.dumps(record_format_attrs)
JSONFormatter
python
getsentry__sentry
src/sentry/issue_detection/detectors/consecutive_http_detector.py
{ "start": 923, "end": 7616 }
class ____(PerformanceDetector): type = DetectorType.CONSECUTIVE_HTTP_OP settings_key = DetectorType.CONSECUTIVE_HTTP_OP def __init__(self, settings: dict[DetectorType, Any], event: dict[str, Any]) -> None: super().__init__(settings, event) self.consecutive_http_spans: list[Span] = [] ...
ConsecutiveHTTPSpanDetector
python
modin-project__modin
modin/core/dataframe/algebra/default2pandas/rolling.py
{ "start": 2474, "end": 4477 }
class ____(DefaultMethod): """Builder for default-to-pandas aggregation on an expanding window functions.""" OBJECT_TYPE = "Expanding" @classmethod def _build_expanding(cls, func, squeeze_self): """ Build function that creates an expanding window and executes `func` on it. Par...
ExpandingDefault
python
google__pytype
pytype/ast/visitor_test.py
{ "start": 120, "end": 365 }
class ____(visitor.BaseVisitor): """Tests visit order.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.funcs = [] def visit_FunctionDef(self, node): self.funcs.append(node.name)
_VisitOrderVisitor
python
spyder-ide__spyder
spyder/plugins/ipythonconsole/widgets/debugging.py
{ "start": 6632, "end": 27026 }
class ____(DebuggingHistoryWidget, SpyderConfigurationAccessor): """ Widget with the necessary attributes and methods to handle communications between a console in debugging mode and Spyder """ CONF_SECTION = 'ipython_console' def __init__(self, *args, **kwargs): # Communication st...
DebuggingWidget
python
mlflow__mlflow
examples/llama_index/workflow/workflow/workflow.py
{ "start": 771, "end": 6387 }
class ____(Workflow): VALID_RETRIEVERS = {"vector_search", "bm25", "web_search"} def __init__(self, retrievers=None, **kwargs): super().__init__(**kwargs) self.llm = Settings.llm self.retrievers = retrievers or [] if invalid_retrievers := set(self.retrievers) - self.VALID_RETRI...
HybridRAGWorkflow
python
django__django
tests/gis_tests/geos_tests/test_mutable_list.py
{ "start": 17053, "end": 17120 }
class ____(ListMixinTest): listType = UserListB
ListMixinTestSingle
python
cython__cython
Cython/Debugger/Tests/TestLibCython.py
{ "start": 5382, "end": 7501 }
class ____(DebuggerTestCase): def setUp(self): if not test_gdb(): return super().setUp() prefix_code = textwrap.dedent('''\ python import os import sys import traceback def excepthook(type, value, tb): ...
GdbDebuggerTestCase
python
coleifer__peewee
tests/sql.py
{ "start": 93486, "end": 95013 }
class ____(BaseTestCase): def _test_sql_to_string(self, _param): class FakeDB(SqliteDatabase): param = _param db = FakeDB(None) T = Table('tbl', ('id', 'val')).bind(db) query = (T.select() .where((T.val == 'foo') | (T.val == b'ba...
TestSqlToString
python
getsentry__sentry
src/sentry/api/serializers/models/dashboard.py
{ "start": 15490, "end": 15628 }
class ____(TypedDict, total=False): period: str utc: str expired: bool start: datetime end: datetime
PageFiltersOptional
python
huggingface__transformers
src/transformers/quantizers/auto.py
{ "start": 3678, "end": 5770 }
class ____: """ The Auto-HF quantization config class that takes care of automatically dispatching to the correct quantization config given a quantization config stored in a dictionary. """ @classmethod def from_dict(cls, quantization_config_dict: dict): quant_method = quantization_conf...
AutoQuantizationConfig
python
wandb__wandb
wandb/integration/lightning/fabric/logger.py
{ "start": 1328, "end": 27233 }
class ____(Logger): r"""Log using `Weights and Biases <https://docs.wandb.ai/integrations/lightning>`_. **Installation and set-up** Install with pip: .. code-block:: bash pip install wandb Create a `WandbLogger` instance: .. code-block:: python from lightning.fabric.logger...
WandbLogger
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/layout/mouse_handlers.py
{ "start": 385, "end": 1589 }
class ____: """ Two dimensional raster of callbacks for mouse events. """ def __init__(self) -> None: def dummy_callback(mouse_event: MouseEvent) -> NotImplementedOrNone: """ :param mouse_event: `MouseEvent` instance. """ return NotImplemented ...
MouseHandlers
python
huggingface__transformers
src/transformers/models/roc_bert/configuration_roc_bert.py
{ "start": 797, "end": 7779 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`RoCBertModel`]. It is used to instantiate a RoCBert model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar confi...
RoCBertConfig
python
scipy__scipy
scipy/linalg/tests/test_blas.py
{ "start": 28713, "end": 29997 }
class ____: def setup_method(self): self.a = np.array([[1., 0.], [0., -2.], [2., 3.]]) self.t = np.array([[1., 0., 2.], [0., 4., -6.], [2., -6., 13.]]) self.tt = np.array([[5., 6.], ...
TestBLAS3Syrk
python
fluentpython__example-code-2e
05-data-classes/dataclass/resource.py
{ "start": 1787, "end": 2810 }
class ____(TypedDict): identifier: str title: str creators: list[str] date: Optional[date] type: ResourceType description: str language: str subjects: list[str] if __name__ == '__main__': r = Resource('0') description = 'Improving the design of existing code' book = Resourc...
ResourceDict
python
walkccc__LeetCode
solutions/343. Integer Break/343.py
{ "start": 0, "end": 559 }
class ____: def integerBreak(self, n: int) -> int: # If an optimal product contains a factor f >= 4, then we can replace it # with 2 and f - 2 without losing optimality. As 2(f - 2) = 2f - 4 >= f, # we never need a factor >= 4, meaning we only need factors 1, 2, and 3 # (and 1 is wasteful). # Also...
Solution
python
sympy__sympy
sympy/core/tests/test_priority.py
{ "start": 287, "end": 2000 }
class ____(Integer): ''' Integer of value 1 and _op_priority 20 Operations handled by this class return 1 and reverse operations return 2 ''' _op_priority = 20.0 result: Expr = S.One def __new__(cls): obj = Expr.__new__(cls) obj.p = 1 return obj @call_highest_...
Higher
python
readthedocs__readthedocs.org
readthedocs/builds/migrations/0043_add_cancelled_state.py
{ "start": 149, "end": 976 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("builds", "0042_version_state"), ] operations = [ migrations.AlterField( model_name="build", name="state", field=models.CharField( choices=[ ...
Migration
python
doocs__leetcode
solution/3000-3099/3069.Distribute Elements Into Two Arrays I/Solution.py
{ "start": 0, "end": 293 }
class ____: def resultArray(self, nums: List[int]) -> List[int]: arr1 = [nums[0]] arr2 = [nums[1]] for x in nums[2:]: if arr1[-1] > arr2[-1]: arr1.append(x) else: arr2.append(x) return arr1 + arr2
Solution
python
huggingface__transformers
src/transformers/models/poolformer/modeling_poolformer.py
{ "start": 4579, "end": 6844 }
class ____(nn.Module): """This corresponds to the 'PoolFormerBlock' class in the original implementation.""" def __init__(self, config, num_channels, pool_size, hidden_size, intermediate_size, drop_path): super().__init__() self.pooling = PoolFormerPooling(pool_size) self.output = PoolF...
PoolFormerLayer
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/util/langhelpers.py
{ "start": 12588, "end": 33341 }
class ____: def __init__( self, group: str, auto_fn: Optional[Callable[..., Any]] = None ): self.group = group self.impls: Dict[str, Any] = {} self.auto_fn = auto_fn def clear(self): self.impls.clear() def load(self, name: str) -> Any: if name in self.im...
PluginLoader
python
readthedocs__readthedocs.org
readthedocs/organizations/tests/test_privacy_urls.py
{ "start": 1822, "end": 2983 }
class ____(OrganizationMixin, TestCase): """All views are available for the owner of the organization.""" response_data = { # Places where we 302 on success. "/organizations/choose/{next_name}/": {"status_code": 302}, "/organizations/invite/{hash}/redeem/": {"status_code": 302}, ...
AuthUserOrganizationsTest
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/llama_index/vector_stores/azure_postgres/common/_shared.py
{ "start": 11318, "end": 11860 }
class ____(SearchParams): ef_search: Annotated[PositiveInt | None, Field(le=1_000)] = None iterative_scan: HNSWIterativeScanMode | None = None max_scan_tuples: PositiveInt | None = None scan_mem_multiplier: Annotated[PositiveFloat | None, Field(le=1_000)] = None @override def search_settings(se...
HNSWSearchParams
python
prakhar1989__Algorithms
tests/singly_linked_list_test.py
{ "start": 143, "end": 668 }
class ____(unittest.TestCase): def setUp(self): self.tens = SinglyLinkedList(range(0, 100, 10)) self.blankList = SinglyLinkedList() def test_length_method(self): self.assertEqual(len(self.tens), 10) self.assertEqual(len(self.blankList), 0) def test_add_method(self): ...
test_graph
python
django__django
django/contrib/postgres/fields/citext.py
{ "start": 122, "end": 533 }
class ____(CharField): system_check_removed_details = { "msg": ( "django.contrib.postgres.fields.CICharField is removed except for support " "in historical migrations." ), "hint": ( 'Use CharField(db_collation="…") with a case-insensitive non-deterministic...
CICharField
python
getsentry__sentry
src/sentry/hybridcloud/outbox/base.py
{ "start": 896, "end": 2937 }
class ____(Model): """ overrides model save, update, and delete methods such that, within an atomic transaction, an outbox returned from outbox_for_update is saved. Furthermore, using this mixin causes get_protected_operations to protect any updates/deletes/inserts of this model that do not go through t...
RegionOutboxProducingModel
python
apache__airflow
providers/google/src/airflow/providers/google/marketing_platform/operators/search_ads.py
{ "start": 9772, "end": 10959 }
class ____(_GoogleSearchAdsBaseOperator): """ List all custom columns. .. seealso: For API documentation check: https://developers.google.com/search-ads/reporting/api/reference/rest/v0/customers.customColumns/list .. seealso:: For more information on how to use this operator, t...
GoogleSearchAdsListCustomColumnsOperator
python
pandas-dev__pandas
pandas/tests/frame/methods/test_astype.py
{ "start": 31099, "end": 32565 }
class ____(pd.Int16Dtype): # GH 42501 def construct_array_type(self): return IntegerArrayNoCopy def test_frame_astype_no_copy(): # GH 42501 df = DataFrame({"a": [1, 4, None, 5], "b": [6, 7, 8, 9]}, dtype=object) result = df.astype({"a": Int16DtypeNoCopy()}) assert result.a.dtype == p...
Int16DtypeNoCopy
python
euske__pdfminer
pdfminer/ccitt.py
{ "start": 23474, "end": 25463 }
class ____(CCITTG4Parser): def __init__(self, width, bytealign=False, reversed=False): CCITTG4Parser.__init__(self, width, bytealign=bytealign) self.reversed = reversed self._buf = b'' return def close(self): return self._buf def output_line(self, y, bits): ...
CCITTFaxDecoder
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeVarDefaultTypeAlias3.py
{ "start": 3332, "end": 3802 }
class ____[T1, *Ts2]: ... type TA_TC[T1 = str, *Ts2 = Unpack[tuple[T1, ...]]] = ClassTC[T1, *Ts2] def func6( tc1: TA_TC, tc2: TA_TC[int], tc3: TA_TC[int, *tuple[()]], tc4: TA_TC[int, *tuple[None]], ): reveal_type(tc1, expected_text="ClassTC[str, *tuple[str, ...]]") reveal_type(tc2, expected_...
ClassTC
python
great-expectations__great_expectations
docs/docusaurus/versioned_docs/version-0.18/oss/guides/expectations/creating_custom_expectations/column_pair_map_expectation_template.py
{ "start": 1051, "end": 2783 }
class ____(ColumnPairMapMetricProvider): # </snippet> # This is the id string that will be used to reference your metric. # <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/column_pair_map_expectation_template.py metric_name"> condition_metric_name = "METRIC NAME ...
ColumnPairValuesMatchSomeCriteria
python
catalyst-team__catalyst
catalyst/metrics/_cmc_score.py
{ "start": 8205, "end": 13511 }
class ____(AccumulativeMetric): """Cumulative Matching Characteristics for Reid case Args: embeddings_key: key of embedding tensor in batch pids_key: key of pids tensor in batch cids_key: key of cids tensor in batch is_query_key: key of query flag tensor in batch topk: l...
ReidCMCMetric
python
django__django
tests/admin_changelist/admin.py
{ "start": 1989, "end": 2055 }
class ____(admin.ModelAdmin): list_filter = ["genres"]
BandAdmin
python
django__django
tests/admin_changelist/admin.py
{ "start": 2698, "end": 2766 }
class ____(admin.ModelAdmin): list_filter = ["members"]
GroupAdmin
python
pytorch__pytorch
test/torch_np/test_ndarray_methods.py
{ "start": 17205, "end": 21653 }
class ____(TestCase): usg_data = [ ([1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], 8), ([3, 3, 3, 3, 2, 2, 2, 2], 4), ([0, 1, 2, 3, 4, 5, 6, 7], 0), ([7, 6, 5, 4, 3, 2, 1, 0], 7), ] sg_data = usg_data + [ ([1, 2, 3, 4, -4, -3, -2, -1], 4), ([1, 2, 3, 4, -1, -2...
TestArgmin
python
facebookresearch__faiss
faiss/gpu/test/test_gpu_basics.py
{ "start": 8149, "end": 11548 }
class ____(unittest.TestCase): def test_input_types(self): self.do_test_input_types(0, 0) def test_input_types_tiling(self): self.do_test_input_types(0, 500) self.do_test_input_types(1000, 0) self.do_test_input_types(1000, 500) def do_test_input_types(self, vectorsMemoryLim...
TestKnn
python
walkccc__LeetCode
solutions/3509. Maximum Product of Subsequences With an Alternating Sum Equal to K/3509.py
{ "start": 24, "end": 240 }
class ____(Enum): FIRST = 0 # first element - add to sum and start product SUBTRACT = 1 # second element - subtract from sum and multiply product ADD = 2 # third element - add to sum and multiply product
State
python
tensorflow__tensorflow
tensorflow/python/keras/engine/keras_tensor.py
{ "start": 22463, "end": 25178 }
class ____(object): """Iterates over the leading dim of a KerasTensor. Performs 0 error checks.""" def __init__(self, tensor, dim0): self._tensor = tensor self._index = 0 self._limit = dim0 def __iter__(self): return self def __next__(self): if self._index == self._limit: raise Stop...
_KerasTensorIterator
python
tiangolo__fastapi
fastapi/openapi/models.py
{ "start": 2179, "end": 2301 }
class ____(BaseModelWithConfig): name: str identifier: Optional[str] = None url: Optional[AnyUrl] = None
License
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/endpoints/backend/main.py
{ "start": 4752, "end": 5305 }
class ____(remote.Service): @endpoints.method( message_types.VoidMessage, Greeting, path="greet", http_method="POST", name="greet", ) def greet(self, request): user = endpoints.get_current_user() user_name = user.email() if user else "Anonymous" ...
AuthedGreetingApi
python
cython__cython
tests/run/posonly.py
{ "start": 11203, "end": 18330 }
class ____(object): """ >>> TestMangling().f() 42 >>> TestMangling().f2() 42 #>>> TestMangling().f3() #(42, 43) #>>> TestMangling().f4() #(42, 43, 44) >>> TestMangling().f2(1) 1 #>>> TestMangling().f3(1, _TestMangling__b=2) #(1, 2) #>>> TestMangling().f4(1, _Te...
TestMangling