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
rushter__MLAlgorithms
mla/ensemble/gbm.py
{ "start": 4237, "end": 4484 }
class ____(GradientBoosting): def fit(self, X, y=None): # Convert labels from {0, 1} to {-1, 1} y = (y * 2) - 1 self.loss = LogisticLoss() super(GradientBoostingClassifier, self).fit(X, y)
GradientBoostingClassifier
python
pytorch__pytorch
torch/_functorch/_aot_autograd/descriptors.py
{ "start": 23976, "end": 24220 }
class ____(AOTOutput): """The final offset from the functionalized RNG calls, forward only""" def expr(self) -> str: return "__philox_updated_forward_offset" @dataclasses.dataclass(frozen=True)
PhiloxUpdatedForwardOffsetAOTOutput
python
apache__airflow
helm-tests/tests/helm_tests/statsd/test_labels_networkpolicy.py
{ "start": 900, "end": 4044 }
class ____: """Tests statsd network policy labels.""" TEMPLATE_FILE = "templates/statsd/statsd-networkpolicy.yaml" def test_should_add_global_labels(self): """Test adding only .Values.labels.""" docs = render_chart( values={ "statsd": {"enabled": True}, ...
TestStatsdNetworkPolicy
python
pandas-dev__pandas
pandas/tests/frame/indexing/test_xs.py
{ "start": 763, "end": 3991 }
class ____: def test_xs(self, float_frame): idx = float_frame.index[5] xs = float_frame.xs(idx) for item, value in xs.items(): if np.isnan(value): assert np.isnan(float_frame[item][idx]) else: assert value == float_frame[item][idx] ...
TestXS
python
bokeh__bokeh
src/bokeh/models/dom.py
{ "start": 6232, "end": 6412 }
class ____(Placeholder): # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs)
Index
python
pypa__pip
src/pip/_vendor/packaging/metadata.py
{ "start": 1161, "end": 1722 }
class ____(ValueError): """A metadata field contains invalid data.""" field: str """The name of the field that contains invalid data.""" def __init__(self, field: str, message: str) -> None: self.field = field super().__init__(message) # The RawMetadata class attempts to make as few ...
InvalidMetadata
python
aio-libs__aiohttp
aiohttp/helpers.py
{ "start": 7074, "end": 9660 }
class ____: proxy: URL proxy_auth: BasicAuth | None def basicauth_from_netrc(netrc_obj: netrc.netrc | None, host: str) -> BasicAuth: """ Return :py:class:`~aiohttp.BasicAuth` credentials for ``host`` from ``netrc_obj``. :raises LookupError: if ``netrc_obj`` is :py:data:`None` or if no ...
ProxyInfo
python
openai__openai-python
src/openai/types/shared/response_format_text_python.py
{ "start": 201, "end": 342 }
class ____(BaseModel): type: Literal["python"] """The type of response format being defined. Always `python`."""
ResponseFormatTextPython
python
dagster-io__dagster
python_modules/dagster/dagster_tests/components_tests/component_tree_tests/test_get_all_components.py
{ "start": 3468, "end": 5356 }
class ____(dg.Component): def build_defs(self, context: dg.ComponentLoadContext) -> dg.Definitions: return dg.Definitions(assets=[dg.AssetSpec("bar_asset")]) @dg.component_instance def load_foo(context: dg.ComponentLoadContext) -> FooComponent: return FooComponent() @dg.component_instance def load_foo...
BarComponent
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_set_print_scale01.py
{ "start": 315, "end": 1215 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("set_print_scale01.xlsx") self.ignore_files = [ "xl/printerSettings/printerSettings1.bin", "xl/worksheets/_rels/sheet1.x...
TestCompareXLSXFiles
python
tensorflow__tensorflow
tensorflow/python/eager/polymorphic_function/polymorphic_function_xla_jit_test.py
{ "start": 1951, "end": 43540 }
class ____(xla_test.XLATestCase): def _compareTwoMethodsCompilerIROutput(self, f, args, kwargs): """Assert the two different methods (tensor_spec inputs or tensor inputs) experimental_get_compiler give same HLO text.""" flat_args = list(args) + list(kwargs.values()) if not all([isinstance(x, tensor.Tenso...
FunctionTest
python
spyder-ide__spyder
spyder/plugins/completion/providers/fallback/tests/conftest.py
{ "start": 367, "end": 1051 }
class ____(QObject): sig_recv_tokens = Signal(list) def handle_response(self, client, req_id, response): tokens = list(response['params']) self.sig_recv_tokens.emit(list(tokens)) @pytest.fixture(scope='module') def fallback_completions(qtbot_module, request): fallback = FallbackProvider(N...
CompletionManagerMock
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/ddl.py
{ "start": 38670, "end": 38843 }
class ____(_CreateDropBase["Constraint"]): """Represent a COMMENT ON CONSTRAINT IS NULL statement.""" __visit_name__ = "drop_constraint_comment"
DropConstraintComment
python
PrefectHQ__prefect
src/prefect/server/schemas/filters.py
{ "start": 85030, "end": 85977 }
class ____(PrefectOperatorFilterBaseModel): """Filter by `Variable.tags`.""" all_: Optional[list[str]] = Field( default=None, examples=[["tag-1", "tag-2"]], description=( "A list of tags. Variables will be returned only if their tags are a" " superset of the list...
VariableFilterTags
python
ray-project__ray
release/ray_release/exception.py
{ "start": 3745, "end": 3787 }
class ____(CommandError): pass
LogsError
python
ray-project__ray
python/ray/serve/schema.py
{ "start": 6568, "end": 8785 }
class ____(BaseModel): """Options with which to start a replica actor.""" runtime_env: dict = Field( default={}, description=( "This deployment's runtime_env. working_dir and " "py_modules may contain only remote URIs." ), ) num_cpus: float = Field( ...
RayActorOptionsSchema
python
pytorch__pytorch
torch/ao/nn/quantized/modules/conv.py
{ "start": 25886, "end": 30662 }
class ____(_ConvNd): _FLOAT_MODULE: ClassVar[type[nn.modules.conv._ConvNd]] def __init__( self, in_channels, out_channels, kernel_size, stride, padding, dilation, transposed, output_padding, groups, bias, padding_mo...
_ConvTransposeNd
python
MongoEngine__mongoengine
mongoengine/fields.py
{ "start": 39000, "end": 45831 }
class ____(BaseField): """A reference to a document that will be automatically dereferenced on access (lazily). Note this means you will get a database I/O access everytime you access this field. This is necessary because the field returns a :class:`~mongoengine.Document` which precise type can dep...
ReferenceField
python
boto__boto3
boto3/resources/action.py
{ "start": 6333, "end": 8079 }
class ____: """ A class representing a callable waiter action on a resource, for example ``s3.Bucket('foo').wait_until_bucket_exists()``. The waiter action may construct parameters from existing resource identifiers. :type waiter_model: :py:class`~boto3.resources.model.Waiter` :param waiter...
WaiterAction
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 57330, "end": 57678 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("id", "client_mutation_id") id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="id") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId"...
ApproveVerifiableDomainInput
python
PrefectHQ__prefect
tests/server/models/test_csrf_token.py
{ "start": 2473, "end": 3686 }
class ____: async def test_can_get_token_for_client( self, session: AsyncSession, csrf_token: core.CsrfToken ): token = await models.csrf_token.read_token_for_client( session=session, client="client123" ) assert token assert token.client == csrf_token.client ...
TestTokenForClient
python
pytorch__pytorch
torch/distributed/checkpoint/default_planner.py
{ "start": 10846, "end": 15995 }
class ____(LoadPlanner): """ DefaultLoadPlanner that adds multiple features on top of LoadPlanner. In particular it adds the following: flatten_state_dict: Handle state_dict with nested dicts flatten_sharded_tensors: For FSDP in 2D parallel mode allow_partial_load: If False, will raise a runti...
DefaultLoadPlanner
python
huggingface__transformers
src/transformers/models/emu3/modeling_emu3.py
{ "start": 43748, "end": 46758 }
class ____(nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer` def __init__(self, config: Emu3Config, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings self.co...
Emu3RotaryEmbedding
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 655486, "end": 655918 }
class ____(sgqlc.types.Type): """An edge in a connection.""" __schema__ = github_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field("EnterpriseServerUserAccou...
EnterpriseServerUserAccountsUploadEdge
python
lepture__authlib
authlib/jose/rfc7515/models.py
{ "start": 1979, "end": 2448 }
class ____(dict): """A dict instance to represent a JWS object.""" def __init__(self, header, payload, type="compact"): super().__init__( header=header, payload=payload, ) self.header = header self.payload = payload self.type = type @property...
JWSObject
python
matplotlib__matplotlib
lib/matplotlib/axes/_axes.py
{ "start": 2827, "end": 370944 }
class ____(_AxesBase): """ An Axes object encapsulates all the elements of an individual (sub-)plot in a figure. It contains most of the (sub-)plot elements: `~.axis.Axis`, `~.axis.Tick`, `~.lines.Line2D`, `~.text.Text`, `~.patches.Polygon`, etc., and sets the coordinate system. Like all v...
Axes
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 954349, "end": 954761 }
class ____(sgqlc.types.Type): """An edge in a connection.""" __schema__ = github_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field("ReviewDismissalAllowance"...
ReviewDismissalAllowanceEdge
python
pytorch__pytorch
torch/distributions/binomial.py
{ "start": 488, "end": 6484 }
class ____(Distribution): r""" Creates a Binomial distribution parameterized by :attr:`total_count` and either :attr:`probs` or :attr:`logits` (but not both). :attr:`total_count` must be broadcastable with :attr:`probs`/:attr:`logits`. Example:: >>> # xdoctest: +IGNORE_WANT("non-determinis...
Binomial
python
langchain-ai__langchain
libs/langchain_v1/tests/unit_tests/agents/test_responses_spec.py
{ "start": 498, "end": 712 }
class ____(BaseSchema): prompt: str tools_with_expected_calls: ToolCalls expected_last_message: str expected_structured_response: dict[str, Any] | None llm_request_count: int
AssertionByInvocation
python
doocs__leetcode
solution/1200-1299/1295.Find Numbers with Even Number of Digits/Solution.py
{ "start": 0, "end": 122 }
class ____: def findNumbers(self, nums: List[int]) -> int: return sum(len(str(x)) % 2 == 0 for x in nums)
Solution
python
cookiecutter__cookiecutter
cookiecutter/exceptions.py
{ "start": 3730, "end": 3899 }
class ____(CookiecutterException): """ Exception for missing repo. Raised when the specified cookiecutter repository doesn't exist. """
RepositoryNotFound
python
ApeWorX__ape
tests/functional/utils/test_basemodel.py
{ "start": 291, "end": 1683 }
class ____(ManagerAccessMixin): pass @pytest.mark.parametrize("accessor", (CustomClass, CustomClass())) def test_provider(accessor, eth_tester_provider): assert accessor.provider == eth_tester_provider @pytest.mark.parametrize("accessor", (CustomClass, CustomClass())) def test_provider_not_active(networks, ...
CustomClass
python
huggingface__transformers
src/transformers/models/cvt/configuration_cvt.py
{ "start": 780, "end": 6684 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`CvtModel`]. It is used to instantiate a CvT model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration...
CvtConfig
python
ray-project__ray
python/ray/serve/_private/replica.py
{ "start": 47962, "end": 56242 }
class ____: """Actor definition for replicas of Ray Serve deployments. This class defines the interface that the controller and deployment handles (i.e., from proxies and other replicas) use to interact with a replica. All interaction with the user-provided callable is done via the `UserCallableWr...
ReplicaActor
python
cython__cython
tests/run/test_patma.py
{ "start": 81967, "end": 90262 }
class ____(unittest.TestCase): def assert_syntax_error(self, code: str): with self.assertRaises(SyntaxError): compile(inspect.cleandoc(code), "<test>", "exec") def test_alternative_patterns_bind_different_names_0(self): self.assert_syntax_error(""" match ...: ca...
TestSyntaxErrors
python
ipython__ipython
IPython/utils/capture.py
{ "start": 1716, "end": 3447 }
class ____: """Simple object for containing captured stdout/err and rich display StringIO objects Each instance `c` has three attributes: - ``c.stdout`` : standard output as a string - ``c.stderr`` : standard error as a string - ``c.outputs``: a list of rich display outputs Additionally, ther...
CapturedIO
python
kamyu104__LeetCode-Solutions
Python/design-search-autocomplete-system.py
{ "start": 860, "end": 2083 }
class ____(object): def __init__(self, sentences, times): """ :type sentences: List[str] :type times: List[int] """ self.__trie = TrieNode() self.__cur_node = self.__trie self.__search = [] self.__sentence_to_count = collections.defaultdict(int) ...
AutocompleteSystem
python
psf__black
tests/data/cases/preview_long_dict_values.py
{ "start": 3503, "end": 7642 }
class ____: def func(): random_service.status.active_states.inactive = ( make_new_top_level_state_from_dict( { "topLevelBase": { "secondaryBase": { "timestamp": 1234, "latitude": 1...
Random
python
scipy__scipy
scipy/stats/_continuous_distns.py
{ "start": 223105, "end": 232261 }
class ____(rv_continuous): r"""Kappa 4 parameter distribution. %(before_notes)s Notes ----- The probability density function for kappa4 is: .. math:: f(x, h, k) = (1 - k x)^{1/k - 1} (1 - h (1 - k x)^{1/k})^{1/h-1} if :math:`h` and :math:`k` are not equal to 0. If :math:`h`...
kappa4_gen
python
PrefectHQ__prefect
src/integrations/prefect-aws/prefect_aws/credentials.py
{ "start": 5785, "end": 9553 }
class ____(CredentialsBlock): """ Block used to manage authentication with MinIO. Refer to the [MinIO docs](https://docs.min.io/docs/minio-server-configuration-guide.html) for more info about the possible credential configurations. Attributes: minio_root_user: Admin or root user. mi...
MinIOCredentials
python
PyCQA__pylint
tests/functional/ext/docstyle/docstyle_first_line_empty.py
{ "start": 266, "end": 486 }
class ____: # [docstring-first-line-empty] """ Test Docstring First Line Empty """ def method1(self): # [docstring-first-line-empty] ''' Test Triple Single Quotes docstring '''
FFFF
python
qdrant__qdrant-client
qdrant_client/http/api/aliases_api.py
{ "start": 3043, "end": 3934 }
class ____(_AliasesApi): async def get_collection_aliases( self, collection_name: str, ) -> m.InlineResponse2008: """ Get list of all aliases for a collection """ return await self._build_for_get_collection_aliases( collection_name=collection_name, ...
AsyncAliasesApi
python
openai__openai-python
src/openai/types/eval_list_params.py
{ "start": 204, "end": 754 }
class ____(TypedDict, total=False): after: str """Identifier for the last eval from the previous pagination request.""" limit: int """Number of evals to retrieve.""" order: Literal["asc", "desc"] """Sort order for evals by timestamp. Use `asc` for ascending order or `desc` for descending ...
EvalListParams
python
kamyu104__LeetCode-Solutions
Python/create-maximum-number.py
{ "start": 76, "end": 1539 }
class ____(object): def maxNumber(self, nums1, nums2, k): """ :type nums1: List[int] :type nums2: List[int] :type k: int :rtype: List[int] """ def get_max_digits(nums, start, end, max_digits): max_digits[end] = max_digit(nums, end) for ...
Solution
python
kamyu104__LeetCode-Solutions
Python/online-election.py
{ "start": 110, "end": 760 }
class ____(object): def __init__(self, persons, times): """ :type persons: List[int] :type times: List[int] """ lead = -1 self.__lookup, count = [], collections.defaultdict(int) for t, p in itertools.izip(times, persons): count[p] += 1 ...
TopVotedCandidate
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 129342, "end": 132743 }
class ____(Operation): def __init__( self, num=50, endpoint=True, retstep=False, dtype=None, axis=0, *, name=None, ): super().__init__(name=name) self.num = num self.endpoint = endpoint self.retstep = retstep ...
Linspace
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0112_alter_project_help_text.py
{ "start": 184, "end": 1574 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0111_add_multiple_versions_without_translations"), ] operations = [ migrations.AlterField( model_name="historicalproject", name="external_builds_privacy_level", ...
Migration
python
doocs__leetcode
solution/2800-2899/2857.Count Pairs of Points With Distance k/Solution.py
{ "start": 0, "end": 350 }
class ____: def countPairs(self, coordinates: List[List[int]], k: int) -> int: cnt = Counter() ans = 0 for x2, y2 in coordinates: for a in range(k + 1): b = k - a x1, y1 = a ^ x2, b ^ y2 ans += cnt[(x1, y1)] cnt[(x2, y2)...
Solution
python
catalyst-team__catalyst
tests/catalyst/callbacks/test_profiler.py
{ "start": 482, "end": 1105 }
class ____(Dataset): """Dummy dataset.""" features_dim: int = 4 out_dim: int = 2 def __init__(self, num_records: int): self.num_records = num_records def __len__(self): """ Returns: dataset's length. """ return self.num_records def __getite...
DummyDataset
python
networkx__networkx
networkx/algorithms/tests/test_euler.py
{ "start": 6429, "end": 9603 }
class ____: def test_eulerian_path(self): x = [(4, 0), (0, 1), (1, 2), (2, 0)] for e1, e2 in zip(x, nx.eulerian_path(nx.DiGraph(x))): assert e1 == e2 def test_eulerian_path_straight_link(self): G = nx.DiGraph() result = [(1, 2), (2, 3), (3, 4), (4, 5)] G.add_...
TestEulerianPath
python
mlflow__mlflow
mlflow/evaluation/assessment.py
{ "start": 7333, "end": 13374 }
class ____(_MlflowObject): """ Assessment data associated with an evaluation result. Assessment is an enriched output from the evaluation that provides more context, such as the rationale, source, and metadata for the evaluation result. Example: .. code-block:: python from mlflow.eva...
Assessment
python
ray-project__ray
rllib/env/multi_agent_env.py
{ "start": 26795, "end": 30904 }
class ____: def __init__(self, env: MultiAgentEnv, return_error_as_obs: bool = False): assert isinstance(env, MultiAgentEnv) self.env = env self.return_error_as_obs = return_error_as_obs self.initialized = False self.last_obs = {} self.last_rewards = {} self....
_MultiAgentEnvState
python
kamyu104__LeetCode-Solutions
Python/unique-length-3-palindromic-subsequences.py
{ "start": 29, "end": 467 }
class ____(object): def countPalindromicSubsequence(self, s): """ :type s: str :rtype: int """ first, last = [len(s)]*26, [-1]*26 for i, c in enumerate(s): first[ord(c)-ord('a')] = min(first[ord(c)-ord('a')], i) last[ord(c)-ord('a')] = max(last...
Solution
python
huggingface__transformers
tests/models/siglip/test_tokenization_siglip.py
{ "start": 1009, "end": 11596 }
class ____(TokenizerTesterMixin, unittest.TestCase): from_pretrained_id = "google/siglip-base-patch16-224" tokenizer_class = SiglipTokenizer test_rust_tokenizer = False test_sentencepiece = True test_sentencepiece_ignore_case = True @classmethod def setUpClass(cls): super().setUpCla...
SiglipTokenizationTest
python
tensorflow__tensorflow
tensorflow/python/debug/cli/analyzer_cli_test.py
{ "start": 21359, "end": 62755 }
class ____(test_util.TensorFlowTestCase): @classmethod def setUpClass(cls): cls._dump_root = tempfile.mkdtemp() cls._dump_root_for_unique = tempfile.mkdtemp() cls._is_gpu_available = test.is_gpu_available() if cls._is_gpu_available: gpu_name = test_util.gpu_device_name() cls._main_devi...
AnalyzerCLISimpleMulAddTest
python
pytorch__pytorch
torch/_inductor/fx_passes/group_batch_fusion.py
{ "start": 48640, "end": 48816 }
class ____(BatchMathOpsPreGradFusion): def __init__(self, **kwargs): super().__init__(torch.clamp, **kwargs) @register_fusion("batch_dropout")
BatchClampPreGradFusion
python
pytorch__pytorch
test/distributed/tensor/debug/test_comm_mode.py
{ "start": 762, "end": 7692 }
class ____(TestCase): def tearDown(self): super().tearDown() dist.destroy_process_group() def setUp(self): super().setUp() self.world_size = 2 store = FakeStore() dist.init_process_group( backend="fake", rank=1, world_size=self.world_size, store=store...
TestCommMode
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 67395, "end": 67747 }
class ____(sgqlc.types.Enum): """The possible states of a pull request review comment. Enumeration Choices: * `PENDING`: A comment that is part of a pending review * `SUBMITTED`: A comment that is part of a submitted review """ __schema__ = github_schema __choices__ = ("PENDING", "SUBMITT...
PullRequestReviewCommentState
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/steps/docker.py
{ "start": 463, "end": 5110 }
class ____(Step): def __init__( self, title: str, context: PipelineContext, paths_to_mount: Optional[List[MountPath]] = None, internal_tools: Optional[List[MountPath]] = None, secret_env_variables: Optional[Dict[str, Secret]] = None, env_variables: dict[str, s...
SimpleDockerStep
python
weaviate__weaviate-python-client
weaviate/exceptions.py
{ "start": 7510, "end": 7764 }
class ____(WeaviateQueryError): """Is raised if a gRPC batch send request to Weaviate fails in any way.""" def __init__(self, message: str): super().__init__(message, "GRPC batch send") self.message = message
WeaviateBatchSendError
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-vectorx/tests/test_vector_stores_vectorx.py
{ "start": 5400, "end": 7052 }
class ____(VectorXTestSetup): @classmethod def setUpClass(cls): super().setUpClass() cls.embed_model = HuggingFaceEmbedding( "sentence-transformers/all-MiniLM-L6-v2", device="cpu" ) cls.vector_store = VectorXVectorStore.from_params( api_token=cls.vecx_api_...
TestCustomRetrieval
python
huggingface__transformers
src/transformers/models/metaclip_2/modeling_metaclip_2.py
{ "start": 10603, "end": 11786 }
class ____(GradientCheckpointingLayer): def __init__(self, config: Union[MetaClip2VisionConfig, MetaClip2TextConfig]): super().__init__() self.embed_dim = config.hidden_size self.self_attn = MetaClip2Attention(config) self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_n...
MetaClip2EncoderLayer
python
getsentry__sentry
src/sentry/apidocs/utils.py
{ "start": 284, "end": 1345 }
class ____: """ Basic class that simply stores a type that is parsed into Open API Schema. Used by `utils.inline_sentry_response_serializer` """ def __init__(self, t: type) -> None: self.typeSchema = t def inline_sentry_response_serializer(name: str, t: type) -> type: """ Function...
_RawSchema
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/cloud_run.py
{ "start": 6094, "end": 7758 }
class ____(GoogleBaseAsyncHook): """ Async hook for the Google Cloud Run service. :param gcp_conn_id: The connection ID to use when fetching connection info. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to...
CloudRunAsyncHook
python
run-llama__llama_index
llama-index-integrations/voice_agents/llama-index-voice-agents-gemini-live/llama_index/voice_agents/gemini_live/events.py
{ "start": 432, "end": 520 }
class ____(BaseVoiceAgentEvent): tool_name: str tool_result: Any
ToolCallResultEvent
python
google__jax
jax/_src/linear_util.py
{ "start": 3359, "end": 3427 }
class ____: pass _EMPTY_STORE_VALUE = EmptyStoreValue()
EmptyStoreValue
python
FactoryBoy__factory_boy
tests/test_typing.py
{ "start": 167, "end": 594 }
class ____(unittest.TestCase): def test_simple_factory(self) -> None: class UserFactory(factory.Factory[User]): name = "John Doe" email = "john.doe@example.org" id = 42 class Meta: model = User result: User result = UserFact...
TypingTests
python
pytorch__pytorch
test/quantization/pt2e/test_metadata_porting.py
{ "start": 2268, "end": 21478 }
class ____(QuantizationTestCase): def _test_quant_tag_preservation_through_decomp( self, model, example_inputs, from_node_to_tags ): ep = torch.export.export(model, example_inputs, strict=True) found_tags = True not_found_nodes = "" for from_node, tag in from_node_to_tags...
TestMetaDataPorting
python
viewflow__viewflow
viewflow/templatetags/viewflow.py
{ "start": 3855, "end": 4280 }
class ____(BaseViewsetURLNode): """ Reverse a url to a view within viewset Example:: {% current_viewset_reverse viewset viewname args kwargs %} """ def _reverse_url(self, viewset, view_name, args, kwargs, current_app, context): return current_viewset_reverse( context.re...
CurrentViewsetURLNode
python
PrefectHQ__prefect
tests/server/orchestration/api/test_workers.py
{ "start": 60158, "end": 67546 }
class ____: async def test_heartbeat_worker(self, client, work_pool): workers_response = await client.post( f"/work_pools/{work_pool.name}/workers/filter" ) assert workers_response.status_code == status.HTTP_200_OK assert len(workers_response.json()) == 0 dt = da...
TestWorkerProcess
python
pypa__pipenv
pipenv/patched/pip/_internal/metadata/importlib/_compat.py
{ "start": 451, "end": 2811 }
class ____(Protocol): """A protocol that various path objects conform. This exists because importlib.metadata uses both ``pathlib.Path`` and ``zipfile.Path``, and we need a common base for type hints (Union does not work well since ``zipfile.Path`` is too new for our linter setup). This does not m...
BasePath
python
dagster-io__dagster
python_modules/libraries/dagster-tableau/dagster_tableau/translator.py
{ "start": 6835, "end": 7036 }
class ____(NamespacedTagSet): asset_type: Optional[Literal["dashboard", "data_source", "sheet"]] = None @classmethod def namespace(cls) -> str: return "dagster-tableau"
TableauTagSet
python
tensorflow__tensorflow
tensorflow/python/tpu/embedding_context_utils.py
{ "start": 965, "end": 1542 }
class ____: """Disables embedding pipelining for all ops created in the scope.""" def __init__(self): self._original_embedding_pipelining_state_enabled = ( embedding_pipelining_state.enabled ) def __enter__(self): embedding_pipelining_state.enabled = False logging.info("Entering Sequenti...
SequentialEmbeddingContext
python
pytorch__pytorch
test/dynamo/test_guard_serialization.py
{ "start": 60265, "end": 61654 }
class ____(torch.nn.Module): def __init__(self, c): super().__init__() self.c = c self.p = torch.nn.Parameter(torch.randn(3, 2)) def forward(self, x): z = x + 1 for p in self.parameters(): z += p return z if not IS_MACOS: from torch.testing._int...
SimpleModule
python
walkccc__LeetCode
solutions/369. Plus One Linked List/369.py
{ "start": 0, "end": 362 }
class ____: def plusOne(self, head: ListNode) -> ListNode: if not head: return ListNode(1) if self._addOne(head) == 1: return ListNode(1, head) return head def _addOne(self, node: ListNode) -> int: carry = self._addOne(node.next) if node.next else 1 summ = node.val + carry node....
Solution
python
kamyu104__LeetCode-Solutions
Python/find-good-days-to-rob-the-bank.py
{ "start": 29, "end": 671 }
class ____(object): def goodDaysToRobBank(self, security, time): """ :type security: List[int] :type time: int :rtype: List[int] """ right = [0] for i in reversed(xrange(1, len(security))): right.append(right[-1]+1 if security[i] >= security[i-1] e...
Solution
python
pypa__pipenv
pipenv/patched/pip/_internal/index/package_finder.py
{ "start": 21762, "end": 39511 }
class ____: """This finds packages. This is meant to match easy_install's technique for looking for packages, by reading pages and looking for appropriate links. """ def __init__( self, link_collector: LinkCollector, target_python: TargetPython, allow_yanked: bool, ...
PackageFinder
python
django__django
django/template/loader_tags.py
{ "start": 970, "end": 2619 }
class ____(Node): def __init__(self, name, nodelist, parent=None): self.name = name self.nodelist = nodelist self.parent = parent def __repr__(self): return "<Block Node: %s. Contents: %r>" % (self.name, self.nodelist) def render(self, context): block_context = cont...
BlockNode
python
sqlalchemy__sqlalchemy
test/ext/asyncio/test_session.py
{ "start": 34252, "end": 35722 }
class ____(AsyncFixture): def test_default(self, async_engine): ass = AsyncSession(async_engine) is_true(isinstance(ass.sync_session, Session)) is_(ass.sync_session.__class__, Session) is_(ass.sync_session_class, Session) def test_init_class(self, async_engine): ass = A...
OverrideSyncSession
python
python__mypy
mypy/test/testfinegrained.py
{ "start": 15103, "end": 17776 }
class ____(unittest.TestCase): def test_simple_sorting(self) -> None: msgs = ['x.py:1: error: "int" not callable', 'foo/y.py:123: note: "X" not defined'] old_msgs = ['foo/y.py:12: note: "Y" not defined', 'x.py:8: error: "str" not callable'] assert sort_messages_preserving_file_order(msgs, ol...
TestMessageSorting
python
google__jax
tests/compilation_cache_test.py
{ "start": 3080, "end": 26735 }
class ____(CompilationCacheTestCase): def setUp(self): super().setUp() supported_platforms = ["tpu", "gpu", "cpu"] if not jtu.test_device_matches(supported_platforms): raise SkipTest( "serialize executable only works on " + ",".join(supported_platforms) ) def test_get_no_executab...
CompilationCacheTest
python
redis__redis-py
tests/test_connection_pool.py
{ "start": 19386, "end": 23066 }
class ____: def test_host(self): pool = redis.ConnectionPool.from_url("rediss://my.host") assert pool.connection_class == redis.SSLConnection assert pool.connection_kwargs == {"host": "my.host"} def test_connection_class_override(self): class MyConnection(redis.SSLConnection): ...
TestSSLConnectionURLParsing
python
pypa__warehouse
tests/unit/manage/views/test_organizations.py
{ "start": 28660, "end": 48614 }
class ____: @pytest.mark.usefixtures("_enable_organizations") def test_manage_organization(self, db_request, organization_service, monkeypatch): db_request.user = pretend.stub() organization = OrganizationFactory.create() OrganizationProjectFactory.create( organization=organi...
TestManageOrganizationSettings
python
django__django
tests/fixtures_regress/models.py
{ "start": 2899, "end": 3308 }
class ____(models.Model): name = models.CharField(max_length=255) author = models.ForeignKey(Person, models.CASCADE) stores = models.ManyToManyField(Store) class Meta: ordering = ("name",) def __str__(self): return "%s by %s (available at %s)" % ( self.name, ...
Book
python
PrefectHQ__prefect
src/prefect/events/filters.py
{ "start": 2283, "end": 2884 }
class ____(EventDataFilter): since: DateTime = Field( default_factory=lambda: prefect.types._datetime.start_of_day( prefect.types._datetime.now("UTC") ) - datetime.timedelta(days=180), description="Only include events after this time (inclusive)", ) until: DateTim...
EventOccurredFilter
python
Lightning-AI__lightning
src/lightning/pytorch/loops/progress.py
{ "start": 3008, "end": 3949 }
class ____(_StartedTracker): """Track an event's progress. Args: ready: Intended to track the number of events ready to start. started: Intended to be incremented after the event is started (e.g. after ``on_*_start`` runs). processed: Intended to be incremented after the event is proces...
_ProcessedTracker
python
skorch-dev__skorch
scripts/hf-integration-tests.py
{ "start": 2457, "end": 4326 }
class ____(nn.Module): def __init__(self, name, num_labels): super().__init__() self.name = name self.num_labels = num_labels self.reset_weights() def reset_weights(self): self.bert = AutoModelForSequenceClassification.from_pretrained( self.name, num_labels=...
BertModule
python
jazzband__django-polymorphic
src/polymorphic/base.py
{ "start": 561, "end": 737 }
class ____(RuntimeWarning): pass ################################################################################### # PolymorphicModel meta class
ManagerInheritanceWarning
python
viewflow__viewflow
viewflow/workflow/nodes/mixins.py
{ "start": 734, "end": 1676 }
class ____(object): """Mixin for nodes that have only one outgoing path.""" def __init__(self, *args, **kwargs): # noqa D102 self._next = None self._task_data = None self._task_seed = None super().__init__(*args, **kwargs) def Next( self, node, task...
NextNodeMixin
python
doocs__leetcode
solution/1700-1799/1746.Maximum Subarray Sum After One Operation/Solution.py
{ "start": 0, "end": 292 }
class ____: def maxSumAfterOperation(self, nums: List[int]) -> int: f = g = 0 ans = -inf for x in nums: ff = max(f, 0) + x gg = max(max(f, 0) + x * x, g + x) f, g = ff, gg ans = max(ans, f, g) return ans
Solution
python
bokeh__bokeh
src/bokeh/models/widgets/tables.py
{ "start": 8887, "end": 16118 }
class ____(StringFormatter): ''' Date cell formatter. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) format = Either(Enum(DateFormat), String, default='ISO-8601', help=""" The date format can ...
DateFormatter
python
astropy__astropy
astropy/visualization/wcsaxes/transforms.py
{ "start": 5661, "end": 6411 }
class ____(CurvedTransform, metaclass=abc.ABCMeta): """ Base transformation from pixel to world coordinates. """ has_inverse = True frame_out = None @property @abc.abstractmethod def output_dims(self): """ The number of output world dimensions. """ @abc.abs...
Pixel2WorldTransform
python
joke2k__faker
faker/providers/bank/pl_PL/__init__.py
{ "start": 42, "end": 180 }
class ____(BankProvider): """Implement bank provider for ``pl_PL`` locale.""" bban_format = "#" * 24 country_code = "PL"
Provider
python
allegroai__clearml
clearml/backend_api/services/v2_20/tasks.py
{ "start": 92095, "end": 95384 }
class ____(Response): """ Response of tasks.archive_many endpoint. :param succeeded: :type succeeded: Sequence[dict] :param failed: :type failed: Sequence[dict] """ _service = "tasks" _action = "archive_many" _version = "2.20" _schema = { "definitions": {}, ...
ArchiveManyResponse
python
jina-ai__jina
tests/integration/docker_volumes/filewriter-exec/executor.py
{ "start": 49, "end": 305 }
class ____(Executor): @requests def foo(self, **kwargs): print(self.workspace) file = os.path.join(self.workspace, 'out.txt') with open(file, 'w', encoding='utf-8') as f: f.write('Filewriter was here')
FilewriterExec
python
ray-project__ray
python/ray/data/tests/test_namespace_expressions.py
{ "start": 7842, "end": 9106 }
class ____: """Tests for string padding operations.""" def test_string_padding( self, dataset_format, method_name, method_kwargs, expected_value ): """Test string padding methods.""" data = [{"val": "hi"}] ds = _create_dataset(data, dataset_format) method = getattr...
TestStringPadding
python
google__pytype
pytype/pyi/parser_test.py
{ "start": 36318, "end": 41813 }
class ____(parser_test_base.ParserTestBase): def test_no_bases(self): canonical = """ class Foo: ... """ self.check(canonical, canonical) self.check( """ class Foo(): pass """, canonical, ) def test_bases(self): self.check(""" class Foo(...
ClassTest
python
networkx__networkx
networkx/algorithms/tree/tests/test_distance_measures.py
{ "start": 1922, "end": 3389 }
class ____: @pytest.mark.parametrize("n", [1, 2, 99, 100]) def test_tree_centroid_path_graphs(self, n): G = nx.path_graph(n) expected = {(n - 1) // 2, math.ceil((n - 1) / 2)} assert set(nx.tree.centroid(G)) == expected @pytest.mark.parametrize("r", range(2, 5)) @pytest.mark.para...
TestDistance
python
huggingface__transformers
src/transformers/models/sam3/modeling_sam3.py
{ "start": 40981, "end": 42734 }
class ____(Sam3PreTrainedModel): config_class = Sam3VisionConfig main_input_name = "pixel_values" _can_record_outputs = { "hidden_states": Sam3ViTLayer, "attentions": Sam3ViTRoPEAttention, } def __init__(self, config: Sam3VisionConfig): super().__init__(config) self....
Sam3VisionModel
python
pypa__warehouse
tests/unit/email/test_init.py
{ "start": 25997, "end": 28144 }
class ____: def test_new_email_added_emails(self, pyramid_request, pyramid_config, monkeypatch): stub_user = pretend.stub( id="id", username="username", name=None, email="foo@example.com" ) stub_email = pretend.stub(id="id", email="email@example.com", verified=False) new_...
TestNewEmailAddedEmails