Constructs Signature for the given python function
496025
def from_function(cls, func):
        """"""

        if not isinstance(func, types.FunctionType):
            raise TypeError("{!r} is not a Python function".format(func))

        Parameter = cls._parameter_cls

        # Parameter information.
        func_code = func.__code__
        pos_count = func_code.co_argcount
        arg_names = func_code.co_varnames
        positional = tuple(arg_names[:pos_count])
        keyword_only_count = getattr(func_code, "co_kwonlyargcount", 0)
        keyword_only = arg_names[pos_count : (pos_count + keyword_only_count)]
        annotations = getattr(func, "__annotations__", {})
        defaults = func.__defaults__
        kwdefaults = getattr(func, "__kwdefaults__", None)

        if defaults:
            pos_default_count = len(defaults)
        else:
            pos_default_count = 0

        parameters = []

        # Non-keyword-only parameters w/o defaults.
        non_default_count = pos_count - pos_default_count
        for name in positional[:non_default_count]:
            annotation = annotations.get(name, _empty)
            parameters.append(
                Parameter(name, annotation=annotation, kind=_POSITIONAL_OR_KEYWORD)
            )

        # ... w/ defaults.
        for offset, name in enumerate(positional[non_default_count:]):
            annotation = annotations.get(name, _empty)
            parameters.append(
                Parameter(
                    name,
                    annotation=annotation,
                    kind=_POSITIONAL_OR_KEYWORD,
                    default=defaults[offset],
                )
            )

        # *args
        if func_code.co_flags & 0x04:
            name = arg_names[pos_count + keyword_only_count]
            annotation = annotations.get(name, _empty)
            parameters.append(
                Parameter(name, annotation=annotation, kind=_VAR_POSITIONAL)
            )

        # Keyword-only parameters.
        for name in keyword_only:
            default = _empty
            if kwdefaults is not None:
                default = kwdefaults.get(name, _empty)

            annotation = annotations.get(name, _empty)
            parameters.append(
                Parameter(
                    name, annotation=annotation, kind=_KEYWORD_ONLY, default=default
                )
            )
        # **kwargs
        if func_code.co_flags & 0x08:
            index = pos_count + keyword_only_count
            if func_code.co_flags & 0x04:
                index += 1

            name = arg_names[index]
            annotation = annotations.get(name, _empty)
            parameters.append(Parameter(name, annotation=annotation, kind=_VAR_KEYWORD))

        return cls(
            parameters,
            return_annotation=annotations.get("return", _empty),
            __validate_parameters__=False,
        )
784712
def _generate_ndarray_function_code(handle, name, func_name, signature_only=False):
    """"""
    real_name = ctypes.c_char_p()
    desc = ctypes.c_char_p()
    num_args = mx_uint()
    arg_names = ctypes.POINTER(ctypes.c_char_p)()
    arg_types = ctypes.POINTER(ctypes.c_char_p)()
    arg_descs = ctypes.POINTER(ctypes.c_char_p)()
    key_var_num_args = ctypes.c_char_p()
    ret_type = ctypes.c_char_p()

    check_call(_LIB.MXSymbolGetAtomicSymbolInfo(
        handle, ctypes.byref(real_name), ctypes.byref(desc),
        ctypes.byref(num_args),
        ctypes.byref(arg_names),
        ctypes.byref(arg_types),
        ctypes.byref(arg_descs),
        ctypes.byref(key_var_num_args),
        ctypes.byref(ret_type)))
    narg = int(num_args.value)
    arg_names = [py_str(arg_names[i]) for i in range(narg)]
    arg_types = [py_str(arg_types[i]) for i in range(narg)]
    key_var_num_args = py_str(key_var_num_args.value)
    ret_type = py_str(ret_type.value) if ret_type.value is not None else ''
    doc_str = _build_doc(name,
                         py_str(desc.value),
                         arg_names,
                         arg_types,
                         [py_str(arg_descs[i]) for i in range(narg)],
                         key_var_num_args,
                         ret_type)

    dtype_name = None
    arr_name = None
    ndsignature = []
    signature = []
    ndarg_names = []
    kwarg_names = []
    for i in range(narg):
        name, atype = arg_names[i], arg_types[i]
        if name == 'dtype':
            dtype_name = name
            signature.append('%s=_Null'%name)
        elif atype.startswith('NDArray') or atype.startswith('Symbol'):
            assert not arr_name, \
                "Op can only have one argument with variable " \
                "size and it must be the last argument."
            if atype.endswith('[]'):
                ndsignature.append('*%s'%name)
                arr_name = name
            else:
                ndsignature.append('%s=None'%name)
                ndarg_names.append(name)
        else:
            signature.append('%s=_Null'%name)
            kwarg_names.append(name)
    signature.append('out=None')
    signature.append('name=None')
    signature.append('**kwargs')
    signature = ndsignature + signature

    code = []
    if arr_name:
        code.append("""
def %s(*%s, **kwargs):"""%(func_name, arr_name))
        if not signature_only:
            code.append("""
    ndargs = []
    for i in {}:
        assert isinstance(i, NDArrayBase), \\
            "Positional arguments must have NDArray type, " \\
            "but got %s"%str(i)
        ndargs.append(i)""".format(arr_name))
            if dtype_name is not None:
                code.append("""
    if '%s' in kwargs:
        kwargs['%s'] = _np.dtype(kwargs['%s']).name"""%(
            dtype_name, dtype_name, dtype_name))
            code.append("""
    _ = kwargs.pop('name', None)
    out = kwargs.pop('out', None)
    keys = list(kwargs.keys())
    vals = list(kwargs.values())""")
    else:
        code.append("""
def %s(%s):"""%(func_name, ', '.join(signature)))
        if not signature_only:
            code.append("""
    ndargs = []
    keys = list(kwargs.keys())
    vals = list(kwargs.values())""")
            # NDArray args
            for name in ndarg_names: # pylint: disable=redefined-argument-from-local
                code.append("""
    if {name} is not None:
        assert isinstance({name}, NDArrayBase), \\
            "Argument {name} must have NDArray type, but got %s"%str({name})
        ndargs.append({name})""".format(name=name))
            # kwargs
            for name in kwarg_names: # pylint: disable=redefined-argument-from-local
                code.append("""
    if %s is not _Null:
        keys.append('%s')
        vals.append(%s)"""%(name, name, name))
            # dtype
            if dtype_name is not None:
                code.append("""
    if %s is not _Null:
        keys.append('%s')
        vals.append(_np.dtype(%s).name)"""%(dtype_name, dtype_name, dtype_name))

    if not signature_only:
        code.append("""
    return _imperative_invoke(%d, ndargs, keys, vals, out)"""%(
        handle.value))
    else:
        code.append("""
    return (0,)""")

    doc_str_lines = _os.linesep+''.join(['    '+s if s.strip() else s
                                         for s in 'r"""{doc_str}"""'.format(doc_str=doc_str)
                                         .splitlines(True)])
    code.insert(1, doc_str_lines)
    return ''.join(code), doc_str
166263
def signature(array):
    
    length = len(array)
    index = _NUM_SIGNATURE_BYTES if length > _NUM_SIGNATURE_BYTES else length

    return array[:index]
546907
def format_ft_def(func, full_name:str=None)->str:
    ""
    sig = inspect.signature(func)
    name = f'<code>{full_name or func.__name__}</code>'
    fmt_params = [format_param(param) for name,param
                  in sig.parameters.items() if name not in ('self','cls')]
    arg_str = f"({', '.join(fmt_params)})"
    if sig.return_annotation and (sig.return_annotation != sig.empty): arg_str += f" → {anno_repr(sig.return_annotation)}"
    if is_fastai_class(type(func)):        arg_str += f" :: {link_type(type(func))}"
    f_name = f"<code>class</code> {name}" if inspect.isclass(func) else name
    return f'{f_name}',f'{name}{arg_str}'
566546
def args_from_config(func):
    
    func_args = signature(func).parameters

    @wraps(func)
    def wrapper(*args, **kwargs):
        config = get_config()
        for i, argname in enumerate(func_args):
            if len(args) > i or argname in kwargs:
                continue
            elif argname in config:
                kwargs[argname] = config[argname]
        try:
            getcallargs(func, *args, **kwargs)
        except TypeError as exc:
            msg = "{}\n{}".format(exc.args[0], PALLADIUM_CONFIG_ERROR)
            exc.args = (msg,)
            raise exc
        return func(*args, **kwargs)

    wrapper.__wrapped__ = func
    return wrapper
432096
def _make_symbol_function(handle, name, func_name):
    """"""
    code, doc_str = _generate_symbol_function_code(handle, name, func_name)

    local = {}
    exec(code, None, local)  # pylint: disable=exec-used
    symbol_function = local[func_name]
    symbol_function.__name__ = func_name
    symbol_function.__doc__ = doc_str
    symbol_function.__module__ = 'mxnet.symbol'
    return symbol_function
116638
def _compute_signature(parameters, access_key_secret, method, path):
    '''
    
    '''
    parameters['signature_method'] = 'HmacSHA256'

    string_to_sign = '{0}\n{1}\n'.format(method.upper(), path)

    keys = sorted(parameters.keys())
    pairs = []
    for key in keys:
        val = six.text_type(parameters[key]).encode('utf-8')
        pairs.append(_quote(key, safe='') + '=' + _quote(val, safe='-_~'))
    qs = '&'.join(pairs)
    string_to_sign += qs

    h = hmac.new(access_key_secret, digestmod=sha256)
    h.update(string_to_sign)

    signature = base64.b64encode(h.digest()).strip()

    return signature
304261
def from_callable(cls, func, ignored_parameters=set()):
        
        group = cls()
        signature = inspect.signature(func)
        for parameter in signature.parameters.values():
            if parameter.name.startswith('_') or parameter.name in ignored_parameters:
                continue
            parameter = Parameter.from_callable_parameter(parameter)
            group[parameter.name] = parameter
        return group
1105606
def get_signature(func):
    
    code = func.__code__

    # Names of regular parameters
    parameters = tuple(code.co_varnames[:code.co_argcount])

    # Flags
    has_varargs = bool(code.co_flags & inspect.CO_VARARGS)
    has_varkw = bool(code.co_flags & inspect.CO_VARKEYWORDS)
    has_kwonly = bool(code.co_kwonlyargcount)

    # A mapping of parameter names to default values
    default_values = func.__defaults__ or ()
    defaults = dict(zip(parameters[-len(default_values):], default_values))

    # Type annotations for all parameters
    type_hints = typing.get_type_hints(func) if typing else func.__annotations__
    types = tuple(normalize_type(type_hints.get(param, AnyType)) for param in parameters)

    # Type annotations for required parameters
    required = types[:-len(defaults)] if defaults else types

    # Complexity
    complexity = tuple(map(type_complexity, types)) if typing else None

    return Signature(parameters, types, complexity, defaults, required,
                     has_varargs, has_varkw, has_kwonly)
650906
def get_signature(func):
    
    try:
        return object.__getattribute__(func, '__tri_declarative_signature')
    except AttributeError:
        pass

    try:
        if sys.version_info[0] < 3:  # pragma: no mutate
            names, _, varkw, defaults = inspect.getargspec(func)  # pragma: no mutate
        else:
            names, _, varkw, defaults, _, _, _ = inspect.getfullargspec(func)  # pragma: no covererage
    except TypeError:
        return None

    first_arg_index = 1 if inspect.ismethod(func) else 0  # Skip self argument on methods

    number_of_defaults = len(defaults) if defaults else 0
    if number_of_defaults > 0:
        required = ','.join(sorted(names[first_arg_index:-number_of_defaults]))
        optional = ','.join(sorted(names[-number_of_defaults:]))
    else:
        required = ','.join(sorted(names[first_arg_index:]))
        optional = ''
    wildcard = '*' if varkw is not None else ''

    signature = '|'.join((required, optional, wildcard))
    try:
        object.__setattr__(func, '__tri_declarative_signature', signature)
    except TypeError:
        # For classes
        type.__setattr__(func, '__tri_declarative_signature', signature)
    except AttributeError:
        pass
    return signature
868213
def fn_signature(callable, 
                 argument_transform=(lambda name: name),
                 default_transform=(lambda name, value: "%s=%s" % 
                                                        (name, repr(value))),
                 vararg_transform=(lambda name: "*" + name),
                 kwargs_transform=(lambda name: "**" + name)):
    """"""
    signature = []
    fn = get_fn(callable)
    avail_ac = fn_available_argcount(fn)
    kwargs = fn_kwargs(fn)
    argnames = fn_argnames(fn)
    for name in stop_at(argnames, avail_ac):
        if name in kwargs:
            signature.append(default_transform(name, kwargs[name]))
        else:
            signature.append(argument_transform(name))
    if fn_has_args(fn):
        if fn_has_kwargs(fn):
            signature.append(vararg_transform(argnames[-2]))
            signature.append(kwargs_transform(argnames[-1]))
        else:
            signature.append(vararg_transform(argnames[-1]))
    elif fn_has_kwargs(fn):
        signature.append(kwargs_transform(argnames[-1]))

    return signature
349223
def repr_part(self):
        """"""
        optargs = [('norm', self.norm, ''),
                   ('exponent', self.exponent, 2.0)]
        return signature_string([], optargs, mod=[[], ['!r', ':.4']])
594128
def define_api(name, camel_name, effective_names, params, returns, options)
      params, returns = generate_signature(params.dup, returns)

      ffi_lib *(ffi_libraries.map(&:name) << options[:dll]) if options[:dll]
      libs = ffi_libraries.map(&:name)

      alternative = options.delete(:alternative) # Function may have alternative signature
      effective_name = if alternative

        alt_params, alt_returns, condition = generate_signature(*alternative)
        api = function name, params, returns,
                       options.merge( camel_only: true, camel_name: "#{camel_name}Original")
        alt_api = function name, alt_params, alt_returns,
                           options.merge( camel_only: true, camel_name: "#{camel_name}Alternative")

        define_method camel_name do |*args|
          (condition[*args] ? alt_api : api).call(*args)
        end
        module_function camel_name
        public camel_name
        api.effective_name
      else
        effective_names.inject(nil) do |func, effective_name|
          func || begin
            # Try to attach basic CamelCase method via FFI
            attach_function(camel_name, effective_name, params.dup, returns)
            effective_name
          rescue FFI::NotFoundError
            nil
          end
        end
      end

      raise Win::Errors::NotFoundError.new(name, libs) unless effective_name

      # Create API object that holds information about defined and effective function names, params, etc.
      # This object is further used by enhanced snake_case method to reflect on underlying API and
      # intelligently call it.
      API.new(namespace, camel_name, effective_name, params, returns, libs)
    end
848566
def check_no_signature(self, function, docstring):  # def context
        
        if docstring:
            first_line = ast.literal_eval(docstring).strip().split('\n')[0]
            if function.name + '(' in first_line.replace(' ', ''):
                return violations.D402()
362417
def signature(self):
        """"""
        if self.usage is not None:
            return self.usage


        params = self.clean_params
        if not params:
            return ''

        result = []
        for name, param in params.items():
            greedy = isinstance(param.annotation, converters._Greedy)

            if param.default is not param.empty:
                # We don't want None or '' to trigger the [name=value] case and instead it should
                # do [name] since [name=None] or [name=] are not exactly useful for the user.
                should_print = param.default if isinstance(param.default, str) else param.default is not None
                if should_print:
                    result.append('[%s=%s]' % (name, param.default) if not greedy else
                                  '[%s=%s]...' % (name, param.default))
                    continue
                else:
                    result.append('[%s]' % name)

            elif param.kind == param.VAR_POSITIONAL:
                result.append('[%s...]' % name)
            elif greedy:
                result.append('[%s]...' % name)
            elif self._is_typing_optional(param.annotation):
                result.append('[%s]' % name)
            else:
                result.append('<%s>' % name)

        return ' '.join(result)
676044
def accepts_kwarg(func, kwarg):
    
    signature = inspect.signature(func)
    try:
        signature.bind_partial(**{kwarg: None})
        return True
    except TypeError:
        return False
577000
def get_func_args(func):
    
    if isinstance(func, functools.partial):
        return _signature(func.func)
    if inspect.isfunction(func) or inspect.ismethod(func):
        return _signature(func)
    # Callable class
    return _signature(func.__call__)