Script entry point.
423727
def main():
    ''''''
    import getopt

    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hv', ['help', 'version'])
    except getopt.GetoptError as err:
        sys.stderr.write('Error: %s\n' % err)
        exit(2)

    for opt, _ in opts:
        if opt in ['-h', '--help']:
            show_usage()
            exit()
        elif opt in ['-v', '--version']:
            show_version()
            exit()

    if len(args) != 2:
        show_usage()
        exit(1)

    infile, outfile = args
    if infile == outfile:
        sys.stderr.write('Error: outfile must differ from infile\n')
        exit(3)

    reverse_file(infile, outfile)
    sys.stdout.write('Successfully written to %s\n' % outfile)
963789
def main(argv=sys.argv[1:], loop=None):
    """"""
    args = docopt(__doc__, argv=argv,
                  version=pkg_resources.require('rflink')[0].version)

    level = logging.ERROR
    if args['-v']:
        level = logging.INFO
    if args['-v'] == 2:
        level = logging.DEBUG
    logging.basicConfig(level=level)

    if not loop:
        loop = asyncio.get_event_loop()

    if args['--ignore']:
        ignore = args['--ignore'].split(',')
    else:
        ignore = []

    command = next((c for c in ALL_COMMANDS if args[c] is True), None)

    if command:
        protocol = PROTOCOLS['command']
    else:
        protocol = PROTOCOLS[args['-m']]

    conn = create_rflink_connection(
        protocol=protocol,
        host=args['--host'],
        port=args['--port'],
        baud=args['--baud'],
        loop=loop,
        ignore=ignore,
    )

    transport, protocol = loop.run_until_complete(conn)

    try:
        if command:
            for _ in range(int(args['--repeat'])):
                loop.run_until_complete(
                    protocol.send_command_ack(
                        args['<id>'], command))
        else:
            loop.run_forever()
    except KeyboardInterrupt:
        # cleanup connection
        transport.close()
        loop.run_forever()
    finally:
        loop.close()
388255
def main():
    """"""
    args = docopt(__doc__, version=__version__, options_first=True)

    # Validate args.
    s = Schema({
        six.text_type: bool,
        '--config-file': Or(None, str),
        '<args>': list,
        '<command>': Or(str, lambda _: 'help'),
    })
    try:
        args = s.validate(args)
    except SchemaError as exc:
        print('{0}\n{1}'.format(str(exc), printable_usage(__doc__)), file=sys.stderr)
        sys.exit(1)

    # Get subcommand.
    cmd = args['<command>']
    if cmd in cmd_aliases:
        cmd = cmd_aliases[cmd]

    if (cmd == 'help') or (not cmd):
        if not args['<args>']:
            sys.exit(print(__doc__.strip(), file=sys.stderr))
        else:
            ia_module = load_ia_module(args['<args>'][0])
            sys.exit(print(ia_module.__doc__.strip(), file=sys.stderr))

    if cmd != 'configure' and args['--config-file']:
        if not os.path.isfile(args['--config-file']):
            print('--config-file should be a readable file.\n{0}'.format(
                printable_usage(__doc__)), file=sys.stderr)
            sys.exit(1)

    argv = [cmd] + args['<args>']

    config = dict()
    if args['--log']:
        config['logging'] = {'level': 'INFO'}
    elif args['--debug']:
        config['logging'] = {'level': 'DEBUG'}

    if args['--insecure']:
        config['general'] = dict(secure=False)

    session = get_session(config_file=args['--config-file'],
                          config=config,
                          debug=args['--debug'])

    ia_module = load_ia_module(cmd)
    try:
        sys.exit(ia_module.main(argv, session))
    except IOError as e:
        # Handle Broken Pipe errors.
        if e.errno == errno.EPIPE:
            sys.stderr.close()
            sys.stdout.close()
            sys.exit(0)
        else:
            raise
1374002
def main(opts):
    """"""
    term = Terminal()
    style = Style()

    # if the terminal supports colors, use a Style instance with some
    # standout colors (magenta, cyan).
    if term.number_of_colors:
        style = Style(attr_major=term.magenta,
                      attr_minor=term.bright_cyan,
                      alignment=opts['--alignment'])
    style.name_len = term.width - 15

    screen = Screen(term, style, wide=opts['--wide'])
    pager = Pager(term, screen, opts['character_factory'])

    with term.location(), term.cbreak(), \
            term.fullscreen(), term.hidden_cursor():
        pager.run(writer=echo, reader=term.inkey)
    return 0
249126
def _run(self, lines):
        '''

        '''
        lines = [x for x in lines if x not in ['', None]]

        # Default runscript is first index
        runscript = lines[0]

        # Multiple line runscript needs multiple lines written to script
        if len(lines) > 1:

            bot.warning('More than one line detected for runscript!')
            bot.warning('These will be echoed into a single script to call.')
            self._write_script('/entrypoint.sh', lines)
            runscript = "/bin/bash /entrypoint.sh"

        self.cmd = runscript
120706
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName="polyglot"
    )
    arguments, settings, log, dbConn = su.setup()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    # for k, v in locals().iteritems():
    #     print k, v

    if not destinationFolder:
        destinationFolder = os.getcwd()
    if not filenameFlag:
        filenameFlag = False
    if not cleanFlag:
        readability = False
    else:
        readability = True

    if init:
        from os.path import expanduser
        home = expanduser("~")
        filepath = home + "/.config/polyglot/polyglot.yaml"
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass

    if pdf and url:
        filepath = printpdf.printpdf(
            log=log,
            settings=settings,
            url=url,
            folderpath=destinationFolder,
            title=filenameFlag,
            append=False,
            readability=readability
        ).get()

    if html and url:

        cleaner = htmlCleaner.htmlCleaner(
            log=log,
            settings=settings,
            url=url,
            outputDirectory=destinationFolder,
            title=filenameFlag,  # SET TO FALSE TO USE WEBPAGE TITLE,
            style=cleanFlag,  # add polyglot's styling to the HTML document
            metadata=True,  # include metadata in generated HTML (e.g. title),
            h1=True  # include title as H1 at the top of the doc
        )
        filepath = cleaner.clean()

    if epub:
        if url:
            iinput = url
        else:
            iinput = docx
        from polyglot import ebook
        epub = ebook(
            log=log,
            settings=settings,
            urlOrPath=iinput,
            title=filenameFlag,
            bookFormat="epub",
            outputDirectory=destinationFolder
        )
        filepath = epub.get()

    if mobi:
        if url:
            iinput = url
        else:
            iinput = docx
        from polyglot import ebook
        mobi = ebook(
            log=log,
            settings=settings,
            urlOrPath=iinput,
            title=filenameFlag,
            bookFormat="mobi",
            outputDirectory=destinationFolder,
        )
        filepath = mobi.get()

    if kindle:
        if url:
            iinput = url
        else:
            iinput = docx
        from polyglot import kindle
        sender = kindle(
            log=log,
            settings=settings,
            urlOrPath=iinput,
            title=filenameFlag
        )
        success = sender.send()

    if kindleNB2MD:
        basename = os.path.basename(notebook)
        extension = os.path.splitext(basename)[1]
        filenameNoExtension = os.path.splitext(basename)[0]
        if destinationFolder:
            filepath = destinationFolder + "/" + filenameNoExtension + ".md"
        else:
            filepath = notebook.replace("." + extension, ".md")
        from polyglot.markdown import kindle_notebook
        nb = kindle_notebook(
            log=log,
            kindleExportPath=notebook,
            outputPath=filepath
        )
        nb.convert()

    if openFlag:
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
774253
def main():
    ""

    actions = """
        {LWIN}
        {PAUSE .25}
        r
        {PAUSE .25}
        Notepad.exe{ENTER}
        {PAUSE 1}
        Hello{SPACE}World!
        {PAUSE 1}
        %{F4}
        {PAUSE .25}
        n
        """
    SendKeys(actions, pause = .1)

    keys = parse_keys(actions)
    for k in keys:
        print(k)
        k.Run()
        time.sleep(.1)

    test_strings = [
        "\n"
        "(aa)some text\n",
        "(a)some{ }text\n",
        "(b)some{{}text\n",
        "(c)some{+}text\n",
        "(d)so%me{ab 4}text",
        "(e)so%me{LEFT 4}text",
        "(f)so%me{ENTER 4}text",
        "(g)so%me{^aa 4}text",
        "(h)some +(asdf)text",
        "(i)some %^+(asdf)text",
        "(j)some %^+a text+",
        "(k)some %^+a tex+{&}",
        "(l)some %^+a tex+(dsf)",
        "",
        ]

    for s in test_strings:
        print(repr(s))
        keys = parse_keys(s, with_newlines = True)
        print(keys)

        for k in keys:
            k.Run()
            time.sleep(.1)
        print()
1261896
def main():
    """"""
    # Check command line arguments.
    if len(sys.argv) < 2:
        raise RuntimeError('Usage: python3 async_recv.py <json config>')

    # Set up logging.
    sip_logging.init_logger(show_thread=True)

    # Load SPEAD configuration from JSON file.
    # with open(sys.argv[-1]) as f:
    #     spead_config = json.load(f)
    spead_config = json.loads(sys.argv[1])

    # Set up the SPEAD receiver and run it (see method, above).
    receiver = SpeadReceiver(spead_config)
    receiver.run()
1024133
def main(argv=None):
    """"""

    parser = argparse.ArgumentParser(
        description='Commands as arguments'
    )
    command_help = 'optional command to run, if no command given, enter an interactive shell'
    parser.add_argument('command', nargs='?',
                        help=command_help)
    arg_help = 'optional arguments for command'
    parser.add_argument('command_args', nargs=argparse.REMAINDER,
                        help=arg_help)

    args = parser.parse_args(argv)

    c = CmdLineApp()

    if args.command:
        # we have a command, run it and then exit
        c.onecmd_plus_hooks('{} {}'.format(args.command, ' '.join(args.command_args)))
    else:
        # we have no command, drop into interactive mode
        c.cmdloop()
787223
def main():
    """"""
    options, command = parser()

    # logging
    root_logger = logging.getLogger()
    for log_handler in root_logger.handlers:
        root_logger.removeHandler(log_handler)
    root_logger = None
    numeric_loglevel = getattr(logging, options.debug_level.upper(), None)
    logformat = '%(levelname)s:%(module)s:%(message)s'
    logging.basicConfig(level=numeric_loglevel, filename=options.logfile,
                        filemode='w', format=logformat)

    # locate alot config files
    cpath = options.config
    if options.config is None:
        xdg_dir = get_xdg_env('XDG_CONFIG_HOME',
                              os.path.expanduser('~/.config'))
        alotconfig = os.path.join(xdg_dir, 'alot', 'config')
        if os.path.exists(alotconfig):
            cpath = alotconfig

    try:
        settings.read_config(cpath)
        settings.read_notmuch_config(options.notmuch_config)
    except (ConfigError, OSError, IOError) as e:
        print('Error when parsing a config file. '
              'See log for potential details.')
        sys.exit(e)

    # store options given by config swiches to the settingsManager:
    if options.colour_mode:
        settings.set('colourmode', options.colour_mode)

    # get ourselves a database manager
    indexpath = settings.get_notmuch_setting('database', 'path')
    indexpath = options.mailindex_path or indexpath
    dbman = DBManager(path=indexpath, ro=options.read_only)

    # determine what to do
    if command is None:
        try:
            cmdstring = settings.get('initial_command')
        except CommandParseError as err:
            sys.exit(err)
    elif command.subcommand in _SUBCOMMANDS:
        cmdstring = ' '.join(options.command)

    # set up and start interface
    UI(dbman, cmdstring)

    # run the exit hook
    exit_hook = settings.get_hook('exit')
    if exit_hook is not None:
        exit_hook()
1160479
def main():
    """"""
    
    # Find the current Boost source-directory in which this script is located.
    sourceDir = current_boost_dir()
    if sourceDir == None:
        sourceDir = ""
    
    # Prepare and run cmdline-parser.
    cmdlineParser = argparse.ArgumentParser(description="A generator-script for pre-processed Boost.MPL headers.")
    cmdlineParser.add_argument("-v", "--verbose", dest='verbose', action='store_true',
                               help="Be a little bit more verbose.")
    cmdlineParser.add_argument("-s", "--sequence-type", dest='seqType', choices=['variadic', 'numbered', 'both'],
                               default='both',
                               help="Only update pre-processed headers for the selected sequence types, "
                                    "either 'numbered' sequences, 'variadic' sequences or 'both' sequence "
                                    "types. (Default=both)")
    cmdlineParser.add_argument("--no-vector", dest='want_vector', action='store_false',
                               help="Do not update pre-processed headers for Boost.MPL Vector.")
    cmdlineParser.add_argument("--no-list", dest='want_list', action='store_false',
                               help="Do not update pre-processed headers for Boost.MPL List.")
    cmdlineParser.add_argument("--no-set", dest='want_set', action='store_false',
                               help="Do not update pre-processed headers for Boost.MPL Set.")
    cmdlineParser.add_argument("--no-map", dest='want_map', action='store_false',
                               help="Do not update pre-processed headers for Boost.MPL Map.")
    cmdlineParser.add_argument("--num-elements", dest='numElements', metavar="<num-elements>",
                               type=to_positive_multiple_of_10, default=100,
                               help="The maximal number of elements per container sequence. (Default=100)")
    cmdlineParser.add_argument(dest='sourceDir', metavar="<source-dir>", default=current_boost_dir(), nargs='?',
                               type=to_existing_absolute_path,
                               help="The source-directory of Boost. (Default=\"" + sourceDir + "\")")
    args = cmdlineParser.parse_args()

    # Some verbose debug output.
    if args.verbose:
        print "Arguments extracted from command-line:"
        print "  verbose          = ", args.verbose
        print "  source directory = ", args.sourceDir
        print "  num elements     = ", args.numElements
        print "  sequence type    = ", args.seqType
        print "  want: vector     = ", args.want_vector
        print "  want: list       = ", args.want_list
        print "  want: set        = ", args.want_set
        print "  want: map        = ", args.want_map

    # Verify that we received any source-directory.
    if args.sourceDir == None:
        print "You should specify a valid path to the Boost source-directory."
        sys.exit(0)

    # The directories for header- and source files of Boost.MPL.
    # NOTE: Assuming 'args.sourceDir' is the source-directory of the entire boost project.
    headerDir = os.path.join( args.sourceDir, "boost", "mpl" )
    sourceDir = os.path.join( args.sourceDir, "libs", "mpl", "preprocessed" )
    # Check that the header/source-directories exist.
    if not os.path.exists( headerDir ) or not os.path.exists( sourceDir ):
        # Maybe 'args.sourceDir' is not the source-directory of the entire boost project
        # but instead of the Boost.MPL git-directory, only?
        headerDir = os.path.join( args.sourceDir, "include", "boost", "mpl" )
        sourceDir = os.path.join( args.sourceDir, "preprocessed" )
        if not os.path.exists( headerDir ) or not os.path.exists( sourceDir ):
            cmdlineParser.print_usage()
            print "error: Cannot find Boost.MPL header/source files in given Boost source-directory!"
            sys.exit(0)

    # Some verbose debug output.
    if args.verbose:
        print "Chosen header-directory: ", headerDir
        print "Chosen source-directory: ", sourceDir

    # Create list of containers for which files shall be pre-processed.
    containers = []
    if args.want_vector:
        containers.append('vector')
    if args.want_list:
        containers.append('list')
    if args.want_set:
        containers.append('set')
    if args.want_map:
        containers.append('map')
    if containers == []:
        print "Nothing to do."
        print "(Why did you prevent generating pre-processed headers for all Boost.MPL container types?)"
        sys.exit(0)

    # Possibly fix the header-comments of input-files needed for pre-processing.
    if args.verbose:
        print "Checking if prior to pre-processing some input-files need fixing."
    needFixing = fixmpl.check_input_files(headerDir, sourceDir, containers, args.seqType, args.verbose)
    if needFixing:
        if args.verbose:
            print "Fixing of some input-files prior to pre-processing is needed."
            print "Will fix them now!"
        fixmpl.fix_input_files(headerDir, sourceDir, containers, args.seqType, args.verbose)

    # Some verbose debug output.
    if args.verbose:
        print "Containers for which to pre-process headers: ", containers

    # Create (additional) input files for generating pre-processed headers of numbered sequence MPL containers.
    if args.seqType == "both" or args.seqType == "numbered":
        create_input_for_numbered_sequences(headerDir, sourceDir, containers, args.numElements)
    # Modify settings for generating pre-processed headers of variadic sequence MPL containers.
    if args.seqType == "both" or args.seqType == "variadic":
        adjust_container_limits_for_variadic_sequences(headerDir, containers, args.numElements)

    # Generate MPL-preprocessed files.
    os.chdir( sourceDir )
    if args.seqType == "both" or args.seqType == "numbered":
        if args.want_vector:
            if args.verbose:
                print "Pre-process headers for Boost.MPL numbered vectors."
            os.system( "python " + os.path.join( sourceDir, "preprocess_vector.py" ) + " all " + args.sourceDir )
        if args.want_list:
            if args.verbose:
                print "Pre-process headers for Boost.MPL numbered lists."
            os.system( "python " + os.path.join( sourceDir, "preprocess_list.py" ) + " all " + args.sourceDir )
        if args.want_set:
            if args.verbose:
                print "Pre-process headers for Boost.MPL numbered sets."
            os.system( "python " + os.path.join( sourceDir, "preprocess_set.py" ) + " all " + args.sourceDir )
        if args.want_map:
            if args.verbose:
                print "Pre-process headers for Boost.MPL numbered maps."
            os.system( "python " + os.path.join( sourceDir, "preprocess_map.py" ) + " all " + args.sourceDir )
    if args.seqType == "both" or args.seqType == "variadic":
        if args.verbose:
            print "Pre-process headers for Boost.MPL variadic containers."
        os.system( "python " + os.path.join( sourceDir, "preprocess.py" ) + " all " + args.sourceDir )
738073
function main() {
  config = createConfig(process.argv.slice(2));

  if (config.options.help) {
    config.options.showHelp(NODE_DEBUG_MODE);
    process.exit();
  }

  if (config.options.version) {
    config.options.showVersion();
    process.exit();
  }

  process.on('SIGINT', function() {
     process.exit();
  });

  startInspectorProcess(function(error, result) {
    if (error) {
      console.error(formatNodeInspectorError(error));
      process.exit(1);
    }

    var url = result.address.url;
    var isUnixSocket = result.address.isUnixSocket;

    startDebuggedProcess(function(error) {
      if (error) {
        console.error('Cannot start %s: %s', config.subproc.script, error.message || error);
        process.exit(2);
      }

      openBrowserAndPrintInfo(url, isUnixSocket);
    });
  });
}
320421
def main(args=None):
    """"""

    Config.options, Config.args = parse(args)

    logger()

    if Config.options.aeidon or Config.options.fix:
        start_aeidon()
    else:
        start_srt()

    if Config.options.fix:
        sys.exit(0)

    if not Config.results:
        basenames = [os.path.basename(os.path.abspath(x)) for x in Config.args]
        print('Search of', basenames, 'returned no results.')

        # leave the terminal open long enough to read message
        if Config.options.gui:
            from time import sleep
            sleep(2)
532814
def main():
    """""""
    parser = argparse.ArgumentParser(description='Do something awesome')
    parser.add_argument('input_list', nargs='+',
                        type=str, default=sys.stdin)
    parser.add_argument('-o', '--outfile', nargs='?',
                        type=argparse.FileType('w'), default=sys.stdout)
    args = parser.parse_args()

    input_list = args.input_list
    print '\n'.join(get_ips_from_cidr_subnets(input_list))
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))
619113
def main():
    """"""
    from docopt import docopt
    args = docopt(__doc__)
    infile = args['INFILE']
    outfile = args['OUTFILE']
    i3extract(infile, outfile)
1057468
def main():
    """"""
    import sys

    output = []
    line = sys.stdin.readline()

    while line:
        line = line.strip("\n")
        output.append(transform(line))

        line = sys.stdin.readline()
    output.reverse()
    print("\n".join(output))