id
stringlengths
16
16
source
stringclasses
2 values
repo
stringclasses
92 values
specification
stringlengths
78
30.9k
code
stringlengths
0
5k
url
stringlengths
37
200
c71a279a4c5f8774
docstring
scipy/scipy
def test(*, parent_callback, pytest_args, tests, coverage, durations, submodule, mode, array_api_backend, **kwargs): Run tests PYTEST_ARGS are passed through directly to pytest, e.g.: spin test -- --pdb To run tests on a directory or file:  spin test scipy/linalg To report the durations of the N s...
def test(*, parent_callback, pytest_args, tests, coverage, durations, submodule, mode, array_api_backend, **kwargs): """🔧 Run tests PYTEST_ARGS are passed through directly to pytest, e.g.: spin test -- --pdb To run tests on a directory or file: \b spin test scipy/linalg To...
https://github.com/scipy/scipy/blob/HEAD/.spin/cmds.py
7134dc214ba0b456
docstring
huggingface/transformers
def _load_class_with_fallback(mapping, backend): Load an image processor class from a backend-to-class mapping, with fallback. Tries the requested backend first, then the opposite standard backend, then any remaining backends. Works with both string class names and resolved class objects. Unavailable backends are de...
def _load_class_with_fallback(mapping, backend): """ Load an image processor class from a backend-to-class mapping, with fallback. Tries the requested backend first, then the opposite standard backend, then any remaining backends. Works with both string class names and resolved class objects. Unav...
https://github.com/huggingface/transformers/blob/HEAD/src/transformers/models/auto/image_processing_auto.py
3934ccfcc339135e
docstring
Textualize/textual
def tree(self) -> Tree: A Rich tree to display the DOM. Log this to visualize your app in the textual console. Example: ```python self.log(self.tree) ``` Returns: A Tree renderable.
def tree(self) -> Tree: """A Rich tree to display the DOM. Log this to visualize your app in the textual console. Example: ```python self.log(self.tree) ``` Returns: A Tree renderable. """ from rich.pretty import Pretty ...
https://github.com/Textualize/textual/blob/HEAD/src/textual/dom.py
f43c02cea744ebc3
docstring
dropbox/dropbox-sdk-python
def get_path_lookup(self): Only call this if :meth:`is_path_lookup` is true. :rtype: LookupError Raises: AttributeError("tag 'path_lookup' not set")
def get_path_lookup(self): """ Only call this if :meth:`is_path_lookup` is true. :rtype: LookupError """ if not self.is_path_lookup(): raise AttributeError("tag 'path_lookup' not set") return self._value
https://github.com/dropbox/dropbox-sdk-python/blob/HEAD/dropbox/files.py
932e716b4b969dbf
docstring
aio-libs/aiohttp
def decode(self, data: bytes) -> bytes: Decodes data synchronously. Decodes data according the specified Content-Encoding or Content-Transfer-Encoding headers value. Note: For large payloads, consider using decode_iter() instead to avoid blocking the event loop during decompression.
def decode(self, data: bytes) -> bytes: """Decodes data synchronously. Decodes data according the specified Content-Encoding or Content-Transfer-Encoding headers value. Note: For large payloads, consider using decode_iter() instead to avoid blocking the event loop during decomp...
https://github.com/aio-libs/aiohttp/blob/HEAD/aiohttp/multipart.py
32bc21dc22b63ef7
docstring
huggingface/datasets
def format_table( table: Table, key: Union[int, slice, range, str, Iterable], formatter: Formatter, format_columns: Optional[list] = None, output_all_columns=False, ): Format a Table depending on the key that was used and a Formatter object. Args: table (``datasets.table.Table``): The input Ta...
def format_table( table: Table, key: Union[int, slice, range, str, Iterable], formatter: Formatter, format_columns: Optional[list] = None, output_all_columns=False, ): """ Format a Table depending on the key that was used and a Formatter object. Args: table (``datasets.table.Tab...
https://github.com/huggingface/datasets/blob/HEAD/src/datasets/formatting/formatting.py
eaa654d9e8eefb1d
docstring
matplotlib/matplotlib
def _get_subplotspec_with_optional_colorbar(self): Return the subplotspec for this Axes, except that if this Axes has been moved to a subgridspec to make room for a colorbar, then return the subplotspec that encloses both this Axes and the colorbar Axes.
def _get_subplotspec_with_optional_colorbar(self): """ Return the subplotspec for this Axes, except that if this Axes has been moved to a subgridspec to make room for a colorbar, then return the subplotspec that encloses both this Axes and the colorbar Axes. """ ss = self...
https://github.com/matplotlib/matplotlib/blob/HEAD/lib/matplotlib/axes/_base.py
fd32ddda57fc969f
github_issue
dropbox/dropbox-sdk-python
High-level diagram visualization of the dropbox-sdk-python codebase <!-- Thank you for your pull request. Please provide a description below. --> This PR introduces markdown (mermaid) documentation in order for new people to get up-to-speed faster. You can see how the docs render here: https://github.com/CodeBoar...
https://github.com/dropbox/dropbox-sdk-python/pull/515
47e268f9e725c535
docstring
qdrant/qdrant-client
def is_supported_sparse_model(cls, model_name: str) -> bool: Checks if the model is supported by fastembed. Args: model_name (str): The name of the model to check. Returns: bool: True if the model is supported, False otherwise.
def is_supported_sparse_model(cls, model_name: str) -> bool: """Checks if the model is supported by fastembed. Args: model_name (str): The name of the model to check. Returns: bool: True if the model is supported, False otherwise. """ if model_name.lower...
https://github.com/qdrant/qdrant-client/blob/HEAD/qdrant_client/fastembed_common.py
a2e1806c67a078ec
docstring
prompt-toolkit/python-prompt-toolkit
def get_height_for_line( self, lineno: int, width: int, get_line_prefix: GetLinePrefixCallable | None, slice_stop: int | None = None, ) -> int: Return the height that a given line would need if it is rendered in a space with the given width (using line wrapping). :param get...
def get_height_for_line( self, lineno: int, width: int, get_line_prefix: GetLinePrefixCallable | None, slice_stop: int | None = None, ) -> int: """ Return the height that a given line would need if it is rendered in a space with the given width (using ...
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/HEAD/src/prompt_toolkit/layout/controls.py
0a330a0a4a23b4bf
docstring
python-trio/trio
def current_statistics() -> RunStatistics: Returns ``RunStatistics``, which contains run-loop-level debugging information. Currently, the following fields are defined: * ``tasks_living`` (int): The number of tasks that have been spawned and not yet exited. * ``tasks_runnable`` (int): The number of tasks that are c...
def current_statistics() -> RunStatistics: """Returns ``RunStatistics``, which contains run-loop-level debugging information. Currently, the following fields are defined: * ``tasks_living`` (int): The number of tasks that have been spawned and not yet exited. * ``tasks_runnable`` (int): The numb...
https://github.com/python-trio/trio/blob/HEAD/src/trio/_core/_generated_run.py
4e3dc193b4628de6
docstring
urllib3/urllib3
def request_chunked( self, method: str, url: str, body: _TYPE_BODY | None = None, headers: typing.Mapping[str, str] | None = None, ) -> None: Alternative to the common request method, which sends the body with chunked encoding and not as one block
def request_chunked( self, method: str, url: str, body: _TYPE_BODY | None = None, headers: typing.Mapping[str, str] | None = None, ) -> None: """ Alternative to the common request method, which sends the body with chunked encoding and not as one block ...
https://github.com/urllib3/urllib3/blob/HEAD/src/urllib3/connection.py
9dc8ac3bb8009b9d
docstring
lepture/authlib
def get_token_grant(self, request): Find the token grant for current request. :param request: OAuth2Request instance. :return: grant instance Raises: UnsupportedGrantTypeError(request.payload.grant_type)
def get_token_grant(self, request): """Find the token grant for current request. :param request: OAuth2Request instance. :return: grant instance """ for grant_cls, extensions in self._token_grants: if grant_cls.check_token_endpoint(request): return _c...
https://github.com/lepture/authlib/blob/HEAD/authlib/oauth2/rfc6749/authorization_server.py
a4178ff7e454e675
docstring
dask/dask
def nanmedian(a, axis=None, keepdims=False, out=None): This works by automatically chunking the reduced axes to a single chunk and then calling ``numpy.nanmedian`` function across the remaining dimensions Raises: NotImplementedError('The da.nanmedian function only works along an axis or a subset of axes. The ful...
def nanmedian(a, axis=None, keepdims=False, out=None): """ This works by automatically chunking the reduced axes to a single chunk and then calling ``numpy.nanmedian`` function across the remaining dimensions """ if axis is None: raise NotImplementedError( "The da.nanmedian funct...
https://github.com/dask/dask/blob/HEAD/dask/array/reductions.py
9df2b720c8373fd4
docstring
googleapis/python-pubsub
def detach_subscription( self, ) -> Callable[ [pubsub.DetachSubscriptionRequest], pubsub.DetachSubscriptionResponse ]: Return a callable for the detach subscription method over gRPC. Detaches a subscription from this topic. All messages retained in the subscription are dropped. Subsequent ``Pu...
def detach_subscription( self, ) -> Callable[ [pubsub.DetachSubscriptionRequest], pubsub.DetachSubscriptionResponse ]: r"""Return a callable for the detach subscription method over gRPC. Detaches a subscription from this topic. All messages retained in the subscription a...
https://github.com/googleapis/python-pubsub/blob/HEAD/google/pubsub_v1/services/publisher/transports/grpc.py
d23b2a6ac9c090d4
docstring
huggingface/transformers
def _load_pretrained_model( model: "PreTrainedModel", state_dict: dict | None, checkpoint_files: list[str] | None, load_config: LoadStateDictConfig, expected_keys: list[str] | None = None, ) -> tuple[LoadStateDictInfo, dict]: Perform the actual loading of some checkpoints in...
def _load_pretrained_model( model: "PreTrainedModel", state_dict: dict | None, checkpoint_files: list[str] | None, load_config: LoadStateDictConfig, expected_keys: list[str] | None = None, ) -> tuple[LoadStateDictInfo, dict]: """Perform the actual loading of some chec...
https://github.com/huggingface/transformers/blob/HEAD/src/transformers/modeling_utils.py
88b7fc77acb7ef18
docstring
boto/boto3
def deserialize(self, value): The method to deserialize the DynamoDB data types. :param value: A DynamoDB value to be deserialized to a pythonic value. Here are the various conversions: DynamoDB Python -------- ------ {'NULL': True} ...
def deserialize(self, value): """The method to deserialize the DynamoDB data types. :param value: A DynamoDB value to be deserialized to a pythonic value. Here are the various conversions: DynamoDB Python -------- ...
https://github.com/boto/boto3/blob/HEAD/boto3/dynamodb/types.py
2a2073ded272c32b
docstring
psf/requests
def send( self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None ): Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (o...
def send( self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None ): """Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request c...
https://github.com/psf/requests/blob/HEAD/src/requests/adapters.py
4028722be29824b4
docstring
astropy/astropy
def __missing__(self, ufunc): Called if a ufunc is not found. Check if the ufunc is in any of the available modules, and, if so, import the helpers for that module. Raises: TypeError(f'unknown ufunc {ufunc.__name__}. If you believe this ufunc should be supported, please raise an issue on https://github.com/astr...
def __missing__(self, ufunc): """Called if a ufunc is not found. Check if the ufunc is in any of the available modules, and, if so, import the helpers for that module. """ with self._lock: # Check if it was loaded while we waited for the lock if ufunc in ...
https://github.com/astropy/astropy/blob/HEAD/astropy/units/quantity_helper/converters.py
08d9a94b68f39072
docstring
twisted/twisted
def _setDOP(self, dopType, value): Sets a particular dilution of position value. @param dopType: The type of dilution of position to set. One of ('pdop', 'hdop', 'vdop'). @type dopType: C{str} @param value: The value to set the dilution of position type to. @type value: C{float} If this position error tests dil...
def _setDOP(self, dopType, value): """ Sets a particular dilution of position value. @param dopType: The type of dilution of position to set. One of ('pdop', 'hdop', 'vdop'). @type dopType: C{str} @param value: The value to set the dilution of position type to. ...
https://github.com/twisted/twisted/blob/HEAD/src/twisted/positioning/base.py
a0ff8b8ff630f04e
docstring
nltk/nltk
def executable(self, base_path): The function that determines the system specific binary that should be used in the pipeline. In case, the system is not known the default senna binary will be used.
def executable(self, base_path): """ The function that determines the system specific binary that should be used in the pipeline. In case, the system is not known the default senna binary will be used. """ os_name = system() if os_name == "Linux": bits...
https://github.com/nltk/nltk/blob/HEAD/nltk/classify/senna.py
7d535132773b562c
docstring
psf/black
def parse_req_python_version(requires_python: str) -> list[TargetVersion] | None: Parse a version string (i.e. ``"3.7"``) to a list of TargetVersion. If parsing fails, will raise a packaging.version.InvalidVersion error. If the parsed version cannot be mapped to a valid TargetVersion, returns None.
def parse_req_python_version(requires_python: str) -> list[TargetVersion] | None: """Parse a version string (i.e. ``"3.7"``) to a list of TargetVersion. If parsing fails, will raise a packaging.version.InvalidVersion error. If the parsed version cannot be mapped to a valid TargetVersion, returns None. ...
https://github.com/psf/black/blob/HEAD/src/black/files.py
f97e3239d3453466
docstring
redis/redis-py
def arrtrim(self, name: str, path: str, start: int, stop: int) -> ( int | list[int | None] | None ) | Awaitable[int | list[int | None] | None]: Trim the array JSON value under ``path`` at key ``name`` to the inclusive range given by ``start`` and ``stop``. For more information see `JSON.ARRTRIM <https://r...
def arrtrim(self, name: str, path: str, start: int, stop: int) -> ( int | list[int | None] | None ) | Awaitable[int | list[int | None] | None]: """Trim the array JSON value under ``path`` at key ``name`` to the inclusive range given by ``start`` and ``stop``. For more information se...
https://github.com/redis/redis-py/blob/HEAD/redis/commands/json/commands.py
7a822c7a2128412e
docstring
urllib3/urllib3
def from_int( cls, retries: Retry | bool | int | None, redirect: bool | int | None = True, default: Retry | bool | int | None = None, ) -> Retry: Backwards-compatibility for the old retries format.
def from_int( cls, retries: Retry | bool | int | None, redirect: bool | int | None = True, default: Retry | bool | int | None = None, ) -> Retry: """Backwards-compatibility for the old retries format.""" if retries is None: retries = default if default is ...
https://github.com/urllib3/urllib3/blob/HEAD/src/urllib3/util/retry.py
d839e13196e7e245
docstring
redis/redis-py
def record_error_count( self, server_address: Optional[str] = None, server_port: Optional[int] = None, network_peer_address: Optional[str] = None, network_peer_port: Optional[int] = None, error_type: Optional[Exception] = None, retry_attempts: Optional[int] = None...
def record_error_count( self, server_address: Optional[str] = None, server_port: Optional[int] = None, network_peer_address: Optional[str] = None, network_peer_port: Optional[int] = None, error_type: Optional[Exception] = None, retry_attempts: Optional[int] = None...
https://github.com/redis/redis-py/blob/HEAD/redis/observability/metrics.py
14a447244c0e3809
docstring
chroma-core/chroma
def get_sql( query: pypika.queries.QueryBuilder, formatstr: str = "?" ) -> Tuple[str, Tuple[Any, ...]]: Wrapper for pypika's get_sql method that allows the values for Parameters to be expressed inline while building a query, and that returns a tuple of the SQL string and parameters. This makes it easier to constru...
def get_sql( query: pypika.queries.QueryBuilder, formatstr: str = "?" ) -> Tuple[str, Tuple[Any, ...]]: """ Wrapper for pypika's get_sql method that allows the values for Parameters to be expressed inline while building a query, and that returns a tuple of the SQL string and parameters. This makes i...
https://github.com/chroma-core/chroma/blob/HEAD/chromadb/db/base.py
8282221c4efdf50d
docstring
googleapis/python-bigquery
def from_api_repr(cls, api_repr: dict) -> ExternalCatalogDatasetOptions: Factory: constructs an instance of the class (cls) given its API representation. Args: api_repr (Dict[str, Any]): API representation of the object to be instantiated. Returns: An instance of the class initialized with data from ...
def from_api_repr(cls, api_repr: dict) -> ExternalCatalogDatasetOptions: """Factory: constructs an instance of the class (cls) given its API representation. Args: api_repr (Dict[str, Any]): API representation of the object to be instantiated. Returns: ...
https://github.com/googleapis/python-bigquery/blob/HEAD/google/cloud/bigquery/external_config.py
ef9656423a592539
docstring
python-trio/trio
async def open_tcp_listeners( port: int, *, host: str | bytes | None = None, backlog: int | None = None, ) -> list[trio.SocketListener]: Create :class:`SocketListener` objects to listen for TCP connections. Args: port (int): The port to listen on. If you use 0 as your port, then the kernel w...
async def open_tcp_listeners( port: int, *, host: str | bytes | None = None, backlog: int | None = None, ) -> list[trio.SocketListener]: """Create :class:`SocketListener` objects to listen for TCP connections. Args: port (int): The port to listen on. If you use 0 as your port,...
https://github.com/python-trio/trio/blob/HEAD/src/trio/_highlevel_open_tcp_listeners.py
3168fed5f75e9cca
docstring
huggingface/datasets
def check_acceptable_input_type(data, allow64): Check that the data has an acceptable type for tensor encoding. :param data: array :param allow64: allow 64 bit types Raises: ValueError('unsupported dataypte') ValueError('64 bit datatypes not allowed unless explicitly enabled')
def check_acceptable_input_type(data, allow64): """Check that the data has an acceptable type for tensor encoding. :param data: array :param allow64: allow 64 bit types """ for a in data: if a.dtype.name not in long_to_short: raise ValueError("unsupported dataypte") if n...
https://github.com/huggingface/datasets/blob/HEAD/src/datasets/packaged_modules/webdataset/_tenbin.py
07a938ebee81ca79
docstring
UKPLab/sentence-transformers
def embed_minibatch( self, sentence_feature: dict[str, Tensor], begin: int, end: int, with_grad: bool, copy_random_state: bool, random_state: RandContext | None = None, ) -> tuple[Tensor, Tensor, RandContext | None]: Do forward pass on a minibatch of the inpu...
def embed_minibatch( self, sentence_feature: dict[str, Tensor], begin: int, end: int, with_grad: bool, copy_random_state: bool, random_state: RandContext | None = None, ) -> tuple[Tensor, Tensor, RandContext | None]: """Do forward pass on a minibatch o...
https://github.com/UKPLab/sentence-transformers/blob/HEAD/sentence_transformers/losses/CachedGISTEmbedLoss.py
596ce16f23059672
docstring
twisted/twisted
def auth_keyboard_interactive(self) -> bool: Try to authenticate with keyboard-interactive authentication. Send the request to the server and return True.
def auth_keyboard_interactive(self) -> bool: """ Try to authenticate with keyboard-interactive authentication. Send the request to the server and return True. """ self._log.debug("authing with keyboard-interactive") self.askForAuth(b"keyboard-interactive", NS(b"") + NS(b...
https://github.com/twisted/twisted/blob/HEAD/src/twisted/conch/ssh/userauth.py
17a2e5b248a18fc8
docstring
twisted/twisted
def __repr__(self) -> str: Returns a string representation of this angle. @return: The string representation. @rtype: C{str}
def __repr__(self) -> str: """ Returns a string representation of this angle. @return: The string representation. @rtype: C{str} """ if self.variation is None: variationRepr = "unknown variation" else: variationRepr = repr(self.variation) ...
https://github.com/twisted/twisted/blob/HEAD/src/twisted/positioning/base.py
1ca30cf5d6abed0f
docstring
astropy/astropy
def _pixel_to_world_correlation_matrix(wcs): Return a correlation matrix between the pixel coordinates and the high level world coordinates, along with the list of high level world coordinate classes. The shape of the matrix is ``(n_world, n_pix)``, where ``n_world`` is the number of high level world coordinates.
def _pixel_to_world_correlation_matrix(wcs): """ Return a correlation matrix between the pixel coordinates and the high level world coordinates, along with the list of high level world coordinate classes. The shape of the matrix is ``(n_world, n_pix)``, where ``n_world`` is the number of high l...
https://github.com/astropy/astropy/blob/HEAD/astropy/wcs/utils.py
56b1edc15018ecd4
docstring
twilio/twilio-python
def page( self, page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, ) -> DependentPhoneNumberPage: Retrieve a single page of DependentPhoneNumberInstance records from the API. Request is execute...
def page( self, page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, ) -> DependentPhoneNumberPage: """ Retrieve a single page of DependentPhoneNumberInstance records from the API....
https://github.com/twilio/twilio-python/blob/HEAD/twilio/rest/api/v2010/account/address/dependent_phone_number.py
e7d1177ba59cb42f
docstring
twilio/twilio-python
def _proxy(self) -> "AddressContext": Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: AddressContext for this AddressInstance
def _proxy(self) -> "AddressContext": """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: AddressContext for this AddressInstance """ if self._context is None: ...
https://github.com/twilio/twilio-python/blob/HEAD/twilio/rest/api/v2010/account/address/__init__.py
bfbc06ca45e3cf65
docstring
mongodb/mongo-python-driver
async def add_option(self, mask: int) -> AsyncCursor[_DocumentType]: Set arbitrary query flags using a bitmask. To set the tailable flag: cursor.add_option(2) Raises: TypeError(f'mask must be an int, not {type(mask)}') InvalidOperation("Can't use limit and exhaust together.") InvalidOperation('Exhaust cu...
async def add_option(self, mask: int) -> AsyncCursor[_DocumentType]: """Set arbitrary query flags using a bitmask. To set the tailable flag: cursor.add_option(2) """ if not isinstance(mask, int): raise TypeError(f"mask must be an int, not {type(mask)}") self....
https://github.com/mongodb/mongo-python-driver/blob/HEAD/pymongo/asynchronous/cursor.py
6c4da244501456ba
docstring
Lightning-AI/pytorch-lightning
def validation_step(self, *args: Any, **kwargs: Any) -> STEP_OUTPUT: Operates on a single batch of data from the validation set. In this step you'd might generate examples or calculate anything of interest like accuracy. Args: batch: The output of your data iterable, normally a :class:`~torch.utils.data.DataLoade...
def validation_step(self, *args: Any, **kwargs: Any) -> STEP_OUTPUT: r"""Operates on a single batch of data from the validation set. In this step you'd might generate examples or calculate anything of interest like accuracy. Args: batch: The output of your data iterable, normally a ...
https://github.com/Lightning-AI/pytorch-lightning/blob/HEAD/src/lightning/pytorch/core/module.py
a915ded495873982
docstring
elastic/elasticsearch-py
async def list( self, *, connector_name: t.Optional[t.Union[str, t.Sequence[str]]] = None, error_trace: t.Optional[bool] = None, filter_path: t.Optional[t.Union[str, t.Sequence[str]]] = None, from_: t.Optional[int] = None, human: t.Optional[bool] = None, i...
async def list( self, *, connector_name: t.Optional[t.Union[str, t.Sequence[str]]] = None, error_trace: t.Optional[bool] = None, filter_path: t.Optional[t.Union[str, t.Sequence[str]]] = None, from_: t.Optional[int] = None, human: t.Optional[bool] = None, i...
https://github.com/elastic/elasticsearch-py/blob/HEAD/elasticsearch/_async/client/connector.py
1a4611eafb980a8e
docstring
astropy/astropy
def world_to_array_index(self, *world_objects): Convert world coordinates (represented by Astropy objects) to array indices. If `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_n_dim` is ``1``, this method returns a single scalar or array, otherwise a tuple of scalars or arrays is returned. See `~astropy.wcs.wcsapi.BaseLow...
def world_to_array_index(self, *world_objects): """ Convert world coordinates (represented by Astropy objects) to array indices. If `~astropy.wcs.wcsapi.BaseLowLevelWCS.pixel_n_dim` is ``1``, this method returns a single scalar or array, otherwise a tuple of scalars or a...
https://github.com/astropy/astropy/blob/HEAD/astropy/wcs/wcsapi/high_level_api.py
aa2e0ea568118a51
docstring
elastic/elasticsearch-py
async def delete_ip_location_database( self, *, id: t.Union[str, t.Sequence[str]], error_trace: t.Optional[bool] = None, filter_path: t.Optional[t.Union[str, t.Sequence[str]]] = None, human: t.Optional[bool] = None, master_timeout: t.Optional[t.Union[str, t.Litera...
async def delete_ip_location_database( self, *, id: t.Union[str, t.Sequence[str]], error_trace: t.Optional[bool] = None, filter_path: t.Optional[t.Union[str, t.Sequence[str]]] = None, human: t.Optional[bool] = None, master_timeout: t.Optional[t.Union[str, t.Litera...
https://github.com/elastic/elasticsearch-py/blob/HEAD/elasticsearch/_async/client/ingest.py
d008239f5fcfb802
docstring
joblib/joblib
def print_progress(self): Display the process of the parallel execution only a fraction of time, controlled by self.verbose.
def print_progress(self): """Display the process of the parallel execution only a fraction of time, controlled by self.verbose. """ if not self.verbose: return if self.n_tasks is not None and self.n_tasks > 0: width = floor(log10(self.n_tasks)) + 1 ...
https://github.com/joblib/joblib/blob/HEAD/joblib/parallel.py
aac8ef96d0a9f925
github_issue
python-poetry/poetry
fix: seek to range_start in lazy_wheel _ensure_downloaded _ensure_downloaded() was seeking to `start` (the beginning of the requested range) instead of `range_start` (the beginning of the sub-interval actually being fetched). When part of a range was already cached, data for later sub-ranges was written at the wrong f...
https://github.com/python-poetry/poetry/pull/10806
29ec7cec7f6a317f
docstring
twisted/twisted
def list(self, channels): Send a group of LIST response lines @type channels: C{list} of C{(str, int, str)} @param channels: Information about the channels being sent: their name, the number of participants, and their topic.
def list(self, channels): """ Send a group of LIST response lines @type channels: C{list} of C{(str, int, str)} @param channels: Information about the channels being sent: their name, the number of participants, and their topic. """ for name, size, topic in c...
https://github.com/twisted/twisted/blob/HEAD/src/twisted/words/service.py
7867be2f1fee5c0e
docstring
dask/dask
def apply_along_axis(func1d, axis, arr, *args, dtype=None, shape=None, **kwargs): This is a blocked variant of :func:`numpy.apply_along_axis` implemented via :func:`dask.array.map_blocks` Notes ----- If either of `dtype` or `shape` are not provided, Dask attempts to determine them by calling `func1d` on a dummy array...
def apply_along_axis(func1d, axis, arr, *args, dtype=None, shape=None, **kwargs): """ This is a blocked variant of :func:`numpy.apply_along_axis` implemented via :func:`dask.array.map_blocks` Notes ----- If either of `dtype` or `shape` are not provided, Dask attempts to determine them by ca...
https://github.com/dask/dask/blob/HEAD/dask/array/routines.py
25cee4721a8a86ed
docstring
networkx/networkx
def _find_chordality_breaker(G, s=None, treewidth_bound=sys.maxsize): Given a graph G, starts a max cardinality search (starting from s if s is given and from an arbitrary node otherwise) trying to find a non-chordal cycle. If it does find one, it returns (u,v,w) where u,v,w are the three nodes that together with s a...
def _find_chordality_breaker(G, s=None, treewidth_bound=sys.maxsize): """Given a graph G, starts a max cardinality search (starting from s if s is given and from an arbitrary node otherwise) trying to find a non-chordal cycle. If it does find one, it returns (u,v,w) where u,v,w are the three nodes ...
https://github.com/networkx/networkx/blob/HEAD/networkx/algorithms/chordal.py
23caabb7adaa78c8
docstring
pandas-dev/pandas
def _slice(self, slobj: slice, axis: AxisInt = 0) -> Self: Construct a slice of this container. Slicing with this method is *always* positional.
def _slice(self, slobj: slice, axis: AxisInt = 0) -> Self: """ Construct a slice of this container. Slicing with this method is *always* positional. """ assert isinstance(slobj, slice), type(slobj) axis = self._get_block_manager_axis(axis) new_mgr = self._mgr.get...
https://github.com/pandas-dev/pandas/blob/HEAD/pandas/core/generic.py
f65989b77b9ab42b
docstring
sympy/sympy
def log(self): Returns the logarithm of the quaternion, given by $\log q$. Examples ======== >>> from sympy import Quaternion >>> q = Quaternion(1, 2, 3, 4) >>> q.log() log(sqrt(30)) + 2*sqrt(29)*acos(sqrt(30)/30)/29*i + 3*sqrt(29)*acos(sqrt(30)/30)/29*j + 4*sqrt(29)*acos(sqrt(30)/30)/29*k Raises: ValueError('C...
def log(self): r"""Returns the logarithm of the quaternion, given by $\log q$. Examples ======== >>> from sympy import Quaternion >>> q = Quaternion(1, 2, 3, 4) >>> q.log() log(sqrt(30)) + 2*sqrt(29)*acos(sqrt(30)/30)/29*i + 3*sqrt(29)*acos(sqrt(...
https://github.com/sympy/sympy/blob/HEAD/sympy/algebras/quaternion.py
d57ef23e6fd42262
docstring
explosion/spaCy
def biluo_tags_to_spans(doc: Doc, tags: Iterable[str]) -> List[Span]: Encode per-token tags following the BILUO scheme into Span object, e.g. to overwrite the doc.ents. doc (Doc): The document that the BILUO tags refer to. tags (iterable): A sequence of BILUO tags with each tag describing one token. Each tag stri...
def biluo_tags_to_spans(doc: Doc, tags: Iterable[str]) -> List[Span]: """Encode per-token tags following the BILUO scheme into Span object, e.g. to overwrite the doc.ents. doc (Doc): The document that the BILUO tags refer to. tags (iterable): A sequence of BILUO tags with each tag describing one ...
https://github.com/explosion/spaCy/blob/HEAD/spacy/training/iob_utils.py
408b30f092c690f8
docstring
mongodb/mongo-python-driver
def _cleanup_cursor_lock( self, cursor_id: int, address: Optional[_CursorAddress], conn_mgr: _ConnectionManager, session: Optional[ClientSession], ) -> None: Cleanup a cursor from cursor.close() using a lock. This method handles cleanup for Cursors/CommandCursors including ...
def _cleanup_cursor_lock( self, cursor_id: int, address: Optional[_CursorAddress], conn_mgr: _ConnectionManager, session: Optional[ClientSession], ) -> None: """Cleanup a cursor from cursor.close() using a lock. This method handles cleanup for Cursors/Command...
https://github.com/mongodb/mongo-python-driver/blob/HEAD/pymongo/synchronous/mongo_client.py
03a05cd7cc3c7c5a
docstring
redis/redis-py
def record_csc_eviction( count: int, reason: Optional[CSCReason] = None, ) -> None: Record a Client Side Caching (CSC) eviction. Args: count: Number of evictions reason: Reason for eviction
def record_csc_eviction( count: int, reason: Optional[CSCReason] = None, ) -> None: """ Record a Client Side Caching (CSC) eviction. Args: count: Number of evictions reason: Reason for eviction """ global _metrics_collector if _metrics_collector is None: _metric...
https://github.com/redis/redis-py/blob/HEAD/redis/observability/recorder.py
25b8ff1cd1dd832b
docstring
pallets/flask
def template_global( self, name: T_template_global | str | None = None ) -> T_template_global | t.Callable[[T_template_global], T_template_global]: Decorate a function to register it as a custom Jinja global. The name is optional. The decorator may be used without parentheses. .. code-block:: python ...
def template_global( self, name: T_template_global | str | None = None ) -> T_template_global | t.Callable[[T_template_global], T_template_global]: """Decorate a function to register it as a custom Jinja global. The name is optional. The decorator may be used without parentheses. .....
https://github.com/pallets/flask/blob/HEAD/src/flask/sansio/app.py
653592078fd2ca3f
docstring
googleapis/python-bigquery
def try_import(self, raise_if_error: bool = False) -> Any: Verifies that a recent enough version of pyarrow extra is installed. The function assumes that pyarrow extra is installed, and should thus be used in places where this assumption holds. Because `pip` can install an outdated version of this extra despite the ...
def try_import(self, raise_if_error: bool = False) -> Any: """Verifies that a recent enough version of pyarrow extra is installed. The function assumes that pyarrow extra is installed, and should thus be used in places where this assumption holds. Because `pip` can install an outdated ...
https://github.com/googleapis/python-bigquery/blob/HEAD/google/cloud/bigquery/_versions_helpers.py
959b7a0c8925ffc4
docstring
google/flax
def bind( self: M, variables: VariableDict, *args, rngs: RNGSequences | None = None, mutable: CollectionFilter = False, ) -> M: Creates an interactive Module instance by binding variables and RNGs. ``bind`` provides an "interactive" instance of a Module directly without transforming a function w...
def bind( self: M, variables: VariableDict, *args, rngs: RNGSequences | None = None, mutable: CollectionFilter = False, ) -> M: """Creates an interactive Module instance by binding variables and RNGs. ``bind`` provides an "interactive" instance of a Module directly without transformin...
https://github.com/google/flax/blob/HEAD/flax/linen/module.py
76cbebcf6dfc02e9
docstring
mlflow/mlflow
def _run_session_scorer( scorer: Any, trace_ids: list[str], tracking_store: AbstractStore, log_assessments: bool, ) -> dict[str, TraceResult]: Run a session-level scorer on all traces as a conversation. Reuses evaluate_session_level_scorers from the evaluation harness. Args: scorer: The scorer in...
def _run_session_scorer( scorer: Any, trace_ids: list[str], tracking_store: AbstractStore, log_assessments: bool, ) -> dict[str, TraceResult]: """ Run a session-level scorer on all traces as a conversation. Reuses evaluate_session_level_scorers from the evaluation harness. Args: ...
https://github.com/mlflow/mlflow/blob/HEAD/mlflow/genai/scorers/job.py
c186cf287dadb365
docstring
matplotlib/matplotlib
def set_rlim(self, bottom=None, top=None, *, emit=True, auto=False, **kwargs): Set the radial axis view limits. This function behaves like `.Axes.set_ylim`, but additionally supports *rmin* and *rmax* as aliases for *bottom* and *top*. See Also -------- .Axes.set_ylim Raises: ValueError('Cannot...
def set_rlim(self, bottom=None, top=None, *, emit=True, auto=False, **kwargs): """ Set the radial axis view limits. This function behaves like `.Axes.set_ylim`, but additionally supports *rmin* and *rmax* as aliases for *bottom* and *top*. See Also ----...
https://github.com/matplotlib/matplotlib/blob/HEAD/lib/matplotlib/projections/polar.py
5c494c848d31f56b
docstring
encode/uvicorn
def subprocess_started( config: Config, target: Callable[..., None], sockets: list[socket], stdin_fileno: int | None, ) -> None: Called when the child process starts. * config - The Uvicorn configuration instance. * target - A callable that accepts a list of sockets. In practice this will b...
def subprocess_started( config: Config, target: Callable[..., None], sockets: list[socket], stdin_fileno: int | None, ) -> None: """ Called when the child process starts. * config - The Uvicorn configuration instance. * target - A callable that accepts a list of sockets. In practice thi...
https://github.com/encode/uvicorn/blob/HEAD/uvicorn/_subprocess.py
65214409fc0d87d3
docstring
langchain-ai/langchain
async def run_in_executor( executor_or_config: Executor | RunnableConfig | None, func: Callable[P, T], *args: P.args, **kwargs: P.kwargs, ) -> T: Run a function in an executor. Args: executor_or_config: The executor or config to run in. func: The function. *args: The positional arguments t...
async def run_in_executor( executor_or_config: Executor | RunnableConfig | None, func: Callable[P, T], *args: P.args, **kwargs: P.kwargs, ) -> T: """Run a function in an executor. Args: executor_or_config: The executor or config to run in. func: The function. *args: The ...
https://github.com/langchain-ai/langchain/blob/HEAD/libs/core/langchain_core/runnables/config.py
088ed6a2d216f253
docstring
prefecthq/prefect
async def increment_concurrency_slots( self, names: list[str], slots: int, mode: Literal["concurrency", "rate_limit"], ) -> "Response": Increment concurrency slots for the specified limits. Args: names: A list of limit names for which to occupy slots. slots: The number of c...
async def increment_concurrency_slots( self, names: list[str], slots: int, mode: Literal["concurrency", "rate_limit"], ) -> "Response": """ Increment concurrency slots for the specified limits. Args: names: A list of limit names for which to occup...
https://github.com/prefecthq/prefect/blob/HEAD/src/prefect/client/orchestration/_concurrency_limits/client.py
afe713aff0463406
docstring
Textualize/rich
def get( cls, console: "Console", options: "ConsoleOptions", renderable: "RenderableType" ) -> "Measurement": Get a measurement for a renderable. Args: console (~rich.console.Console): Console instance. options (~rich.console.ConsoleOptions): Console options. renderable (RenderableType): An ob...
def get( cls, console: "Console", options: "ConsoleOptions", renderable: "RenderableType" ) -> "Measurement": """Get a measurement for a renderable. Args: console (~rich.console.Console): Console instance. options (~rich.console.ConsoleOptions): Console options. ...
https://github.com/Textualize/rich/blob/HEAD/rich/measure.py
ee786aa3c1d0f135
docstring
twisted/twisted
def warn(self, text: bytes) -> None: Notify the user (non-interactively) of the provided text, by writing it to the console. @param text: Some information the user is to be made aware of.
def warn(self, text: bytes) -> None: """ Notify the user (non-interactively) of the provided text, by writing it to the console. @param text: Some information the user is to be made aware of. """ try: with closing(self.opener()) as f: f.write(...
https://github.com/twisted/twisted/blob/HEAD/src/twisted/conch/client/knownhosts.py
c2c5033ee8de3455
docstring
huggingface/datasets
def is_small_dataset(dataset_size): Check if `dataset_size` is smaller than `config.IN_MEMORY_MAX_SIZE`. Args: dataset_size (int): Dataset size in bytes. Returns: bool: Whether `dataset_size` is smaller than `config.IN_MEMORY_MAX_SIZE`.
def is_small_dataset(dataset_size): """Check if `dataset_size` is smaller than `config.IN_MEMORY_MAX_SIZE`. Args: dataset_size (int): Dataset size in bytes. Returns: bool: Whether `dataset_size` is smaller than `config.IN_MEMORY_MAX_SIZE`. """ if dataset_size and config.IN_MEMORY_M...
https://github.com/huggingface/datasets/blob/HEAD/src/datasets/utils/info_utils.py
405490eaf119fb56
docstring
huggingface/accelerate
def align_module_device(module: torch.nn.Module, execution_device: Optional[torch.device] = None): Context manager that moves a module's parameters to the specified execution device. Args: module (`torch.nn.Module`): Module with parameters to align. execution_device (`torch.device`, *optional*): ...
def align_module_device(module: torch.nn.Module, execution_device: Optional[torch.device] = None): """ Context manager that moves a module's parameters to the specified execution device. Args: module (`torch.nn.Module`): Module with parameters to align. execution_device (`torch....
https://github.com/huggingface/accelerate/blob/HEAD/src/accelerate/utils/modeling.py
89102b52b44c21a3
docstring
mongodb/mongo-python-driver
def upload_from_stream_with_id( self, file_id: Any, filename: str, source: Any, chunk_size_bytes: Optional[int] = None, metadata: Optional[Mapping[str, Any]] = None, session: Optional[ClientSession] = None, ) -> None: Uploads a user file to a GridFS bucket wi...
def upload_from_stream_with_id( self, file_id: Any, filename: str, source: Any, chunk_size_bytes: Optional[int] = None, metadata: Optional[Mapping[str, Any]] = None, session: Optional[ClientSession] = None, ) -> None: """Uploads a user file to a GridFS...
https://github.com/mongodb/mongo-python-driver/blob/HEAD/gridfs/synchronous/grid_file.py
15642b8b24a7dde5
docstring
dask/dask
def safe_sqrt(a): A version of sqrt that properly handles scalar masked arrays. To mimic ``np.ma`` reductions, we need to convert scalar masked arrays that have an active mask to the ``np.ma.masked`` singleton. This is properly handled automatically for reduction code, but not for ufuncs. We implement a simple versio...
def safe_sqrt(a): """A version of sqrt that properly handles scalar masked arrays. To mimic ``np.ma`` reductions, we need to convert scalar masked arrays that have an active mask to the ``np.ma.masked`` singleton. This is properly handled automatically for reduction code, but not for ufuncs. We impleme...
https://github.com/dask/dask/blob/HEAD/dask/array/reductions.py
23c8259cdfaebc9e
docstring
nltk/nltk
def __init__(self, word_fd, bigram_fd, wildcard_fd, trigram_fd): Construct a TrigramCollocationFinder, given FreqDists for appearances of words, bigrams, two words with any word between them, and trigrams.
def __init__(self, word_fd, bigram_fd, wildcard_fd, trigram_fd): """Construct a TrigramCollocationFinder, given FreqDists for appearances of words, bigrams, two words with any word between them, and trigrams. """ AbstractCollocationFinder.__init__(self, word_fd, trigram_fd) ...
https://github.com/nltk/nltk/blob/HEAD/nltk/collocations.py
10ac03a2d9a67e57
docstring
kubernetes-client/python
def name(self, name): Sets the name of this ApiextensionsV1ServiceReference. name is the name of the service. Required # noqa: E501 :param name: The name of this ApiextensionsV1ServiceReference. # noqa: E501 :type: str Raises: ValueError('Invalid value for `name`, must not be `None`')
def name(self, name): """Sets the name of this ApiextensionsV1ServiceReference. name is the name of the service. Required # noqa: E501 :param name: The name of this ApiextensionsV1ServiceReference. # noqa: E501 :type: str """ if self.local_vars_configuration.client_si...
https://github.com/kubernetes-client/python/blob/HEAD/kubernetes/client/models/apiextensions_v1_service_reference.py
71fa36e240b3dd19
docstring
spotify/luigi
def get_task_cls(cls, name): Returns an unambiguous class or raises an exception. Raises: TaskClassNotFoundException(cls._missing_task_msg(name)) TaskClassAmbigiousException('Task %r is ambiguous' % name)
def get_task_cls(cls, name): """ Returns an unambiguous class or raises an exception. """ task_cls = cls._get_reg().get(name) if not task_cls: raise TaskClassNotFoundException(cls._missing_task_msg(name)) if task_cls == cls.AMBIGUOUS_CLASS: raise ...
https://github.com/spotify/luigi/blob/HEAD/luigi/task_register.py
407acef2359f0564
docstring
spotify/luigi
def clone(self, cls=None, **kwargs): Creates a new instance from an existing instance where some of the args have changed. There's at least two scenarios where this is useful (see test/clone_test.py): * remove a lot of boiler plate when you have recursive dependencies and lots of args * there's task inheritance and ...
def clone(self, cls=None, **kwargs): """ Creates a new instance from an existing instance where some of the args have changed. There's at least two scenarios where this is useful (see test/clone_test.py): * remove a lot of boiler plate when you have recursive dependencies and lots of a...
https://github.com/spotify/luigi/blob/HEAD/luigi/task.py
809065f12b83e439
docstring
sendgrid/sendgrid-python
def __init__(self, file_name=None): Create a FileName object :param file_name: The file name of the attachment :type file_name: string, optional
def __init__(self, file_name=None): """Create a FileName object :param file_name: The file name of the attachment :type file_name: string, optional """ self._file_name = None if file_name is not None: self.file_name = file_name
https://github.com/sendgrid/sendgrid-python/blob/HEAD/sendgrid/helpers/mail/file_name.py
65d090fd91da7c2e
docstring
prompt-toolkit/python-prompt-toolkit
def text(self, value: str) -> None: Setting text. (When doing this, make sure that the cursor_position is valid for this text. text/cursor_position should be consistent at any time, otherwise set a Document instead.) Raises: EditReadOnlyBuffer()
def text(self, value: str) -> None: """ Setting text. (When doing this, make sure that the cursor_position is valid for this text. text/cursor_position should be consistent at any time, otherwise set a Document instead.) """ # Ensure cursor position remains within the siz...
https://github.com/prompt-toolkit/python-prompt-toolkit/blob/HEAD/src/prompt_toolkit/buffer.py
2894c95773525938
docstring
twilio/twilio-python
def create_with_http_info(self, ip_access_control_list_sid: str) -> ApiResponse: Create the AuthCallsIpAccessControlListMappingInstance and return response metadata :param ip_access_control_list_sid: The SID of the IpAccessControlList resource to map to the SIP domain. :returns: ApiResponse with instance, status cod...
def create_with_http_info(self, ip_access_control_list_sid: str) -> ApiResponse: """ Create the AuthCallsIpAccessControlListMappingInstance and return response metadata :param ip_access_control_list_sid: The SID of the IpAccessControlList resource to map to the SIP domain. :returns: Ap...
https://github.com/twilio/twilio-python/blob/HEAD/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_ip_access_control_list_mapping.py
c9c552fff9c4632f
docstring
googleapis/python-storage
def _add_query_parameters(base_url, name_value_pairs): Add one query parameter to a base URL. :type base_url: string :param base_url: Base URL (may already contain query parameters) :type name_value_pairs: list of (string, string) tuples. :param name_value_pairs: Names and values of the query parameters to add :rty...
def _add_query_parameters(base_url, name_value_pairs): """Add one query parameter to a base URL. :type base_url: string :param base_url: Base URL (may already contain query parameters) :type name_value_pairs: list of (string, string) tuples. :param name_value_pairs: Names and values of the query p...
https://github.com/googleapis/python-storage/blob/HEAD/google/cloud/storage/blob.py
bf3b430d6557bc47
docstring
stripe/stripe-python
async def cancel_async( self, intent: str, params: Optional["PaymentIntentCancelParams"] = None, options: Optional["RequestOptions"] = None, ) -> "PaymentIntent": You can cancel a PaymentIntent object when it's in one of these statuses: requires_payment_method, requires_capture, req...
async def cancel_async( self, intent: str, params: Optional["PaymentIntentCancelParams"] = None, options: Optional["RequestOptions"] = None, ) -> "PaymentIntent": """ You can cancel a PaymentIntent object when it's in one of these statuses: requires_payment_method, re...
https://github.com/stripe/stripe-python/blob/HEAD/stripe/_payment_intent_service.py
5259b4149123e71f
docstring
sympy/sympy
def to_scipy_sparse(m, **options): Convert a sympy/numpy matrix to a scipy.sparse matrix. Raises: TypeError('Expected sympy/numpy/scipy.sparse matrix, got: %r' % m) ImportError
def to_scipy_sparse(m, **options): """Convert a sympy/numpy matrix to a scipy.sparse matrix.""" dtype = options.get('dtype', 'complex') if isinstance(m, (MatrixBase, Expr)): return sympy_to_scipy_sparse(m, dtype=dtype) elif isinstance(m, numpy_ndarray): if not sparse: raise I...
https://github.com/sympy/sympy/blob/HEAD/sympy/physics/quantum/matrixutils.py
f4ab78eadc757cd2
docstring
stripe/stripe-python
def retrieve( self, payout: str, params: Optional["PayoutRetrieveParams"] = None, options: Optional["RequestOptions"] = None, ) -> "Payout": Retrieves the details of an existing payout. Supply the unique payout ID from either a payout creation request or the payout list. Stripe retu...
def retrieve( self, payout: str, params: Optional["PayoutRetrieveParams"] = None, options: Optional["RequestOptions"] = None, ) -> "Payout": """ Retrieves the details of an existing payout. Supply the unique payout ID from either a payout creation request or the payou...
https://github.com/stripe/stripe-python/blob/HEAD/stripe/_payout_service.py
de3d2da7c07597ac
docstring
twilio/twilio-python
def iso8601_datetime(d): Return a string representation of a date that the Twilio API understands Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date
def iso8601_datetime(d): """ Return a string representation of a date that the Twilio API understands Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date """ if d == values.unset: return d elif isinstance(d, datetime.datetime) or isinstance(d, datetime.date): ...
https://github.com/twilio/twilio-python/blob/HEAD/twilio/base/serialize.py
e1f1fdb2dc7f9701
docstring
langchain-ai/langchain
def _set_config_context( config: RunnableConfig, ) -> tuple[Token[RunnableConfig | None], dict[str, Any] | None]: Set the child Runnable config + tracing context. Args: config: The config to set. Returns: The token to reset the config and the previous tracing context.
def _set_config_context( config: RunnableConfig, ) -> tuple[Token[RunnableConfig | None], dict[str, Any] | None]: """Set the child Runnable config + tracing context. Args: config: The config to set. Returns: The token to reset the config and the previous tracing context. """ # ...
https://github.com/langchain-ai/langchain/blob/HEAD/libs/core/langchain_core/runnables/config.py
d50097b51a9a8ed2
docstring
langchain-ai/langchain
def translate_content_chunk(message: AIMessageChunk) -> list[types.ContentBlock]: Derive standard content blocks from a message chunk with OpenAI content. Args: message: The message chunk to translate. Returns: The derived content blocks.
def translate_content_chunk(message: AIMessageChunk) -> list[types.ContentBlock]: """Derive standard content blocks from a message chunk with OpenAI content. Args: message: The message chunk to translate. Returns: The derived content blocks. """ if isinstance(message.content, str):...
https://github.com/langchain-ai/langchain/blob/HEAD/libs/core/langchain_core/messages/block_translators/openai.py
db3d56ee24268d86
docstring
pydantic/pydantic
def frozenset_schema( items_schema: CoreSchema | None = None, *, min_length: int | None = None, max_length: int | None = None, fail_fast: bool | None = None, strict: bool | None = None, ref: str | None = None, metadata: dict[str, Any] | None = None, serialization: SerSchema | None = ...
def frozenset_schema( items_schema: CoreSchema | None = None, *, min_length: int | None = None, max_length: int | None = None, fail_fast: bool | None = None, strict: bool | None = None, ref: str | None = None, metadata: dict[str, Any] | None = None, serialization: SerSchema | None = ...
https://github.com/pydantic/pydantic/blob/HEAD/pydantic-core/python/pydantic_core/core_schema.py
62e2b1a9e1da1c76
docstring
pallets/click
def _complete_visible_commands( ctx: Context, incomplete: str ) -> cabc.Iterator[tuple[str, Command]]: List all the subcommands of a group that start with the incomplete value and aren't hidden. :param ctx: Invocation context for the group. :param incomplete: Value being completed. May be empty.
def _complete_visible_commands( ctx: Context, incomplete: str ) -> cabc.Iterator[tuple[str, Command]]: """List all the subcommands of a group that start with the incomplete value and aren't hidden. :param ctx: Invocation context for the group. :param incomplete: Value being completed. May be empty....
https://github.com/pallets/click/blob/HEAD/src/click/core.py
24f74be86a46db8c
docstring
twilio/twilio-python
def get(self, sid: str) -> StreamContext: Constructs a StreamContext :param sid: The SID or the `name` of the Stream resource to be stopped
def get(self, sid: str) -> StreamContext: """ Constructs a StreamContext :param sid: The SID or the `name` of the Stream resource to be stopped """ return StreamContext( self._version, account_sid=self._solution["account_sid"], call_sid=self._...
https://github.com/twilio/twilio-python/blob/HEAD/twilio/rest/api/v2010/account/call/stream.py
ca5aaa123c019d0f
docstring
redis/redis-py
async def record_connection_handoff( pool_name: str, ) -> None: Record a connection handoff event (e.g., after MOVING notification). Args: pool_name: Connection pool identifier
async def record_connection_handoff( pool_name: str, ) -> None: """ Record a connection handoff event (e.g., after MOVING notification). Args: pool_name: Connection pool identifier """ collector = _get_or_create_collector() if collector is None: return try: coll...
https://github.com/redis/redis-py/blob/HEAD/redis/asyncio/observability/recorder.py
df7520c964027f1d
docstring
twilio/twilio-python
async def list_with_http_info_async( self, identity: Union[List[str], object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> ApiResponse: Asynchronously lists InviteInstance and returns headers from first page :param List[str] identity: The [User...
async def list_with_http_info_async( self, identity: Union[List[str], object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> ApiResponse: """ Asynchronously lists InviteInstance and returns headers from first page :param L...
https://github.com/twilio/twilio-python/blob/HEAD/twilio/rest/chat/v1/service/channel/invite.py
6d30dfdeb0fd701e
docstring
elastic/elasticsearch-py
def delete_trained_model( self, *, model_id: str, error_trace: t.Optional[bool] = None, filter_path: t.Optional[t.Union[str, t.Sequence[str]]] = None, force: t.Optional[bool] = None, human: t.Optional[bool] = None, pretty: t.Optional[bool] = None, ...
def delete_trained_model( self, *, model_id: str, error_trace: t.Optional[bool] = None, filter_path: t.Optional[t.Union[str, t.Sequence[str]]] = None, force: t.Optional[bool] = None, human: t.Optional[bool] = None, pretty: t.Optional[bool] = None, ...
https://github.com/elastic/elasticsearch-py/blob/HEAD/elasticsearch/_sync/client/ml.py
01a18119d2f0215b
github_issue
aws/aws-cli
aws: [ERROR]: argument of type 'NoneType' is not a container or iterable ### Describe the bug I am trying to use `aws` against Hetzner S3 `aws --profile=hetz-fsn1 s3 ls` works fine, it lists all buckets. but then `aws --profile=hetz-fsn1 s3 ls s3://my-bucket-name` returns: > aws: [ERROR]: argument of type 'NoneTy...
https://github.com/aws/aws-cli/issues/10161
b401967467ce7b15
github_issue
websocket-client/websocket-client
104 connection reset by peer While using the long-live-connection pattern, I occasionally experience hard disconnects saying "Errorno 104, connection reset by peer". I have multiple WS clients using Gevent monkey patching. When this happens in one of the WS clients, it crashes the rest of them, and also a similar WS...
https://github.com/websocket-client/websocket-client/issues/541
aadcb2c86df61f4b
docstring
astropy/astropy
def _read_leap_seconds(cls, file, **kwargs): Read a file, identifying expiration by matching 'File expires'. Raises: ValueError(f'did not find expiration date in {file}')
def _read_leap_seconds(cls, file, **kwargs): """Read a file, identifying expiration by matching 'File expires'.""" expires = None # Find expiration date. with get_readable_fileobj(file) as fh: lines = fh.readlines() for line in lines: match = cls._...
https://github.com/astropy/astropy/blob/HEAD/astropy/utils/iers/iers.py
f12cb602b2003384
docstring
google/flax
def create_descriptor_wrapper(descriptor: Descriptor): Creates a descriptor wrapper that calls a get_fn on the descriptor. Raises: AttributeError() errors.DescriptorAttributeError()
def create_descriptor_wrapper(descriptor: Descriptor): """Creates a descriptor wrapper that calls a get_fn on the descriptor.""" class _DescriptorWrapper(DescriptorWrapper): """A descriptor that can wrap any descriptor.""" if hasattr(descriptor, '__isabstractmethod__'): __isabstractmethod__ = descri...
https://github.com/google/flax/blob/HEAD/flax/linen/module.py
698c214a252b5fcd
docstring
googleapis/python-bigquery
def dataframe_to_parquet( dataframe, bq_schema, filepath, parquet_compression="SNAPPY", parquet_use_compliant_nested_type=True, ): Write dataframe as a Parquet file, according to the desired BQ schema. This function requires the :mod:`pyarrow` package. Arrow is used as an intermediate format. Arg...
def dataframe_to_parquet( dataframe, bq_schema, filepath, parquet_compression="SNAPPY", parquet_use_compliant_nested_type=True, ): """Write dataframe as a Parquet file, according to the desired BQ schema. This function requires the :mod:`pyarrow` package. Arrow is used as an intermediat...
https://github.com/googleapis/python-bigquery/blob/HEAD/google/cloud/bigquery/_pandas_helpers.py
b95e0d21e9a46949
docstring
huggingface/transformers
def prepare_next_batch(self) -> bool: Prepare tensors and metadata for the next model forward pass. Returns True if there are requests to process, False otherwise. Raises: RuntimeError('No requests can be scheduled and no request can be offloaded.')
def prepare_next_batch(self) -> bool: """Prepare tensors and metadata for the next model forward pass. Returns True if there are requests to process, False otherwise.""" # Get new requests from the queue, stop if there are no pending requests self._get_new_requests() self.schedu...
https://github.com/huggingface/transformers/blob/HEAD/src/transformers/generation/continuous_batching/continuous_api.py
7e48f80631c6a5ad
docstring
chroma-core/chroma
def __call__(self, input: Documents) -> SparseVectors: Generate embeddings for the given documents. Args: input: Documents to generate embeddings for. Returns: Embeddings for the documents. Raises: ValueError('The fastembed python package is not installed. Please install it with `pip install fastembed`'...
def __call__(self, input: Documents) -> SparseVectors: """Generate embeddings for the given documents. Args: input: Documents to generate embeddings for. Returns: Embeddings for the documents. """ try: from fastembed.sparse.bm25 import Bm25 ...
https://github.com/chroma-core/chroma/blob/HEAD/chromadb/utils/embedding_functions/bm25_embedding_function.py
5ab9f3bc18d38c53
docstring
python-attrs/cattrs
def use_class_methods( converter: BaseConverter, structure_method_name: Optional[str] = None, unstructure_method_name: Optional[str] = None, ) -> None: Configure the converter such that dedicated methods are used for (un)structuring the instance of a class if such methods are available. The default (un)str...
def use_class_methods( converter: BaseConverter, structure_method_name: Optional[str] = None, unstructure_method_name: Optional[str] = None, ) -> None: """ Configure the converter such that dedicated methods are used for (un)structuring the instance of a class if such methods are available. The ...
https://github.com/python-attrs/cattrs/blob/HEAD/src/cattrs/strategies/_class_methods.py
d7eb6bf50bfe0fe5
github_issue
Lightning-AI/pytorch-lightning
fix: honor train_bn in BackboneFinetuning.freeze_before_training ## What does this PR do? Fixes #21531 `BackboneFinetuning.freeze_before_training()` called `self.freeze(pl_module.backbone)` without forwarding the `train_bn` parameter, so BatchNorm layers stayed trainable during the initial frozen phase regardless of...
https://github.com/Lightning-AI/pytorch-lightning/pull/21652
66d01ad125ebabc0
docstring
qdrant/qdrant-client
def list_late_interaction_text_models(cls) -> dict[str, tuple[int, models.Distance]]: Lists the supported late interaction text models. Custom late interaction models are not supported yet, but calls to LateInteractionTextEmbedding.list_supported_models() is done each time in order for preserving the same style as wi...
def list_late_interaction_text_models(cls) -> dict[str, tuple[int, models.Distance]]: """Lists the supported late interaction text models. Custom late interaction models are not supported yet, but calls to LateInteractionTextEmbedding.list_supported_models() is done each time in order f...
https://github.com/qdrant/qdrant-client/blob/HEAD/qdrant_client/fastembed_common.py
82a6d238f62802ab
docstring
huggingface/transformers
def set_experts_implementation(self, experts_implementation: str | dict): Set the requested `experts_implementation` for this model. Args: experts_implementation (`str` or `dict`): The experts implementation to set for this model. It can be either a `str`, in which case it will be dispatched to al...
def set_experts_implementation(self, experts_implementation: str | dict): """ Set the requested `experts_implementation` for this model. Args: experts_implementation (`str` or `dict`): The experts implementation to set for this model. It can be either a `str`, in whi...
https://github.com/huggingface/transformers/blob/HEAD/src/transformers/modeling_utils.py
5d2f8841301e03bd
docstring
matplotlib/matplotlib
def subplots(self, *, sharex=False, sharey=False, squeeze=True, subplot_kw=None): Add all subplots specified by this `GridSpec` to its parent figure. See `.Figure.subplots` for detailed documentation. Raises: ValueError('GridSpec.subplots() only works for GridSpecs created with a parent figure')
def subplots(self, *, sharex=False, sharey=False, squeeze=True, subplot_kw=None): """ Add all subplots specified by this `GridSpec` to its parent figure. See `.Figure.subplots` for detailed documentation. """ figure = self.figure if figure is None: ...
https://github.com/matplotlib/matplotlib/blob/HEAD/lib/matplotlib/gridspec.py
7cfd273dad7c8fac
docstring
dask/dask
def _layer(self) -> dict: The graph layer added by this expression. Simple expressions that apply one task per partition can choose to only implement `Expr._task` instead. Examples -------- >>> class Add(Expr): ... def _layer(self): ... return { ... name: Task( ... name, ... ...
def _layer(self) -> dict: """The graph layer added by this expression. Simple expressions that apply one task per partition can choose to only implement `Expr._task` instead. Examples -------- >>> class Add(Expr): ... def _layer(self): ... re...
https://github.com/dask/dask/blob/HEAD/dask/_expr.py
563f21aa952f184d
docstring
Textualize/textual
def mount( self, *widgets: Widget, before: int | str | Widget | None = None, after: int | str | Widget | None = None, ) -> AwaitMount: Mount the given widgets relative to the app's screen. Args: *widgets: The widget(s) to mount. before: Optional location to mount before. An...
def mount( self, *widgets: Widget, before: int | str | Widget | None = None, after: int | str | Widget | None = None, ) -> AwaitMount: """Mount the given widgets relative to the app's screen. Args: *widgets: The widget(s) to mount. before: Opt...
https://github.com/Textualize/textual/blob/HEAD/src/textual/app.py
e381bb2c0e3832a5
docstring
Textualize/rich
def _apply_stylized_ranges(self, text: Text) -> None: Apply stylized ranges to a text instance, using the given code to determine the right portion to apply the style to. Args: text (Text): Text instance to apply the style to.
def _apply_stylized_ranges(self, text: Text) -> None: """ Apply stylized ranges to a text instance, using the given code to determine the right portion to apply the style to. Args: text (Text): Text instance to apply the style to. """ code = text.plain ...
https://github.com/Textualize/rich/blob/HEAD/rich/syntax.py
6fed8e1fce28385c
docstring
matplotlib/matplotlib
def _pass_image_data(x, alpha=None, bytes=False, norm=True): Helper function to pass ndarray of shape (...,3) or (..., 4) through `to_rgba()`, see `to_rgba()` for docstring. Raises: ValueError('Third dimension must be 3 or 4') ValueError('Floating point image RGB values must be in the [0,1] range') ValueE...
def _pass_image_data(x, alpha=None, bytes=False, norm=True): """ Helper function to pass ndarray of shape (...,3) or (..., 4) through `to_rgba()`, see `to_rgba()` for docstring. """ if x.shape[2] == 3: if alpha is None: alpha = 1 if x.dtype...
https://github.com/matplotlib/matplotlib/blob/HEAD/lib/matplotlib/colorizer.py