controller wrap
wrap controllers for router

@param {object} ctx context
@param {function} ctrl controller function
@param {object} hooks controller hook functions
@param {function} next koa router next function
@returns
322060
function controllerWrap(ctx, ctrl, hooks, next) {
  let result
  const preHooks = []
  hooks.pre.map(pre => {
    preHooks.push(() => pre(ctx))
  })

  return sequenceAndReturnOne(preHooks)
    .then(() => {
      return ctrl(ctx)
    })
    .then(data => {
      if (!data && ctx.body && ctx.body.data) {
        data = ctx.body.data
      }
      result = data
      const postHooks = []
      hooks.post.map(post => {
        // Use pre action's result for next action's data
        postHooks.push(preResult => post(ctx, preResult || result))
      })
      return sequenceAndReturnOne(postHooks)
    })
    .then(ret => {
      if (!ctx.body) {
        ctx.body = {
          code: 0,
          data: ret || result
        }
      }
      next && next()
    })
    .catch(err => {
      // throw errors to app error handler
      throw err
    })
}
840226
function wrapWithDispatch(asyncItems) {
  return asyncItems.map((item) => {
    const { key } = item;
    if (!key) return item;

    return {
      ...item,
      promise: (options) => {
        const { store: { dispatch } } = options;
        const next = item.promise(options);

        // NOTE: possibly refactor this with a breaking change in mind for future versions
        // we can return result of processed promise/thunk if need be
        if (isPromise(next)) {
          dispatch(load(key));
          // add action dispatchers
          next
            .then(data => dispatch(loadSuccess(key, data)))
            .catch(err => dispatch(loadFail(key, err)));
        } else if (next) {
          dispatch(loadSuccess(key, next));
        }

        return next;
      },
    };
  });
}
783960
function MdListController($scope, $element, $mdListInkRipple) {
  var ctrl = this;
  ctrl.attachRipple = attachRipple;

  function attachRipple (scope, element) {
    var options = {};
    $mdListInkRipple.attach(scope, element, options);
  }
}
205185
function wrapHandler(handler) {
  return function (state, ...args) {
    return _.assign({}, state, handler(state, ...args));
  };
}
1176071
function applyHooks(_target, _hooks, _owner) {
    for(var key in _hooks) {
      if(_hooks.hasOwnProperty(key)) {
        _target.$on(key, wrapHook(_hooks[key], _owner));
      }
    }
  }
655293
function executeHooks(data, allHooks, checkHooks, creationMode) {
    var hooksToCall = creationMode ? allHooks : checkHooks;
    if (hooksToCall) {
        callHooks(data, hooksToCall);
    }
}
38510
function routerStrategy(metadata, dataAdapter, opts) {
    const { router, routePrefix } = opts;
    for (const name in metadata) {
        const obj = metadata[name];
        const { routeSwitch = {} } = obj;
        let originalPath = name.toLowerCase();
        if (routePrefix) {
            routePrefix = routePrefix.startsWith('/') ? routePrefix : `/${routePrefix}`;
            originalPath = `${routePrefix}/${originalPath}`;
        } else {
            originalPath = `/${originalPath}`;
        }
        for (const key in routes) {
            if (routeSwitch[key] !== true) continue;

            let path = originalPath;
            const route = routes[key];
            const { pres, posts } = getHooks(obj, key, opts);
            const middleware = route.call(null, name, dataAdapter, opts, pres, posts);

            let method = null;
            switch (key) {
                case 'list':
                    method = 'get';
                    break;
                case 'id':
                    path = `${path}/id`;
                    method = 'get';
                    break;
                case 'create':
                    method = 'post';
                    break;
                case 'update':
                    method = 'put';
                    break;
                case 'remove':
                    method = 'delete';
                    break;
            }

            if (!method) {
                continue;
            }

            router[method](path, middleware);
            if (typeof opts.onRoute === 'function') {
                opts.onRoute.call(null, { name, path, method, middleware, pres, posts });
            }
        }
    }
    return async function empty(ctx, next) {
        try {
            await next();
        } catch (err) {
            throw err;
        }
    };
}
1131908
public function connectMiddlewares($controller, $method, MiddleWares $middleWares, $decorators = [])
    {
        $isClosure = is_callable($controller);
        if ($middleWares->valid()) {
            if ($isClosure) {
                $next = $this->getInvokeMiddlewareNext($controller, $middleWares, $decorators);
            } else {
                $next = $this->getControllerMiddlewareNext($controller, $method, $middleWares, $decorators);
            }
            $middleWares->withNextArgs($next);
            $response = $this->injectionClass($middleWares->current(), 'handle', $middleWares->getNextArgs());
        } else {
            if ($isClosure) {
                $controller = $this->closureBinder($controller);
                $response = $this->injectionClosure($controller, $decorators);
            } else {
                $response = $this->injectionClass($controller, $method, [], $decorators);
            }
        }

        if ($response instanceof Response) {
            $this->sendByResponse($response);
        }
    }
502542
def determine_hooks(self, controller=None):
        '''
        
        '''

        controller_hooks = []
        if controller:
            controller_hooks = _cfg(controller).get('hooks', [])
            if controller_hooks:
                return list(
                    sorted(
                        chain(controller_hooks, self.hooks),
                        key=operator.attrgetter('priority')
                    )
                )
        return self.hooks
57797
function copyHooks() {
		var src = path.join(__dirname, 'hooks');
		var dest = path.join(process.env.PWD, 'hooks');

		return pify(fs.copy.bind(fs), Promise)(path.join(__dirname, 'platforms.json'), path.join(dest, 'platforms.json'))
			.then(function () {
				memFsEditor.copyTpl(src, dest, options);

				return pify(memFsEditor.commit.bind(memFsEditor))();
			})
			.then(function () {
				// Make all the scripts executable in the Cordova project
				fs.readdirSync(src).forEach(function (hook) {
					var hookPath = path.join(dest, hook);

					fs.readdirSync(hookPath).forEach(function (script) {
						fs.chmodSync(path.join(hookPath, script), '755');
					});
				});
			});
	}
20680
function Context(hook, opts) {
    var prop;
    this.hook = hook;

    //create new object, to avoid affecting input opts in other places
    //For example context.opts.plugin = Object is done, then it affects by reference
    this.opts = {};
    for (prop in opts) {
    if (opts.hasOwnProperty(prop)) {
        this.opts[prop] = opts[prop];
      }
    }
    this.cmdLine =  process.argv.join(' ');
    this.cordova = require('../cordova/cordova');
}
1071651
function call($func,$args=NULL,$hooks='') {
		if (!is_array($args))
			$args=array($args);
		// Grab the real handler behind the string representation
		if (is_string($func))
			$func=$this->grab($func,$args);
		// Execute function; abort if callback/hook returns FALSE
		if (!is_callable($func))
			// No route handler
			if ($hooks=='beforeroute,afterroute') {
				$allowed=array();
				if (is_array($func))
					$allowed=array_intersect(
						array_map('strtoupper',get_class_methods($func[0])),
						explode('|',self::VERBS)
					);
				header('Allow: '.implode(',',$allowed));
				$this->error(405);
			}
			else
				user_error(sprintf(self::E_Method,
					is_string($func)?$func:$this->stringify($func)),
					E_USER_ERROR);
		$obj=FALSE;
		if (is_array($func)) {
			$hooks=$this->split($hooks);
			$obj=TRUE;
		}
		// Execute pre-route hook if any
		if ($obj && $hooks && in_array($hook='beforeroute',$hooks) &&
			method_exists($func[0],$hook) &&
			call_user_func_array(array($func[0],$hook),$args)===FALSE)
			return FALSE;
		// Execute callback
		$out=call_user_func_array($func,$args?:array());
		if ($out===FALSE)
			return FALSE;
		// Execute post-route hook if any
		if ($obj && $hooks && in_array($hook='afterroute',$hooks) &&
			method_exists($func[0],$hook) &&
			call_user_func_array(array($func[0],$hook),$args)===FALSE)
			return FALSE;
		return $out;
	}
699953
def find_controller(self, state):
        '''
        
        '''
        # get a sorted list of hooks, by priority (no controller hooks yet)
        req = state.request
        pecan_state = req.pecan

        # store the routing path for the current application to allow hooks to
        # modify it
        pecan_state['routing_path'] = path = req.path_info

        # handle "on_route" hooks
        self.handle_hooks(self.hooks, 'on_route', state)

        # lookup the controller, respecting content-type as requested
        # by the file extension on the URI
        pecan_state['extension'] = None

        # attempt to guess the content type based on the file extension
        if self.guess_content_type_from_ext \
                and not pecan_state['content_type'] \
                and '.' in path:
            _, extension = splitext(path.rstrip('/'))

            # preface with a letter to ensure compat for 2.5
            potential_type = guess_type('x' + extension)[0]

            if extension and potential_type is not None:
                path = ''.join(path.rsplit(extension, 1))
                pecan_state['extension'] = extension
                pecan_state['content_type'] = potential_type

        controller, remainder = self.route(req, self.root, path)
        cfg = _cfg(controller)

        if cfg.get('generic_handler'):
            raise exc.HTTPNotFound

        # handle generic controllers
        im_self = None
        if cfg.get('generic'):
            im_self = six.get_method_self(controller)
            handlers = cfg['generic_handlers']
            controller = handlers.get(req.method, handlers['DEFAULT'])
            handle_security(controller, im_self)
            cfg = _cfg(controller)

        # add the controller to the state so that hooks can use it
        state.controller = controller

        # if unsure ask the controller for the default content type
        content_types = cfg.get('content_types', {})
        if not pecan_state['content_type']:
            # attempt to find a best match based on accept headers (if they
            # exist)
            accept = getattr(req.accept, 'header_value', '*/*') or '*/*'
            if accept == '*/*' or (
                    accept.startswith('text/html,') and
                    list(content_types.keys()) in self.SIMPLEST_CONTENT_TYPES):
                pecan_state['content_type'] = cfg.get(
                    'content_type',
                    'text/html'
                )
            else:
                best_default = acceptparse.MIMEAccept(
                    accept
                ).best_match(
                    content_types.keys()
                )

                if best_default is None:
                    msg = "Controller '%s' defined does not support " + \
                          "content_type '%s'. Supported type(s): %s"
                    logger.error(
                        msg % (
                            controller.__name__,
                            pecan_state['content_type'],
                            content_types.keys()
                        )
                    )
                    raise exc.HTTPNotAcceptable()

                pecan_state['content_type'] = best_default
        elif cfg.get('content_type') is not None and \
                pecan_state['content_type'] not in content_types:

            msg = "Controller '%s' defined does not support content_type " + \
                  "'%s'. Supported type(s): %s"
            logger.error(
                msg % (
                    controller.__name__,
                    pecan_state['content_type'],
                    content_types.keys()
                )
            )
            raise exc.HTTPNotFound

        # fetch any parameters
        if req.method == 'GET':
            params = req.GET
        elif req.content_type in ('application/json',
                                  'application/javascript'):
            try:
                if not isinstance(req.json, dict):
                    raise TypeError('%s is not a dict' % req.json)
                params = NestedMultiDict(req.GET, req.json)
            except (TypeError, ValueError):
                params = req.params
        else:
            params = req.params

        # fetch the arguments for the controller
        args, varargs, kwargs = self.get_args(
            state,
            params.mixed(),
            remainder,
            cfg['argspec'],
            im_self
        )
        state.arguments = Arguments(args, varargs, kwargs)

        # handle "before" hooks
        self.handle_hooks(self.determine_hooks(controller), 'before', state)

        return controller, args + varargs, kwargs
533095
function nextPostHook(res) {
                    response = checkResponse(res, response);

                    if (currentPost + 1 < totalPost && self.__hooksEnabled !== false) {
                        currentPost += 1;

                        // Reference to current post hook
                        const currPost = posts[currentPost];
                        const hookMethod = currPost.displayName || currPost.name;
                        scope = getScope(self, name, res, hookMethod, 'post');

                        // Recursively call all the "post" hooks
                        return currPost.call(scope, response).then(nextPostHook, postHookErrorHandler);
                    }

                    /**
                     * All "post" hook process done.
                     * If the response has an "__override" property it will be our response
                     */
                    if (is.object(response) && {}.hasOwnProperty.call(response, '__override')) {
                        response = response.__override;
                    }

                    return resolveFn(response);
                }
579770
function asyncWrap (route) {
  return (req, res, next) => route(req, res, next).catch(next)
}
1120023
function (ctx, next) {
        var plugins = []
        var config = process.cssy.config

        ctx.imports = []

        var parseImportPlugin = postcss.plugin('cssy-parse-imports', function () {
          return function (styles) {
            styles.walkAtRules(function (atRule) {
              if (atRule.name !== 'import') {
                return
              }
              if (/^url\(|:\/\//.test(atRule.params)) {
                return // Absolute
              }
              ctx.imports.push(parseImport(atRule.params))
              atRule.remove()
            })
          }
        })

        if (ctx.config.import) {
          plugins.push(parseImportPlugin)
        }

        if (config.minify) {
          plugins.push(cssnano(extend({}, (typeof config.minify === 'object')
            ? config.minify : DEFAULT_MINIFY_OPTIONS)))
        }
        postcss(plugins)
          .process(ctx.src, {
            from: ctx.filename,
            to: ctx.filename + '.map',
            map: {
              prev: ctx.map,
              inline: config.sourcemap
            }
          })
          .then(function (result) {
            ctx.src = result.css
            if (config.sourcemap) {
              // TODO: Dig sourcemap, dig more.
              ctx.src += '\n/*# sourceURL=' + ctx.filename + '.output*/'
            }
            ctx.map = result.map
            next(null, ctx)
          })

        next(null, ctx)
      }
870568
def passes_route_hooks?(route, message, robot)
      robot.hooks[:validate_route].all? do |hook|
        hook.call(handler: handler, route: route, message: message, robot: robot)
      end
    end