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
Delgan__loguru
loguru/_colorizer.py
{ "start": 980, "end": 1145 }
class ____: RESET_ALL = 0 BOLD = 1 DIM = 2 ITALIC = 3 UNDERLINE = 4 BLINK = 5 REVERSE = 7 HIDE = 8 STRIKE = 9 NORMAL = 22
Style
python
arrow-py__arrow
arrow/parser.py
{ "start": 1332, "end": 2044 }
class ____(ParserError): """ This class is a subclass of the ParserError class and is used to raise errors that occur during the matching process. Notes: This class is part of the Arrow parser and is used to provide error handling when a parsing match fails. """ pass _WEEKDATE_ELEMENT =...
ParserMatchError
python
ray-project__ray
rllib/algorithms/tests/test_env_runner_failures.py
{ "start": 6946, "end": 32440 }
class ____(unittest.TestCase): @classmethod def setUpClass(cls) -> None: ray.init() obs_space = gym.spaces.Box(0, 1, (2,), np.float32) def _sa(ctx): ctx.update({"observation_space": obs_space}) return FaultInjectEnv(ctx) register_env("fault_env", _sa) ...
TestEnvRunnerFailures
python
giampaolo__psutil
tests/test_linux.py
{ "start": 22664, "end": 23375 }
class ____(PsutilTestCase): def test_fields(self): fields = psutil.cpu_times()._fields kernel_ver = re.findall(r'\d+\.\d+\.\d+', os.uname()[2])[0] kernel_ver_info = tuple(map(int, kernel_ver.split('.'))) if kernel_ver_info >= (2, 6, 11): assert 'steal' in fields e...
TestSystemCPUTimes
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/ndb/properties/snippets.py
{ "start": 2350, "end": 2583 }
class ____(ndb.Model): name = ndb.StringProperty() name_lower = ndb.ComputedProperty(lambda self: self.name.lower()) def create_some_entity(): entity = SomeEntity(name="Nick") entity.put() return entity
SomeEntity
python
huggingface__transformers
src/transformers/convert_slow_tokenizer.py
{ "start": 32542, "end": 33268 }
class ____(SpmConverter): def vocab(self, proto): vocab = [ ("<s>", 0.0), ("<pad>", 0.0), ("</s>", 0.0), ("<unk>", 0.0), ] vocab += [(piece.piece, piece.score) for piece in proto.pieces[3:]] return vocab def unk_id(self, proto): ...
NllbConverter
python
huggingface__transformers
src/transformers/models/flaubert/modeling_flaubert.py
{ "start": 54051, "end": 58339 }
class ____(FlaubertPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.transformer = FlaubertModel(config) self.dropout = nn.Dropout(config.dropout) self.classifier = nn.Linear(config.hidden_size, config.num_labels)...
FlaubertForTokenClassification
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 242624, "end": 243976 }
class ____(GeneratedAirbyteSource): @public def __init__( self, name: str, instance_api_url: str, username: Optional[str] = None, password: Optional[str] = None, session_token: Optional[str] = None, ): r"""Airbyte Source for Metabase. Document...
MetabaseSource
python
langchain-ai__langchain
libs/langchain_v1/tests/unit_tests/agents/test_responses_spec.py
{ "start": 712, "end": 879 }
class ____(BaseSchema): name: str response_format: Union[Dict[str, Any], List[Dict[str, Any]]] assertions_by_invocation: List[AssertionByInvocation]
TestCase
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/links/batch.py
{ "start": 914, "end": 1233 }
class ____(BaseAwsLink): """Helper class for constructing AWS Batch Job Definition Link.""" name = "Batch Job Definition" key = "batch_job_definition" format_str = ( BASE_AWS_CONSOLE_LINK + "/batch/home?region={region_name}#job-definition/detail/{job_definition_arn}" )
BatchJobDefinitionLink
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pycodestyle/E30.py
{ "start": 633, "end": 680 }
class ____(object): pass # end # No error
Bar
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pydoclint/DOC202_google.py
{ "start": 286, "end": 702 }
class ____: # DOC202 def foo(self) -> str: """ Do something Args: num (int): A number Returns: str: A string """ print('test') # OK def bar(self) -> str: """ Do something Args: num (int): A ...
Bar
python
sqlalchemy__sqlalchemy
test/sql/test_returning.py
{ "start": 17798, "end": 20726 }
class ____(fixtures.TablesTest, AssertsExecutionResults): __requires__ = ("update_returning",) __sparse_driver_backend__ = True run_create_tables = "each" define_tables = InsertReturningTest.define_tables def test_update_returning(self, connection): table = self.tables.returning_tbl ...
UpdateReturningTest
python
yaml__pyyaml
tests/legacy_tests/canonical.py
{ "start": 62, "end": 110 }
class ____(yaml.YAMLError): pass
CanonicalError
python
pytorch__pytorch
torch/testing/_internal/common_quantization.py
{ "start": 87687, "end": 88556 }
class ____(torch.nn.Module): r"""A module with manually inserted `QuantStub` and `DeQuantStub` and contains both linear and conv modules """ def __init__(self, qconfig=None): super().__init__() self.qconfig = ( qconfig if qconfig else torch.ao.quantiz...
ManualConvLinearQATModel
python
keras-team__keras
keras/src/initializers/random_initializers.py
{ "start": 4855, "end": 6735 }
class ____(RandomInitializer): """Random uniform initializer. Draws samples from a uniform distribution for given parameters. Examples: >>> # Standalone usage: >>> initializer = RandomUniform(minval=0.0, maxval=1.0) >>> values = initializer(shape=(2, 2)) >>> # Usage in a Keras layer: ...
RandomUniform
python
walkccc__LeetCode
solutions/2818. Apply Operations to Maximize Score/2818.py
{ "start": 0, "end": 2337 }
class ____: def maximumScore(self, nums: list[int], k: int) -> int: MOD = 1_000_000_007 n = len(nums) ans = 1 minPrimeFactors = self._sieveEratosthenes(max(nums) + 1) primeScores = [self._getPrimeScore(num, minPrimeFactors) for num in nums] # left[i] := the next index on the left (if any) ...
Solution
python
ray-project__ray
doc/source/serve/doc_code/tutorial_tensorflow.py
{ "start": 1335, "end": 2226 }
class ____: def __init__(self, model_path: str): import tensorflow as tf self.model_path = model_path self.model = tf.keras.models.load_model(model_path) async def __call__(self, starlette_request: Request) -> Dict: # Step 1: transform HTTP request -> tensorflow input #...
TFMnistModel
python
pyca__cryptography
tests/x509/test_name.py
{ "start": 306, "end": 8186 }
class ____: def test_invalid(self, subtests): for value in [ "C=US,CN=Joe , Smith,DC=example", ",C=US,CN=Joe , Smith,DC=example", "C=US,UNKNOWN=Joe , Smith,DC=example", "C=US,CN,DC=example", "C=US,FOOBAR=example", "CN=Lu\\C4\\8Di\\C4par...
TestRFC4514
python
conda__conda
conda/activate.py
{ "start": 37591, "end": 38865 }
class ____(_Activator): pathsep_join = ";".join sep = "\\" path_conversion = staticmethod(_path_identity) script_extension = ".bat" tempfile_extension = ".env" command_join = "\n" needs_line_ending_fix = False # we are not generating a script to run but rather an INI style file # wi...
CmdExeActivator
python
getsentry__sentry
src/sentry/notifications/api/endpoints/notification_actions_index.py
{ "start": 1302, "end": 1667 }
class ____(OrganizationPermission): scope_map = { "GET": ["org:read", "org:write", "org:admin"], "POST": ["org:read", "org:write", "org:admin"], "PUT": ["org:read", "org:write", "org:admin"], "DELETE": ["org:read", "org:write", "org:admin"], } @region_silo_endpoint @extend_sche...
NotificationActionsPermission
python
langchain-ai__langchain
libs/partners/qdrant/langchain_qdrant/sparse_embeddings.py
{ "start": 405, "end": 1108 }
class ____(ABC): """An interface for sparse embedding models to use with Qdrant.""" @abstractmethod def embed_documents(self, texts: list[str]) -> list[SparseVector]: """Embed search docs.""" @abstractmethod def embed_query(self, text: str) -> SparseVector: """Embed query text.""" ...
SparseEmbeddings
python
tensorflow__tensorflow
tensorflow/lite/python/op_hint.py
{ "start": 22568, "end": 27454 }
class ____(_LiteOperand): """An operand for a tflite hint function that is aggregated from many. For example, an LSTM is a grid of operators that are all related. Inputs going into them may need to be fused, so they should all be tracked as related arguments. """ def __init__(self, aggregation): _Lite...
_LiteAggregateOperand
python
falconry__falcon
falcon/errors.py
{ "start": 3528, "end": 3749 }
class ____(RuntimeError): """The method or operation is not supported.""" # NOTE(kgriffs): This inherits from ValueError to be consistent with the type # raised by Python's built-in file-like objects.
UnsupportedError
python
getsentry__sentry
src/sentry/sentry_apps/external_requests/alert_rule_action_requester.py
{ "start": 1386, "end": 5387 }
class ____: install: SentryAppInstallation | RpcSentryAppInstallation uri: str fields: Sequence[Mapping[str, str]] = field(default_factory=list) http_method: str | None = "POST" def run(self) -> SentryAppAlertRuleActionResult: event = SentryAppEventType.ALERT_RULE_ACTION_REQUESTED w...
SentryAppAlertRuleActionRequester
python
google__pytype
pytype/tools/traces/traces_test.py
{ "start": 677, "end": 1044 }
class ____(traces.MatchAstVisitor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.traces_by_node_type = collections.defaultdict(list) def generic_visit(self, node): try: matches = self.match(node) except NotImplementedError: return self.traces_by_node_...
_TestVisitor
python
pydata__xarray
xarray/core/datatree.py
{ "start": 15690, "end": 15851 }
class ____: data_vars: dict[str, CoercibleValue] = field(default_factory=dict) coords: dict[str, CoercibleValue] = field(default_factory=dict)
_DatasetArgs
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 1020575, "end": 1021034 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("actor", "created_at", "lockable") actor = sgqlc.types.Field(Actor, graphql_name="actor") created_at = sgqlc.types.Field( sgqlc.types.non_null(DateTime), graphql...
UnlockedEvent
python
bokeh__bokeh
tests/unit/bokeh/core/test_validation.py
{ "start": 2970, "end": 9221 }
class ____(Model): foo = Int(default=0) @v.error("E") def _check_error(self): if self.foo > 5: return "err" @v.warning("W") def _check_warning(self): if self.foo < -5: return "wrn" def test_check_integrity_pass() -> None: m = Mod() issues = ValidationIssues(error=[], warn...
Mod
python
instagram__MonkeyType
tests/test_stubs.py
{ "start": 33008, "end": 34097 }
class ____: def test_ignore_non_matching_functions(self): b = StubIndexBuilder('foo.bar', max_typed_dict_size=0) b.log(CallTrace(untyped_helper, {'x': int, 'y': str})) assert len(b.index) == 0 def test_build_index(self): idxb = StubIndexBuilder('tests', max_typed_dict_size=0) ...
TestStubIndexBuilder
python
getsentry__sentry
src/sentry/analytics/events/release_get_previous_commits.py
{ "start": 85, "end": 310 }
class ____(analytics.Event): user_id: int | None = None organization_id: int project_ids: list[int] user_agent: str | None = None analytics.register(ReleaseGetPreviousCommitsEvent)
ReleaseGetPreviousCommitsEvent
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/bigquery.py
{ "start": 71709, "end": 76186 }
class ____(GoogleCloudBaseOperator): """ Update a table for your Project in BigQuery. Use ``fields`` to specify which fields of table to update. If a field is listed in ``fields`` and is ``None`` in table, it will be deleted. .. seealso:: For more information on how to use this operator, t...
BigQueryUpdateTableOperator
python
dagster-io__dagster
python_modules/dagster/dagster/_core/events/__init__.py
{ "start": 63552, "end": 64902 }
class ____( NamedTuple( "AssetFailedToMaterializeData", [ ("asset_materialization_failure", AssetMaterializationFailure), ("error", Optional[SerializableErrorInfo]), ], ) ): def __new__( cls, asset_materialization_failure: AssetMaterializationF...
AssetFailedToMaterializeData
python
django-import-export__django-import-export
tests/core/tests/test_widgets.py
{ "start": 9752, "end": 10126 }
class ____(TestCase): def setUp(self): self.datetime = datetime(1868, 8, 13) self.widget = widgets.DateTimeWidget("%d.%m.%Y") def test_render(self): self.assertEqual("13.08.1868", self.widget.render(self.datetime)) def test_clean(self): self.assertEqual(self.datetime, self....
DateTimeWidgetBefore1900Test
python
redis__redis-py
redis/commands/bf/commands.py
{ "start": 1417, "end": 5921 }
class ____: """Bloom Filter commands.""" def create(self, key, errorRate, capacity, expansion=None, noScale=None): """ Create a new Bloom Filter `key` with desired probability of false positives `errorRate` expected entries to be inserted as `capacity`. Default expansion value i...
BFCommands
python
pypa__pip
src/pip/_vendor/urllib3/response.py
{ "start": 4249, "end": 30641 }
class ____(io.IOBase): """ HTTP Response container. Backwards-compatible with :class:`http.client.HTTPResponse` but the response ``body`` is loaded and decoded on-demand when the ``data`` property is accessed. This class is also compatible with the Python standard library's :mod:`io` module, a...
HTTPResponse
python
Pylons__pyramid
src/pyramid/httpexceptions.py
{ "start": 35277, "end": 35689 }
class ____(HTTPServerError): """ subclass of :class:`~HTTPServerError` This indicates that the server does not support the functionality required to fulfill the request. code: 501, title: Not Implemented """ # differences from webob.exc.HTTPNotAcceptable: # # - "template" attr lef...
HTTPNotImplemented
python
Textualize__textual
docs/examples/guide/styles/colors01.py
{ "start": 112, "end": 706 }
class ____(App): def compose(self) -> ComposeResult: self.widget1 = Static("Textual One") yield self.widget1 self.widget2 = Static("Textual Two") yield self.widget2 self.widget3 = Static("Textual Three") yield self.widget3 def on_mount(self) -> None: self...
ColorApp
python
getsentry__sentry
tests/sentry/notifications/api/endpoints/test_notification_actions_details.py
{ "start": 1574, "end": 20918 }
class ____(APITestCase): endpoint = "sentry-api-0-organization-notification-actions-details" def setUp(self) -> None: self.user = self.create_user("summoner@rift.io") self.organization = self.create_organization(name="league", owner=self.user) self.other_organization = self.create_organ...
NotificationActionsDetailsEndpointTest
python
google__python-fire
fire/decorators_test.py
{ "start": 1450, "end": 1660 }
class ____: @decorators.SetParseFns(arg1=str) def example4(self, arg1, arg2): return arg1, arg2 @decorators.SetParseFns(arg2=str) def example5(self, arg1, arg2): return arg1, arg2
PartialParseFn
python
google__jax
jax/experimental/jax2tf/tests/jax2tf_test.py
{ "start": 60228, "end": 61297 }
class ____(JaxToTfTestCase): def test_key_argument(self): func = lambda key: jax.random.uniform(key, ()) key = jax.random.PRNGKey(0) key_raw = jax.random.key_data(key) with self.assertWarnsRegex(FutureWarning, "Raw arrays as random keys.*"): tf_result = jax2tf.convert(func)(key_raw) jax_res...
Jax2tfWithCustomPRNGTest
python
networkx__networkx
networkx/generators/tests/test_geometric.py
{ "start": 2527, "end": 5868 }
class ____: """Unit tests for :func:`~networkx.soft_random_geometric_graph`""" def test_number_of_nodes(self): G = nx.soft_random_geometric_graph(50, 0.25, seed=42) assert len(G) == 50 G = nx.soft_random_geometric_graph(range(50), 0.25, seed=42) assert len(G) == 50 def test...
TestSoftRandomGeometricGraph
python
huggingface__transformers
tests/models/emu3/test_modeling_emu3.py
{ "start": 9813, "end": 11303 }
class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( Emu3Model, Emu3ForConditionalGeneration, ) if is_torch_available() else () ) pipeline_model_mapping = ( {"any-to-any": Emu3ForC...
Emu3Vision2TextModelTest
python
getsentry__sentry
src/sentry/dynamic_sampling/rules/utils.py
{ "start": 3102, "end": 3222 }
class ____(TypedDict): type: SamplingValueType value: NotRequired[float] limit: NotRequired[int]
SamplingValue
python
kamyu104__LeetCode-Solutions
Python/maximum-strictly-increasing-cells-in-a-matrix.py
{ "start": 82, "end": 784 }
class ____(object): def maxIncreasingCells(self, mat): """ :type mat: List[List[int]] :rtype: int """ lookup = collections.defaultdict(list) for i in xrange(len(mat)): for j in xrange(len(mat[0])): lookup[mat[i][j]].append((i, j)) d...
Solution
python
huggingface__transformers
src/transformers/models/modernbert_decoder/modeling_modernbert_decoder.py
{ "start": 29060, "end": 33936 }
class ____(ModernBertDecoderPreTrainedModel): def __init__(self, config: ModernBertDecoderConfig): super().__init__(config) self.num_labels = config.num_labels self.model = ModernBertDecoderModel(config) self.head = ModernBertDecoderPredictionHead(config) self.classifier = n...
ModernBertDecoderForSequenceClassification
python
jazzband__django-redis
django_redis/serializers/json.py
{ "start": 155, "end": 425 }
class ____(BaseSerializer): encoder_class = DjangoJSONEncoder def dumps(self, value: Any) -> bytes: return json.dumps(value, cls=self.encoder_class).encode() def loads(self, value: bytes) -> Any: return json.loads(value.decode())
JSONSerializer
python
vyperlang__vyper
vyper/semantics/types/user.py
{ "start": 955, "end": 1805 }
class ____(VyperType): def __init__(self, members=None): super().__init__(members=members) if members is not None: for mt in members.values(): if not mt.is_valid_member_type: raise StructureException(f"not a valid {self.typeclass} member: {mt}") d...
_UserType
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 335444, "end": 337173 }
class ____(Response): """ Response of tasks.failed endpoint. :param updated: Number of tasks updated (0 or 1) :type updated: int :param fields: Updated fields names and values :type fields: dict """ _service = "tasks" _action = "failed" _version = "2.23" _schema = { ...
FailedResponse
python
marshmallow-code__apispec
tests/test_ext_marshmallow.py
{ "start": 9261, "end": 11242 }
class ____: @pytest.mark.parametrize("schema", [PetSchema, PetSchema()]) def test_can_use_schema_in_response(self, spec, schema): if spec.openapi_version.major < 3: resp = {"schema": schema} else: resp = {"content": {"application/json": {"schema": schema}}} spec.c...
TestComponentResponseHelper
python
pallets__werkzeug
src/werkzeug/exceptions.py
{ "start": 22845, "end": 23112 }
class ____(HTTPException): """*501* `Not Implemented` Raise if the application does not support the action requested by the browser. """ code = 501 description = "The server does not support the action requested by the browser."
NotImplemented
python
charliermarsh__ruff
crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/class_definition.py
{ "start": 3765, "end": 4244 }
class ____(AltersData): """Represent a lazy database lookup for a set of objects.""" def as_manager(cls): # Address the circular dependency between `Queryset` and `Manager`. from django.db.models.manager import Manager manager = Manager.from_queryset(cls)() manager._built_with_...
QuerySet
python
spack__spack
lib/spack/spack/cmd/buildcache.py
{ "start": 12343, "end": 31812 }
class ____(spack.error.SpackError): """Raised when a spec is not installed but picked to be packaged.""" def _specs_to_be_packaged( requested: List[Spec], things_to_install: str, build_deps: bool ) -> List[Spec]: """Collect all non-external with or without roots and dependencies""" if "dependencies" n...
PackageNotInstalledError
python
PyCQA__pylint
tests/functional/n/none_dunder_protocols_py38.py
{ "start": 136, "end": 317 }
class ____(metaclass=MetaContainer): if (__iter__ := lambda x: x): # [unnecessary-lambda-assignment] pass def test(): 1 in NamedExpressionClass()
NamedExpressionClass
python
falconry__falcon
tests/test_httpstatus.py
{ "start": 771, "end": 1718 }
class ____: @falcon.before(before_hook) def on_get(self, req, resp): resp.status = falcon.HTTP_500 resp.set_header('X-Failed', 'True') resp.text = 'Fail' def on_post(self, req, resp): resp.status = falcon.HTTP_500 resp.set_header('X-Failed', 'True') resp.text...
TestStatusResource
python
google__pytype
pytype/rewrite/flow/conditions.py
{ "start": 274, "end": 360 }
class ____(Condition): def __repr__(self): return 'TRUE' @_frozen_dataclass
_True
python
huggingface__transformers
src/transformers/models/smolvlm/image_processing_smolvlm_fast.py
{ "start": 5698, "end": 22647 }
class ____(BaseImageProcessorFast): resample = PILImageResampling.LANCZOS image_mean = IMAGENET_STANDARD_MEAN image_std = IMAGENET_STANDARD_STD size = {"longest_edge": 4 * 364} max_image_size = {"longest_edge": 364} do_resize = True do_rescale = True do_normalize = True do_convert_rg...
SmolVLMImageProcessorFast
python
doocs__leetcode
solution/1700-1799/1786.Number of Restricted Paths From First to Last Node/Solution.py
{ "start": 0, "end": 782 }
class ____: def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int: @cache def dfs(i): if i == n: return 1 ans = 0 for j, _ in g[i]: if dist[i] > dist[j]: ans = (ans + dfs(j)) % mod ret...
Solution
python
pydantic__pydantic
pydantic-core/tests/validators/test_pickling.py
{ "start": 1960, "end": 2592 }
class ____: __pydantic_validator__: SchemaValidator __pydantic_complete__ = True def test_schema_validator_not_reused_when_unpickling() -> None: s = SchemaValidator( core_schema.model_schema( cls=Model, schema=core_schema.model_fields_schema(fields={}, model_name='Model'), ...
Model
python
tensorflow__tensorflow
tensorflow/python/ops/gradient_checker_v2_test.py
{ "start": 1760, "end": 9532 }
class ____(test.TestCase): def testSparseTensorReshape(self): x = constant_op.constant(2.0, shape=(2,)) def sparse_tensor_reshape(values): sparse = sparse_tensor.SparseTensor( indices=[[0, 0], [1, 2]], values=values, dense_shape=[3, 4]) sparse = sparse_ops.sparse_reshape(sparse, shape=...
GradientCheckerTest
python
huggingface__transformers
tests/models/data2vec/test_modeling_data2vec_audio.py
{ "start": 13071, "end": 20669 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( Data2VecAudioForCTC, Data2VecAudioModel, Data2VecAudioForSequenceClassification, Data2VecAudioForAudioFrameClassification, Data2VecAudioForXVector, ...
Data2VecAudioModelTest
python
ray-project__ray
python/ray/dashboard/modules/job/tests/test_cli_integration.py
{ "start": 7755, "end": 8270 }
class ____: def test_bad_runtime_env(self, ray_start_stop): """Should fail with helpful error if runtime env setup fails.""" stdout, _ = _run_cmd( 'ray job submit --runtime-env-json=\'{"pip": ' '["does-not-exist"]}\' -- echo hi', should_fail=True, ) ...
TestRuntimeEnv
python
tensorflow__tensorflow
tensorflow/python/autograph/pyct/errors.py
{ "start": 937, "end": 1051 }
class ____(PyCTError, ValueError): """Raised when inspect can not access source code."""
InaccessibleSourceCodeError
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-gcs/llama_index/readers/gcs/base.py
{ "start": 950, "end": 10211 }
class ____(BasePydanticReader, ResourcesReaderMixin, FileSystemReaderMixin): """ A reader for Google Cloud Storage (GCS) files and directories. This class allows reading files from GCS, listing resources, and retrieving resource information. It supports authentication via service account keys and imple...
GCSReader
python
great-expectations__great_expectations
tests/datasource/fluent/test_pandas_azure_blob_storage_datasource.py
{ "start": 1340, "end": 1575 }
class ____: def walk_blobs( self, name_starts_with: str | None = None, include: Any | None = None, delimiter: str = "/", **kwargs, ) -> Iterator: return iter([])
MockContainerClient
python
huggingface__transformers
src/transformers/models/data2vec/modular_data2vec_audio.py
{ "start": 4487, "end": 6352 }
class ____(PreTrainedModel, Wav2Vec2PreTrainedModel): config: Data2VecAudioConfig base_model_prefix = "data2vec_audio" main_input_name = "input_values" input_modalities = "audio" supports_gradient_checkpointing = True _supports_flash_attn = True _supports_sdpa = True _supports_flex_attn ...
Data2VecAudioPreTrainedModel
python
viewflow__viewflow
tests/workflow/test_nodes__handle.py
{ "start": 1191, "end": 1321 }
class ____(Process): raise_exception = jsonstore.BooleanField() class Meta: proxy = True
TestWorkflowHandlerProcess
python
langchain-ai__langchain
libs/core/langchain_core/utils/iter.py
{ "start": 345, "end": 2955 }
class ____: """Dummy lock that provides the proper interface but no protection.""" def __enter__(self) -> None: """Do nothing.""" def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> Literal[...
NoLock
python
bokeh__bokeh
src/bokeh/core/property/required.py
{ "start": 1476, "end": 2481 }
class ____(SingleParameterizedProperty[T]): """ A property accepting a value of some other type while having undefined default. """ def __init__(self, type_param: TypeOrInst[Property[T]], *, default: Init[T] = Undefined, help: str | None = None) -> None: super().__init__(type_param, default=default, he...
Required
python
getsentry__sentry
tests/sentry/monitors/clock_tasks/test_check_timeout.py
{ "start": 653, "end": 18785 }
class ____(TestCase): @mock.patch("sentry.monitors.clock_tasks.check_timeout.mark_failed", wraps=mark_failed) @mock.patch("sentry.monitors.clock_tasks.check_timeout.produce_task") def test_timeout( self, mock_produce_task: mock.MagicMock, mock_mark_failed: mock.MagicMock ) -> None: org =...
MonitorClockTasksCheckTimeoutTest
python
Textualize__textual
src/textual/css/styles.py
{ "start": 2022, "end": 4973 }
class ____(TypedDict, total=False): """A typed dict for CSS rules. Any key may be absent, indicating that rule has not been set. Does not define composite rules, that is a rule that is made of a combination of other rules. """ display: Display visibility: Visibility layout: "Layout" ...
RulesMap
python
tox-dev__tox
src/tox/session/cmd/run/common.py
{ "start": 1473, "end": 8441 }
class ____(Action): def __call__( self, parser: ArgumentParser, # noqa: ARG002 namespace: Namespace, values: str | Sequence[Any] | None, option_string: str | None = None, # noqa: ARG002 ) -> None: if not values: raise ArgumentError(self, "cannot be e...
InstallPackageAction
python
django__django
django/db/migrations/exceptions.py
{ "start": 603, "end": 715 }
class ____(RuntimeError): """An irreversible migration is about to be reversed.""" pass
IrreversibleError
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF033.py
{ "start": 1298, "end": 1557 }
class ____: def __post_init__( self, bar: int = (x := 1) # comment , baz: int = (y := 2), # comment foo = (a := 1) # comment , faz = (b := 2), # comment ) -> None: pass @dataclass
Foo
python
scipy__scipy
scipy/spatial/tests/test_qhull.py
{ "start": 15246, "end": 22170 }
class ____: """ Check that triangulation works. """ def test_masked_array_fails(self): masked_array = np.ma.masked_all(1) assert_raises(ValueError, qhull.Delaunay, masked_array) # Shouldn't be inherently unsafe; retry with cpython 3.14 once traceback # thread safety issues are ...
TestDelaunay
python
tensorflow__tensorflow
tensorflow/python/training/basic_session_run_hooks.py
{ "start": 38394, "end": 42659 }
class ____(session_run_hook.SessionRunHook): """Captures CPU/GPU profiling information every N steps or seconds. This produces files called "timeline-<step>.json", which are in Chrome Trace format. For more information see: https://github.com/catapult-project/catapult/blob/master/tracing/README.md """ ...
ProfilerHook
python
doocs__leetcode
solution/1900-1999/1985.Find the Kth Largest Integer in the Array/Solution.py
{ "start": 0, "end": 142 }
class ____: def kthLargestNumber(self, nums: List[str], k: int) -> str: return nlargest(k, nums, key=lambda x: int(x))[k - 1]
Solution
python
pandas-dev__pandas
pandas/io/formats/excel.py
{ "start": 15272, "end": 35115 }
class ____: """ Class for formatting a DataFrame to a list of ExcelCells, Parameters ---------- df : DataFrame or Styler na_rep: na representation float_format : str, default None Format string for floating point numbers cols : sequence, optional Columns to write hea...
ExcelFormatter
python
walkccc__LeetCode
solutions/2518. Number of Great Partitions/2518.py
{ "start": 0, "end": 508 }
class ____: def countPartitions(self, nums: list[int], k: int) -> int: MOD = 1_000_000_007 summ = sum(nums) ans = pow(2, len(nums), MOD) # 2^n % MOD dp = [1] + [0] * k for num in nums: for i in range(k, num - 1, -1): dp[i] += dp[i - num] dp[i] %= MOD # Substract the ca...
Solution
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_format08.py
{ "start": 315, "end": 1561 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_format08.xlsx") def test_create_file(self): """Test the creation of an XlsxWriter file with chart formatting.""" workbook = ...
TestCompareXLSXFiles
python
pypa__warehouse
warehouse/manage/views/__init__.py
{ "start": 28137, "end": 31396 }
class ____: def __init__(self, request): self.request = request self.user_service = request.find_service(IUserService, context=None) @view_config( request_method="GET", route_name="manage.account.recovery-codes.generate", renderer="warehouse:templates/manage/account/reco...
ProvisionRecoveryCodesViews
python
ray-project__ray
python/ray/tune/tests/test_trainable_util.py
{ "start": 4615, "end": 5499 }
class ____(unittest.TestCase): def setUp(self): sys.modules["GPUtil"] = GPUUtilMock([0, 1], ["GPU-aaa", "GPU-bbb"]) def testGPUWait1(self): wait_for_gpu(0, delay_s=0) def testGPUWait2(self): wait_for_gpu("1", delay_s=0) def testGPUWait3(self): wait_for_gpu("GPU-aaa", d...
GPUTest
python
bokeh__bokeh
src/bokeh/models/scales.py
{ "start": 3207, "end": 3510 }
class ____(Scale): ''' Represent a scale transformation between a categorical source range and continuous target range. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs)
CategoricalScale
python
apache__airflow
providers/fab/src/airflow/providers/fab/auth_manager/views/user_edit.py
{ "start": 1788, "end": 2158 }
class ____(ResetPasswordView): """Customize permission names for FAB's builtin ResetPasswordView.""" class_permission_name = permissions.RESOURCE_PASSWORD method_permission_name = { "this_form_get": "read", "this_form_post": "edit", } base_permissions = [permissions.ACTION_CAN_EDIT...
CustomResetPasswordView
python
getsentry__sentry
src/sentry/web/frontend/csv.py
{ "start": 411, "end": 1216 }
class ____(Generic[T]): def get_header(self) -> tuple[str, ...]: raise NotImplementedError def get_row(self, item: T) -> tuple[str, ...]: raise NotImplementedError def respond(self, iterable: Iterable[T], filename: str) -> StreamingHttpResponse: def row_iter() -> Generator[tuple[st...
CsvResponder
python
sympy__sympy
sympy/plotting/pygletplot/color_scheme.py
{ "start": 1521, "end": 12522 }
class ____: def __init__(self, *args, **kwargs): self.args = args self.f, self.gradient = None, ColorGradient() if len(args) == 1 and not isinstance(args[0], Basic) and callable(args[0]): self.f = args[0] elif len(args) == 1 and isinstance(args[0], str): if ...
ColorScheme
python
tensorflow__tensorflow
tensorflow/python/types/core.py
{ "start": 1535, "end": 2165 }
class ____(object): """The base class of all dense Tensor objects. A dense tensor has a static data type (dtype), and may have a static rank and shape. Tensor objects are immutable. Mutable objects may be backed by a Tensor which holds the unique handle that identifies the mutable object. """ @property ...
Tensor
python
getsentry__sentry
src/sentry/sentry_apps/services/hook/service.py
{ "start": 580, "end": 3062 }
class ____(RpcService): key = "hook" local_mode = SiloMode.REGION @classmethod def get_local_implementation(cls) -> RpcService: from sentry.sentry_apps.services.hook.impl import DatabaseBackedHookService return DatabaseBackedHookService() @regional_rpc_method(ByOrganizationId()) ...
HookService
python
pandas-dev__pandas
pandas/core/arrays/floating.py
{ "start": 4473, "end": 4765 }
class ____(FloatingDtype): type = np.float64 name: ClassVar[str] = "Float64" __doc__ = _dtype_docstring.format(dtype="float64") NUMPY_FLOAT_TO_DTYPE: dict[np.dtype, FloatingDtype] = { np.dtype(np.float32): Float32Dtype(), np.dtype(np.float64): Float64Dtype(), }
Float64Dtype
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_cond_format14.py
{ "start": 315, "end": 1262 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("cond_format14.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with conditional formatting.""" ...
TestCompareXLSXFiles
python
sympy__sympy
sympy/stats/drv_types.py
{ "start": 5031, "end": 6579 }
class ____(SingleDiscreteDistribution): _argnames = ('p',) set = S.Naturals @staticmethod def check(p): _value_check((0 < p, p <= 1), "p must be between 0 and 1") def pdf(self, k): return (1 - self.p)**(k - 1) * self.p def _characteristic_function(self, t): p = self.p ...
GeometricDistribution
python
pypa__pip
src/pip/_vendor/pygments/filters/__init__.py
{ "start": 2862, "end": 31761 }
class ____(Filter): """Convert mathematical symbols such as \\<longrightarrow> in Isabelle or \\longrightarrow in LaTeX into Unicode characters. This is mostly useful for HTML or console output when you want to approximate the source rendering you'd see in an IDE. Options accepted: `lang` : s...
SymbolFilter
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/auto_materialize_rule_evaluation.py
{ "start": 1620, "end": 1888 }
class ____( AutoMaterializeRuleEvaluationData, NamedTuple("_TextRuleEvaluationData", [("text", str)]), ): @property def metadata(self) -> MetadataMapping: return {"text": MetadataValue.text(self.text)} @whitelist_for_serdes
TextRuleEvaluationData
python
geekcomputers__Python
venv/Lib/site-packages/pip/_vendor/pygments/formatters/terminal256.py
{ "start": 3193, "end": 10210 }
class ____(Formatter): """ Format tokens with ANSI color sequences, for output in a 256-color terminal or console. Like in `TerminalFormatter` color sequences are terminated at newlines, so that paging the output works correctly. The formatter takes colors from a style defined by the `style` optio...
Terminal256Formatter
python
walkccc__LeetCode
solutions/730. Count Different Palindromic Subsequences/730.py
{ "start": 0, "end": 928 }
class ____: def countPalindromicSubsequences(self, s: str) -> int: MOD = 1_000_000_007 n = len(s) # dp[i][j] := the number of different non-empty palindromic subsequences in # s[i..j] dp = [[0] * n for _ in range(n)] for i in range(n): dp[i][i] = 1 for d in range(1, n): for i...
Solution
python
pytorch__pytorch
torch/nn/modules/pooling.py
{ "start": 54944, "end": 56928 }
class ____(_AdaptiveMaxPoolNd): r"""Applies a 3D adaptive max pooling over an input signal composed of several input planes. The output is of size :math:`D_{out} \times H_{out} \times W_{out}`, for any input size. The number of output features is equal to the number of input planes. Args: outp...
AdaptiveMaxPool3d
python
google__jax
jax/_src/lax/parallel.py
{ "start": 49262, "end": 118799 }
class ____(core.Effect): __str__ = lambda _: "one-sided communication" def __hash__(self): return hash(SingleSideCollectiveEffect) def __eq__(self, other): return isinstance(other, SingleSideCollectiveEffect) single_side_collective_effect = SingleSideCollectiveEffect() core.effects.control_flow_allowed_...
SingleSideCollectiveEffect
python
sqlalchemy__sqlalchemy
test/aaa_profiling/test_resultset.py
{ "start": 479, "end": 5238 }
class ____(fixtures.TablesTest, AssertsExecutionResults): __backend__ = True @classmethod def define_tables(cls, metadata): Table( "table1", metadata, *[ Column("field%d" % fnum, String(50)) for fnum in range(NUM_FIELDS) ...
ResultSetTest
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/hooks/dms.py
{ "start": 1237, "end": 14398 }
class ____(AwsBaseHook): """ Interact with AWS Database Migration Service (DMS). Provide thin wrapper around :external+boto3:py:class:`boto3.client("dms") <DatabaseMigrationService.Client>`. Additional arguments (such as ``aws_conn_id``) may be specified and are passed down to the underlying A...
DmsHook
python
doocs__leetcode
solution/2400-2499/2436.Minimum Split Into Subarrays With GCD Greater Than One/Solution.py
{ "start": 0, "end": 229 }
class ____: def minimumSplits(self, nums: List[int]) -> int: ans, g = 1, 0 for x in nums: g = gcd(g, x) if g == 1: ans += 1 g = x return ans
Solution