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
langchain-ai__langchain
libs/core/langchain_core/messages/system.py
{ "start": 1728, "end": 2140 }
class ____(SystemMessage, BaseMessageChunk): """System Message chunk.""" # Ignoring mypy re-assignment here since we're overriding the value # to make sure that the chunk variant can be discriminated from the # non-chunk variant. type: Literal["SystemMessageChunk"] = "SystemMessageChunk" # type: i...
SystemMessageChunk
python
numba__numba
numba/tests/test_ufuncs.py
{ "start": 11215, "end": 32839 }
class ____(BasicUFuncTest, TestCase): def basic_int_ufunc_test(self, name=None): skip_inputs = [ types.float32, types.float64, types.Array(types.float32, 1, 'C'), types.Array(types.float64, 1, 'C'), ] self.basic_ufunc_test(name, skip_inputs=ski...
TestUFuncs
python
dagster-io__dagster
python_modules/libraries/dagster-github/dagster_github/resources.py
{ "start": 16005, "end": 19202 }
class ____(ConfigurableResource): """A resource configuration class for GitHub integration. This class provides configuration fields for setting up a GitHub Application, including the application ID, private RSA key, installation ID, and hostname. Args: github_app_id (int): The GitHub Applicat...
GithubResource
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/operators/bedrock.py
{ "start": 17116, "end": 25471 }
class ____(AwsBaseOperator[BedrockAgentHook]): """ Create a knowledge base that contains data sources used by Amazon Bedrock LLMs and Agents. To create a knowledge base, you must first set up your data sources and configure a supported vector store. .. seealso:: For more information on how to ...
BedrockCreateKnowledgeBaseOperator
python
wandb__wandb
wandb/sdk/launch/runner/kubernetes_runner.py
{ "start": 8889, "end": 12116 }
class ____(AbstractRun): """Run submitted to a CRD backend, e.g. Volcano.""" def __init__( self, group: str, version: str, plural: str, name: str, namespace: str, core_api: CoreV1Api, custom_api: CustomObjectsApi, ) -> None: """Create ...
CrdSubmittedRun
python
pypa__pipenv
pipenv/vendor/pythonfinder/finders/asdf_finder.py
{ "start": 314, "end": 2208 }
class ____(PathFinder): """ Finder that searches for Python in asdf installations. """ def __init__( self, data_dir: str | Path | None = None, ignore_unsupported: bool = True, ): """ Initialize a new AsdfFinder. Args: data_dir: The data d...
AsdfFinder
python
django__django
tests/queries/tests.py
{ "start": 131510, "end": 135036 }
class ____(TestCase): """ Some regressiontests for ticket #17600. Some of these likely duplicate other existing tests. """ @classmethod def setUpTestData(cls): # Create a few Orders. cls.o1 = Order.objects.create(pk=1) cls.o2 = Order.objects.create(pk=2) cls.o3 =...
ExcludeTest17600
python
langchain-ai__langchain
libs/core/langchain_core/messages/content.py
{ "start": 8469, "end": 9712 }
class ____(TypedDict): """Represents an AI's request to call a tool. Example: ```python {"name": "foo", "args": {"a": 1}, "id": "123"} ``` This represents a request to call the tool named "foo" with arguments {"a": 1} and an identifier of "123". !!! note "Factory f...
ToolCall
python
tensorflow__tensorflow
tensorflow/python/grappler/auto_mixed_precision_test.py
{ "start": 10499, "end": 34736 }
class ____(test.TestCase, parameterized.TestCase): """Tests the Grappler auto mixed precision optimizer.""" IGNORE_PERF_VAR = 'TF_AUTO_MIXED_PRECISION_GRAPH_REWRITE_IGNORE_PERFORMANCE' # TODO(benbarsdell): Add tests for eager mode with a tf.function. def setUp(self): super(AutoMixedPrecisionTest, self).se...
AutoMixedPrecisionTest
python
catalyst-team__catalyst
examples/detection/models/yolo_x.py
{ "start": 1258, "end": 1820 }
class ____(nn.Module): """Depthwise Conv + Conv""" def __init__(self, in_channels, out_channels, ksize, stride=1, act="silu"): super().__init__() self.dconv = BaseConv( in_channels, in_channels, ksize=ksize, stride=stride, groups=in_ch...
DWConv
python
mlflow__mlflow
tests/webhooks/test_e2e.py
{ "start": 2614, "end": 32943 }
class ____: def __init__(self, base: str) -> None: self._base = base def get_url(self, endpoint: str) -> str: return f"{self._base}{endpoint}" def reset(self) -> None: """Reset both logs and counters""" resp = requests.post(self.get_url("/reset")) resp.raise_for_sta...
AppClient
python
google__pytype
pytype/datatypes.py
{ "start": 3479, "end": 4362 }
class ____(dict[_K, _V]): """A dict that tracks access of its original items.""" def __init__(self, d=()): super().__init__(d) self.accessed_subset = {} def __getitem__(self, k): v = super().__getitem__(k) if k not in self.accessed_subset: self.accessed_subset[k] = v return v def __...
AccessTrackingDict
python
ray-project__ray
python/ray/autoscaler/_private/_azure/node_provider.py
{ "start": 1668, "end": 37276 }
class ____(NodeProvider): """Node Provider for Azure This provider assumes Azure credentials are set by running ``az login`` and the default subscription is configured through ``az account`` or set in the ``provider`` field of the autoscaler configuration. Nodes may be in one of three states: {pen...
AzureNodeProvider
python
py-pdf__pypdf
pypdf/generic/_viewerpref.py
{ "start": 1693, "end": 6758 }
class ____(DictionaryObject): def __init__(self, obj: Optional[DictionaryObject] = None) -> None: super().__init__(self) if not is_null_or_none(obj): self.update(obj.items()) # type: ignore try: self.indirect_reference = obj.indirect_reference # type: ignore ...
ViewerPreferences
python
getsentry__sentry
tests/sentry/workflow_engine/migration_helpers/test_migrate_alert_rule.py
{ "start": 35591, "end": 38289 }
class ____(BaseMetricAlertMigrationTest): def setUp(self) -> None: self.metric_alert = self.create_alert_rule() self.alert_rule_trigger = self.create_alert_rule_trigger( alert_rule=self.metric_alert, label="critical" ) self.create_migrated_metric_alert_objects(self.metric...
DualDeleteAlertRuleTriggerTest
python
PrefectHQ__prefect
src/prefect/utilities/importtools.py
{ "start": 7598, "end": 7975 }
class ____(NamedTuple): """ A definition for the `AliasedModuleFinder`. Args: alias: The import name to create real: The import name of the module to reference for the alias callback: A function to call when the alias module is loaded """ alias: str real: str callba...
AliasedModuleDefinition
python
PrefectHQ__prefect
src/prefect/server/orchestration/core_policy.py
{ "start": 38450, "end": 40435 }
class ____(TaskRunOrchestrationRule): """ Rejects failed states and schedules a retry if the retry limit has not been reached. This rule rejects transitions into a failed state if `retries` has been set, the run count has not reached the specified limit, and the client asserts it is a retriable tas...
RetryFailedTasks
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_with_poly.py
{ "start": 5482, "end": 5560 }
class ____(_WithPolymorphicBase, _PolymorphicJoins): pass
PolymorphicJoinsTest
python
kamyu104__LeetCode-Solutions
Python/smallest-string-with-swaps.py
{ "start": 512, "end": 1227 }
class ____(object): def smallestStringWithSwaps(self, s, pairs): """ :type s: str :type pairs: List[List[int]] :rtype: str """ union_find = UnionFind(len(s)) for x,y in pairs: union_find.union_set(x, y) components = collections.defaultdict...
Solution
python
altair-viz__altair
altair/vegalite/v6/schema/channels.py
{ "start": 354205, "end": 360782 }
class ____(DatumChannelMixin, core.DatumDef): """ LongitudeDatum schema wrapper. Parameters ---------- bandPosition : float Relative position on a band of a stacked, binned, time unit, or band scale. For example, the marks will be positioned at the beginning of the band if set to ``...
LongitudeDatum
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 66032, "end": 68556 }
class ____(Blockwise): _projection_passthrough = True _filter_passthrough = True _parameters = ["frame", "predicate"] operation = operator.getitem _preserves_partitioning_information = True def _simplify_up(self, parent, dependents): if isinstance(self.predicate, Or): result...
Filter
python
apache__airflow
providers/github/tests/unit/github/sensors/test_github.py
{ "start": 1275, "end": 3546 }
class ____: # TODO: Potential performance issue, converted setup_class to a setup_connections function level fixture @pytest.fixture(autouse=True) def setup_connections(self, create_connection_without_db): create_connection_without_db( Connection( conn_id="github_default"...
TestGithubSensor
python
Farama-Foundation__Gymnasium
gymnasium/wrappers/common.py
{ "start": 16828, "end": 21287 }
class ____( gym.Wrapper[ObsType, ActType, ObsType, ActType], gym.utils.RecordConstructorArgs ): """This wrapper will keep track of cumulative rewards and episode lengths. At the end of an episode, the statistics of the episode will be added to ``info`` using the key ``episode``. If using a vectorized e...
RecordEpisodeStatistics
python
django__django
django/urls/converters.py
{ "start": 339, "end": 558 }
class ____: regex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" def to_python(self, value): return uuid.UUID(value) def to_url(self, value): return str(value)
UUIDConverter
python
airbytehq__airbyte
airbyte-integrations/connectors/source-salesforce/source_salesforce/streams.py
{ "start": 16465, "end": 17426 }
class ____(HttpSubStream): state_converter = IsoMillisConcurrentStreamStateConverter(is_sequential_state=False) SLICE_BATCH_SIZE = 200 def stream_slices( self, sync_mode: SyncMode, cursor_field: Optional[List[str]] = None, stream_state: Optional[Mapping[str, Any]] = None ) -> Iterable[Optional[...
BatchedSubStream
python
PyCQA__pylint
tests/functional/d/deprecated/deprecated_decorators.py
{ "start": 277, "end": 487 }
class ____: def __init__(self): self._baz = 84 def method(self): return self._baz @method.setter # Invalid decorator def method(self, value): self._baz = value
Foo
python
django__django
tests/fixtures_regress/models.py
{ "start": 1456, "end": 1533 }
class ____(Article): pass # Models to regression test #22421
SpecialArticle
python
huggingface__transformers
src/transformers/models/autoformer/modeling_autoformer.py
{ "start": 18679, "end": 19188 }
class ____(nn.Module): """ Special designed layer normalization for the seasonal part, calculated as: AutoformerLayernorm(x) = nn.LayerNorm(x) - torch.mean(nn.LayerNorm(x)) """ def __init__(self, config: AutoformerConfig): super().__init__() self.layernorm = nn.LayerNorm(config.d_mo...
AutoformerLayernorm
python
dagster-io__dagster
docs/sphinx/_ext/sphinx-mdx-builder/tests/dummy_module.py
{ "start": 1055, "end": 1884 }
class ____: """A generic wrapper class that demonstrates common wrapping patterns.""" def __init__(self, func, pattern_name="func"): # Store the function using different attribute patterns if pattern_name == "func": self.func = func elif pattern_name == "function": ...
GenericWrapper
python
walkccc__LeetCode
solutions/1433. Check If a String Can Break Another String/1433-2.py
{ "start": 0, "end": 356 }
class ____: def checkIfCanBreak(self, s1: str, s2: str) -> bool: count = collections.Counter(s1) count.subtract(collections.Counter(s2)) for a, b in itertools.pairwise(string.ascii_lowercase): count[b] += count[a] return (all(value <= 0 for value in count.values()) or all(value >= ...
Solution
python
huggingface__transformers
src/transformers/models/rwkv/modeling_rwkv.py
{ "start": 14318, "end": 18145 }
class ____(PreTrainedModel): config: RwkvConfig base_model_prefix = "rwkv" _no_split_modules = ["RwkvBlock"] _keep_in_fp32_modules = ["time_decay", "time_first"] supports_gradient_checkpointing = True _is_stateful = True @torch.no_grad() def _init_weights(self, module: nn.Module): ...
RwkvPreTrainedModel
python
sympy__sympy
sympy/stats/crv.py
{ "start": 17094, "end": 21028 }
class ____(ContinuousPSpace, SinglePSpace): """ A continuous probability space over a single univariate variable. These consist of a Symbol and a SingleContinuousDistribution This class is normally accessed through the various random variable functions, Normal, Exponential, Uniform, etc.... ""...
SingleContinuousPSpace
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/functions.py
{ "start": 10321, "end": 13755 }
class ____: """ Pre-processes zip path parameter. Responsible for checking if the zip path parameter is correctly specified in relation with source_code body fields. Non empty zip path parameter is special because it is mutually exclusive with sourceArchiveUrl and sourceRepository body fields. ...
ZipPathPreprocessor
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_pubmed_id.py
{ "start": 1599, "end": 3833 }
class ____(ColumnMapExpectation): """Expect column values to conform to the valid PubMed ID format.""" # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "well_formed_pubmed_...
ExpectColumnValuesToBeValidPubmedId
python
dagster-io__dagster
python_modules/libraries/dagster-slack/dagster_slack_tests/test_hooks.py
{ "start": 967, "end": 4786 }
class ____(Exception): pass @patch("slack_sdk.WebClient.api_call") @patch("slack_sdk.WebClient.chat_postMessage") def test_failure_hook_on_op_instance(mock_chat_postMessage, mock_api_call): @op(required_resource_keys={"slack"}) def pass_op(_): pass @op(required_resource_keys={"slack"}) de...
SomeUserException
python
PrefectHQ__prefect
tests/server/models/test_flow_run_input.py
{ "start": 2074, "end": 3995 }
class ____: async def test_reads_flow_run_input(self, session: AsyncSession, flow_run): for key in ["my-key", "my-key2", "other-key"]: await models.flow_run_input.create_flow_run_input( session=session, flow_run_input=schemas.core.FlowRunInput( ...
TestFilterFlowRunInput
python
google__jax
jax/experimental/mosaic/gpu/constraints.py
{ "start": 1817, "end": 2125 }
class ____(Constant): """Wraps a known SMEM Tile Transform. If an SMEM reference may, in principle, have transforms but should not be tiled, then `value` is `None`. """ value: lc.TileTransform | None def __str__(self): return f"C({self.value})" @dataclasses.dataclass(frozen=True)
SMEMTiling
python
ray-project__ray
python/ray/util/client/server/proxier.py
{ "start": 24793, "end": 25728 }
class ____: def __init__(self, request_iterator): self.request_iterator = request_iterator def __iter__(self): return self def __next__(self): try: return next(self.request_iterator) except grpc.RpcError as e: # To stop proxying already CANCLLED requ...
RequestIteratorProxy
python
getsentry__sentry
src/sentry/auth/providers/saml2/forms.py
{ "start": 1657, "end": 1801 }
class ____(forms.Form): metadata_url = forms.URLField(label="Metadata URL", assume_scheme="https") processor = process_url
URLMetadataForm
python
jazzband__django-waffle
waffle/mixins.py
{ "start": 462, "end": 932 }
class ____(BaseWaffleMixin): """ Checks that as flag is active, or 404. Operates like the FBV decorator waffle_flag """ waffle_flag: str | None = None def dispatch(self, request, *args, **kwargs): func = partial(flag_is_active, request) active = self.validate_waffle(self.waffle...
WaffleFlagMixin
python
pallets__werkzeug
src/werkzeug/datastructures/structures.py
{ "start": 32510, "end": 33113 }
class ____(ImmutableDictMixin[K, V], dict[K, V]): # type: ignore[misc] """An immutable :class:`dict`. .. versionadded:: 0.5 """ def __repr__(self) -> str: return f"{type(self).__name__}({dict.__repr__(self)})" def copy(self) -> dict[K, V]: """Return a shallow mutable copy of this...
ImmutableDict
python
apache__airflow
airflow-core/tests/unit/cli/commands/test_connection_command.py
{ "start": 14408, "end": 27075 }
class ____: parser = cli_parser.get_parser() def setup_method(self): clear_db_connections(add_default_connections_back=False) @skip_if_force_lowest_dependencies_marker @pytest.mark.parametrize( ("cmd", "expected_output", "expected_conn"), [ pytest.param( ...
TestCliAddConnections
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0038_change-default-python-interpreter.py
{ "start": 150, "end": 772 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0037_add_htmlfile"), ] operations = [ migrations.AlterField( model_name="project", name="python_interpreter", field=models.CharField( choices=[...
Migration
python
sympy__sympy
sympy/physics/quantum/spin.py
{ "start": 34358, "end": 35103 }
class ____(SpinState, Ket): """Eigenket of Jx. See JzKet for the usage of spin eigenstates. See Also ======== JzKet: Usage of spin states """ @classmethod def dual_class(self): return JxBra @classmethod def coupled_class(self): return JxKetCoupled def _...
JxKet
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta_billing_error.py
{ "start": 192, "end": 280 }
class ____(BaseModel): message: str type: Literal["billing_error"]
BetaBillingError
python
apache__airflow
dev/breeze/src/airflow_breeze/prepare_providers/provider_distributions.py
{ "start": 1428, "end": 1537 }
class ____(Exception): """Wrong setup prepared for the package."""
PrepareReleasePackageWrongSetupException
python
realpython__materials
python-property/point_v4.py
{ "start": 0, "end": 609 }
class ____: def __init__(self, x, y): self.x = x self.y = y @property def x(self): return self._x @x.setter def x(self, value): try: self._x = float(value) print("Validated!") except ValueError: raise ValueError('"x" must ...
Point
python
pytorch__pytorch
test/distributed/_composable/fsdp/test_fully_shard_overlap.py
{ "start": 11043, "end": 11427 }
class ____(nn.Module): def __init__(self, dim: int, sleep_ms: int): super().__init__() self.weight = nn.Parameter(torch.randn((dim, dim))) self.sleep_ms = sleep_ms def forward(self, x: torch.Tensor) -> torch.Tensor: return nn.functional.relu(Matmul.apply(x, self.weight, self.sle...
LinearWithSleep
python
getsentry__sentry
tests/sentry/web/frontend/test_auth_oauth2.py
{ "start": 1600, "end": 8392 }
class ____(AuthProviderTestCase): provider = DummyOAuth2Provider provider_name = "oauth2_dummy" def setUp(self) -> None: super().setUp() auth_provider = AuthProvider.objects.create( provider=self.provider_name, organization_id=self.organization.id ) AuthIdentity....
AuthOAuth2Test
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_tasks.py
{ "start": 6124, "end": 6956 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.tasks.CloudTasksHook") def test_delete_queue(self, mock_hook): mock_hook.return_value.purge_queue.return_value = TEST_QUEUE operator = CloudTasksQueuePurgeOperator(location=LOCATION, queue_name=QUEUE_ID, task_id="id") res...
TestCloudTasksQueuePurge
python
gevent__gevent
src/greentest/3.10/test_threading.py
{ "start": 2704, "end": 35184 }
class ____(BaseTestCase): @cpython_only def test_name(self): def func(): pass thread = threading.Thread(name="myname1") self.assertEqual(thread.name, "myname1") # Convert int name to str thread = threading.Thread(name=123) self.assertEqual(thread.name, "123") ...
ThreadTests
python
pyca__cryptography
src/cryptography/hazmat/primitives/asymmetric/utils.py
{ "start": 420, "end": 790 }
class ____: def __init__(self, algorithm: hashes.HashAlgorithm): if not isinstance(algorithm, hashes.HashAlgorithm): raise TypeError("Expected instance of HashAlgorithm.") self._algorithm = algorithm self._digest_size = algorithm.digest_size @property def digest_size(se...
Prehashed
python
tensorflow__tensorflow
tensorflow/python/ops/nn_test.py
{ "start": 69763, "end": 72975 }
class ____(test_lib.TestCase): def testRaggedTensor(self): weights = constant_op.constant([[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3]]) ragged_ids = ragged_factory_ops.constant([[1, 2, 3], [0], [1, 2]], ragged_rank=1) embedded_ragged = nn.embedding_lookup(wei...
RaggedEmbeddingTest
python
getsentry__sentry
src/sentry/management/commands/check_notifications.py
{ "start": 826, "end": 1740 }
class ____(BaseCommand): help = "Dump addresses that would get an email notification" def add_arguments(self, parser): parser.add_argument( "--organization", action="store", type=int, dest="organization", default=0, help="" ) parser.add_argument( "--project", act...
Command
python
getsentry__sentry
tests/snuba/rules/conditions/test_event_frequency.py
{ "start": 52879, "end": 53036 }
class ____( PerfIssuePlatformEventMixin, EventFrequencyPercentConditionTestCase, ): pass
PerfIssuePlatformIssueEventFrequencyPercentConditionTestCase
python
ray-project__ray
python/ray/serve/_private/proxy_state.py
{ "start": 10764, "end": 19569 }
class ____: def __init__( self, actor_proxy_wrapper: ProxyWrapper, actor_name: str, node_id: str, node_ip: str, node_instance_id: str, proxy_restart_count: int = 0, timer: TimerBase = Timer(), ): self._actor_proxy_wrapper = actor_proxy_wrap...
ProxyState
python
apache__airflow
providers/databricks/src/airflow/providers/databricks/operators/databricks_repos.py
{ "start": 10380, "end": 13155 }
class ____(BaseOperator): """ Deletes specified repository using the DELETE api/2.0/repos API endpoint. See: https://docs.databricks.com/dev-tools/api/latest/repos.html#operation/delete-repo :param repo_id: optional ID of existing repository. Should be specified if ``repo_path`` is omitted :param ...
DatabricksReposDeleteOperator
python
pytorch__pytorch
test/distributed/_tools/test_runtime_estimator.py
{ "start": 2030, "end": 7558 }
class ____(TestCase): def _train_step( self, model: nn.Module, optimizer: optim.Optimizer, inp: torch.Tensor, ): out = model(inp) loss = out.sum() loss.backward() optimizer.step() optimizer.zero_grad() def _measure_actual_cuda_time( ...
TestRuntimeEstimator
python
neetcode-gh__leetcode
python/0238-product-of-array-except-self.py
{ "start": 0, "end": 339 }
class ____: def productExceptSelf(self, nums: List[int]) -> List[int]: res = [1] * (len(nums)) for i in range(1, len(nums)): res[i] = res[i-1] * nums[i-1] postfix = 1 for i in range(len(nums) - 1, -1, -1): res[i] *= postfix postfix *= nums[i] ...
Solution
python
celery__celery
t/unit/tasks/test_chord.py
{ "start": 454, "end": 611 }
class ____: def setup_method(self): @self.app.task(shared=False) def add(x, y): return x + y self.add = add
ChordCase
python
cherrypy__cherrypy
cherrypy/_cpwsgi.py
{ "start": 5966, "end": 6485 }
class ____(object): """WSGI middleware that traps exceptions.""" def __init__(self, nextapp, throws=(KeyboardInterrupt, SystemExit)): """Initialize exception trapper.""" self.nextapp = nextapp self.throws = throws def __call__(self, environ, start_response): """Handle excep...
ExceptionTrapper
python
docker__docker-py
docker/context/context.py
{ "start": 238, "end": 7828 }
class ____: """A context.""" def __init__(self, name, orchestrator=None, host=None, endpoints=None, tls=False): if not name: raise Exception("Name not provided") self.name = name self.context_type = None self.orchestrator = orchestrator self....
Context
python
dagster-io__dagster
python_modules/dagster/dagster/_core/storage/compute_log_manager.py
{ "start": 703, "end": 789 }
class ____: stdout: Optional[str] stderr: Optional[str]
LogRetrievalShellCommand
python
airbytehq__airbyte
airbyte-ci/connectors/connectors_insights/src/connectors_insights/result_backends.py
{ "start": 403, "end": 582 }
class ____: file_name: str file_content: str | None = None def set_file_content(self, file_content: str) -> None: self.file_content = file_content
FileToPersist
python
weaviate__weaviate-python-client
journey_tests/test_fastapi.py
{ "start": 252, "end": 1617 }
class ____(TypedDict): sync: SyncJourneys async_: AsyncJourneys journeys: Journeys = {} @asynccontextmanager async def lifespan(app: FastAPI): journeys["async_"] = await AsyncJourneys.use() journeys["sync"] = SyncJourneys.use() try: yield finally: await journeys["async_"].clo...
Journeys
python
kamyu104__LeetCode-Solutions
Python/maximum-beauty-of-an-array-after-applying-operation.py
{ "start": 70, "end": 403 }
class ____(object): def maximumBeauty(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ nums.sort() left = 0 for right in xrange(len(nums)): if nums[right]-nums[left] > k*2: left += 1 return righ...
Solution
python
huggingface__transformers
tests/models/gpt2/test_modeling_gpt2.py
{ "start": 4590, "end": 11125 }
class ____(CausalLMModelTest, unittest.TestCase): # `all_model_classes` is overwritten because of `GPT2DoubleHeadsModel` all_model_classes = ( ( GPT2Model, GPT2LMHeadModel, GPT2DoubleHeadsModel, GPT2ForQuestionAnswering, GPT2ForSequenceClassifi...
GPT2ModelTest
python
sqlalchemy__sqlalchemy
test/orm/test_unitofwork.py
{ "start": 29589, "end": 37921 }
class ____(fixtures.MappedTest): """Exercise mappings on columns with DefaultGenerators. Tests that when saving objects whose table contains DefaultGenerators, either python-side, preexec or database-side, the newly saved instances receive all the default values either through a post-fetch or getting t...
DefaultTest
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 147704, "end": 150254 }
class ____(ExprNode, Nodes.CopyWithUpTreeRefsMixin): # The __exit__() call of a 'with' statement. Used in both the # except and finally clauses. # with_stat WithStatNode the surrounding 'with' statement # args TupleNode or ResultStatNode the exception info tuple # await_exp...
WithExitCallNode
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_state_dict.py
{ "start": 2875, "end": 4280 }
class ____(Module): def __init__( self, wrap_fsdp, register_buffers=False, ignore_inner=False, mixed_precision=False, process_group=None, ): super().__init__() self.inner = Linear(*INNER_SHAPE) if register_buffers: self.inner.bu...
Model
python
gevent__gevent
src/gevent/tests/test__threadpool.py
{ "start": 3689, "end": 4728 }
class ____(TestCase): size = 1 MAP_IS_GEN = False def setUp(self): greentest.TestCase.setUp(self) self._makeOne(self.size) @greentest.ignores_leakcheck def test_map(self): pmap = self.pool.map if self.MAP_IS_GEN: pmap = lambda f, i: list(self.pool.map(...
_AbstractPoolTest
python
ansible__ansible
test/units/utils/test_datatag.py
{ "start": 1022, "end": 6725 }
class ____(_TestDatatagTarget): later = t.cast(t.Self, Later(locals(), parent_type=_TestDatatagTarget)) tag_instances_with_reprs = [ (Origin(path='/himom.yml', line_num=42, col_num=42), "Origin(path='/himom.yml', line_num=42, col_num=42)"), (TrustedAsTemplate(), "TrustedAsTemplate()"), ...
TestDatatagController
python
mlflow__mlflow
mlflow/store/_unity_catalog/registry/uc_oss_rest_store.py
{ "start": 2364, "end": 20116 }
class ____(BaseRestStore): """ Client for an Open Source Unity Catalog Server accessed via REST API calls. """ def __init__(self, store_uri): super().__init__(get_host_creds=functools.partial(get_oss_host_creds, store_uri)) self.tracking_uri = None # OSS has no tracking URI def _g...
UnityCatalogOssStore
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 144495, "end": 144912 }
class ____(BaseModel): """ Usage of the hardware resources, spent to process the request """ hardware: Optional["HardwareUsage"] = Field( default=None, description="Usage of the hardware resources, spent to process the request" ) inference: Optional["InferenceUsage"] = Field( de...
Usage
python
scipy__scipy
scipy/_build_utils/tempita/_tempita.py
{ "start": 17264, "end": 17573 }
class ____: def __init__(self, template_obj): self.__template_obj = template_obj def __getattr__(self, attr): return getattr(self.__template_obj, attr, Empty) def __repr__(self): return '<%s around %r>' % (self.__class__.__name__, self.__template_obj)
TemplateObjectGetter
python
plotly__plotly.py
plotly/graph_objs/layout/legend/title/_font.py
{ "start": 235, "end": 9967 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout.legend.title" _path_str = "layout.legend.title.font" _valid_props = { "color", "family", "lineposition", "shadow", "size", "style", "textcase", "variant", "weight", } ...
Font
python
huggingface__transformers
tests/quantization/ggml/test_ggml.py
{ "start": 1221, "end": 4600 }
class ____(unittest.TestCase): """ Test cases for weights dequantization with GGUF models. Note: The quantization names should keep aligned with `GGMLQuantizationType` in gguf-py: https://github.com/ggerganov/llama.cpp/blob/4b0c638b9a68f577cb2066b638c9f622d91ee661/gguf-py/gguf/constants.py#L1545-L1576 ...
GgufQuantizationTests
python
mahmoud__boltons
boltons/timeutils.py
{ "start": 14507, "end": 15345 }
class ____(tzinfo): """ A :class:`~datetime.tzinfo` subtype whose *offset* remains constant (no daylight savings). Args: name (str): Name of the timezone. offset (datetime.timedelta): Offset of the timezone. """ def __init__(self, name="ConstantTZ", offset=ZERO): self.na...
ConstantTZInfo
python
django__django
tests/admin_widgets/models.py
{ "start": 2615, "end": 3245 }
class ____(models.Model): main_band = models.ForeignKey( Band, models.CASCADE, limit_choices_to=models.Q(pk__gt=0), related_name="events_main_band_at", ) supporting_bands = models.ManyToManyField( Band, blank=True, related_name="events_supporting_band_...
Event
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 669599, "end": 669965 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("client_mutation_id", "issue_comment") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") issue_comment = sgqlc.types.Field("IssueComment", graphq...
UpdateIssueCommentPayload
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 22527, "end": 22700 }
class ____(Inet6TestBase): """Base class for UDP-over-IPv6 tests.""" def newSocket(self): return socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
UDP6TestBase
python
allegroai__clearml
clearml/backend_api/services/v2_23/events.py
{ "start": 153287, "end": 153627 }
class ____(Response): """ Response of events.multi_task_scalar_metrics_iter_histogram endpoint. """ _service = "events" _action = "multi_task_scalar_metrics_iter_histogram" _version = "2.23" _schema = {"additionalProperties": True, "definitions": {}, "type": "object"}
MultiTaskScalarMetricsIterHistogramResponse
python
huggingface__transformers
src/transformers/models/emu3/modular_emu3.py
{ "start": 4745, "end": 4831 }
class ____(ChameleonVQVAEEncoderConvDownsample): pass
Emu3VQVAEEncoderConvDownsample
python
pytorch__pytorch
torch/nn/modules/batchnorm.py
{ "start": 7461, "end": 10139 }
class ____(LazyModuleMixin, _NormBase): weight: UninitializedParameter # type: ignore[assignment] bias: UninitializedParameter # type: ignore[assignment] def __init__( self, eps=1e-5, momentum=0.1, affine=True, track_running_stats=True, device=None, ...
_LazyNormBase
python
Lightning-AI__lightning
tests/tests_pytorch/trainer/test_dataloaders.py
{ "start": 31319, "end": 32711 }
class ____(BoringModel): def __init__(self): super().__init__() self.seen_samples = [] def training_step(self, batch, batch_idx): self.seen_samples.extend(batch.tolist()) # the actual training step is not needed for the test return super().training_step(torch.rand(1, 32,...
TestModelUniqueDDPSampling
python
google__pytype
pytype/overlays/enum_overlay.py
{ "start": 1902, "end": 2491 }
class ____(overlay.Overlay): """An overlay for the enum std lib module.""" def __init__(self, ctx): member_map = { "Enum": overlay.add_name("Enum", EnumBuilder), "EnumMeta": EnumMeta, "EnumType": EnumMeta, "IntEnum": overlay.add_name("IntEnum", EnumBuilder), "StrEnum": o...
EnumOverlay
python
kubernetes-client__python
kubernetes/client/models/v1_node_selector_requirement.py
{ "start": 383, "end": 6193 }
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...
V1NodeSelectorRequirement
python
pytorch__pytorch
test/distributed/test_c10d_pypg.py
{ "start": 4851, "end": 4990 }
class ____(AbstractDDPSingleRank, MultiThreadedTestCase): @property def use_wrapper(self): return True
TestDDPWithWorkWrapper
python
walkccc__LeetCode
solutions/1796. Second Largest Digit in a String/1796.py
{ "start": 0, "end": 342 }
class ____: def secondHighest(self, s: str) -> int: maxDigit = -1 secondMaxDigit = -1 for c in s: if c.isdigit(): d = int(c) if d > maxDigit: secondMaxDigit = maxDigit maxDigit = d elif maxDigit > d > secondMaxDigit: secondMaxDigit = d retu...
Solution
python
getsentry__sentry
src/sentry/spans/buffer.py
{ "start": 5238, "end": 5860 }
class ____(NamedTuple): trace_id: str span_id: str parent_span_id: str | None segment_id: str | None project_id: int payload: bytes end_timestamp: float is_segment_span: bool = False def effective_parent_id(self): # Note: For the case where the span's parent is in another pr...
Span
python
pytorch__pytorch
torch/_inductor/autotune_process.py
{ "start": 22144, "end": 22237 }
class ____(GPUDeviceBenchmarkMixin, TritonBenchmarkRequest): pass
TritonGPUBenchmarkRequest
python
ray-project__ray
rllib/offline/is_estimator.py
{ "start": 240, "end": 304 }
class ____(ImportanceSampling): pass
ImportanceSamplingEstimator
python
getsentry__sentry
tests/sentry/seer/fetch_issues/test_by_function_name.py
{ "start": 1556, "end": 3056 }
class ____(IntegrationTestCase, CreateEventTestCase): provider = GitHubIntegrationProvider def setUp(self): super().setUp() self.gh_repo: Repository = self.create_repo( name="getsentry/sentry", provider="integrations:github", integration_id=self.integration.i...
TestGetProjectsAndFilenamesFromSourceFile
python
google__jax
jax/_src/pallas/mosaic/interpret/shared_memory.py
{ "start": 848, "end": 6376 }
class ____: def __init__( self, shared_memory: SharedMemory, semaphore_id: int, ): self.shared_memory = shared_memory self.id: int = semaphore_id # TODO(jburnim): Use one Condition variable per device. (Which will be # easier to do when we're using single integer device IDs.) ...
Semaphore
python
jupyterlab__jupyterlab
jupyterlab/coreconfig.py
{ "start": 1189, "end": 5227 }
class ____: """An object representing a core config. This enables custom lab application to override some parts of the core configuration of the build system. """ def __init__(self): self._data = _get_default_core_data() def add(self, name, semver, extension=False, mime_extension=Fals...
CoreConfig
python
huggingface__transformers
src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py
{ "start": 113769, "end": 115462 }
class ____(ModelOutput): r""" loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Language modeling loss (for next-token prediction). logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the lan...
Qwen2_5OmniTalkerCausalLMOutputWithPast
python
astropy__astropy
astropy/utils/masked/tests/test_masked.py
{ "start": 5482, "end": 7632 }
class ____: """Try creating a MaskedList and subclasses. By no means meant to be realistic, just to check that the basic machinery allows it. """ @classmethod def setup_class(cls): cls._base_classes_orig = Masked._base_classes.copy() cls._masked_classes_orig = Masked._masked_cl...
TestMaskedClassCreation
python
apache__airflow
airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_assets.py
{ "start": 1031, "end": 2324 }
class ____: def test_get_asset_by_name(self, client, session): asset = AssetModel( id=1, name="test_get_asset_by_name", uri="s3://bucket/key", group="asset", extra={"foo": "bar"}, created_at=DEFAULT_DATE, updated_at=DEFAULT_...
TestGetAssetByName
python
zarr-developers__zarr-python
src/zarr/codecs/crc32c_.py
{ "start": 441, "end": 2221 }
class ____(BytesBytesCodec): """crc32c codec""" is_fixed_size = True @classmethod def from_dict(cls, data: dict[str, JSON]) -> Self: parse_named_configuration(data, "crc32c", require_configuration=False) return cls() def to_dict(self) -> dict[str, JSON]: return {"name": "c...
Crc32cCodec
python
coleifer__peewee
tests/regressions.py
{ "start": 3154, "end": 3741 }
class ____(BaseTestCase): def test_custom_reprs(self): # In 3.5.0, Peewee included a new implementation and semantics for # customizing model reprs. This introduced a regression where model # classes that defined a __repr__() method had this override ignored # silently. This test ens...
TestOverrideModelRepr