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
pytorch__pytorch
torch/_inductor/codegen/multi_kernel.py
{ "start": 11316, "end": 18906 }
class ____: """ This class is called at run time to actually run the kernel """ def __init__(self, multi_kernel_name, kernels, arg_index): assert len(kernels) >= 1 self._kernels = kernels self.multi_kernel_name = multi_kernel_name self.disable_cache = os.environ.get( ...
MultiKernelCall
python
tensorflow__tensorflow
tensorflow/python/ops/ragged/ragged_bincount_ops_test.py
{ "start": 18303, "end": 20261 }
class ____(test_util.TensorFlowTestCase): def test_dense_input_ragged_weights_fails(self): x = np.array([[3, 2, 1], [5, 4, 4]], dtype=np.int32) weights = ragged_factory_ops.constant([[6, 0.5, 2], [14], [10, 0.25, 5, 3]]) with self.assertRaisesRegex(ValueError, "must be a tf.Tensor"): self.evaluate(s...
TestSparseCountFailureModes
python
scrapy__scrapy
tests/test_spidermiddleware_output_chain.py
{ "start": 2737, "end": 3283 }
class ____(ProcessSpiderInputSpiderWithoutErrback): name = "ProcessSpiderInputSpiderWithErrback" async def start(self): yield Request( self.mockserver.url("/status?n=200"), self.parse, errback=self.errback ) def errback(self, failure): self.logger.info("Got a Failure on...
ProcessSpiderInputSpiderWithErrback
python
sympy__sympy
sympy/tensor/array/expressions/array_expressions.py
{ "start": 12945, "end": 27862 }
class ____(_CodegenArrayAbstract): r""" Class to represent permutation of axes of arrays. Examples ======== >>> from sympy.tensor.array import permutedims >>> from sympy import MatrixSymbol >>> M = MatrixSymbol("M", 3, 3) >>> cg = permutedims(M, [1, 0]) The object ``cg`` represent...
PermuteDims
python
huggingface__transformers
tests/models/cohere/test_tokenization_cohere.py
{ "start": 872, "end": 15227 }
class ____(TokenizerTesterMixin, unittest.TestCase): tokenizer_class = CohereTokenizer from_pretrained_vocab_key = "tokenizer_file" from_pretrained_id = "hf-internal-testing/tiny-random-CohereForCausalLM" special_tokens_map = { "bos_token": "<BOS_TOKEN>", "eos_token": "<|END_OF_TURN_TOKE...
CohereTokenizationTest
python
tensorflow__tensorflow
tensorflow/python/framework/python_op_gen_annotation_test.py
{ "start": 945, "end": 1808 }
class ____(googletest.TestCase): def test_type_annotation_not_empty_for_internal_op(self): for internal_op in [ data_flow_ops.dynamic_stitch, gen_nn_ops._fused_batch_norm, gen_math_ops.add, ]: sig = inspect.signature(internal_op) for key in sig.parameters: if key =...
PythonOpGetTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 853340, "end": 854627 }
class ____(sgqlc.types.Type): """The value of a reviewers field in a Project item.""" __schema__ = github_schema __field_names__ = ("field", "reviewers") field = sgqlc.types.Field(sgqlc.types.non_null("ProjectV2FieldConfiguration"), graphql_name="field") """The field that contains this value.""" ...
ProjectV2ItemFieldReviewerValue
python
kamyu104__LeetCode-Solutions
Python/find-the-minimum-area-to-cover-all-ones-i.py
{ "start": 41, "end": 542 }
class ____(object): def minimumArea(self, grid): """ :type grid: List[List[int]] :rtype: int """ min_r, max_r, min_c, max_c = len(grid), -1, len(grid[0]), -1 for i in xrange(len(grid)): for j in xrange(len(grid[0])): if grid[i][j] == 0: ...
Solution
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_axis45.py
{ "start": 315, "end": 1790 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_axis45.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_...
TestCompareXLSXFiles
python
PyCQA__pylint
tests/functional/i/invalid/invalid_repr_returned.py
{ "start": 1029, "end": 1126 }
class ____: """ Uninferable return value """ __repr__ = lambda self: Missing
AmbiguousRepr
python
numpy__numpy
numpy/_core/tests/test_casting_unittests.py
{ "start": 2134, "end": 4546 }
class ____(enum.IntEnum): no = 0 equiv = 1 safe = 2 same_kind = 3 unsafe = 4 same_value = 64 same_value_dtypes = tuple(type(np.dtype(c)) for c in "?bhilqBHILQefdgFDG") def _get_cancast_table(): table = textwrap.dedent(""" X ? b h i l q B H I L Q e f d g F D G S U V O M m ?...
Casting
python
huggingface__transformers
src/transformers/models/convbert/modeling_convbert.py
{ "start": 5787, "end": 11937 }
class ____(nn.Module): def __init__(self, config): super().__init__() if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention...
ConvBertSelfAttention
python
walkccc__LeetCode
solutions/2345. Finding the Number of Visible Mountains/2345.py
{ "start": 0, "end": 451 }
class ____: def visibleMountains(self, peaks: list[list[int]]) -> int: ans = 0 maxRightFoot = 0 peaks.sort(key=lambda x: (x[0] - x[1], -x[0])) for i, peak in enumerate(peaks): overlapWithNext = i + 1 < len(peaks) and peak == peaks[i + 1] currRightFoot = peak[0] + peak[1] if currRig...
Solution
python
tensorflow__tensorflow
tensorflow/python/framework/tensor.py
{ "start": 5331, "end": 28615 }
class ____(internal.NativeObject, core_tf_types.Symbol): """A `tf.Tensor` represents a multidimensional array of elements. All elements are of a single known data type. When writing a TensorFlow program, the main object that is manipulated and passed around is the `tf.Tensor`. A `tf.Tensor` has the followi...
Tensor
python
openai__openai-python
src/openai/resources/fine_tuning/jobs/checkpoints.py
{ "start": 7197, "end": 7442 }
class ____: def __init__(self, checkpoints: AsyncCheckpoints) -> None: self._checkpoints = checkpoints self.list = async_to_streamed_response_wrapper( checkpoints.list, )
AsyncCheckpointsWithStreamingResponse
python
doocs__leetcode
lcof2/剑指 Offer II 071. 按权重生成随机数/Solution.py
{ "start": 0, "end": 650 }
class ____: def __init__(self, w: List[int]): n = len(w) self.presum = [0] * (n + 1) for i in range(n): self.presum[i + 1] = self.presum[i] + w[i] def pickIndex(self) -> int: n = len(self.presum) x = random.randint(1, self.presum[-1]) left, right = 0,...
Solution
python
anthropics__anthropic-sdk-python
tests/lib/test_vertex.py
{ "start": 364, "end": 5771 }
class ____: client = AnthropicVertex(region="region", project_id="project", access_token="my-access-token") @pytest.mark.respx() def test_messages_retries(self, respx_mock: MockRouter) -> None: request_url = "https://region-aiplatform.googleapis.com/v1/projects/project/locations/region/publishers/a...
TestAnthropicVertex
python
huggingface__transformers
src/transformers/testing_utils.py
{ "start": 83434, "end": 95657 }
class ____: """ Helper class that will count all requests made online. Might not be robust if urllib3 changes its logging format but should be good enough for us. Usage: ```py with RequestCounter() as counter: _ = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert") ...
RequestCounter
python
coleifer__peewee
tests/db_tests.py
{ "start": 33406, "end": 34057 }
class ____(BaseTestCase): def test_model_property(self): database = get_in_memory_db() class M1(database.Model): pass class M2(database.Model): pass class CM1(M1): pass for M in (M1, M2, CM1): self.assertTrue(M._meta.database is database) def test_model_prope...
TestModelPropertyHelper
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py
{ "start": 124516, "end": 125508 }
class ____: @mock.patch("google.cloud.aiplatform_v1.types.PipelineJob.to_dict") @mock.patch(VERTEX_AI_PATH.format("pipeline_job.PipelineJobHook")) def test_execute(self, mock_hook, to_dict_mock): op = GetPipelineJobOperator( task_id=TASK_ID, gcp_conn_id=GCP_CONN_ID, ...
TestVertexAIGetPipelineJobOperator
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/operators/emr.py
{ "start": 14532, "end": 17048 }
class ____(AwsBaseOperator[EmrHook]): """ An operator that stops a running EMR notebook execution. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:EmrStopNotebookExecutionOperator` :param notebook_execution_id: The unique i...
EmrStopNotebookExecutionOperator
python
PyCQA__pycodestyle
testing/data/E30not.py
{ "start": 8, "end": 87 }
class ____: pass #: Okay def foo(): pass #: Okay # -*- coding: utf-8 -*-
X
python
simplejson__simplejson
simplejson/tests/test_iterable.py
{ "start": 269, "end": 1390 }
class ____(unittest.TestCase): def test_iterable(self): for l in ([], [1], [1, 2], [1, 2, 3]): for opts in [{}, {'indent': 2}]: for dumps in (json.dumps, iter_dumps, sio_dump): expect = dumps(l, **opts) default_expect = dumps(sum(l), **opts...
TestIterable
python
fluentpython__example-code-2e
13-protocol-abc/typing/randompickload.py
{ "start": 110, "end": 218 }
class ____(RandomPicker, Protocol): # <2> def load(self, Iterable) -> None: ... # <3>
LoadableRandomPicker
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 938387, "end": 938791 }
class ____(sgqlc.types.Type): """An edge in a connection.""" __schema__ = github_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field("RepositoryInvitation", gr...
RepositoryInvitationEdge
python
dagster-io__dagster
python_modules/dagster/dagster/_core/storage/legacy_storage.py
{ "start": 6142, "end": 14755 }
class ____(RunStorage, ConfigurableClass): def __init__(self, storage: DagsterStorage, inst_data: Optional[ConfigurableClassData] = None): self._storage = check.inst_param(storage, "storage", DagsterStorage) self._inst_data = check.opt_inst_param(inst_data, "inst_data", ConfigurableClassData) ...
LegacyRunStorage
python
getsentry__sentry
tests/sentry/monitors/endpoints/test_project_processing_errors_details.py
{ "start": 299, "end": 1762 }
class ____(MonitorTestCase, APITestCase): endpoint = "sentry-api-0-project-processing-errors-details" method = "delete" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) def test_empty(self) -> None: self.get_error_response(self.organization.slug, self.proj...
ProjectProcessingErrorsDetailsEndpointTest
python
django__django
tests/model_fields/test_imagefield.py
{ "start": 3565, "end": 7477 }
class ____(ImageFieldTestMixin, TestCase): """ Tests for ImageField that don't need to be run with each of the different test model classes. """ def test_equal_notequal_hash(self): """ Bug #9786: Ensure '==' and '!=' work correctly. Bug #9508: make sure hash() works as expec...
ImageFieldTests
python
wandb__wandb
wandb/sdk/data_types/table.py
{ "start": 689, "end": 774 }
class ____: def set_table(self, table): self._table = table
_TableLinkMixin
python
cython__cython
Cython/Debugger/libpython.py
{ "start": 83273, "end": 83505 }
class ____(ExecutionControlCommandBase, PythonStepperMixin): "Step through Python code." stepinto = True @dont_suppress_errors def invoke(self, args, from_tty): self.python_step(stepinto=self.stepinto)
PyStep
python
allegroai__clearml
clearml/utilities/py3_interop.py
{ "start": 184, "end": 1386 }
class ____(object): """An abstract base class for context managers. Supported in contextlib from python 3.6 and up""" def __enter__(self) -> "AbstractContextManager": """Return `self` upon entering the runtime context.""" return self @abc.abstractmethod def __exit__( self, ...
AbstractContextManager
python
doocs__leetcode
solution/3500-3599/3506.Find Time Required to Eliminate Bacterial Strains/Solution.py
{ "start": 0, "end": 265 }
class ____: def minEliminationTime(self, timeReq: List[int], splitTime: int) -> int: heapify(timeReq) while len(timeReq) > 1: heappop(timeReq) heappush(timeReq, heappop(timeReq) + splitTime) return timeReq[0]
Solution
python
networkx__networkx
networkx/utils/heaps.py
{ "start": 161, "end": 3216 }
class ____: """Base class for min-heaps. A MinHeap stores a collection of key-value pairs ordered by their values. It supports querying the minimum pair, inserting a new pair, decreasing the value in an existing pair and deleting the minimum pair. """ class _Item: """Used by subclasses...
MinHeap
python
automl__auto-sklearn
autosklearn/metalearning/metafeatures/metafeatures.py
{ "start": 23544, "end": 23862 }
class ____(MetaFeature): def _calculate(self, X, y, logger, feat_type): skews = helper_functions.get_value("Skewnesses") maximum = np.nanmax(skews) if len(skews) > 0 else 0 return maximum if np.isfinite(maximum) else 0 @metafeatures.define("SkewnessMean", dependency="Skewnesses")
SkewnessMax
python
pennersr__django-allauth
tests/apps/socialaccount/providers/apple/tests.py
{ "start": 4276, "end": 9827 }
class ____(OAuth2TestsMixin, TestCase): provider_id = AppleProvider.id def get_apple_id_token_payload(self): now = int(time.time()) return { "iss": "https://appleid.apple.com", "aud": "app123id", # Matches `setup_app` "exp": now + 60 * 60, "iat":...
AppleTests
python
great-expectations__great_expectations
contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_south_dakota_zip.py
{ "start": 1782, "end": 4155 }
class ____(ColumnMapExpectation): """Expect values in this column to be valid South Dakota zipcodes. See https://pypi.org/project/zipcodes/ for more information. """ # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples ...
ExpectColumnValuesToBeValidSouthDakotaZip
python
python__mypy
mypy/semanal_shared.py
{ "start": 10908, "end": 15795 }
class ____(BoolTypeQuery): def __init__(self) -> None: super().__init__(ANY_STRATEGY) def visit_placeholder_type(self, t: PlaceholderType) -> bool: return True def has_placeholder(typ: Type) -> bool: """Check if a type contains any placeholder types (recursively).""" return typ.accept...
HasPlaceholders
python
django__django
tests/multiple_database/tests.py
{ "start": 88857, "end": 97533 }
class ____(TestCase): databases = {"default", "other"} class WriteCheckRouter: def db_for_write(self, model, **hints): raise RouterUsed(mode=RouterUsed.WRITE, model=model, hints=hints) def override_router(self): return override_settings( DATABASE_ROUTERS=[RouteForWr...
RouteForWriteTestCase
python
getsentry__sentry
src/sentry/issues/grouptype.py
{ "start": 12964, "end": 13338 }
class ____(GroupType): type_id = 1008 slug = "performance_file_io_main_thread" description = "File IO on Main Thread" category = GroupCategory.PERFORMANCE.value category_v2 = GroupCategory.MOBILE.value noise_config = NoiseConfig() default_priority = PriorityLevel.LOW released = True @d...
PerformanceFileIOMainThreadGroupType
python
pytorch__pytorch
test/quantization/jit/test_ondevice_quantization.py
{ "start": 649, "end": 935 }
class ____(torch.nn.Module): def __init__(self, weight): super().__init__() self.fc1 = torch.nn.Linear(5, 5).float() self.fc1.weight = weight self.fc2 = torch.nn.Linear(5, 5).float() def forward(self, x): return self.fc2(self.fc1(x))
myMod
python
dask__distributed
distributed/tests/test_profile.py
{ "start": 9408, "end": 9862 }
class ____: def __init__(self, f_back=None, f_code=None): self.f_back = self l = [] self.f_code = l.append self.f_lineno = 1 def test_builtin(): # https://github.com/dask/distributed/issues/8163 assert identifier(MockFrame()) == "list.append:1" assert info_frame(MockFr...
MockFrame
python
pydantic__pydantic
tests/mypy/modules/plugin_success.py
{ "start": 302, "end": 405 }
class ____(BaseModel): x: float y: str model_config = ConfigDict(from_attributes=True)
Model
python
ray-project__ray
release/nightly_tests/dataset/image_loader_microbenchmark.py
{ "start": 9458, "end": 9823 }
class ____(LocalDataset): def __init__(self, local: str, transforms: Callable) -> None: super().__init__(local=local) self.transforms = transforms def __getitem__(self, idx: int) -> Any: obj = super().__getitem__(idx) image = obj["image"] label = obj["label"] ret...
MosaicDataset
python
realpython__materials
python-contact-book/source_code_final/rpcontacts/views.py
{ "start": 2921, "end": 4822 }
class ____(QDialog): """Add Contact dialog.""" def __init__(self, parent=None): """Initializer.""" super().__init__(parent=parent) self.setWindowTitle("Add Contact") self.layout = QVBoxLayout() self.setLayout(self.layout) self.data = None self.setupUI() ...
AddDialog
python
huggingface__transformers
tests/models/yolos/test_modeling_yolos.py
{ "start": 6320, "end": 13156 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as YOLOS does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = (YolosModel, YolosForObjectDetection) if is_torch_ava...
YolosModelTest
python
kamyu104__LeetCode-Solutions
Python/find-the-minimum-amount-of-time-to-brew-potions.py
{ "start": 54, "end": 512 }
class ____(object): def minTime(self, skill, mana): """ :type skill: List[int] :type mana: List[int] :rtype: int """ result = 0 for i in xrange(1, len(mana)): prefix = mx = 0 for x in skill: prefix += x m...
Solution
python
sympy__sympy
sympy/physics/biomechanics/tests/test_curve.py
{ "start": 35041, "end": 53270 }
class ____: @pytest.fixture(autouse=True) def _fiber_force_length_active_arguments_fixture(self): self.l_M_tilde = Symbol('l_M_tilde') self.c0 = Symbol('c_0') self.c1 = Symbol('c_1') self.c2 = Symbol('c_2') self.c3 = Symbol('c_3') self.c4 = Symbol('c_4') ...
TestFiberForceLengthActiveDeGroote2016
python
bokeh__bokeh
src/bokeh/core/types.py
{ "start": 2406, "end": 2471 }
class ____(SpanGeometry): x: float y: float
SpanGeometryData
python
getsentry__sentry
src/sentry/api/exceptions.py
{ "start": 3574, "end": 3865 }
class ____(SentryAPIException): status_code = status.HTTP_401_UNAUTHORIZED code = "primary-email-verification-required" message = "Primary email verification required." def __init__(self, user): super().__init__(username=user.username)
PrimaryEmailVerificationRequired
python
walkccc__LeetCode
solutions/404. Sum of Left Leaves/404.py
{ "start": 0, "end": 340 }
class ____: def sumOfLeftLeaves(self, root: TreeNode | None) -> int: if not root: return 0 ans = 0 if root.left: if not root.left.left and not root.left.right: ans += root.left.val else: ans += self.sumOfLeftLeaves(root.left) ans += self.sumOfLeftLeaves(root.right) ...
Solution
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta/beta_memory_tool_20250818_str_replace_command.py
{ "start": 216, "end": 524 }
class ____(BaseModel): command: Literal["str_replace"] """Command type identifier""" new_str: str """Text to replace with""" old_str: str """Text to search for and replace""" path: str """Path to the file where text should be replaced"""
BetaMemoryTool20250818StrReplaceCommand
python
langchain-ai__langchain
libs/partners/groq/tests/unit_tests/fake/callbacks.py
{ "start": 6177, "end": 6590 }
class ____(FakeCallbackHandler): def on_chat_model_start( self, serialized: dict[str, Any], messages: list[list[BaseMessage]], *, run_id: UUID, parent_run_id: UUID | None = None, **kwargs: Any, ) -> Any: assert all(isinstance(m, BaseMessage) for m ...
FakeCallbackHandlerWithChatStart
python
walkccc__LeetCode
solutions/3316. Find Maximum Removals From Source String/3316-2.py
{ "start": 0, "end": 715 }
class ____: def maxRemovals( self, source: str, pattern: str, targetIndices: list[int] ) -> int: m = len(source) n = len(pattern) target = set(targetIndices) # dp[i][j] := the maximum number of operations that can be performed for # source[i..m) and pattern[j..n) dp =...
Solution
python
tensorflow__tensorflow
tensorflow/python/distribute/cross_device_ops_test.py
{ "start": 4692, "end": 5789 }
class ____: def __init__(self, num_processes): cluster_spec_dict = multi_worker_test_base.create_cluster_spec( num_workers=num_processes ) self.runner = multi_process_runner.MultiProcessPoolRunner(cluster_spec_dict) # Global MultiProcessPoolRunners that can be shared by test cases to avoid # ex...
MultiProcessPoolRunner
python
automl__auto-sklearn
autosklearn/pipeline/components/feature_preprocessing/fast_ica.py
{ "start": 540, "end": 3377 }
class ____(AutoSklearnPreprocessingAlgorithm): def __init__(self, algorithm, whiten, fun, n_components=None, random_state=None): self.algorithm = algorithm self.whiten = whiten self.fun = fun self.n_components = n_components self.random_state = random_state def fit(self...
FastICA
python
astropy__astropy
astropy/modeling/polynomial.py
{ "start": 43269, "end": 47825 }
class ____(OrthoPolynomialBase): r""" Bivariate Legendre series. Defined as: .. math:: P_{n_m}(x,y) = \sum_{n,m=0}^{n=d,m=d}C_{nm} L_n(x ) L_m(y) where ``L_n(x)`` and ``L_m(y)`` are Legendre polynomials. For explanation of ``x_domain``, ``y_domain``, ``x_window`` and ``y_window`` see :r...
Legendre2D
python
dask__distributed
distributed/worker.py
{ "start": 4947, "end": 7434 }
class ____(TypedDict): status: Literal["OK"] data: dict[Key, object] def fail_hard(method: Callable[P, T]) -> Callable[P, T]: """ Decorator to close the worker if this method encounters an exception. """ reason = f"worker-{method.__name__}-fail-hard" if iscoroutinefunction(method): ...
GetDataSuccess
python
doocs__leetcode
solution/2500-2599/2566.Maximum Difference by Remapping a Digit/Solution.py
{ "start": 0, "end": 245 }
class ____: def minMaxDifference(self, num: int) -> int: s = str(num) mi = int(s.replace(s[0], '0')) for c in s: if c != '9': return int(s.replace(c, '9')) - mi return num - mi
Solution
python
SmileyChris__easy-thumbnails
easy_thumbnails/templatetags/thumbnail.py
{ "start": 1016, "end": 10636 }
class ____(Node): def __init__(self, source_var, opts, context_name=None): self.source_var = source_var self.opts = opts self.context_name = context_name def render(self, context): # Note that this isn't a global constant because we need to change the # value for tests. ...
ThumbnailNode
python
pytorch__pytorch
torch/nn/modules/activation.py
{ "start": 54922, "end": 55524 }
class ____(Module): r"""Applies the element-wise Softsign function. .. math:: \text{SoftSign}(x) = \frac{x}{ 1 + |x|} Shape: - Input: :math:`(*)`, where :math:`*` means any number of dimensions. - Output: :math:`(*)`, same shape as the input. .. image:: ../scripts/activation_i...
Softsign
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/required2.py
{ "start": 278, "end": 1328 }
class ____(TypedDict, total=False): a: Annotated["te.Required[int]", ""] b: Annotated[te.NotRequired[str], ""] c: "te.Required[int | str]" d: te.Required[str | None] e: Required[Literal[1, 2, 3]] f: Required[None] g: Required[type[int]] td1_1: TD1 = {"a": 3, "c": "hi", "d": None, "e": 3, "...
TD1
python
facelessuser__soupsieve
tests/test_versions.py
{ "start": 93, "end": 4052 }
class ____(unittest.TestCase): """Test versions.""" def test_version_output(self): """Test that versions generate proper strings.""" assert Version(1, 0, 0, "final")._get_canonical() == "1.0" assert Version(1, 2, 0, "final")._get_canonical() == "1.2" assert Version(1, 2, 3, "fi...
TestVersion
python
kamyu104__LeetCode-Solutions
Python/minimum-limit-of-balls-in-a-bag.py
{ "start": 55, "end": 604 }
class ____(object): def minimumSize(self, nums, maxOperations): """ :type nums: List[int] :type maxOperations: int :rtype: int """ def check(nums, maxOperations, x): return sum((num+x-1)//x-1 for num in nums) <= maxOperations left, right = 1, ...
Solution
python
Textualize__textual
src/textual/renderables/tint.py
{ "start": 304, "end": 2605 }
class ____: """Applies a color on top of an existing renderable.""" def __init__( self, renderable: RenderableType, color: Color, ) -> None: """Wrap a renderable to apply a tint color. Args: renderable: A renderable. color: A color (presumabl...
Tint
python
pytorch__pytorch
test/test_set_default_mobile_cpu_allocator.py
{ "start": 115, "end": 976 }
class ____(TestCase): def test_no_exception(self): torch._C._set_default_mobile_cpu_allocator() torch._C._unset_default_mobile_cpu_allocator() def test_exception(self): with self.assertRaises(Exception): torch._C._unset_default_mobile_cpu_allocator() with self.asser...
TestSetDefaultMobileCPUAllocator
python
walkccc__LeetCode
solutions/2163. Minimum Difference in Sums After Removal of Elements/2163.py
{ "start": 0, "end": 863 }
class ____: def minimumDifference(self, nums: list[int]) -> int: n = len(nums) // 3 ans = math.inf leftSum = 0 rightSum = 0 maxHeap = [] # Left part, as small as possible minHeap = [] # Right part, as big as possible # minLeftSum[i] := the minimum of the sum of n nums in nums[0..i) m...
Solution
python
kubernetes-client__python
kubernetes/client/models/v1_service_spec.py
{ "start": 383, "end": 44516 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1ServiceSpec
python
kamyu104__LeetCode-Solutions
Python/minimum-incompatibility.py
{ "start": 175, "end": 1314 }
class ____(object): def minimumIncompatibility(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ inf = (len(nums)-1)*(len(nums)//k)+1 def backtracking(nums, d, lookup): if not nums: return 0 if nums ...
Solution
python
numba__numba
numba/tests/test_ir_inlining.py
{ "start": 36368, "end": 38100 }
class ____(MemoryLeakMixin, InliningBase): def test_with_inlined_and_noninlined_variants(self): # This test is contrived and was to demonstrate fixing a bug in the # template walking logic where inlinable and non-inlinable definitions # would not mix. @overload(len, inline='always'...
TestGeneralInlining
python
keras-team__keras
keras/src/distribution/distribution_lib_test.py
{ "start": 5561, "end": 9623 }
class ____(testing.TestCase): def setUp(self): super().setUp() self.devices = [f"cpu:{i}" for i in range(8)] shape = (8,) axis_names = ["data"] self.device_mesh = distribution_lib.DeviceMesh( shape, axis_names, self.devices ) def test_create_with_dev...
DataParallelDistributionTest
python
tqdm__tqdm
tests/tests_contrib_logging.py
{ "start": 589, "end": 754 }
class ____(tqdm): messages = [] @classmethod def write(cls, s, **__): # pylint: disable=arguments-differ CustomTqdm.messages.append(s)
CustomTqdm
python
doocs__leetcode
solution/1200-1299/1282.Group the People Given the Group Size They Belong To/Solution.py
{ "start": 0, "end": 269 }
class ____: def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: g = defaultdict(list) for i, v in enumerate(groupSizes): g[v].append(i) return [v[j : j + i] for i, v in g.items() for j in range(0, len(v), i)]
Solution
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 163240, "end": 163355 }
class ____(RecvmsgTests, SendrecvmsgUDPTestBase): pass @requireAttrs(socket.socket, "recvmsg_into")
RecvmsgUDPTest
python
rapidsai__cudf
python/cudf_polars/cudf_polars/dsl/expressions/slicing.py
{ "start": 451, "end": 1203 }
class ____(Expr): __slots__ = ("length", "offset") _non_child = ("dtype", "offset", "length") def __init__( self, dtype: DataType, offset: int, length: int | None, column: Expr, ) -> None: self.dtype = dtype self.offset = offset self.lengt...
Slice
python
ansible__ansible
test/units/module_utils/facts/test_collectors.py
{ "start": 16402, "end": 16610 }
class ____(BaseFactsTest): __test__ = True gather_subset = ['!all', 'user'] valid_subsets = ['user'] fact_namespace = 'ansible_user' collector_class = UserFactCollector
TestUserFactCollector
python
walkccc__LeetCode
solutions/446. Arithmetic Slices II - Subsequence/446.py
{ "start": 0, "end": 597 }
class ____: def numberOfArithmeticSlices(self, nums: list[int]) -> int: n = len(nums) ans = 0 # dp[i][j] := the number of subsequences end in nums[j] nums[i] dp = [[0] * n for _ in range(n)] numToIndices = collections.defaultdict(list) for i, num in enumerate(nums): numToIndices[num].ap...
Solution
python
wandb__wandb
wandb/apis/public/reports.py
{ "start": 8932, "end": 16613 }
class ____: """Converts Python-style query expressions to MongoDB-style queries for W&B reports. <!-- lazydoc-ignore-class: internal --> """ SPACER = "----------" DECIMAL_SPACER = ";;;" FRONTEND_NAME_MAPPING = { "ID": "name", "Name": "displayName", "Tags": "tags", ...
PythonMongoishQueryGenerator
python
huggingface__transformers
src/transformers/models/bart/modeling_bart.py
{ "start": 19481, "end": 20289 }
class ____(PreTrainedModel): config: BartConfig base_model_prefix = "model" supports_gradient_checkpointing = True _keys_to_ignore_on_load_unexpected = ["encoder.version", "decoder.version"] _no_split_modules = [r"BartEncoderLayer", r"BartDecoderLayer"] _skip_keys_device_placement = "past_key_va...
BartPreTrainedModel
python
PyCQA__pylint
tests/functional/i/iterable_context.py
{ "start": 1977, "end": 2211 }
class ____(Iterable): pass m = MyClass() for i in m: print(i) # skip uninferable instances ambiguous = range(i) or range(i) for j in ambiguous: print(j) # skip checks if statement is inside mixin/base/abstract class
MyClass
python
kamyu104__LeetCode-Solutions
Python/erect-the-fence-ii.py
{ "start": 123, "end": 2025 }
class ____(object): def outerTrees(self, trees): """ :type trees: List[List[int]] :rtype: List[float] """ def dist(a, b): return ((a[0]-b[0])**2 + (a[1]-b[1])**2)**0.5 def inside(c, p): return dist(c[0], p) < c[1]+EPS def circle_cente...
Solution
python
pandas-dev__pandas
pandas/tests/reshape/merge/test_merge_asof.py
{ "start": 296, "end": 121035 }
class ____: def prep_data(self, df, dedupe=False): if dedupe: df = df.drop_duplicates(["time", "ticker"], keep="last").reset_index( drop=True ) df.time = to_datetime(df.time) return df @pytest.fixture def trades(self): df = pd.DataFram...
TestAsOfMerge
python
walkccc__LeetCode
solutions/3447. Assign Elements to Groups with Constraints/3447.py
{ "start": 0, "end": 780 }
class ____: def assignElements(self, groups: list[int], elements: list[int]) -> list[int]: ans = [] elementToMinIndex = {} for i, element in enumerate(elements): if element not in elementToMinIndex: elementToMinIndex[element] = i for num in groups: ans.append(self._getMinIndex(nu...
Solution
python
kamyu104__LeetCode-Solutions
Python/sum-of-elements-with-frequency-divisible-by-k.py
{ "start": 46, "end": 417 }
class ____(object): def sumDivisibleByK(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ mx = max(nums) cnt = [0]*(mx+1) for x in nums: cnt[x] += 1 return sum(x for x in nums if cnt[x]%k == 0) # Time: O(n) #...
Solution
python
encode__django-rest-framework
tests/test_relations.py
{ "start": 13829, "end": 19111 }
class ____(APISimpleTestCase): def setUp(self): self.queryset = MockQueryset([ MockObject( pk=1, name='foo', nested=MockObject( pk=2, name='bar', nested=MockObject( pk=7, name="foobar" ) ) ...
TestNestedSlugRelatedField
python
wandb__wandb
wandb/sdk/artifacts/_generated/project_artifact_collections.py
{ "start": 778, "end": 1057 }
class ____(GQLResult): total_count: int = Field(alias="totalCount") page_info: PageInfoFragment = Field(alias="pageInfo") edges: List[ProjectArtifactCollectionsProjectArtifactTypeArtifactCollectionsEdges]
ProjectArtifactCollectionsProjectArtifactTypeArtifactCollections
python
pytorch__pytorch
test/distributed/_composable/test_replicate.py
{ "start": 9232, "end": 10627 }
class ____(ReplicateTest): @skip_if_lt_x_gpu(2) @unittest.skipIf(TEST_XPU, "XPU does not support gloo backend") def test_replicate_fully_shard_init(self): class ToyModel(nn.Module): def __init__(self, dim: int): super().__init__() self.linears = nn.Sequent...
ReplicateFullyShardInit
python
bokeh__bokeh
tests/unit/bokeh/document/test_events__document.py
{ "start": 1291, "end": 2102 }
class ____: def __init__(self) -> None: self.called = [] def _document_changed(self, event): self.called.append('_document_changed') def _document_patched(self, event): self.called.append('_document_patched') def _document_model_changed(self, event): self.called.append('_docum...
FakeFullDispatcher
python
PrefectHQ__prefect
src/prefect/events/clients.py
{ "start": 14961, "end": 16196 }
class ____(PrefectEventsClient): """A Prefect Events client that streams events to a Prefect Cloud Workspace""" def __init__( self, api_url: Optional[str] = None, api_key: Optional[str] = None, reconnection_attempts: int = 10, checkpoint_every: int = 700, ): ...
PrefectCloudEventsClient
python
ray-project__ray
python/ray/util/collective/types.py
{ "start": 3382, "end": 3481 }
class ____: reduceOp = ReduceOp.SUM timeout_ms = unset_timeout_ms @dataclass
AllReduceOptions
python
huggingface__transformers
src/transformers/models/ijepa/modeling_ijepa.py
{ "start": 3146, "end": 7567 }
class ____(nn.Module): """ Construct the CLS token, position and patch embeddings. Optionally, also the mask token. """ def __init__(self, config: IJepaConfig, use_mask_token: bool = False) -> None: super().__init__() self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))...
IJepaEmbeddings
python
xlwings__xlwings
xlwings/_xlwindows.py
{ "start": 46262, "end": 48329 }
class ____(base_classes.Shape): def __init__(self, xl): self.xl = xl @property def api(self): return self.xl @property def name(self): return self.xl.Name @property def parent(self): return Sheet(xl=self.xl.Parent) @property def type(self): ...
Shape
python
coleifer__peewee
tests/sqlite.py
{ "start": 100520, "end": 101196 }
class ____(ModelTestCase): database = get_in_memory_db() def test_deterministic(self): db = self.database @db.func(deterministic=True) def pylower(s): if s is not None: return s.lower() class Reg(db.Model): key = TextField() c...
TestDeterministicFunction
python
bokeh__bokeh
src/bokeh/models/ranges.py
{ "start": 10208, "end": 18013 }
class ____(Range): ''' A Range of values for a categorical dimension. In addition to supplying ``factors`` as a keyword argument to the ``FactorRange`` initializer, you may also instantiate with a sequence of positional arguments: .. code-block:: python FactorRange("foo", "bar") # equival...
FactorRange
python
jamielennox__requests-mock
tests/test_custom_matchers.py
{ "start": 863, "end": 1997 }
class ____(base.TestCase): def assertMatchAll(self, resp): self.assertEqual(200, resp.status_code) self.assertEqual(resp.text, u'data') @requests_mock.Mocker() def test_custom_matcher(self, mocker): mocker.add_matcher(match_all) resp = requests.get('http://any/thing') ...
CustomMatchersTests
python
redis__redis-py
redis/event.py
{ "start": 7949, "end": 8184 }
class ____(EventListenerInterface): """ Listener that performs re-authentication of given connection. """ def listen(self, event: AfterConnectionReleasedEvent): event.connection.re_auth()
ReAuthConnectionListener
python
google__jax
tests/lax_test.py
{ "start": 200717, "end": 213870 }
class ____(jtu.JaxTestCase): def _test_ragged_dot(self, m, k, n, num_groups, dtype): """Tests ragged_dot. The ragged_dot is tested against numpy reference implementation, and by running JAX compilation. Raises: SkipTest: in the case dtype is not supported. """ if (dtype == np.float16)...
RaggedTest
python
dagster-io__dagster
python_modules/libraries/dagster-airflow/dagster_airflow/operators/dagster_operator.py
{ "start": 500, "end": 4768 }
class ____(BaseOperator): """DagsterOperator. Uses the dagster graphql api to run and monitor dagster jobs on remote dagster infrastructure Parameters: repository_name (str): the name of the repository to use repostitory_location_name (str): the name of the repostitory location to use ...
DagsterOperator
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 584788, "end": 585614 }
class ____(sgqlc.types.relay.Connection): """The connection type for EnterpriseAdministratorInvitation.""" __schema__ = github_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field(sgqlc.types.list_of("EnterpriseAdministratorInvitationEdge"), graphql_name="ed...
EnterpriseAdministratorInvitationConnection
python
walkccc__LeetCode
solutions/2530. Maximal Score After Applying K Operations/2530.py
{ "start": 0, "end": 294 }
class ____: def maxKelements(self, nums: list[int], k: int) -> int: ans = 0 maxHeap = [-num for num in nums] heapq.heapify(maxHeap) for _ in range(k): num = -heapq.heappop(maxHeap) ans += num heapq.heappush(maxHeap, -math.ceil(num / 3)) return ans
Solution
python
fluentpython__example-code-2e
24-class-metaprog/sentinel/sentinel_test.py
{ "start": 104, "end": 811 }
class ____(Sentinel): repr = '***SentinelRepr***' def test_repr(): assert repr(PlainSentinel) == 'PlainSentinel' def test_cannot_instantiate(): with pytest.raises(TypeError) as e: PlainSentinel() msg = "'PlainSentinel' is a sentinel and cannot be instantiated" assert msg in str(e.value) ...
SentinelCustomRepr