Example usage for java.lang String equals

List of usage examples for java.lang String equals

Introduction

In this page you can find the example usage for java.lang String equals.

Prototype

public boolean equals(Object anObject) 

Source Link

Document

Compares this string to the specified object.

Usage

From source file:asl.seedscan.DQAWeb.java

public static void main(String args[]) {
    db = new MetricDatabase("", "", "");
    findConsoleHandler();//ww w.  j  a  v  a 2s.  co m
    consoleHandler.setLevel(Level.ALL);
    Logger.getLogger("").setLevel(Level.CONFIG);

    // Default locations of config and schema files
    File configFile = new File("dqaweb-config.xml");
    File schemaFile = new File("schemas/DQAWebConfig.xsd");
    boolean parseConfig = true;
    boolean testMode = false;

    ArrayList<File> schemaFiles = new ArrayList<File>();
    schemaFiles.add(schemaFile);
    // ==== Command Line Parsing ====
    Options options = new Options();
    Option opConfigFile = new Option("c", "config-file", true,
            "The config file to use for seedscan. XML format according to SeedScanConfig.xsd.");
    Option opSchemaFile = new Option("s", "schema-file", true,
            "The schame file which should be used to verify the config file format. ");
    Option opTest = new Option("t", "test", false, "Run in test console mode rather than as a servlet.");

    OptionGroup ogConfig = new OptionGroup();
    ogConfig.addOption(opConfigFile);

    OptionGroup ogSchema = new OptionGroup();
    ogConfig.addOption(opSchemaFile);

    OptionGroup ogTest = new OptionGroup();
    ogTest.addOption(opTest);

    options.addOptionGroup(ogConfig);
    options.addOptionGroup(ogSchema);
    options.addOptionGroup(ogTest);

    PosixParser optParser = new PosixParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = optParser.parse(options, args, true);
    } catch (org.apache.commons.cli.ParseException e) {
        logger.severe("Error while parsing command-line arguments.");
        System.exit(1);
    }

    Option opt;
    Iterator iter = cmdLine.iterator();
    while (iter.hasNext()) {
        opt = (Option) iter.next();

        if (opt.getOpt().equals("c")) {
            configFile = new File(opt.getValue());
        } else if (opt.getOpt().equals("s")) {
            schemaFile = new File(opt.getValue());
        } else if (opt.getOpt().equals("t")) {
            testMode = true;
        }
    }
    String query = "";
    System.out.println("Entering Test Mode");
    System.out.println("Enter a query string to view results or type \"help\" for example query strings");
    InputStreamReader input = new InputStreamReader(System.in);
    BufferedReader reader = new BufferedReader(input);
    String result = "";

    while (testMode == true) {
        try {

            System.out.printf("Query: ");
            query = reader.readLine();
            if (query.equals("exit")) {
                testMode = false;
            } else if (query.equals("help")) {
                System.out.println("Need to add some help for people"); //TODO
            } else {
                result = processCommand(query);
            }
            System.out.println(result);
        } catch (IOException err) {
            System.err.println("Error reading line, in DQAWeb.java");
        }
    }
    System.err.printf("DONE.\n");
}

From source file:it.units.malelab.ege.MappingPropertiesExperimenter.java

public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {
    final int n = 10000;
    final int nDist = 10000;
    //prepare problems and methods
    List<String> problems = Lists.newArrayList("bool-parity5", "bool-mopm3", "sr-keijzer6", "sr-nguyen7",
            "sr-pagie1", "sr-vladislavleva4", "other-klandscapes3", "other-klandscapes7", "other-text");
    List<String> mappers = new ArrayList<>();
    for (int gs : new int[] { 64, 128, 256, 512, 1024 }) {
        mappers.add("ge-" + gs + "-2");
        mappers.add("ge-" + gs + "-4");
        mappers.add("ge-" + gs + "-8");
        mappers.add("ge-" + gs + "-12");
        mappers.add("pige-" + gs + "-4");
        mappers.add("pige-" + gs + "-8");
        mappers.add("pige-" + gs + "-16");
        mappers.add("pige-" + gs + "-24");
        mappers.add("hge-" + gs + "-0");
        mappers.add("whge-" + gs + "-2");
        mappers.add("whge-" + gs + "-3");
        mappers.add("whge-" + gs + "-5");
    }/*from w ww .j  av a 2  s  .  c  om*/
    mappers.add("sge-0-5");
    mappers.add("sge-0-6");
    mappers.add("sge-0-7");
    mappers.add("sge-0-8");
    mappers.clear();
    mappers.addAll(Lists.newArrayList("ge-1024-8", "pige-1024-16", "hge-1024-0", "whge-1024-3", "sge-0-6"));
    PrintStream filePrintStream = null;
    if (args.length > 0) {
        filePrintStream = new PrintStream(args[0]);
    } else {
        filePrintStream = System.out;
    }
    filePrintStream.printf("problem;mapper;genotypeSize;param;property;value%n");
    //prepare distances
    Distance<Node<String>> phenotypeDistance = new CachedDistance<>(new LeavesEdit<String>());
    Distance<Sequence> genotypeDistance = new CachedDistance<>(new Hamming());
    //iterate
    for (String problemName : problems) {
        for (String mapperName : mappers) {
            System.out.printf("%20.20s, %20.20s", problemName, mapperName);
            //build problem
            Problem<String, NumericFitness> problem = null;
            if (problemName.equals("bool-parity5")) {
                problem = new Parity(5);
            } else if (problemName.equals("bool-mopm3")) {
                problem = new MultipleOutputParallelMultiplier(3);
            } else if (problemName.equals("sr-keijzer6")) {
                problem = new HarmonicCurve();
            } else if (problemName.equals("sr-nguyen7")) {
                problem = new Nguyen7(1);
            } else if (problemName.equals("sr-pagie1")) {
                problem = new Pagie1();
            } else if (problemName.equals("sr-vladislavleva4")) {
                problem = new Vladislavleva4(1);
            } else if (problemName.equals("other-klandscapes3")) {
                problem = new KLandscapes(3);
            } else if (problemName.equals("other-klandscapes7")) {
                problem = new KLandscapes(7);
            } else if (problemName.equals("other-text")) {
                problem = new Text();
            }
            //build configuration and evolver
            Mapper mapper = null;
            int genotypeSize = Integer.parseInt(mapperName.split("-")[1]);
            int mapperMainParam = Integer.parseInt(mapperName.split("-")[2]);
            if (mapperName.split("-")[0].equals("ge")) {
                mapper = new StandardGEMapper<>(mapperMainParam, 1, problem.getGrammar());
            } else if (mapperName.split("-")[0].equals("pige")) {
                mapper = new PiGEMapper<>(mapperMainParam, 1, problem.getGrammar());
            } else if (mapperName.split("-")[0].equals("sge")) {
                mapper = new SGEMapper<>(mapperMainParam, problem.getGrammar());
            } else if (mapperName.split("-")[0].equals("hge")) {
                mapper = new HierarchicalMapper<>(problem.getGrammar());
            } else if (mapperName.split("-")[0].equals("whge")) {
                mapper = new WeightedHierarchicalMapper<>(mapperMainParam, false, true, problem.getGrammar());
            }
            //prepare things
            Random random = new Random(1);
            Set<Sequence> genotypes = new LinkedHashSet<>(n);
            //build genotypes
            if (mapperName.split("-")[0].equals("sge")) {
                SGEGenotypeFactory<String> factory = new SGEGenotypeFactory<>((SGEMapper) mapper);
                while (genotypes.size() < n) {
                    genotypes.add(factory.build(random));
                }
                genotypeSize = factory.getBitSize();
            } else {
                BitsGenotypeFactory factory = new BitsGenotypeFactory(genotypeSize);
                while (genotypes.size() < n) {
                    genotypes.add(factory.build(random));
                }
            }
            //build and fill map
            Multimap<Node<String>, Sequence> multimap = HashMultimap.create();
            int progress = 0;
            for (Sequence genotype : genotypes) {
                Node<String> phenotype;
                try {
                    if (mapperName.split("-")[0].equals("sge")) {
                        phenotype = mapper.map((SGEGenotype<String>) genotype, new HashMap<>());
                    } else {
                        phenotype = mapper.map((BitsGenotype) genotype, new HashMap<>());
                    }
                } catch (MappingException e) {
                    phenotype = Node.EMPTY_TREE;
                }
                multimap.put(phenotype, genotype);
                progress = progress + 1;
                if (progress % Math.round(n / 10) == 0) {
                    System.out.print(".");
                }
            }
            System.out.println();
            //compute distances
            List<Pair<Double, Double>> allDistances = new ArrayList<>();
            List<Pair<Double, Double>> allValidDistances = new ArrayList<>();
            Multimap<Node<String>, Double> genotypeDistances = ArrayListMultimap.create();
            for (Node<String> phenotype : multimap.keySet()) {
                for (Sequence genotype1 : multimap.get(phenotype)) {
                    for (Sequence genotype2 : multimap.get(phenotype)) {
                        double gDistance = genotypeDistance.d(genotype1, genotype2);
                        genotypeDistances.put(phenotype, gDistance);
                        if (genotypeDistances.get(phenotype).size() > nDist) {
                            break;
                        }
                    }
                    if (genotypeDistances.get(phenotype).size() > nDist) {
                        break;
                    }
                }
            }
            List<Map.Entry<Node<String>, Sequence>> entries = new ArrayList<>(multimap.entries());
            Collections.shuffle(entries, random);
            for (Map.Entry<Node<String>, Sequence> entry1 : entries) {
                for (Map.Entry<Node<String>, Sequence> entry2 : entries) {
                    double gDistance = genotypeDistance.d(entry1.getValue(), entry2.getValue());
                    double pDistance = phenotypeDistance.d(entry1.getKey(), entry2.getKey());
                    allDistances.add(new Pair<>(gDistance, pDistance));
                    if (!Node.EMPTY_TREE.equals(entry1.getKey()) && !Node.EMPTY_TREE.equals(entry2.getKey())) {
                        allValidDistances.add(new Pair<>(gDistance, pDistance));
                    }
                    if (allDistances.size() > nDist) {
                        break;
                    }
                }
                if (allDistances.size() > nDist) {
                    break;
                }
            }
            //compute properties
            double invalidity = (double) multimap.get(Node.EMPTY_TREE).size() / (double) genotypes.size();
            double redundancy = 1 - (double) multimap.keySet().size() / (double) genotypes.size();
            double validRedundancy = redundancy;
            if (multimap.keySet().contains(Node.EMPTY_TREE)) {
                validRedundancy = 1 - ((double) multimap.keySet().size() - 1d)
                        / (double) (genotypes.size() - multimap.get(Node.EMPTY_TREE).size());
            }
            double locality = Utils.pearsonCorrelation(allDistances);
            double validLocality = Utils.pearsonCorrelation(allValidDistances);
            double[] sizes = new double[multimap.keySet().size()];
            double[] meanGenotypeDistances = new double[multimap.keySet().size()];
            int invalidIndex = -1;
            int c = 0;
            for (Node<String> phenotype : multimap.keySet()) {
                if (Node.EMPTY_TREE.equals(phenotype)) {
                    invalidIndex = c;
                }
                sizes[c] = multimap.get(phenotype).size();
                double[] distances = new double[genotypeDistances.get(phenotype).size()];
                int k = 0;
                for (Double distance : genotypeDistances.get(phenotype)) {
                    distances[k] = distance;
                    k = k + 1;
                }
                meanGenotypeDistances[c] = StatUtils.mean(distances);
                c = c + 1;
            }
            double nonUniformity = Math.sqrt(StatUtils.variance(sizes)) / StatUtils.mean(sizes);
            double nonSynonymousity = StatUtils.mean(meanGenotypeDistances)
                    / StatUtils.mean(firsts(allDistances));
            double validNonUniformity = nonUniformity;
            double validNonSynonymousity = nonSynonymousity;
            if (invalidIndex != -1) {
                double[] validSizes = new double[multimap.keySet().size() - 1];
                double[] validMeanGenotypeDistances = new double[multimap.keySet().size() - 1];
                if (invalidIndex > 0) {
                    System.arraycopy(sizes, 0, validSizes, 0, invalidIndex);
                    System.arraycopy(meanGenotypeDistances, 0, validMeanGenotypeDistances, 0, invalidIndex);
                }
                System.arraycopy(sizes, invalidIndex + 1, validSizes, invalidIndex,
                        sizes.length - invalidIndex - 1);
                System.arraycopy(meanGenotypeDistances, invalidIndex + 1, validMeanGenotypeDistances,
                        invalidIndex, meanGenotypeDistances.length - invalidIndex - 1);
                validNonUniformity = Math.sqrt(StatUtils.variance(validSizes)) / StatUtils.mean(validSizes);
                validNonSynonymousity = StatUtils.mean(validMeanGenotypeDistances)
                        / StatUtils.mean(firsts(allValidDistances));
            }
            //compute locality
            filePrintStream.printf("%s;%s;%d;%d;invalidity;%f %n", problemName, mapperName.split("-")[0],
                    genotypeSize, mapperMainParam, invalidity);
            filePrintStream.printf("%s;%s;%d;%d;redundancy;%f %n", problemName, mapperName.split("-")[0],
                    genotypeSize, mapperMainParam, redundancy);
            filePrintStream.printf("%s;%s;%d;%d;validRedundancy;%f %n", problemName, mapperName.split("-")[0],
                    genotypeSize, mapperMainParam, validRedundancy);
            filePrintStream.printf("%s;%s;%d;%d;locality;%f %n", problemName, mapperName.split("-")[0],
                    genotypeSize, mapperMainParam, locality);
            filePrintStream.printf("%s;%s;%d;%d;validLLocality;%f %n", problemName, mapperName.split("-")[0],
                    genotypeSize, mapperMainParam, validLocality);
            filePrintStream.printf("%s;%s;%d;%d;nonUniformity;%f %n", problemName, mapperName.split("-")[0],
                    genotypeSize, mapperMainParam, nonUniformity);
            filePrintStream.printf("%s;%s;%d;%d;validNonUniformity;%f %n", problemName,
                    mapperName.split("-")[0], genotypeSize, mapperMainParam, validNonUniformity);
            filePrintStream.printf("%s;%s;%d;%d;nonSynonymousity;%f %n", problemName, mapperName.split("-")[0],
                    genotypeSize, mapperMainParam, nonSynonymousity);
            filePrintStream.printf("%s;%s;%d;%d;validNonSynonymousity;%f %n", problemName,
                    mapperName.split("-")[0], genotypeSize, mapperMainParam, validNonSynonymousity);
        }
    }
    if (filePrintStream != null) {
        filePrintStream.close();
    }
}

From source file:com.admc.jcreole.JCreole.java

/**
 * Run this method with no parameters to see syntax requirements and the
 * available parameters./*from  w  ww  .j a  va  2  s .c  om*/
 *
 * N.b. do not call this method from a persistent program, because it
 * may call System.exit!
 * <p>
 * Any long-running program should use the lower-level methods in this
 * class instead (or directly use CreoleParser and CreoleScanner
 * instances).
 * </p> <p>
 * This method executes with all JCreole privileges.
 * </p> <p>
 * This method sets up the following htmlExpander mappings (therefore you
 * can reference these in both Creole and boilerplate text).<p>
 * <ul>
 *   <li>sys|*: mappings for Java system properties
 *   <li>isoDateTime
 *   <li>isoDate
 *   <li>pageTitle: Value derived from the specified Creole file name.
 * </ul>
 *
 * @throws IOException for any I/O problem that makes it impossible to
 *         satisfy the request.
 * @throws CreoleParseException
 *         if can not generate output, or if the run generates 0 output.
 *         If the problem is due to input formatting, in most cases you
 *         will get a CreoleParseException, which is a RuntimException, and
 *         CreoleParseException has getters for locations in the source
 *         data (though they will be offset for \r's in the provided
 *         Creole source, if any).
 */
public static void main(String[] sa) throws IOException {
    String bpResPath = null;
    String bpFsPath = null;
    String outPath = null;
    String inPath = null;
    boolean debugs = false;
    boolean troubleshoot = false;
    boolean noBp = false;
    int param = -1;
    try {
        while (++param < sa.length) {
            if (sa[param].equals("-d")) {
                debugs = true;
                continue;
            }
            if (sa[param].equals("-t")) {
                troubleshoot = true;
                continue;
            }
            if (sa[param].equals("-r") && param + 1 < sa.length) {
                if (bpFsPath != null || bpResPath != null || noBp)
                    throw new IllegalArgumentException();
                bpResPath = sa[++param];
                continue;
            }
            if (sa[param].equals("-f") && param + 1 < sa.length) {
                if (bpResPath != null || bpFsPath != null || noBp)
                    throw new IllegalArgumentException();
                bpFsPath = sa[++param];
                continue;
            }
            if (sa[param].equals("-")) {
                if (noBp || bpFsPath != null || bpResPath != null)
                    throw new IllegalArgumentException();
                noBp = true;
                continue;
            }
            if (sa[param].equals("-o") && param + 1 < sa.length) {
                if (outPath != null)
                    throw new IllegalArgumentException();
                outPath = sa[++param];
                continue;
            }
            if (inPath != null)
                throw new IllegalArgumentException();
            inPath = sa[param];
        }
        if (inPath == null)
            throw new IllegalArgumentException();
    } catch (IllegalArgumentException iae) {
        System.err.println(SYNTAX_MSG);
        System.exit(1);
    }
    if (!noBp && bpResPath == null && bpFsPath == null)
        bpResPath = DEFAULT_BP_RES_PATH;
    String rawBoilerPlate = null;
    if (bpResPath != null) {
        if (bpResPath.length() > 0 && bpResPath.charAt(0) == '/')
            // Classloader lookups are ALWAYS relative to CLASSPATH roots,
            // and will abort if you specify a beginning "/".
            bpResPath = bpResPath.substring(1);
        InputStream iStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(bpResPath);
        if (iStream == null)
            throw new IOException("Boilerplate inaccessible: " + bpResPath);
        rawBoilerPlate = IOUtil.toString(iStream);
    } else if (bpFsPath != null) {
        rawBoilerPlate = IOUtil.toString(new File(bpFsPath));
    }
    String creoleResPath = (inPath.length() > 0 && inPath.charAt(0) == '/') ? inPath.substring(1) : inPath;
    // Classloader lookups are ALWAYS relative to CLASSPATH roots,
    // and will abort if you specify a beginning "/".
    InputStream creoleStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(creoleResPath);
    File inFile = (creoleStream == null) ? new File(inPath) : null;
    JCreole jCreole = (rawBoilerPlate == null) ? (new JCreole()) : (new JCreole(rawBoilerPlate));
    if (debugs) {
        jCreole.setInterWikiMapper(new InterWikiMapper() {
            // This InterWikiMapper is just for prototyping.
            // Use wiki name of "nil" to force lookup failure for path.
            // Use wiki page of "nil" to force lookup failure for label.
            public String toPath(String wikiName, String wikiPage) {
                if (wikiName != null && wikiName.equals("nil"))
                    return null;
                return "{WIKI-LINK to: " + wikiName + '|' + wikiPage + '}';
            }

            public String toLabel(String wikiName, String wikiPage) {
                if (wikiPage == null)
                    throw new RuntimeException("Null page name sent to InterWikiMapper");
                if (wikiPage.equals("nil"))
                    return null;
                return "{LABEL for: " + wikiName + '|' + wikiPage + '}';
            }
        });
        Expander creoleExpander = new Expander(Expander.PairedDelims.RECTANGULAR);
        creoleExpander.put("testMacro",
                "\n\n<<prettyPrint>>\n{{{\n" + "!/bin/bash -p\n\ncp /etc/inittab /tmp\n}}}\n");
        jCreole.setCreoleExpander(creoleExpander);
    }
    jCreole.setPrivileges(EnumSet.allOf(JCreolePrivilege.class));
    Expander exp = jCreole.getHtmlExpander();
    Date now = new Date();
    exp.putAll("sys", System.getProperties(), false);
    exp.put("isoDateTime", isoDateTimeFormatter.format(now), false);
    exp.put("isoDate", isoDateFormatter.format(now), false);
    exp.put("pageTitle",
            (inFile == null) ? creoleResPath.replaceFirst("[.][^.]*$", "").replaceFirst(".*[/\\\\.]", "")
                    : inFile.getName().replaceFirst("[.][^.]*$", ""));
    if (troubleshoot) {
        // We don't write any HMTL output here.
        // Goal is just to output diagnostics.
        StringBuilder builder = (creoleStream == null) ? IOUtil.toStringBuilder(inFile)
                : IOUtil.toStringBuilder(creoleStream);
        int newlineCount = 0;
        int lastOffset = -1;
        int offset = builder.indexOf("\n");
        for (; offset >= 0; offset = builder.indexOf("\n", offset + 1)) {
            lastOffset = offset;
            newlineCount++;
        }
        // Accommodate input files with no terminating newline:
        if (builder.length() > lastOffset + 1)
            newlineCount++;
        System.out.println("Input lines:  " + newlineCount);
        Exception lastException = null;
        while (true) {
            try {
                jCreole.parseCreole(builder);
                break;
            } catch (Exception e) {
                lastException = e;
            }
            if (builder.charAt(builder.length() - 1) == '\n')
                builder.setLength(builder.length() - 1);
            offset = builder.lastIndexOf("\n");
            if (offset < 1)
                break;
            newlineCount--;
            builder.setLength(builder.lastIndexOf("\n"));
        }
        System.out.println((lastException == null) ? "Input validates"
                : String.format("Error around input line %d:  %s", newlineCount, lastException.getMessage()));
        return;
    }
    String generatedHtml = (creoleStream == null) ? jCreole.parseCreole(inFile)
            : jCreole.parseCreole(IOUtil.toStringBuilder(creoleStream));
    String html = jCreole.postProcess(generatedHtml, SystemUtils.LINE_SEPARATOR);
    if (outPath == null) {
        System.out.print(html);
    } else {
        FileUtils.writeStringToFile(new File(outPath), html, "UTF-8");
    }
}

From source file:com.quattroresearch.helm.HlConfigEntry.java

public static void main(String[] args) throws Exception {
    CommandLineParser cmdline_parser = new DefaultParser();
    Options options = new Options();
    String usage = "Usage: -i <input_file> -o <output_file> -c <highlight_config_file>";
    String errorLine;// w w  w .ja va2s.  c om

    if (args.length < 6) {
        log(usage);
        return;
    }

    options.addOption("c", true, "config file containing highlighting options");
    options.addOption("i", true, "input file containing HELM string");
    options.addOption("o", true, "output file containing highlighted HELM string");

    try { // parse the command line arguments
        CommandLine cmd_line = cmdline_parser.parse(options, args);
        String cfilename = cmd_line.getOptionValue("c");
        log("Cfg filename=" + cfilename);
        String ofilename = cmd_line.getOptionValue("o");
        log("Output filename=" + ofilename);
        String ifilename = cmd_line.getOptionValue("i");
        log("Input filename=" + ifilename);
        if (cfilename == null || ofilename == null || ifilename == null || cfilename.equals("")
                || ifilename.equals("") || ofilename.equals("")) {
            log(usage);
            return;
        }
        if (!(errorLine = setupHlConfigEntries(cfilename)).equals("")) { // in case of error, a non-empty string will be returned
            log("Bad entry in " + cfilename + ": '" + errorLine
                    + "': missing category, keyword or value, exiting..."); // error
            return;
        }
        handleInputOutputFiles(ifilename, ofilename);
    } catch (IOException e) {
        System.out.println(e);
    }
}

From source file:CreateNewType.java

public static void main(String[] args) {
    String url = "jdbc:mySubprotocol:myDataSource";

    Connection con;/* w ww .  j  a  va2 s  .co  m*/
    Statement stmt;
    try {
        Class.forName("myDriver.ClassName");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {
        con = DriverManager.getConnection(url, "myLogin", "myPassword");

        stmt = con.createStatement();

        String typeToCreate = null;
        String prompt = "Enter 's' to create a structured type " + "or 'd' to create a distinct type\n"
                + "and hit Return: ";
        do {
            typeToCreate = getInput(prompt) + " ";
            typeToCreate = typeToCreate.toLowerCase().substring(0, 1);
        } while (!(typeToCreate.equals("s") || typeToCreate.equals("d")));

        Vector dataTypes = getDataTypes(con, typeToCreate);

        String typeName;
        String attributeName;
        String sqlType;
        prompt = "Enter the new type name and hit Return: ";
        typeName = getInput(prompt);
        String createTypeString = "create type " + typeName;
        if (typeToCreate.equals("d"))
            createTypeString += " as ";
        else
            createTypeString += " (";

        String commaAndSpace = ", ";
        boolean firstTime = true;
        while (true) {
            System.out.println("");
            prompt = "Enter an attribute name " + "(or nothing when finished) \nand hit Return: ";
            attributeName = getInput(prompt);
            if (firstTime) {
                if (attributeName.length() == 0) {
                    System.out.print("Need at least one attribute;");
                    System.out.println(" please try again");
                    continue;
                } else {
                    createTypeString += attributeName + " ";
                    firstTime = false;
                }
            } else if (attributeName.length() == 0) {
                break;
            } else {
                createTypeString += commaAndSpace + attributeName + " ";
            }

            String localTypeName = null;
            String paramString = "";
            while (true) {
                System.out.println("");
                System.out.println("LIST OF TYPES YOU MAY USE:  ");
                boolean firstPrinted = true;
                int length = 0;
                for (int i = 0; i < dataTypes.size(); i++) {
                    DataType dataType = (DataType) dataTypes.get(i);
                    if (!dataType.needsToBeSet()) {
                        if (!firstPrinted)
                            System.out.print(commaAndSpace);
                        else
                            firstPrinted = false;
                        System.out.print(dataType.getSQLType());
                        length += dataType.getSQLType().length();
                        if (length > 50) {
                            System.out.println("");
                            length = 0;
                            firstPrinted = true;
                        }
                    }
                }
                System.out.println("");

                int index;
                prompt = "Enter an attribute type " + "from the list and hit Return:  ";
                sqlType = getInput(prompt);
                for (index = 0; index < dataTypes.size(); index++) {
                    DataType dataType = (DataType) dataTypes.get(index);
                    if (dataType.getSQLType().equalsIgnoreCase(sqlType) && !dataType.needsToBeSet()) {
                        break;
                    }
                }

                localTypeName = null;
                paramString = "";
                if (index < dataTypes.size()) { // there was a match
                    String params;
                    DataType dataType = (DataType) dataTypes.get(index);
                    params = dataType.getParams();
                    localTypeName = dataType.getLocalType();
                    if (params != null) {
                        prompt = "Enter " + params + ":  ";
                        paramString = "(" + getInput(prompt) + ")";
                    }
                    break;
                } else { // use the name as given
                    prompt = "Are you sure?  " + "Enter 'y' or 'n' and hit Return:  ";
                    String check = getInput(prompt) + " ";
                    check = check.toLowerCase().substring(0, 1);
                    if (check.equals("n"))
                        continue;
                    else {
                        localTypeName = sqlType;
                        break;
                    }
                }
            }

            createTypeString += localTypeName + paramString;

            if (typeToCreate.equals("d"))
                break;
        }

        if (typeToCreate.equals("s"))
            createTypeString += ")";
        System.out.println("");
        System.out.print("Your CREATE TYPE statement as ");
        System.out.println("sent to your DBMS:  ");
        System.out.println(createTypeString);
        System.out.println("");

        stmt.executeUpdate(createTypeString);

        stmt.close();
        con.close();

    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
    }
}

From source file:com.board.games.handler.modx.MODXPokerLoginServiceImpl.java

public static void main(String[] a) {

    Verifier verifier = new Verifier();

    String dbHash = "iDxLTbkejeeaQqpPoZTqUCJfWo1ALcBf7gMlYwwMa+Y="; //"dlgQ65ruCfeVVxqHJ3Bf02j50P0Wvis7WOoTfHYV3Nk=";
    String password = "rememberme";
    String dbSalt = "008747a35b77a4c7e55ab7ea8aec3ee0";
    PasswordResponse response = new PasswordResponse();
    String salt = "008747a35b77a4c7e55ab7ea8aec3ee0";
    response.setAlgorithm(Algorithm.PBKDF2);
    response.setSalt(salt);/*w w  w  .  j a v a 2s.co  m*/
    response.setAlgorithmDetails(new AlgorithmDetails());
    response.getAlgorithmDetails().setIterations(1000);
    response.getAlgorithmDetails().setHashFunction("SHA256");
    response.getAlgorithmDetails().setKeySize(263);
    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 1000,
            response.getAlgorithmDetails().getKeySize());
    try {
        SecretKeyFactory skf = PBKDF2Algorithms.getSecretKeyFactory(
                "PBKDF2WithHmac" + response.getAlgorithmDetails().getHashFunction().replace("-", ""));
        byte[] hash = skf.generateSecret(spec).getEncoded();

        String encodedHash = Base64.encodeBase64String(hash);
        response.setHash(encodedHash);

        System.out.println("hash " + response.getHash());
        if (verifier.verify(password, response)) {
            // Check it against database stored hash
            if (encodedHash.equals(dbHash)) {
                System.out.println("Authentication Successful");
            } else {
                System.out.println("Authentication failed");
            }

        } else {
            System.out.println("failed verification of hashing");
        }
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:de.uniwue.info2.main.CommandLineInterpreter.java

@SuppressWarnings("static-access")
public static void main(String[] args) {

    /*-------------------------------------------------------- */
    /*---------------SETTING TARGET LANGUAGE------------------ */
    /*-------------------------------------------------------- */
    LanguageFactory languageFactory = new LanguageFactory();

    CommandLine line = null;/*from  w  w  w .ja v a 2s  . c  om*/
    CommandLineParser parser = new BasicParser();
    Options options = new Options();
    // options to display in the help page
    Options options_short = new Options();

    // add help option
    Option help_option = new Option(HELP_OPTION_SHORT, HELP_OPTION, false, HELP_DESCRIPTION);
    options.addOption(help_option);
    options_short.addOption(help_option);
    // add extended help option
    Option help2_option = new Option(HELP2_OPTION_SHORT, HELP2_OPTION, false, HELP2_DESCRIPTION);
    options.addOption(help2_option);
    options_short.addOption(help2_option);
    // add optional operations option
    options.addOption(new Option(OPTIONAL_OPTION_SHORT, OPTIONAL_OPTION, false, OPTIONAL_DESCRIPTION));
    options.addOption(new Option(BIG_ENDIAN_OPTION_SHORT, BIG_ENDIAN_OPTION, false, BIG_ENDIAN_DESCRIPTION));
    options.addOption(
            new Option(LITTLE_ENDIAN_OPTION_SHORT, LITTLE_ENDIAN_OPTION, false, LITTLE_ENDIAN_DESCRIPTION));
    // add optional operations config option
    options.addOption(OptionBuilder.withLongOpt(OPTIONAL_FUNCTIONS_CONFIG_OPTION)
            .withArgName(OPTIONAL_FUNCTIONS_CONFIG_ARGUMENT)
            .withDescription(OPTIONAL_FUNCTIONS_CONFIG_DESCRIPTION).hasArg()
            .create(OPTIONAL_FUNCTIONS_CONFIG_SHORT));
    // add dsl option
    Option dsl_option = OptionBuilder.withLongOpt(DSL_OPTION).withArgName(DSL_ARGUMENT)
            .withDescription(DSL_DESCRIPTION).hasArg().isRequired().create(DSL_OPTION_SHORT);
    options.addOption(dsl_option);
    options_short.addOption(dsl_option);
    // add output-folder option
    Option output_option = OptionBuilder.withLongOpt(OUTPUT_OPTION).isRequired().withArgName(OUTPUT_ARGUMENT)
            .withDescription(OUTPUT_DESCRIPTION).hasArg().create(OUTPUT_OPTION_SHORT);
    options.addOption(output_option);
    options_short.addOption(output_option);

    // count possible language-specifications
    short optionCounter = 1;

    // get all possible language-specifications from language-factory and iterate through them
    List<LanguageSpecification> lSpecs = languageFactory.getAvailableLanguageSpecifications_();

    for (LanguageSpecification lSpec : lSpecs) {
        // get all possible unit-specifications for current language and iterate through them
        List<UnitTestLibrarySpecification> uSpecs = languageFactory
                .getAvailableUnitTestLibraries_(lSpec.getOptionName());
        String languageDescriptionAll = LANGUAGE_SPECIFICATION + lSpec.getLanguageName();
        String languageCounter = "s" + INDEX.format(optionCounter++);

        for (UnitTestLibrarySpecification uSpec : uSpecs) {
            // get all possible arithmetic-library-specifications for current language and iterate through
            // them
            List<ArithmeticLibrarySpecification> aSpecs = languageFactory
                    .getAvailableArithmeticLibraries_(lSpec.getOptionName());
            for (ArithmeticLibrarySpecification aSpec : aSpecs) {
                String languageDescription = "Generate unit-test for " + lSpec.getLanguageName() + "\n*["
                        + uSpec.getLibraryName() + " - " + uSpec.getVersion() + "]\n*[" + aSpec.getLibraryName()
                        + " - " + aSpec.getVersion() + "]";

                // if there is more than one option, generate suitable option-names and add them all to
                // commandline options
                if (uSpecs.size() > 1 || aSpecs.size() > 1) {
                    options.addOption(OptionBuilder
                            .withLongOpt(lSpec.getOptionName() + "_" + uSpec.getOptionName() + "_"
                                    + aSpec.getOptionName())
                            .withDescription(languageDescription).hasArg(false)
                            .create("s" + INDEX.format(optionCounter++)));
                } else {
                    // if there is only one option, use language-name as option-name
                    languageDescriptionAll = languageDescription;
                }
            }
            // add specifications to options
            options.addOption(OptionBuilder.withLongOpt(lSpec.getOptionName())
                    .withDescription(languageDescriptionAll).hasArg(false).create(languageCounter));
        }
    }

    /*-------------------------------------------------------- */
    /*-------------------PARSE USER INPUT--------------------- */
    /*-------------------------------------------------------- */
    try {
        // manual search for help-arguments
        for (String arg : args) {
            arg = arg.trim().replace("-", "");
            if (arg.equals(HELP_OPTION_SHORT) || arg.equals(HELP_OPTION)) {
                printHelp(options_short);
                return;
            }
            if (arg.equals(HELP2_OPTION_SHORT) || arg.equals(HELP2_OPTION)) {
                printExtendedHelp(options);
                return;
            }
        }

        // parse arguments   
        line = parser.parse(options, args);

        File dsl_file = null;
        File output_folder = null;
        File optional_config = null;
        Properties optional_operations = null;
        Boolean optional = false;
        Boolean little_endian = null;
        ArrayList<String> optional_exceptions = new ArrayList<String>();

        // if help-option found print help
        if (line.hasOption(HELP2_OPTION_SHORT) || args.length == 0) {
            printExtendedHelp(options);
            return;
        }

        // if help-option found print help
        if (line.hasOption(HELP_OPTION_SHORT) || args.length == 0) {
            System.out.println("\n");
            printHelp(options_short);
            return;
        }

        if (line.hasOption(OPTIONAL_OPTION_SHORT)) {
            optional = true;
        }

        if (line.hasOption(LITTLE_ENDIAN_OPTION)) {
            little_endian = true;
        }

        if (line.hasOption(BIG_ENDIAN_OPTION)) {
            little_endian = false;
        }

        // if dsl-option found, check if file exists and is readable
        // print help if error occurs
        if (line.hasOption(DSL_OPTION_SHORT)) {
            dsl_file = new File(line.getOptionValue(DSL_OPTION_SHORT));
            if (!dsl_file.exists()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - DSL-file doesn't exist:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (dsl_file.isDirectory()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - DSL-file is a directory:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (!dsl_file.canRead()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Need read-permission for DSL-file:\n"
                        + dsl_file + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            }
        }

        // if output-option found, check if folder exists and if write-permission was granted
        // print help if error occurs
        if (line.hasOption(OUTPUT_OPTION_SHORT)) {
            output_folder = new File(line.getOptionValue(OUTPUT_OPTION_SHORT));
            if (!output_folder.exists()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Output-folder doesn't exist:\n"
                        + output_folder + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (!output_folder.isDirectory()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Output-folder is not a directory:\n"
                        + output_folder + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            } else if (!output_folder.canWrite() || !output_folder.canRead()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Missing permissions for output-folder:\n"
                        + output_folder + "\n" + SEPERATOR + "\n");
                printHelp(options_short);
                return;
            }
        }

        if (line.hasOption(OPTIONAL_FUNCTIONS_CONFIG_SHORT)) {
            optional_config = new File(line.getOptionValue(OPTIONAL_FUNCTIONS_CONFIG_OPTION));
            if (!dsl_file.exists()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - config-file doesn't exist:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printExtendedHelp(options);
                return;
            } else if (dsl_file.isDirectory()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - config-file is a directory:\n" + dsl_file
                        + "\n" + SEPERATOR + "\n");
                printExtendedHelp(options);
                return;
            } else if (!dsl_file.canRead()) {
                System.err.println("\n" + SEPERATOR + "\n" + "ERROR - Need read-permission for config-file:\n"
                        + dsl_file + "\n" + SEPERATOR + "\n");
                printExtendedHelp(options);
                return;
            }
        }

        if (optional_config != null) {
            optional_operations = new Properties();
            BufferedInputStream stream = new BufferedInputStream(new FileInputStream(optional_config));
            optional_operations.load(stream);
            stream.close();
            String optional_prop = optional_operations.getProperty("GENERATE_OPTIONAL");
            if (optional_prop != null) {
                if (optional_prop.trim().toLowerCase().equals("true")) {
                    optional = true;
                } else if (optional_prop.trim().toLowerCase().equals("false")) {
                    optional = false;
                } else if (!optional_prop.trim().isEmpty()) {
                    System.err.println("\n" + SEPERATOR + "\n"
                            + "ERROR - Syntax incorrect in config-file:\nUse \"true\" or \"false\" for \"GENERATE_OPTIONAL\"\n"
                            + SEPERATOR + "\n");
                    printExtendedHelp(options);
                    return;
                }
            }
            String exceptions = optional_operations.getProperty("EXCLUSIONS");
            if (exceptions != null) {
                for (String exc : optional_operations.getProperty("EXCLUSIONS").split(";")) {
                    optional_exceptions.add(exc.trim());
                }
            }
        }

        /*-------------------------------------------------------- */
        /*-------------------START GENERATING--------------------- */
        /*-------------------------------------------------------- */

        // instantiate generator for unit-tests
        TestcaseGenerator mainGenerator = new TestcaseGenerator(dsl_file, output_folder);

        boolean overrideDefaultSpecs = false;

        // check if user input contains a language-specifications
        // if user specified language, set overrideDefaultSpecs to true, so that only given specifications
        // are used
        for (int i = 1; i <= optionCounter; i++) {
            String opt = "s" + INDEX.format(i);
            if (line.hasOption(opt)) {
                LanguageSpecification targetSpecification = languageFactory
                        .getLanguageSpecification(options.getOption(opt).getLongOpt());
                String output = (GENERATING_DIALOG + targetSpecification.getLanguageName());

                // finally generate unit-test for current language-specification
                boolean successful = mainGenerator.generateUnitTest(targetSpecification, optional,
                        optional_exceptions, little_endian);

                if (successful) {
                    System.out.println(output + "\n--> Successfully generated.");
                } else {
                    System.err.println(output + "\n--> ERROR - see logfile");
                }
                overrideDefaultSpecs = true;
            }
        }

        // skip, if user already defined one language-specification
        // if user did not define language-specification, generate unit-tests for all
        // possible language-specifications (default)
        if (!overrideDefaultSpecs) {
            for (int i = 0; i < lSpecs.size(); i++) {
                LanguageSpecification specification = languageFactory
                        .getLanguageSpecification(lSpecs.get(i).getOptionName());

                String output = INDEX.format(i + 1) + " - " + GENERATING_DIALOG
                        + specification.getLanguageName();

                // finally generate unit-test for current language-specification
                boolean successful = mainGenerator.generateUnitTest(specification, optional,
                        optional_exceptions, little_endian);

                if (successful) {
                    System.out.println(output + "\n--> Successfully generated.");
                } else {
                    System.err.println(output + "\n--> ERROR - see logfile");
                }
            }
        }

    } catch (ParseException | IOException p) {
        System.err.println("\n" + SEPERATOR + "\n" + "ERROR - WRONG ARGUMENTS:\n" + p.getMessage() + "\n"
                + SEPERATOR + "\n");
        printHelp(options_short);
        System.out.println("\n");
    }
}

From source file:de.julielab.jtbd.TokenizerApplication.java

public static void main(final String[] args) throws IOException {

    if (args.length < 1) {
        System.err.println("usage: JTBD <mode> <mode-specific-parameters>");
        showModes();/*from   w  w  w.  j  a va2 s . co m*/
        System.exit(-1);
    }

    final String mode = args[0];

    if (mode.equals("c"))
        startCheckMode(args);
    else if (mode.equals("s"))
        start9010ValidationMode(args);
    else if (mode.equals("x"))
        startXValidationMode(args);
    else if (mode.equals("t"))
        startTrainingMode(args);
    else if (mode.equals("p"))
        startPredictionMode(args);
    else if (mode.equals("e"))
        startCompareValidationMode(args);
    else { // unknown mode
        System.err.println("unknown mode");
        showModes();
    }

}

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step5bGoldLabelStatistics.java

@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
    String inputDir = args[0];/*from w  w w. java2 s. co  m*/

    Collection<File> files = IOHelper.listXmlFiles(new File(inputDir));

    int totalPairsWithReasonSameAsGold = 0;

    DescriptiveStatistics ds = new DescriptiveStatistics();

    DescriptiveStatistics statsPerTopic = new DescriptiveStatistics();

    Map<String, Integer> goldDataDistribution = new HashMap<>();

    int totalGoldReasonTokens = 0;

    for (File file : files) {
        List<AnnotatedArgumentPair> argumentPairs = (List<AnnotatedArgumentPair>) XStreamTools.getXStream()
                .fromXML(file);

        int pairsPerTopicCounter = 0;

        for (AnnotatedArgumentPair annotatedArgumentPair : argumentPairs) {
            String goldLabel = annotatedArgumentPair.getGoldLabel();

            int sameInOnePair = 0;

            if (goldLabel != null) {
                if (!goldDataDistribution.containsKey(goldLabel)) {
                    goldDataDistribution.put(goldLabel, 0);
                }

                goldDataDistribution.put(goldLabel, goldDataDistribution.get(goldLabel) + 1);

                // get gold reason statistics
                for (AnnotatedArgumentPair.MTurkAssignment assignment : annotatedArgumentPair.mTurkAssignments) {
                    String label = assignment.getValue();

                    if (goldLabel.equals(label)) {
                        sameInOnePair++;

                        totalGoldReasonTokens += assignment.getReason().split("\\W+").length;
                    }
                }

                pairsPerTopicCounter++;
            }

            ds.addValue(sameInOnePair);
            totalPairsWithReasonSameAsGold += sameInOnePair;

        }

        statsPerTopic.addValue(pairsPerTopicCounter);
    }

    System.out.println("Total reasons matching gold " + totalPairsWithReasonSameAsGold);
    System.out.println(ds);

    int totalPairs = 0;
    for (Integer pairs : goldDataDistribution.values()) {
        totalPairs += pairs;
    }

    System.out.println(goldDataDistribution);
    System.out.println(goldDataDistribution.values());
    System.out.println("Total pairs: " + totalPairs);

    System.out.println("Stats per topic: " + statsPerTopic);
    System.out.println("Total gold reason tokens: " + totalGoldReasonTokens);

}

From source file:biomine.nodeimportancecompression.ImportanceCompressionReport.java

public static void main(String[] args) throws IOException, java.text.ParseException {
    opts.addOption("algorithm", true,
            "Used algorithm for compression. Possible values are 'brute-force', "
                    + "'brute-force-edges','brute-force-merges','randomized','randomized-merges',"
                    + "'randomized-edges'," + "'fast-brute-force',"
                    + "'fast-brute-force-merges','fast-brute-force-merge-edges'. Default is 'brute-force'.");
    opts.addOption("query", true, "Query nodes ids, separated by comma.");
    opts.addOption("queryfile", true, "Read query nodes from file.");
    opts.addOption("ratio", true, "Goal ratio");
    opts.addOption("importancefile", true, "Read importances straight from file");
    opts.addOption("keepedges", false, "Don't remove edges during merges");
    opts.addOption("connectivity", false, "Compute and output connectivities in edge oriented case");
    opts.addOption("paths", false, "Do path oriented compression");
    opts.addOption("edges", false, "Do edge oriented compression");
    // opts.addOption( "a",

    double sigma = 1.0;
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;/*from w w  w  .  j a  v a 2s.  com*/

    try {
        cmd = parser.parse(opts, args);
    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(0);
    }

    String queryStr = cmd.getOptionValue("query");
    String[] queryNodeIDs = {};
    double[] queryNodeIMP = {};
    if (queryStr != null) {
        queryNodeIDs = queryStr.split(",");
        queryNodeIMP = new double[queryNodeIDs.length];
        for (int i = 0; i < queryNodeIDs.length; i++) {
            String s = queryNodeIDs[i];
            String[] es = s.split("=");
            queryNodeIMP[i] = 1;
            if (es.length == 2) {
                queryNodeIDs[i] = es[0];
                queryNodeIMP[i] = Double.parseDouble(es[1]);
            } else if (es.length > 2) {
                System.out.println("Too many '=' in querynode specification: " + s);
            }
        }
    }

    String queryFile = cmd.getOptionValue("queryfile");
    Map<String, Double> queryNodes = Collections.EMPTY_MAP;
    if (queryFile != null) {
        File in = new File(queryFile);
        BufferedReader read = new BufferedReader(new FileReader(in));

        queryNodes = readMap(read);
        read.close();
    }

    String impfile = cmd.getOptionValue("importancefile");
    Map<String, Double> importances = null;
    if (impfile != null) {
        File in = new File(impfile);
        BufferedReader read = new BufferedReader(new FileReader(in));

        importances = readMap(read);
        read.close();
    }

    String algoStr = cmd.getOptionValue("algorithm");
    CompressionAlgorithm algo = null;

    if (algoStr == null || algoStr.equals("brute-force")) {
        algo = new BruteForceCompression();
    } else if (algoStr.equals("brute-force-edges")) {
        algo = new BruteForceCompressionOnlyEdges();
    } else if (algoStr.equals("brute-force-merges")) {
        algo = new BruteForceCompressionOnlyMerges();
    } else if (algoStr.equals("fast-brute-force-merges")) {
        //algo = new FastBruteForceCompressionOnlyMerges();
        algo = new FastBruteForceCompression(true, false);
    } else if (algoStr.equals("fast-brute-force-edges")) {
        algo = new FastBruteForceCompression(false, true);
        //algo = new FastBruteForceCompressionOnlyEdges();
    } else if (algoStr.equals("fast-brute-force")) {
        algo = new FastBruteForceCompression(true, true);
    } else if (algoStr.equals("randomized-edges")) {
        algo = new RandomizedCompressionOnlyEdges(); //modified
    } else if (algoStr.equals("randomized")) {
        algo = new RandomizedCompression();
    } else if (algoStr.equals("randomized-merges")) {
        algo = new RandomizedCompressionOnlyMerges();
    } else {
        System.out.println("Unsupported algorithm: " + algoStr);
        printHelp();
    }

    String ratioStr = cmd.getOptionValue("ratio");
    double ratio = 0;
    if (ratioStr != null) {
        ratio = Double.parseDouble(ratioStr);
    } else {
        System.out.println("Goal ratio not specified");
        printHelp();
    }

    String infile = null;
    if (cmd.getArgs().length != 0) {
        infile = cmd.getArgs()[0];
    } else {
        printHelp();
    }

    BMGraph bmg = BMGraphUtils.readBMGraph(new File(infile));
    HashMap<BMNode, Double> queryBMNodes = new HashMap<BMNode, Double>();
    for (String id : queryNodes.keySet()) {
        queryBMNodes.put(bmg.getNode(id), queryNodes.get(id));
    }

    long startMillis = System.currentTimeMillis();
    ImportanceGraphWrapper wrap = QueryImportance.queryImportanceGraph(bmg, queryBMNodes);

    if (importances != null) {
        for (String id : importances.keySet()) {
            wrap.setImportance(bmg.getNode(id), importances.get(id));
        }
    }

    ImportanceMerger merger = null;
    if (cmd.hasOption("edges")) {
        merger = new ImportanceMergerEdges(wrap.getImportanceGraph());
    } else if (cmd.hasOption("paths")) {
        merger = new ImportanceMergerPaths(wrap.getImportanceGraph());
    } else {
        System.out.println("Specify either 'paths' or 'edges'.");
        System.exit(1);
    }

    if (cmd.hasOption("keepedges")) {
        merger.setKeepEdges(true);
    }

    algo.compress(merger, ratio);
    long endMillis = System.currentTimeMillis();

    // write importance

    {
        BufferedWriter wr = new BufferedWriter(new FileWriter("importance.txt", false));
        for (BMNode nod : bmg.getNodes()) {
            wr.write(nod + " " + wrap.getImportance(nod) + "\n");
        }
        wr.close();
    }

    // write sum of all pairs of node importance    added by Fang
    /*   {
    BufferedWriter wr = new BufferedWriter(new FileWriter("sum_of_all_pairs_importance.txt", true));
    ImportanceGraph orig = wrap.getImportanceGraph();
    double sum = 0;
            
    for (int i = 0; i <= orig.getMaxNodeId(); i++) {
        for (int j = i+1; j <= orig.getMaxNodeId(); j++) {
            sum = sum+ wrap.getImportance(i)* wrap.getImportance(j);
        }
    }
            
    wr.write(""+sum);
    wr.write("\n");
    wr.close();
       }
            
    */

    // write uncompressed edges
    {
        BufferedWriter wr = new BufferedWriter(new FileWriter("edges.txt", false));
        ImportanceGraph orig = wrap.getImportanceGraph();
        ImportanceGraph ucom = merger.getUncompressedGraph();
        for (int i = 0; i <= orig.getMaxNodeId(); i++) {
            String iname = wrap.intToNode(i).toString();
            HashSet<Integer> ne = new HashSet<Integer>();
            ne.addAll(orig.getNeighbors(i));
            ne.addAll(ucom.getNeighbors(i));
            for (int j : ne) {
                if (i < j)
                    continue;
                String jname = wrap.intToNode(j).toString();
                double a = orig.getEdgeWeight(i, j);
                double b = ucom.getEdgeWeight(i, j);
                wr.write(iname + " " + jname + " " + a + " " + b + " " + Math.abs(a - b));
                wr.write("\n");
            }
        }
        wr.close();
    }
    // write distance
    {
        // BufferedWriter wr = new BufferedWriter(new
        // FileWriter("distance.txt",false));
        BufferedWriter wr = new BufferedWriter(new FileWriter("distance.txt", true)); //modified by Fang

        ImportanceGraph orig = wrap.getImportanceGraph();
        ImportanceGraph ucom = merger.getUncompressedGraph();
        double error = 0;
        for (int i = 0; i <= orig.getMaxNodeId(); i++) {
            HashSet<Integer> ne = new HashSet<Integer>();
            ne.addAll(orig.getNeighbors(i));
            ne.addAll(ucom.getNeighbors(i));
            for (int j : ne) {
                if (i <= j)
                    continue;
                double a = orig.getEdgeWeight(i, j);
                double b = ucom.getEdgeWeight(i, j);
                error += (a - b) * (a - b) * wrap.getImportance(i) * wrap.getImportance(j);
                // modify by Fang: multiply imp(u)imp(v)

            }
        }
        error = Math.sqrt(error);
        //////////error = Math.sqrt(error / 2); // modified by Fang: the error of each
        // edge is counted twice
        wr.write("" + error);
        wr.write("\n");
        wr.close();
    }
    // write sizes
    {
        ImportanceGraph orig = wrap.getImportanceGraph();
        ImportanceGraph comp = merger.getCurrentGraph();
        // BufferedWriter wr = new BufferedWriter(new
        // FileWriter("sizes.txt",false));
        BufferedWriter wr = new BufferedWriter(new FileWriter("sizes.txt", true)); //modified by Fang

        wr.write(orig.getNodeCount() + " " + orig.getEdgeCount() + " " + comp.getNodeCount() + " "
                + comp.getEdgeCount());
        wr.write("\n");
        wr.close();
    }
    //write time
    {
        System.out.println("writing time");
        BufferedWriter wr = new BufferedWriter(new FileWriter("time.txt", true)); //modified by Fang
        double secs = (endMillis - startMillis) * 0.001;
        wr.write("" + secs + "\n");
        wr.close();
    }

    //write change of connectivity for edge-oriented case       // added by Fang
    {
        if (cmd.hasOption("connectivity")) {

            BufferedWriter wr = new BufferedWriter(new FileWriter("connectivity.txt", true));
            ImportanceGraph orig = wrap.getImportanceGraph();
            ImportanceGraph ucom = merger.getUncompressedGraph();

            double diff = 0;

            for (int i = 0; i <= orig.getMaxNodeId(); i++) {
                ProbDijkstra pdori = new ProbDijkstra(orig, i);
                ProbDijkstra pducom = new ProbDijkstra(ucom, i);

                for (int j = i + 1; j <= orig.getMaxNodeId(); j++) {
                    double oriconn = pdori.getProbTo(j);
                    double ucomconn = pducom.getProbTo(j);

                    diff = diff + (oriconn - ucomconn) * (oriconn - ucomconn) * wrap.getImportance(i)
                            * wrap.getImportance(j);

                }
            }

            diff = Math.sqrt(diff);
            wr.write("" + diff);
            wr.write("\n");
            wr.close();

        }
    }

    //write output graph
    {
        BMGraph output = bmg;//new BMGraph(bmg);

        int no = 0;
        BMNode[] nodes = new BMNode[merger.getGroups().size()];
        for (ArrayList<Integer> gr : merger.getGroups()) {
            BMNode bmgroup = new BMNode("Group", "" + (no + 1));
            bmgroup.setAttributes(new HashMap<String, String>());
            bmgroup.put("autoedges", "0");
            nodes[no] = bmgroup;
            no++;
            if (gr.size() == 0)
                continue;
            for (int x : gr) {
                BMNode nod = output.getNode(wrap.intToNode(x).toString());
                BMEdge belongs = new BMEdge(nod, bmgroup, "belongs_to");
                output.ensureHasEdge(belongs);
            }
            output.ensureHasNode(bmgroup);
        }
        for (int i = 0; i < nodes.length; i++) {
            for (int x : merger.getCurrentGraph().getNeighbors(i)) {
                if (x == i) {
                    nodes[x].put("selfedge", "" + merger.getCurrentGraph().getEdgeWeight(i, x));
                    //ge.put("goodness", ""+merger.getCurrentGraph().getEdgeWeight(i, x));
                    continue;
                }
                BMEdge ge = new BMEdge(nodes[x], nodes[i], "groupedge");
                ge.setAttributes(new HashMap<String, String>());
                ge.put("goodness", "" + merger.getCurrentGraph().getEdgeWeight(i, x));
                output.ensureHasEdge(ge);
            }
        }
        System.out.println(output.getGroupNodes());

        BMGraphUtils.writeBMGraph(output, "output.bmg");
    }
}