Main entry point for Glances.

    Select the mode (standalone, client or server)
    Run it...
497356
def main():
    
    # Catch the CTRL-C signal
    signal.signal(signal.SIGINT, __signal_handler)

    # Log Glances and psutil version
    logger.info('Start Glances {}'.format(__version__))
    logger.info('{} {} and psutil {} detected'.format(
        platform.python_implementation(),
        platform.python_version(),
        psutil_version))

    # Share global var
    global core

    # Create the Glances main instance
    core = GlancesMain()
    config = core.get_config()
    args = core.get_args()

    # Glances can be ran in standalone, client or server mode
    start(config=config, args=args)
589678
function main() {
  var server = new grpc.Server();
  server.addService(hello_proto.Greeter.service, {sayHello: sayHello});
  server.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure());
  server.start();
}
1296576
def autorun():
    '''
    
    '''
    def wrapper(cls):

        import inspect
        if inspect.getmodule(cls).__name__ == "__main__":
            cls().run()
        return cls

    return wrapper
980628
def do_mode(self, arg):
        
        restart_server = False
        if self.server.is_server_running() == 'yes' or self.server.is_server_running() == 'maybe':
            r = raw_input("Switching modes requires the server to restart. Really "
                          "switch modes? y or n: ")
            if r != 'y':
                return
            restart_server = True
        if arg['<which>'] is None:
            if self.sandbox:
                arg['<which>'] = 'live'
            else:
                arg['<which>'] = 'sandbox'
        if arg['<which>'] == 'live':
            self.set_sandbox(False)
            self.update_hit_tally()
            print 'Entered %s mode' % colorize('live', 'bold')
        else:
            self.set_sandbox(True)
            self.update_hit_tally()
            print 'Entered %s mode' % colorize('sandbox', 'bold')
        if restart_server:
            self.server_restart()
775873
public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					BootstrapWindow frame = new BootstrapWindow();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
248849
def main():
    """"""

    # Squelch SSL warnings
    logging.captureWarnings(True)
    if six.PY3:
        # These ones get triggered even when capturing warnings is turned on
        warnings.simplefilter('ignore', ResourceWarning)  # pylint:disable=E0602

    # Set the terminal title
    if os.getenv('DISPLAY'):
        title = 'rtv {0}'.format(__version__)
        sys.stdout.write('\x1b]2;{0}\x07'.format(title))
        sys.stdout.flush()

    args = Config.get_args()
    fargs, bindings = Config.get_file(args.get('config'))

    # Apply the file config first, then overwrite with any command line args
    config = Config()
    config.update(**fargs)
    config.update(**args)

    # If key bindings are supplied in the config file, overwrite the defaults
    if bindings:
        config.keymap.set_bindings(bindings)

    if config['copy_config']:
        return copy_default_config()
    if config['copy_mailcap']:
        return copy_default_mailcap()
    if config['list_themes']:
        return Theme.print_themes()

    # Load the browsing history from previous sessions
    config.load_history()

    # Load any previously saved auth session token
    config.load_refresh_token()
    if config['clear_auth']:
        config.delete_refresh_token()

    if config['log']:
        # Log request headers to the file (print hack only works on python 3.x)
        # from http import client
        # _http_logger = logging.getLogger('http.client')
        # client.HTTPConnection.debuglevel = 2
        # def print_to_file(*args, **_):
        #     if args[0] != "header:":
        #         _http_logger.info(' '.join(args))
        # client.print = print_to_file
        logging.basicConfig(
            level=logging.DEBUG,
            filename=config['log'],
            format='%(asctime)s:%(levelname)s:%(filename)s:%(lineno)d:%(message)s')
    else:
        # Add an empty handler so the logger doesn't complain
        logging.root.addHandler(logging.NullHandler())

    # Make sure the locale is UTF-8 for unicode support
    default_locale = locale.setlocale(locale.LC_ALL, '')
    try:
        encoding = locale.getlocale()[1] or locale.getdefaultlocale()[1]
    except ValueError:
        # http://stackoverflow.com/a/19961403
        # OS X on some terminals will set the LC_CTYPE to "UTF-8"
        # (as opposed to something like "en_US.UTF-8") and python
        # doesn't know how to handle it.
        _logger.warning('Error parsing system locale: `%s`,'
                        ' falling back to utf-8', default_locale)
        encoding = 'UTF-8'

    if not encoding or encoding.lower() != 'utf-8':
        text = ('System encoding was detected as (%s) instead of UTF-8'
                ', falling back to ascii only mode' % encoding)
        warnings.warn(text)
        config['ascii'] = True

    if packages.__praw_bundled__:
        praw_info = 'packaged, commit {}'.format(packages.__praw_hash__[:12])
    else:
        praw_info = 'system installed v{}'.format(praw.__version__)

    # Update the webbrowser module's default behavior
    patch_webbrowser()
    if webbrowser_import_warning:
        _logger.warning('webbrowser module was unexpectedly imported before'
                        '$BROWSER could be overwritten')

    # Construct the reddit user agent
    user_agent = docs.AGENT.format(version=__version__)

    debug_info = [
        'rtv version: rtv {}'.format(__version__),
        'rtv module path: {}'.format(os.path.abspath(__file__)),
        'python version: {}'.format(sys.version.replace('\n', ' ')),
        'python executable: {}'.format(sys.executable),
        'praw version: {}'.format(praw_info),
        'locale, encoding: {}, {}'.format(default_locale, encoding),
        'Environment Variables']
    for name, value in [
        ('BROWSER', BROWSER),
        ('DISPLAY', os.getenv('DISPLAY')),
        ('EDITOR', os.getenv('EDITOR')),
        ('LANG', os.getenv('LANG')),
        ('PAGER', os.getenv('PAGER')),
        ('RTV_BROWSER', RTV_BROWSER),
        ('RTV_EDITOR', os.getenv('RTV_EDITOR')),
        ('RTV_PAGER', os.getenv('RTV_PAGER')),
        ('RTV_URLVIEWER', os.getenv('RTV_URLVIEWER')),
        ('TERM', os.getenv('TERM')),
        ('VISUAL', os.getenv('VISUAL')),
        ('XDG_CONFIG_HOME', os.getenv('XDG_CONFIG_HOME')),
        ('XDG_DATA_HOME', os.getenv('XDG_DATA_HOME')),
    ]:
        debug_info.append('  {:<16}: {}'.format(name, value or ''))
    debug_info.append('')
    debug_text = '\n'.join(debug_info)

    _logger.info(debug_text)
    if config['debug_info']:
        print(debug_text)
        return

    try:
        with curses_session() as stdscr:

            term = Terminal(stdscr, config)

            if config['monochrome'] or config['theme'] == 'monochrome':
                _logger.info('Using monochrome theme')
                theme = Theme(use_color=False)
            elif config['theme'] and config['theme'] != 'default':
                _logger.info('Loading theme: %s', config['theme'])
                theme = Theme.from_name(config['theme'])
            else:
                # Set to None to let the terminal figure out which theme
                # to use depending on if colors are supported or not
                theme = None
            term.set_theme(theme)

            with term.loader('Initializing', catch_exception=False):
                reddit = praw.Reddit(user_agent=user_agent,
                                     decode_html_entities=False,
                                     disable_update_check=True,
                                     timeout=10,  # 10 second request timeout
                                     handler=RequestHeaderRateLimiter())

            # Dial the request cache up from 30 seconds to 5 minutes
            # I'm trying this out to make navigation back and forth
            # between pages quicker, it may still need to be fine tuned.
            reddit.config.api_request_delay = 300

            # Authorize on launch if the refresh token is present
            oauth = OAuthHelper(reddit, term, config)
            if config['autologin'] and config.refresh_token:
                oauth.authorize(autologin=True)

            # Open the supplied submission link before opening the subreddit
            if config['link']:
                # Expand shortened urls like https://redd.it/
                # Praw won't accept the shortened versions, add the reddit
                # headers to avoid a 429 response from reddit.com
                url = requests.head(
                    config['link'],
                    headers=reddit.http.headers,
                    allow_redirects=True
                ).url

                page = None
                with term.loader('Loading submission'):
                    try:
                        page = SubmissionPage(reddit, term, config, oauth, url)
                    except Exception as e:
                        _logger.exception(e)
                        raise SubmissionError('Unable to load {0}'.format(url))
                while page:
                    page = page.loop()

            page = None
            name = config['subreddit']
            with term.loader('Loading subreddit'):
                try:
                    page = SubredditPage(reddit, term, config, oauth, name)
                except Exception as e:
                    # If we can't load the subreddit that was requested, try
                    # to load the "popular" page instead so at least the
                    # application still launches. This used to use the user's
                    # front page, but some users have an empty front page.
                    _logger.exception(e)
                    page = SubredditPage(reddit, term, config, oauth, 'popular')
                    raise SubredditError('Unable to load {0}'.format(name))

            # Launch the subreddit page
            while page:
                page = page.loop()

    except ConfigError as e:
        _logger.exception(e)
        print(e)
    except Exception as e:
        _logger.exception(e)
        import traceback
        exit_message = '\n'.join([
            debug_text,
            traceback.format_exc(),
            'rtv has crashed. Please report this traceback at:',
            'https://github.com/michael-lazar/rtv/issues\n'])
        sys.stderr.write(exit_message)
        return 1  # General error exception code
    except KeyboardInterrupt:
        pass
    finally:
        # Try to save the browsing history
        config.save_history()
        # Ensure sockets are closed to prevent a ResourceWarning
        if 'reddit' in locals():
            reddit.handler.http.close()
1298359
def main() -> None:
    """"""

    # Make sure we have access to self
    if 'self' not in globals():
        print("Run 'set locals_in_py true' and then rerun this script")
        return

    # Make sure the user passed in an output file
    if len(sys.argv) != 2:
        print("Usage: {} <output_file>".format(os.path.basename(sys.argv[0])))
        return

    # Open the output file
    outfile_path = os.path.expanduser(sys.argv[1])
    try:
        outfile = open(outfile_path, 'w')
    except OSError as e:
        print("Error opening {} because: {}".format(outfile_path, e))
        return

    # Write the help summary
    header = '{0}\nSUMMARY\n{0}\n'.format(ASTERISKS)
    outfile.write(header)

    result = app('help -v')
    outfile.write(result.stdout)

    # Get a list of all commands and help topics and then filter out duplicates
    all_commands = set(self.get_all_commands())
    all_topics = set(self.get_help_topics())
    to_save = list(all_commands | all_topics)
    to_save.sort()

    for item in to_save:
        is_command = item in all_commands
        add_help_to_file(item, outfile, is_command)

        if is_command:
            # Add any sub-commands
            for subcmd in get_sub_commands(getattr(self.cmd_func(item), 'argparser', None)):
                full_cmd = '{} {}'.format(item, subcmd)
                add_help_to_file(full_cmd, outfile, is_command)

    outfile.close()
    print("Output written to {}".format(outfile_path))
1062498
def start(main_gui_class, **kwargs):
    """"""
    debug = kwargs.pop('debug', False)
    standalone = kwargs.pop('standalone', False)

    logging.basicConfig(level=logging.DEBUG if debug else logging.INFO,
                        format='%(name)-16s %(levelname)-8s %(message)s')
    logging.getLogger('remi').setLevel(
            level=logging.DEBUG if debug else logging.INFO)

    if standalone:
        s = StandaloneServer(main_gui_class, start=True, **kwargs)
    else:
        s = Server(main_gui_class, start=True, **kwargs)
738497
def main():
    
    try:
        # Get the `src` directory's absolute path
        src_path = os.path.dirname(
            # `aoiklivereload` directory's absolute path
            os.path.dirname(
                # `demo` directory's absolute path
                os.path.dirname(
                    # This file's absolute path
                    os.path.abspath(__file__)
                )
            )
        )

        # If the `src` directory path is not in `sys.path`
        if src_path not in sys.path:
            # Add to `sys.path`.
            #
            # This aims to save user setting PYTHONPATH when running this demo.
            #
            sys.path.append(src_path)

        # Import reloader class
        from aoiklivereload import LiveReloader

        # Create reloader
        reloader = LiveReloader(
            # Reload mode.
            #
            # In windows, have to use `spawn_exit` reload mode and force the
            # current process to exit immediately, otherwise will get the
            # error:
            # ```
            # OSError: [WinError 10048] Only one usage of each socket address
            # (protocol/network address/port) is normally permitted
            # ```
            #
            # Notice in `spawn_exit` reload mode, the user will not be able
            # to kill the new process using Ctrl-c.
            #
            reload_mode=('spawn_exit' if sys.platform == 'win32' else 'exec'),
            force_exit=True,
        )

        # Start watcher thread
        reloader.start_watcher_thread()

        # Server host
        server_host = '0.0.0.0'

        # Server port
        server_port = 8000

        # Get message
        msg = '# ----- Run server -----\nHost: {}\nPort: {}'.format(
            server_host, server_port
        )

        # Print message
        print(msg)

        # Create request handler
        class HelloHandler(tornado.web.RequestHandler):
            """
            Request handler class.
            """

            def get(self):
                """
                Request handler.

                :return:
                    None.
                """
                # Write response body
                self.write('hello')

        # List of tuples that maps URL pattern to handler
        handler_tuples = [
            ('/', HelloHandler),
        ]

        # Create Tornado app
        tornado_app = tornado.web.Application(
            handler_tuples,
            # Disable Tornado's reloader
            debug=False,
        )

        # Start listening
        tornado_app.listen(server_port, address=server_host)

        # Get event loop
        io_loop = tornado.ioloop.IOLoop.current()

        # Run event loop
        io_loop.start()

    # If have `KeyboardInterrupt`
    except KeyboardInterrupt:
        # Not treat as error
        pass
1283830
def main():
    
    application = Application(sys.argv, ignore_close=not SKIP_FILTER)

    platform.hide_cursor()

    with open(resource_filename(__name__, 'intervention.css')) as css:
        application.setStyleSheet(css.read())

    # exec() is required for objc so we must use spawn
    # multiprocessing.set_start_method('spawn')

    # target = do_nothing

    # if sys.platform == 'darwin' and not SKIP_FILTER:
    #     from filters import filter_input
    #     target = filter_input

    # pool = multiprocessing.Pool(1)  # pylint: disable=not-callable

    # def filter_input_done_cb(ignored):
    #     application.closeAllWindows()

    # result = pool.apply_async(target, callback=filter_input_done_cb)

    # pylint: disable=unused-variable
    @atexit.register
    def exit_handler():
        """
        Clean up.
        """
        logging.info('atexit triggered')

        platform.show_cursor()

    #     # terminate the pool so we don't sit forever waiting on our get()
    #     logging.info('Terminating pool...')
    #     pool.terminate()

    #     logging.info('Joining pool...')
    #     pool.join()

    #     logging.info('Retrieving result...')
    #     try:
    #         # raise any exceptions raised by the input filtering code
    #         result.get(0)
    #     except multiprocessing.TimeoutError:
    #         logging.info('Timed out waiting for result.')

    # def duration_reached():
    #     logging.info('Duration reached, exiting...')

    #     sys.exit(0)

    # Run for DURATION and then exit
    # QtCore.QTimer.singleShot(DURATION, duration_reached)

    application.run()
210032
def main():
        
        app = QApplication(sys.argv)
        rlbot_icon = QtGui.QIcon(os.path.join(get_rlbot_directory(), 'img', 'rlbot_icon.png'))
        app.setWindowIcon(rlbot_icon)
        window = RLBotQTGui()
        window.show()
        app.exec_()
1010097
def main():
    
    arguments = docopt(main.__doc__)

    if arguments.get('--version'):
        print('with {}'.format(withtool.__version__))
        sys.exit()

    while True:
        sub = yield from get_prompt(arguments['<command>'])
        call = '{cmd} {sub}'.format(cmd=arguments['<command>'], sub=sub)
        run(call)
968921
def main():
    
    arguments = docopt(__doc__)
    if arguments['init']:
        return_code = init()
        sys.exit(return_code)

    run_converter(arguments)
859665
def main():
    

    if not sys.platform.startswith("win"):
        if "--daemon" in sys.argv:
            daemonize()
    from gns3server.run import run
    run()
1001741
def main():
    

    print("Ontospy " + VERSION)

    Shell()._clear_screen()
    print(Style.BRIGHT + "** Ontospy Interactive Ontology Browser " + VERSION + " **" + Style.RESET_ALL)
    # manager.get_or_create_home_repo()
    Shell().cmdloop()
    raise SystemExit(1)
302118
def entry_point():
    
    try:
        main("omego", items=[
            (InstallCommand.NAME, InstallCommand),
            (UpgradeCommand.NAME, UpgradeCommand),
            (ConvertCommand.NAME, ConvertCommand),
            (DownloadCommand.NAME, DownloadCommand),
            (DbCommand.NAME, DbCommand),
            (Version.NAME, Version)])
    except Stop, stop:
        if stop.rc != 0:
            print "ERROR:", stop
        else:
            print stop
        sys.exit(stop.rc)
29671
public function main()
    {
        # The theme is activated.
        # Location: Resources/Themes/Default/
        Theme::active('Default');
        
        # The current settings are being configured.
        Masterpage::headPage('Sections/head')
                  ->bodyPage('Sections/body')
                  ->browserIcon(FILES_DIR . 'favicon.ico')
                  ->backgroundImage(FILES_DIR . 'background.jpg');
    }