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
cython__cython
Cython/Compiler/Nodes.py
{ "start": 406506, "end": 432748 }
class ____(StatNode, ParallelNode): """ Base class for 'with cython.parallel.parallel():' and 'for i in prange():'. assignments { Entry(var) : (var.pos, inplace_operator_or_None) } assignments to variables in this parallel section parent parent ParallelStatNode or None...
ParallelStatNode
python
Textualize__textual
src/textual/css/_style_properties.py
{ "start": 4250, "end": 7576 }
class ____: """Descriptor for getting and setting scalar properties. Scalars are numeric values with a unit, e.g. "50vh".""" def __init__( self, units: set[Unit] | None = None, percent_unit: Unit = Unit.WIDTH, allow_auto: bool = True, ) -> None: self.units: set[Unit]...
ScalarProperty
python
tensorflow__tensorflow
tensorflow/python/ops/structured/structured_tensor_test.py
{ "start": 2538, "end": 3183 }
class ____(extension_type.ExtensionType): ragged: ragged_tensor.RaggedTensor @dispatch.dispatch_for_types(array_ops.shape_v2, _PrivateBrokenType) def shape_v2_broken( input: _PrivateBrokenType, # pylint: disable=redefined-builtin out_type: dtypes.DType = None, name: Optional[str] = None) -> DynamicRagg...
_PrivateBrokenType
python
pydantic__pydantic
tests/mypy/outputs/mypy-plugin-strict_ini/plugin_fail_baseConfig.py
{ "start": 171, "end": 788 }
class ____(BaseModel): x: int y: str def method(self) -> None: pass class Config: alias_generator = None frozen = True extra = Extra.forbid def config_method(self) -> None: ... model = Model(x=1, y='y', z='z') # MYPY: error: Unexpected keyword arg...
Model
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/data_version.py
{ "start": 1638, "end": 2606 }
class ____( NamedTuple( "_DataVersionsByPartition", [("data_versions_by_partition", Mapping[str, DataVersion])] ) ): def __new__( cls, data_versions_by_partition: Mapping[str, Union[str, DataVersion]], ): check.dict_param( data_versions_by_partition, ...
DataVersionsByPartition
python
getsentry__sentry
src/sentry/utils/snuba.py
{ "start": 15463, "end": 15729 }
class ____(QueryExecutionError): """ This query has resulted in needing to check multiple datasets in a way that is not currently handled, clickhouse errors with data being compressed by different methods when this happens """
DatasetSelectionError
python
pypa__warehouse
warehouse/observations/models.py
{ "start": 5431, "end": 7946 }
class ____: """ A mixin for models that can have Observations. Since Observations require a User to link to as the creator, any code using `record_observation()` will need to pass a `request` object that has a `user` attribute. For Views, when using `@view_config(..., uses_session=True)`, U...
HasObservations
python
google__jax
jax/_src/pallas/mosaic/core.py
{ "start": 7081, "end": 7782 }
class ____(enum.Enum): REGULAR = "regular" DMA = "dma" BARRIER = "barrier" def __call__(self, shape: tuple[int, ...]): dtype: Any if self == SemaphoreType.DMA: dtype = DMASemaphore() elif self == SemaphoreType.BARRIER: dtype = pallas_core.BarrierSemaphore() else: dtype = palla...
SemaphoreType
python
matplotlib__matplotlib
lib/matplotlib/_docstring.py
{ "start": 2105, "end": 2576 }
class ____(dict): def __missing__(self, key): if not key.endswith(":kwdoc"): raise KeyError(key) name = key[:-len(":kwdoc")] from matplotlib.artist import Artist, kwdoc try: cls, = (cls for cls in _api.recursive_subclasses(Artist) if cls.__...
_ArtistKwdocLoader
python
spyder-ide__spyder
spyder/plugins/run/widgets.py
{ "start": 2232, "end": 5138 }
class ____(QDialog): """Run configuration dialog box, base widget""" size_change = Signal(QSize) def __init__(self, parent=None, disable_run_btn=False): QDialog.__init__(self, parent) self.setWindowFlags( self.windowFlags() & ~Qt.WindowContextHelpButtonHint) # Destroyin...
BaseRunConfigDialog
python
walkccc__LeetCode
solutions/2858. Minimum Edge Reversals So Every Node Is Reachable/2858.py
{ "start": 0, "end": 904 }
class ____: def minEdgeReversals(self, n: int, edges: list[list[int]]) -> list[int]: graph = [[] for _ in range(n)] for u, v in edges: graph[u].append((v, True)) # 1 means (u -> v) graph[v].append((u, False)) # 0 means (v <- u) seen = {0} @functools.lru_cache(None) def dp(u: int) ...
Solution
python
encode__django-rest-framework
rest_framework/validators.py
{ "start": 12010, "end": 12604 }
class ____(BaseUniqueForValidator): message = _('This field must be unique for the "{date_field}" date.') def filter_queryset(self, attrs, queryset, field_name, date_field_name): value = attrs[self.field] date = attrs[self.date_field] filter_kwargs = {} filter_kwargs[field_name...
UniqueForDateValidator
python
sdispater__pendulum
src/pendulum/locales/locale.py
{ "start": 220, "end": 2837 }
class ____: """ Represent a specific locale. """ _cache: ClassVar[dict[str, Locale]] = {} def __init__(self, locale: str, data: Any) -> None: self._locale: str = locale self._data: Any = data self._key_cache: dict[str, str] = {} @classmethod def load(cls, locale: s...
Locale
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-snowflake-cortex/destination_snowflake_cortex/cortex_processor.py
{ "start": 2929, "end": 3690 }
class ____(SQLTypeConverter): """A class to convert types for Snowflake.""" @overrides def to_sql_type( self, json_schema_property_def: dict[str, str | dict | list], ) -> sqlalchemy.types.TypeEngine: """Convert a value to a SQL type. We first call the parent class metho...
SnowflakeTypeConverter
python
doocs__leetcode
solution/0900-0999/0934.Shortest Bridge/Solution.py
{ "start": 0, "end": 973 }
class ____: def shortestBridge(self, grid: List[List[int]]) -> int: def dfs(i, j): q.append((i, j)) grid[i][j] = 2 for a, b in pairwise(dirs): x, y = i + a, j + b if 0 <= x < n and 0 <= y < n and grid[x][y] == 1: dfs(x, ...
Solution
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/ppo/optimizer_torch.py
{ "start": 818, "end": 1170 }
class ____(OnPolicyHyperparamSettings): beta: float = 5.0e-3 epsilon: float = 0.2 lambd: float = 0.95 num_epoch: int = 3 shared_critic: bool = False learning_rate_schedule: ScheduleType = ScheduleType.LINEAR beta_schedule: ScheduleType = ScheduleType.LINEAR epsilon_schedule: ScheduleType...
PPOSettings
python
kamyu104__LeetCode-Solutions
Python/powx-n.py
{ "start": 32, "end": 439 }
class ____(object): def myPow(self, x, n): """ :type x: float :type n: int :rtype: float """ result = 1 abs_n = abs(n) while abs_n: if abs_n & 1: result *= x abs_n >>= 1 x *= x return 1 / res...
Solution
python
kamyu104__LeetCode-Solutions
Python/maximum-profit-from-trading-stocks-with-discounts.py
{ "start": 83, "end": 2474 }
class ____(object): def maxProfit(self, n, present, future, hierarchy, budget): """ :type n: int :type present: List[int] :type future: List[int] :type hierarchy: List[List[int]] :type budget: int :rtype: int """ def iter_dfs(): ret...
Solution
python
getsentry__sentry
tests/sentry/snuba/test_transactions.py
{ "start": 1006, "end": 108200 }
class ____(SnubaTestCase, TestCase): def setUp(self) -> None: super().setUp() self.environment = self.create_environment(self.project, name="prod") self.release = self.create_release(self.project, version="first-release") self.now = before_now() self.one_min_ago = before_now(...
TransactionQueryIntegrationTest
python
mlflow__mlflow
mlflow/pyfunc/scoring_server/client.py
{ "start": 1124, "end": 3190 }
class ____(BaseScoringServerClient): def __init__(self, host, port): self.url_prefix = f"http://{host}:{port}" def ping(self): ping_status = requests.get(url=self.url_prefix + "/ping") if ping_status.status_code != 200: raise Exception(f"ping failed (error code {ping_status....
ScoringServerClient
python
pytorch__pytorch
test/dynamo/test_einops.py
{ "start": 4250, "end": 5628 }
class ____(nn.Module): def __init__(self) -> None: super().__init__() def forward(self, x_abc, suffix=""): a, b, c = x_abc.shape def suf(pattern): parts = pattern.split() return " ".join([p if p[-1] not in "acd" else p + suffix for p in parts]) # patter...
TorchModuleWithOperations
python
airbytehq__airbyte
airbyte-integrations/connectors/source-shopify/source_shopify/utils.py
{ "start": 4100, "end": 4284 }
class ____(enum.Enum): rest = "rest" graphql = "graphql" @classmethod def api_types(cls) -> List: return [api_type.value for api_type in ApiTypeEnum]
ApiTypeEnum
python
getsentry__sentry
tests/sentry/issues/test_status_change.py
{ "start": 630, "end": 3064 }
class ____(TestCase): def test_ignore_until_escalating(self) -> None: assert ( infer_substatus( new_status=GroupStatus.IGNORED, new_substatus=None, status_details={"untilEscalating": True}, group_list=[], ) =...
InferSubstatusTest
python
celery__celery
t/unit/security/test_serialization.py
{ "start": 443, "end": 2520 }
class ____(SecurityCase): def _get_s(self, key, cert, certs, serializer="json"): store = CertStore() for c in certs: store.add_cert(Certificate(c)) return SecureSerializer( PrivateKey(key), Certificate(cert), store, serializer=serializer ) @pytest.mark.p...
test_secureserializer
python
getsentry__sentry
src/sentry/utils/retries.py
{ "start": 3436, "end": 5466 }
class ____(RetryPolicy): """ A basic policy that can be used to retry a callable based on the result of a test function that determines whether or not to retry after the callable throws an exception. The test function takes two arguments: the number of times the callable has unsuccessfully been...
ConditionalRetryPolicy
python
encode__django-rest-framework
tests/test_request.py
{ "start": 983, "end": 1359 }
class ____(TestCase): def test_request_type(self): request = Request(factory.get('/')) message = ( 'The `request` argument must be an instance of ' '`django.http.HttpRequest`, not `rest_framework.request.Request`.' ) with self.assertRaisesMessage(AssertionErr...
TestInitializer
python
rapidsai__cudf
python/cudf/cudf/core/column_accessor.py
{ "start": 821, "end": 2609 }
class ____(dict): """A dictionary whose __getitem__ method accesses nested dicts. This class directly subclasses dict for performance, so there are a number of gotchas: 1) the only safe accessor for nested elements is `__getitem__` (all other accessors will fail to perform nested lookups), 2) neste...
_NestedGetItemDict
python
scikit-learn__scikit-learn
sklearn/externals/_arff.py
{ "start": 11578, "end": 11755 }
class ____(Exception): message: Optional[str] = None def __init__(self): self.line = -1 def __str__(self): return self.message%self.line
ArffException
python
ray-project__ray
python/ray/data/block.py
{ "start": 4417, "end": 5650 }
class ____: """Execution stats for this block. Attributes: wall_time_s: The wall-clock time it took to compute this block. cpu_time_s: The CPU time it took to compute this block. node_id: A unique id for the node that computed this block. max_uss_bytes: An estimate of the maximu...
BlockExecStats
python
getsentry__sentry
tests/sentry/seer/endpoints/test_group_ai_summary.py
{ "start": 363, "end": 2700 }
class ____(APITestCase, SnubaTestCase): def setUp(self) -> None: super().setUp() self.group = self.create_group() self.url = self._get_url(self.group.id) self.login_as(user=self.user) def _get_url(self, group_id: int) -> str: return f"/api/0/issues/{group_id}/summarize/"...
GroupAiSummaryEndpointTest
python
Netflix__metaflow
test/unit/inheritance/flows/comprehensive_linear_base.py
{ "start": 831, "end": 1076 }
class ____(BaseB): """Another middle class with additional config and parameter""" gamma = Parameter("gamma", help="Gamma parameter", default=2.5) config_c = Config("config_c", default_value={"mode": "production", "debug": False})
BaseC
python
scipy__scipy
scipy/sparse/linalg/_interface.py
{ "start": 21821, "end": 22747 }
class ____(LinearOperator): """Transposition of arbitrary Linear Operator""" def __init__(self, A): shape = (A.shape[1], A.shape[0]) super().__init__(dtype=A.dtype, shape=shape) self.A = A self.args = (A,) def _matvec(self, x): # NB. np.conj works also on sparse mat...
_TransposedLinearOperator
python
Netflix__metaflow
metaflow/_vendor/zipp.py
{ "start": 2873, "end": 3634 }
class ____(CompleteDirs): """ ZipFile subclass to ensure implicit dirs exist and are resolved rapidly. """ def namelist(self): with contextlib.suppress(AttributeError): return self.__names self.__names = super(FastLookup, self).namelist() return self.__names ...
FastLookup
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 88145, "end": 99165 }
class ____(Operation): def __init__(self, subscripts, *, name=None): super().__init__(name=name) self.subscripts = subscripts def call(self, *operands, **kwargs): return backend.numpy.einsum(self.subscripts, *operands, **kwargs) def compute_output_spec(self, *operands): """...
Einsum
python
getsentry__sentry
src/sentry/testutils/cases.py
{ "start": 30025, "end": 30356 }
class ____(TestCase): provider: type[Provider] = DummyProvider def setUp(self): super().setUp() # TestCase automatically sets up dummy provider if self.provider != DummyProvider: auth.register(self.provider) self.addCleanup(auth.unregister, self.provider)
AuthProviderTestCase
python
ansible__ansible
test/lib/ansible_test/_internal/util.py
{ "start": 29873, "end": 30109 }
class ____(Exception): """An unhandled internal error indicating a bug in the code.""" def __init__(self, message: str) -> None: super().__init__(f'An internal error has occurred in ansible-test: {message}')
InternalError
python
vyperlang__vyper
vyper/compiler/input_bundle.py
{ "start": 1444, "end": 2100 }
class ____(CompilerInput): # some json input, which has already been parsed into a dict or list # this is needed because json inputs present json interfaces as json # objects, not as strings. this class helps us avoid round-tripping # back to a string to pretend it's a file. data: Any = field() # s...
JSONInput
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 60740, "end": 60961 }
class ____(_PrintableStructure): _fields_ = [ ('l1Cache', c_ulonglong), ('l2Cache', c_ulonglong), ('deviceMemory', c_ulonglong), ('registerFile', c_ulonglong), ]
c_nvmlEccErrorCounts_t
python
eth-brownie__brownie
brownie/typing.py
{ "start": 3951, "end": 4150 }
class ____(_CompilerSettings): evmVersion: NotRequired[Optional[EvmVersion]] remappings: List[str] optimizer: NotRequired[OptimizerSettings] viaIR: NotRequired[bool] @final
SettingsSolc
python
cython__cython
docs/examples/userguide/sharing_declarations/shrubbing.py
{ "start": 30, "end": 203 }
class ____: def __cinit__(self, w: cython.int, l: cython.int): self.width = w self.length = l def standard_shrubbery(): return Shrubbery(3, 7)
Shrubbery
python
huggingface__transformers
tests/trainer/test_trainer.py
{ "start": 9077, "end": 9531 }
class ____: def __init__(self, length=64, vocab_size=100, num_labels=5): self.length = length self.sequences = [torch.randint(0, vocab_size, (64,)).tolist() for _ in range(length)] self.labels = torch.randint(0, num_labels, (length,)).tolist() def __len__(self): return self.leng...
SequenceClassificationDataset
python
pytorch__pytorch
test/inductor/test_aoti_cross_compile_windows.py
{ "start": 8399, "end": 14105 }
class ____(TestCase): """ Test class for AOT Inductor Windows cross-compilation. Define test methods that return ModelTestConfig, and the decorator will auto-generate compile/load test methods. """ def _define_simple(self): """Define the Simple model and its test configuration.""" ...
TestAOTInductorWindowsCrossCompilation
python
pandas-dev__pandas
pandas/tests/scalar/timestamp/test_constructors.py
{ "start": 15243, "end": 17057 }
class ____: def test_construct_from_time_unit(self): # GH#54097 only passing a time component, no date ts = Timestamp("01:01:01.111") assert ts.unit == "us" def test_constructor_str_infer_reso(self): # non-iso8601 path # _parse_delimited_date path ts = Timestamp...
TestTimestampResolutionInference
python
pytorch__pytorch
test/distributed/pipelining/test_pipe.py
{ "start": 1245, "end": 2025 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.mlp0 = MLPModule(d_hid) self.mlp1 = MLPModule(d_hid) self.mlp2 = MLPModule(d_hid) self.mlp3 = MLPModule(d_hid) def forward(self, x, y): x = self.mlp0(x) pipe_split() ...
MultiMLP
python
tornadoweb__tornado
tornado/test/web_test.py
{ "start": 90698, "end": 91580 }
class ____(RequestHandler): def initialize(self, test): self.test = test self.method = None self.methods = [] # type: typing.List[str] @contextlib.contextmanager def in_method(self, method): if self.method is not None: self.test.fail(f"entered method {method} wh...
BaseFlowControlHandler
python
getsentry__sentry
tests/sentry/flags/endpoints/test_hooks.py
{ "start": 409, "end": 15153 }
class ____(APITestCase): endpoint = "sentry-api-0-organization-flag-hooks" def setUp(self) -> None: super().setUp() self.url = reverse(self.endpoint, args=(self.organization.slug, "launchdarkly")) @property def features(self) -> dict[str, bool]: return {} def test_generic_...
OrganizationFlagsHooksEndpointTestCase
python
ansible__ansible
lib/ansible/_internal/_templating/_jinja_common.py
{ "start": 7547, "end": 8143 }
class ____(Marker, metaclass=abc.ABCMeta): """Base `Marker` class that represents exceptions encountered and deferred during templating.""" __slots__ = () @abc.abstractmethod def _as_exception(self) -> Exception: pass def _as_message(self) -> str: return str(self._as_exception()) ...
ExceptionMarker
python
great-expectations__great_expectations
great_expectations/expectations/metrics/column_map_metrics/column_values_null.py
{ "start": 1436, "end": 3194 }
class ____(MetricProvider): """A convenience class to provide an alias for easier access to the null count in a column.""" metric_name = "column_values.null.count" @metric_value(engine=PandasExecutionEngine) def _pandas(*, metrics, **kwargs): return metrics[ f"column_values.nonnull...
ColumnValuesNullCount
python
pytorch__pytorch
torch/ao/nn/intrinsic/qat/modules/conv_fused.py
{ "start": 15481, "end": 17315 }
class ____(_ConvBnNd, nn.Conv1d): r""" A ConvBn1d module is a module fused from Conv1d and BatchNorm1d, attached with FakeQuantize modules for weight, used in quantization aware training. We combined the interface of :class:`torch.nn.Conv1d` and :class:`torch.nn.BatchNorm1d`. Similar to :c...
ConvBn1d
python
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/resolvelib/structs.py
{ "start": 3147, "end": 4094 }
class ____(object): """Wrap an iterator factory returned by `find_matches()`. Calling `iter()` on this class would invoke the underlying iterator factory, making it a "collection with ordering" that can be iterated through multiple times, but lacks random access methods presented in built-in Python...
_FactoryIterableView
python
pytorch__pytorch
test/test_mps.py
{ "start": 464638, "end": 490239 }
class ____(TestCaseMPS): def test_conv1d_all_strides_paddings(self): # https://github.com/pytorch/pytorch/issues/82921 def helper(stride, padding): y_cpu = torch.randn(1, 57, 40) conv_cpu = nn.Conv1d(57, 20, stride=stride, padding=padding, kernel_size=3, bias=False) ...
TestConvolutionMPS
python
doocs__leetcode
solution/3000-3099/3000.Maximum Area of Longest Diagonal Rectangle/Solution.py
{ "start": 0, "end": 323 }
class ____: def areaOfMaxDiagonal(self, dimensions: List[List[int]]) -> int: ans = mx = 0 for l, w in dimensions: t = l**2 + w**2 if mx < t: mx = t ans = l * w elif mx == t: ans = max(ans, l * w) return ans
Solution
python
PyCQA__pylint
pylint/reporters/multi_reporter.py
{ "start": 621, "end": 3771 }
class ____: """Reports messages and layouts in plain text.""" name = "_internal_multi_reporter" # Note: do not register this reporter with linter.register_reporter as it is # not intended to be used directly like a regular reporter, but is # instead used to implement the # `--...
MultiReporter
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/destinations.py
{ "start": 112663, "end": 117790 }
class ____(GeneratedAirbyteDestination): class Disable: @public def __init__( self, ): self.mode = "disable" class Allow: @public def __init__( self, ): self.mode = "allow" class Prefer: @public ...
PostgresDestination
python
numpy__numpy
numpy/_core/tests/test_umath.py
{ "start": 4098, "end": 8987 }
class ____: def test_out_subok(self): for subok in (True, False): a = np.array(0.5) o = np.empty(()) r = np.add(a, 2, o, subok=subok) assert_(r is o) r = np.add(a, 2, out=o, subok=subok) assert_(r is o) r = np.add(a, 2, out...
TestOut
python
ray-project__ray
python/ray/data/_internal/planner/plan_expression/expression_visitors.py
{ "start": 2207, "end": 3348 }
class ____(_ExprVisitorBase): """Visitor that collects all column references from expression trees. This visitor traverses expression trees and accumulates column names referenced in ColumnExpr nodes. """ def __init__(self): """Initialize with an empty set of referenced columns.""" ...
_ColumnReferenceCollector
python
MorvanZhou__Reinforcement-learning-with-tensorflow
experiments/2D_car/DDPG.py
{ "start": 4017, "end": 6811 }
class ____(object): def __init__(self, sess, state_dim, action_dim, learning_rate, gamma, t_replace_iter, a, a_): self.sess = sess self.s_dim = state_dim self.a_dim = action_dim self.lr = learning_rate self.gamma = gamma self.t_replace_iter = t_replace_iter se...
Critic
python
kubernetes-client__python
kubernetes/client/api/networking_api.py
{ "start": 543, "end": 5193 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator Ref: https://openapi-generator.tech Do not edit the class manually. """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client ...
NetworkingApi
python
django__django
tests/generic_views/views.py
{ "start": 5099, "end": 5326 }
class ____(generic.DeleteView): queryset = Author.objects.all() template_name = "generic_views/confirm_delete.html" context_object_name = "thingy" success_url = reverse_lazy("authors_list")
SpecializedAuthorDelete
python
fsspec__filesystem_spec
fsspec/gui.py
{ "start": 318, "end": 5655 }
class ____: """Signal-slot mixin, for Panel event passing Include this class in a widget manager's superclasses to be able to register events and callbacks on Panel widgets managed by that class. The method ``_register`` should be called as widgets are added, and external code should call ``connec...
SigSlot
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowing1.py
{ "start": 158, "end": 1099 }
class ____: def x(self): return maybe = True a = None if maybe else ClassA() b = None if maybe else ClassA() if not a or not b: a.x() b.x() else: a.x() b.x() if not (not a or not b): a.x() b.x() else: a.x() b.x() if not a and not b: # This should be flagged as an er...
ClassA
python
PrefectHQ__prefect
src/prefect/server/schemas/filters.py
{ "start": 78205, "end": 78754 }
class ____(PrefectFilterBaseModel): """Filter by `ArtifactCollection.latest_id`.""" any_: Optional[list[UUID]] = Field( default=None, description="A list of artifact ids to include" ) def _get_filter_list( self, db: "PrefectDBInterface" ) -> Iterable[sa.ColumnExpressionArgument[boo...
ArtifactCollectionFilterLatestId
python
walkccc__LeetCode
solutions/2433. Find The Original Array of Prefix Xor/2433.py
{ "start": 0, "end": 203 }
class ____: def findArray(self, pref: list[int]) -> list[int]: ans = [0] * len(pref) ans[0] = pref[0] for i in range(1, len(ans)): ans[i] = pref[i] ^ pref[i - 1] return ans
Solution
python
PyCQA__pylint
tests/functional/a/alternative/alternative_union_syntax.py
{ "start": 2009, "end": 2066 }
class ____(metaclass=ReverseMetaclass): pass
WithReverse
python
huggingface__transformers
tests/models/eomt/test_image_processing_eomt.py
{ "start": 4024, "end": 14287 }
class ____(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = EomtImageProcessor if is_vision_available() else None fast_image_processing_class = EomtImageProcessorFast if is_torchvision_available() else None def setUp(self): super().setUp() self.image_processor_tester =...
EomtImageProcessingTest
python
MongoEngine__mongoengine
tests/fields/test_decimal128_field.py
{ "start": 234, "end": 617 }
class ____(Document): dec128_fld = Decimal128Field() dec128_min_0 = Decimal128Field(min_value=0) dec128_max_100 = Decimal128Field(max_value=100) def generate_test_cls() -> Document: Decimal128Document.drop_collection() Decimal128Document(dec128_fld=None).save() Decimal128Document(dec128_fld=De...
Decimal128Document
python
huggingface__transformers
src/transformers/models/glm4v/processing_glm4v.py
{ "start": 1881, "end": 14435 }
class ____(ProcessorMixin): r""" Constructs a GLM-4V processor which wraps a GLM-4V image processor and a GLM-4 tokenizer into a single processor. [`~Glm4vProcessor.__call__`] and [`~Glm4vProcessor.decode`] for more information. Args: image_processor ([`Glm4vProcessor`], *optional*): ...
Glm4vProcessor
python
kamyu104__LeetCode-Solutions
Python/reverse-prefix-of-word.py
{ "start": 29, "end": 251 }
class ____(object): def reversePrefix(self, word, ch): """ :type word: str :type ch: str :rtype: str """ i = word.find(ch) return word[:i+1][::-1]+word[i+1:]
Solution
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/widgets/base.py
{ "start": 30002, "end": 31620 }
class ____(_DialogList[_T]): """ List of radio buttons. Only one can be checked at the same time. :param values: List of (value, label) tuples. """ def __init__( self, values: Sequence[tuple[_T, AnyFormattedText]], default: _T | None = None, show_numbers: bool = Fal...
RadioList
python
catalyst-team__catalyst
catalyst/metrics/_functional_metric.py
{ "start": 225, "end": 3582 }
class ____(ICallbackBatchMetric): """Class for custom **batch-based** metrics in a functional way. Args: metric_fn: metric function, that get outputs, targets and return score as torch.Tensor metric_key: metric name compute_on_call: Computes and returns metric value during m...
FunctionalBatchMetric
python
ApeWorX__ape
src/ape/api/networks.py
{ "start": 24079, "end": 29606 }
class ____(ManagerAccessMixin): """ A context manager for temporarily connecting to a network. When entering the context, calls the :meth:`ape.api.providers.ProviderAPI.connect` method. And conversely, when exiting, calls the :meth:`ape.api.providers.ProviderPAI.disconnect` method, unless in a multi...
ProviderContextManager
python
astropy__astropy
astropy/io/votable/exceptions.py
{ "start": 14865, "end": 15487 }
class ____(VOTableSpecWarning): """ The VOTable specification uses the attribute name ``ID`` (with uppercase letters) to specify unique identifiers. Some VOTable-producing tools use the more standard lowercase ``id`` instead. ``astropy.io.votable`` accepts ``id`` and emits this warning if ``ver...
W09
python
keras-team__keras
keras/src/saving/file_editor_test.py
{ "start": 659, "end": 4051 }
class ____(testing.TestCase): def test_basics(self): temp_filepath = os.path.join(self.get_temp_dir(), "my_model.keras") model = get_source_model() model.save(temp_filepath) editor = KerasFileEditor(temp_filepath) editor.summary() target_model = get_target_model() ...
SavingTest
python
allegroai__clearml
clearml/backend_api/services/v2_13/tasks.py
{ "start": 126465, "end": 148045 }
class ____(Request): """ Create a new task :param name: Task name. Unique within the company. :type name: str :param tags: User-defined tags list :type tags: Sequence[str] :param system_tags: System tags list. This field is reserved for system use, please don't use it. :type sys...
CreateRequest
python
tensorflow__tensorflow
tensorflow/python/keras/initializers/initializers_v2.py
{ "start": 6159, "end": 7469 }
class ____(Initializer): """Initializer that generates tensors with constant values. Also available via the shortcut function `tf.keras.initializers.constant`. Only scalar values are allowed. The constant value provided must be convertible to the dtype requested when calling the initializer. Examples: ...
Constant
python
apache__airflow
helm-tests/tests/helm_tests/airflow_core/test_scheduler.py
{ "start": 969, "end": 38402 }
class ____: """Tests scheduler.""" @pytest.mark.parametrize( ("executor", "persistence", "kind"), [ ("CeleryExecutor", False, "Deployment"), ("CeleryExecutor", True, "Deployment"), ("CeleryKubernetesExecutor", True, "Deployment"), ("CeleryExecutor...
TestScheduler
python
jazzband__django-model-utils
model_utils/fields.py
{ "start": 8838, "end": 9857 }
class ____(_SplitFieldBase): def contribute_to_class(self, cls: type[models.Model], name: str, *args: Any, **kwargs: Any) -> None: if not cls._meta.abstract: excerpt_field: models.TextField = models.TextField(editable=False) cls.add_to_class(_excerpt_field_name(name), excerpt_field)...
SplitField
python
Farama-Foundation__Gymnasium
gymnasium/wrappers/vector/vectorize_action.py
{ "start": 7717, "end": 8698 }
class ____(VectorizeTransformAction): """Clip the continuous action within the valid :class:`Box` observation space bound. Example - Passing an out-of-bounds action to the environment to be clipped. >>> import numpy as np >>> import gymnasium as gym >>> envs = gym.make_vec("MountainCarC...
ClipAction
python
davidhalter__jedi
test/completion/descriptors.py
{ "start": 1148, "end": 2140 }
class ____(): def __init__(self, a): self.a = a @property def ret(self): return self.a @ret.setter def ret(self, value): return 1.0 def ret2(self): return self.a ret2 = property(ret2) @property def nested(self): """ causes recusions in prope...
PropClass
python
celery__celery
t/unit/backends/test_cosmosdbsql.py
{ "start": 323, "end": 4994 }
class ____: def setup_method(self): self.url = "cosmosdbsql://:key@endpoint" self.backend = CosmosDBSQLBackend(app=self.app, url=self.url) def test_missing_third_party_sdk(self): pydocumentdb = cosmosdbsql.pydocumentdb try: cosmosdbsql.pydocumentdb = None ...
test_DocumentDBBackend
python
kamyu104__LeetCode-Solutions
Python/palindrome-partitioning-iv.py
{ "start": 1158, "end": 1812 }
class ____(object): def checkPartitioning(self, s): """ :type s: str :rtype: bool """ dp = [[False]*len(s) for _ in xrange(len(s))] for i in reversed(xrange(len(s))): for j in xrange(i, len(s)): if s[i] == s[j] and (j-i < 2 or dp[i+...
Solution2
python
langchain-ai__langchain
libs/langchain/langchain_classic/agents/conversational/output_parser.py
{ "start": 273, "end": 1625 }
class ____(AgentOutputParser): """Output parser for the conversational agent.""" ai_prefix: str = "AI" """Prefix to use before AI output.""" format_instructions: str = FORMAT_INSTRUCTIONS """Default formatting instructions""" def get_format_instructions(self) -> str: """Returns format...
ConvoOutputParser
python
pola-rs__polars
py-polars/src/polars/io/cloud/credential_provider/_providers.py
{ "start": 15947, "end": 18212 }
class ____(CachingCredentialProvider): """ GCP Credential Provider. Using this requires the `google-auth` Python package to be installed. .. warning:: This functionality is considered **unstable**. It may be changed at any point without it being considered a breaking change. """ ...
CredentialProviderGCP
python
modin-project__modin
modin/_version.py
{ "start": 1831, "end": 24597 }
class ____(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY: Dict[str, str] = {} HANDLERS: Dict[str, Dict[str, Callable]] = {} def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator """Create decorator to mark a method as the handler of...
NotThisMethod
python
cython__cython
Cython/Debugger/libpython.py
{ "start": 83883, "end": 85138 }
class ____(ExecutionControlCommandBase): invoke = dont_suppress_errors(ExecutionControlCommandBase.cont) def _pointervalue(gdbval): """ Return the value of the pointer as a Python int. gdbval.type must be a pointer type """ # don't convert with int() as it will raise a RuntimeError if gd...
PyCont
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_heapq.py
{ "start": 13156, "end": 13363 }
class ____: def __init__(self, value, heap): self.value = value self.heap = heap def __lt__(self, other): self.heap[:] = [] return self.value < other.value
SideEffectLT
python
ipython__ipython
IPython/core/magic_arguments.py
{ "start": 7531, "end": 8147 }
class ____(ArgDecorator): """ Mark the magic as having argparse arguments and possibly adjust the name. """ def __init__(self, name=None): self.name = name def __call__(self, func): if not getattr(func, 'has_arguments', False): func.has_arguments = True func...
magic_arguments
python
tensorflow__tensorflow
tensorflow/compiler/tests/reduce_window_test.py
{ "start": 1034, "end": 3405 }
class ____(xla_test.XLATestCase): """Test cases for xla.reduce_window.""" def _reduce_window(self, operand, init, reducer, **kwargs): with self.session(): placeholder = array_ops.placeholder(operand.dtype) with self.test_scope(): output = xla.reduce_window(placeholder, init, reducer, **kwar...
ReduceWindowTest
python
tensorflow__tensorflow
tensorflow/python/debug/wrappers/framework.py
{ "start": 7867, "end": 8174 }
class ____: """Enum-like values for possible action to take on start of a run() call.""" # Run once with debug tensor-watching. DEBUG_RUN = "debug_run" # Run once with profiler. PROFILE_RUN = "profile_run" # Run without debug tensor-watching. NON_DEBUG_RUN = "non_debug_run"
OnRunStartAction
python
django-extensions__django-extensions
django_extensions/management/commands/reset_db.py
{ "start": 595, "end": 8653 }
class ____(BaseCommand): help = "Resets the database for this project." def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( "--noinput", "--no-input", action="store_false", dest="interactive", default=Tr...
Command
python
getsentry__sentry
tests/sentry/integrations/gitlab/test_client.py
{ "start": 2084, "end": 13717 }
class ____(GitLabClientTest): get_user_should_succeed = True def setUp(self) -> None: super().setUp() def tearDown(self) -> None: responses.reset() def make_users_request(self): return self.gitlab_client.get_user() def add_refresh_auth(self, success=True): respons...
GitlabRefreshAuthTest
python
apache__airflow
airflow-core/tests/unit/serialization/test_serde.py
{ "start": 5241, "end": 5345 }
class ____: x: int __version__: ClassVar[int] = 1 def __init__(self, x): self.x = x
Y
python
dagster-io__dagster
python_modules/dagster/dagster_tests/cli_tests/fake_python_logger_module/__init__.py
{ "start": 162, "end": 213 }
class ____(logging.StreamHandler): pass
FakeHandler
python
arrow-py__arrow
tests/test_arrow.py
{ "start": 10275, "end": 11745 }
class ____: def test_eq(self): assert self.arrow == self.arrow assert self.arrow == self.arrow.datetime assert not (self.arrow == "abc") def test_ne(self): assert not (self.arrow != self.arrow) assert not (self.arrow != self.arrow.datetime) assert self.arrow != "...
TestArrowComparison
python
jina-ai__jina
jina/proto/docarray_v1/pb/jina_pb2_grpc.py
{ "start": 10053, "end": 10588 }
class ____(object): """* jina gRPC service to expose Endpoints from Executors. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.endpoint_discovery = channel.unary_unary( '/jina.JinaDiscoverEndpointsRPC/endp...
JinaDiscoverEndpointsRPCStub
python
great-expectations__great_expectations
great_expectations/metrics/column/values_not_match_regex_count.py
{ "start": 261, "end": 487 }
class ____(ColumnMetric[ColumnValuesNotMatchRegexCountResult]): """Count of values in a column that do not match a regex""" name = "column_values.not_match_regex.count" regex: StrictStr
ColumnValuesNotMatchRegexCount
python
django__django
django/db/models/functions/comparison.py
{ "start": 2928, "end": 4213 }
class ____(Func): """Return, from left to right, the first non-null expression.""" function = "COALESCE" def __init__(self, *expressions, **extra): if len(expressions) < 2: raise ValueError("Coalesce must take at least two expressions") super().__init__(*expressions, **extra) ...
Coalesce
python
gevent__gevent
src/greentest/3.14/test_urllib2_localnet.py
{ "start": 11161, "end": 15430 }
class ____(unittest.TestCase): URL = "http://localhost" USER = "tester" PASSWD = "test123" REALM = "TestRealm" def setUp(self): super(ProxyAuthTests, self).setUp() # Ignore proxy bypass settings in the environment. def restore_environ(old_environ): os.environ.cl...
ProxyAuthTests
python
tensorflow__tensorflow
tensorflow/python/keras/mixed_precision/loss_scale_optimizer.py
{ "start": 3868, "end": 10031 }
class ____(trackable.Trackable): """The state of a dynamic loss scale.""" def __init__(self, initial_loss_scale, growth_steps, multiplier): """Creates the dynamic loss scale.""" super(_DynamicLossScaleState, self).__init__() self._initial_loss_scale = float(...
_DynamicLossScaleState
python
donnemartin__system-design-primer
solutions/object_oriented_design/online_chat/online_chat.py
{ "start": 1904, "end": 2089 }
class ____(object): def __init__(self, message_id, message, timestamp): self.message_id = message_id self.message = message self.timestamp = timestamp
Message