Most of these args are passed directly to BackEnd(). However, default_host 
    is used a bit differently. It should be a (host, port) pair, and may be 
    overridden with cmdline args:
      file.py localhost
      file.py localhost 54545
175783
def build_backend(tasks, default_host=('127.0.0.1', DEFAULT_PORT), *args, 
                  **kw):
    
    host, port = default_host
    if len(sys.argv) > 1:
        host = sys.argv[1]
    if len(sys.argv) > 2:
        port = sys.argv[2]
    
    return BackEnd(tasks, host, port, *args, **kw)
575709
def get_argparser(parser=None):
        """"""
        parser = parser or argparse.ArgumentParser()
        parser.add_argument("--host", default="0.0.0.0", help="Host listen address")
        parser.add_argument("--port", "-p", default=9050, help="Listen port", type=int)
        parser.add_argument(
            "--debug",
            "-d",
            default=False,
            action="store_true",
            help="Enable debug mode",
        )
        parser.add_argument(
            "--log-level",
            "-l",
            default="INFO",
            help="Log Level, empty string to disable.",
        )
        parser.add_argument(
            "--twisted",
            default=False,
            action="store_true",
            help="Use twisted to server requests.",
        )
        parser.add_argument(
            "--gunicorn",
            default=False,
            action="store_true",
            help="Use gunicorn to server requests.",
        )
        parser.add_argument(
            "--threads", default=None, help="Number of threads to use.", type=int
        )
        parser.add_argument("--disable-embedded-logging",
                            default=False,
                            action="store_true",
                            help="Disable embedded logging configuration")
        return parser
101159
def setup_backend(
    serve=True,
    host=DEFAULT_HOST,
    port=DEFAULT_PORT,
    debug=False,
    open_browser=True,
    browsername=None,
    testing=False,
    private_key=None,
    certificate=None,
    LLDB=False,
):
    """"""
    app.config["LLDB"] = LLDB

    kwargs = {}
    ssl_context = get_ssl_context(private_key, certificate)
    if ssl_context:
        # got valid ssl context
        # force everything through https
        SSLify(app)
        # pass ssl_context to flask
        kwargs["ssl_context"] = ssl_context

    url = "%s:%s" % (host, port)
    if kwargs.get("ssl_context"):
        protocol = "https://"
        url_with_prefix = "https://" + url
    else:
        protocol = "http://"
        url_with_prefix = "http://" + url

    if debug:
        async_mode = "eventlet"
    else:
        async_mode = "gevent"

    socketio.server_options["async_mode"] = async_mode
    try:
        socketio.init_app(app)
    except Exception:
        print(
            'failed to initialize socketio app with async mode "%s". Continuing with async mode "threading".'
            % async_mode
        )
        socketio.server_options["async_mode"] = "threading"
        socketio.init_app(app)

    if testing is False:
        if host == DEFAULT_HOST:
            url = (DEFAULT_HOST, port)
        else:
            try:
                url = (socket.gethostbyname(socket.gethostname()), port)
            except Exception:
                url = (host, port)

        if open_browser is True and debug is False:
            browsertext = repr(browsername) if browsername else "default browser"
            args = (browsertext,) + url
            text = ("Opening gdbgui with %s at " + protocol + "%s:%d") % args
            print(colorize(text))
            b = webbrowser.get(browsername) if browsername else webbrowser
            b.open(url_with_prefix)
        else:
            print(colorize("View gdbgui at %s%s:%d" % (protocol, url[0], url[1])))

        print("exit gdbgui by pressing CTRL+C")

        try:
            socketio.run(
                app,
                debug=debug,
                port=int(port),
                host=host,
                extra_files=get_extra_files(),
                **kwargs
            )
        except KeyboardInterrupt:
            # Process was interrupted by ctrl+c on keyboard, show message
            pass
489083
def default_blockstack_api_opts(working_dir, config_file=None):
   

   from .util import url_to_host_port, url_protocol

   if config_file is None:
      config_file = virtualchain.get_config_filename(get_default_virtualchain_impl(), working_dir)

   parser = SafeConfigParser()
   parser.read(config_file)

   blockstack_api_opts = {}
   indexer_url = None
   api_port = DEFAULT_API_PORT
   api_host = DEFAULT_API_HOST
   run_api = True

   if parser.has_section('blockstack-api'):
      if parser.has_option('blockstack-api', 'enabled'):
          run_api = parser.get('blockstack-api', 'enabled').lower() in ['true', '1', 'on']

      if parser.has_option('blockstack-api', 'api_port'):
          api_port = int(parser.get('blockstack-api', 'api_port'))

      if parser.has_option('blockstack-api', 'api_host'):
          api_host = parser.get('blockstack-api', 'api_host')

      if parser.has_option('blockstack-api', 'indexer_url'):
          indexer_host, indexer_port = url_to_host_port(parser.get('blockstack-api', 'indexer_url'))
          indexer_protocol = url_protocol(parser.get('blockstack-api', 'indexer_url'))
          if indexer_protocol is None:
              indexer_protocol = 'http'

          indexer_url = parser.get('blockstack-api', 'indexer_url')

   if indexer_url is None:
       # try defaults
       indexer_url = 'http://localhost:{}'.format(RPC_SERVER_PORT)

   blockstack_api_opts = {
        'indexer_url': indexer_url,
        'api_host': api_host,
        'api_port': api_port,
        'enabled': run_api
   }

   # strip Nones
   for (k, v) in blockstack_api_opts.items():
      if v is None:
         del blockstack_api_opts[k]

   return blockstack_api_opts
219595
public static void main( String[] args )
    {
        myOut.println( "NanoHTTPD 1.25 (C) 2001,2005-2011 Jarno Elonen and (C) 2010 Konstantinos Togias\n" +
                "(Command line options: [-p port] [-d root-dir] [--licence])\n" );

        // Defaults
        int port = 80;
        File wwwroot = new File(".").getAbsoluteFile();

        // Show licence if requested
        for ( int i=0; i<args.length; ++i )
            if(args[i].equalsIgnoreCase("-p"))
                port = Integer.parseInt( args[i+1] );
            else if(args[i].equalsIgnoreCase("-d"))
                wwwroot = new File( args[i+1] ).getAbsoluteFile();
            else if ( args[i].toLowerCase().endsWith( "licence" ))
            {
                myOut.println( LICENCE + "\n" );
                break;
            }

        try
        {
            new NanoHTTPD( port, wwwroot );
        }
        catch( IOException ioe )
        {
            System.err.println( "Couldn't start server:\n" + ioe );
            System.exit( -1 );
        }

        myOut.println( "Now serving files in port " + port + " from \"" + wwwroot + "\"" );
        myOut.println( "Hit Enter to stop.\n" );

        try { System.in.read(); } catch( Throwable t ) {}
    }
521775
def serve(opts):
    
    resources = _load(opts.resources, opts.output_dir)
    opts.output_dir = resources.output_dir  # allow resources.yaml to set default output_dir
    if not os.path.exists(opts.output_dir):
        sys.stderr.write("Resources dir '{}' not found.  Did you fetch?\n".format(opts.output_dir))
        return 1
    backend.PyPIResource.build_pypi_indexes(opts.output_dir)
    os.chdir(opts.output_dir)

    HTTPServer.allow_reuse_address = True
    httpd = HTTPServer((opts.host, opts.port), SimpleHTTPRequestHandler)

    if opts.ssl_cert:
        httpd.socket = ssl.wrap_socket(httpd.socket, certfile=opts.ssl_cert, server_side=True)

    print("Serving at: http{}://{}:{}/".format(
        's' if opts.ssl_cert else '', socket.gethostname(), opts.port))
    httpd.serve_forever()
833334
def install_host(trg_queue, *hosts, **kwargs):
    '''  '''
    user = kwargs.pop('user', None)
    group = kwargs.pop('group', None)
    mode = kwargs.pop('mode', None)
    item_user = kwargs.pop('item_user', None)
    item_group = kwargs.pop('item_group', None)
    item_mode = kwargs.pop('item_mode', None)
    is_down = kwargs.pop('is_down', False)

    #set modes
    mode, user, group, item_user, item_group, item_mode =\
        _def_mode(mode, user, group, item_user, item_group, item_mode)
    uid, gid = uid_gid(user, group)
    host_path = fsq_path.hosts(trg_queue)
    try:
        _instdir(host_path, mode, uid, gid)
    except (OSError, IOError, ), e:
        if e.errno not in ( errno.EEXIST, errno.ENOTEMPTY, ):
            raise FSQInstallError(e.errno, wrap_io_os_err(e))
    if hosts:
        for host in hosts:
            host = fsq_path.valid_name(host)
            # uid_gid makes calls to the pw db and|or gr db, in addition to
            # potentially stat'ing, as such, we want to avoid calling it
            # unless we absoultely have to
            uid, gid = uid_gid(user, group)
            tmp_full, tmp_queue = _tmp_trg(host, host_path)
            try:
                # open once to cut down on stat/open for chown/chmod combo
                fd = os.open(tmp_full, os.O_RDONLY)
                try:
                    # always fchmod here as mkdtemp is different than normal
                    # mkdir
                    os.fchmod(fd, mode)
                    if -1 != uid or -1 != gid:
                        os.fchown(fd, uid, gid)
                finally:
                    os.close(fd)

                # bless our queue with its children
                _instdir(fsq_path.tmp(trg_queue, tmp_queue), mode, uid, gid)
                _instdir(fsq_path.queue(trg_queue, tmp_queue), mode, uid, gid)
                _instdir(fsq_path.done(trg_queue, tmp_queue), mode, uid, gid)
                _instdir(fsq_path.fail(trg_queue, tmp_queue), mode, uid, gid)

                # down via configure.down if necessary
                if is_down:
                    down_host(tmp_queue, host, user=item_user,
                              group=item_group, mode=item_mode)

                # atomic commit -- by rename
                os.rename(tmp_full, fsq_path.base(trg_queue, host))
            except (OSError, IOError, ), e:
                shutil.rmtree(tmp_full)
                if e.errno == errno.ENOTEMPTY:
                    raise FSQInstallError(e.errno, u'queue exists: {0}'.format(
                                          trg_queue))
                if isinstance(e, FSQError):
                    raise e
768252
def host(environ):  # pragma: no cover
    

    url = environ['wsgi.url_scheme'] + '://'

    if environ.get('HTTP_HOST'):
        url += environ['HTTP_HOST']
    else:
        url += environ['SERVER_NAME']

        if environ['wsgi.url_scheme'] == 'https':
            if environ['SERVER_PORT'] != '443':
                url += ':' + environ['SERVER_PORT']
        else:
            if environ['SERVER_PORT'] != '80':
                url += ':' + environ['SERVER_PORT']

    return url + quote(environ.get('SCRIPT_NAME', ''))
705085
def base_argparser(argv=()):
    
    global verbose
    verbose = _not_verbose

    _p = argparse.ArgumentParser(add_help=False)
    _p.add_argument('--debug', action='store_true', help="turn on all the show and verbose options (mainly for debugging pydeps itself)")
    _p.add_argument('--config', help="specify config file", metavar="FILE")
    _p.add_argument('--no-config', help="disable processing of config files", action='store_true')
    _p.add_argument('--version', action='store_true', help='print pydeps version')
    _p.add_argument('-L', '--log', help=textwrap.dedent('''
        set log-level to one of CRITICAL, ERROR, WARNING, INFO, DEBUG, NOTSET.
    '''))
    _args, argv = _p.parse_known_args(argv)

    if _args.log:
        loglevels = "CRITICAL DEBUG ERROR FATAL INFO WARN"
        if _args.log not in loglevels:  # pragma: nocover
            error('legal values for the -L parameter are:', loglevels)
        loglevel = getattr(logging, _args.log)
    else:
        loglevel = None

    logging.basicConfig(
        level=loglevel,
        format='%(filename)s:%(lineno)d: %(levelname)s: %(message)s'
    )

    if _args.version:  # pragma: nocover
        print("pydeps v" + __version__)
        sys.exit(0)

    return _p, _args, argv
856296
def console():
    '''
    
    '''
    parser = argparse.ArgumentParser(description='Start an endpoints WSGI server', add_help=True)
    #parser.add_argument('--debug', dest='debug', action='store_true', help='print debugging info')
    parser.add_argument(
        "-v", "--version",
        action='version',
        version="%(prog)s {}".format(endpoints.__version__)
    )
    parser.add_argument(
        "--quiet",
        action='store_true',
        dest='quiet'
    )
    parser.add_argument(
        '--prefix', "--controller-prefix", "-P",
        required=True,
        help='The endpoints controller prefix'
    )
    parser.add_argument(
        '--file', "-F", "--wsgi-file", "--wsgifile",
        dest="file",
        default="",
        help='The wsgi file, the file that has an application callable'
    )
    parser.add_argument(
        '--host', "-H",
        required=True,
        help='The host to serve on in the form host:port'
    )
    parser.add_argument(
        '--count', "-C",
        help='How many requests to process until self termination',
        type=int,
        default=0
    )
    parser.add_argument(
        '--dir', "-D", "--directory",
        dest="directory",
        default=os.getcwd(),
        help='directory to run the server in, usually contains the prefix module path',
    )
#     parser.add_argument(
#         '--config', "--config-script", "-S",
#         dest="config_script",
#         default="",
#         help='This script will be loaded before Server is created allowing custom configuration',
#     )

    args = parser.parse_args()

    # we want to make sure the directory can be imported from since chances are
    # the prefix module lives in that directory
    sys.path.append(args.directory)

    if not args.quiet:
        # https://docs.python.org/2.7/library/logging.html#logging.basicConfig
        logging.basicConfig(format="%(message)s", level=logging.DEBUG, stream=sys.stdout)

    logger = logging.getLogger(__name__)
    os.environ["ENDPOINTS_HOST"] = args.host
    environ.HOST = args.host
    os.environ["ENDPOINTS_PREFIX"] = args.prefix
    #environ.PREFIXES = args.prefix

    config = {}
    if args.file:
        # load the configuration file
        config = runpy.run_path(args.file)

#     if args.config_script:
#         # load a config script so you can customize the environment
#         h = "wsgiserver_config_{}".format(uuid.uuid4())
#         config_module = imp.load_source(h, args.config_script)

    s = Server()

    if "application" in config:
        s.application = config["application"]

    if args.count:
        logger.info("Listening on {} for {} requests".format(args.host, args.prefix))
        s.serve_count(args.count)

    else:
        logger.info("Listening on {}".format(args.host))
        s.serve_forever()

    return 0
86268
def main(args=None):
    """"""
    if args is None:
        args = sys.argv[1:]

    # Parse command-line
    args = docopt(__doc__, argv=args)

    # Parse arguments
    path, address = resolve(args['<path>'], args['<address>'])
    host, port = split_address(address)

    # Validate arguments
    if address and not (host or port):
        print 'Error: Invalid address', repr(address)
        return

    # Default values
    if path is None:
        path = '.'
    if host is None:
        host = 'localhost'
    if port is None:
        port = 5000

    # Run server
    print ' * Serving %s on http://%s:%s/' % (path, host, port)
1271329
def apply_module_defaults(args)
      args[:port] = args[:server].to_s.end_with?(JAMFCLOUD_DOMAIN) ? JAMFCLOUD_PORT : SSL_PORT if args[:no_port_specified]
      args[:timeout] ||= DFT_TIMEOUT
      args[:open_timeout] ||= DFT_OPEN_TIMEOUT
      args[:ssl_version] ||= DFT_SSL_VERSION
      args
    end
604040
public static void main(String[] args) throws Exception {
    CustomHeaderClient client = new CustomHeaderClient("localhost", 50051);
    try {
      /* Access a service running on the local machine on port 50051 */
      String user = "world";
      if (args.length > 0) {
        user = args[0]; /* Use the arg as the name to greet if provided */
      }
      client.greet(user);
    } finally {
      client.shutdown();
    }
  }
952815
def from_args(cls, target_url, default_url, test_url):
        """"""
        return cls("You're trying to upload to the legacy PyPI site '{}'. "
                   "Uploading to those sites is deprecated. \n "
                   "The new sites are pypi.org and test.pypi.org. Try using "
                   "{} (or {}) to upload your packages instead. "
                   "These are the default URLs for Twine now. \n More at "
                   "https://packaging.python.org/guides/migrating-to-pypi-org/"
                   " .".format(target_url, default_url, test_url)
                   )
270182
def main(forward=26944, host='127.0.0.1', listen=5555):
    '''
    
    '''
    # HTTP->HTTP: On your computer, browse to "http://127.0.0.1:81/" and you'll get http://www.google.com
    server = maproxy.proxyserver.ProxyServer("127.0.0.1", forward)
    server.listen(listen)
    print("Local IP:", socket.gethostbyname(socket.gethostname()))
    print("0.0.0.0:{} -> {}:{}".format(listen, host, forward))
    tornado.ioloop.IOLoop.instance().start()
1051701
def main(self, configuration):
    
    _custom_func_arguments = {"conf"}
    filename = os.path.basename(os.path.abspath(sys.argv[0]))

    default_arg_list = [item for item in configuration.get("default") if len(item.strip()) != 0]
    if len(default_arg_list) == 0:
      sys.stdout.write(self.generate_help(filename=filename))
      return

    command_name = default_arg_list.pop(0)
    if command_name not in self._modules.keys():
      sys.stdout.write(self.generate_help(filename=filename))
      return

    command = self._modules[command_name]
    entry_point = command["entry_point"]
    class_path = command["classpath"]
    metainfo = command["metainfo"]
    """:type metainfo ModuleMetaInfo"""

    try:
      args = metainfo.parse_default_arguments(default_arg_list)
      args.update(metainfo.parse_arguments(configuration))

      f_args = entry_point.__code__.co_varnames[:entry_point.__code__.co_argcount]

      if len(f_args) - len(set(f_args) & _custom_func_arguments) != len(set(args.keys()) & set(f_args)):
        raise ArgumentException("Function \"{}\" from module {} doesn't implement all arguments in the signature".format(
          entry_point.__name__, class_path
        ))

      if "conf" in f_args:
        args["conf"] = configuration

      entry_point(**args)
    except ArgumentException as e:
      sys.stdout.write("Application arguments exception: {}\n".format(str(e)))
      return
620502
def create_argparser():
    
    parser = argparse.ArgumentParser()
    arg_defaults = {
        "daemon": False,
        "loop": False,
        "listpresets": False,
        "config": None,
        "debug": False,
        "sleeptime": 300,
        "version": False,
        "verbose_count": 0
    }

    # add generic client options to the CLI:
    parser.add_argument("-c", "--config", dest="config",
                        help="config file", default=arg_defaults["config"])
    parser.add_argument("--list-presets", dest="listpresets",
                        help="list all available presets",
                        action="store_true", default=arg_defaults["listpresets"])
    parser.add_argument("-d", "--daemon", dest="daemon",
                        help="go into daemon mode (implies --loop)",
                        action="store_true", default=arg_defaults["daemon"])
    parser.add_argument("--debug", dest="debug",
                        help="increase logging level to DEBUG (DEPRECATED, please use -vvv)",
                        action="store_true", default=arg_defaults["debug"])
    parser.add_argument("--loop", dest="loop",
                        help="loop forever (default is to update once)",
                        action="store_true", default=arg_defaults["loop"])
    parser.add_argument("--sleeptime", dest="sleeptime",
                        help="how long to sleep between checks in seconds",
                        default=arg_defaults["sleeptime"])
    parser.add_argument("--version", dest="version",
                        help="show version and exit",
                        action="store_true", default=arg_defaults["version"])
    parser.add_argument("-v", "--verbose", dest="verbose_count",
                        action="count", default=arg_defaults["verbose_count"],
                        help="increases log verbosity for each occurrence")

    return parser, arg_defaults