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
test/dynamo/test_higher_order_ops.py
{ "start": 150748, "end": 152886 }
class ____(torch.nn.Module): def forward(self, L_x_: "f32[5]"): l_x_ = L_x_ _saved_tensors_hooks_disable = torch._C._autograd._saved_tensors_hooks_disable("torch.func.{grad, vjp, jacrev, hessian} don't yet support saved tensor hooks. Please open an issue with your use case."); _saved_tensors_hooks...
GraphModule
python
dagster-io__dagster
python_modules/dagster/dagster/_core/errors.py
{ "start": 8486, "end": 8771 }
class ____(DagsterError): """Thrown when a run cannot be found in run storage.""" def __init__(self, *args, **kwargs): self.invalid_run_id = check.str_param(kwargs.pop("invalid_run_id"), "invalid_run_id") super().__init__(*args, **kwargs)
DagsterRunNotFoundError
python
tensorflow__tensorflow
tensorflow/python/distribute/vars_test.py
{ "start": 19315, "end": 28183 }
class ____(test.TestCase, parameterized.TestCase): @combinations.generate(ms_combination) def testScatterSub(self, distribution): with distribution.scope(): v = variables_lib.Variable( [0., 0., 0.], aggregation=variables_lib.VariableAggregation.MEAN) self.evaluate(v.initializer) @def_f...
OnWriteVariableSyncScatterTests
python
RaRe-Technologies__gensim
gensim/similarities/docsim.py
{ "start": 29340, "end": 34581 }
class ____(interfaces.SimilarityABC): """Compute cosine similarity against a corpus of documents by storing the index matrix in memory. Unless the entire matrix fits into main memory, use :class:`~gensim.similarities.docsim.Similarity` instead. Examples -------- .. sourcecode:: pycon >>> ...
MatrixSimilarity
python
docker__docker-py
docker/errors.py
{ "start": 4659, "end": 4843 }
class ____(DockerException): def __init__(self, param): self.param = param def __str__(self): return (f"missing parameter: {self.param}")
MissingContextParameter
python
django__django
tests/multiple_database/tests.py
{ "start": 49453, "end": 50684 }
class ____(SimpleTestCase): @override_settings( DATABASE_ROUTERS=[ "multiple_database.tests.TestRouter", "multiple_database.tests.WriteRouter", ] ) def test_router_init_default(self): connection_router = ConnectionRouter() self.assertEqual( ...
ConnectionRouterTestCase
python
Lightning-AI__lightning
src/lightning/fabric/utilities/load.py
{ "start": 1358, "end": 6092 }
class ____: def __init__( self, metatensor: Tensor, archiveinfo: "_LazyLoadingUnpickler", storageinfo: tuple, rebuild_args: tuple, ) -> None: self.metatensor = metatensor self.archiveinfo = archiveinfo self.storageinfo = storageinfo self.re...
_NotYetLoadedTensor
python
python-attrs__attrs
src/attr/validators.py
{ "start": 15915, "end": 16719 }
class ____: min_length = attrib() def __call__(self, inst, attr, value): """ We use a callable class to be able to change the ``__repr__``. """ if len(value) < self.min_length: msg = f"Length of '{attr.name}' must be >= {self.min_length}: {len(value)}" ra...
_MinLengthValidator
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataplex.py
{ "start": 141414, "end": 145195 }
class ____(DataplexCatalogBaseOperator): """ List AspectType resources. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:DataplexCatalogListAspectTypesOperator` :param filter_by: Optional. Filter to apply on the list results....
DataplexCatalogListAspectTypesOperator
python
prabhupant__python-ds
data_structures/graphs/print_all_paths_between_nodes.py
{ "start": 37, "end": 1039 }
class ____: def __init__(self, vertices): self.graph = defaultdict(list) self.vertices = vertices def add_edge(self, u, v): self.graph[u].append(v) def print_path(self, s, d, visited, path): visited[s] = True path.append(s) if s == d: print(...
Graph
python
google__jax
jax/_src/scipy/optimize/minimize.py
{ "start": 884, "end": 4954 }
class ____(NamedTuple): """Object holding optimization results. Parameters: x: final solution. success: ``True`` if optimization succeeded. status: integer solver specific return code. 0 means converged (nominal), 1=max BFGS iters reached, 3=zoom failed, 4=saddle point reached, 5=max line s...
OptimizeResults
python
getsentry__sentry
src/sentry/plugins/base/structs.py
{ "start": 228, "end": 615 }
class ____: def __init__(self, event, rule=None, rules=None): if rule and not rules: rules = [rule] self.event = event self.rules = rules or [] @property def rule(self): warnings.warn( "Notification.rule is deprecated. Switch to Notification.rules.",...
Notification
python
mlflow__mlflow
mlflow/sklearn/__init__.py
{ "start": 20478, "end": 21548 }
class ____: _SUPPORTED_CUSTOM_PREDICT_FN = [ "predict_proba", "predict_log_proba", "predict_joint_log_proba", "score", ] def __init__(self, sklearn_model): self.sklearn_model = sklearn_model # Patch the model with custom predict functions that can be specifi...
_SklearnModelWrapper
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI034.py
{ "start": 4178, "end": 4418 }
class ____: def __new__() -> InvalidButPluginDoesNotCrash: ... def __enter__() -> InvalidButPluginDoesNotCrash: ... async def __aenter__() -> InvalidButPluginDoesNotCrash: ...
InvalidButPluginDoesNotCrash
python
sympy__sympy
sympy/stats/crv.py
{ "start": 1290, "end": 1554 }
class ____(RandomDomain): """ A domain with continuous support Represented using symbols and Intervals. """ is_Continuous = True def as_boolean(self): raise NotImplementedError("Not Implemented for generic Domains")
ContinuousDomain
python
getsentry__sentry
tests/sentry/integrations/slack/notifications/test_nudge.py
{ "start": 326, "end": 1542 }
class ____(SlackActivityNotificationTest): @responses.activate def test_nudge_block(self) -> None: notification = IntegrationNudgeNotification( self.organization, recipient=Actor.from_object(self.user), provider=ExternalProviders.SLACK, seed=SEED, ...
SlackNudgeNotificationTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 65332, "end": 65664 }
class ____(sgqlc.types.Enum): """The layout of a project v2 view. Enumeration Choices: * `BOARD_LAYOUT`: Board layout * `ROADMAP_LAYOUT`: Roadmap layout * `TABLE_LAYOUT`: Table layout """ __schema__ = github_schema __choices__ = ("BOARD_LAYOUT", "ROADMAP_LAYOUT", "TABLE_LAYOUT")
ProjectV2ViewLayout
python
spack__spack
lib/spack/spack/package_base.py
{ "start": 107708, "end": 107866 }
class ____(InvalidPackageOpError): """Raised when attempting an invalid operation on a package that requires a manual download."""
ManualDownloadRequiredError
python
Pylons__pyramid
tests/test_util.py
{ "start": 12174, "end": 12931 }
class ____(unittest.TestCase): def _callFUT(self, *args, **kw): from pyramid.util import strings_differ return strings_differ(*args, **kw) def test_it_bytes(self): self.assertFalse(self._callFUT(b'foo', b'foo')) self.assertTrue(self._callFUT(b'123', b'345')) self.assert...
Test_strings_differ
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_looker.py
{ "start": 2000, "end": 5969 }
class ____(LookerTestBase): @mock.patch(OPERATOR_PATH.format("LookerHook")) def test_execute(self, mock_hook): # mock return vals from hook mock_hook.return_value.start_pdt_build.return_value.materialization_id = TEST_JOB_ID mock_hook.return_value.wait_for_job.return_value = None ...
TestLookerStartPdtBuildOperator
python
getsentry__sentry
tests/apidocs/endpoints/scim/test_group_index.py
{ "start": 184, "end": 1197 }
class ____(APIDocsTestCase, SCIMTestCase): def setUp(self) -> None: super().setUp() self.member = self.create_member(user=self.create_user(), organization=self.organization) self.team = self.create_team(organization=self.organization, members=[self.user]) self.url = reverse( ...
SCIMTeamIndexDocs
python
tornadoweb__tornado
tornado/test/netutil_test.py
{ "start": 5331, "end": 5463 }
class ____(_ResolverTestMixin): def setUp(self): super().setUp() self.resolver = CaresResolver()
CaresResolverTest
python
django__django
tests/backends/base/test_base.py
{ "start": 468, "end": 3830 }
class ____(SimpleTestCase): def test_repr(self): conn = connections[DEFAULT_DB_ALIAS] self.assertEqual( repr(conn), f"<DatabaseWrapper vendor={connection.vendor!r} alias='default'>", ) def test_initialization_class_attributes(self): """ The "initi...
DatabaseWrapperTests
python
redis__redis-py
redis/commands/search/querystring.py
{ "start": 2411, "end": 2607 }
class ____(Value): combinable = False def __init__(self, *tags): self.tags = tags def to_string(self): return "{" + " | ".join(str(t) for t in self.tags) + "}"
TagValue
python
tensorflow__tensorflow
tensorflow/python/framework/errors_impl.py
{ "start": 14692, "end": 15171 }
class ____(OpError): """Raised when an operation was aborted, typically due to a concurrent action. For example, running a `tf.queue.QueueBase.enqueue` operation may raise `AbortedError` if a `tf.queue.QueueBase.close` operation previously ran. """ def __init__(self, node_def, op, message, *args): ...
AbortedError
python
astropy__astropy
astropy/modeling/tests/test_spline.py
{ "start": 880, "end": 11678 }
class ____: def setup_class(self): self.num_opt = 3 self.optional_inputs = {f"test{i}": mk.MagicMock() for i in range(self.num_opt)} self.extra_kwargs = {f"new{i}": mk.MagicMock() for i in range(self.num_opt)} class Spline(_Spline): optional_inputs = {"test": "test"} ...
TestSpline
python
getsentry__sentry
tests/sentry/integrations/slack/test_link_identity.py
{ "start": 6040, "end": 7496 }
class ____(SlackIntegrationLinkIdentityTestBase): def setUp(self) -> None: super().setUp() self.unlinking_url = build_unlinking_url( self.integration.id, self.external_id, self.channel_id, self.response_url, ) def test_basic_flow(self) ->...
SlackIntegrationUnlinkIdentityTest
python
pandas-dev__pandas
pandas/core/computation/ops.py
{ "start": 4603, "end": 7816 }
class ____: """ Hold an operator of arbitrary arity. """ op: str def __init__(self, op: str, operands: Iterable[Term | Op], encoding=None) -> None: self.op = _bool_op_map.get(op, op) self.operands = operands self.encoding = encoding def __iter__(self) -> Iterator: ...
Op
python
doocs__leetcode
solution/2400-2499/2470.Number of Subarrays With LCM Equal to K/Solution.py
{ "start": 0, "end": 296 }
class ____: def subarrayLCM(self, nums: List[int], k: int) -> int: n = len(nums) ans = 0 for i in range(n): a = nums[i] for b in nums[i:]: x = lcm(a, b) ans += x == k a = x return ans
Solution
python
mwaskom__seaborn
tests/_core/test_scales.py
{ "start": 548, "end": 10290 }
class ____: @pytest.fixture def x(self): return pd.Series([1, 3, 9], name="x", dtype=float) def setup_ticks(self, x, *args, **kwargs): s = Continuous().tick(*args, **kwargs)._setup(x, Coordinate()) a = PseudoAxis(s._matplotlib_scale) a.set_view_interval(0, 1) retur...
TestContinuous
python
pytorch__pytorch
benchmarks/functional_autograd_benchmark/torchvision_models.py
{ "start": 12133, "end": 13035 }
class ____(nn.Module): __constants__ = ["aux_classifier"] def __init__(self, backbone, classifier, aux_classifier=None): super().__init__() self.backbone = backbone self.classifier = classifier self.aux_classifier = aux_classifier def forward(self, x): input_shape =...
_SimpleSegmentationModel
python
ipython__ipython
IPython/lib/backgroundjobs.py
{ "start": 16756, "end": 17680 }
class ____(BackgroundJobBase): """Run a function call as a background job (uses a separate thread).""" def __init__(self, func, *args, **kwargs): """Create a new job from a callable object. Any positional arguments and keyword args given to this constructor after the initial callable a...
BackgroundJobFunc
python
bokeh__bokeh
src/bokeh/protocol/exceptions.py
{ "start": 1670, "end": 1881 }
class ____(Exception): ''' Indicate an error in processing wire protocol fragments. This exception indicates that decoded message fragments cannot be properly assembled. ''' pass
ProtocolError
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1592924, "end": 1593086 }
class ____(sgqlc.types.Union): """Types that can be pinned to a profile page.""" __schema__ = github_schema __types__ = (Gist, Repository)
PinnableItem
python
django-mptt__django-mptt
tests/myapp/tests.py
{ "start": 41465, "end": 48404 }
class ____(TreeTestCase): fixtures = ["categories.json", "genres.json", "persons.json"] def test_all_managers_are_different(self): # all tree managers should be different. otherwise, possible infinite recursion. seen = {} for model in apps.get_models(): if not issubclass(mod...
ManagerTests
python
great-expectations__great_expectations
great_expectations/exceptions/exceptions.py
{ "start": 14960, "end": 15338 }
class ____(ValidationActionRegistryError): def __init__(self, action_type: str | None) -> None: if action_type: message = f"Invalid action configuration; no action of type {action_type} found." else: message = "Invalid action configuration; no 'type' key found." supe...
ValidationActionRegistryRetrievalError
python
numpy__numpy
numpy/lib/_arraysetops_impl.py
{ "start": 14944, "end": 15030 }
class ____(NamedTuple): values: np.ndarray counts: np.ndarray
UniqueCountsResult
python
wandb__wandb
wandb/vendor/graphql-core-1.1/wandb_graphql/type/definition.py
{ "start": 11625, "end": 14224 }
class ____(GraphQLType): """Enum Type Definition Some leaf values of requests and input values are Enums. GraphQL serializes Enum values as strings, however internally Enums can be represented by any kind of type, often integers. Example: RGBType = GraphQLEnumType( name='RGB', ...
GraphQLEnumType
python
kamyu104__LeetCode-Solutions
Python/remove-element.py
{ "start": 29, "end": 444 }
class ____(object): # @param A a list of integers # @param elem an integer, value need to be removed # @return an integer def removeElement(self, A, elem): i, last = 0, len(A) - 1 while i <= last: if A[i] == elem: A[i], A[last] = A[last], A[i] ...
Solution
python
tensorflow__tensorflow
tensorflow/python/distribute/combinations_test.py
{ "start": 8056, "end": 8286 }
class ____(test.TestCase, parameterized.TestCase): def testSysArgvClearedIsFine(self): original_argv = list(sys.argv) sys.argv.clear() importlib.reload(combinations) sys.argv = original_argv
ModuleInitializingTest
python
django__django
tests/queries/models.py
{ "start": 9386, "end": 9454 }
class ____(ObjectA): class Meta: proxy = True
ProxyObjectA
python
allegroai__clearml
clearml/backend_api/session/jsonmodels/fields.py
{ "start": 4441, "end": 4770 }
class ____(BaseField): """Integer field.""" types = (int,) def parse_value(self, value: Any) -> Optional[int]: """Cast value to `int`, e.g. from string or long""" parsed = super(IntField, self).parse_value(value) if parsed is None: return parsed return int(parse...
IntField
python
encode__django-rest-framework
tests/schemas/test_managementcommand.py
{ "start": 545, "end": 843 }
class ____: SCHEMA = {"key": "value"} def __init__(self, *args, **kwargs): pass def get_schema(self, **kwargs): return self.SCHEMA @override_settings(ROOT_URLCONF=__name__) @pytest.mark.skipif(not uritemplate, reason='uritemplate is not installed')
CustomSchemaGenerator
python
doocs__leetcode
solution/3600-3699/3645.Maximum Total from Optimal Activation Order/Solution.py
{ "start": 0, "end": 308 }
class ____: def maxTotal(self, value: List[int], limit: List[int]) -> int: g = defaultdict(list) for v, lim in zip(value, limit): g[lim].append(v) ans = 0 for lim, vs in g.items(): vs.sort() ans += sum(vs[-lim:]) return ans
Solution
python
eventlet__eventlet
tests/convenience_test.py
{ "start": 308, "end": 6303 }
class ____(tests.LimitedTestCase): def setUp(self): super().setUp() debug.hub_exceptions(False) def tearDown(self): super().tearDown() debug.hub_exceptions(True) def test_exiting_server(self): # tests that the server closes the client sock on handle() exit d...
TestServe
python
astropy__astropy
astropy/io/ascii/html.py
{ "start": 3149, "end": 4199 }
class ____(core.BaseSplitter): """ Split HTML table data. """ def __call__(self, lines): """ Return HTML data from lines as a generator. """ for line in lines: if not isinstance(line, SoupString): raise TypeError("HTML lines should be of type ...
HTMLSplitter
python
keon__algorithms
tests/test_dp.py
{ "start": 3865, "end": 4310 }
class ____(unittest.TestCase): def test_get_maximum_value(self): item1, item2, item3 = Item(60, 10), Item(100, 20), Item(120, 30) self.assertEqual(220, get_maximum_value([item1, item2, item3], 50)) item1, item2, item3, item4 = Item(60, 5), Item(50, 3), Item(70, 4), Item(30, 2) self....
TestKnapsack
python
django__django
tests/migrations/test_migrations_conflict_long_name/0001_initial.py
{ "start": 43, "end": 281 }
class ____(migrations.Migration): initial = True operations = [ migrations.CreateModel( "Author", [ ("id", models.AutoField(primary_key=True)), ], ), ]
Migration
python
getsentry__sentry
src/sentry/middleware/stats.py
{ "start": 369, "end": 817 }
class ____(MiddlewareMixin): def process_response(self, request: Request, response: Response) -> Response: metrics.incr("response", instance=str(response.status_code), skip_internal=False) return response def process_exception(self, request: Request, exception: Exception) -> None: if no...
ResponseCodeMiddleware
python
numba__numba
numba/tests/test_iteration.py
{ "start": 6612, "end": 7049 }
class ____(MemoryLeakMixin, TestCase): def test_zip_with_arrays(self): @njit def foo(sequence): c = 0 for a, b in zip(range(len(sequence)), sequence): c += (a + 1) * b.sum() return sequence = [np.arange(1 + i) for i in range(10)] s...
TestIterationRefct
python
kamyu104__LeetCode-Solutions
Python/sort-even-and-odd-indices-independently.py
{ "start": 2720, "end": 2962 }
class ____(object): def sortEvenOdd(self, nums): """ :type nums: List[int] :rtype: List[int] """ nums[::2], nums[1::2] = sorted(nums[::2]), sorted(nums[1::2], reverse=True) return nums
Solution3
python
langchain-ai__langchain
libs/cli/langchain_cli/namespaces/migrate/generate/utils.py
{ "start": 418, "end": 7001 }
class ____(ast.NodeVisitor): """Import extractor.""" def __init__(self, *, from_package: str | None = None) -> None: """Extract all imports from the given code, optionally filtering by package.""" self.imports: list[tuple[str, str]] = [] self.package = from_package @override de...
ImportExtractor
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_A.py
{ "start": 6771, "end": 7933 }
class ____(Benchmark): r""" AMGM objective function. The AMGM (Arithmetic Mean - Geometric Mean Equality) global optimization problem is a multimodal minimization problem defined as follows .. math:: f_{\text{AMGM}}(x) = \left ( \frac{1}{n} \sum_{i=1}^{n} x_i - \sqrt[n]{ \prod_{...
AMGM
python
numpy__numpy
numpy/lib/tests/test_histograms.py
{ "start": 25521, "end": 33951 }
class ____: def test_simple(self): x = np.array([[-.5, .5, 1.5], [-.5, 1.5, 2.5], [-.5, 2.5, .5], [.5, .5, 1.5], [.5, 1.5, 2.5], [.5, 2.5, 2.5]]) H, edges = histogramdd(x, (2, 3, 3), range=[[-1, 1], [0, 3], [0, 3]]) answer = np.array([...
TestHistogramdd
python
huggingface__transformers
src/transformers/models/cwm/modular_cwm.py
{ "start": 9523, "end": 9589 }
class ____(BaseModelOutputWithPast): pass
CwmModelOutputWithPast
python
pytorch__pytorch
test/test_tensorboard.py
{ "start": 7469, "end": 10243 }
class ____(BaseTestCase): def test_to_HWC(self): test_image = np.random.randint(0, 256, size=(3, 32, 32), dtype=np.uint8) converted = convert_to_HWC(test_image, "chw") self.assertEqual(converted.shape, (32, 32, 3)) test_image = np.random.randint(0, 256, size=(16, 3, 32, 32), dtype=np...
TestTensorBoardUtils
python
tensorflow__tensorflow
tensorflow/python/data/experimental/kernel_tests/prefetch_with_slack_test.py
{ "start": 1157, "end": 4140 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): def setUp(self): super(PrefetchWithSlackTest, self).setUp() self._devices = self.configureDevicesForMultiDeviceTest(3) @combinations.generate(test_base.default_test_combinations()) def testPrefetchWithSlackOption(self): """Determines sla...
PrefetchWithSlackTest
python
langchain-ai__langchain
libs/langchain/langchain_classic/evaluation/exact_match/base.py
{ "start": 144, "end": 3058 }
class ____(StringEvaluator): """Compute an exact match between the prediction and the reference. Examples: ---------- >>> evaluator = ExactMatchChain() >>> evaluator.evaluate_strings( prediction="Mindy is the CTO", reference="Mindy is the CTO", ) # This will return ...
ExactMatchStringEvaluator
python
tornadoweb__tornado
demos/s3server/s3server.py
{ "start": 1999, "end": 2800 }
class ____(web.Application): """Implementation of an S3-like storage server based on local files. If bucket depth is given, we break files up into multiple directories to prevent hitting file system limits for number of files in each directories. 1 means one level of directories, 2 means 2, etc. ""...
S3Application
python
huggingface__transformers
src/transformers/models/glm4v_moe/modeling_glm4v_moe.py
{ "start": 24085, "end": 24822 }
class ____(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ Glm4vMoeTextRMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states): ...
Glm4vMoeTextRMSNorm
python
networkx__networkx
networkx/algorithms/tests/test_cuts.py
{ "start": 4850, "end": 5376 }
class ____: """Unit tests for the :func:`~networkx.mixing_expansion` function.""" def test_graph(self): G = nx.barbell_graph(5, 0) S = set(range(5)) T = set(G) - S expansion = nx.mixing_expansion(G, S, T) # There is one cut edge, and the total number of edges in the ...
TestMixingExpansion
python
doocs__leetcode
solution/2600-2699/2678.Number of Senior Citizens/Solution.py
{ "start": 0, "end": 127 }
class ____: def countSeniors(self, details: List[str]) -> int: return sum(int(x[11:13]) > 60 for x in details)
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 830187, "end": 830597 }
class ____(sgqlc.types.Type): """Represents a object that contains package activity statistics such as downloads. """ __schema__ = github_schema __field_names__ = ("downloads_total_count",) downloads_total_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="downloadsTotalCount") ...
PackageStatistics
python
dagster-io__dagster
python_modules/libraries/dagster-dbt/dagster_dbt/core/dbt_cli_invocation.py
{ "start": 1469, "end": 1655 }
class ____(NamedTuple): """Hashable representation of the information needed to identify a relation in a database.""" database: str schema: str identifier: str
RelationKey
python
numba__numba
numba/tests/test_dispatcher.py
{ "start": 30217, "end": 32504 }
class ____(TestCase): def test_pass_dispatcher_as_arg(self): # Test that a Dispatcher object can be pass as argument @jit(nopython=True) def add1(x): return x + 1 @jit(nopython=True) def bar(fn, x): return fn(x) @jit(nopython=True) de...
TestDispatcherFunctionBoundaries
python
pyca__cryptography
src/cryptography/hazmat/primitives/ciphers/base.py
{ "start": 1411, "end": 1632 }
class ____(CipherContext, metaclass=abc.ABCMeta): @abc.abstractmethod def authenticate_additional_data(self, data: Buffer) -> None: """ Authenticates the provided bytes. """
AEADCipherContext
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/input/vt100_parser.py
{ "start": 984, "end": 1077 }
class ____: """Helper object to indicate flush operation to the parser.""" pass
_Flush
python
skorch-dev__skorch
skorch/callbacks/logging.py
{ "start": 28855, "end": 34232 }
class ____(Callback): """Logs results from history to Sacred. Sacred is a tool to help you configure, organize, log and reproduce experiments. Developed at IDSIA. See https://github.com/IDSIA/sacred. Use this callback to automatically log all interesting values from your net's history to Sacred. ...
SacredLogger
python
doocs__leetcode
solution/0200-0299/0222.Count Complete Tree Nodes/Solution2.py
{ "start": 192, "end": 660 }
class ____: def countNodes(self, root: Optional[TreeNode]) -> int: def depth(root): d = 0 while root: d += 1 root = root.left return d if root is None: return 0 left, right = depth(root.left), depth(root.right) ...
Solution
python
pytorch__pytorch
test/dynamo/test_subclasses.py
{ "start": 105406, "end": 106918 }
class ____(torch.nn.Module): def forward( self, primals_1: "Sym(s16)", # PlainAOTInput(idx=0) primals_2: "f32[3, s16]", # SubclassGetAttrAOTInput(base=PlainAOTInput(idx=1), attr='a') primals_3: "f32[3, s16]", # SubclassGetAttrAOTInput(base=PlainAOTInput(idx=1), attr='b') p...
GraphModule
python
Textualize__textual
tests/input/test_cut_copy_paste.py
{ "start": 79, "end": 1714 }
class ____(App): def compose(self) -> ComposeResult: yield Input() async def test_cut(): """Check that cut removes text and places it in the clipboard.""" app = InputApp() async with app.run_test() as pilot: input = app.query_one(Input) await pilot.click(input) await pi...
InputApp
python
huggingface__transformers
tests/models/gpt_sw3/test_tokenization_gpt_sw3.py
{ "start": 950, "end": 8047 }
class ____(TokenizerTesterMixin, unittest.TestCase): from_pretrained_id = "AI-Sweden-Models/gpt-sw3-126m" tokenizer_class = GPTSw3Tokenizer test_rust_tokenizer = False test_sentencepiece = True test_sentencepiece_ignore_case = False @classmethod def setUpClass(cls): super().setUpCla...
GPTSw3TokenizationTest
python
walkccc__LeetCode
solutions/225. Implement Stack using Queues/225.py
{ "start": 0, "end": 350 }
class ____: def __init__(self): self.q = collections.deque() def push(self, x: int) -> None: self.q.append(x) for _ in range(len(self.q) - 1): self.q.append(self.q.popleft()) def pop(self) -> int: return self.q.popleft() def top(self) -> int: return self.q[0] def empty(self) -> b...
MyStack
python
google__pytype
pytype/abstract/function.py
{ "start": 34416, "end": 34711 }
class ____(abc.ABC): """Wrapper for a function return type.""" @property @abc.abstractmethod def name(self): ... @abc.abstractmethod def instantiate_parameter(self, node, param_name): ... @abc.abstractmethod def get_parameter(self, node, param_name): ...
_ReturnType
python
django-guardian__django-guardian
guardian/testapp/models.py
{ "start": 519, "end": 647 }
class ____: def __init__(self): pass def __getattr__(self, key): return DynamicAccessor()
DynamicAccessor
python
huggingface__transformers
tests/models/qwen2_vl/test_modeling_qwen2_vl.py
{ "start": 14840, "end": 27342 }
class ____(unittest.TestCase): def setUp(self): self.processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct") self.messages = [ { "role": "user", "content": [ {"type": "image"}, {"type": "text", "text":...
Qwen2VLIntegrationTest
python
getsentry__sentry
fixtures/safe_migrations_apps/good_flow_delete_field_pending_with_fk_constraint_app/migrations/0003_delete.py
{ "start": 190, "end": 571 }
class ____(CheckedMigration): dependencies = [ ( "good_flow_delete_field_pending_with_fk_constraint_app", "0002_remove_constraints_and_pending", ), ] operations = [ SafeRemoveField( model_name="testtable", name="fk_table", ...
Migration
python
huggingface__transformers
tests/models/apertus/test_modeling_apertus.py
{ "start": 1330, "end": 1463 }
class ____(CausalLMModelTester): if is_torch_available(): base_model_class = ApertusModel @require_torch
ApertusModelTester
python
scipy__scipy
scipy/fftpack/tests/test_basic.py
{ "start": 9189, "end": 11199 }
class ____: def setup_method(self): np.random.seed(1234) def test_definition(self): x1 = [1,2,3,4,1,2,3,4] x1_1 = [1,2+3j,4+1j,2+3j,4,2-3j,4-1j,2-3j] x2 = [1,2,3,4,1,2,3,4,5] x2_1 = [1,2+3j,4+1j,2+3j,4+5j,4-5j,2-3j,4-1j,2-3j] def _test(x, xr): y = ir...
_TestIRFFTBase
python
apache__airflow
providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/operators/resource.py
{ "start": 4786, "end": 6179 }
class ____(KubernetesResourceBaseOperator): """Create a resource in a kubernetes.""" def create_custom_from_yaml_object(self, body: dict): group, version, namespace, plural = self.get_crd_fields(body) if self.namespaced: self.custom_object_client.create_namespaced_custom_object(grou...
KubernetesCreateResourceOperator
python
allegroai__clearml
clearml/backend_api/services/v2_23/events.py
{ "start": 191928, "end": 194568 }
class ____(Response): """ Response of events.vector_metrics_iter_histogram endpoint. :param images: :type images: Sequence[dict] """ _service = "events" _action = "vector_metrics_iter_histogram" _version = "2.23" _schema = { "definitions": {}, "properties": {"images...
VectorMetricsIterHistogramResponse
python
getsentry__sentry
tests/sentry/models/test_groupresolution.py
{ "start": 171, "end": 9761 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.old_release = self.create_release( version="a", date_added=timezone.now() - timedelta(minutes=30) ) self.new_release = self.create_release(version="b") self.group = self.create_group() sel...
GroupResolutionTest
python
hynek__structlog
tests/test_config.py
{ "start": 10963, "end": 13276 }
class ____: def test_wrap_passes_args(self): """ wrap_logger propagates all arguments to the wrapped bound logger. """ logger = object() p = wrap_logger(logger, processors=[1, 2, 3], context_class=dict) assert logger is p._logger assert [1, 2, 3] == p._proces...
TestFunctions
python
scikit-learn__scikit-learn
sklearn/externals/_packaging/_structures.py
{ "start": 2196, "end": 2922 }
class ____: def __repr__(self) -> str: return "-Infinity" def __hash__(self) -> int: return hash(repr(self)) def __lt__(self, other: object) -> bool: return True def __le__(self, other: object) -> bool: return True def __eq__(self, other: object) -> bool: ...
NegativeInfinityType
python
doocs__leetcode
solution/3200-3299/3290.Maximum Multiplication Score/Solution.py
{ "start": 0, "end": 358 }
class ____: def maxScore(self, a: List[int], b: List[int]) -> int: @cache def dfs(i: int, j: int) -> int: if j >= len(b): return 0 if i >= len(a) else -inf if i >= len(a): return 0 return max(dfs(i, j + 1), a[i] * b[j] + dfs(i + 1, ...
Solution
python
dagster-io__dagster
python_modules/libraries/dagster-dbt/dagster_dbt/components/dbt_project/component.py
{ "start": 2320, "end": 3696 }
class ____(dg.Resolvable): """Aligns with DbtProject.__new__.""" project_dir: str target_path: Optional[str] = None profiles_dir: Optional[str] = None profile: Optional[str] = None target: Optional[str] = None packaged_project_dir: Optional[str] = None state_path: Optional[str] = None ...
DbtProjectArgs
python
sqlalchemy__sqlalchemy
test/sql/test_delete.py
{ "start": 7270, "end": 12212 }
class ____(fixtures.TablesTest): __sparse_driver_backend__ = True @classmethod def define_tables(cls, metadata): Table( "mytable", metadata, Column("myid", Integer), Column("name", String(30)), Column("description", String(50)), ) ...
DeleteFromRoundTripTest
python
pytorch__pytorch
test/inductor/test_device_assert.py
{ "start": 539, "end": 3298 }
class ____(TestCase): @parametrize("backend", ["eager", "aot_eager", "inductor"]) def test_assert_should_throw(self, backend): def func(): a = torch.tensor([1.0, -2.0], device="cpu") result = torch.all(a > 0) assert result, "should throw" def func_inline(): ...
TestTorchDeviceAssertTrigger
python
matplotlib__matplotlib
lib/matplotlib/collections.py
{ "start": 49974, "end": 53163 }
class ____(_CollectionWithSizes): def __init__(self, verts, sizes=None, *, closed=True, **kwargs): """ Parameters ---------- verts : list of array-like The sequence of polygons [*verts0*, *verts1*, ...] where each element *verts_i* defines the vertices of pol...
PolyCollection
python
getsentry__sentry
src/sentry/monitors/processing_errors/manager.py
{ "start": 937, "end": 8238 }
class ____(Exception): pass def _get_cluster() -> RedisCluster | StrictRedis[str]: return redis.redis_clusters.get(settings.SENTRY_MONITORS_REDIS_CLUSTER) def build_set_identifier(entity_identifier: str) -> str: return f"monitors.processing_errors_set.{entity_identifier}" def build_error_identifier(uu...
InvalidProjectError
python
dagster-io__dagster
python_modules/libraries/dagster-fivetran/dagster_fivetran/components/workspace_component/component.py
{ "start": 1283, "end": 1665 }
class ____(pydantic.BaseModel): account_id: str = pydantic.Field(..., description="The Fivetran account ID.") api_key: str = pydantic.Field( ..., description="API key used to authenticate to a Fivetran instance." ) api_secret: str = pydantic.Field( ..., description="API secret used to au...
FivetranWorkspaceModel
python
numpy__numpy
numpy/_core/tests/test_scalarmath.py
{ "start": 11393, "end": 16075 }
class ____: def test_modulus_basic(self): dt = np.typecodes['AllInteger'] + np.typecodes['Float'] for op in [floordiv_and_mod, divmod]: for dt1, dt2 in itertools.product(dt, dt): for sg1, sg2 in itertools.product(_signs(dt1), _signs(dt2)): fmt = 'op: ...
TestModulus
python
allegroai__clearml
clearml/backend_api/services/v2_9/events.py
{ "start": 33034, "end": 33267 }
class ____(Response): """ Response of events.add endpoint. """ _service = "events" _action = "add" _version = "2.9" _schema = {"additionalProperties": True, "definitions": {}, "type": "object"}
AddResponse
python
getsentry__sentry
tests/snuba/api/serializers/test_group_stream.py
{ "start": 637, "end": 10792 }
class ____(APITestCase, BaseMetricsTestCase): def test_environment(self) -> None: group = self.group organization_id = group.project.organization_id environment = Environment.get_or_create(group.project, "production") with mock.patch( "sentry.api.serializers.models.grou...
StreamGroupSerializerTestCase
python
celery__celery
celery/canvas.py
{ "start": 54542, "end": 55391 }
class ____(Signature): _task_name = None _unpack_args = itemgetter('task', 'it') @classmethod def from_dict(cls, d, app=None): return cls(*cls._unpack_args(d['kwargs']), app=app, **d['options']) def __init__(self, task, it, **options): super().__init__(self._task_name, (), ...
_basemap
python
huggingface__transformers
src/transformers/models/decision_transformer/modeling_decision_transformer.py
{ "start": 27887, "end": 35871 }
class ____(DecisionTransformerPreTrainedModel): """ The model builds upon the GPT2 architecture to perform autoregressive prediction of actions in an offline RL setting. Refer to the paper for more details: https://huggingface.co/papers/2106.01345 """ def __init__(self, config): super()._...
DecisionTransformerModel
python
openai__openai-python
src/openai/types/beta/realtime/conversation_item_deleted_event.py
{ "start": 206, "end": 492 }
class ____(BaseModel): event_id: str """The unique ID of the server event.""" item_id: str """The ID of the item that was deleted.""" type: Literal["conversation.item.deleted"] """The event type, must be `conversation.item.deleted`."""
ConversationItemDeletedEvent
python
ray-project__ray
python/ray/llm/_internal/batch/stages/configs.py
{ "start": 1717, "end": 3853 }
class ____(_StageConfigBase): pass def resolve_stage_config( stage_cfg_value: Union[bool, Dict[str, Any], _StageConfigBase], stage_config_cls: Type[T], processor_defaults: Optional[Dict[str, Any]] = None, ) -> T: """Resolve a stage config value (bool | dict | StageConfig) into a typed StageConfig....
PrepareImageStageConfig
python
pytorch__pytorch
torch/_logging/_internal.py
{ "start": 44249, "end": 51950 }
class ____(Generic[_P]): def __init__( self, func: Callable[_P, str], *args: _P.args, **kwargs: _P.kwargs ) -> None: self.func = func self.args = args self.kwargs = kwargs def __str__(self) -> str: return self.func(*self.args, **self.kwargs) # Logs the time it take...
LazyString
python
huggingface__transformers
src/transformers/models/cpm/tokenization_cpm.py
{ "start": 1084, "end": 13862 }
class ____(PreTrainedTokenizer): """Runs pre-tokenization with Jieba-RS segmentation tool. It is used in CPM models.""" vocab_files_names = VOCAB_FILES_NAMES def __init__( self, vocab_file, do_lower_case=False, remove_space=True, keep_accents=False, bos_toke...
CpmTokenizer