Common wrapper for the underlying pyoidc library functions.
    Reads GET params and POST data before passing it on the library and
    converts the response from oic.utils.http_util to wsgi.
    :param func: underlying library function
6338
def pyoidcMiddleware(func):
    

    def wrapper(environ, start_response):
        data = get_or_post(environ)
        cookies = environ.get("HTTP_COOKIE", "")
        resp = func(request=data, cookie=cookies)
        return resp(environ, start_response)

    return wrapper
1054814
def _wrapper(self, func):
        
        def wrapped(*args, **kwargs):
            ret_val = func(*args, **kwargs)
            if isinstance(ret_val, pymongo.cursor.Cursor):
                ret_val = self.from_cursor(ret_val)
            return ret_val

        return wrapped
519414
def _make_read_func(file_obj):
    """"""
    @ffi.callback("cairo_read_func_t", error=constants.STATUS_READ_ERROR)
    def read_func(_closure, data, length):
        string = file_obj.read(length)
        if len(string) < length:  # EOF too early
            return constants.STATUS_READ_ERROR
        ffi.buffer(data, length)[:len(string)] = string
        return constants.STATUS_SUCCESS
    return read_func
1222903
def cached(func):
    
    @wraps(func)
    def wrapper(*args, **kwargs):
        global cache
        key = json.dumps((func, args, kwargs), sort_keys=True, default=str)
        try:
            return cache[key]
        except KeyError:
            pass  # Drop out of the exception handler scope.
        res = func(*args, **kwargs)
        cache[key] = res
        return res
    wrapper._wrapped = func
    return wrapper
660113
def view_func(self):
        
        if request is None:
            raise RuntimeError('view_func need Flask be installed')

        signature = request.args.get('signature')
        timestamp = request.args.get('timestamp')
        nonce = request.args.get('nonce')
        if not self.validate(signature, timestamp, nonce):
            return 'signature failed', 400

        if request.method == 'GET':
            echostr = request.args.get('echostr', '')
            return echostr

        try:
            ret = self.parse(request.data)
        except ValueError:
            return 'invalid', 400

        if 'type' not in ret:
            # not a valid message
            return 'invalid', 400

        if ret['type'] == 'text' and ret['content'] in self._registry:
            func = self._registry[ret['content']]
        else:
            ret_set = frozenset(ret.items())
            matched_rules = (
                _func for _func, _limitation in self._registry_without_key
                if _limitation.issubset(ret_set))
            func = next(matched_rules, None)  # first matched rule

        if func is None:
            if '*' in self._registry:
                func = self._registry['*']
            else:
                func = 'failed'

        if callable(func):
            text = func(**ret)
        else:
            # plain text
            text = self.reply(
                username=ret['sender'],
                sender=ret['receiver'],
                content=func,
            )

        return Response(text, content_type='text/xml; charset=utf-8')
495830
def with_read_hdf5(func):
    
    @wraps(func)
    def decorated_func(fobj, *args, **kwargs):
        # pylint: disable=missing-docstring
        if not isinstance(fobj, h5py.HLObject):
            if isinstance(fobj, FILE_LIKE):
                fobj = fobj.name
            with h5py.File(fobj, 'r') as h5f:
                return func(h5f, *args, **kwargs)
        return func(fobj, *args, **kwargs)

    return decorated_func
1119723
def remote(func):
    

    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        if self.mode == 'server':
            # In server mode, call the function
            return func(self, *args, **kwargs)

        # Make sure we're connected
        if not self.conn:
            self.connect()

        # Call the remote function
        self.conn.send('CALL', func.__name__, args, kwargs)

        # Receive the response
        cmd, payload = self.conn.recv()
        if cmd == 'ERR':
            self.close()
            raise Exception("Catastrophic error from server: %s" %
                            payload[0])
        elif cmd == 'EXC':
            exc_type = utils.find_entrypoint(None, payload[0])
            raise exc_type(payload[1])
        elif cmd != 'RES':
            self.close()
            raise Exception("Invalid command response from server: %s" % cmd)

        return payload[0]

    # Mark it a callable
    wrapper._remote = True

    # Return the wrapped function
    return wrapper
1217129
def api_auth(func):
    
    @wraps(func)
    def _decorator(request, *args, **kwargs):
        authentication = APIAuthentication(request)
        if authentication.authenticate():
            return func(request, *args, **kwargs)
        raise Http404
    return _decorator
1197838
def cache(cls, func):
        

        @functools.wraps(func)
        def func_wrapper(*args, **kwargs):
            func_key = cls.get_key(func)
            val_cache = cls.get_cache(func_key)
            lock = cls.get_cache_lock(func_key)

            return cls._get_value_from_cache(
                func, val_cache, lock, *args, **kwargs)

        return func_wrapper
501813
def compress(func):
    
    @wraps(func)
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        if ('gzip' in bottle.request.headers.get('Accept-Encoding', '') and
                isinstance(result, string_type) and
                len(result) > 1024):
            if isinstance(result, unicode):
                result = result.encode('utf-8')
            tmp_fo = BytesIO()
            with gzip.GzipFile(mode='wb', fileobj=tmp_fo) as gzip_fo:
                gzip_fo.write(result)
            result = tmp_fo.getvalue()
            bottle.response.add_header('Content-Encoding', 'gzip')
        return result
    return wrapper
89286
def POST(self, func, data):
        
        s, message = self.checkAccount()
        if s is False:
            return False, message

        url = nurls[func]
        r = self.session.post(url, data = data)
        r.encoding = 'utf-8'

        if self.debug:
            print r.text.encode("utf-8")

        try:
            metadata = json.loads(r.text)
            message = metadata['message']
            if message == 'success':
                try:
                    return True, metadata['resultvalue']
                except:
                    return True, metadata['resultcode']
            else:
                return False, "Error %s: %s" %(func, message)
        except:
            #for e in sys.exc_info():
            #    print e
            #sys.exit(1)
            return False, "Error %s: Failed to send POST request" %func
831410
def _get_data(self, func):
        
        def wrapper(*args, **kwargs):
            timeout = kwargs.pop('timeout', None)

            uri, params, method, body, headers, singleobject = func(*args, **kwargs)

            if headers is None:
                headers = {}

            # Use the JSON API by default, but remember we might request a PDF (application/pdf)
            # so don't force the Accept header.
            if 'Accept' not in headers:
                headers['Accept'] = 'application/json'

            # Set a user-agent so Xero knows the traffic is coming from pyxero
            # or individual user/partner
            headers['User-Agent'] = self.user_agent

            response = getattr(requests, method)(
                    uri, data=body, headers=headers, auth=self.credentials.oauth,
                    params=params, timeout=timeout)

            if response.status_code == 200:
                # If we haven't got XML or JSON, assume we're being returned a binary file
                if not response.headers['content-type'].startswith('application/json'):
                    return response.content

                return self._parse_api_response(response, self.name)

            elif response.status_code == 204:
                return response.content

            elif response.status_code == 400:
                raise XeroBadRequest(response)

            elif response.status_code == 401:
                raise XeroUnauthorized(response)

            elif response.status_code == 403:
                raise XeroForbidden(response)

            elif response.status_code == 404:
                raise XeroNotFound(response)

            elif response.status_code == 500:
                raise XeroInternalError(response)

            elif response.status_code == 501:
                raise XeroNotImplemented(response)

            elif response.status_code == 503:
                # Two 503 responses are possible. Rate limit errors
                # return encoded content; offline errors don't.
                # If you parse the response text and there's nothing
                # encoded, it must be a not-available error.
                payload = parse_qs(response.text)
                if payload:
                    raise XeroRateLimitExceeded(response, payload)
                else:
                    raise XeroNotAvailable(response)
            else:
                raise XeroExceptionUnknown(response)

        return wrapper
1301675
def wrap_json_params(func):
    

    @functools.wraps(func)
    def wrapper(request, *args, **kwargs):
        ctype, pdict = parse_header(request.headers.get('Content-Type', ''))
        if ctype == "application/json":
            request.params = json.loads(request.body.decode("utf-8")) if request.body else None
        return func(request, *args, **kwargs)
    return wrapper
592831
def http(container = None):
    ""
    def decorator(func):
        @functools.wraps(func)
        def handler(self, event):
            return _handler(self if container is None else container, event, lambda env: func(self, env))
        return handler
    return decorator
632454
def receive(self, **kwargs):
        
        def _decorator(func):
            self.connect(func, **kwargs)
            return func
        return _decorator
1298727
def cors_wrapper(func):
    
    def _setdefault(obj, key, value):
        if value == None:
            return
        obj.setdefault(key, value)

    def output(*args, **kwargs):
        response = func(*args, **kwargs)
        headers = response.headers
        _setdefault(headers, "Access-Control-Allow-Origin", "*")
        _setdefault(headers, "Access-Control-Allow-Headers", flask.request.headers.get("Access-Control-Request-Headers"))
        _setdefault(headers, "Access-Control-Allow-Methods", flask.request.headers.get("Access-Control-Request-Methods"))
        _setdefault(headers, "Content-Type", "application/json")
        _setdefault(headers, "Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload")
        return response

    output.provide_automatic_options = False
    output.__name__ = func.__name__
    return output
77262
def api(func=None, timeout=API_TIMEOUT):  # incoming
    
    if func is None:
        return partial(api, timeout=timeout)
    else:
        wrapper = _get_api_decorator(func=func, timeout=timeout)
        return wrapper