Decorator converts function's arguments from dbus types to python.
774145
def signal_wrapper(f):
    """"""
    @wraps(f)
    def wrapper(*args, **kwds):
        args = map(convert, args)
        kwds = {convert(k): convert(v) for k, v in kwds.items()}
        return f(*args, **kwds)
    return wrapper
1199802
def return_as(returntype):
    
    def decorator(func):
        # @wraps(func) <- we can't use this as normal because it doesn't work
        #                 on python < 3 for instance methods,
        #                 see workaround below
        def wrapped(*args, **kwargs):
            result = func(*args, **kwargs)
            try:
                return returntype(result)
            except (TypeError, ValueError) as exc:
                exc.args = (
                    'failed to cast return from {0} as {1}: {2}'.format(
                        func.__name__, returntype.__name__, str(exc)),
                )
                raise
        try:
            return wraps(func)(wrapped)
        except AttributeError:  # python < 3.0.0
            wrapped.__doc__ == func.__doc__
            return wrapped

    return decorator
1353928
def pipe_util(func):
    
    @wraps(func)
    def pipe_util_wrapper(function, *args, **kwargs):
        if isinstance(function, XObject):
            function = ~function

        original_function = function

        if args or kwargs:
            function = xpartial(function, *args, **kwargs)

        name = lambda: '%s(%s)' % (get_name(func), ', '.join(
            filter(None, (get_name(original_function), repr_args(*args, **kwargs)))))

        f = func(function)

        result = pipe | set_name(name, f)

        # if the util defines an 'attrs' mapping, copy it as attributes
        # to the result
        attrs = getattr(f, 'attrs', {})
        for k, v in dict_items(attrs):
            setattr(result, k, v)

        return result

    return pipe_util_wrapper
871637
def call(self, func, *args, **kwargs):
        
        wrapped = self.wrap(func)
        return wrapped(*args, **kwargs)
904932
def pytype_to_ctype(t):
    
    if isinstance(t, List):
        return 'pythonic::types::list<{0}>'.format(
            pytype_to_ctype(t.__args__[0])
        )
    elif isinstance(t, Set):
        return 'pythonic::types::set<{0}>'.format(
            pytype_to_ctype(t.__args__[0])
        )
    elif isinstance(t, Dict):
        tkey, tvalue = t.__args__
        return 'pythonic::types::dict<{0},{1}>'.format(pytype_to_ctype(tkey),
                                                       pytype_to_ctype(tvalue))
    elif isinstance(t, Tuple):
        return 'decltype(pythonic::types::make_tuple({0}))'.format(
            ", ".join('std::declval<{}>()'.format(pytype_to_ctype(p))
                      for p in t.__args__)
        )
    elif isinstance(t, NDArray):
        dtype = pytype_to_ctype(t.__args__[0])
        ndim = len(t.__args__) - 1
        shapes = ','.join(('long'
                           if s.stop == -1 or s.stop is None
                           else 'std::integral_constant<long, {}>'.format(
                               s.stop)
                           ) for s in t.__args__[1:])
        pshape = 'pythonic::types::pshape<{0}>'.format(shapes)
        arr = 'pythonic::types::ndarray<{0},{1}>'.format(
                    dtype, pshape)
        if t.__args__[1].start == -1:
            return 'pythonic::types::numpy_texpr<{0}>'.format(arr)
        elif any(s.step is not None and s.step < 0 for s in t.__args__[1:]):
            slices = ", ".join(['pythonic::types::normalized_slice'] * ndim)
            return 'pythonic::types::numpy_gexpr<{0},{1}>'.format(arr, slices)
        else:
            return arr
    elif isinstance(t, Pointer):
        return 'pythonic::types::pointer<{0}>'.format(
            pytype_to_ctype(t.__args__[0])
        )
    elif isinstance(t, Fun):
        return 'pythonic::types::cfun<{0}({1})>'.format(
            pytype_to_ctype(t.__args__[-1]),
            ", ".join(pytype_to_ctype(arg) for arg in t.__args__[:-1]),
        )
    elif t in PYTYPE_TO_CTYPE_TABLE:
        return PYTYPE_TO_CTYPE_TABLE[t]
    else:
        raise NotImplementedError("{0}:{1}".format(type(t), t))
604434
def decorate_method(cls, func):
        
        func_args = [arg for arg in function_arguments(func) if arg != 'self']
        method_return_types = \
            Endpoint._parse_function_return_types_from_doc(func.__doc__)
        name = '%s.%s' % (cls.path, func.__name__)

        @wraps(func)
        def method_decorator(self, *args, **kwargs):
            for i in range(len(args)):
                kwargs[func_args[i]] = args[i]

            api_call = self.connection._pre_process_call(
                name, endpoint_params=kwargs)
            try:
                data = func(**kwargs)
            except RestException as e:
                api_call.error = e
                raise e

            except Exception as e:
                call_queue = self.connection._call_queue.get(
                    self.connection._get_thread_id(), [])
                if api_call in call_queue:
                    call_queue.remove(api_call)
                e = RestException(original_error=e,
                                  stack=traceback.format_exc())
                log.error('ApiCall Exception: %s' % e, exc_info=True)
                raise e
            return self.connection._post_process_call(
                api_call, data, method_return_types)

        method_decorator.rest_method = True
        return method_decorator
890231
def optional_arg_class_decorator(fn):
    
    @functools.wraps(fn)
    def wrapped_decorator(*args, **kwargs):
        if len(args) == 1 and isinstance(args[0], type) and not kwargs:
            return fn(args[0])
        else:
            def real_decorator(decoratee):
                return fn(decoratee, *args, **kwargs)
            return real_decorator
    return wrapped_decorator
140737
def python(self, func, *args, **kwargs):
        """"""
        self.ops.append(lambda: func(*args, **kwargs))
278155
def wrap(func):
    
    @functools.wraps(func, assigned=('restype', 'argtypes'))
    def wrapped(*args):
        if len(args) != len(func.argtypes):
            logger.warn("{} {} not of same length",
                        args, func.argtypes)

        typed_args = []
        for (arg, argtype) in zip(args, func.argtypes):
            if argtype == c_char_p:
                # create a string buffer for strings
                typed_arg = create_string_buffer(arg)
            else:
                # for other types, use the type to do the conversion
                if hasattr(argtype, 'contents'):
                    # type is a pointer
                    typed_arg = argtype(argtype._type_(arg))
                else:
                    typed_arg = argtype(arg)
            typed_args.append(typed_arg)
        result = func(*typed_args)
        if hasattr(result, 'contents'):
            return result.contents
        else:
            return result
    return wrapped
80825
def _wrapper(func, *vect_args, **vect_kwargs):
        """"""
        if not hasattr(func, '__name__'):
            # Set name if not available. Happens if func is actually a function
            func.__name__ = '{}.__call__'.format(func.__class__.__name__)

        return wraps(func)(_NumpyVectorizeWrapper(func, *vect_args,
                                                  **vect_kwargs))
111526
def _wrap(cls, func):
        

        if isinstance(func, cls):
            return func
        return functools.update_wrapper(cls(func), func)
440739
def _iterable_to_varargs_method(func):
    """"""
    def wrapped(self, *args, **kwargs):
        return func(self, args, **kwargs)
    return wrapped
627100
def wrap_args_kwargs_to_initdict(init_args_kwargs_fn: InitArgsKwargsFnType,
                                 typename: str,
                                 check_result: bool = True) \
        -> InstanceToInitDictFnType:
    
    def wrapper(obj: Instance) -> InitDict:
        result = init_args_kwargs_fn(obj)
        if check_result:
            if (not isinstance(result, tuple) or
                    not len(result) == 2 or
                    not isinstance(result[0], list) or
                    not isinstance(result[1], dict)):
                raise ValueError(
                    "Class {} failed to provide an (args, kwargs) tuple and "
                    "provided instead: {}".format(typename, repr(result)))
        return args_kwargs_to_initdict(*result)

    return wrapper
449087
def decorate(decorator_cls, *args, **kwargs):
    """"""
    global _wrappers

    wrapper_cls = _wrappers.get(decorator_cls, None)
    if wrapper_cls is None:

        class PythonWrapper(decorator_cls):
            pass

        wrapper_cls = PythonWrapper
        wrapper_cls.__name__ = decorator_cls.__name__ + "PythonWrapper"
        _wrappers[decorator_cls] = wrapper_cls

    def decorator(fn):
        wrapped = wrapper_cls(fn, *args, **kwargs)
        _update_wrapper(wrapped, fn)
        return wrapped

    return decorator
217492
def decorator(func):
  
  """
  def wrapper(__decorated__=None, *Args, **KwArgs):
    if __decorated__ is None: # the decorator has some optional arguments.
      return lambda _func: func(_func, *Args, **KwArgs)

    else:
      return func(__decorated__, *Args, **KwArgs)

  return wrap(wrapper, func)
91066
def convert2dbus(value, signature):
    
    if len(signature) == 2 and signature.startswith('a'):
        return dbus.Array(value, signature=signature[-1])
    dbus_string_type = dbus.String if PY3 else dbus.UTF8String
    type_map = {
        'b': dbus.Boolean, 'y': dbus.Byte, 'n': dbus.Int16,
        'i': dbus.Int32, 'x': dbus.Int64, 'q': dbus.UInt16, 'u': dbus.UInt32,
        't': dbus.UInt64, 'd': dbus.Double, 'o': dbus.ObjectPath,
        'g': dbus.Signature, 's': dbus_string_type}
    return type_map[signature](value)
852858
def wrap_kwargs_to_initdict(init_kwargs_fn: InitKwargsFnType,
                            typename: str,
                            check_result: bool = True) \
        -> InstanceToInitDictFnType:
    
    def wrapper(obj: Instance) -> InitDict:
        result = init_kwargs_fn(obj)
        if check_result:
            if not isinstance(result, dict):
                raise ValueError(
                    "Class {} failed to provide a kwargs dict and "
                    "provided instead: {}".format(typename, repr(result)))
        return kwargs_to_initdict(init_kwargs_fn(obj))

    return wrapper