Creates a chrome extension for the proxy
        Only need to be done this way when using a proxy with auth
192333
def _proxy_extension(self, proxy_parts):
        
        import zipfile
        manifest_json = """
                        {
                            "version": "1.0.0",
                            "manifest_version": 2,
                            "name": "Chrome Proxy",
                            "permissions": [
                                "proxy",
                                "tabs",
                                "unlimitedStorage",
                                "storage",
                                "<all_urls>",
                                "webRequest",
                                "webRequestBlocking"
                            ],
                            "background": {
                                "scripts": ["background.js"]
                            },
                            "minimum_chrome_version":"22.0.0"
                        }
                        """

        background_js = """
                        var config = {{
                                mode: "fixed_servers",
                                rules: {{
                                  singleProxy: {{
                                    scheme: "{schema}",
                                    host: "{host}",
                                    port: parseInt({port})
                                  }},
                                  bypassList: []
                                }}
                              }};

                        chrome.proxy.settings.set({{value: config, scope: "regular"}}, function() {{}});

                        function callbackFn(details) {{
                            return {{
                                authCredentials: {{
                                    username: "{user}",
                                    password: "{password}"
                                }}
                            }};
                        }}

                        chrome.webRequest.onAuthRequired.addListener(
                                    callbackFn,
                                    {{urls: ["<all_urls>"]}},
                                    ['blocking']
                        );
                        """.format(**proxy_parts)

        plugin_file = 'proxy_auth_plugin.zip'
        with zipfile.ZipFile(plugin_file, 'w') as zp:
            zp.writestr("manifest.json", manifest_json)
            zp.writestr("background.js", background_js)

        return plugin_file
1208684
function createHttpsServer(options, requestHandler, keys) {
  net
    .createServer(function(socket){
      socket.once('data', function(buffer){
        // Pause the socket
        socket.pause();

        // Determine if this is an HTTP(s) request
        var byte = buffer[0];
        var proxy;

        if (byte === 22)
          proxy = server.https;
        else if (32 < byte && byte < 127)
          proxy = server.http;

        if (proxy)
        {
          // Push the buffer back onto the front of the data stream
          socket.unshift(buffer);

          // Emit the socket to the HTTP(s) server
          proxy.emit('connection', socket);
        }

        // Resume the socket data stream
        socket.resume();
      });
    })
    .on('error', function(error){
      onError(error, options);
    })
    .listen(options.port, function(){
      onListen(this, options);
    });

  var server = {
    http: http.createServer(requestHandler),
    https: https.createServer(keys, requestHandler)
  };

  return server;
}
1263354
function HttpsProxyAgent (opts) {
  if (!(this instanceof HttpsProxyAgent)) return new HttpsProxyAgent(opts);
  if ('string' == typeof opts) opts = url.parse(opts);
  if (!opts) throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!');
  debug('creating new HttpsProxyAgent instance: %o', opts);
  Agent.call(this, connect);

  var proxy = extend({}, opts);

  // if `true`, then connect to the proxy server over TLS. defaults to `false`.
  this.secureProxy = proxy.protocol ? /^https:?$/i.test(proxy.protocol) : false;

  // prefer `hostname` over `host`, and set the `port` if needed
  proxy.host = proxy.hostname || proxy.host;
  proxy.port = +proxy.port || (this.secureProxy ? 443 : 80);

  if (proxy.host && proxy.path) {
    // if both a `host` and `path` are specified then it's most likely the
    // result of a `url.parse()` call... we need to remove the `path` portion so
    // that `net.connect()` doesn't attempt to open that as a unix socket file.
    delete proxy.path;
    delete proxy.pathname;
  }

  this.proxy = proxy;
}
840407
def _proxy_kwargs(browser_name, proxy, browser_kwargs={}):  # pylint: disable=dangerous-default-value
    

    proxy_dict = {
        "httpProxy": proxy.proxy,
        "proxyType": 'manual',
    }

    if browser_name == 'firefox' and 'desired_capabilities' not in browser_kwargs:
        # This one works for firefox locally
        wd_proxy = webdriver.common.proxy.Proxy(proxy_dict)
        browser_kwargs['proxy'] = wd_proxy
    else:
        # This one works with chrome, both locally and remote
        # This one works with firefox remote, but not locally
        if 'desired_capabilities' not in browser_kwargs:
            browser_kwargs['desired_capabilities'] = {}

        browser_kwargs['desired_capabilities']['proxy'] = proxy_dict

    return browser_kwargs
655713
public static <T> T buildProxy(String proxyType, Class<T> clazz, Invoker proxyInvoker) throws Exception {
        try {
            ExtensionClass<Proxy> ext = ExtensionLoaderFactory.getExtensionLoader(Proxy.class)
                .getExtensionClass(proxyType);
            if (ext == null) {
                throw ExceptionUtils.buildRuntime("consumer.proxy", proxyType,
                    "Unsupported proxy of client!");
            }
            Proxy proxy = ext.getExtInstance();
            return proxy.getProxy(clazz, proxyInvoker);
        } catch (SofaRpcRuntimeException e) {
            throw e;
        } catch (Throwable e) {
            throw new SofaRpcRuntimeException(e.getMessage(), e);
        }
    }
406745
function proxy() {
    // cannot re-use cmd, modifiying breaks subsequent
    // method invocations must use a local variable
    var name = cmd
      , args = [].slice.call(arguments)
      , cb;

    if(typeof args[args.length - 1] === 'function') {
      cb = args.pop();
    }
    this.execute(cmd, args, cb);
    return this;
  }
1123830
public Proxy setAuthentication( Authentication auth )
    {
        if ( eq( this.auth, auth ) )
        {
            return this;
        }
        return new Proxy( type, host, port, auth );
    }
234113
function createProxyHandler (proxies, urlRoot) {
  if (!proxies.length) {
    const nullProxy = (request, response, next) => next()
    nullProxy.upgrade = () => {}
    return nullProxy
  }

  function createProxy (request, response, next) {
    const proxyRecord = proxies.find((p) => request.url.startsWith(p.path))
    if (proxyRecord) {
      log.debug(`proxying request - ${request.url} to ${proxyRecord.host}:${proxyRecord.port}`)
      request.url = request.url.replace(proxyRecord.path, proxyRecord.baseUrl)
      proxyRecord.proxy.web(request, response)
    } else {
      return next()
    }
  }

  createProxy.upgrade = function (request, socket, head) {
    // special-case karma's route to avoid upgrading it
    if (request.url.startsWith(urlRoot)) {
      log.debug(`NOT upgrading proxyWebSocketRequest ${request.url}`)
      return
    }

    const proxyRecord = proxies.find((p) => request.url.startsWith(p.path))
    if (proxyRecord) {
      log.debug(`upgrade proxyWebSocketRequest ${request.url} to ${proxyRecord.host}:${proxyRecord.port}`)
      request.url = request.url.replace(proxyRecord.path, proxyRecord.baseUrl)
      proxyRecord.proxy.ws(request, socket, head)
    }
  }

  return createProxy
}
214269
function proxyConfig(path) {
  const config = {}

  const {endpointsExtension} = tryGetGraphQLProjectConfig()
  if (endpointsExtension) {
    const graphqlEndpoint = endpointsExtension.getEndpoint()

    const {url: target, headers} = graphqlEndpoint
    const changeOrigin = true

    const pathRewrite = {}
    pathRewrite[`^${path}`] = ''

    config[path] = {changeOrigin, headers, pathRewrite, target}
  }

  return config
}
243539
def _generate_request_handler_proxy(handler_class, handler_args, name):
    """"""

    @scope.inject
    def request_handler_wrapper(app, handler, **kwargs):
        handler = handler_class(app, handler.request, **handler_args)
        handler._execute([], **kwargs)
    request_handler_wrapper.__name__ = name
    request_handler_wrapper.handler_class = handler_class
    request_handler_wrapper.handler_args = handler_args

    return request_handler_wrapper
628452
def set_proxy(url, basic_auth=None):
    
    global _pools, _onetime_pool_spec
    if not url:
        _pools['default'] = urllib3.PoolManager(**_default_pool_params)
        _onetime_pool_spec = (urllib3.PoolManager, _onetime_pool_params)
    elif basic_auth:
        h = urllib3.make_headers(proxy_basic_auth=':'.join(basic_auth))
        _pools['default'] = urllib3.ProxyManager(url, proxy_headers=h, **_default_pool_params)
        _onetime_pool_spec = (urllib3.ProxyManager, dict(proxy_url=url, proxy_headers=h, **_onetime_pool_params))
    else:
        _pools['default'] = urllib3.ProxyManager(url, **_default_pool_params)
        _onetime_pool_spec = (urllib3.ProxyManager, dict(proxy_url=url, **_onetime_pool_params))
110793
function applyProxy(options, cb) {
  npmconf.load({}, function (er, conf) {
    var proxyUrl;

    if (!er) {
      proxyUrl = conf.get('https-proxy') ||
                 conf.get('proxy') ||
                 conf.get('http-proxy');
    }

    var env = process.env;

    options.proxy = proxyUrl ||
                    env.HTTPS_PROXY ||
                    env.https_proxy ||
                    env.HTTP_PROXY ||
                    env.http_proxy;

    cb(options);
  });
}
309033
def urlopen(self, method, url, redirect=True, **kw):
        ""
        u = parse_url(url)

        if u.scheme == "http":
            # For proxied HTTPS requests, httplib sets the necessary headers
            # on the CONNECT to the proxy. For HTTP, we'll definitely
            # need to set 'Host' at the very least.
            headers = kw.get('headers', self.headers)
            kw['headers'] = self._set_proxy_headers(url, headers)

        return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)
459722
function insertProxy(proxies, namespace, serverType, proxy) {
    proxies[namespace] = proxies[namespace] || {};
    if (proxies[namespace][serverType]) {
        for (const attr in proxy) {
            if (proxy.hasOwnProperty(attr)) {
                proxies[namespace][serverType][attr] = proxy[attr];
            }
        }
    } else proxies[namespace][serverType] = proxy;
}
240290
function request(location, settings) {
    var cookie, data, options, proto, req;

    if (_.isUndefined(settings) && _.isObject(location)) {
        settings = location;
        location = settings.location;
    }

    if (_.isFunction(settings)) {
        settings = { complete: settings };
    }

    _.defaults(settings, {
        complete: function () {},
        headers: {},
        maxRedirects: 10,
        nRedirects: 0,
        timeout: 1000 * 10,  // timeout request after 10 seconds
        proxy: proxy         // default to global proxy object
    });

    _.defaults(settings.headers, {
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/24.0.1312.70 Safari/537.1', 
        'accept-encoding': 'gzip,deflate'
    });

    options = url.parse(location);
    _.extend(options, settings);

    if (settings.proxy) {                        
        if (options.protocol === 'https:') {
            // We must tunnel SSL over HTTP, simply setting proxy headers won't work
            options.agent = tunnel.httpsOverHttp({ 
                proxy: {
                    host: settings.proxy.host,
                    port: settings.proxy.port,
                    proxyAuth: settings.proxy.auth
                } 
            });                  
        } else {
            // Modify host and port to request via proxy
            options.host = settings.proxy.host;
            options.port = settings.proxy.port;
            options.path = options.href;
            options.headers['host'] = options.hostname;
            if (settings.proxy.auth) {            
                options.headers['proxy-authorization'] = 'Basic ' + new Buffer(settings.proxy.auth).toString('base64');
            }

            delete options.hostname;
            delete options.href;
            delete options.pathname;
        }
    }

    if (settings.cookieJar) {        
        cookie = settings.cookieJar.toString();
        if (cookie.length) {            
            options.headers['cookie'] = settings.cookieJar.toString();            
        }            
    }

    data = null;
    if (options.data) {
        data = options.data;

        if (!options.method) {
            options.method = 'POST'; // Default to POST when data present and method not supplied
        }
        
        if (_.isObject(options.data)) {
            if (_(options.headers['content-type']).startsWith('application/json')) {
                data = JSON.stringify(options.data);
            } else {            
                // Default to form encoding
                if (!options.headers['content-type']) {
                    options.headers['content-type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
                }
                data = querystring.stringify(options.data);
            }
        } else {
            // Send raw string...
            data = options.data;
        }  

        // Calculate content length
        options.headers['content-length'] = Buffer.byteLength(data);      
    }
    
    // switch between http/s depending on protocol  
    proto = (options.protocol === 'https:') ? https : http;
    req = proto.request(options, function (res) {
        var output = new StringStream();                
        switch (res.headers['content-encoding']) {
            case 'gzip':
                res.pipe(zlib.createGunzip()).pipe(output);
                break;
            case 'deflate':
                res.pipe(zlib.createInflate()).pipe(output);
                break;
            default:
                // Treat as uncompressed string
                res.pipe(output);
                break;
        }

        output.on('end', function() {
            var i, baseUrl, cookies, err, location;

            if (settings.cookieJar && res.headers['set-cookie']) {
                cookies = res.headers['set-cookie'];
                for (i = 0; i < cookies.length; i++) {
                    settings.cookieJar.set(cookies[i]);
                }
            }

            if (res.statusCode >= 300 && res.statusCode < 400) {
                if (settings.maxRedirects > settings.nRedirects++) {
                    // Follow redirect                                            
                    baseUrl = options.protocol + '//' + ((proxy) ? options.headers['host'] : options.host);
                    location = url.resolve(baseUrl, res.headers['location']);
                    request(location, settings);                                   
                } else {
                    err = new Error('Max redirects reached.');
                    err.success = false;
                    settings.complete(err); 
                }
            } else if (res.statusCode >= 400) {
                err = new Error(output.caught);
                err.success = false;
                err.code = res.statusCode;
                settings.complete(err);            
            } else {                                
                settings.complete(null, output.caught, res);
            }
        });
    });

    req.on('socket', function (socket) {
        socket.setTimeout(settings.timeout);
        socket.on('timeout', function() {
            req.abort();
        });
    });

    req.on('error', function (err) {
        err.success = false;
        settings.complete(err);
    });

    if (data) { req.write(data); }

    req.end();
}
123096
function setupForCorporateProxy(proxyConfig) {
  if (!Array.isArray(proxyConfig)) {
    proxyConfig = [proxyConfig];
  }

  const proxyServer = process.env.http_proxy || process.env.HTTP_PROXY;
  let agent = null;

  if (proxyServer) {
    console.log(`Using corporate proxy server: ${proxyServer}`);
    agent = new HttpsProxyAgent(proxyServer);
    proxyConfig.forEach(entry => { entry.agent = agent; });
  }

  return proxyConfig;
}
749981
def proxy(ctx, bind, port):
    
    app = web.Application()
    app.on_startup.append(startup_proxy)
    app.on_cleanup.append(cleanup_proxy)

    app.router.add_route("GET", r'/stream/{path:.*$}', websocket_handler)
    app.router.add_route("GET", r'/wsproxy/{path:.*$}', websocket_handler)
    app.router.add_route('*', r'/{path:.*$}', web_handler)
    if getattr(ctx.args, 'testing', False):
        return app
    web.run_app(app, host=bind, port=port)