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
rq__rq
tests/test_queue.py
{ "start": 955, "end": 37146 }
class ____(RQTestCase): def test_create_queue(self): """Creating queues.""" q = Queue('my-queue', connection=self.connection) self.assertEqual(q.name, 'my-queue') self.assertEqual(str(q), '<Queue my-queue>') def test_create_queue_with_serializer(self): """Creating queues...
TestQueue
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_sensor_definition.py
{ "start": 1903, "end": 10356 }
class ____(SensorDefinition, IHasInternalInit): """Define an asset sensor that initiates a set of runs based on the materialization of a given asset. If the asset has been materialized multiple times between since the last sensor tick, the evaluation function will only be invoked once, with the latest ...
AssetSensorDefinition
python
sqlalchemy__sqlalchemy
test/engine/test_reflection.py
{ "start": 48597, "end": 53158 }
class ____(fixtures.TablesTest): __sparse_driver_backend__ = True run_create_tables = None @classmethod def teardown_test_class(cls): # TablesTest is used here without # run_create_tables, so add an explicit drop of whatever is in # metadata cls._tables_metadata.drop_al...
CreateDropTest
python
readthedocs__readthedocs.org
readthedocs/api/v3/views.py
{ "start": 18677, "end": 19531 }
class ____( APIv3Settings, NestedViewSetMixin, ProjectQuerySetMixin, FlexFieldsMixin, ModelViewSet, ): model = Redirect lookup_field = "pk" lookup_url_kwarg = "redirect_pk" permission_classes = (IsAuthenticated & IsProjectAdmin,) def get_queryset(self): queryset = super(...
RedirectsViewSet
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 816693, "end": 817027 }
class ____( sgqlc.types.Type, Node, AuditEntry, OrganizationAuditEntryData ): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("permission",) permission = sgqlc.types.Field( OrgAddMemberAuditEntryPermission, graphql_name="permission" )
OrgAddMemberAuditEntry
python
lepture__authlib
authlib/jose/errors.py
{ "start": 1780, "end": 1919 }
class ____(JoseError): error = "missing_encryption_algorithm" description = "Missing 'enc' in header"
MissingEncryptionAlgorithmError
python
doocs__leetcode
solution/2900-2999/2967.Minimum Cost to Make Array Equalindromic/Solution.py
{ "start": 158, "end": 453 }
class ____: def minimumCost(self, nums: List[int]) -> int: def f(x: int) -> int: return sum(abs(v - x) for v in nums) nums.sort() i = bisect_left(ps, nums[len(nums) // 2]) return min(f(ps[j]) for j in range(i - 1, i + 2) if 0 <= j < len(ps))
Solution
python
sympy__sympy
sympy/assumptions/predicates/calculus.py
{ "start": 1058, "end": 1646 }
class ____(Predicate): """ Infinite number predicate. Explanation =========== ``Q.infinite(x)`` is true iff the absolute value of ``x`` is infinity. Examples ======== >>> from sympy import Q, ask, oo, zoo, I >>> ask(Q.infinite(oo)) True >>> ask(Q.infinite(-oo)) Tr...
InfinitePredicate
python
django__django
tests/model_fields/models.py
{ "start": 3983, "end": 4069 }
class ____(models.Model): value = models.PositiveIntegerField()
PositiveIntegerModel
python
huggingface__transformers
src/transformers/models/siglip/tokenization_siglip.py
{ "start": 1246, "end": 14320 }
class ____(SentencePieceBackend): """ Construct a Siglip tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece). This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to this superclass for more information regarding those...
SiglipTokenizer
python
python-pillow__Pillow
src/PIL/PcfFontFile.py
{ "start": 1338, "end": 7223 }
class ____(FontFile.FontFile): """Font file plugin for the X11 PCF format.""" name = "name" def __init__(self, fp: BinaryIO, charset_encoding: str = "iso8859-1"): self.charset_encoding = charset_encoding magic = l32(fp.read(4)) if magic != PCF_MAGIC: msg = "not a PCF f...
PcfFontFile
python
ipython__ipython
IPython/extensions/tests/test_deduperreload.py
{ "start": 37882, "end": 56557 }
class ____(ShellFixture): def test_autoreload_class_basic(self): self.shell.magic_autoreload("2") mod_name, mod_fn = self.new_module( """ x = 9 class C: def foo(): return 1 """ ) self.shell.run_code("impo...
AutoreloadReliabilitySuite
python
sanic-org__sanic
sanic/touchup/meta.py
{ "start": 114, "end": 702 }
class ____(SanicMeta): def __new__(cls, name, bases, attrs, **kwargs): gen_class = super().__new__(cls, name, bases, attrs, **kwargs) methods = attrs.get("__touchup__") attrs["__touched__"] = False if methods: for method in methods: if method not in attrs...
TouchUpMeta
python
spyder-ide__spyder
spyder/widgets/elementstable.py
{ "start": 6084, "end": 8204 }
class ____(CustomSortFilterProxy): FUZZY = False # ---- Public API # ------------------------------------------------------------------------- def filter_row(self, row_num, text=None): # Use the pattern set by set_filter if no text is passed. Otherwise # use `text` as pattern i...
SortElementsFilterProxy
python
sqlalchemy__sqlalchemy
test/ext/test_mutable.py
{ "start": 26601, "end": 27086 }
class ____( _MutableNoHashFixture, _MutableDictTestBase, fixtures.MappedTest ): @classmethod def define_tables(cls, metadata): MutableDict = cls._type_fixture() mutable_pickle = MutableDict.as_mutable(PickleType) Table( "foo", metadata, Column( ...
MutableDictNoHashTest
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/internal/conjecture/choice.py
{ "start": 1116, "end": 1253 }
class ____(TypedDict): min_value: float max_value: float allow_nan: bool smallest_nonzero_magnitude: float
FloatConstraints
python
jazzband__django-simple-history
simple_history/registry_tests/migration_test_app/models.py
{ "start": 767, "end": 968 }
class ____(models.Model): what_i_mean = CustomAttrNameForeignKey( WhatIMean, models.CASCADE, attr_name="custom_attr_name" ) history = HistoricalRecords()
ModelWithCustomAttrForeignKey
python
django-import-export__django-import-export
tests/core/tests/test_import_export_tags.py
{ "start": 91, "end": 369 }
class ____(TestCase): def test_compare_values(self): target = ( '<del style="background:#ffe6e6;">a</del>' '<ins style="background:#e6ffe6;">b</ins>' ) self.assertEqual(target, import_export_tags.compare_values("a", "b"))
TagsTest
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 65040, "end": 65411 }
class ____(_PrintableStructure): _fields_ = [ ('version', c_uint), ('sampleValType', _nvmlValueType_t), ('vgpuInstanceCount', c_uint), ('lastSeenTimeStamp', c_ulonglong), ('vgpuUtilArray', POINTER(c_nvmlVgpuInstanceUtilizationInfo_v1_t)), ] VgpuInstancesUtilizationInfo_v...
c_nvmlVgpuInstancesUtilizationInfo_v1_t
python
astropy__astropy
astropy/modeling/tests/test_bounding_box.py
{ "start": 7890, "end": 27006 }
class ____: def setup_method(self): class BoundingDomain(_BoundingDomain): def fix_inputs(self, model, fix_inputs): super().fix_inputs(model, fixed_inputs=fix_inputs) def prepare_inputs(self, input_shape, inputs): super().prepare_inputs(input_shape, i...
Test_BoundingDomain
python
getsentry__sentry
src/sentry/workflow_engine/processors/delayed_workflow.py
{ "start": 8829, "end": 17247 }
class ____: """ Represents all the data that uniquely identifies a condition and its single respective Snuba query that must be made. Multiple instances of the same condition can share a single query. """ handler: type[BaseEventFrequencyQueryHandler] interval: str environment_id: int | ...
UniqueConditionQuery
python
kubernetes-client__python
kubernetes/client/models/v1beta2_counter.py
{ "start": 383, "end": 3633 }
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...
V1beta2Counter
python
pytorch__pytorch
torch/testing/_internal/distributed/rpc/dist_autograd_test.py
{ "start": 6155, "end": 6534 }
class ____(Function): _simulate_error = True @staticmethod def forward(ctx, input): return input @staticmethod @once_differentiable def backward(ctx, input): if SimulateBackwardError._simulate_error: raise Exception("Simulate error on backward pass") # noqa: TRY002...
SimulateBackwardError
python
huggingface__transformers
src/transformers/models/bertweet/tokenization_bertweet.py
{ "start": 21199, "end": 24418 }
class ____: r""" Examples: ```python >>> # Tokenizer for tweets. >>> from nltk.tokenize import TweetTokenizer >>> tknzr = TweetTokenizer() >>> s0 = "This is a cooool #dummysmiley: :-) :-P <3 and some arrows < > -> <--" >>> tknzr.tokenize(s0) ['This', 'is', 'a', 'cooool', '#dummysmi...
TweetTokenizer
python
PyCQA__pylint
tests/functional/u/unused/unused_typing_imports.py
{ "start": 749, "end": 1748 }
class ____: def __enter__(self): return {1} def __exit__(self, *_args): pass with ContextManager() as SOME_DICT: # type: Set[int] print(SOME_DICT) def func_test_type_comment(param): # type: (NamedTuple) -> Tuple[NamedTuple, Pattern] return param, re.compile('good') def typing_...
ContextManager
python
weaviate__weaviate-python-client
weaviate/collections/classes/cluster.py
{ "start": 990, "end": 2976 }
class ____: @staticmethod def nodes_verbose(nodes: List[NodeREST]) -> List[NodeVerbose]: return [ Node( git_hash=node.get("gitHash", "None"), name=node["name"], shards=( [ Shard( ...
_ConvertFromREST
python
tiangolo__fastapi
tests/test_no_schema_split.py
{ "start": 612, "end": 701 }
class ____(BaseModel): body: str = "" events: List[MessageEvent] = []
MessageOutput
python
numba__numba
numba/cuda/simulator/kernelapi.py
{ "start": 319, "end": 756 }
class ____(object): ''' Used to implement thread/block indices/dimensions ''' def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __str__(self): return '(%s, %s, %s)' % (self.x, self.y, self.z) def __repr__(self): return 'Dim3(%s, %s, %s)' ...
Dim3
python
PrefectHQ__prefect
tests/cli/test_work_pool.py
{ "start": 18855, "end": 19561 }
class ____: async def test_resume(self, prefect_client, work_pool): assert work_pool.is_paused is False # set paused await prefect_client.update_work_pool( work_pool_name=work_pool.name, work_pool=WorkPoolUpdate(is_paused=True), ) work_pool = await pr...
TestResume
python
tensorflow__tensorflow
tensorflow/python/eager/forwardprop_test.py
{ "start": 36600, "end": 37719 }
class ____(test.TestCase): @test_util.assert_no_new_pyobjects_executing_eagerly() def testOfFunctionWhile(self): y = constant_op.constant(1.) with forwardprop.ForwardAccumulator(y, 1.) as acc: self.assertAllClose(10., acc.jvp(_has_loop(constant_op.constant(5), y))) @test_util.assert_no_new_pyobjec...
ControlFlowTests
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/executor_definition.py
{ "start": 2687, "end": 9985 }
class ____(NamedConfigurableDefinition): """An executor is responsible for executing the steps of a job. Args: name (str): The name of the executor. config_schema (Optional[ConfigSchema]): The schema for the config. Configuration data available in `init_context.executor_config`. If ...
ExecutorDefinition
python
encode__django-rest-framework
rest_framework/authtoken/migrations/0004_alter_tokenproxy_options.py
{ "start": 84, "end": 379 }
class ____(migrations.Migration): dependencies = [ ('authtoken', '0003_tokenproxy'), ] operations = [ migrations.AlterModelOptions( name='tokenproxy', options={'verbose_name': 'Token', 'verbose_name_plural': 'Tokens'}, ), ]
Migration
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chartsheet08.py
{ "start": 315, "end": 1934 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chartsheet08.xlsx") self.ignore_files = ["xl/drawings/drawing1.xml"] def test_create_file(self): """Test the worksheet properties ...
TestCompareXLSXFiles
python
run-llama__llama_index
llama-index-core/llama_index/core/schema.py
{ "start": 6351, "end": 6860 }
class ____(str, Enum): """ Node relationships used in `BaseNode` class. Attributes: SOURCE: The node is the source document. PREVIOUS: The node is the previous node in the document. NEXT: The node is the next node in the document. PARENT: The node is the parent node in the d...
NodeRelationship
python
google__jax
tests/api_util_test.py
{ "start": 824, "end": 3101 }
class ____(jtu.JaxTestCase): def test_donation_vector(self): params = {"a": jnp.ones([]), "b": jnp.ones([])} state = {"c": jnp.ones([]), "d": jnp.ones([])} x = jnp.ones([]) args = params, state, x for size in range(4): for donate_argnums in it.permutations((0, 1, 2), size): for kwa...
ApiUtilTest
python
encode__django-rest-framework
tests/test_fields.py
{ "start": 78095, "end": 78454 }
class ____(FieldValues): valid_inputs = () invalid_inputs = [ ((0, 1), ['Ensure this field has at least 3 elements.']), ((0, 1, 2, 3, 4, 5), ['Ensure this field has no more than 4 elements.']), ] outputs = () field = serializers.ListField(child=serializers.IntegerField(), min_length=...
TestListFieldLengthLimit
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/classes5.py
{ "start": 549, "end": 2400 }
class ____(ParentClass1): # This should generate an error. cv1 = "" # This should generate an error if reportIncompatibleVariableOverride # is enabled. cv2: int = 3 cv3 = 3 # This should generate an error if reportIncompatibleVariableOverride # is enabled because it's overriding a non...
Subclass1
python
walkccc__LeetCode
solutions/2546. Apply Bitwise Operations to Make Strings Equal/2546.py
{ "start": 0, "end": 116 }
class ____: def makeStringsEqual(self, s: str, target: str) -> bool: return ('1' in s) == ('1' in target)
Solution
python
joke2k__faker
faker/providers/job/fr_CH/__init__.py
{ "start": 108, "end": 41739 }
class ____(BaseProvider): jobs = [ "Accompagnant socioprofessionnel diplômé", "Accompagnateur de randonnée avec brevet fédéral", "Accompagnateur social avec brevet fédéral", "Acousticien en systèmes auditifs CFC", "Administrateur diplomé de biens immobiliers", "Agent ...
Provider
python
zarr-developers__zarr-python
src/zarr/testing/buffer.py
{ "start": 440, "end": 544 }
class ____(np.ndarray): """An example of a ndarray-like class""" __test__ = False
TestNDArrayLike
python
mlflow__mlflow
mlflow/server/graphql/autogenerated_graphql_schema.py
{ "start": 3741, "end": 3876 }
class ____(graphene.ObjectType): path = graphene.String() is_dir = graphene.Boolean() file_size = LongString()
MlflowFileInfo
python
walkccc__LeetCode
solutions/3281. Maximize Score of Numbers in Ranges/3281.py
{ "start": 0, "end": 498 }
class ____: def maxPossibleScore(self, start: list[int], d: int) -> int: def isPossible(m: int) -> bool: lastPick = start[0] for i in range(1, len(start)): if lastPick + m > start[i] + d: return False lastPick = max(lastPick + m, start[i]) return True start.sort() ...
Solution
python
davidhalter__jedi
jedi/inference/value/module.py
{ "start": 1296, "end": 2011 }
class ____: @inference_state_method_cache() def sub_modules_dict(self): """ Lists modules in the directory of this module (if this module is a package). """ names = {} if self.is_package(): mods = self.inference_state.compiled_subprocess.iter_module_na...
SubModuleDictMixin
python
pytorch__pytorch
torch/_inductor/codegen/cpp_grouped_gemm_template.py
{ "start": 6159, "end": 20910 }
class ____(CppGemmTemplate): def __init__( self, input_nodes: list[ir.IRNode], layout: ir.Layout, num_threads: int, register_blocking: GemmBlocking, beta: int = 1, alpha: int = 1, has_bias: bool = False, epilogue_creator: Optional[Callable[[ir....
CppGroupedGemmTemplate
python
cython__cython
Cython/Compiler/ModuleNode.py
{ "start": 7618, "end": 191002 }
class ____(Nodes.Node, Nodes.BlockNode): # doc string or None # body StatListNode # # referenced_modules [ModuleScope] # full_module_name string # # scope The module scope. # compilation_source A CompilationSource (see Main) # directives ...
ModuleNode
python
PyCQA__pylint
tests/functional/i/invalid/invalid_getnewargs/invalid_getnewargs_returned.py
{ "start": 216, "end": 351 }
class ____: """__getnewargs__ returns <type 'tuple'>""" def __getnewargs__(self): return (1, "2", 3)
FirstGoodGetNewArgs
python
facebook__pyre-check
tools/upgrade/commands/tests/fix_configuration_test.py
{ "start": 783, "end": 6784 }
class ____(unittest.TestCase): @patch("subprocess.check_output") @patch.object(Configuration, "get_errors") @patch.object(Repository, "commit_changes") @patch.object(Repository, "remove_paths") def test_run_fix_configuration( self, remove_paths, commit_changes, get_errors, check_output )...
FixmeConfigurationTest
python
scipy__scipy
scipy/optimize/_trustregion_constr/report.py
{ "start": 1410, "end": 1782 }
class ____(ReportBase): COLUMN_NAMES = ["niter", "f evals", "CG iter", "obj func", "tr radius", "opt", "c viol", "penalty", "barrier param", "CG stop"] COLUMN_WIDTHS = [7, 7, 7, 13, 10, 10, 10, 10, 13, 7] ITERATION_FORMATS = ["^7", "^7", "^7", "^+13.4e", "^10.2e", "^10.2e", ...
IPReport
python
pypa__pip
src/pip/_vendor/platformdirs/android.py
{ "start": 190, "end": 9013 }
class ____(PlatformDirsABC): """ Follows the guidance `from here <https://android.stackexchange.com/a/216132>`_. Makes use of the `appname <platformdirs.api.PlatformDirsABC.appname>`, `version <platformdirs.api.PlatformDirsABC.version>`, `ensure_exists <platformdirs.api.PlatformDirsABC.ensure_exists>`....
Android
python
joke2k__faker
tests/providers/test_currency.py
{ "start": 5329, "end": 6528 }
class ____: """Test de_AT currency provider""" num_samples = 100 @classmethod def setup_class(cls): from faker.providers.currency.de_AT import Provider as DeAtCurrencyProvider cls.provider = DeAtCurrencyProvider cls.currencies = cls.provider.currencies cls.currency_nam...
TestDeAt
python
keras-team__keras
keras/src/legacy/saving/legacy_h5_format_test.py
{ "start": 11340, "end": 20239 }
class ____(testing.TestCase): def _check_reloading_model(self, ref_input, model, tf_keras_model): # Whole model file ref_output = tf_keras_model(ref_input) temp_filepath = os.path.join(self.get_temp_dir(), "model.h5") tf_keras_model.save(temp_filepath) loaded = legacy_h5_form...
LegacyH5BackwardsCompatTest
python
huggingface__transformers
tests/models/idefics2/test_image_processing_idefics2.py
{ "start": 1117, "end": 6478 }
class ____: def __init__( self, parent, batch_size=7, num_channels=3, num_images=1, image_size=18, min_resolution=30, max_resolution=400, do_resize=True, size=None, do_rescale=True, rescale_factor=1 / 255, do_nor...
Idefics2ImageProcessingTester
python
spyder-ide__spyder
spyder/plugins/preferences/api.py
{ "start": 188, "end": 266 }
class ____: Show = 'show_action' Reset = 'reset_action'
PreferencesActions
python
kamyu104__LeetCode-Solutions
Python/fruits-into-baskets-ii.py
{ "start": 63, "end": 1910 }
class ____(object): def numOfUnplacedFruits(self, fruits, baskets): """ :type fruits: List[int] :type baskets: List[int] :rtype: int """ class SegmentTree(object): def __init__(self, N, build_fn=lambda _: 0, ...
Solution
python
great-expectations__great_expectations
great_expectations/expectations/metrics/column_map_metrics/column_values_unique.py
{ "start": 665, "end": 3486 }
class ____(ColumnMapMetricProvider): condition_metric_name = "column_values.unique" @column_condition_partial(engine=PandasExecutionEngine) def _pandas(cls, column, **kwargs): return ~column.duplicated(keep=False) # NOTE: 20201119 - JPC - We cannot split per-dialect into window and non-window ...
ColumnValuesUnique
python
tensorflow__tensorflow
tensorflow/python/autograph/core/ag_ctx.py
{ "start": 2310, "end": 3093 }
class ____(object): """Helper substitute for contextlib.nullcontext.""" def __enter__(self): pass def __exit__(self, unused_type, unused_value, unused_traceback): pass def _default_control_status_ctx(): return ControlStatusCtx(status=Status.UNSPECIFIED) INSPECT_SOURCE_SUPPORTED = True try: inspe...
NullCtx
python
getsentry__sentry
src/sentry/notifications/utils/__init__.py
{ "start": 17089, "end": 18507 }
class ____(PerformanceProblemContext): def to_dict(self) -> dict[str, str | float | list[str]]: return { "transaction_name": self.transaction, "repeating_spans": self.path_prefix, "parameters": self.parameters, "num_repeating_spans": ( str(len(...
NPlusOneAPICallProblemContext
python
facebook__pyre-check
tools/generate_taint_models/tests/get_exit_nodes_test.py
{ "start": 362, "end": 2070 }
class ____(unittest.TestCase): def test_compute_models(self) -> None: self.maxDiff = None sink = "TaintSink[ReturnedToUser]" self.assertEqual( [ *map( str, ExitNodeGenerator(django_urls=MagicMock()).compute_models( ...
GetExitNodesTest
python
python-openxml__python-docx
src/docx/image/image.py
{ "start": 6381, "end": 8005 }
class ____: """Base class for image header subclasses like |Jpeg| and |Tiff|.""" def __init__(self, px_width: int, px_height: int, horz_dpi: int, vert_dpi: int): self._px_width = px_width self._px_height = px_height self._horz_dpi = horz_dpi self._vert_dpi = vert_dpi @prope...
BaseImageHeader
python
getsentry__sentry
src/sentry/sentry_metrics/indexer/base.py
{ "start": 1523, "end": 3064 }
class ____: """ A KeyCollection is a way of keeping track of a group of keys used to fetch ids, whose results are stored in KeyResults. A key is a org_id, string pair, either represented as a tuple e.g (1, "a"), or a string "1:a". Initial mapping is org_id's to sets of strings: { 1: {"...
KeyCollection
python
astropy__astropy
astropy/utils/iers/tests/test_leap_second.py
{ "start": 14883, "end": 15436 }
class ____: """Base class for tests that change the ERFA leap-second tables. It ensures the original state is restored. """ def setup_method(self): # Keep current leap-second table and expiration. self.erfa_ls = self._erfa_ls = erfa.leap_seconds.get() self.erfa_expires = self._...
ERFALeapSecondsSafe
python
networkx__networkx
networkx/algorithms/centrality/tests/test_betweenness_centrality.py
{ "start": 16088, "end": 24867 }
class ____: def test_K5(self): """Weighted betweenness centrality: K5""" G = nx.complete_graph(5) b = nx.betweenness_centrality(G, weight="weight", normalized=False) b_answer = {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0} for n in sorted(G): assert b[n] == pytest.appr...
TestWeightedBetweennessCentrality
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 119678, "end": 120704 }
class ____(TestCase): def test_normal(self): iterable = [10, 20, 30, 40, 50] actual = list(mi.difference(iterable)) expected = [10, 10, 10, 10, 10] self.assertEqual(actual, expected) def test_custom(self): iterable = [10, 20, 30, 40, 50] actual = list(mi.differen...
DifferenceTest
python
tensorflow__tensorflow
tensorflow/python/util/lazy_loader.py
{ "start": 3736, "end": 7820 }
class ____(LazyLoader): """LazyLoader that handles routing to different Keras version.""" def __init__( # pylint: disable=super-init-not-called self, parent_module_globals, mode=None, submodule=None, name="keras"): self._tfll_parent_module_globals = parent_module_globals self._tfll_mode = mode s...
KerasLazyLoader
python
pytorch__pytorch
torch/distributed/_pycute/layout.py
{ "start": 2713, "end": 17979 }
class ____(LayoutBase): def __init__(self, _shape: IntTuple, _stride: Optional[IntTuple] = None) -> None: self.shape = _shape if _stride is None: self.stride = suffix_product(self.shape) else: self.stride = _stride # operator == def __eq__(self, other: object...
Layout
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol3.py
{ "start": 3102, "end": 3168 }
class ____(NamedTuple): x: str = "" @dataclass(frozen=False)
NT9
python
google__jax
jax/_src/stages.py
{ "start": 14409, "end": 17607 }
class ____(Stage): """Traced form of a function specialized to argument types and values. A traced computation is ready for lowering. This class carries the traced representation with the remaining information needed to later lower, compile, and execute it. """ __slots__ = ['_meta_tys_flat', '_params', '_i...
Traced
python
psf__black
src/blib2to3/pgen2/tokenize.py
{ "start": 2706, "end": 7378 }
class ____(Exception): ... def transform_whitespace( token: pytokens.Token, source: str, prev_token: pytokens.Token | None ) -> pytokens.Token: r""" Black treats `\\\n` at the end of a line as a 'NL' token, while it is ignored as whitespace in the regular Python parser. But, only the first one. If...
TokenError
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 95629, "end": 96123 }
class ____(sgqlc.types.Enum): """The level of enforcement for a rule or ruleset. Enumeration Choices: * `ACTIVE`: Rules will be enforced * `DISABLED`: Do not evaluate or enforce rules * `EVALUATE`: Allow admins to test rules before enforcing them. Admins can view insights on the Rule Insight...
RuleEnforcement
python
run-llama__llama_index
llama-index-core/llama_index/core/response_synthesizers/type.py
{ "start": 24, "end": 2102 }
class ____(str, Enum): """Response modes of the response builder (and synthesizer).""" REFINE = "refine" """ Refine is an iterative way of generating a response. We first use the context in the first node, along with the query, to generate an \ initial answer. We then pass this answer, the ...
ResponseMode
python
networkx__networkx
networkx/algorithms/tests/test_matching.py
{ "start": 13369, "end": 14833 }
class ____: """Unit tests for the :func:`~networkx.algorithms.matching.is_matching` function. """ def test_dict(self): G = nx.path_graph(4) assert nx.is_matching(G, {0: 1, 1: 0, 2: 3, 3: 2}) def test_empty_matching(self): G = nx.path_graph(4) assert nx.is_matching(...
TestIsMatching
python
Netflix__metaflow
test/core/tests/nested_unbounded_foreach.py
{ "start": 72, "end": 2549 }
class ____(MetaflowTest): PRIORITY = 1 SKIP_GRAPHS = [ "simple_switch", "nested_switch", "branch_in_switch", "foreach_in_switch", "switch_in_branch", "switch_in_foreach", "recursive_switch", "recursive_switch_inside_foreach", ] @steps(0, [...
NestedUnboundedForeachTest
python
google__pytype
pytype/tests/test_attr1.py
{ "start": 159, "end": 19885 }
class ____(test_base.BaseTest): """Tests for attr.ib.""" def test_basic(self): ty = self.Infer(""" import attr @attr.s class Foo: x = attr.ib() y = attr.ib(type=int) z = attr.ib(type=str) """) self.assertTypesMatchPytd( ty, """ import attr...
TestAttrib
python
streamlit__streamlit
lib/tests/streamlit/elements/pyplot_test.py
{ "start": 1050, "end": 8189 }
class ____(DeltaGeneratorTestCase): def setUp(self): super().setUp() if mpl.get_backend().lower() != "agg": plt.switch_backend("agg") def tearDown(self): # Clear the global pyplot figure between tests plt.clf() super().tearDown() def test_st_pyplot(self)...
PyplotTest
python
mlflow__mlflow
mlflow/gateway/providers/cohere.py
{ "start": 452, "end": 11157 }
class ____(ProviderAdapter): @staticmethod def _scale_temperature(payload): # The range of Cohere's temperature is 0-5, but ours is 0-2, so we scale it. if temperature := payload.get("temperature"): payload["temperature"] = 2.5 * temperature return payload @classmethod ...
CohereAdapter
python
huggingface__transformers
src/transformers/models/textnet/modeling_textnet.py
{ "start": 8111, "end": 9762 }
class ____(TextNetPreTrainedModel): def __init__(self, config): super().__init__(config) self.stem = TextNetConvLayer(config) self.encoder = TextNetEncoder(config) self.pooler = nn.AdaptiveAvgPool2d((2, 2)) self.post_init() @auto_docstring def forward( self, ...
TextNetModel
python
altair-viz__altair
altair/utils/data.py
{ "start": 7091, "end": 14835 }
class ____(TypedDict): url: str format: _FormatDict @overload def to_json( data: None = ..., prefix: str = ..., extension: str = ..., filename: str = ..., urlpath: str = ..., ) -> partial: ... @overload def to_json( data: DataType, prefix: str = ..., extension: str = ..., ...
_ToFormatReturnUrlDict
python
pandas-dev__pandas
pandas/tests/window/test_numba.py
{ "start": 1387, "end": 9731 }
class ____: @pytest.mark.parametrize("jit", [True, False]) def test_numba_vs_cython_apply(self, jit, nogil, parallel, nopython, center, step): def f(x, *args): arg_sum = 0 for arg in args: arg_sum += arg return np.mean(x) + arg_sum if jit: ...
TestEngine
python
pytorch__pytorch
benchmarks/inductor_backends/cutlass.py
{ "start": 1729, "end": 2239 }
class ____: max_autotune: bool = True coordinate_descent_tuning: bool = True max_autotune_gemm_backends: str = "ATEN" @abstractmethod def name(self) -> str: pass def to_options(self) -> dict[str, Any]: return { "max_autotune": self.max_autotune, "coordin...
ExperimentConfig
python
google__flatbuffers
conanfile.py
{ "start": 166, "end": 2922 }
class ____(ConanFile): name = "flatbuffers" license = "Apache-2.0" url = "https://github.com/google/flatbuffers" homepage = "http://google.github.io/flatbuffers/" author = "Wouter van Oortmerssen" topics = ("conan", "flatbuffers", "serialization", "rpc", "json-parser") description = "Memory Efficient Seri...
FlatbuffersConan
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_slots/SLOT000.py
{ "start": 38, "end": 111 }
class ____(str): # Ok __slots__ = ["foo"] from enum import Enum
Good
python
langchain-ai__langchain
libs/core/langchain_core/tools/base.py
{ "start": 13550, "end": 44881 }
class ____(BaseTool): ... args_schema: Type[BaseModel] = SchemaClass ...""" name = cls.__name__ msg = ( f"Tool definition for {name} must include valid type annotations" f" for argument 'args_schema' to behave as expected.\n" f"Expected...
ChildTool
python
Textualize__textual
src/textual/widgets/_progress_bar.py
{ "start": 5791, "end": 6656 }
class ____(Label): """A label to display the estimated time until completion of the progress bar.""" DEFAULT_CSS = """ ETAStatus { width: 9; content-align-horizontal: right; } """ eta: reactive[float | None] = reactive[Optional[float]](None) """Estimated number of seconds ti...
ETAStatus
python
PrefectHQ__prefect
tests/server/models/test_saved_searches.py
{ "start": 84, "end": 2174 }
class ____: async def test_create_saved_search_succeeds(self, session): filters = [ { "object": "flow", "property": "name", "type": "string", "operation": "equals", "value": "foo", }, { ...
TestCreateSavedSearch
python
getsentry__sentry
tests/sentry/backup/test_rpc.py
{ "start": 12559, "end": 18101 }
class ____(TestCase): """ Validate errors related to the `import_by_model()` RPC method. """ @staticmethod def is_user_model(model: Any) -> bool: return NormalizedModelName(model["model"]) == USER_MODEL_NAME @cached_property def _json_of_exhaustive_user_with_minimum_privileges(self...
RpcImportErrorTests
python
django__django
tests/aggregation_regress/models.py
{ "start": 172, "end": 335 }
class ____(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() friends = models.ManyToManyField("self", blank=True)
Author
python
getsentry__sentry
src/sentry/ingest/transaction_clusterer/__init__.py
{ "start": 150, "end": 744 }
class ____: name: str """Human-friendly name of the namespace. For example, logging purposes.""" data: str """Prefix to store input data to the clusterer.""" rules: str """Prefix to store produced rules in the clusterer, in non-persistent storage.""" persistent_storage: str """Option nam...
NamespaceOption
python
airbytehq__airbyte
airbyte-integrations/connectors/source-shopify/source_shopify/scopes.py
{ "start": 2979, "end": 6490 }
class ____: # define default logger logger = logging.getLogger("airbyte") def __init__(self, config: Mapping[str, Any]) -> None: self.permitted_streams: List[str] = list(ALWAYS_PERMITTED_STREAMS) self.not_permitted_streams: List[set[str, str]] = [] self._error_handler = ShopifyError...
ShopifyScopes
python
getsentry__sentry
tests/sentry/snuba/test_query_subscription_consumer.py
{ "start": 2510, "end": 4869 }
class ____(BaseQuerySubscriptionTest, TestCase): @pytest.fixture(autouse=True) def _setup_metrics(self): with mock.patch("sentry.utils.metrics") as self.metrics: yield def test_arroyo_consumer(self) -> None: topic_defn = get_topic_definition(Topic.EVENTS) create_topics(t...
HandleMessageTest
python
pypa__setuptools
setuptools/tests/test_config_discovery.py
{ "start": 12325, "end": 15237 }
class ____: def _simulate_package_with_extension(self, tmp_path): # This example is based on: https://github.com/nucleic/kiwi/tree/1.4.0 files = [ "benchmarks/file.py", "docs/Makefile", "docs/requirements.txt", "docs/source/conf.py", "proj/...
TestWithCExtension
python
pandas-dev__pandas
asv_bench/benchmarks/strings.py
{ "start": 7425, "end": 7521 }
class ____(Dtypes): def time_iter(self, dtype): for i in self.s: pass
Iter
python
huggingface__transformers
tests/models/chameleon/test_image_processing_chameleon.py
{ "start": 3667, "end": 10003 }
class ____(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = ChameleonImageProcessor if is_vision_available() else None fast_image_processing_class = ChameleonImageProcessorFast if is_torchvision_available() else None # Copied from tests.models.clip.test_image_processing_clip.CLIPImage...
ChameleonImageProcessingTest
python
xlwings__xlwings
xlwings/constants.py
{ "start": 112442, "end": 112554 }
class ____: xlByColumns = 2 # from enum XlSearchOrder xlByRows = 1 # from enum XlSearchOrder
SearchOrder
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 275144, "end": 275830 }
class ____(sgqlc.types.Input): """Autogenerated input type of RemoveEnterpriseMember""" __schema__ = github_schema __field_names__ = ("enterprise_id", "user_id", "client_mutation_id") enterprise_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="enterpriseId") """The ID of the enterpris...
RemoveEnterpriseMemberInput
python
paramiko__paramiko
paramiko/auth_strategy.py
{ "start": 3348, "end": 3918 }
class ____(PrivateKey): """ An in-memory, decrypted `.PKey` object. """ def __init__(self, username, pkey): super().__init__(username=username) # No decryption (presumably) necessary! self.pkey = pkey def __repr__(self): # NOTE: most of interesting repr-bits for pri...
InMemoryPrivateKey
python
dask__distributed
distributed/dashboard/components/scheduler.py
{ "start": 32474, "end": 35417 }
class ____(DashboardComponent): """How many tasks are on each worker""" @log_errors def __init__(self, scheduler, **kwargs): self.last = 0 self.scheduler = scheduler self.source = ColumnDataSource( { "bandwidth": [1, 2], "source": ["a", "b...
BandwidthWorkers
python
pypa__setuptools
setuptools/_vendor/wheel/cli/convert.py
{ "start": 3054, "end": 5003 }
class ____(ConvertSource): def __init__(self, path: Path): if not (match := egg_filename_re.match(path.name)): raise ValueError(f"Invalid egg file name: {path.name}") # Binary wheels are assumed to be for CPython self.path = path self.name = normalize(match.group("name")...
EggFileSource
python
modin-project__modin
modin/tests/pandas/extensions/test_series_extensions.py
{ "start": 5808, "end": 10304 }
class ____: def test_override_index(self, Backend1): series = pd.Series(["a", "b"]) def set_index(self, new_index): self._query_compiler.index = [f"{v}_custom" for v in new_index] register_series_accessor(name="index", backend=Backend1)( property(fget=lambda self: s...
TestProperty
python
weaviate__weaviate-python-client
weaviate/collections/classes/config.py
{ "start": 11317, "end": 11619 }
class ____(_GenerativeProvider): generative: Union[GenerativeSearches, _EnumLikeStr] = Field( default=GenerativeSearches.NVIDIA, frozen=True, exclude=True ) temperature: Optional[float] model: Optional[str] maxTokens: Optional[int] baseURL: Optional[str]
_GenerativeNvidia
python
Textualize__textual
src/textual/widgets/_static.py
{ "start": 223, "end": 3180 }
class ____(Widget, inherit_bindings=False): """A widget to display simple static content, or use as a base class for more complex widgets. Args: content: A Content object, Rich renderable, or string containing console markup. expand: Expand content if required to fill container. shrink:...
Static