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
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_axis43.py
{ "start": 315, "end": 1396 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_axis43.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_...
TestCompareXLSXFiles
python
tensorflow__tensorflow
tensorflow/python/framework/errors_impl.py
{ "start": 9389, "end": 9942 }
class ____(OpError): """Unknown error. An example of where this error may be returned is if a Status value received from another address space belongs to an error-space that is not known to this address space. Also, errors raised by APIs that do not return enough error information may be converted to this ...
UnknownError
python
getsentry__sentry
src/sentry/snuba/sessions_v2.py
{ "start": 14580, "end": 19163 }
class ____(InvalidParams): """ An exception that is raised when parsing orderBy, to indicate that this is only an exception in the case where we don't run a preflight query on an accepted pre-flight query field """ ... def get_now(): """Wrapper function to make it mockable in unit tests""" ...
NonPreflightOrderByException
python
sqlalchemy__sqlalchemy
test/ext/test_associationproxy.py
{ "start": 6200, "end": 15263 }
class ____(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table( "Parent", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("name", String(128)), ) ...
_CollectionOperations
python
allegroai__clearml
clearml/backend_api/services/v2_20/events.py
{ "start": 50407, "end": 50655 }
class ____(BatchRequest): """ Adds a batch of events in a single call (json-lines format, stream-friendly) """ _service = "events" _action = "add_batch" _version = "2.20" _batched_request_cls = AddRequest
AddBatchRequest
python
jazzband__django-model-utils
tests/fields.py
{ "start": 576, "end": 1026 }
class ____(models.TextField): def to_python(self, value: object) -> Any: return mutable_from_db(value) def from_db_value(self, value: object, expression: object, connection: BaseDatabaseWrapper) -> Any: return mutable_from_db(value) def get_db_prep_save(self, value: object, connection: Bas...
MutableField
python
falconry__falcon
tests/asgi/test_hello_asgi.py
{ "start": 4546, "end": 4624 }
class ____: async def on_get(self, req, resp): pass
NoStatusResource
python
google__pytype
pytype/overlays/metaclass.py
{ "start": 1475, "end": 2025 }
class ____(abstract.PyTDFunction): """Implements the add_metaclass decorator.""" @classmethod def make(cls, ctx, module): return super().make("add_metaclass", ctx, module) def call(self, node, func, args, alias_map=None): """Adds a metaclass.""" del func, alias_map # unused self.match_args(no...
AddMetaclass
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/vertex_ai/test_generative_model.py
{ "start": 8296, "end": 14763 }
class ____: def dummy_get_credentials(self): pass def setup_method(self): with mock.patch( BASE_STRING.format("GoogleBaseHook.__init__"), new=mock_base_gcp_hook_default_project_id ): self.hook = GenerativeModelHook(gcp_conn_id=TEST_GCP_CONN_ID) self.h...
TestGenerativeModelWithDefaultProjectIdHook
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-scrapegraph/tests/test_integration.py
{ "start": 8587, "end": 12023 }
class ____: """Test parameter validation and handling.""" @pytest.fixture def mock_tool_spec(self): """Create a mocked tool spec for parameter testing.""" with patch("llama_index.tools.scrapegraph.base.Client") as mock_client_class: mock_client = Mock() mock_client_c...
TestParameterValidation
python
matplotlib__matplotlib
lib/matplotlib/transforms.py
{ "start": 77453, "end": 79963 }
class ____(_BlendedMixin, Affine2DBase): """ A "blended" transform uses one transform for the *x*-direction, and another transform for the *y*-direction. This version is an optimization for the case where both child transforms are of type `Affine2DBase`. """ is_separable = True def __...
BlendedAffine2D
python
huggingface__transformers
src/transformers/models/luke/modeling_luke.py
{ "start": 1389, "end": 2636 }
class ____(BaseModelOutputWithPooling): r""" pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`): Last layer hidden-state of the first token of the sequence (classification token) further processed by a Linear layer and a Tanh activation function. entity_last_hidden_stat...
BaseLukeModelOutputWithPooling
python
prabhupant__python-ds
data_structures/linked_list/merge_list_of_linked_lists.py
{ "start": 0, "end": 754 }
class ____: def __init__(self, x): self.val = x self.next = None def merge_two_lists(l1, l2): if not l1 and not l2: return elif not l2: return l1 elif not l1: return l2 if (l1.val < l2.val): l1.next = merge_two_lists(l1.next, l2) re...
Node
python
streamlit__streamlit
lib/tests/streamlit/file_uploader_utils_test.py
{ "start": 1007, "end": 1918 }
class ____(unittest.TestCase): @parameterized.expand( [ ("png", [".png"]), (["png", ".svg", "foo"], [".png", ".svg", ".foo"]), (["jpeg"], [".jpeg", ".jpg"]), (["png", ".jpg"], [".png", ".jpg", ".jpeg"]), ([".JpG"], [".jpg", ".jpeg"]), ] ...
FileUploaderUtilsTest
python
faif__python-patterns
patterns/behavioral/chain_of_responsibility.py
{ "start": 2010, "end": 2423 }
class ____(Handler): """... With helper methods.""" def check_range(self, request: int) -> Optional[bool]: start, end = self.get_interval_from_db() if start <= request < end: print(f"request {request} handled in handler 2") return True return None @staticmet...
ConcreteHandler2
python
google__jax
tests/multiprocess/tpu_device_test.py
{ "start": 719, "end": 3068 }
class ____(jt_multiprocess.MultiProcessTest): def test_coords(self): for device in jax.local_devices(): coords = device.coords self.assertIsInstance(coords, list) self.assertLen(coords, 3) for coord in coords: self.assertIsInstance(coord, int) def test_core(self): for devic...
TpuDeviceTest
python
huggingface__transformers
tests/models/speecht5/test_modeling_speecht5.py
{ "start": 31393, "end": 35045 }
class ____: def __init__( self, parent, batch_size=13, encoder_seq_length=7, decoder_seq_length=1024, # speech is longer is_training=False, hidden_size=24, num_hidden_layers=2, num_attention_heads=2, intermediate_size=4, vocab_...
SpeechT5ForTextToSpeechTester
python
getsentry__sentry
src/sentry/auth/authenticators/totp.py
{ "start": 85, "end": 1066 }
class ____(OtpMixin): """This interface uses TOTP with an authenticator.""" type = 1 interface_id = "totp" name = _("Authenticator App") allow_rotation_in_place = True description = _( "An authenticator application that supports TOTP (like " "Google Authenticator or 1Password) c...
TotpInterface
python
apache__airflow
providers/arangodb/src/airflow/providers/arangodb/sensors/arangodb.py
{ "start": 1109, "end": 2234 }
class ____(BaseSensorOperator): """ Checks for the existence of a document which matches the given query in ArangoDB. :param collection: Target DB collection. :param query: The query to poke, or you can provide .sql file having the query :param arangodb_conn_id: The :ref:`ArangoDB connection id <ho...
AQLSensor
python
Lightning-AI__lightning
tests/tests_pytorch/callbacks/test_weight_averaging.py
{ "start": 5124, "end": 17370 }
class ____(WeightAveraging): def __init__(self, **kwargs: Any) -> None: super().__init__(avg_fn=get_swa_avg_fn(), **kwargs) self.swap_calls = 0 self.copy_calls = 0 # Record the first epoch, as if we are resuming from a checkpoint this may not be equal to 0. self.first_epoch: ...
SWATestCallback
python
jazzband__django-redis
tests/test_client.py
{ "start": 5198, "end": 7164 }
class ____: @patch("test_client.DefaultClient.make_pattern") @patch("test_client.ShardClient.__init__", return_value=None) def test_delete_pattern_calls_scan_iter_with_count_if_itersize_given( self, init_mock, make_pattern_mock, ): client = ShardClient() client._b...
TestShardClient
python
tensorflow__tensorflow
tensorflow/python/ops/ragged/string_ngrams_op_test.py
{ "start": 1192, "end": 13956 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): def test_unpadded_ngrams(self): data = [[b"aa", b"bb", b"cc", b"dd"], [b"ee", b"ff"]] data_tensor = ragged_factory_ops.constant(data) ngram_op = ragged_string_ops.ngrams( data_tensor, ngram_width=3, separator=b"|") result = sel...
StringNgramsTest
python
kamyu104__LeetCode-Solutions
Python/find-distance-in-a-binary-tree.py
{ "start": 159, "end": 1595 }
class ____(object): def findDistance(self, root, p, q): """ :type root: TreeNode :type p: int :type q: int :rtype: int """ def iter_dfs(root, p, q): result = 0 dist = [-1] stk = [(1, [root, dist])] while stk: ...
Solution
python
django__django
django/forms/models.py
{ "start": 53126, "end": 58197 }
class ____(ChoiceField): """A ChoiceField whose choices are a model QuerySet.""" # This class is a subclass of ChoiceField for purity, but it doesn't # actually use any of ChoiceField's implementation. default_error_messages = { "invalid_choice": _( "Select a valid choice. That choi...
ModelChoiceField
python
getsentry__sentry
src/sentry/workflow_engine/migrations/0093_add_action_config_index.py
{ "start": 191, "end": 1785 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # o...
Migration
python
pdm-project__pdm
src/pdm/cli/commands/update.py
{ "start": 722, "end": 8416 }
class ____(BaseCommand): """Update package(s) in pyproject.toml""" arguments = ( *BaseCommand.arguments, groups_group, install_group, lockfile_option, frozen_lockfile_option, save_strategy_group, override_option, update_strategy_group, pre...
Command
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 586047, "end": 586679 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field( sgqlc.types.list_of("RepositoryCollaboratorEdge"), graphql_name="edges" ) node...
RepositoryCollaboratorConnection
python
pypa__setuptools
setuptools/_vendor/wheel/vendored/packaging/specifiers.py
{ "start": 1149, "end": 2843 }
class ____(metaclass=abc.ABCMeta): @abc.abstractmethod def __str__(self) -> str: """ Returns the str representation of this Specifier-like object. This should be representative of the Specifier itself. """ @abc.abstractmethod def __hash__(self) -> int: """ ...
BaseSpecifier
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/strategies.py
{ "start": 19373, "end": 19791 }
class ____(LoaderStrategy): """Relationship loader that makes no change to the object's state. Compared to NoLoader, this loader does not initialize the collection/attribute to empty/none; the usual default LazyLoader will take effect. """ @log.class_logger @relationships.RelationshipProperty.st...
_DoNothingLoader
python
ray-project__ray
python/ray/tune/search/searcher.py
{ "start": 520, "end": 15583 }
class ____: """Abstract class for wrapping suggesting algorithms. Custom algorithms can extend this class easily by overriding the `suggest` method provide generated parameters for the trials. Any subclass that implements ``__init__`` must also call the constructor of this class: ``super(Subclass,...
Searcher
python
pyinstaller__pyinstaller
bootloader/waflib/Runner.py
{ "start": 680, "end": 1486 }
class ____(object): def __init__(self): self.lst = [] def __len__(self): return len(self.lst) def __iter__(self): return iter(self.lst) def __str__(self): return 'PriorityTasks: [%s]' % '\n '.join(str(x) for x in self.lst) def clear(self): self.lst = [] ...
PriorityTasks
python
dask__distributed
distributed/comm/core.py
{ "start": 8146, "end": 8695 }
class ____(Listener): def __init__(self) -> None: self.__comms: set[Comm] = set() async def on_connection( self, comm: Comm, handshake_overrides: dict[str, Any] | None = None ) -> None: self.__comms.add(comm) try: return await super().on_connection(comm, handshak...
BaseListener
python
allegroai__clearml
clearml/backend_api/services/v2_23/workers.py
{ "start": 90386, "end": 90963 }
class ____(Response): """ Response of workers.unregister endpoint. """ _service = "workers" _action = "unregister" _version = "2.23" _schema = {"definitions": {}, "properties": {}, "type": "object"} response_mapping = { GetAllRequest: GetAllResponse, RegisterRequest: RegisterResp...
UnregisterResponse
python
numba__numba
numba/tests/test_typeinfer.py
{ "start": 1033, "end": 2200 }
class ____(unittest.TestCase): def test_arg_ret_casting(self): def foo(x): return x args = (i32,) return_type = f32 cfunc = njit(return_type(*args))(foo) cres = cfunc.overloads[args] self.assertTrue(isinstance(cfunc(123), float)) self.assertEqual(...
TestArgRetCasting
python
getsentry__sentry-python
sentry_sdk/integrations/ariadne.py
{ "start": 1081, "end": 5834 }
class ____(Integration): identifier = "ariadne" @staticmethod def setup_once(): # type: () -> None version = package_version("ariadne") _check_minimum_version(AriadneIntegration, version) ignore_logger("ariadne") _patch_graphql() def _patch_graphql(): # type:...
AriadneIntegration
python
getsentry__sentry
tests/sentry/web/frontend/test_auth_channel_login.py
{ "start": 2932, "end": 3838 }
class ____(TestCase): def create_auth_provider(self, partner_org_id, sentry_org_id): config_data = FlyOAuth2Provider.build_config(resource={"id": partner_org_id}) AuthProvider.objects.create( organization_id=sentry_org_id, provider="fly-non-partner", config=config_data ) def...
AuthNonPartnerOrganizationChannelLoginTest
python
PrefectHQ__prefect
src/prefect/server/schemas/responses.py
{ "start": 21641, "end": 21781 }
class ____(BaseModel): results: list[FlowRunResponse] count: int limit: int pages: int page: int
FlowRunPaginationResponse
python
openai__openai-python
src/openai/types/responses/response_output_refusal.py
{ "start": 198, "end": 388 }
class ____(BaseModel): refusal: str """The refusal explanation from the model.""" type: Literal["refusal"] """The type of the refusal. Always `refusal`."""
ResponseOutputRefusal
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1405396, "end": 1405994 }
class ____(sgqlc.types.Type, Node, AuditEntry, RepositoryAuditEntryData, OrganizationAuditEntryData): """Audit log entry for a repo.change_merge_setting event.""" __schema__ = github_schema __field_names__ = ("is_enabled", "merge_type") is_enabled = sgqlc.types.Field(Boolean, graphql_name="isEnabled") ...
RepoChangeMergeSettingAuditEntry
python
doocs__leetcode
solution/1100-1199/1185.Day of the Week/Solution.py
{ "start": 0, "end": 146 }
class ____: def dayOfTheWeek(self, day: int, month: int, year: int) -> str: return datetime.date(year, month, day).strftime('%A')
Solution
python
PrefectHQ__prefect
tests/cli/test_work_queues.py
{ "start": 343, "end": 3056 }
class ____: def test_create_work_queue(self): invoke_and_assert( command="work-queue create q-name", expected_output_contains=[ "Created work queue with properties:", "name - 'q-name'", ], expected_code=0, ) def tes...
TestCreateWorkQueue
python
sphinx-doc__sphinx
tests/test_markup/test_markup.py
{ "start": 2503, "end": 2583 }
class ____(HTML5Translator, ForgivingTranslator): pass
ForgivingHTMLTranslator
python
numba__numba
numba/core/ir.py
{ "start": 51901, "end": 52254 }
class ____(EqualityCheckMixin): _singleton = None def __new__(cls): obj = cls._singleton if obj is not None: return obj else: obj = object.__new__(cls) cls._singleton = obj return obj def __repr__(self): return "Undefined" UNDE...
UndefinedType
python
Lightning-AI__lightning
src/lightning/pytorch/plugins/precision/bitsandbytes.py
{ "start": 755, "end": 1592 }
class ____(Precision, FabricBNBPrecision): """Plugin for quantizing weights with `bitsandbytes <https://github.com/bitsandbytes-foundation/bitsandbytes>`__. .. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature. .. note:: The optimizer is not automatically replaced wit...
BitsandbytesPrecision
python
dask__dask
dask/dataframe/dask_expr/_indexing.py
{ "start": 997, "end": 1066 }
class ____: def __init__(self, obj): self.obj = obj
Indexer
python
getsentry__sentry
tests/sentry/seer/fetch_issues/test_by_error_type.py
{ "start": 408, "end": 21410 }
class ____(APITestCase, SnubaTestCase): def test_simple(self) -> None: release = self.create_release(project=self.project, version="1.0.0") repo = self.create_repo( project=self.project, name="getsentry/sentryA", provider="integrations:github", externa...
TestFetchIssuesByErrorType
python
numba__llvmlite
llvmlite/ir/types.py
{ "start": 15625, "end": 17716 }
class ____(Aggregate): """ The base type for heterogenous struct types. """ _packed = False @property def packed(self): """ A boolean attribute that indicates whether the structure uses packed layout. """ return self._packed @packed.setter def pa...
BaseStructType
python
joke2k__faker
tests/providers/test_currency.py
{ "start": 15517, "end": 15942 }
class ____: """Test pt_BR currency provider""" num_samples = 100 @classmethod def setup_class(cls): from faker.providers.currency.pt_BR import Provider as PtBrCurrencyProvider cls.provider = PtBrCurrencyProvider def test_pricetag(self, faker, num_samples): for _ in range(...
TestPtBr
python
sympy__sympy
sympy/sets/sets.py
{ "start": 37855, "end": 44098 }
class ____(Set, LatticeOp): """ Represents a union of sets as a :class:`Set`. Parameters ========== args : iterable[Set] The input sets to be united. evaluate : bool, optional If True (default from sympy.core.parameters.global_parameters.evaluate), the constructor simpl...
Union
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/elements.py
{ "start": 113710, "end": 116539 }
class ____(ColumnElement[_T]): """Represent a ``CASE`` expression. :class:`.Case` is produced using the :func:`.case` factory function, as in:: from sqlalchemy import case stmt = select(users_table).where( case( (users_table.c.name == "wendy", "W"), ...
Case
python
skorch-dev__skorch
skorch/callbacks/logging.py
{ "start": 34232, "end": 40915 }
class ____(Callback): """Logs results from history and artifact to Mlflow "MLflow is an open source platform for managing the end-to-end machine learning lifecycle" (:doc:`mlflow:index`) Use this callback to automatically log your metrics and create/log artifacts to mlflow. The best way to lo...
MlflowLogger
python
getsentry__sentry
src/sentry/workflow_engine/migrations/0075_add_index_to_dcg_action.py
{ "start": 155, "end": 1493 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # o...
Migration
python
getsentry__sentry
tests/sentry/workflow_engine/handlers/detector/test_stateful.py
{ "start": 510, "end": 3736 }
class ____(TestCase): def setUp(self) -> None: self.detector = self.create_detector( name="Stateful Detector", project=self.project, ) def _get_full_detector(self) -> Detector: """ Fetches the full detector with its workflow condition group and conditions...
TestStatefulDetectorHandler
python
pytorch__pytorch
torch/testing/_internal/distributed/ddp_under_dist_autograd_test.py
{ "start": 3249, "end": 3643 }
class ____(nn.Module): def __init__(self, d_in: int, d_out: int): gLogger.info("Initing RemoteNet with %s %s", d_in, d_out) super().__init__() self.fc = getLinear(d_in, d_out) self.relu = nn.ReLU() def forward(self, input: torch.Tensor): gLogger.debug("Running RemoteNet....
RemoteNet
python
python__mypy
mypyc/irbuild/for_helpers.py
{ "start": 30926, "end": 34848 }
class ____(ForGenerator): """Generate optimized IR for a for loop over a sequence. Supports iterating in both forward and reverse. """ length_reg: Value | AssignmentTarget | None def init( self, expr_reg: Value, target_type: RType, reverse: bool, length: Value | None = None ) -> None:...
ForSequence
python
allegroai__clearml
clearml/backend_api/services/v2_13/tasks.py
{ "start": 382647, "end": 384367 }
class ____(Response): """ Response of tasks.stop_many endpoint. :param stopped: Number of tasks stopped :type stopped: int """ _service = "tasks" _action = "stop_many" _version = "2.13" _schema = { "definitions": {}, "failures": { "item": { ...
StopManyResponse
python
getsentry__sentry
tests/sentry/integrations/aws_lambda/test_utils.py
{ "start": 620, "end": 985 }
class ____(TestCase): def test_simple(self) -> None: arn = ( "arn:aws:cloudformation:us-east-2:599817902985:stack/" "Sentry-Monitoring-Stack/e42083d0-3e3f-11eb-b66a-0ac9b5db7f30" ) parsed = parse_arn(arn) assert parsed["account"] == "599817902985" asse...
ParseArnTest
python
kamyu104__LeetCode-Solutions
Python/count-the-number-of-houses-at-a-certain-distance-i.py
{ "start": 66, "end": 1194 }
class ____(object): def countOfPairs(self, n, x, y): """ :type n: int :type x: int :type y: int :rtype: List[int] """ x, y = x-1, y-1 if x > y: x, y = y, x diff = [0]*n for i in xrange(n): diff[0] += 1+1 ...
Solution
python
pypa__pipenv
pipenv/vendor/click/_textwrap.py
{ "start": 75, "end": 1353 }
class ____(textwrap.TextWrapper): def _handle_long_word( self, reversed_chunks: t.List[str], cur_line: t.List[str], cur_len: int, width: int, ) -> None: space_left = max(width - cur_len, 1) if self.break_long_words: last = reversed_chunks[-1] ...
TextWrapper
python
ansible__ansible
test/integration/targets/lookup-option-name/lookup_plugins/non_terms_posargs.py
{ "start": 84, "end": 514 }
class ____(LookupBase): """Test plugin whose run method has a kwarg named terms that is not the first positional arg.""" def run(self, not_terms, variables=None, terms=None, **kwargs): # pylint:disable=arguments-renamed """Echo back a dictionary with the first posarg and the terms kwarg to ensure we di...
LookupModule
python
huggingface__transformers
src/transformers/models/granitemoehybrid/modeling_granitemoehybrid.py
{ "start": 42401, "end": 45431 }
class ____(nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer` def __init__(self, config: GraniteMoeHybridConfig, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings ...
GraniteMoeHybridRotaryEmbedding
python
ansible__ansible
test/units/plugins/inventory/test_inventory.py
{ "start": 1095, "end": 3857 }
class ____(unittest.TestCase): patterns = { 'a': ['a'], 'a, b': ['a', 'b'], 'a , b': ['a', 'b'], ' a,b ,c[1:2] ': ['a', 'b', 'c[1:2]'], '9a01:7f8:191:7701::9': ['9a01:7f8:191:7701::9'], '9a01:7f8:191:7701::9,9a01:7f8:191:7701::9': ['9a01:7f8:191:7701::9', '9a01:7f8:1...
TestInventory
python
PyCQA__pylint
tests/functional/a/arguments_differ.py
{ "start": 3213, "end": 3282 }
class ____: def test(self, first, second): pass
Positional
python
ray-project__ray
python/ray/llm/_internal/batch/stages/sglang_engine_stage.py
{ "start": 488, "end": 631 }
class ____(str, Enum): """The type of task to run on the SGLang engine.""" """Generate text.""" GENERATE = "generate"
SGLangTaskType
python
PyCQA__pylint
tests/functional/r/redefined/redefined_outer_name_type_checking.py
{ "start": 225, "end": 809 }
class ____: def func(self, stuff: defaultdict, my_deque: deque): # These imports make the definition work. # pylint: disable=import-outside-toplevel from collections import defaultdict from collections import deque obj = defaultdict() obj2 = deque() obj.updat...
Cls
python
pytest-dev__pytest
src/_pytest/recwarn.py
{ "start": 8650, "end": 13386 }
class ____(WarningsRecorder): def __init__( self, expected_warning: type[Warning] | tuple[type[Warning], ...] = Warning, match_expr: str | re.Pattern[str] | None = None, *, _ispytest: bool = False, ) -> None: check_ispytest(_ispytest) super().__init__(_isp...
WarningsChecker
python
tensorflow__tensorflow
tensorflow/python/profiler/internal/flops_registry_test.py
{ "start": 1058, "end": 2093 }
class ____(test.TestCase): @test_util.run_v1_only('Test requires a Graph and NodeDef inspection') def testSimpleStatistics(self): a = variables.Variable(random_ops.random_normal([25, 16])) b = variables.Variable(random_ops.random_normal([16, 9])) math_ops.matmul(a, b) g = ops.get_default_graph() ...
FlopsRegistryTest
python
kamyu104__LeetCode-Solutions
Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py
{ "start": 30, "end": 382 }
class ____(object): def maxProfit(self, prices, fee): """ :type prices: List[int] :type fee: int :rtype: int """ cash, hold = 0, -prices[0] for i in xrange(1, len(prices)): cash = max(cash, hold+prices[i]-fee) hold = max(hold, cash-pric...
Solution
python
getsentry__sentry
src/sentry/replays/endpoints/project_replay_jobs_delete.py
{ "start": 1921, "end": 2102 }
class ____(serializers.Serializer): data = ReplayDeletionJobCreateDataSerializer(required=True) # type: ignore[assignment] @region_silo_endpoint
ReplayDeletionJobCreateSerializer
python
plotly__plotly.py
plotly/graph_objs/violin/selected/_marker.py
{ "start": 233, "end": 3579 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "violin.selected" _path_str = "violin.selected.marker" _valid_props = {"color", "opacity", "size"} @property def color(self): """ Sets the marker color of selected points. The 'color' property is a color and may be spe...
Marker
python
conda__conda
conda/plugins/types.py
{ "start": 1549, "end": 1989 }
class ____: """ Base class for all conda plugins. """ #: User-facing name of the plugin used for selecting & filtering plugins and error messages. name: str def __post_init__(self): try: self.name = self.name.lower().strip() except AttributeError: # Attr...
CondaPlugin
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_table01.py
{ "start": 315, "end": 857 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("table01.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with tables.""" workbook = Workbook(se...
TestCompareXLSXFiles
python
dagster-io__dagster
python_modules/dagster/dagster/_core/remote_representation/code_location.py
{ "start": 12826, "end": 24239 }
class ____(CodeLocation): def __init__(self, origin: InProcessCodeLocationOrigin, instance: DagsterInstance): from dagster._grpc.server import LoadedRepositories self._origin = check.inst_param(origin, "origin", InProcessCodeLocationOrigin) self._instance = instance loadable_target...
InProcessCodeLocation
python
eventlet__eventlet
tests/timeout_with_statement_test.py
{ "start": 254, "end": 4136 }
class ____(LimitedTestCase): def test_cancellation(self): # Nothing happens if with-block finishes before the timeout expires t = Timeout(DELAY * 2) sleep(0) # make it pending assert t.pending, repr(t) with t: assert t.pending, repr(t) sleep(DELAY) ...
Test
python
walkccc__LeetCode
solutions/684. Redundant Connection/684.py
{ "start": 540, "end": 762 }
class ____: def findRedundantConnection(self, edges: list[list[int]]) -> list[int]: uf = UnionFind(len(edges) + 1) for edge in edges: u, v = edge if not uf.unionByRank(u, v): return edge
Solution
python
pikepdf__pikepdf
src/pikepdf/models/_content_stream.py
{ "start": 873, "end": 5147 }
class ____(Exception): """Error when parsing a PDF content stream.""" def __init__(self, message=None, line=None): if not message: message = f"Error encoding content stream at line {line}" super().__init__(message) self.line = line def parse_content_stream( page_or_str...
PdfParsingError
python
google__pytype
pytype/tests/test_calls1.py
{ "start": 145, "end": 2802 }
class ____(test_base.BaseTest): """Tests for checking function calls.""" def test_optional(self): with test_utils.Tempdir() as d: d.create_file( "mod.pyi", """ def foo(x: int, y: int = ..., z: int = ...) -> int: ... """, ) self.Check( """ im...
CallsTest
python
tox-dev__tox
src/tox/execute/api.py
{ "start": 2923, "end": 5004 }
class ____(ABC): """Abstract API for execution of a tox environment.""" _option_class: type[ExecuteOptions] = ExecuteOptions def __init__(self, colored: bool) -> None: # noqa: FBT001 self._colored = colored @contextmanager def call( self, request: ExecuteRequest, ...
Execute
python
django__django
tests/admin_inlines/admin.py
{ "start": 8227, "end": 8377 }
class ____(admin.TabularInline): model = SomeChildModel form = SomeChildModelForm readonly_fields = ("readonly_field",)
SomeChildModelInline
python
MorvanZhou__Reinforcement-learning-with-tensorflow
experiments/2D_car/DDPG.py
{ "start": 6811, "end": 9793 }
class ____(object): def __init__(self, capacity, dims): self.capacity = capacity self.data = np.zeros((capacity, dims)) self.pointer = 0 def store_transition(self, s, a, r, s_): transition = np.hstack((s, a, [r], s_)) index = self.pointer % self.capacity # replace the o...
Memory
python
doocs__leetcode
solution/3600-3699/3613.Minimize Maximum Component Cost/Solution.py
{ "start": 0, "end": 546 }
class ____: def minCost(self, n: int, edges: List[List[int]], k: int) -> int: def find(x: int) -> int: if p[x] != x: p[x] = find(p[x]) return p[x] if k == n: return 0 edges.sort(key=lambda x: x[2]) cnt = n p = list(range(n)...
Solution
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataplex.py
{ "start": 55291, "end": 59816 }
class ____(GoogleCloudBaseOperator): """ Creates a DataScan Data Profile resource. :param project_id: Required. The ID of the Google Cloud project that the lake belongs to. :param region: Required. The ID of the Google Cloud region that the lake belongs to. :param body: Required. The Request body ...
DataplexCreateOrUpdateDataProfileScanOperator
python
dagster-io__dagster
python_modules/libraries/dagster-powerbi/dagster_powerbi/translator.py
{ "start": 2212, "end": 2509 }
class ____(Enum): """Enum representing each object in PowerBI's ontology, generically referred to as "content" by the API.""" DASHBOARD = "dashboard" REPORT = "report" SEMANTIC_MODEL = "semantic_model" DATA_SOURCE = "data_source" @whitelist_for_serdes @record
PowerBIContentType
python
HypothesisWorks__hypothesis
hypothesis-python/tests/patching/callables.py
{ "start": 760, "end": 1291 }
class ____: @example(n=0, label="whatever") @given(st.integers(), st.text()) def mth(self, n, label): """Indented method with existing example decorator.""" @given(st.integers()) @example(x=2).via("not a literal when repeated " * 2) @example(x=1).via("covering example") def covered(x): """A te...
Cases
python
dask__distributed
distributed/_async_taskgroup.py
{ "start": 830, "end": 1239 }
class ____(RuntimeError): pass def _delayed(corofunc: Callable[P, Coro[T]], delay: float) -> Callable[P, Coro[T]]: """Decorator to delay the evaluation of a coroutine function by the given delay in seconds.""" async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: await asyncio.sleep(delay) ...
AsyncTaskGroupClosedError
python
mlflow__mlflow
mlflow/sentence_transformers/__init__.py
{ "start": 19716, "end": 21696 }
class ____: def __init__(self, model, task=None): self.model = model self.task = task def get_raw_model(self): """ Returns the underlying model. """ return self.model def predict(self, sentences, params: dict[str, Any] | None = None): """ Arg...
_SentenceTransformerModelWrapper
python
redis__redis-py
tests/test_asyncio/test_multidb/test_command_executor.py
{ "start": 600, "end": 7084 }
class ____: @pytest.mark.asyncio @pytest.mark.parametrize( "mock_db,mock_db1,mock_db2", [ ( {"weight": 0.2, "circuit": {"state": CBState.CLOSED}}, {"weight": 0.7, "circuit": {"state": CBState.CLOSED}}, {"weight": 0.5, "circuit": {"state...
TestDefaultCommandExecutor
python
django__django
django/contrib/messages/views.py
{ "start": 38, "end": 524 }
class ____: """ Add a success message on successful form submission. """ success_message = "" def form_valid(self, form): response = super().form_valid(form) success_message = self.get_success_message(form.cleaned_data) if success_message: messages.success(self....
SuccessMessageMixin
python
pytorch__pytorch
test/onnx/internal/test_registration.py
{ "start": 6581, "end": 9823 }
class ____(common_utils.TestCase): def tearDown(self) -> None: registration.registry._registry.pop("test::test_op", None) def test_onnx_symbolic_registers_function(self): self.assertFalse(registration.registry.is_registered_op("test::test_op", 9)) @registration.onnx_symbolic("test::tes...
TestRegistrationDecorators
python
davidhalter__jedi
jedi/inference/cache.py
{ "start": 2216, "end": 4191 }
class ____(type): """ This is basically almost the same than the decorator above, it just caches class initializations. Either you do it this way or with decorators, but with decorators you lose class access (isinstance, etc). """ @inference_state_as_method_param_cache() def __call__(self, *...
CachedMetaClass
python
allegroai__clearml
clearml/backend_api/session/request.py
{ "start": 1667, "end": 3460 }
class ____(Request): _batched_request_cls = abc.abstractproperty() _schema_errors = (SchemaError, ValidationError, FormatError, Unresolvable) def __init__( self, requests: Union[List[Request], Tuple[Request]], validate_requests: bool = False, allow_raw_requests: bool = True...
BatchRequest
python
doocs__leetcode
solution/2300-2399/2398.Maximum Number of Robots Within Budget/Solution.py
{ "start": 0, "end": 605 }
class ____: def maximumRobots( self, chargeTimes: List[int], runningCosts: List[int], budget: int ) -> int: q = deque() ans = s = l = 0 for r, (t, c) in enumerate(zip(chargeTimes, runningCosts)): s += c while q and chargeTimes[q[-1]] <= t: ...
Solution
python
openai__openai-python
src/openai/types/graders/label_model_grader_param.py
{ "start": 1311, "end": 1715 }
class ____(TypedDict, total=False): content: Required[InputContent] """Inputs to the model - can contain template strings.""" role: Required[Literal["user", "assistant", "system", "developer"]] """The role of the message input. One of `user`, `assistant`, `system`, or `developer`. """ typ...
Input
python
ray-project__ray
rllib/connectors/common/agent_to_module_mapping.py
{ "start": 480, "end": 12048 }
class ____(ConnectorV2): """ConnectorV2 that performs mapping of data from AgentID based to ModuleID based. Note: This is one of the default env-to-module or Learner ConnectorV2 pieces that are added automatically by RLlib into every env-to-module/Learner connector pipeline, unless `config.add_default_...
AgentToModuleMapping
python
coleifer__peewee
peewee.py
{ "start": 160775, "end": 161070 }
class ____(AutoField): field_type = 'INT GENERATED BY DEFAULT AS IDENTITY' def __init__(self, generate_always=False, **kwargs): if generate_always: self.field_type = 'INT GENERATED ALWAYS AS IDENTITY' super(IdentityField, self).__init__(**kwargs)
IdentityField
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-cerebras/llama_index/llms/cerebras/base.py
{ "start": 98, "end": 1347 }
class ____(OpenAILike): """ Cerebras LLM. Examples: `pip install llama-index-llms-cerebras` ```python from llama_index.llms.cerebras import Cerebras # Set up the Cerebras class with the required model and API key llm = Cerebras(model="llama-3.3-70b", api_key="your_...
Cerebras
python
tensorflow__tensorflow
tensorflow/python/ops/resource_variable_ops.py
{ "start": 92050, "end": 97005 }
class ____(BaseResourceVariable): """A variable with no initializer.""" def __init__( # pylint: disable=super-init-not-called self, trainable=None, caching_device=None, name=None, shape=None, dtype=None, constraint=None, synchronization=None, aggregation=None,...
UninitializedVariable
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_axis12.py
{ "start": 315, "end": 1394 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_axis12.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_...
TestCompareXLSXFiles
python
weaviate__weaviate-python-client
weaviate/collections/classes/grpc.py
{ "start": 4720, "end": 5001 }
class ____(_WeaviateInput): """Define how the query's RAG capabilities should be performed.""" single_prompt: Optional[str] = Field(default=None) grouped_task: Optional[str] = Field(default=None) grouped_properties: Optional[List[str]] = Field(default=None)
Generate
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 639642, "end": 641086 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "check_run_count", "check_run_counts_by_state", "edges", "nodes", "page_info", "status_context_count", "status_con...
StatusCheckRollupContextConnection