The ChefAPI connection object with lots of pretty middleware.
433222
def connection
      @connection ||= ChefAPI::Connection.new do |conn|
        conn.endpoint   = ENV['STOVE_ENDPOINT']      || Config.endpoint || DEFAULT_ENDPOINT
        conn.client     = ENV['STOVE_USERNAME']      || Config.username
        conn.key        = ENV['STOVE_KEY']           || Config.key
        conn.ssl_verify = ENV['STOVE_NO_SSL_VERIFY'] || Config.ssl_verify
      end
    end
428263
def make_middleware(self, app):
        

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

        return application
1143787
function compose (middleware) {
  if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')
  for (const fn of middleware) {
    if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')
  }

  /**
   * @param {Object} context
   * @return {Promise}
   * @api public
   */

  return function (context, next) {
    // last called middleware #
    let index = -1
    return dispatch(0)
    function dispatch (i) {
      if (i <= index) return Promise.reject(new Error('next() called multiple times'))
      index = i
      let fn = middleware[i]
      if (i === middleware.length) fn = next
      if (!fn) return Promise.resolve()
      try {
        return Promise.resolve(fn(context, dispatch.bind(null, i + 1)))
      } catch (err) {
        return Promise.reject(err)
      }
    }
  }
}
1097166
function(middlewares, method, request, response_middlewares, callback) {
        var that = this;
        try {
            var middleware = middlewares.shift();
            if (!middleware) {
                return this._makeRequest(request, callback, response_middlewares);
            }
            if (middleware.cond(method, request)) {
                var middleware_callback = function(retVal) {
                    /**
                     * got an error
                     * break middleware chain and callback
                     */
                    if (retVal && retVal instanceof Error) {
                        return callback(retVal, null);
                    }
                    /**
                     * got a response object
                     * break middleware chain and bypass request
                     */
                    if (retVal && typeof retVal == 'object') {
                        return that._callResponseMiddlewares(response_middlewares, retVal, callback);
                    }
                    /**
                     * got a callback
                     * push it on response_middlewares array
                     * will be called after request
                     */
                    if (retVal && typeof retVal == 'function') {
                        response_middlewares.unshift(retVal);
                    }
                    that._callRequestMiddlewares(middlewares, method, request, response_middlewares, callback);
                };
                middleware.fun(method, request, middleware_callback);
            } else {
                this._callRequestMiddlewares(middlewares, method, request, response_middlewares, callback);
            }
        } catch (e) {
            callback(e, null);
        }
    }
468981
function createDefaultMiddleware(connect, options) {
    var middlewares = [];
    if (!Array.isArray(options.base)) {
      options.base = [options.base];
    }
    // Options for serve-static module. See https://www.npmjs.com/package/serve-static
    var defaultStaticOptions = {};
    var directory = options.directory || options.base[options.base.length - 1];
    options.base.forEach(function(base) {
      // Serve static files.
      var path = base.path || base;
      var staticOptions = base.options || defaultStaticOptions;
      middlewares.push(serveStatic(path, staticOptions));
    });
    // Make directory browse-able.
    middlewares.push(serveIndex(directory.path || directory, directory.options));
    return middlewares;
  }
36673
def _make_middleware_stack(middleware, base):
        
        for ware in reversed(middleware):
            base = ware(base)
        return base
956282
def get_recipe_object(self, mode_name, pipeline_name='default'):
        """"""
        active_mode = self.modes[mode_name]
        active_pipeline = self.pipelines[pipeline_name]
        recipe = active_pipeline.get_recipe_object(active_mode)
        return recipe
14685
function middlewareStrategy(metadata, dataAdapter, opts) {
    opts.filter = opts.filter || defaultFilter;
    const { filter } = opts;
    return async function magic(ctx, next) {
        const { name, key } = opts.filter.call(null, ctx);
        const obj = metadata[name];
        const { routeSwitch = {} } = obj;

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

        try {
            if (typeof middleware === 'function') {
                await middleware.call(null, ctx, next);
            } else {
                await next();
            }
        } catch (err) {
            throw err;
        }
    }
}
302302
def construct_fixture_middleware(fixtures):
    
    def fixture_middleware(make_request, web3):
        def middleware(method, params):
            if method in fixtures:
                result = fixtures[method]
                return {'result': result}
            else:
                return make_request(method, params)
        return middleware
    return fixture_middleware
395745
def connection(model_connections):
    

    # for each connection group
    for connection_str in model_connections:

        # the services to connect
        services = connection_str.split(':')
        services.sort()

        service_name = ''.join([service.title() for service in services])

        # the template context
        context = {
            # make sure the first letter is lowercase
            'name': service_name[0].lower() + service_name[1:],
            'services': services,
        }

        render_template(template='common', context=context)
        render_template(template='connection', context=context)
1286514
def recursively_collect_orders(
        name, ctx, all_inputs, orders=None, blacklist=None
        ):
    '''

    '''
    name = name.lower()
    if orders is None:
        orders = []
    if blacklist is None:
        blacklist = set()
    try:
        recipe = Recipe.get_recipe(name, ctx)
        dependencies = get_dependency_tuple_list_for_recipe(
            recipe, blacklist=blacklist
        )

        # handle opt_depends: these impose requirements on the build
        # order only if already present in the list of recipes to build
        dependencies.extend(fix_deplist(
            [[d] for d in recipe.get_opt_depends_in_list(all_inputs)
             if d.lower() not in blacklist]
        ))

        if recipe.conflicts is None:
            conflicts = []
        else:
            conflicts = [dep.lower() for dep in recipe.conflicts]
    except ValueError:
        # The recipe does not exist, so we assume it can be installed
        # via pip with no extra dependencies
        dependencies = []
        conflicts = []

    new_orders = []
    # for each existing recipe order, see if we can add the new recipe name
    for order in orders:
        if name in order:
            new_orders.append(deepcopy(order))
            continue
        if order.conflicts():
            continue
        if any([conflict in order for conflict in conflicts]):
            continue

        for dependency_set in product(*dependencies):
            new_order = deepcopy(order)
            new_order[name] = set(dependency_set)

            dependency_new_orders = [new_order]
            for dependency in dependency_set:
                dependency_new_orders = recursively_collect_orders(
                    dependency, ctx, all_inputs, dependency_new_orders,
                    blacklist=blacklist
                )

            new_orders.extend(dependency_new_orders)

    return new_orders
958089
function ActionMiddleware(...middleware) {
    return function (target, propertyKey, descriptor) {
        if (middleware != undefined) {
            let m = exports.globalKCState.getOrInsertController(target.constructor).getOrInsertMethod(propertyKey);
            m.middleware = middleware.concat(m.middleware);
        }
    };
}
585100
def connection
      @connection ||= begin
        uri = URI(Config.artifactory.strip)
        # Open the HTTP connection to artifactory.
        http = Net::HTTP.new(uri.host, uri.port)
        if uri.scheme == 'https'
          http.use_ssl = true
          # Mimic the behavior of the Cookbook uploader for SSL verification.
          if ENV['STOVE_NO_SSL_VERIFY'] || !Config.ssl_verify
            http.verify_mode = OpenSSL::SSL::VERIFY_NONE
          end
        end
        http.start
      end
    end
407074
function RestAPI() {
  this.models = {};
  this.router = express.Router();
  this.router.use(require('res-error')({
    log: false
  }));
}
186691
function middlewareF (req, res, end) {
    var index = 0

    // inject stats middleware
    if (middlewareF.options && middlewareF.options.stats) {
      middlewareF.stack = middlewareF.stack.map(function (mw) {
        var fn
        if (typeof mw === 'object') {
          var key = Object.keys(mw)[0]
          if (!mw[key].stats) {
            fn = {}
            fn[key] = middlewareF.options.stats(mw[key])
          }
        } else {
          if (!mw.stats) {
            fn = middlewareF.options.stats(mw)
          }
        }
        return fn
      })
    }

    // looping over all middleware functions defined by stack
    ;(function next (err) {
      var arity
      var middleware = middlewareF.stack[index++] // obtain the current middleware from the stack

      if (!middleware) {
        // we are at the end of the stack
        end && end(err)
        return
      } else {
        // extract middleware from object
        if (typeof (middleware) === 'object') {
          var name = Object.keys(middleware)[0]
          if (typeof (middleware[name]) === 'function') {
            middleware = middleware[name]
          } else {
            middleware = function (req, res, next) {
              next(new Error('missing middleware'))
            }
          }
        }

        try {
          arity = middleware.length // number of arguments function middleware requires
          // handle errors
          if (err) {
            // If the middleware function contains 4 arguments than this will act as an "error trap"
            if (arity === 4) {
              middleware(err, req, res, function (err) {
                nextTick(next, err)
              })
            } else {
              // otherwise check the next middleware
              next(err)
            }
          } else if (arity < 4) {
            // process non "error trap" stack
            middleware(req, res, function (err) {
              nextTick(next, err)
            })
          } else {
            // loop over "error traps" if no error `err` is set.
            next()
          }
        } catch (e) {
          next(e)
        }
      }
    })()
  }
1322185
def cli(env, **kwargs):
    

    mgr = SoftLayer.DedicatedHostManager(env.client)
    tables = []

    if not kwargs['flavor'] and not kwargs['datacenter']:
        options = mgr.get_create_options()

        # Datacenters
        dc_table = formatting.Table(['datacenter', 'value'])
        dc_table.sortby = 'value'
        for location in options['locations']:
            dc_table.add_row([location['name'], location['key']])
        tables.append(dc_table)

        dh_table = formatting.Table(['Dedicated Virtual Host Flavor(s)', 'value'])
        dh_table.sortby = 'value'
        for item in options['dedicated_host']:
            dh_table.add_row([item['name'], item['key']])
        tables.append(dh_table)
    else:
        if kwargs['flavor'] is None or kwargs['datacenter'] is None:
            raise exceptions.ArgumentError('Both a flavor and datacenter need '
                                           'to be passed as arguments '
                                           'ex. slcli dh create-options -d '
                                           'ams01 -f '
                                           '56_CORES_X_242_RAM_X_1_4_TB')
        router_opt = mgr.get_router_options(kwargs['datacenter'], kwargs['flavor'])
        br_table = formatting.Table(
            ['Available Backend Routers'])
        for router in router_opt:
            br_table.add_row([router['hostname']])
        tables.append(br_table)

    env.fout(formatting.listing(tables, separator='\n'))
617252
function(arr, req, res, indx, cb) {
    if (arr.length === indx) {
      cb();
    } else {
      arr[indx](req, res, function() {
        middleware(arr, req, res, ++indx, cb);
      });
    }
  }