a
    oÝEb'B  ã                   @  sî   d Z ddlmZ ddlmZmZ ddlZddlZddl	m
Z
 ddlmZmZ dd„ Zd	d
„ Zdd„ Zdd„ Zdd„ Zdd„ Zd0dd„Zdd„ Zd1dd„Zdddœdd„Zd2d d!œd"d#„Zd$d%d&œd'd(„Zd$d%d)œd*d+„Zd,d,d,d-œd.d/„ZdS )3zV
Module that contains many useful utilities
for validating data or function arguments
é    )Úannotations)ÚIterableÚSequenceN)Úfind_stack_level)Úis_boolÚ
is_integerc              	   C  sl   |dk rt dƒ‚t|ƒt|ƒkrht|ƒ| }t|ƒ| }|dkrDdnd}t| › d|› d|› d|› d	�ƒ‚d
S )zÀ
    Checks whether 'args' has length of at most 'compat_args'. Raises
    a TypeError if that is not the case, similar to in Python when a
    function is called with too many arguments.
    r   z*'max_fname_arg_count' must be non-negativeé   ÚargumentÚ	argumentsz() takes at most ú z (z given)N)Ú
ValueErrorÚlenÚ	TypeError)ÚfnameÚargsÚmax_fname_arg_countÚcompat_argsZmax_arg_countZactual_arg_countr	   © r   úW/home/ja/django-apps/lartica_env/lib/python3.9/site-packages/pandas/util/_validators.pyÚ_check_arg_length   s    ÿÿr   c              	   C  sž   |D ]”}zR|| }|| }|dur*|du s:|du r@|dur@d}n||k}t |ƒsXtdƒ‚W n" ty|   || || u }Y n0 |std|› d| › d�ƒ‚qdS )zø
    Check that the keys in `arg_val_dict` are mapped to their
    default values as specified in `compat_args`.

    Note that this function is to be called only when it has been
    checked that arg_val_dict.keys() is a subset of compat_args
    NFz'match' is not a booleanzthe 'z=' parameter is not supported in the pandas implementation of z())r   r   )r   Zarg_val_dictr   ÚkeyÚv1Úv2Úmatchr   r   r   Ú_check_for_default_values+   s"     ÿÿr   c                 C  s,   t | |||ƒ tt||ƒƒ}t| ||ƒ dS )a  
    Checks whether the length of the `*args` argument passed into a function
    has at most `len(compat_args)` arguments and whether or not all of these
    elements in `args` are set to their default values.

    Parameters
    ----------
    fname : str
        The name of the function being passed the `*args` parameter
    args : tuple
        The `*args` parameter passed into a function
    max_fname_arg_count : int
        The maximum number of arguments that the function `fname`
        can accept, excluding those in `args`. Used for displaying
        appropriate error messages. Must be non-negative.
    compat_args : dict
        A dictionary of keys and their associated default values.
        In order to accommodate buggy behaviour in some versions of `numpy`,
        where a signature displayed keyword arguments but then passed those
        arguments **positionally** internally when calling downstream
        implementations, a dict ensures that the original
        order of the keyword arguments is enforced.

    Raises
    ------
    TypeError
        If `args` contains more values than there are `compat_args`
    ValueError
        If `args` contains values that do not correspond to those
        of the default values specified in `compat_args`
    N)r   ÚdictÚzipr   )r   r   r   r   Úkwargsr   r   r   Úvalidate_argsQ   s     r   c                 C  s8   t |ƒt |ƒ }|r4t|ƒd }t| › d|› d�ƒ‚dS )z}
    Checks whether 'kwargs' contains any keys that are not
    in 'compat_args' and raises a TypeError if there is one.
    r   z'() got an unexpected keyword argument 'ú'N)ÚsetÚlistr   )r   r   r   ÚdiffZbad_argr   r   r   Ú_check_for_invalid_keysz   s    r#   c                 C  s$   |  ¡ }t| ||ƒ t| ||ƒ dS )aÞ  
    Checks whether parameters passed to the **kwargs argument in a
    function `fname` are valid parameters as specified in `*compat_args`
    and whether or not they are set to their default values.

    Parameters
    ----------
    fname : str
        The name of the function being passed the `**kwargs` parameter
    kwargs : dict
        The `**kwargs` parameter passed into `fname`
    compat_args: dict
        A dictionary of keys that `kwargs` is allowed to have and their
        associated default values

    Raises
    ------
    TypeError if `kwargs` contains keys not in `compat_args`
    ValueError if `kwargs` contains keys in `compat_args` that do not
    map to the default values specified in `compat_args`
    N)Úcopyr#   r   )r   r   r   Úkwdsr   r   r   Úvalidate_kwargs‡   s    r&   c                 C  sh   t | |t| ¡ ƒ ||ƒ tt||ƒƒ}|D ] }||v r,t| › d|› d�ƒ‚q,| |¡ t| ||ƒ dS )aý  
    Checks whether parameters passed to the *args and **kwargs argument in a
    function `fname` are valid parameters as specified in `*compat_args`
    and whether or not they are set to their default values.

    Parameters
    ----------
    fname: str
        The name of the function being passed the `**kwargs` parameter
    args: tuple
        The `*args` parameter passed into a function
    kwargs: dict
        The `**kwargs` parameter passed into `fname`
    max_fname_arg_count: int
        The minimum number of arguments that the function `fname`
        requires, excluding those in `args`. Used for displaying
        appropriate error messages. Must be non-negative.
    compat_args: dict
        A dictionary of keys that `kwargs` is allowed to
        have and their associated default values.

    Raises
    ------
    TypeError if `args` contains more values than there are
    `compat_args` OR `kwargs` contains keys not in `compat_args`
    ValueError if `args` contains values not at the default value (`None`)
    `kwargs` contains keys in `compat_args` that do not map to the default
    value as specified in `compat_args`

    See Also
    --------
    validate_args : Purely args validation.
    validate_kwargs : Purely kwargs validation.

    z-() got multiple values for keyword argument 'r   N)r   ÚtupleÚvaluesr   r   r   Úupdater&   )r   r   r   r   r   Z	args_dictr   r   r   r   Úvalidate_args_and_kwargs¢   s    &ÿÿ
r*   TFc                 C  sN   t | ƒ}|r|p| du }|r*|p(t| tƒ}|sJtd|› dt| ƒj› d�ƒ‚| S )aR  
    Ensure that argument passed in arg_name can be interpreted as boolean.

    Parameters
    ----------
    value : bool
        Value to be validated.
    arg_name : str
        Name of the argument. To be reflected in the error message.
    none_allowed : bool, default True
        Whether to consider None to be a valid boolean.
    int_allowed : bool, default False
        Whether to consider integer value to be a valid boolean.

    Returns
    -------
    value
        The same value as input.

    Raises
    ------
    ValueError
        If the value is not a valid boolean.
    NzFor argument "z$" expected type bool, received type Ú.)r   Ú
isinstanceÚintr   ÚtypeÚ__name__)ÚvalueÚarg_nameÚnone_allowedÚint_allowedZ
good_valuer   r   r   Úvalidate_bool_kwargÚ   s    ÿÿr4   c              	     sn  i }dˆ v r0t ‡ fdd„| jD ƒƒr0d}t|ƒ‚|ˆ v rr|rT|› d|› d�}t|ƒ‚|  ˆ  dd¡¡}ˆ | ||< ˆ  ¡ D ]2\}}	z|  |¡}
W n ty¢   Y qz0 |	||
< qzt|ƒdkr¼n®t|ƒdkrè|  ˆ  dd¡¡}|d ||< n‚t|ƒd	k�rVdˆ v �rd
}t|ƒ‚d|› d|› d�}tj	|t
tƒ d� |d ||  d¡< |d ||  d¡< nd|› d�}t|ƒ‚|S )a¥  
    Argument handler for mixed index, columns / axis functions

    In an attempt to handle both `.method(index, columns)`, and
    `.method(arg, axis=.)`, we have to do some bad things to argument
    parsing. This translates all arguments to `{index=., columns=.}` style.

    Parameters
    ----------
    data : DataFrame
    args : tuple
        All positional arguments from the user
    kwargs : dict
        All keyword arguments from the user
    arg_name, method_name : str
        Used for better error messages

    Returns
    -------
    kwargs : dict
        A dictionary of keyword arguments. Doesn't modify ``kwargs``
        inplace, so update them with the return value here.

    Examples
    --------
    >>> df = pd.DataFrame(range(2))
    >>> validate_axis_style_args(df, (str.upper,), {'columns': id},
    ...                          'mapper', 'rename')
    {'columns': <built-in function id>, 'index': <method 'upper' of 'str' objects>}

    This emits a warning
    >>> validate_axis_style_args(df, (str.upper, id), {},
    ...                          'mapper', 'rename')
    {'index': <method 'upper' of 'str' objects>, 'columns': <built-in function id>}
    Úaxisc                 3  s   | ]}|ˆ v V  qd S )Nr   )Ú.0Úx©r   r   r   Ú	<genexpr>-  ó    z+validate_axis_style_args.<locals>.<genexpr>z;Cannot specify both 'axis' and any of 'index' or 'columns'.z# got multiple values for argument 'r   r   r   é   z:Cannot specify both 'axis' and any of 'index' or 'columns'zInterpreting call
	'.z(a, b)' as 
	'.z (index=a, columns=b)'.
Use named arguments to remove any ambiguity. In the future, using positional arguments for 'index' or 'columns' will raise a 'TypeError'.)Ú
stacklevelzCannot specify all of 'z', 'index', 'columns'.)ÚanyZ_AXIS_TO_AXIS_NUMBERr   Z_get_axis_nameÚgetÚitemsr   r   ÚwarningsÚwarnÚFutureWarningr   )Údatar   r   r1   Úmethod_nameÚoutÚmsgr5   ÚkÚvÚaxr   r8   r   Úvalidate_axis_style_args  sF    & 

ÿÿrJ   c                 C  sš   ddl m} | du r&|du r&tdƒ‚nl| du r@|dur@||ƒ}nR| durz|du rz|r’t| ttfƒr’tdt| ƒj› d�ƒ‚n| dur’|dur’tdƒ‚| |fS )a$  
    Validate the keyword arguments to 'fillna'.

    This checks that exactly one of 'value' and 'method' is specified.
    If 'method' is specified, this validates that it's a valid method.

    Parameters
    ----------
    value, method : object
        The 'value' and 'method' keyword arguments for 'fillna'.
    validate_scalar_dict_value : bool, default True
        Whether to validate that 'value' is a scalar or dict. Specifically,
        validate that it is not a list or tuple.

    Returns
    -------
    value, method : object
    r   )Úclean_fill_methodNz(Must specify a fill 'value' or 'method'.z>"value" parameter must be a scalar or dict, but you passed a "ú"z)Cannot specify both 'value' and 'method'.)	Zpandas.core.missingrK   r   r,   r!   r'   r   r.   r/   )r0   ÚmethodZvalidate_scalar_dict_valuerK   r   r   r   Úvalidate_fillna_kwargsb  s    

ÿÿrN   zfloat | Iterable[float]z
np.ndarray)ÚqÚreturnc                 C  sj   t  | ¡}d}|jdkrBd|  kr,dksfn t| |d ¡ƒ‚n$tdd„ |D ƒƒsft| |d ¡ƒ‚|S )aå  
    Validate percentiles (used by describe and quantile).

    This function checks if the given float or iterable of floats is a valid percentile
    otherwise raises a ValueError.

    Parameters
    ----------
    q: float or iterable of floats
        A single percentile or an iterable of percentiles.

    Returns
    -------
    ndarray
        An ndarray of the percentiles if valid.

    Raises
    ------
    ValueError if percentiles are not in given interval([0, 1]).
    zApercentiles should all be in the interval [0, 1]. Try {} instead.r   r   g      Y@c                 s  s&   | ]}d |  kodkn  V  qdS )r   r   Nr   )r6   Úqsr   r   r   r9   ¦  r:   z&validate_percentile.<locals>.<genexpr>)ÚnpZasarrayÚndimr   ÚformatÚall)rO   Zq_arrrF   r   r   r   Úvalidate_percentile‰  s    

rV   z!bool | int | Sequence[bool | int]©Ú	ascendingc                   s<   dddœ‰ t | ttfƒs*t| dfi ˆ ¤ŽS ‡ fdd„| D ƒS )z8Validate ``ascending`` kwargs for ``sort_index`` method.FT)r2   r3   rX   c                   s   g | ]}t |d fi ˆ ¤Ž‘qS rW   )r4   )r6   Úitemr8   r   r   Ú
<listcomp>³  r:   z&validate_ascending.<locals>.<listcomp>)r,   r!   r'   r4   rW   r   r8   r   Úvalidate_ascending«  s    
r[   z
str | Noneztuple[bool, bool])ÚclosedrP   c                 C  sF   d}d}| du rd}d}n$| dkr(d}n| dkr6d}nt dƒ‚||fS )a%  
    Check that the `closed` argument is among [None, "left", "right"]

    Parameters
    ----------
    closed : {None, "left", "right"}

    Returns
    -------
    left_closed : bool
    right_closed : bool

    Raises
    ------
    ValueError : if argument is not among valid values
    FNTÚleftÚrightz/Closed has to be either 'left', 'right' or None)r   )r\   Zleft_closedZright_closedr   r   r   Úvalidate_endpoints¶  s    r_   )Ú	inclusiverP   c                 C  s6   d}t | tƒr"dddddœ | ¡}|du r2tdƒ‚|S )aD  
    Check that the `inclusive` argument is among {"both", "neither", "left", "right"}.

    Parameters
    ----------
    inclusive : {"both", "neither", "left", "right"}

    Returns
    -------
    left_right_inclusive : tuple[bool, bool]

    Raises
    ------
    ValueError : if argument is not among valid values
    N)TT)TF)FT)FF)Zbothr]   r^   Zneitherz?Inclusive has to be either 'both', 'neither', 'left' or 'right')r,   Ústrr>   r   )r`   Zleft_right_inclusiver   r   r   Úvalidate_inclusive×  s    
üûÿrb   r-   )ÚlocÚlengthrP   c                 C  sZ   t | ƒstd|› d|› �ƒ‚| dk r,| |7 } d|   kr@|ksVn td|› d|› �ƒ‚| S )z¼
    Check that we have an integer between -length and length, inclusive.

    Standardize negative loc to within [0, length].

    The exceptions we raise on failure match np.insert.
    z loc must be an integer between -z and r   )r   r   Ú
IndexError)rc   rd   r   r   r   Úvalidate_insert_locù  s    rf   )TF)T)T)Ú__doc__Ú
__future__r   Útypingr   r   r@   ÚnumpyrR   Zpandas.util._exceptionsr   Zpandas.core.dtypes.commonr   r   r   r   r   r#   r&   r*   r4   rJ   rN   rV   r[   r_   rb   rf   r   r   r   r   Ú<module>   s*   &)8
(`
'# ÿ!"