Any argument starting with "@" gets replaced with all values read from a text file.
    Text file arguments can be split by newline or by space.
    Values are added "as-is", as if they were specified in this order on the command line.
495418
def expand_file_arguments():
    
    new_args = []
    expanded = False
    for arg in sys.argv:
        if arg.startswith("@"):
            expanded = True
            with open(arg[1:],"r") as f:
                for line in f.readlines():
                    new_args += shlex.split(line)
        else:
            new_args.append(arg)
    if expanded:
        print("esptool.py %s" % (" ".join(new_args[1:])))
        sys.argv = new_args
920468
private String[] parseParams(String line) {
        //JENKINS-24870 CommandLine.getExecutable tries to fix file separators, so if the first param contains slashes, it can cause problems
        //Adding some placeholder instead of executable
        CommandLine cmdLine = CommandLine.parse("executable_placeholder " + line);
        String[] parsedArgs = cmdLine.getArguments();
        String[] args = new String[parsedArgs.length];
        if(parsedArgs.length > 0) {
            System.arraycopy(parsedArgs, 0, args, 0, parsedArgs.length);
        }
        return args;
    }
996796
@Configurable
  public void setArgs(String arg)
  {
    int i = 0;
    int len = arg.length();

    CharBuffer cb = new CharBuffer();
    
    while (i < len) {
      char ch;
      for (; i < len && Character.isWhitespace(ch = arg.charAt(i)); i++) {
      }

      if (len <= i)
        return;

      cb.clear();

      for (; i < len && ! Character.isWhitespace(ch = arg.charAt(i)); i++)
        cb.append(ch);

      addArg(cb.toString());
    }
  }
73229
def read_quoted
      logger.debug "  read quoted"
      skip_whitespace
      q = text[position] # quote character
      increase
      r = ""
      while !empty? && (c = text[position]) != q
        if c == "\\"
          increase
          c = text[position] unless empty?
          case c
          when 'r'
            c = "\r"
          when 'n'
            c = "\n"
          when '\''
            c = "\'"
          when '\\'
            c = "\\"
          else
            c = "\\" + c
          end
        end
        r << c
        increase
      end
      error("I expected #{q} but I got #{c}") if c != q
      increase
      logger.debug "  resulting string: '#{r}'"
      r
    end
566001
public static void main(String[] args) {
		if (args.length == 0) {
			System.out.println(
				"Usage: SplittingBAMIndex [splitting BAM indices...]\n\n"+

				"Writes a few statistics about each splitting BAM index.");
			return;
		}

		for (String arg : args) {
			final File f = new File(arg);
			if (f.isFile() && f.canRead()) {
				try {
					System.err.printf("%s:\n", f);
					final SplittingBAMIndex bi = new SplittingBAMIndex(f);
					if (bi.size() == 1) {
						System.err.printf("\t0 alignments\n" +
								"\tassociated BAM file size %d\n", bi.bamSize());
					} else {
						final long first = bi.first();
						final long last = bi.last();
						System.err.printf(
								"\t%d alignments\n" +
										"\tfirst is at %#06x in BGZF block at %#014x\n" +
										"\tlast  is at %#06x in BGZF block at %#014x\n" +
										"\tassociated BAM file size %d\n",
								bi.size(),
								first & 0xffff, first >>> 16,
								last & 0xffff, last >>> 16,
								bi.bamSize());
					}
				} catch (IOException e) {
					System.err.printf("Failed to read %s!\n", f);
					e.printStackTrace();
				}
			} else
				System.err.printf("%s does not look like a readable file!\n", f);
		}
	}
332771
public static void main(String [] args){
        if (args.length != 2){
            displayHelp();
            return;
        }
        
        //Read the input data
        try{
            String option = args[0];
            if (option.equalsIgnoreCase("-inputfile")){
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(new FileInputStream(args[1]), "UTF-8"));
                BufferedWriter out = new BufferedWriter(
                        new OutputStreamWriter(new FileOutputStream(args[1] + ".tkn") , "UTF-8"));

                String line = "";
                while ((line = in.readLine()) != null){                
                    out.write(PennTokenizer.tokenize(line));
                    out.write("\n");
                }
                
                in.close();
                out.close();
            }
            
            else if (option.equalsIgnoreCase("-inputdir")){
                System.out.println("Tokenize input");
                //segment only files ends with .sent
                File inputDir = new File(args[1]);
                File [] childrent = inputDir.listFiles(new FilenameFilter() {
                    public boolean accept(File dir, String name) {
                        return name.endsWith(".sent");
                    }
                });
                
                for (int i = 0; i < childrent.length; ++i){                    
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(new FileInputStream(childrent[i]), "UTF-8"));
                    BufferedWriter out = new BufferedWriter(
                            new OutputStreamWriter(new FileOutputStream(childrent[i] + ".tkn") , "UTF-8"));

                    String line = "";
                    while ((line = in.readLine()) != null){                
                        out.write(PennTokenizer.tokenize(line));
                        out.write("\n");
                    }

                    in.close();
                    out.close();    
                }
            }           
        } catch (Exception e){
            System.out.println("Error:" + e.getMessage());
        }
    }
267027
public static void main(final String[] args) {
        Switch about = new Switch("a", "about", "display about message");
        Switch help = new Switch("h", "help", "display help message");
        FileArgument fastaFile = new FileArgument("i", "fasta-file", "input FASTA file, default stdin", false);
        StringArgument outputFilePrefix = new StringArgument("p", "output-file-prefix", "output file prefix, default \"\"", false);
        StringArgument outputFileExtension = new StringArgument("x", "output-file-extension", "output file extension, default " + DEFAULT_OUTPUT_FILE_EXTENSION, false);
        FileArgument outputDirectory = new FileArgument("d", "output-directory", "output directory, default .", false);

        ArgumentList arguments = new ArgumentList(about, help, fastaFile, outputFilePrefix, outputFileExtension, outputDirectory);
        CommandLine commandLine = new CommandLine(args);

        SplitFasta splitFasta = null;
        try
        {
            CommandLineParser.parse(commandLine, arguments);
            if (about.wasFound()) {
                About.about(System.out);
                System.exit(0);
            }
            if (help.wasFound()) {
                Usage.usage(USAGE, null, commandLine, arguments, System.out);
                System.exit(0);
            }
            splitFasta = new SplitFasta(fastaFile.getValue(), outputFilePrefix.getValue(DEFAULT_OUTPUT_FILE_PREFIX), outputFileExtension.getValue(DEFAULT_OUTPUT_FILE_EXTENSION), outputDirectory.getValue(DEFAULT_OUTPUT_DIRECTORY));
        }
        catch (CommandLineParseException e) {
            Usage.usage(USAGE, e, commandLine, arguments, System.err);
            System.exit(-1);
        }
        try {
            System.exit(splitFasta.call());
        }
        catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
1163651
public static void main(String[] args) throws IOException {
    if (args.length == 0){
      usage();
    }
    int ai=0;
    try {
      String encoding = null;
      String dict = null;
      while (args[ai].startsWith("-")) {
        if (args[ai].equals("-encoding")) {
          ai++;
          if (ai < args.length) {
            encoding = args[ai++];
          }
          else {
            usage();
          }
        }
        else if (args[ai].equals("-dict")) {
          ai++;
          if (ai < args.length) {
            dict = args[ai++];
          }
          else {
            usage();
          }
        }
        else {
          System.err.println("Unknown option "+args[ai]);
          usage();
        }
      }
      File inFile = new File(args[ai++]);
      File outFile = new File(args[ai++]);
      int cutoff = 5;
      int iterations = 100;
      if (args.length > ai) {
        cutoff = Integer.parseInt(args[ai++]);
        iterations = Integer.parseInt(args[ai++]);
      }
      GISModel mod;
      if (dict != null) {
        System.err.println("Building dictionary");
        MutableDictionary mdict = new MutableDictionary(cutoff);
        DataStream data = new ch.epfl.bbp.shaded.opennlp.maxent.PlainTextByLineDataStream(new java.io.FileReader(inFile));
        while(data.hasNext()) {
          String tagStr = (String) data.nextToken();
          String[] tt = tagStr.split(" ");
          String[] words = new String[tt.length];
          for (int wi=0;wi<words.length;wi++) {
            words[wi] = tt[wi].substring(0,tt[wi].lastIndexOf('_'));
          }
          mdict.add(words,1,true);
        }
        System.out.println("Saving the dictionary");
        mdict.persist(new File(dict));
      }
      EventStream es;
      if (encoding == null) {
        if (dict == null) {
          es = new POSEventStream(new PlainTextByLineDataStream(new InputStreamReader(new FileInputStream(inFile))));
        }
        else {
          es = new POSEventStream(new PlainTextByLineDataStream(new InputStreamReader(new FileInputStream(inFile))), new Dictionary(dict));
        }
      }
      else {
        if (dict == null) {
          es = new POSEventStream(new PlainTextByLineDataStream(new InputStreamReader(new FileInputStream(inFile),encoding)));
        }
        else {
          es = new POSEventStream(new PlainTextByLineDataStream(new InputStreamReader(new FileInputStream(inFile),encoding)), new Dictionary(dict));
        }
      }
      mod = train(es, iterations, cutoff);
      System.out.println("Saving the model as: " + outFile);
      new SuffixSensitiveGISModelWriter(mod, outFile).persist();

    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
822940
def main():
    
    parser = argparse.ArgumentParser(description='Validate STIX Patterns.')
    parser.add_argument('-f', '--file',
                        help="Specify this arg to read patterns from a file.",
                        type=argparse.FileType("r"))
    args = parser.parse_args()

    pass_count = fail_count = 0

    # I tried using a generator (where each iteration would run raw_input()),
    # but raw_input()'s behavior seems to change when called from within a
    # generator: I only get one line, then the generator completes!  I don't
    # know why behavior changes...
    import functools
    if args.file:
        nextpattern = args.file.readline
    else:
        nextpattern = functools.partial(six.moves.input, "Enter a pattern to validate: ")

    try:
        while True:
            pattern = nextpattern()
            if not pattern:
                break
            tests_passed, err_strings = validate(pattern, True)

            if tests_passed:
                print("\nPASS: %s" % pattern)
                pass_count += 1

            else:
                for err in err_strings:
                    print(err, '\n')
                fail_count += 1
    except (EOFError, KeyboardInterrupt):
        pass
    finally:
        if args.file:
            args.file.close()

    print("\nPASSED:", pass_count, " patterns")
    print("FAILED:", fail_count, " patterns")
1349956
def split_args(line):
    
    lex = shlex.shlex(line, posix=True)
    lex.whitespace_split = True
    lex.commenters = ''
    res = []
    try:
        while True:
            res.append(next(lex))
    except ValueError:  # No closing quotation
        pass
    except StopIteration:  # End of loop
        pass
    if lex.token:
        res.append(lex.token)
    return res
121875
public static void main(final String[] args) {
        Switch about = new Switch("a", "about", "display about message");
        Switch help = new Switch("h", "help", "display help message");
        FileArgument firstFastqFile = new FileArgument("1", "first-fastq-file", "first FASTQ input file", true);
        FileArgument secondFastqFile = new FileArgument("2", "second-fastq-file", "second FASTQ input file", true);
        FileArgument ssakeFile = new FileArgument("o", "ssake-file", "output SSAKE file, default stdout", false);
        FileArgument unpairedFile = new FileArgument("u", "unpaired-file", "write unpaired read names to file", false);
        IntegerArgument insertSize = new IntegerArgument("s", "insert-size", "insert size, must be at least zero, default " + DEFAULT_INSERT_SIZE, false);

        ArgumentList arguments = new ArgumentList(about, help, firstFastqFile, secondFastqFile, ssakeFile, insertSize, unpairedFile);
        CommandLine commandLine = new CommandLine(args);

        FastqToSsake fastqToSsake = null;
        try
        {
            CommandLineParser.parse(commandLine, arguments);
            if (about.wasFound()) {
                About.about(System.out);
                System.exit(0);
            }
            if (help.wasFound()) {
                Usage.usage(USAGE, null, commandLine, arguments, System.out);
                System.exit(0);
            }
            fastqToSsake = new FastqToSsake(firstFastqFile.getValue(), secondFastqFile.getValue(), ssakeFile.getValue(), insertSize.getValue(DEFAULT_INSERT_SIZE), unpairedFile.getValue());
        }
        catch (CommandLineParseException e) {
            if (about.wasFound()) {
                About.about(System.out);
                System.exit(0);
            }
            if (help.wasFound()) {
                Usage.usage(USAGE, null, commandLine, arguments, System.out);
                System.exit(0);
            }
            Usage.usage(USAGE, e, commandLine, arguments, System.err);
            System.exit(-1);
        }
        try {
            System.exit(fastqToSsake.call());
        }
        catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
406998
def argument(value, options = {})
      return unless @shell.applicable?(options)
      value = value.to_s
      if @shell.requires_escaping?(value)
        value = @shell.escape_value(value)
      end
      @command << ' ' << value
      @last_arg = :argument
    end
1367410
def line_to_args(self, line):
        
        # Note: using shlex.split causes quoted substrings to stay together.
        args = shlex.split(line)
        self.redirect_filename = ''
        self.redirect_dev = None
        redirect_index = -1
        if '>' in args:
            redirect_index = args.index('>')
        elif '>>' in args:
            redirect_index = args.index('>>')
        if redirect_index >= 0:
            if redirect_index + 1 >= len(args):
                raise ShellError("> requires a filename")
            self.redirect_filename = resolve_path(args[redirect_index + 1])
            rmode = auto(get_mode, os.path.dirname(self.redirect_filename))
            if not mode_isdir(rmode):
                raise ShellError("Unable to redirect to '%s', directory doesn't exist" %
                                 self.redirect_filename)
            if args[redirect_index] == '>':
                self.redirect_mode = 'w'
                if DEBUG:
                    print('Redirecting (write) to', self.redirect_filename)
            else:
                self.redirect_mode = 'a'
                if DEBUG:
                    print('Redirecting (append) to', self.redirect_filename)
            self.redirect_dev, self.redirect_filename = get_dev_and_path(self.redirect_filename)
            try:
                if self.redirect_dev is None:
                    self.stdout = SmartFile(open(self.redirect_filename, self.redirect_mode))
                else:
                    # Redirecting to a remote device. We collect the results locally
                    # and copy them to the remote device at the end of the command.
                    self.stdout = SmartFile(tempfile.TemporaryFile(mode='w+'))
            except OSError as err:
                raise ShellError(err)

            del args[redirect_index + 1]
            del args[redirect_index]
        curr_cmd, _, _ = self.parseline(self.lastcmd)
        parser = self.create_argparser(curr_cmd)
        if parser:
            args = parser.parse_args(args)
        return args
58722
function (file) {
  var regex = new RegExp(/(\/\*\! \@\{target\:\s*?).*?([^"]*?)(\} \*\/)/gi),
      replaceRegex = '',
      matches = '',
      match = '',
      parts = '',
      replace = '',
      endString = '',
      files = {},
      cut = '',
      start = 0,
      end = 0,
      result = {};

  matches = file.match(regex);

  for (var i in matches) {
    match = matches[i];
    regex = new RegExp(/(\/\*\! \@\{target\:\s*?).*?([^"]*?)(\} \*\/)/gi)

    parts = regex.exec(match);
    endString = '/*! {target:' + parts[2] + '}@ */'

    start = file.indexOf(parts[0]);
    end = file.indexOf(endString) + endString.length;

    cut = file.slice(start, end);
    file = file.slice(0, start - 1) + file.slice(end + 1);

    cut = cut.replace(parts[0], '').replace(endString, '');

    if (files[parts[2]]) {
      files[parts[2]].push(cut);
    }
    else {
      files[parts[2]] = [];
      files[parts[2]].push(cut);
    }
  }

  result.file = file;
  result.files = files;

  return result;
}
1063766
@Override
	public String parse(String argument) throws CommandLineException {

		File file = new File(argument);

		try {
			Assert.isTrue(file.exists(), "File '" + file + "' does not exist");
			Assert.isFalse(file.isDirectory(), "File '" + file + "' is a directory");
			Assert.isTrue(file.canRead(), "File '" + file + "' cannot be read");
		}
		catch (IllegalArgumentException e) {
			throw new CommandLineException(e.getMessage());
		}

		return file.getAbsolutePath();
	}
634053
def parse_options(arguments=None):
    
    if arguments is None:
        arguments = sys.argv[1:]
    if isinstance(arguments, str):
        arguments = arguments.split()
    if isinstance(arguments, argparse.Namespace):
        return arguments
    parser = create_args_parser()
    args = parser.parse_args(arguments)
    # pprint(args.__dict__)

    args.dialect = args.dialect.lower()
    if args.dialect not in ['lisp', 'newlisp', 'clojure', 'scheme', 'all', '']:
        parser.error("`{0}' is not a recognized dialect".format(args.dialect))

    args.backup_dir = os.path.expanduser(args.backup_dir)
    if not os.path.exists(args.backup_dir):
        parser.error("Directory `{0}' does not exist".format(args.backup_dir))

    if len(args.files) > 1 and args.output_file:
        parser.error('Cannot use the -o flag when more than one file is specified')

    if not args.files:
        # Indentation from standard input
        if args.modify and not args.output_file:
            args.modify = False
        args.backup = False
        args.warning = False

    if args.output_diff:
        # If someone requests a diff we assume he/she doesn't want the file to be
        # modified
        args.modify = False

    return args
313146
long parseDir(final String line, final String path) throws IOException {
        // read from the end of the line to find the last numeric
        // character on the line, then continue until we find the first
        // non-numeric character, and everything between that and the last
        // numeric character inclusive is our free space bytes count
        int bytesStart = 0;
        int bytesEnd = 0;
        int j = line.length() - 1;
        innerLoop1: while (j >= 0) {
            final char c = line.charAt(j);
            if (Character.isDigit(c)) {
                // found the last numeric character, this is the end of
                // the free space bytes count
                bytesEnd = j + 1;
                break innerLoop1;
            }
            j--;
        }
        innerLoop2: while (j >= 0) {
            final char c = line.charAt(j);
            if (!Character.isDigit(c) && c != ',' && c != '.') {
                // found the next non-numeric character, this is the
                // beginning of the free space bytes count
                bytesStart = j + 1;
                break innerLoop2;
            }
            j--;
        }
        if (j < 0) {
            throw new IOException("Command line 'dir /-c' did not return valid info " + "for path '" + path + "'");
        }

        // remove commas and dots in the bytes count
        final StringBuilder buf = new StringBuilder(line.substring(bytesStart, bytesEnd));
        for (int k = 0; k < buf.length(); k++) {
            if (buf.charAt(k) == ',' || buf.charAt(k) == '.') {
                buf.deleteCharAt(k--);
            }
        }
        return parseBytes(buf.toString(), path);
    }