Example usage for java.io File getName

List of usage examples for java.io File getName

Introduction

In this page you can find the example usage for java.io File getName.

Prototype

public String getName() 

Source Link

Document

Returns the name of the file or directory denoted by this abstract pathname.

Usage

From source file:apps.quantification.LearnQuantificationSVMLight.java

public static void main(String[] args) throws IOException {
    String cmdLineSyntax = LearnQuantificationSVMLight.class.getName()
            + " [OPTIONS] <path to svm_light_learn> <path to svm_light_classify> <trainingIndexDirectory> <outputDirectory>";

    Options options = new Options();

    OptionBuilder.withArgName("f");
    OptionBuilder.withDescription("Number of folds");
    OptionBuilder.withLongOpt("f");
    OptionBuilder.isRequired(true);//from w ww. j  a  va  2  s. c  om
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("c");
    OptionBuilder.withDescription("The c value for svm_light (default 1)");
    OptionBuilder.withLongOpt("c");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("k");
    OptionBuilder.withDescription("Kernel type (default 0: linear, 1: polynomial, 2: RBF, 3: sigmoid)");
    OptionBuilder.withLongOpt("k");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("t");
    OptionBuilder.withDescription("Path for temporary files");
    OptionBuilder.withLongOpt("t");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("v");
    OptionBuilder.withDescription("Verbose output");
    OptionBuilder.withLongOpt("v");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("s");
    OptionBuilder.withDescription("Don't delete temporary training file in svm_light format (default: delete)");
    OptionBuilder.withLongOpt("s");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    SvmLightLearnerCustomizer classificationLearnerCustomizer = null;
    SvmLightClassifierCustomizer classificationCustomizer = null;

    int folds = -1;

    GnuParser parser = new GnuParser();
    String[] remainingArgs = null;
    try {
        CommandLine line = parser.parse(options, args);

        remainingArgs = line.getArgs();

        classificationLearnerCustomizer = new SvmLightLearnerCustomizer(remainingArgs[0]);
        classificationCustomizer = new SvmLightClassifierCustomizer(remainingArgs[1]);

        folds = Integer.parseInt(line.getOptionValue("f"));

        if (line.hasOption("c"))
            classificationLearnerCustomizer.setC(Float.parseFloat(line.getOptionValue("c")));

        if (line.hasOption("k")) {
            System.out.println("Kernel type: " + line.getOptionValue("k"));
            classificationLearnerCustomizer.setKernelType(Integer.parseInt(line.getOptionValue("k")));
        }

        if (line.hasOption("v"))
            classificationLearnerCustomizer.printSvmLightOutput(true);

        if (line.hasOption("s"))
            classificationLearnerCustomizer.setDeleteTrainingFiles(false);

        if (line.hasOption("t")) {
            classificationLearnerCustomizer.setTempPath(line.getOptionValue("t"));
            classificationCustomizer.setTempPath(line.getOptionValue("t"));
        }

    } catch (Exception exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    assert (classificationLearnerCustomizer != null);

    if (remainingArgs.length != 4) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    String indexFile = remainingArgs[2];

    File file = new File(indexFile);

    String indexName = file.getName();
    String indexPath = file.getParent();

    String outputPath = remainingArgs[3];

    SvmLightLearner classificationLearner = new SvmLightLearner();

    classificationLearner.setRuntimeCustomizer(classificationLearnerCustomizer);

    FileSystemStorageManager fssm = new FileSystemStorageManager(indexPath, false);
    fssm.open();

    IIndex training = TroveReadWriteHelper.readIndex(fssm, indexName, TroveContentDBType.Full,
            TroveClassificationDBType.Full);

    final TextualProgressBar progressBar = new TextualProgressBar("Learning the quantifiers");

    IOperationStatusListener status = new IOperationStatusListener() {

        @Override
        public void operationStatus(double percentage) {
            progressBar.signal((int) percentage);
        }
    };

    QuantificationLearner quantificationLearner = new QuantificationLearner(folds, classificationLearner,
            classificationLearnerCustomizer, classificationCustomizer, ClassificationMode.PER_CATEGORY,
            new LogisticFunction(), status);

    IQuantifier[] quantifiers = quantificationLearner.learn(training);

    File executableFile = new File(classificationLearnerCustomizer.getSvmLightLearnPath());
    IDataManager classifierDataManager = new SvmLightDataManager(new SvmLightClassifierCustomizer(
            executableFile.getParentFile().getAbsolutePath() + Os.pathSeparator() + "svm_light_classify"));
    String description = "_SVMLight_C-" + classificationLearnerCustomizer.getC() + "_K-"
            + classificationLearnerCustomizer.getKernelType();
    if (classificationLearnerCustomizer.getAdditionalParameters().length() > 0)
        description += "_" + classificationLearnerCustomizer.getAdditionalParameters();
    String quantifierPrefix = indexName + "_Quantifier-" + folds + description;

    FileSystemStorageManager fssmo = new FileSystemStorageManager(
            outputPath + File.separatorChar + quantifierPrefix, true);
    fssmo.open();
    QuantificationLearner.write(quantifiers, fssmo, classifierDataManager);
    fssmo.close();

    BufferedWriter bfs = new BufferedWriter(
            new FileWriter(outputPath + File.separatorChar + quantifierPrefix + "_rates.txt"));
    TShortDoubleHashMap simpleTPRs = quantificationLearner.getSimpleTPRs();
    TShortDoubleHashMap simpleFPRs = quantificationLearner.getSimpleFPRs();
    TShortDoubleHashMap scaledTPRs = quantificationLearner.getScaledTPRs();
    TShortDoubleHashMap scaledFPRs = quantificationLearner.getScaledFPRs();

    ContingencyTableSet contingencyTableSet = quantificationLearner.getContingencyTableSet();

    short[] cats = simpleTPRs.keys();
    for (int i = 0; i < cats.length; ++i) {
        short cat = cats[i];
        String catName = training.getCategoryDB().getCategoryName(cat);
        ContingencyTable contingencyTable = contingencyTableSet.getCategoryContingencyTable(cat);
        double simpleTPR = simpleTPRs.get(cat);
        double simpleFPR = simpleFPRs.get(cat);
        double scaledTPR = scaledTPRs.get(cat);
        double scaledFPR = scaledFPRs.get(cat);
        String line = quantifierPrefix + "\ttrain\tsimple\t" + catName + "\t" + cat + "\t"
                + contingencyTable.tp() + "\t" + contingencyTable.fp() + "\t" + contingencyTable.fn() + "\t"
                + contingencyTable.tn() + "\t" + simpleTPR + "\t" + simpleFPR + "\n";
        bfs.write(line);
        line = quantifierPrefix + "\ttrain\tscaled\t" + catName + "\t" + cat + "\t" + contingencyTable.tp()
                + "\t" + contingencyTable.fp() + "\t" + contingencyTable.fn() + "\t" + contingencyTable.tn()
                + "\t" + scaledTPR + "\t" + scaledFPR + "\n";
        bfs.write(line);
    }
    bfs.close();
}

From source file:apps.quantification.QuantifySVMLight.java

public static void main(String[] args) throws IOException {
    String cmdLineSyntax = QuantifySVMLight.class.getName()
            + " [OPTIONS] <path to svm_light_classify> <testIndexDirectory> <quantificationModelDirectory>";

    Options options = new Options();

    OptionBuilder.withArgName("d");
    OptionBuilder.withDescription("Dump confidences file");
    OptionBuilder.withLongOpt("d");
    OptionBuilder.isRequired(false);//from   www  .j  a v a2  s  . c om
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("t");
    OptionBuilder.withDescription("Path for temporary files");
    OptionBuilder.withLongOpt("t");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("v");
    OptionBuilder.withDescription("Verbose output");
    OptionBuilder.withLongOpt("v");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("s");
    OptionBuilder.withDescription("Don't delete temporary files in svm_light format (default: delete)");
    OptionBuilder.withLongOpt("s");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    SvmLightClassifierCustomizer customizer = null;

    GnuParser parser = new GnuParser();
    String[] remainingArgs = null;
    try {
        CommandLine line = parser.parse(options, args);

        remainingArgs = line.getArgs();

        customizer = new SvmLightClassifierCustomizer(remainingArgs[0]);

        if (line.hasOption("v"))
            customizer.printSvmLightOutput(true);

        if (line.hasOption("s")) {
            System.out.println("Keeping temporary files.");
            customizer.setDeleteTestFiles(false);
            customizer.setDeletePredictionsFiles(false);
        }

        if (line.hasOption("t"))
            customizer.setTempPath(line.getOptionValue("t"));

    } catch (Exception exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    if (remainingArgs.length != 3) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    String indexFile = remainingArgs[1];

    File file = new File(indexFile);

    String indexName = file.getName();
    String indexPath = file.getParent();

    String quantifierFilename = remainingArgs[2];

    FileSystemStorageManager indexFssm = new FileSystemStorageManager(indexPath, false);
    indexFssm.open();

    IIndex test = TroveReadWriteHelper.readIndex(indexFssm, indexName, TroveContentDBType.Full,
            TroveClassificationDBType.Full);

    indexFssm.close();

    FileSystemStorageManager quantifierFssm = new FileSystemStorageManager(quantifierFilename, false);
    quantifierFssm.open();

    SvmLightDataManager classifierDataManager = new SvmLightDataManager(customizer);

    FileSystemStorageManager fssm = new FileSystemStorageManager(quantifierFilename, false);
    fssm.open();

    IQuantifier[] quantifiers = QuantificationLearner.read(fssm, classifierDataManager,
            ClassificationMode.PER_CATEGORY);
    fssm.close();

    quantifierFssm.close();

    Quantification ccQuantification = quantifiers[0].quantify(test);
    Quantification paQuantification = quantifiers[1].quantify(test);
    Quantification accQuantification = quantifiers[2].quantify(test);
    Quantification maxQuantification = quantifiers[3].quantify(test);
    Quantification sccQuantification = quantifiers[4].quantify(test);
    Quantification spaQuantification = quantifiers[5].quantify(test);
    Quantification trueQuantification = new Quantification("True", test.getClassificationDB());

    File quantifierFile = new File(quantifierFilename);

    String quantificationName = quantifierFile.getParent() + Os.pathSeparator() + indexName + "_"
            + quantifierFile.getName() + ".txt";

    BufferedWriter writer = new BufferedWriter(new FileWriter(quantificationName));
    IShortIterator iterator = test.getCategoryDB().getCategories();
    while (iterator.hasNext()) {
        short category = iterator.next();
        String prefix = quantifierFile.getName() + "\t" + indexName + "\t"
                + test.getCategoryDB().getCategoryName(category) + "\t" + category + "\t"
                + trueQuantification.getQuantification(category) + "\t";

        writer.write(prefix + ccQuantification.getName() + "\t" + ccQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + paQuantification.getName() + "\t" + paQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + accQuantification.getName() + "\t" + accQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + maxQuantification.getName() + "\t" + maxQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + sccQuantification.getName() + "\t" + sccQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + spaQuantification.getName() + "\t" + spaQuantification.getQuantification(category)
                + "\n");
    }
    writer.close();

    BufferedWriter bfs = new BufferedWriter(new FileWriter(quantifierFile.getParent() + Os.pathSeparator()
            + indexName + "_" + quantifierFile.getName() + "_rates.txt"));
    TShortDoubleHashMap simpleTPRs = ((CCQuantifier) quantifiers[0]).getSimpleTPRs();
    TShortDoubleHashMap simpleFPRs = ((CCQuantifier) quantifiers[0]).getSimpleFPRs();
    TShortDoubleHashMap maxTPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier())
            .getSimpleTPRs();
    TShortDoubleHashMap maxFPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier())
            .getSimpleFPRs();
    TShortDoubleHashMap scaledTPRs = ((PAQuantifier) quantifiers[1]).getScaledTPRs();
    TShortDoubleHashMap scaledFPRs = ((PAQuantifier) quantifiers[1]).getScaledFPRs();

    ContingencyTableSet simpleContingencyTableSet = ((CCQuantifier) quantifiers[0]).getContingencyTableSet();
    ContingencyTableSet maxContingencyTableSet = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3])
            .getInternalQuantifier()).getContingencyTableSet();

    short[] cats = simpleTPRs.keys();
    for (int i = 0; i < cats.length; ++i) {
        short cat = cats[i];
        String catName = test.getCategoryDB().getCategoryName(cat);
        ContingencyTable simpleContingencyTable = simpleContingencyTableSet.getCategoryContingencyTable(cat);
        ContingencyTable maxContingencyTable = maxContingencyTableSet.getCategoryContingencyTable(cat);
        double simpleTPR = simpleTPRs.get(cat);
        double simpleFPR = simpleFPRs.get(cat);
        double maxTPR = maxTPRs.get(cat);
        double maxFPR = maxFPRs.get(cat);
        double scaledTPR = scaledTPRs.get(cat);
        double scaledFPR = scaledFPRs.get(cat);
        String line = indexName + "_" + quantifierFile.getName() + "\ttest\tsimple\t" + catName + "\t" + cat
                + "\t" + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t"
                + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + simpleTPR + "\t"
                + simpleFPR + "\n";
        bfs.write(line);
        line = indexName + "_" + quantifierFile.getName() + "\ttest\tmax\t" + catName + "\t" + cat + "\t"
                + maxContingencyTable.tp() + "\t" + maxContingencyTable.fp() + "\t" + maxContingencyTable.fn()
                + "\t" + maxContingencyTable.tn() + "\t" + maxTPR + "\t" + maxFPR + "\n";
        bfs.write(line);
        line = indexName + "_" + quantifierFile.getName() + "\ttest\tscaled\t" + catName + "\t" + cat + "\t"
                + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t"
                + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + scaledTPR + "\t"
                + scaledFPR + "\n";
        bfs.write(line);
    }
    bfs.close();
}

From source file:apps.quantification.QuantifySVMPerf.java

public static void main(String[] args) throws IOException {
    String cmdLineSyntax = QuantifySVMPerf.class.getName()
            + " [OPTIONS] <path to svm_perf_classify> <testIndexDirectory> <quantificationModelDirectory>";

    Options options = new Options();

    OptionBuilder.withArgName("d");
    OptionBuilder.withDescription("Dump confidences file");
    OptionBuilder.withLongOpt("d");
    OptionBuilder.isRequired(false);/*  w  w w .ja  va2  s  . co m*/
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("t");
    OptionBuilder.withDescription("Path for temporary files");
    OptionBuilder.withLongOpt("t");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("v");
    OptionBuilder.withDescription("Verbose output");
    OptionBuilder.withLongOpt("v");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("s");
    OptionBuilder.withDescription("Don't delete temporary files in svm_perf format (default: delete)");
    OptionBuilder.withLongOpt("s");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    SvmPerfClassifierCustomizer customizer = null;

    GnuParser parser = new GnuParser();
    String[] remainingArgs = null;
    try {
        CommandLine line = parser.parse(options, args);

        remainingArgs = line.getArgs();

        customizer = new SvmPerfClassifierCustomizer(remainingArgs[0]);

        if (line.hasOption("v"))
            customizer.printSvmPerfOutput(true);

        if (line.hasOption("s")) {
            System.out.println("Keeping temporary files.");
            customizer.setDeleteTestFiles(false);
            customizer.setDeletePredictionsFiles(false);
        }

        if (line.hasOption("t"))
            customizer.setTempPath(line.getOptionValue("t"));

    } catch (Exception exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    if (remainingArgs.length != 3) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    String indexFile = remainingArgs[1];

    File file = new File(indexFile);

    String indexName = file.getName();
    String indexPath = file.getParent();

    String quantifierFilename = remainingArgs[2];

    FileSystemStorageManager indexFssm = new FileSystemStorageManager(indexPath, false);
    indexFssm.open();

    IIndex test = TroveReadWriteHelper.readIndex(indexFssm, indexName, TroveContentDBType.Full,
            TroveClassificationDBType.Full);

    indexFssm.close();

    FileSystemStorageManager quantifierFssm = new FileSystemStorageManager(quantifierFilename, false);
    quantifierFssm.open();

    SvmPerfDataManager classifierDataManager = new SvmPerfDataManager(customizer);

    FileSystemStorageManager fssm = new FileSystemStorageManager(quantifierFilename, false);
    fssm.open();

    IQuantifier[] quantifiers = QuantificationLearner.read(fssm, classifierDataManager,
            ClassificationMode.PER_CATEGORY);
    fssm.close();

    quantifierFssm.close();

    Quantification ccQuantification = quantifiers[0].quantify(test);
    Quantification paQuantification = quantifiers[1].quantify(test);
    Quantification accQuantification = quantifiers[2].quantify(test);
    Quantification maxQuantification = quantifiers[3].quantify(test);
    Quantification sccQuantification = quantifiers[4].quantify(test);
    Quantification spaQuantification = quantifiers[5].quantify(test);
    Quantification trueQuantification = new Quantification("True", test.getClassificationDB());

    File quantifierFile = new File(quantifierFilename);

    String quantificationName = quantifierFile.getParent() + Os.pathSeparator() + indexName + "_"
            + quantifierFile.getName() + ".txt";

    BufferedWriter writer = new BufferedWriter(new FileWriter(quantificationName));
    IShortIterator iterator = test.getCategoryDB().getCategories();
    while (iterator.hasNext()) {
        short category = iterator.next();
        String prefix = quantifierFile.getName() + "\t" + indexName + "\t"
                + test.getCategoryDB().getCategoryName(category) + "\t" + category + "\t"
                + trueQuantification.getQuantification(category) + "\t";

        writer.write(prefix + ccQuantification.getName() + "\t" + ccQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + paQuantification.getName() + "\t" + paQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + accQuantification.getName() + "\t" + accQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + maxQuantification.getName() + "\t" + maxQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + sccQuantification.getName() + "\t" + sccQuantification.getQuantification(category)
                + "\n");
        writer.write(prefix + spaQuantification.getName() + "\t" + spaQuantification.getQuantification(category)
                + "\n");
    }
    writer.close();

    BufferedWriter bfs = new BufferedWriter(new FileWriter(quantifierFile.getParent() + Os.pathSeparator()
            + indexName + "_" + quantifierFile.getName() + "_rates.txt"));
    TShortDoubleHashMap simpleTPRs = ((CCQuantifier) quantifiers[0]).getSimpleTPRs();
    TShortDoubleHashMap simpleFPRs = ((CCQuantifier) quantifiers[0]).getSimpleFPRs();
    TShortDoubleHashMap maxTPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier())
            .getSimpleTPRs();
    TShortDoubleHashMap maxFPRs = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3]).getInternalQuantifier())
            .getSimpleFPRs();
    TShortDoubleHashMap scaledTPRs = ((PAQuantifier) quantifiers[1]).getScaledTPRs();
    TShortDoubleHashMap scaledFPRs = ((PAQuantifier) quantifiers[1]).getScaledFPRs();

    ContingencyTableSet simpleContingencyTableSet = ((CCQuantifier) quantifiers[0]).getContingencyTableSet();
    ContingencyTableSet maxContingencyTableSet = ((CCQuantifier) ((ScaledQuantifier) quantifiers[3])
            .getInternalQuantifier()).getContingencyTableSet();

    short[] cats = simpleTPRs.keys();
    for (int i = 0; i < cats.length; ++i) {
        short cat = cats[i];
        String catName = test.getCategoryDB().getCategoryName(cat);
        ContingencyTable simpleContingencyTable = simpleContingencyTableSet.getCategoryContingencyTable(cat);
        ContingencyTable maxContingencyTable = maxContingencyTableSet.getCategoryContingencyTable(cat);
        double simpleTPR = simpleTPRs.get(cat);
        double simpleFPR = simpleFPRs.get(cat);
        double maxTPR = maxTPRs.get(cat);
        double maxFPR = maxFPRs.get(cat);
        double scaledTPR = scaledTPRs.get(cat);
        double scaledFPR = scaledFPRs.get(cat);
        String line = indexName + "_" + quantifierFile.getName() + "\ttest\tsimple\t" + catName + "\t" + cat
                + "\t" + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t"
                + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + simpleTPR + "\t"
                + simpleFPR + "\n";
        bfs.write(line);
        line = indexName + "_" + quantifierFile.getName() + "\ttest\tmax\t" + catName + "\t" + cat + "\t"
                + maxContingencyTable.tp() + "\t" + maxContingencyTable.fp() + "\t" + maxContingencyTable.fn()
                + "\t" + maxContingencyTable.tn() + "\t" + maxTPR + "\t" + maxFPR + "\n";
        bfs.write(line);
        line = indexName + "_" + quantifierFile.getName() + "\ttest\tscaled\t" + catName + "\t" + cat + "\t"
                + simpleContingencyTable.tp() + "\t" + simpleContingencyTable.fp() + "\t"
                + simpleContingencyTable.fn() + "\t" + simpleContingencyTable.tn() + "\t" + scaledTPR + "\t"
                + scaledFPR + "\n";
        bfs.write(line);
    }
    bfs.close();
}

From source file:ShowImage.java

public static void main(String args[]) throws IOException {
    List<File> files = ImageIOUtils.getFiles(args, new String[] { "ntf", "nsf" });

    for (Iterator iter = files.iterator(); iter.hasNext();) {
        try {/*from  w w w .  j  av  a 2  s  .c  o  m*/
            File file = (File) iter.next();
            log.debug("Reading: " + file.getAbsolutePath());
            NITFReader imageReader = (NITFReader) ImageIOUtils.getImageReader("nitf", file);

            for (int i = 0; i < imageReader.getRecord().getImages().length; ++i) {
                log.debug(file.getName() + "[" + i + "]");

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                ImageSubheader subheader = imageReader.getRecord().getImages()[i].getSubheader();
                subheader.print(new PrintStream(stream));
                log.debug(stream.toString());

                try {
                    int numBands = subheader.getBandCount();
                    String irep = subheader.getImageRepresentation().getStringData().trim();
                    int bitsPerPixel = subheader.getNumBitsPerPixel().getIntData();
                    int nBytes = (bitsPerPixel - 1) / 8 + 1;

                    if (irep.equals("RGB") && numBands == 3) {
                        BufferedImage image = imageReader.read(i);
                        ImageIOUtils.showImage(image, file.getName() + "[" + i + "]", true);
                    } else {
                        // read each band, separately
                        for (int j = 0; j < numBands; ++j) {
                            if (nBytes == 1 || nBytes == 2 || nBytes == 4 || nBytes == 8) {
                                ImageReadParam readParam = imageReader.getDefaultReadParam();
                                readParam.setSourceBands(new int[] { j });
                                BufferedImage image = imageReader.read(i, readParam);
                                ImageIOUtils.showImage(image, file.getName() + "[" + i + "][" + j + "]", true);

                                ImageIO.write(image, "jpg",
                                        new FileOutputStream("image" + i + "_" + j + ".jpg"));

                                // downsample
                                // readParam.setSourceSubsampling(2, 2, 0,
                                // 0);
                                // BufferedImage smallerImage = imageReader
                                // .read(i, readParam);
                                //
                                // ImageIOUtils.showImage(smallerImage,
                                // "DOWNSAMPLED: " + file.getName());

                            }
                        }
                    }
                } catch (Exception e) {
                    System.out.println(ExceptionUtils.getStackTrace(e));
                    log.error(ExceptionUtils.getStackTrace(e));
                }
            }
        } catch (Exception e) {
            log.debug(ExceptionUtils.getStackTrace(e));
        }
    }
}

From source file:io.mindmaps.migration.csv.Main.java

public static void main(String[] args) {

    String csvFileName = null;//from w  ww  . j a  v  a 2  s.c  o m
    String csvEntityType = null;
    String engineURL = null;
    String graphName = null;

    for (int i = 0; i < args.length; i++) {
        if ("-file".equals(args[i]))
            csvFileName = args[++i];
        else if ("-graph".equals(args[i]))
            graphName = args[++i];
        else if ("-engine".equals(args[i]))
            engineURL = args[++i];
        else if ("-as".equals(args[i])) {
            csvEntityType = args[++i];
        } else if ("csv".equals(args[0])) {
            continue;
        } else
            die("Unknown option " + args[i]);
    }

    if (csvFileName == null) {
        die("Please specify CSV file using the -csv option");
    }
    File csvFile = new File(csvFileName);
    if (!csvFile.exists()) {
        die("Cannot find file: " + csvFileName);
    }
    if (graphName == null) {
        die("Please provide the name of the graph using -graph");
    }
    if (csvEntityType == null) {
        csvEntityType = csvFile.getName().replaceAll("[^A-Za-z0-9]", "_");
    }

    System.out.println("Migrating " + csvFileName + " using MM Engine "
            + (engineURL == null ? "local" : engineURL) + " into graph " + graphName);

    // perform migration
    CSVSchemaMigrator schemaMigrator = new CSVSchemaMigrator();
    CSVDataMigrator dataMigrator = new CSVDataMigrator();

    //
    try {
        MindmapsGraph graph = engineURL == null ? MindmapsClient.getGraph(graphName)
                : MindmapsClient.getGraph(graphName, engineURL);

        Loader loader = engineURL == null ? new BlockingLoader(graphName)
                : new DistributedLoader(graphName, Lists.newArrayList(engineURL));

        CSVParser csvParser = CSVParser.parse(csvFile.toURI().toURL(), StandardCharsets.UTF_8,
                CSVFormat.DEFAULT.withHeader());

        schemaMigrator.graph(graph).configure(csvEntityType, csvParser).migrate(loader);

        System.out.println("Schema migration successful");

        dataMigrator.graph(graph).configure(csvEntityType, csvParser).migrate(loader);

        System.out.println("DataType migration successful");

    } catch (Throwable throwable) {
        throwable.printStackTrace(System.err);
    }

    System.exit(0);
}

From source file:com.ontotext.s4.SBTDemo.Main.java

public static void main(String[] args) {
    /*/* ww  w . j a va 2  s  .  co m*/
     * Read log4j properties file.
     */
    org.apache.log4j.PropertyConfigurator.configure(args.length >= 1 ? args[1] : DEFAULT_LOG4J_FILE);

    /*
     * Read properties file  List all annotated files. We should
     * use absolute path to the files
     */
    init(args);

    ProcessingDocuments processingDocuments = new ProcessingDocuments(
            programProperties.getProperty(PropertiesNames.S4_API_KEY),
            programProperties.getProperty(PropertiesNames.S4_API_PASS),
            programProperties.getProperty(PropertiesNames.RAW_FOLDER),
            programProperties.getProperty(PropertiesNames.ANNOTATED_FOLDER),
            programProperties.getProperty(PropertiesNames.SERVICE),
            programProperties.getProperty(PropertiesNames.MIME_TYPE),
            programProperties.getProperty(PropertiesNames.RESPONSE_FORMAT),
            Integer.parseInt(programProperties.getProperty(PropertiesNames.NUMBER_OF_THREADS)));

    processingDocuments.ProcessData();

    File directory = new File(programProperties.getProperty(PropertiesNames.ANNOTATED_FOLDER));
    listOfAllAnnotatedFiles = FileUtils.listFiles(directory, new RegexFileFilter("^(.*?)"),
            DirectoryFileFilter.DIRECTORY);

    RepoManager repoManager = new RepoManager(programProperties.getProperty(PropertiesNames.REPOSITORY_URL));
    JsonToRDF jsonToRdfParser = new JsonToRDF(programProperties.getProperty(PropertiesNames.MIME_TYPE),
            programProperties.getProperty(PropertiesNames.RDFIZE_FOLDER));

    for (File file : listOfAllAnnotatedFiles) {
        String fileContent = null;
        try {
            fileContent = FileUtils.readFileToString(file, "UTF-8");
        } catch (IOException e) {
            logger.error(e);
        }

        Model graph = jsonToRdfParser.wirteDataToRDF(fileContent, file.getName(),
                programProperties.getProperty(PropertiesNames.RDFIZE_FOLDER));
        try {
            repoManager.sendDataTOGraphDB(graph);
        } catch (RepositoryException e) {
            logger.error(e);
        }

    }

    repoManager.close();
}

From source file:mil.tatrc.physiology.biogears.verification.ScenarioPlotTool.java

public static void main(String[] args) {
    if (args.length < 1) {
        Log.fatal("Expected inputs : [results file path] [result in results file NOT to plot] ");
        return;// w  w w  .  ja  v a2s.c om
    }
    File f = new File(args[0]);
    if (!f.exists()) {
        Log.fatal("Input file cannot be found");
        return;
    }
    String reportDir = "./graph_results/" + f.getName();
    reportDir = reportDir.substring(0, reportDir.lastIndexOf(".")) + "/";
    ScenarioPlotTool t = new ScenarioPlotTool();
    t.graphResults(args[0], reportDir);
}

From source file:ai.emot.demo.EmotAIDemo.java

public static void main(String[] args) throws IOException, InterruptedException {
    if (args.length != 2) {
        printUsage();/*www.j  a  va2 s .c  o  m*/
        System.exit(0);
    }

    String emotAIAPIBaseUrl = args[0];
    String accessToken = args[1];

    PathMatchingResourcePatternResolver fileResolver = new PathMatchingResourcePatternResolver(
            EmotAIDemo.class.getClassLoader());
    Resource[] resources = fileResolver.getResources("images");
    File dir = resources[0].getFile();
    File imagesDir = new File(dir, "/face/cropped");

    EmotAI emotAI = new EmotAITemplate(emotAIAPIBaseUrl, accessToken);

    // Create a display for the images
    ImageDisplay<Long> imageDisplay = new ImageDisplay<Long>(250, 250);

    for (File imageFile : imagesDir.listFiles(new JpegFileFilter())) {
        // Read each image
        BufferedImage image = ImageIO.read(imageFile);

        // Get the emotion profile for each image
        EmotionProfile emotionProfile = emotAI.emotionOperations().getFaceImageEmotionProfile(image);

        // Output emotion, and display image
        System.out.println(imageFile.getName() + " : " + emotionProfile);
        imageDisplay.onFrameUpdate(new SerializableBufferedImageAdapter(image), 1l);

        // Sleep for 1 second
        Thread.sleep(1000);

    }

    System.exit(1);
}

From source file:com.turn.ttorrent.cli.TorrentMain.java

/**
 * Torrent reader and creator.//from  ww w .ja  v  a2 s  .  co m
 *
 * <p>
 * You can use the {@code main()} function of this class to read or create
 * torrent files. See usage for details.
 * </p>
 *
 */
public static void main(String[] args) {
    BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%-5p: %m%n")));

    CmdLineParser parser = new CmdLineParser();
    CmdLineParser.Option help = parser.addBooleanOption('h', "help");
    CmdLineParser.Option filename = parser.addStringOption('t', "torrent");
    CmdLineParser.Option create = parser.addBooleanOption('c', "create");
    CmdLineParser.Option pieceLength = parser.addIntegerOption('l', "length");
    CmdLineParser.Option announce = parser.addStringOption('a', "announce");

    try {
        parser.parse(args);
    } catch (CmdLineParser.OptionException oe) {
        System.err.println(oe.getMessage());
        usage(System.err);
        System.exit(1);
    }

    // Display help and exit if requested
    if (Boolean.TRUE.equals((Boolean) parser.getOptionValue(help))) {
        usage(System.out);
        System.exit(0);
    }

    String filenameValue = (String) parser.getOptionValue(filename);
    if (filenameValue == null) {
        usage(System.err, "Torrent file must be provided!");
        System.exit(1);
    }

    Integer pieceLengthVal = (Integer) parser.getOptionValue(pieceLength);
    if (pieceLengthVal == null) {
        pieceLengthVal = Torrent.DEFAULT_PIECE_LENGTH;
    } else {
        pieceLengthVal = pieceLengthVal * 1024;
    }
    logger.info("Using piece length of {} bytes.", pieceLengthVal);

    Boolean createFlag = (Boolean) parser.getOptionValue(create);

    //For repeated announce urls
    @SuppressWarnings("unchecked")
    Vector<String> announceURLs = (Vector<String>) parser.getOptionValues(announce);

    String[] otherArgs = parser.getRemainingArgs();

    if (Boolean.TRUE.equals(createFlag) && (otherArgs.length != 1 || announceURLs.isEmpty())) {
        usage(System.err,
                "Announce URL and a file or directory must be " + "provided to create a torrent file!");
        System.exit(1);
    }

    OutputStream fos = null;
    try {
        if (Boolean.TRUE.equals(createFlag)) {
            if (filenameValue != null) {
                fos = new FileOutputStream(filenameValue);
            } else {
                fos = System.out;
            }

            //Process the announce URLs into URIs
            List<URI> announceURIs = new ArrayList<URI>();
            for (String url : announceURLs) {
                announceURIs.add(new URI(url));
            }

            //Create the announce-list as a list of lists of URIs
            //Assume all the URI's are first tier trackers
            List<List<URI>> announceList = new ArrayList<List<URI>>();
            announceList.add(announceURIs);

            File source = new File(otherArgs[0]);
            if (!source.exists() || !source.canRead()) {
                throw new IllegalArgumentException(
                        "Cannot access source file or directory " + source.getName());
            }

            String creator = String.format("%s (ttorrent)", System.getProperty("user.name"));

            Torrent torrent = null;
            if (source.isDirectory()) {
                List<File> files = new ArrayList<File>(
                        FileUtils.listFiles(source, TrueFileFilter.TRUE, TrueFileFilter.TRUE));
                Collections.sort(files);
                torrent = Torrent.create(source, files, pieceLengthVal, announceList, creator);
            } else {
                torrent = Torrent.create(source, pieceLengthVal, announceList, creator);
            }

            torrent.save(fos);
        } else {
            Torrent.load(new File(filenameValue), true);
        }
    } catch (Exception e) {
        logger.error("{}", e.getMessage(), e);
        System.exit(2);
    } finally {
        if (fos != System.out) {
            IOUtils.closeQuietly(fos);
        }
    }
}

From source file:com.meltmedia.rodimus.RodimusCli.java

public static void main(String... args) {
    try {/* www . j  a v a2 s. c  o  m*/
        final Cli<RodimusInterface> cli = CliFactory.createCli(RodimusInterface.class);
        final RodimusInterface options = cli.parseArguments(args);

        // if help was requested, then display the help message and exit.
        if (options.isHelp()) {
            System.out.println(cli.getHelpMessage());
            return;
        }

        final boolean verbose = options.isVerbose();

        if (options.getFiles() == null || options.getFiles().size() < 1) {
            System.out.println(cli.getHelpMessage());
            return;
        }

        // get the input file.
        File inputFile = options.getFiles().get(0);

        // get the output file.
        File outputDir = null;
        if (options.getFiles().size() > 1) {
            outputDir = options.getFiles().get(1);
        } else {
            outputDir = new File(inputFile.getName().replaceFirst("\\.[^.]+\\Z", ""));
        }
        if (outputDir.exists() && !outputDir.isDirectory()) {
            throw new Exception(outputDir + " is not a directory.");
        }
        outputDir.mkdirs();

        transformDocument(inputFile, outputDir, verbose);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}