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
doocs__leetcode
solution/0900-0999/0905.Sort Array By Parity/Solution.py
{ "start": 0, "end": 372 }
class ____: def sortArrayByParity(self, nums: List[int]) -> List[int]: i, j = 0, len(nums) - 1 while i < j: if nums[i] % 2 == 0: i += 1 elif nums[j] % 2 == 1: j -= 1 else: nums[i], nums[j] = nums[j], nums[i] ...
Solution
python
PyCQA__pylint
pylint/extensions/empty_comment.py
{ "start": 1186, "end": 1963 }
class ____(BaseRawFileChecker): name = "empty-comment" msgs = { "R2044": ( "Line with empty comment", "empty-comment", ( "Used when a # symbol appears on a line not followed by an actual comment" ), ) } options = () def...
CommentChecker
python
django-import-export__django-import-export
tests/core/tests/test_results.py
{ "start": 253, "end": 1159 }
class ____(SimpleTestCase): def test_repr_no_details(self): try: 1 / 0 except Exception as exc: error = Error(exc) self.assertEqual(repr(error), "<Error: ZeroDivisionError('division by zero')>") def test_repr_all_details(self): try: 1 / 0 ...
ErrorTest
python
mlflow__mlflow
dev/clint/src/clint/rules/no_shebang.py
{ "start": 36, "end": 451 }
class ____(Rule): def _message(self) -> str: return "Python scripts should not contain shebang lines" @staticmethod def check(file_content: str) -> bool: """ Returns True if the file contains a shebang line at the beginning. A shebang line is a line that starts with '#!' (t...
NoShebang
python
pytorch__pytorch
torch/ao/nn/quantized/modules/linear.py
{ "start": 3695, "end": 13612 }
class ____(WeightedQuantizedModule): r""" A quantized linear module with quantized tensor as inputs and outputs. We adopt the same interface as `torch.nn.Linear`, please see https://pytorch.org/docs/stable/nn.html#torch.nn.Linear for documentation. Similar to :class:`~torch.nn.Linear`, attributes w...
Linear
python
pypa__pip
src/pip/_vendor/rich/table.py
{ "start": 5885, "end": 6133 }
class ____(NamedTuple): """A single cell in a table.""" style: StyleType """Style to apply to cell.""" renderable: "RenderableType" """Cell renderable.""" vertical: VerticalAlignMethod """Cell vertical alignment."""
_Cell
python
django__django
tests/queries/tests.py
{ "start": 176112, "end": 177974 }
class ____(TestCase): def test_ticket_23605(self): # Test filtering on a complicated q-object from ticket's report. # The query structure is such that we have multiple nested subqueries. # The original problem was that the inner queries weren't relabeled # correctly. # See al...
Ticket23605Tests
python
huggingface__transformers
tests/models/big_bird/test_modeling_big_bird.py
{ "start": 24445, "end": 42664 }
class ____(unittest.TestCase): # we can have this true once block_sparse attn_probs works accurately test_attention_probs = False def _get_dummy_input_ids(self): # fmt: off ids = torch.tensor( [[6, 117, 33, 36, 70, 22, 63, 31, 71, 72, 88, 58, 109, 49, 48, 116, 92, 6, 19, 95, 118...
BigBirdModelIntegrationTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1422, "end": 1826 }
class ____(sgqlc.types.Enum): """Represents an annotation's information level. Enumeration Choices: * `FAILURE`: An annotation indicating an inescapable error. * `NOTICE`: An annotation indicating some information. * `WARNING`: An annotation indicating an ignorable error. """ __schema__ =...
CheckAnnotationLevel
python
PrefectHQ__prefect
src/integrations/prefect-email/tests/conftest.py
{ "start": 661, "end": 1211 }
class ____(MagicMock): def __init__(self, server, port, context=None): super().__init__() self.server = server self.port = port self.context = context def login(self, username, password): self.username = username self.password = password def starttls(self, c...
SMTPMock
python
run-llama__llama_index
llama-index-integrations/storage/kvstore/llama-index-storage-kvstore-s3/llama_index/storage/kvstore/s3/base.py
{ "start": 189, "end": 4800 }
class ____(BaseKVStore): """ S3 Key-Value store. Stores key-value pairs in a S3 bucket. Can optionally specify a path to a folder where KV data is stored. The KV data is further divided into collections, which are subfolders in the path. Each key-value pair is stored as a JSON file. Arg...
S3DBKVStore
python
pypa__pip
src/pip/_vendor/pygments/lexer.py
{ "start": 1457, "end": 10741 }
class ____(metaclass=LexerMeta): """ Lexer for a specific language. See also :doc:`lexerdevelopment`, a high-level guide to writing lexers. Lexer classes have attributes used for choosing the most appropriate lexer based on various criteria. .. autoattribute:: name :no-value: ....
Lexer
python
instagram__MonkeyType
monkeytype/db/sqlite.py
{ "start": 1927, "end": 3753 }
class ____(CallTraceStore): def __init__(self, conn: sqlite3.Connection, table: str = DEFAULT_TABLE) -> None: self.conn = conn self.table = table @classmethod def make_store(cls, connection_string: str) -> "CallTraceStore": conn = sqlite3.connect(connection_string) create_ca...
SQLiteStore
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/hooks/test_sqs.py
{ "start": 1081, "end": 1259 }
class ____: @mock_aws def test_get_conn(self): hook = SqsHook(aws_conn_id="aws_default") assert hook.get_conn() is not None @pytest.mark.asyncio
TestSqsHook
python
great-expectations__great_expectations
scripts/gen_stub.py
{ "start": 508, "end": 3948 }
class ____(Protocol): __signature__: Signature __call__: Callable def _print_method( # noqa: C901, PLR0912 method: _Callable, method_name: str | None = None, default_override: str = "...", return_type_override: str = "", ): if method_name: print(f"def {method_name}(") signatu...
_Callable
python
conda__conda
conda/core/path_actions.py
{ "start": 5421, "end": 5558 }
class ____(Action, metaclass=ABCMeta): @abstractproperty def target_full_path(self): raise NotImplementedError()
PathAction
python
conda__conda
conda/auxlib/entity.py
{ "start": 17571, "end": 17642 }
class ____(Field): _type = int IntField = IntegerField
IntegerField
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 979130, "end": 979870 }
class ____(sgqlc.types.relay.Connection): """The connection type for SponsorsTier.""" __schema__ = github_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field(sgqlc.types.list_of("SponsorsTierEdge"), graphql_name="edges") """A list of edges.""" node...
SponsorsTierConnection
python
redis__redis-py
redis/_parsers/encoders.py
{ "start": 37, "end": 1734 }
class ____: "Encode strings to bytes-like and decode bytes-like to strings" __slots__ = "encoding", "encoding_errors", "decode_responses" def __init__(self, encoding, encoding_errors, decode_responses): self.encoding = encoding self.encoding_errors = encoding_errors self.decode_res...
Encoder
python
python-pillow__Pillow
Tests/test_image.py
{ "start": 903, "end": 37986 }
class ____: @pytest.mark.parametrize("mode", Image.MODES) def test_image_modes_success(self, mode: str) -> None: Image.new(mode, (1, 1)) @pytest.mark.parametrize("mode", ("", "bad", "very very long")) def test_image_modes_fail(self, mode: str) -> None: with pytest.raises(ValueError, mat...
TestImage
python
ApeWorX__ape
src/ape/utils/os.py
{ "start": 11697, "end": 13889 }
class ____: """ A directory for caching data where each data item is named ``<key>.json`` and is in the directory. You can access the items by their key like a dictionary. This type is used in Ape's contract-caching for ContractTypes, ProxyInfoAPI, and other model types. """ def __init_...
CacheDirectory
python
numpy__numpy
numpy/distutils/system_info.py
{ "start": 96931, "end": 99275 }
class ____(system_info): section = 'Numeric' modulename = 'Numeric' notfounderror = NumericNotFoundError def __init__(self): include_dirs = [] try: module = __import__(self.modulename) prefix = [] for name in module.__file__.split(os.sep): ...
_numpy_info
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/asset_backfill.py
{ "start": 3465, "end": 4355 }
class ____( NamedTuple( "_PartitionedAssetBackfillStatus", [ ("asset_key", AssetKey), ("num_targeted_partitions", int), ("partitions_counts_by_status", Mapping[AssetBackfillStatus, int]), ], ) ): def __new__( cls, asset_key: AssetKe...
PartitionedAssetBackfillStatus
python
bokeh__bokeh
tests/unit/bokeh/core/test_has_props.py
{ "start": 13980, "end": 14588 }
class ____(hp.HasProps, hp.NonQualified): foo = Int() def test_qualified() -> None: class InnerQualified(hp.HasProps, hp.Qualified): foo = Int() class InnerNonQualified(hp.HasProps, hp.NonQualified): foo = Int() assert TopLevelQualified.__qualified_model__ == "test_has_props.TopLevelQ...
TopLevelNonQualified
python
ansible__ansible
hacking/create-bulk-issues.py
{ "start": 6402, "end": 6551 }
class ____: create: bool verbose: bool def run(self) -> None: raise NotImplementedError() @dataclasses.dataclass(frozen=True)
Args
python
kamyu104__LeetCode-Solutions
Python/number-of-subarrays-with-and-value-of-k.py
{ "start": 70, "end": 633 }
class ____(object): def countSubarrays(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ result = 0 dp = collections.defaultdict(int) for x in nums: new_dp = collections.defaultdict(int) if x&k == k: ...
Solution
python
plotly__plotly.py
plotly/graph_objs/indicator/delta/_font.py
{ "start": 233, "end": 9883 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "indicator.delta" _path_str = "indicator.delta.font" _valid_props = { "color", "family", "lineposition", "shadow", "size", "style", "textcase", "variant", "weight", } @pro...
Font
python
tiangolo__fastapi
tests/test_serialize_response.py
{ "start": 155, "end": 1414 }
class ____(BaseModel): name: str price: Optional[float] = None owner_ids: Optional[List[int]] = None @app.get("/items/valid", response_model=Item) def get_valid(): return {"name": "valid", "price": 1.0} @app.get("/items/coerce", response_model=Item) def get_coerce(): return {"name": "coerce", "p...
Item
python
spack__spack
lib/spack/spack/multimethod.py
{ "start": 6298, "end": 11484 }
class ____: """This is a multi-purpose class, which can be used 1. As a context manager to **group directives together** that share the same ``when=`` argument. 2. As a **decorator** for defining multi-methods (multiple methods with the same name are defined, but the version that is called de...
when
python
huggingface__transformers
tests/quantization/bnb/test_4bit.py
{ "start": 23365, "end": 25358 }
class ____(Base4bitTest): def setUp(self): self.model_name = "facebook/opt-350m" super().setUp() def test_training(self): # Step 1: freeze all parameters model = AutoModelForCausalLM.from_pretrained( self.model_name, quantization_config=BitsAndBytesConfig(load_in_4bi...
Bnb4BitTestTraining
python
getsentry__sentry
src/sentry/notifications/notification_action/grouptype.py
{ "start": 684, "end": 2682 }
class ____(GroupType): type_id = 9001 slug = "send-test-notification" description = "Send test notification" category = GroupCategory.TEST_NOTIFICATION.value category_v2 = GroupCategory.TEST_NOTIFICATION.value released = False in_default_search = False enable_auto_resolve = True enab...
SendTestNotification
python
numba__numba
numba/core/typing/npydecl.py
{ "start": 24251, "end": 24548 }
class ____(AbstractTemplate): def generic(self, args, kws): assert not kws arr, = args if isinstance(arr, types.Array): enumerate_type = types.NumpyNdEnumerateType(arr) return signature(enumerate_type, *args) @infer_global(np.nditer)
NdEnumerate
python
django__django
tests/staticfiles_tests/test_management.py
{ "start": 1139, "end": 2153 }
class ____(StaticFilesTestCase): @override_settings(MIDDLEWARE=["django.middleware.common.CommonMiddleware"]) def test_middleware_loaded_only_once(self): command = runserver.Command() with mock.patch("django.middleware.common.CommonMiddleware") as mocked: command.get_handler(use_stat...
TestRunserver
python
tensorflow__tensorflow
tensorflow/compiler/tests/einsum_op_test.py
{ "start": 983, "end": 3332 }
class ____(xla_test.XLATestCase): """Test cases for einsum op.""" def _testUnary(self, op, inp, expected): """Verifies that unary 'op' produces 'expected' when fed input 'inp'.""" with self.session() as session: with self.test_scope(): pinp = array_ops.placeholder( dtypes.as_dtype...
EinsumOpTest
python
pytorch__pytorch
test/distributed/elastic/rendezvous/rendezvous_backend_test.py
{ "start": 527, "end": 3411 }
class ____(ABC): _backend: RendezvousBackend # Type hints assertEqual: Callable assertNotEqual: Callable assertIsNone: Callable assertIsNotNone: Callable assertRaises: Callable @abstractmethod def _corrupt_state(self) -> None: """Corrupts the state stored in the backend."""...
RendezvousBackendTestMixin
python
django-debug-toolbar__django-debug-toolbar
tests/base.py
{ "start": 1960, "end": 3688 }
class ____: _is_async = False client_class = ToolbarTestClient async_client_class = AsyncToolbarTestClient panel: Panel | None = None panel_id = None def setUp(self): super().setUp() self._get_response = lambda request: HttpResponse() self.request = rf.get("/") ...
BaseMixin
python
google__pytype
pytype/tests/test_import2.py
{ "start": 98, "end": 4434 }
class ____(test_base.BaseTest): """Tests for import.""" def test_module_attributes(self): ty = self.Infer(""" import os f = os.__file__ n = os.__name__ d = os.__doc__ p = os.__package__ """) self.assertTypesMatchPytd( ty, """ import os from ...
ImportTest
python
modin-project__modin
modin/core/execution/ray/common/engine_wrapper.py
{ "start": 8800, "end": 9953 }
class ____: """The Hook is called during the materialization and allows performing pre/post computations.""" def pre_materialize(self): """ Get an object reference to be materialized or a pre-computed value. Returns ------- ray.ObjectRef or object """ ra...
MaterializationHook
python
django__django
tests/model_inheritance_regress/models.py
{ "start": 2854, "end": 2949 }
class ____(AuditBase): class Meta(AuditBase.Meta): abstract = True
CertificationAudit
python
huggingface__transformers
src/transformers/models/qwen2_vl/configuration_qwen2_vl.py
{ "start": 11116, "end": 14835 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Qwen2VLModel`]. It is used to instantiate a Qwen2-VL model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar conf...
Qwen2VLConfig
python
numpy__numpy
numpy/_core/tests/test_umath_complex.py
{ "start": 1205, "end": 4913 }
class ____: def test_simple(self): check = check_complex_value f = np.exp check(f, 1, 0, np.exp(1), 0, False) check(f, 0, 1, np.cos(1), np.sin(1), False) ref = np.exp(1) * complex(np.cos(1), np.sin(1)) check(f, 1, 1, ref.real, ref.imag, False) @platform_skip ...
TestCexp
python
h5py__h5py
h5py/tests/test_group.py
{ "start": 11915, "end": 14847 }
class ____(BaseGroup): """ Feature: The Python "in" builtin tests for membership """ def test_contains(self): """ "in" builtin works for membership (byte and Unicode) """ name = make_name() self.f.create_group(name) self.assertIn(name.encode("utf-8"), self.f) ...
TestContains
python
automl__auto-sklearn
test/test_pipeline/components/feature_preprocessing/test_truncatedSVD.py
{ "start": 304, "end": 1960 }
class ____(PreprocessingTestCase): def test_default_configuration(self): transformation, original = _test_preprocessing(TruncatedSVD) self.assertEqual(transformation.shape[0], original.shape[0]) self.assertFalse((transformation == 0).all()) def test_default_configuration_classify(self):...
TruncatedSVDComponentTest
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/sqltypes.py
{ "start": 13133, "end": 15478 }
class ____(HasExpressionLookup, TypeEngineMixin, Generic[_N]): """common mixin for the :class:`.Numeric` and :class:`.Float` types. .. versionadded:: 2.1 """ _default_decimal_return_scale = 10 operator_classes = OperatorClass.NUMERIC if TYPE_CHECKING: @util.ro_memoized_property ...
NumericCommon
python
Netflix__metaflow
metaflow/plugins/cards/card_modules/basic.py
{ "start": 6782, "end": 7104 }
class ____(DefaultComponent): type = "dag" def __init__(self, title=None, subtitle=None, data={}): super().__init__(title=title, subtitle=subtitle) self._data = data def render(self): datadict = super().render() datadict["data"] = self._data return datadict
DagComponent
python
conda__conda
conda/cli/conda_argparse.py
{ "start": 8734, "end": 13424 }
class ____(argparse._SubParsersAction): """A custom subparser action to conditionally act as a greedy consumer. This is a workaround since argparse.REMAINDER does not work as expected, see https://github.com/python/cpython/issues/61252. """ def __call__(self, parser, namespace, values, option_stri...
_GreedySubParsersAction
python
wandb__wandb
wandb/sdk/artifacts/_generated/input_types.py
{ "start": 7697, "end": 8273 }
class ____(GQLInput): team_id: GQLId = Field(alias="teamId") project_id: GQLId = Field(alias="projectId") team_project_role: str = Field(alias="teamProjectRole") client_mutation_id: Optional[str] = Field(alias="clientMutationId", default=None) UpsertModelInput.model_rebuild() UpdateArtifactInput.model...
UpdateProjectTeamMemberInput
python
anthropics__anthropic-sdk-python
src/anthropic/resources/models.py
{ "start": 5943, "end": 11148 }
class ____(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncModelsWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.git...
AsyncModels
python
huggingface__transformers
src/transformers/models/sam/modeling_sam.py
{ "start": 1688, "end": 2344 }
class ____(ModelOutput): r""" image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`): The image embeddings obtained by applying the projection layer to the pooler_output. """ image_embeds: Optional[torch.F...
SamVisionEncoderOutput
python
Textualize__textual
docs/examples/guide/widgets/checker04.py
{ "start": 329, "end": 3465 }
class ____(ScrollView): COMPONENT_CLASSES = { "checkerboard--white-square", "checkerboard--black-square", "checkerboard--cursor-square", } DEFAULT_CSS = """ CheckerBoard > .checkerboard--white-square { background: #A5BAC9; } CheckerBoard > .checkerboard--black-sq...
CheckerBoard
python
airbytehq__airbyte
airbyte-integrations/connectors/source-hubspot/unit_tests/integrations/config_builder.py
{ "start": 92, "end": 514 }
class ____: def __init__(self): self._config = {"enable_experimental_streams": True} def with_start_date(self, start_date: str): self._config["start_date"] = start_date return self def with_auth(self, credentials: Mapping[str, str]): self._config["credentials"] = credential...
ConfigBuilder
python
altair-viz__altair
tools/vega_expr.py
{ "start": 6308, "end": 7014 }
class ____({base}, metaclass={metaclass}): """{doc}\n{links}""" @override def __new__(cls: type[{base}], expr: str) -> {base}: {type_ignore} return {base}(expr=expr) ''' METHOD_SIGNATURE = ( """def {title}(cls{sep}{param_list}{marker}) -> {return_ann}:{type_ignore}""" ) METHOD_TEMPLATE = '''...
expr
python
cython__cython
Cython/Compiler/Tests/TestBuiltin.py
{ "start": 1558, "end": 3453 }
class ____(unittest.TestCase): def test_python_builtin_compatibility(self): expected_builtins = set(KNOWN_PYTHON_BUILTINS) if sys.platform != 'win32': expected_builtins.discard("WindowsError") runtime_builtins = frozenset( name for name in dir(builtins) if...
TestBuiltinCompatibility
python
python-visualization__folium
folium/vector_layers.py
{ "start": 11722, "end": 13194 }
class ____(Marker): """ A circle of a fixed size with radius specified in pixels. See :func:`folium.vector_layers.path_options` for the `Path` options. Parameters ---------- location: tuple[float, float] Latitude and Longitude pair (Northing, Easting) popup: string or folium.Popup,...
CircleMarker
python
pytorch__pytorch
torch/distributed/_tools/fsdp2_mem_tracker.py
{ "start": 2360, "end": 2454 }
class ____(NamedTuple): pre_backward: Callable post_backward: Callable
_SavedFSDPMethods
python
prabhupant__python-ds
data_structures/bst/dfs_iterative.py
{ "start": 0, "end": 1502 }
class ____(): def __init__(self, val): self.val = val self.left = None self.right = None def inorder(root): if not root: return None stack = [] # Keep adding left until there is none while True: if root: stack.append(root) root = roo...
Node
python
keon__algorithms
algorithms/compression/huffman_coding.py
{ "start": 6280, "end": 10199 }
class ____: def __init__(self): pass @staticmethod def decode_file(file_in_name, file_out_name): with open(file_in_name, "rb") as file_in, open(file_out_name, "wb") as file_out: reader = HuffmanReader(file_in) additional_bits = reader.get_number_of_additional_bits_in...
HuffmanCoding
python
ray-project__ray
python/ray/train/v2/_internal/callbacks/accelerators.py
{ "start": 779, "end": 5548 }
class ____(WorkerGroupCallback): """Perform accelerator setup for workers. For example, this callback can be used to share CUDA_VISIBLE_DEVICES among workers on the same node. """ def __init__(self, backend_config: BackendConfig, scaling_config: ScalingConfig): self._backend = backend_conf...
AcceleratorSetupCallback
python
allegroai__clearml
clearml/backend_api/services/v2_23/workers.py
{ "start": 50545, "end": 53854 }
class ____(Request): """ Returns information on all registered workers. :param last_seen: Filter out workers not active for more than last_seen seconds. A value or 0 or 'none' will disable the filter. :type last_seen: int :param tags: The list of allowed worker tags. Prepend tag value with ...
GetAllRequest
python
keon__algorithms
tests/test_strings.py
{ "start": 9005, "end": 9564 }
class ____(unittest.TestCase): """[summary] Test for the file one_edit_distance.py Arguments: unittest {[type]} -- [description] """ def test_is_one_edit(self): self.assertTrue(is_one_edit("abc", "abd")) self.assertFalse(is_one_edit("abc", "aed")) self.assertFalse(i...
TestOneEditDistance
python
apache__airflow
airflow-core/tests/unit/core/test_settings.py
{ "start": 7823, "end": 8588 }
class ____: @staticmethod @patch("airflow.settings.conf") @patch("airflow.settings.is_sqlalchemy_v1") def test_encoding_present_in_v1(is_v1, mock_conf): from airflow import settings is_v1.return_value = True mock_conf.getjson.return_value = {} engine_args = settings.pre...
TestEngineArgs
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-ragie/unit_tests/test_ragie_writer.py
{ "start": 480, "end": 4784 }
class ____(unittest.TestCase): def setUp(self): self.mock_client = Mock() self.mock_config = Mock() # Mock config values self.mock_config.metadata_static_dict = {"source": "airbyte"} self.mock_config.content_fields = ["message"] self.mock_config.document_name_field =...
TestRagieWriter
python
tensorflow__tensorflow
tensorflow/python/training/server_lib_sparse_job_test.py
{ "start": 1008, "end": 1581 }
class ____(test.TestCase): # TODO(b/34465411): Starting multiple servers with different configurations # in the same test is flaky. Move this test case back into # "server_lib_test.py" when this is no longer the case. @test_util.run_deprecated_v1 def testSparseJob(self): server = server_lib.Server({"loca...
SparseJobTest
python
huggingface__transformers
src/transformers/models/layoutlmv2/configuration_layoutlmv2.py
{ "start": 902, "end": 11124 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`LayoutLMv2Model`]. It is used to instantiate an LayoutLMv2 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a simila...
LayoutLMv2Config
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pep8_naming/N815.py
{ "start": 542, "end": 648 }
class ____(D): lower: int CONSTANT: str mixedCase: bool _mixedCase: list mixed_Case: set
E
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_data_labels09.py
{ "start": 315, "end": 1636 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_data_labels09.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(se...
TestCompareXLSXFiles
python
getsentry__sentry
src/sentry/migrations/0967_large_tables_legacy_json_field.py
{ "start": 188, "end": 3939 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # o...
Migration
python
django-import-export__django-import-export
import_export/tmp_storages.py
{ "start": 1189, "end": 1710 }
class ____(BaseStorage): """ By default memcache maximum size per key is 1MB, be careful with large files. """ CACHE_LIFETIME = 86400 CACHE_PREFIX = "django-import-export-" def save(self, data): if not self.name: self.name = uuid4().hex cache.set(self.CACHE_PREFIX +...
CacheStorage
python
ansible__ansible
test/lib/ansible_test/_internal/commands/sanity/__init__.py
{ "start": 12285, "end": 21236 }
class ____: """Parser for the consolidated sanity test ignore file.""" NO_CODE = '_' def __init__(self, args: SanityConfig) -> None: if data_context().content.collection: ansible_version = '%s.%s' % tuple(get_ansible_version().split('.')[:2]) ansible_label = 'Ansible %s' %...
SanityIgnoreParser
python
celery__celery
t/unit/worker/test_components.py
{ "start": 343, "end": 520 }
class ____: def test_create__eventloop(self): w = Mock(name='w') w.use_eventloop = True Timer(w).create(w) assert not w.timer.queue
test_Timer
python
kamyu104__LeetCode-Solutions
Python/short-encoding-of-words.py
{ "start": 145, "end": 634 }
class ____(object): def minimumLengthEncoding(self, words): """ :type words: List[str] :rtype: int """ words = list(set(words)) _trie = lambda: collections.defaultdict(_trie) trie = _trie() nodes = [functools.reduce(dict.__getitem__, word[::-1], trie)...
Solution
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-oci-genai/llama_index/llms/oci_genai/utils.py
{ "start": 26267, "end": 41799 }
class ____(Provider): def __init__(self) -> None: try: from oci.generative_ai_inference import models except ImportError as ex: raise ModuleNotFoundError( "Could not import oci python package. " "Please make sure you have the oci package instal...
XAIProvider
python
encode__django-rest-framework
tests/test_fields.py
{ "start": 26106, "end": 26723 }
class ____(TestBooleanField): """ Valid and invalid values for `BooleanField` when `allow_null=True`. """ valid_inputs = { 'true': True, 'false': False, 'null': None, True: True, False: False, None: None } invalid_inputs = { 'foo': ['Must b...
TestNullableBooleanField
python
allegroai__clearml
clearml/backend_api/session/client/client.py
{ "start": 1174, "end": 2934 }
class ____(Exception): """ Class for representing an API error. self.data - ``dict`` of all returned JSON data self.code - HTTP response code self.subcode - server response subcode self.codes - (self.code, self.subcode) tuple self.message - result message sent from server """ def _...
APIError
python
jazzband__django-simple-history
simple_history/tests/admin.py
{ "start": 1756, "end": 2585 }
class ____(SimpleHistoryAdmin): def get_historical_record_context_helper(self, request, historical_record): return HistoricalPollWithManyToManyContextHelper(self.model, historical_record) admin.site.register(Book, SimpleHistoryAdmin) admin.site.register(Choice, ChoiceAdmin) admin.site.register(ConcreteExt...
PollWithManyToManyAdmin
python
pytorch__pytorch
torch/_higher_order_ops/schema.py
{ "start": 791, "end": 1503 }
class ____: @staticmethod def from_example( example_value: Any, *, name: str = "", default_value: Optional[Any] = None, is_mutated: bool = False, kw_only: bool = False, ) -> HopArgumentInfo: if default_value is not None: assert type(example...
HopArgumentInfoGen
python
facelessuser__pymdown-extensions
tests/test_extensions/test_blocks/test_admonitions.py
{ "start": 66, "end": 5878 }
class ____(util.MdCase): """Test Blocks admonitions cases.""" extension = ['pymdownx.blocks.admonition'] extension_configs = { 'pymdownx.blocks.admonition': { 'types': [ 'note', 'custom', {'name': 'custom2'}, {'name': 'cust...
TestBlocksAdmonitions
python
h5py__h5py
examples/swmr_multiprocess.py
{ "start": 1900, "end": 3865 }
class ____(Process): def __init__(self, event, fname, dsetname): super().__init__() self._event = event self._fname = fname self._dsetname = dsetname def run(self): self.log = logging.getLogger('writer') self.log.info("Creating file %s", self._fname) f = ...
SwmrWriter
python
pyinstaller__pyinstaller
tests/functional/modules/pyi_testmod_relimp3a/aa/pyi_testmod_relimp3c.py
{ "start": 509, "end": 547 }
class ____: string = "... and this"
c1
python
pandas-dev__pandas
pandas/tests/io/formats/test_to_latex.py
{ "start": 10593, "end": 11573 }
class ____: def test_to_latex_bold_rows(self): # GH 16707 df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]}) result = df.to_latex(bold_rows=True) expected = _dedent( r""" \begin{tabular}{lrl} \toprule & a & b \\ \midrule ...
TestToLatexBold
python
django__django
tests/fixtures/models.py
{ "start": 3990, "end": 4236 }
class ____(models.Model): key = models.CharField(max_length=3, unique=True) obj = models.ForeignKey("CircularB", models.SET_NULL, null=True) objects = NaturalKeyManager() def natural_key(self): return (self.key,)
CircularA
python
py-pdf__pypdf
pypdf/generic/_link.py
{ "start": 2771, "end": 4951 }
class ____: """Direct reference link being preserved until we can resolve it correctly.""" def __init__(self, reference: ArrayObject) -> None: """reference: an ArrayObject whose first element is the Page indirect object""" self._reference = reference def find_referenced_page(self) -> Indir...
DirectReferenceLink
python
getsentry__sentry
tests/sentry/deletions/test_project.py
{ "start": 10640, "end": 13573 }
class ____(DeleteProjectTest): def setUp(self) -> None: self.workflow_engine_project = self.create_project(name="workflow_engine_test") self.snuba_query = self.create_snuba_query() self.subscription = QuerySubscription.objects.create( project=self.workflow_engine_project, ...
DeleteWorkflowEngineModelsTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constructor33.py
{ "start": 533, "end": 573 }
class ____(TD1): b: str @dataclass
TD2
python
jazzband__django-oauth-toolkit
oauth2_provider/oauth2_validators.py
{ "start": 2196, "end": 42797 }
class ____(RequestValidator): # Return the given claim only if the given scope is present. # Extended as needed for non-standard OIDC claims/scopes. # Override by setting to None to ignore scopes. # see https://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims # For example, for the "nicknam...
OAuth2Validator
python
tensorflow__tensorflow
tensorflow/compiler/tests/xla_call_module_test.py
{ "start": 1691, "end": 62337 }
class ____(xla_test.XLATestCase, parameterized.TestCase): def _assertOpOutputMatchesExpected(self, op, args, expected, equality_fn=None): """Asserts op(*args) == exp...
XlaCallModuleOpTest
python
openai__openai-python
src/openai/types/conversations/conversation_item.py
{ "start": 1759, "end": 2197 }
class ____(BaseModel): id: str """The unique ID of the image generation call.""" result: Optional[str] = None """The generated image encoded in base64.""" status: Literal["in_progress", "completed", "generating", "failed"] """The status of the image generation call.""" type: Literal["imag...
ImageGenerationCall
python
Pylons__pyramid
src/pyramid/testing.py
{ "start": 20096, "end": 22096 }
class ____: def __init__(self, response): self._received = {} self.response = response def __getattr__(self, attrname): return self def __getitem__(self, attrname): return self def __call__(self, *arg, **kw): self._received.update(kw) return self.respon...
MockTemplate
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 42442, "end": 43036 }
class ____(BaseModel, extra="forbid"): """ Geo filter request Matches coordinates inside the rectangle, described by coordinates of lop-left and bottom-right edges """ top_left: "GeoPoint" = Field( ..., description="Geo filter request Matches coordinates inside the rectangle, describe...
GeoBoundingBox
python
kamyu104__LeetCode-Solutions
Python/expression-add-operators.py
{ "start": 31, "end": 1727 }
class ____(object): def addOperators(self, num, target): """ :type num: str :type target: int :rtype: List[str] """ result, expr = [], [] val, i = 0, 0 val_str = "" while i < len(num): val = val * 10 + ord(num[i]) - ord('0') ...
Solution
python
ipython__ipython
IPython/utils/contexts.py
{ "start": 177, "end": 1610 }
class ____: """Preserve a set of keys in a dictionary. Upon entering the context manager the current values of the keys will be saved. Upon exiting, the dictionary will be updated to restore the original value of the preserved keys. Preserved keys which did not exist when entering the context manag...
preserve_keys
python
facebookresearch__faiss
contrib/rpc.py
{ "start": 1058, "end": 2079 }
class ____: " wraps a socket so that it is usable by pickle/cPickle " def __init__(self,sock): self.sock = sock self.nr=0 def write(self, buf): # print("sending %d bytes"%len(buf)) #self.sock.sendall(buf) # print("...done") bs = 512 * 1024 ns = 0 ...
FileSock
python
pypa__pip
src/pip/_vendor/rich/spinner.py
{ "start": 309, "end": 4214 }
class ____: """A spinner animation. Args: name (str): Name of spinner (run python -m rich.spinner). text (RenderableType, optional): A renderable to display at the right of the spinner (str or Text typically). Defaults to "". style (StyleType, optional): Style for spinner animation. Def...
Spinner
python
tensorflow__tensorflow
third_party/xla/third_party/gpus/find_rocm_config.py
{ "start": 1423, "end": 15131 }
class ____(Exception): pass def _get_default_rocm_path(): return "/opt/rocm" def _get_rocm_install_path(): """Determines and returns the ROCm installation path.""" rocm_install_path = _get_default_rocm_path() if "ROCM_PATH" in os.environ: rocm_install_path = os.environ["ROCM_PATH"] # rocm_install_pa...
ConfigError
python
viewflow__viewflow
viewflow/workflow/flow/views/update.py
{ "start": 274, "end": 1233 }
class ____( FormLayoutMixin, FormAjaxCompleteMixin, FormDependentSelectMixin, mixins.SuccessMessageMixin, mixins.TaskSuccessUrlMixin, mixins.TaskViewTemplateNames, generic.UpdateView, ): """Default view to update a process""" success_message = _("Task {task} has been completed.") ...
UpdateProcessView
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/functionMember2.py
{ "start": 332, "end": 913 }
class ____: def method1(self) -> None: ... @classmethod def method2(cls) -> None: ... @staticmethod def method3() -> None: ... s2 = A().method1.__self__ reveal_type(s2, expected_text="A") s3 = A.method2.__self__ reveal_type(s3, expected_text="type[A]") s3 = A.method2.__self__ reveal_type(s3, e...
A
python
modin-project__modin
asv_bench/benchmarks/benchmarks.py
{ "start": 7847, "end": 8958 }
class ____: param_names = ["shapes", "data_type"] params = [ get_benchmark_shapes("MergeCategoricals"), ["object", "category"], ] def setup(self, shapes, data_type): assert len(shapes) == 2 assert shapes[1] == 2 size = (shapes[0],) self.left = IMPL.DataFr...
TimeMergeCategoricals
python
ansible__ansible
test/units/module_utils/basic/test_run_command.py
{ "start": 6971, "end": 7650 }
class ____: @pytest.mark.parametrize('stdin', [{}], indirect=['stdin']) def test_check_rc_false(self, rc_am): rc_am._subprocess.Popen.return_value.returncode = 1 (rc, stdout, stderr) = rc_am.run_command('/bin/false', check_rc=False) assert rc == 1 @pytest.mark.parametrize('stdin', [...
TestRunCommandRc
python
openai__gym
gym/core.py
{ "start": 14519, "end": 16876 }
class ____(Wrapper): """Superclass of wrappers that can modify observations using :meth:`observation` for :meth:`reset` and :meth:`step`. If you would like to apply a function to the observation that is returned by the base environment before passing it to learning code, you can simply inherit from :class:...
ObservationWrapper
python
sanic-org__sanic
guide/webapp/display/plugins/columns.py
{ "start": 288, "end": 1344 }
class ____(DirectivePlugin): def parse( self, block: BlockParser, m: Match, state: BlockState ) -> dict[str, Any]: info = m.groupdict() new_state = block.state_cls() new_state.process(dedent(info["text"])) block.parse(new_state) return { "type": "col...
Column