Having the common app options as a decorator facilitates reuse.
488442
def options(func):
    """"""

    # Until https://github.com/pallets/click/issues/926 is fixed the options need to be re-defined
    # for every use
    options_ = [
        option(
            '--datadir',
            help='Directory for storing raiden data.',
            default=lambda: os.path.join(os.path.expanduser('~'), '.raiden'),
            type=click.Path(
                exists=False,
                dir_okay=True,
                file_okay=False,
                writable=True,
                resolve_path=True,
                allow_dash=False,
            ),
            show_default=True,
        ),
        option(
            '--config-file',
            help='Configuration file (TOML)',
            default=os.path.join('${datadir}', 'config.toml'),
            type=PathRelativePath(
                file_okay=True,
                dir_okay=False,
                exists=False,
                readable=True,
                resolve_path=True,
            ),
            show_default=True,
        ),
        option(
            '--keystore-path',
            help=(
                'If you have a non-standard path for the ethereum keystore directory'
                ' provide it using this argument.'
            ),
            default=None,
            type=click.Path(exists=True),
            show_default=True,
        ),
        option(
            '--address',
            help=(
                'The ethereum address you would like raiden to use and for which '
                'a keystore file exists in your local system.'
            ),
            default=None,
            type=ADDRESS_TYPE,
            show_default=True,
        ),
        option(
            '--password-file',
            help='Text file containing the password for the provided account',
            default=None,
            type=click.File(lazy=True),
            show_default=True,
        ),
        option(
            '--tokennetwork-registry-contract-address',
            help='hex encoded address of the Token Network Registry contract.',
            type=ADDRESS_TYPE,
            show_default=True,
        ),
        option(
            '--secret-registry-contract-address',
            help='hex encoded address of the Secret Registry contract.',
            type=ADDRESS_TYPE,
            show_default=True,
        ),
        option(
            '--service-registry-contract-address',
            help='hex encoded address of the Service Registry contract.',
            type=ADDRESS_TYPE,
        ),
        option(
            '--endpoint-registry-contract-address',
            help='hex encoded address of the Endpoint Registry contract.',
            type=ADDRESS_TYPE,
            show_default=True,
        ),
        option(
            '--user-deposit-contract-address',
            help='hex encoded address of the User Deposit contract.',
            type=ADDRESS_TYPE,
        ),
        option(
            '--console',
            help='Start the interactive raiden console',
            is_flag=True,
        ),
        option(
            '--transport',
            help='Transport system to use. UDP is not recommended',
            type=click.Choice(['udp', 'matrix']),
            default='matrix',
            show_default=True,
        ),
        option(
            '--network-id',
            help=(
                'Specify the network name/id of the Ethereum network to run Raiden on.\n'
                'Available networks:\n'
                '"mainnet" - network id: 1\n'
                '"ropsten" - network id: 3\n'
                '"rinkeby" - network id: 4\n'
                '"goerli" - network id: 5\n'
                '"kovan" - network id: 42\n'
                '"<NETWORK_ID>": use the given network id directly\n'
            ),
            type=NetworkChoiceType([
                'mainnet',
                'ropsten',
                'rinkeby',
                'goerli',
                'kovan',
                '<NETWORK_ID>',
            ]),
            default='mainnet',
            show_default=True,
        ),
        option(
            '--environment-type',
            help=(
                'Specify the environment (production or development).\n'
                'The "production" setting adds some safety measures and is mainly intended '
                'for running Raiden on the mainnet.\n'
            ),
            type=EnumChoiceType(Environment),
            default=Environment.PRODUCTION.value,
            show_default=True,
        ),
        option(
            '--accept-disclaimer',
            help='Bypass the experimental software disclaimer prompt',
            is_flag=True,
        ),
        option(
            '--showconfig',
            help='Show all configuration values used to control Raiden\'s behavior',
            is_flag=True,
        ),
        option_group(
            'Ethereum Node Options',
            option(
                '--sync-check/--no-sync-check',
                help='Checks if the ethereum node is synchronized against etherscan.',
                default=True,
                show_default=True,
            ),
            option(
                '--gas-price',
                help=(
                    'Set the gas price for ethereum transactions. If not provided '
                    'the normal gas price startegy is used.\n'
                    'Available options:\n'
                    '"fast" - transactions are usually mined within 60 seconds\n'
                    '"normal" - transactions are usually mined within 5 minutes\n'
                    '<GAS_PRICE> - use given gas price\n'
                ),
                type=GasPriceChoiceType(['normal', 'fast']),
                default='fast',
                show_default=True,
            ),
            option(
                '--eth-rpc-endpoint',
                help=(
                    '"host:port" address of ethereum JSON-RPC server.\n'
                    'Also accepts a protocol prefix (http:// or https://) with optional port'
                ),
                default='http://127.0.0.1:8545',  # geth default jsonrpc port
                type=str,
                show_default=True,
            ),
        ),
        option_group(
            'Raiden Services Options',
            option(
                '--routing-mode',
                help=(
                    'Specify the routing mode to be used.\n'
                    '"basic": use local routing\n'
                    '"pfs": use the path finding service\n'
                ),
                type=EnumChoiceType(RoutingMode),
                default=RoutingMode.BASIC.value,
                show_default=True,
            ),
            option(
                '--pathfinding-service-address',
                help=(
                    'URL to the Raiden path finding service to request paths from.\n'
                    'Example: https://pfs-ropsten.services-dev.raiden.network\n'
                    'Can also be given the "auto" value so that raiden chooses a '
                    'PFS randomly from the service registry contract'
                ),
                default='auto',
                type=str,
                show_default=True,
            ),
            option(
                '--pathfinding-eth-address',
                help=(
                    'Ethereum address to which to pay the fees of the path finding service.\n'
                    'If the path finding service is chosen from the service registry contract, '
                    'this option will be ignored. If the path finding service is configured '
                    'manually, i. e. "--pathfinding-service-address" set to a value other than '
                    '"auto", this argument must be set to a valid EIP55 address.'
                ),
                type=str,
            ),
            option(
                '--pathfinding-max-paths',
                help='Set maximum number of paths to be requested from the path finding service.',
                default=DEFAULT_PATHFINDING_MAX_PATHS,
                type=int,
                show_default=True,
            ),
            option(
                '--pathfinding-max-fee',
                help='Set max fee per request paid to the path finding service.',
                default=DEFAULT_PATHFINDING_MAX_FEE,
                type=int,
                show_default=True,
            ),
            option(
                '--pathfinding-iou-timeout',
                help='Number of blocks before a new IOU to the path finding service expires.',
                default=DEFAULT_PATHFINDING_IOU_TIMEOUT,
                type=int,
                show_default=True,
            ),
            option(
                '--enable-monitoring',
                help='Enable broadcasting of balance proofs to the monitoring services.',
                is_flag=True,
            ),
        ),
        option_group(
            'UDP Transport Options',
            option(
                '--listen-address',
                help='"host:port" for the raiden service to listen on.',
                default='0.0.0.0:{}'.format(INITIAL_PORT),
                type=str,
                show_default=True,
            ),
            option(
                '--max-unresponsive-time',
                help=(
                    'Max time in seconds for which an address can send no packets and '
                    'still be considered healthy.'
                ),
                default=30,
                type=int,
                show_default=True,
            ),
            option(
                '--send-ping-time',
                help=(
                    'Time in seconds after which if we have received no message from a '
                    'node we have a connection with, we are going to send a PING message'
                ),
                default=60,
                type=int,
                show_default=True,
            ),
            option(
                '--nat',
                help=(
                    'Manually specify method to use for determining public IP / NAT traversal.\n'
                    'Available methods:\n'
                    '"auto" - Try UPnP, then STUN, fallback to none\n'
                    '"upnp" - Try UPnP, fallback to none\n'
                    '"stun" - Try STUN, fallback to none\n'
                    '"none" - Use the local interface address '
                    '(this will likely cause connectivity issues)\n'
                    '"ext:<IP>[:<PORT>]" - manually specify the external IP (and optionally port '
                    'number)'
                ),
                type=NATChoiceType(['auto', 'upnp', 'stun', 'none', 'ext:<IP>[:<PORT>]']),
                default='auto',
                show_default=True,
                option_group='udp_transport',
            ),
        ),
        option_group(
            'Matrix Transport Options',
            option(
                '--matrix-server',
                help=(
                    'Matrix homeserver to use for communication.\n'
                    'Valid values:\n'
                    '"auto" - automatically select a suitable homeserver\n'
                    'A URL pointing to a Raiden matrix homeserver'
                ),
                default='auto',
                type=MatrixServerType(['auto', '<url>']),
                show_default=True,
            ),
        ),
        option_group(
            'Logging Options',
            option(
                '--log-config',
                help='Log level configuration.\n'
                     'Format: [<logger-name-1>]:<level>[,<logger-name-2>:level][,...]',
                type=LOG_LEVEL_CONFIG_TYPE,
                default=':info',
                show_default=True,
            ),
            option(
                '--log-file',
                help='file path for logging to file',
                default=None,
                type=str,
                show_default=True,
            ),
            option(
                '--log-json',
                help='Output log lines in JSON format',
                is_flag=True,
            ),
            option(
                '--disable-debug-logfile',
                help=(
                    'Disable the debug logfile feature. This is independent of '
                    'the normal logging setup'
                ),
                is_flag=True,
            ),
        ),
        option_group(
            'RPC Options',
            option(
                '--rpc/--no-rpc',
                help='Start with or without the RPC server.',
                default=True,
                show_default=True,
            ),
            option(
                '--rpccorsdomain',
                help='Comma separated list of domains to accept cross origin requests.',
                default='http://localhost:*/*',
                type=str,
                show_default=True,
            ),
            option(
                '--api-address',
                help='"host:port" for the RPC server to listen on.',
                default='127.0.0.1:5001',
                type=str,
                show_default=True,
            ),
            option(
                '--web-ui/--no-web-ui',
                help=(
                    'Start with or without the web interface. Requires --rpc. '
                    'It will be accessible at http://<api-address>. '
                ),
                default=True,
                show_default=True,
            ),
        ),
        option_group(
            'Debugging options',
            option(
                '--unrecoverable-error-should-crash',
                help=(
                    'DO NOT use, unless you know what you are doing. If provided '
                    'along with a production environment setting then all '
                    'unrecoverable errors will lead to a crash and not simply get logged.'
                ),
                is_flag=True,
                default=False,
            ),
        ),
        option_group(
            'Hash Resolver options',
            option(
                '--resolver-endpoint',
                help=(
                    'URL of the resolver server that is used to resolve '
                    'a payment hash to a secret. '
                    'Accepts a protocol prefix (http:// or https://) with optional port'
                ),
                default=None,
                type=str,
                show_default=True,
            ),
        ),
    ]

    for option_ in reversed(options_):
        func = option_(func)
    return func
129035
def define(self, klass, name="default"):
        

        def decorate(func):
            @wraps(func)
            def wrapped(*args, **kwargs):
                return func(*args, **kwargs)

            self.register(klass, func, name=name)

            return wrapped

        return decorate
1151222
def make_application(debug=None, apps_dir='apps', project_dir=None,
    include_apps=None, debug_console=True, settings_file=None,
    local_settings_file=None, start=True, default_settings=None,
    dispatcher_cls=None, dispatcher_kwargs=None, debug_cls=None, debug_kwargs=None,
    reuse=True, verbose=False, pythonpath=None, trace_print=False):
    
    from uliweb.utils.common import import_attr
    from uliweb.utils.whocallme import print_frame
    from werkzeug.debug import DebuggedApplication

    #is reuse, then create application only one
    if reuse and hasattr(SimpleFrame.__global__, 'application') and SimpleFrame.__global__.application:
        return SimpleFrame.__global__.application

    #process settings and local_settings
    settings_file = settings_file or os.environ.get('SETTINGS', 'settings.ini')
    local_settings_file = local_settings_file or os.environ.get('LOCAL_SETTINGS', 'local_settings.ini')

    dispatcher_cls = dispatcher_cls or SimpleFrame.Dispatcher
    dispatcher_kwargs = dispatcher_kwargs or {}

    if project_dir:
        apps_dir = os.path.abspath(os.path.normpath(os.path.join(project_dir, 'apps')))
    if not project_dir:
        project_dir = os.path.abspath(os.path.normpath(os.path.abspath(os.path.join(apps_dir, '..'))))

    if pythonpath:
        if isinstance(pythonpath, str):
            pythonpath = pythonpath.split(';')
        for x in pythonpath:
            if x not in sys.path:
                sys.path.insert(0, x)

    if project_dir not in sys.path:
        sys.path.insert(0, project_dir)

    if apps_dir not in sys.path:
        sys.path.insert(0, apps_dir)

    install_config(apps_dir)

    if trace_print:
        output = sys.stdout

        class MyOut(object):
            def write(self, s):
                output.write(s)
                output.write('\n')
                print_frame(output)
                if hasattr(output, 'flush'):
                    output.flush()

        sys.stdout = MyOut()

    application = app = dispatcher_cls(apps_dir=apps_dir,
        include_apps=include_apps,
        settings_file=settings_file,
        local_settings_file=local_settings_file,
        start=start,
        default_settings=default_settings,
        reset=True,
        **dispatcher_kwargs)

    if verbose:
        log.info(' * settings file is "%s"' % settings_file)
        log.info(' * local settings file is "%s"' % local_settings_file)

    #settings global application object
    SimpleFrame.__global__.application = app

    #process wsgi middlewares
    middlewares = []
    parameters = {}
    for name, v in uliweb.settings.get('WSGI_MIDDLEWARES', {}).iteritems():
        order, kwargs = 500, {}
        if not v:
            continue
        if isinstance(v, (list, tuple)):
            if len(v) > 3:
                logging.error('WSGI_MIDDLEWARE %s difinition is not right' % name)
                raise uliweb.UliwebError('WSGI_MIDDLEWARE %s difinition is not right' % name)
            cls = v[0]
            if len(v) == 2:
                if isinstance(v[1], int):
                    order = v[1]
                else:
                    kwargs = v[1]
            else:
                order, kwargs = v[1], v[2]
        else:
            cls = v
        middlewares.append((order, name))
        parameters[name] = cls, kwargs

    middlewares.sort(cmp=lambda x, y: cmp(x[0], y[0]))
    for name in reversed([x[1] for x in middlewares]):
        clspath, kwargs = parameters[name]
        cls = import_attr(clspath)
        app = cls(app, **kwargs)

    debug_flag = uliweb.settings.GLOBAL.DEBUG
    if debug or (debug is None and debug_flag):
        if not debug_cls:
            debug_cls = DebuggedApplication

        log.setLevel(logging.DEBUG)
        log.info(' * Loading DebuggedApplication...')
        app.debug = True
        app = debug_cls(app, uliweb.settings.GLOBAL.get('DEBUG_CONSOLE', False))
    return app
1080634
def using_config(_func=None):
    
    def decorator(func):
        @wraps(func)
        def inner_dec(*args, **kwargs):
            g = func.__globals__
            var_name = 'config'
            sentinel = object()

            oldvalue = g.get(var_name, sentinel)
            g[var_name] = apps.get_app_config('django_summernote').config

            try:
                res = func(*args, **kwargs)
            finally:
                if oldvalue is sentinel:
                    del g[var_name]
                else:
                    g[var_name] = oldvalue

            return res
        return inner_dec

    if _func is None:
        return decorator
    else:
        return decorator(_func)
550098
private synchronized void reloadSharedFunctionSourceList() {
		Map<String, Define> newMap = createSharedFunctionMap();
		for (int i = 0, size = sharedFunctionSourceList.size(); i < size; i++) {
			ISource source = sharedFunctionSourceList.get(i);
			String fileName = source instanceof FileSource ? ((FileSource)source).getFileName() : null;
			
			Env env = new Env(this);
			new Parser(env, source.getContent(), fileName).parse();
			addToSharedFunctionMap(newMap, env);
			if (devMode) {
				env.addSource(source);
			}
		}
		this.sharedFunctionMap = newMap;
	}
925735
def _apply_decorators(func, decorators):
    
    decorators = filter(_is_not_none_or_false, reversed(decorators))

    for decorator in decorators:
        func = decorator(func)

    return func
414234
def dual_use_decorator(fn):
    """"""
    @functools.wraps(fn)
    def decorator(*args, **kw):
        if len(args) == 1 and not kw and callable(args[0]):
            return fn()(args[0])
        else:
            return fn(*args, **kw)
    return decorator
1036600
function normalizeRouteConfig(config, registry) {
    if (config instanceof route_config_decorator_1.AsyncRoute) {
        var wrappedLoader = wrapLoaderToReconfigureRegistry(config.loader, registry);
        return new route_config_decorator_1.AsyncRoute({
            path: config.path,
            loader: wrappedLoader,
            name: config.name,
            data: config.data,
            useAsDefault: config.useAsDefault
        });
    }
    if (config instanceof route_config_decorator_1.Route || config instanceof route_config_decorator_1.Redirect || config instanceof route_config_decorator_1.AuxRoute) {
        return config;
    }
    if ((+!!config.component) + (+!!config.redirectTo) + (+!!config.loader) != 1) {
        throw new BaseException("Route config should contain exactly one \"component\", \"loader\", or \"redirectTo\" property.");
    }
    if (config.as && config.name) {
        throw new BaseException("Route config should contain exactly one \"as\" or \"name\" property.");
    }
    if (config.as) {
        config.name = config.as;
    }
    if (config.loader) {
        var wrappedLoader = wrapLoaderToReconfigureRegistry(config.loader, registry);
        return new route_config_decorator_1.AsyncRoute({
            path: config.path,
            loader: wrappedLoader,
            name: config.name,
            data: config.data,
            useAsDefault: config.useAsDefault
        });
    }
    if (config.aux) {
        return new route_config_decorator_1.AuxRoute({ path: config.aux, component: config.component, name: config.name });
    }
    if (config.component) {
        if (typeof config.component == 'object') {
            var componentDefinitionObject = config.component;
            if (componentDefinitionObject.type == 'constructor') {
                return new route_config_decorator_1.Route({
                    path: config.path,
                    component: componentDefinitionObject.constructor,
                    name: config.name,
                    data: config.data,
                    useAsDefault: config.useAsDefault
                });
            }
            else if (componentDefinitionObject.type == 'loader') {
                return new route_config_decorator_1.AsyncRoute({
                    path: config.path,
                    loader: componentDefinitionObject.loader,
                    name: config.name,
                    data: config.data,
                    useAsDefault: config.useAsDefault
                });
            }
            else {
                throw new BaseException("Invalid component type \"" + componentDefinitionObject.type + "\". Valid types are \"constructor\" and \"loader\".");
            }
        }
        return new route_config_decorator_1.Route(config);
    }
    if (config.redirectTo) {
        return new route_config_decorator_1.Redirect({ path: config.path, redirectTo: config.redirectTo });
    }
    return config;
}
593124
function(options)
	{
		options = conbo.clone(options || {});
		options.app = this;
		
		this.context = new this.contextClass(options);
	}
1036919
def wrapAppEndpoints(app):
    
    for endpoint, func in app.view_functions.items():
        app.view_functions[endpoint] = wrapHttpEndpoint(func)
106777
def decorator(caller, _func=None):
    """"""
    if _func is not None:  # return a decorated function
        # this is obsolete behavior; you should use decorate instead
        return decorate(_func, caller)
    # else return a decorator function
    if inspect.isclass(caller):
        name = caller.__name__.lower()
        doc = 'decorator(%s) converts functions/generators into ' \
              'factories of %s objects' % (caller.__name__, caller.__name__)
    elif inspect.isfunction(caller):
        if caller.__name__ == '<lambda>':
            name = '_lambda_'
        else:
            name = caller.__name__
        doc = caller.__doc__
    else:  # assume caller is an object with a __call__ method
        name = caller.__class__.__name__.lower()
        doc = caller.__call__.__doc__
    evaldict = dict(_call_=caller, _decorate_=decorate)
    return FunctionMaker.create(
        '%s(func)' % name, 'return _decorate_(func, _call_)',
        evaldict, doc=doc, module=caller.__module__,
        __wrapped__=caller)
94023
def verbose_option(default=False):
    

    def decorator(method):
        @wraps(method)
        def wrapper(*args, **kwargs):
            option = Option.verbose.value
            kwargs[option] = kwargs.get(option, bool(default))
            return method(*args, **kwargs)

        return wrapper

    return decorator
428263
def make_middleware(self, app):
        

        def application(environ, start_response):
            return ClosingIterator(app(environ, start_response), self.cleanup)

        return application
821854
def decorator(cls, func_or_class):
        """"""
        resources = getattr(func_or_class, 'resources', [])
        resources.append(cls)
        func_or_class.resources = resources
        return func_or_class
369636
def use(self, func, when='whenever'):
        '''  '''
        #NOTE A middleware Object ?
        # self.use() is usually called from initialize(), so no logger yet
        print('registering middleware {}'.format(func.__name__))
        self.middlewares.append({
            'call': func,
            'name': func.__name__,
            'args': func.func_code.co_varnames,
            'when': when
        })
635122
def overrideable_partial(func, *args, **default_kwargs):
    
    import functools
    @functools.wraps(func)
    def partial_wrapper(*given_args, **given_kwargs):
        kwargs = default_kwargs.copy()
        kwargs.update(given_kwargs)
        return func(*(args + given_args), **kwargs)
    return partial_wrapper
1043965
def reapply(config):
    """"""
    with open(config, 'r'):
        main.reapply(yaml.load(open(config)))