Example usage for java.util ArrayList get

List of usage examples for java.util ArrayList get

Introduction

In this page you can find the example usage for java.util ArrayList get.

Prototype

public E get(int index) 

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:ISMAGS.CommandLineInterface.java

public static void main(String[] args) throws IOException {
    String folder = null, files = null, motifspec = null, output = null;

    Options opts = new Options();
    opts.addOption("folder", true, "Folder name");
    opts.addOption("linkfiles", true,
            "Link files seperated by spaces (format: linktype[char] directed[d/u] filename)");
    opts.addOption("motif", true, "Motif description by two strings (format: linktypes)");
    opts.addOption("output", true, "Output file name");

    CommandLineParser parser = new PosixParser();
    try {//from   www. j  a v  a  2 s . c o m
        CommandLine cmd = parser.parse(opts, args);
        if (cmd.hasOption("folder")) {
            folder = cmd.getOptionValue("folder");
        }
        if (cmd.hasOption("linkfiles")) {
            files = cmd.getOptionValue("linkfiles");
        }
        if (cmd.hasOption("motif")) {
            motifspec = cmd.getOptionValue("motif");
        }
        if (cmd.hasOption("output")) {
            output = cmd.getOptionValue("output");
        }
    } catch (ParseException e) {
        Die("Error: Parsing error");
    }

    if (print) {
        printBanner(folder, files, motifspec, output);
    }

    if (folder == null || files == null || motifspec == null || output == null) {
        Die("Error: not all options are provided");
    } else {
        ArrayList<String> linkfiles = new ArrayList<String>();
        ArrayList<String> linkTypes = new ArrayList<String>();
        ArrayList<String> sourcenetworks = new ArrayList<String>();
        ArrayList<String> destinationnetworks = new ArrayList<String>();
        ArrayList<Boolean> directed = new ArrayList<Boolean>();
        StringTokenizer st = new StringTokenizer(files, " ");
        while (st.hasMoreTokens()) {
            linkTypes.add(st.nextToken());
            directed.add(st.nextToken().equals("d"));
            sourcenetworks.add(st.nextToken());
            destinationnetworks.add(st.nextToken());
            linkfiles.add(folder + st.nextToken());
        }
        ArrayList<LinkType> allLinkTypes = new ArrayList<LinkType>();
        HashMap<Character, LinkType> typeTranslation = new HashMap<Character, LinkType>();
        for (int i = 0; i < linkTypes.size(); i++) {
            String n = linkTypes.get(i);
            char nn = n.charAt(0);
            LinkType t = typeTranslation.get(nn);
            if (t == null) {
                t = new LinkType(directed.get(i), n, i, nn, sourcenetworks.get(i), destinationnetworks.get(i));
            }
            allLinkTypes.add(t);
            typeTranslation.put(nn, t);
        }
        if (print) {
            System.out.println("Reading network..");
        }
        Network network = Network.readNetworkFromFiles(linkfiles, allLinkTypes);

        Motif motif = getMotif(motifspec, typeTranslation);

        if (print) {
            System.out.println("Starting the search..");
        }
        MotifFinder mf = new MotifFinder(network);
        long tijd = System.nanoTime();
        Set<MotifInstance> motifs = mf.findMotif(motif, false);
        tijd = System.nanoTime() - tijd;
        if (print) {
            System.out.println("Completed search in " + tijd / 1000000 + " milliseconds");
        }
        if (print) {
            System.out.println("Found " + motifs.size() + " instances of " + motifspec + " motif");
        }
        if (print) {
            System.out.println("Writing instances to file: " + output);
        }
        printMotifs(motifs, output);
        if (print) {
            System.out.println("Done.");
        }
        //            Set<MotifInstance> motifs=null;
        //            MotifFinder mf=null;
        //            System.out.println("Starting the search..");
        //            long tstart = System.nanoTime();
        //            for (int i = 0; i < it; i++) {
        //
        //                mf = new MotifFinder(network, allLinkTypes, true);
        //                motifs = mf.findMotif(motif);
        //            }
        //
        //            long tend = System.nanoTime();
        //            double time_in_ms = (tend - tstart) / 1000000.0;
        //            System.out.println("Found " + mf.totalFound + " motifs, " + time_in_ms + " ms");
        ////        System.out.println("Evaluated " + mf.totalNrMappedNodes+ " search nodes");
        ////        System.out.println("Found " + motifs.size() + " motifs, " + time_in_ms + " ms");
        //            printMotifs(motifs, output);

    }

}

From source file:at.tuwien.aic.Main.java

/**
 * Main entry point/*from w  ww .j a v a 2 s .c o  m*/
 *
 * @param args
 */
@SuppressWarnings("empty-statement")
public static void main(String[] args) throws IOException, InterruptedException {

    try {
        System.out.println(new java.io.File(".").getCanonicalPath());
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

    TweetCrawler tc = null;

    try {
        tc = TweetCrawler.getInstance();
    } catch (UnknownHostException ex) {
        logger.severe("Could not connect to mongoDb");
        exitWithError(2);
        return;
    }

    int action;

    while (true) {
        action = getDecision("The following actions can be executed",
                new String[] { "Subscribe to topic", "Query topic", "Test preprocessing",
                        "Recreate the evaluation model", "Quit the application" },
                "What action do you want to execute?");

        switch (action) {
        case 1:
            tc.collectTweets(new DefaultTweetHandler() {
                @Override
                public boolean isMatch(String topic) {
                    return true;
                }
            }, getNonEmptyString(
                    "Which topic do you want to subscribe to (use spaces to specify more than one keyword)?")
                            .split(" "));

            System.out.println("Starting to collection tweets");
            System.out.println("Press enter to quit collecting");

            while (System.in.read() != 10)
                ;

            tc.stopCollecting();

            break;
        case 2:
            System.out.println("Enter tweet");
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String tweet = br.readLine();
            //double prediction = ClassifyTweet.classifyTweets(c, tweet, 2);
            System.exit(0);
            //classifyTopic();
            break;
        case 3:
            int subAction = getDecision("The following preprocessing steps are available",
                    new String[] { "Stop word removal", "Stemming", "Both" }, "What do you want to test?");

            switch (subAction) {
            case 1:
                stopWords();
                break;
            case 2:
                stem();
                break;
            case 3:
                stem(stopWords());
            default:
                break;
            }

            break;
        case 4:
            //ClassifyTweet.classifyTweetArff(c, "resources/unlabeled.arff", "resources/train.arff");
            ArrayList<String> tweets = new ArrayList<>();
            ArrayList<String> processedTweets = new ArrayList<>();

            //Positive Tweets
            tweets.add(
                    "#Office365 is the fastest growing business in Microsofts history, one out of four enterprise clients owns #Office365 in the past 12 months");
            tweets.add("oh yeah back to microsoft word it's great haha");
            tweets.add(
                    "Microsoft Visual Studio 2013 Ultimate: excellent tool, but a bit pricey at $13K - http://t.co/qbc4MHeOrF");
            tweets.add(
                    "Apple 'absolutely' plans to release new product types this year - Design Week: Design WeekApple 'absolutely' p... http://t.co/EK4rIbaHa0");
            tweets.add(
                    "RT @ReformedBroker: \"Apple can't innovate.\" Motherf***er you're watching a movie on a 4 ounce plate of glass.");
            tweets.add(
                    "What's the best brand of shoes?! Lol. There's too damn many, what do you prefer. Me is some Adidas.");
            tweets.add(
                    "I want ?? @AdorableWords: Tribal/Aztec pattern Nike free runs ?? http://t.co/WBxT8CNsPN?");
            tweets.add(
                    "I achieved the Streak Week trophy with my Nike+ FuelBand. #nikeplus http://t.co/OgtpRcoSvp");
            tweets.add("RT @DriveOfAthletes: Retweet for Nike! Favorite for UA! http://t.co/sKZ8hb27xH");

            //Neutral Tweets
            tweets.add("This site is giving away Free Microsoft Points #XBOX LIVE http://t.co/ZR1ythfqJ4");
            tweets.add(
                    "How To Save The World: 1. Open Microsoft Word. 2. In a size 12-36 font, type \"The World\". 3. Click save.");
            tweets.add(
                    "Microsoft Special Deals for Education: Microsoft special deals for Students, faculty and staff: http://t.co/Hf0b2ixPZa");
            tweets.add(
                    "Microsoft is about to take Windows XP off life support On April 8, Windows XP's life is coming to an end. On that d http://t.co/kcSf4uIqW4");
            tweets.add("Microsoft open sources its internet servers http://t.co/oLNTlVjE6Y");
            tweets.add(
                    "The Apple Macintosh computer turns 30 - ... http://t.co/CAfq09Jgn7 #CarlIcahn #IsaacsonIt #SteveJobs #WalterIsaacson");
            tweets.add(
                    "News Update| Samsung opens 60 dedicated stores in Europe with Carphone Warehouse http://t.co/1voh4yPMpN");
            tweets.add("I posted a new photo to Facebook http://t.co/fI40hwklUj");
            tweets.add(
                    "Brand New Men's ADIDAS VIGOR TR 3 Athletic Running shoes. Size: 11.5 http://t.co/oPuFoXLpeI");
            tweets.add("I just ran 2.58 mi with Nike+. http://t.co/pYLkhBxH4Y #nikeplus");
            tweets.add("Why is facebook still a thing");

            //Negative Tweets
            tweets.add("Thank God for microsoft programs.....");
            tweets.add(
                    "RT @verge: UK government once again threatens to ditch Microsoft Office http://t.co/vhvybI1GwI");
            tweets.add("Apple charge far too much for very poor phone cases");
            tweets.add("Here's Why Everyone Is Worried About Apple's iPhone Sales http://t.co/Eq3oPt76AG");
            tweets.add("Is Apple Ready to Disrupt Another Industry? http://t.co/07gedlN0cs via @zite");
            tweets.add(
                    "Tim Cook Officially Admits iPhone 5c Didnt Meet Expectations http://t.co/OdzGZOmdv7 #iPhone #Apple");
            tweets.add("@MushIsAJedi @HeyItsAmine i dont rlly like samsung that much");
            tweets.add("twitter facebook die shit");
            tweets.add(
                    "I am thinking of leaving Facebook for a while... To much spying going on.. I am sick and tired of thinking about... http:/)/t.co/ULydkDEube");
            tweets.add("RT @OfficialSheIdon: RIP Facebook, too many of our parents joined.");

            StopWordRemoval swr = new StopWordRemoval("resources/stopwords.txt");

            for (String t : tweets) {
                t = swr.processText(t);
                processedTweets.add(t);
            }

            for (int i = 0; i < 28; i++) {
                if (i != 4) {
                    ArrayList<Integer> results = ClassifyTweet.classifyTweets(processedTweets, i);

                    int correctCount = 0;
                    int positiveCorrect = 0;
                    int neutralCorrect = 0;
                    int negativeCorrect = 0;
                    int falsePosNeu = 0;
                    int falsePosNeg = 0;
                    int falseNeuPos = 0;
                    int falseNeuNeg = 0;
                    int falseNegNeu = 0;
                    int falseNegPos = 0;

                    for (int j = 0; j < 30; j++) {
                        int pred = results.get(j);

                        if (j >= 0 && j < 10) {
                            if (pred == 1) {
                                correctCount++;
                                positiveCorrect++;
                            } else if (pred == 0) {
                                falsePosNeu++;
                            } else if (pred == -1) {
                                falsePosNeg++;
                            }
                        } else if (j >= 10 && j < 20) {
                            if (pred == 0) {
                                correctCount++;
                                neutralCorrect++;
                            } else if (pred == 1) {
                                falseNeuPos++;
                            } else if (pred == -1) {
                                falseNeuNeg++;
                            }

                        } else if (j >= 20 && j < 30) {
                            if (pred == -1) {
                                correctCount++;
                                negativeCorrect++;
                            } else if (pred == 0) {
                                falseNegNeu++;
                            } else if (pred == 1) {
                                falseNegPos++;
                            }
                        }
                    }

                    System.out.println("Correct Predictions: " + correctCount + " / 30");
                    System.out.println("Correct Positive: " + positiveCorrect + " / 10");
                    System.out.println("Correct Neutral: " + neutralCorrect + " / 10");
                    System.out.println("Correct Negative: " + negativeCorrect + " / 10");

                    System.out.println("False Positive as Neutral: " + falsePosNeu);
                    System.out.println("False Positive as Negative: " + falsePosNeg);

                    System.out.println("False Neutral as Positive: " + falseNeuPos);
                    System.out.println("False Neutral as Negative: " + falseNeuNeg);

                    System.out.println("False Negative as Positive: " + falseNegPos);
                    System.out.println("False Negative as Neutral: " + falseNegNeu);
                }

            }

            exit();
        case 5:
            exit();
        }
    }
}

From source file:no.uio.medicine.virsurveillance.charts.BoxAndWhiskerChart_AWT.java

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

    //Log.getInstance().addTarget(new PrintStreamLogTarget(System.out));
    ArrayList<ArrayList<ArrayList<Float>>> dataPoints = new ArrayList<>();
    ArrayList<String> titles = new ArrayList<>();
    ArrayList<ArrayList<String>> categories = new ArrayList<>();

    for (int i = 0; i < 2; i++) {
        ArrayList<ArrayList<Float>> serie = new ArrayList<>();
        titles.add("Serie " + i);

        ArrayList<String> categoriesPerSerie = new ArrayList<>();
        int max = i + 2;
        for (int j = 0; j < max; j++) {
            ArrayList<Float> points = new ArrayList<>();
            for (int k = 0; k < 50; k++) {
                points.add((float) (i * 10 + Math.random() * 50));
            }//  w  ww. ja  v a  2  s. com
            serie.add(points);
            categoriesPerSerie.add("Categorie" + j);
        }
        dataPoints.add(serie);
        categories.add(categoriesPerSerie);

    }

    final BoxAndWhiskerChart_AWT demo = new BoxAndWhiskerChart_AWT("A", "B", "C", "D", dataPoints, categories,
            titles);

    final BoxAndWhiskerChart_AWT demo2 = new BoxAndWhiskerChart_AWT("A2", "B2", "C2", "D2", dataPoints.get(0),
            categories.get(0), titles.get(0));

    demo.updateChartData();
    demo2.updateChartData();

}

From source file:edu.oregonstate.eecs.mcplan.ml.KulisLowRankKernelLearner.java

/**
 * @param args/*www . ja v  a 2s .c  om*/
 */
public static void main(final String[] args) {
    final RandomGenerator rng = new MersenneTwister(42);
    final int d = 2;
    final double u = 5.0;
    final double ell = 7.0;
    final double gamma = 1.0;
    final ArrayList<RealVector> X = new ArrayList<RealVector>();
    final RealMatrix A0 = MatrixUtils.createRealIdentityMatrix(d);

    for (final int w : new int[] { 0, 5 }) {
        for (final int h : new int[] { 0, 5 }) {
            for (int x = -1; x <= 1; ++x) {
                for (int y = -1; y <= 1; ++y) {
                    X.add(new ArrayRealVector(new double[] { x + w, y + h }));
                }
            }
        }
    }

    final ArrayList<int[]> S = new ArrayList<int[]>();
    S.add(new int[] { 4, 31 }); // Must link diagonally
    final ArrayList<int[]> D = new ArrayList<int[]>();
    D.add(new int[] { 4, 13 });
    D.add(new int[] { 22, 31 });
    D.add(new int[] { 13, 22 }); // Cannot link vertically

    final KulisLowRankKernelLearner itml = new KulisLowRankKernelLearner(X, S, D, u, ell, A0, gamma, rng);
    itml.run();

    final RealMatrix A = itml.A();

    System.out.println(A0.toString());

    for (final int[] c : S) {
        final RealVector diff = X.get(c[0]).subtract(X.get(c[1]));
        System.out.println(diff.dotProduct(A0.operate(diff)));
    }
    for (final int[] c : D) {
        final RealVector diff = X.get(c[0]).subtract(X.get(c[1]));
        System.out.println(diff.dotProduct(A0.operate(diff)));
    }

    System.out.println(A.toString());

    for (final int[] c : S) {
        final RealVector diff = X.get(c[0]).subtract(X.get(c[1]));
        System.out.println(diff.dotProduct(A.operate(diff)));
    }
    for (final int[] c : D) {
        final RealVector diff = X.get(c[0]).subtract(X.get(c[1]));
        System.out.println(diff.dotProduct(A.operate(diff)));
    }

    //      int i = 0;
    //      for( final int w : new int[] { 0, 5 } ) {
    //         for( final int h : new int[] { 0, 5 } ) {
    //            for( int x = -1; x <= 1; ++x ) {
    //               for( int y = -1; y <= 1; ++y ) {
    //                  System.out.println( itml.A().operate( X.get( i++ ) ) );
    //               }
    //            }
    //         }
    //      }
}

From source file:eu.cognitum.readandwrite.App.java

public static void main(String[] args) {
    try {/*from  w  w w .  j  ava 2s  .c o m*/
        String configFile = 0 == args.length ? "example.properties" : args[0];

        CONFIGURATION = new Properties();
        File f = new File(configFile);
        if (!f.exists()) {
            LOGGER.warning("configuration not found at " + configFile);
            return;
        }
        LOGGER.info("loading configuration file " + f.getAbsoluteFile());
        CONFIGURATION.load(new FileInputStream(f));

        String ip = CONFIGURATION.getProperty(PROP_STORAGE_HOSTNAME);
        String keyspace = CONFIGURATION.getProperty(PROP_STORAGE_KEYSPACE);
        String directory = CONFIGURATION.getProperty(PROP_STORAGE_DIRECTORY);

        // N of articles to be generated.
        int Narticles = 100000;
        // size of the buffer to commit each time
        int commitBufferSize = 100;
        // N of articles to commit before trying reads
        int readStep = 100;

        String currentNamespace = "http://mynamespace#";
        LOGGER.log(Level.INFO, "Generating the rdf...");
        GenerateRdf rdfGenerator = new GenerateRdf(currentNamespace, "tmp.rdf");
        rdfGenerator.generateAndSaveRdf(Narticles);
        LOGGER.log(Level.INFO, "Generated the rdf!");
        ArrayList<SimulateReadAndWrite> simulateAll = new ArrayList<SimulateReadAndWrite>();

        int Ndbs = 0;

        DBS[] chosenDbs = { DBS.NATIVE };
        //DBS[] chosenDbs = DBS.values();

        for (DBS dbs : chosenDbs) {
            SailRepository sr;

            switch (dbs) {
            case NATIVE:
                sr = createNativeStoreConnection(directory);
                break;
            case TITAN:
                sr = createTitanConnection(ip, keyspace);
                break;
            case NEO4J:
                sr = createNeo4jConnection(keyspace);
                break;
            case ORIENT:
                sr = createOrientConnection(keyspace);
                break;
            default:
                sr = null;
                break;
            }

            if (sr == null) {
                throw new Exception("Something wrong while connecting to " + dbs.toString());
            }

            simulateAll.add(new SimulateReadAndWrite(sr, "test" + dbs.toString(), Narticles, readStep,
                    commitBufferSize, dbs.toString(), keyspace, currentNamespace, rdfGenerator));

            simulateAll.get(Ndbs).start();
            Ndbs++;
        }

        int Nfinished = 0;
        int k;
        while (Nfinished != Ndbs) {
            Nfinished = 0;
            k = 0;
            for (DBS dbs : chosenDbs) {
                if (simulateAll.get(k).IsProcessCompleted()) {
                    Nfinished++;
                } else {
                    System.out.println(String.format("Process for db %s is at %.2f", dbs.toString(),
                            simulateAll.get(k).GetProgress()));
                }
                k++;
            }
            Thread.sleep(10000);
        }

    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    }
}

From source file:metaTile.Main.java

/**
 * @param args/*  w w w.  j a v  a 2  s .co  m*/
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    try {
        /* parse the command line arguments */
        // create the command line parser
        CommandLineParser parser = new PosixParser();

        // create the Options
        Options options = new Options();
        options.addOption("i", "input", true, "File to read original tile list from.");
        options.addOption("o", "output", true, "File to write shorter meta-tile list to.");
        options.addOption("m", "metatiles", true,
                "Number of tiles in x and y direction to group into one meta-tile.");

        // parse the command line arguments
        CommandLine commandLine = parser.parse(options, args);

        if (!commandLine.hasOption("input") || !commandLine.hasOption("output")
                || !commandLine.hasOption("metatiles"))
            printUsage(options);

        String inputFileName = commandLine.getOptionValue("input");
        String outputFileName = commandLine.getOptionValue("output");
        int metaTileSize = Integer.parseInt(commandLine.getOptionValue("metatiles"));

        ArrayList<RenderingTile> tiles = new ArrayList<RenderingTile>();

        BufferedReader tileListReader = new BufferedReader(new FileReader(new File(inputFileName)));

        BufferedWriter renderMetatileListWriter = new BufferedWriter(new FileWriter(new File(outputFileName)));

        String line = tileListReader.readLine();
        while (line != null) {
            String[] columns = line.split("/");

            if (columns.length == 3)
                tiles.add(new RenderingTile(Integer.parseInt(columns[0]), Integer.parseInt(columns[1]),
                        Integer.parseInt(columns[2])));

            line = tileListReader.readLine();
        }

        tileListReader.close();

        int hits = 0;

        // tiles which we are already rendering as the top left corner of 4x4 metatiles
        HashSet<RenderingTile> whitelist = new HashSet<RenderingTile>();

        // for each tile in the list see if it has a meta-tile in the whitelist already
        for (int i = 0; i < tiles.size(); i++) {
            boolean hit = false; // by default we aren't already rendering this tile as part of another metatile
            for (int dx = 0; dx < metaTileSize; dx++) {
                for (int dy = 0; dy < metaTileSize; dy++) {
                    RenderingTile candidate = new RenderingTile(tiles.get(i).z, tiles.get(i).x - dx,
                            tiles.get(i).y - dy);
                    if (whitelist.contains(candidate)) {
                        hit = true;
                        // now exit the two for loops iterating over tiles inside a meta-tile
                        dx = metaTileSize;
                        dy = metaTileSize;
                    }
                }
            }

            // if this tile doesn't already have a meta-tile in the whitelist, add it
            if (hit == false) {
                hits++;
                renderMetatileListWriter.write(tiles.get(i).toString() + "/" + metaTileSize + "\n");
                whitelist.add(tiles.get(i));
            }
        }
        renderMetatileListWriter.close();
        System.out.println(
                "Reduced " + tiles.size() + " tiles into " + hits + " metatiles of size " + metaTileSize);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.oregonstate.eecs.mcplan.ml.KMeans.java

/**
 * @param args//from ww  w.  j  a v a2  s  .  com
 */
public static void main(final String[] args) {
    final int nclusters = 2;
    final ArrayList<RealVector> data = new ArrayList<RealVector>();

    for (int x = -1; x <= 1; ++x) {
        for (int y = -1; y <= 1; ++y) {
            data.add(new ArrayRealVector(new double[] { x, y }));
            data.add(new ArrayRealVector(new double[] { x + 10, y + 10 }));
        }
    }

    final KMeans kmeans = new KMeans(nclusters, data.toArray(new RealVector[data.size()])); /* {
                                                                                            @Override
                                                                                            public double distance( final RealVector a, final RealVector b ) {
                                                                                            return a.getL1Distance( b );
                                                                                            }
                                                                                            };
                                                                                            */

    kmeans.run();
    for (int i = 0; i < kmeans.centers().length; ++i) {
        System.out.println("Center " + i + ": " + kmeans.centers()[i]);
        for (int j = 0; j < kmeans.clusters().length; ++j) {
            if (kmeans.clusters()[j] == i) {
                System.out.println("\tPoint " + data.get(j));
            }
        }
    }

}

From source file:org.isaacphysics.labs.chemistry.checker.RunParser.java

public static void main(String args[]) throws Exception {
    //noinspection deprecation (We know DefaultSymbolFactory is depracated!)
    ArrayList<Statement> statements = (ArrayList<Statement>) new ChemistryParser(
            new ChemistryLexer(new InputStreamReader(new FileInputStream("src/test.txt"))),
            new DefaultSymbolFactory()).parse().value;
    System.err.flush();//from   ww  w. j a va2  s  .c  o m
    System.out.flush();
    System.out.println();
    for (Statement statement : statements) {
        System.out.println(statement);
        if (statement instanceof ExpressionStatement) {
            System.out.println("Total atoms: " + ((ExpressionStatement) statement).getAtomCount());
            System.out.println("Total charge: " + ((ExpressionStatement) statement).getCharge());
        } else if (statement instanceof EquationStatement) {
            System.out.println("Is balanced? " + ((EquationStatement) statement).isBalanced());
            System.out.println(
                    "Total atoms LHS: " + ((EquationStatement) statement).getLeftExpression().getAtomCount());
            System.out.println(
                    "Total atoms RHS: " + ((EquationStatement) statement).getRightExpression().getAtomCount());
            System.out.println(
                    "Total charge LHS: " + ((EquationStatement) statement).getLeftExpression().getCharge());
            System.out.println(
                    "Total charge RHS: " + ((EquationStatement) statement).getRightExpression().getCharge());
        }
        System.out.println("\n");
    }

    System.out.println();
    EquationStatement a = (EquationStatement) statements.get(5);
    EquationStatement b = (EquationStatement) statements.get(6);
    if (a.equals(b)) {
        System.out.println("\"" + a.toString() + "\" == \"" + b.toString() + "\"");
        if (!b.equals(a)) {
            System.err.println("Equality not symmetric!");
        }
    } else {
        System.out.println("\"" + a.toString() + "\" != \"" + b.toString() + "\"");
        if (b.equals(a)) {
            System.err.println("Equality not symmetric!");
        }
    }
}

From source file:jCloisterZone.CarcassonneEnvironment.java

public static void main(String[] args) {
    int repetitions = 100;
    double[] scores = new double[repetitions];

    RRLJCloisterClient client = new LocalCarcassonneClient("config.ini");
    ServerIF server = null;//from w w w.j av a  2  s  .  c o  m
    Game game = client.getGame();
    Player firstPlayer = null;
    ArrayList<PlayerSlot> slots = new ArrayList<PlayerSlot>();
    for (int r = 0; r < repetitions; r++) {
        client.createGame();
        if (game == null) {
            server = new LocalCarcassonneServer(client.getGame());
            PlayerSlot slot = new PlayerSlot(0, PlayerSlot.SlotType.AI, "RANDOM" + 0, client.getClientId());
            slot.setAiClassName(RandomAIPlayer.class.getName());
            slots.add(slot);
            for (int j = 1; j < Integer.parseInt(args[0]); j++) {
                slot = new PlayerSlot(j, PlayerSlot.SlotType.AI, "AI" + j, client.getClientId());
                slot.setAiClassName(LegacyAiPlayer.class.getName());
                slots.add(slot);
            }
            game = client.getGame();
        } else {
            // Reset the UIs
            server.stopGame();
            game.clearUserInterface();

            // Clear the slots and re-add them.
            for (int i = 0; i < PlayerSlot.COUNT; i++) {
                server.updateSlot(new PlayerSlot(i), null);
            }
        }

        Collections.shuffle(slots);
        for (int i = 0; i < slots.size(); i++) {
            PlayerSlot slot = slots.get(i);
            PlayerSlot cloneSlot = new PlayerSlot(i, slot.getType(), slot.getNick(), slot.getOwner());
            cloneSlot.setAiClassName(slot.getAiClassName());
            server.updateSlot(cloneSlot, LegacyAiPlayer.supportedExpansions());
        }

        server.startGame();

        Phase phase = game.getPhase();

        // Cycle through (probably only once) to keep the game moving.
        while (phase != null && !phase.isEntered()) {
            // Modifying phases to proxyless versions
            if (phase.getClass().equals(CreateGamePhase.class))
                phase = game.getPhases().get(ProxylessCreateGamePhase.class);
            if (phase.getClass().equals(DrawPhase.class))
                phase = game.getPhases().get(ProxylessDrawPhase.class);

            phase.setEntered(true);
            phase.enter();
            phase = game.getPhase();

            if (game.getTurnPlayer().getNick().equals("RANDOM0"))
                firstPlayer = game.getTurnPlayer();
        }
        int score = firstPlayer.getPoints();
        scores[r] = score;
        System.out.println(score);
    }

    Mean m = new Mean();
    StandardDeviation sd = new StandardDeviation();
    System.out.println("Mean: " + m.evaluate(scores) + ", SD: " + sd.evaluate(scores));
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step8GoldDataAggregator.java

public static void main(String[] args) throws Exception {
    String inputDir = args[0] + "/";
    // output dir
    File outputDir = new File(args[1]);
    File turkersConfidence = new File(args[2]);
    if (outputDir.exists()) {
        outputDir.delete();//from  w w  w.  j  a  v a 2  s.  c  o  m
    }
    outputDir.mkdir();

    List<String> annotatorsIDs = new ArrayList<>();
    //        for (File f : FileUtils.listFiles(new File(inputDir), new String[] { "xml" }, false)) {
    //            QueryResultContainer queryResultContainer = QueryResultContainer
    //                    .fromXML(FileUtils.readFileToString(f, "utf-8"));
    //            for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) {
    //                for (QueryResultContainer.MTurkRelevanceVote relevanceVote : rankedResults.mTurkRelevanceVotes) {
    //                    if (!annotatorsIDs.contains(relevanceVote.turkID))
    //                        annotatorsIDs.add(relevanceVote.turkID);
    //                }
    //            }
    //        }
    HashMap<String, Integer> countVotesForATurker = new HashMap<>();
    // creates temporary file with format for mace
    // Hashmap annotations: key is the id of a document and a sentence
    // Value is an array votes[] of turkers decisions: true or false (relevant or not)
    // the length of this array equals the number of annotators in List<String> annotatorsIDs.
    // If an annotator worked on the task his decision is written in the array otherwise the value is NULL

    // key: queryID + clueWebID + sentenceID
    // value: true and false annotations
    TreeMap<String, Annotations> annotations = new TreeMap<>();

    for (File f : FileUtils.listFiles(new File(inputDir), new String[] { "xml" }, false)) {
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));
        System.out.println("Reading " + f.getName());
        for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) {
            String documentID = rankedResults.clueWebID;
            for (QueryResultContainer.MTurkRelevanceVote relevanceVote : rankedResults.mTurkRelevanceVotes) {
                Integer turkerID;
                if (!annotatorsIDs.contains(relevanceVote.turkID)) {
                    annotatorsIDs.add(relevanceVote.turkID);
                    turkerID = annotatorsIDs.size() - 1;
                } else {
                    turkerID = annotatorsIDs.indexOf(relevanceVote.turkID);
                }
                Integer count = countVotesForATurker.get(relevanceVote.turkID);
                if (count == null) {
                    count = 0;
                }
                count++;
                countVotesForATurker.put(relevanceVote.turkID, count);

                String id;
                List<Integer> trueVotes;
                List<Integer> falseVotes;
                for (QueryResultContainer.SingleSentenceRelevanceVote singleSentenceRelevanceVote : relevanceVote.singleSentenceRelevanceVotes)
                    if (!"".equals(singleSentenceRelevanceVote.sentenceID)) {

                        id = f.getName() + "_" + documentID + "_" + singleSentenceRelevanceVote.sentenceID;
                        Annotations turkerVotes = annotations.get(id);
                        if (turkerVotes == null) {
                            trueVotes = new ArrayList<>();
                            falseVotes = new ArrayList<>();
                            turkerVotes = new Annotations(trueVotes, falseVotes);
                        }
                        trueVotes = turkerVotes.trueAnnotations;
                        falseVotes = turkerVotes.falseAnnotations;
                        if ("true".equals(singleSentenceRelevanceVote.relevant)) {
                            // votes[turkerID] = true;
                            trueVotes.add(turkerID);
                        } else if ("false".equals(singleSentenceRelevanceVote.relevant)) {
                            //   votes[turkerID] = false;
                            falseVotes.add(turkerID);
                        } else {
                            throw new IllegalStateException("Annotation value of sentence "
                                    + singleSentenceRelevanceVote.sentenceID + " in " + rankedResults.clueWebID
                                    + " equals " + singleSentenceRelevanceVote.relevant);
                        }
                        try {
                            int allVotesCount = trueVotes.size() + falseVotes.size();
                            if (allVotesCount > 5) {
                                System.err.println(id + " doesn't have 5 annotators: true: " + trueVotes.size()
                                        + " false: " + falseVotes.size());

                                // nasty hack, we're gonna strip some data; true votes first
                                /* we can't do that, it breaks something down the line
                                int toRemove = allVotesCount - 5;
                                if (trueVotes.size() >= toRemove) {
                                trueVotes = trueVotes
                                        .subList(0, trueVotes.size() - toRemove);
                                }
                                else if (
                                    falseVotes.size() >= toRemove) {
                                falseVotes = falseVotes
                                        .subList(0, trueVotes.size() - toRemove);
                                }
                                */
                                System.err.println("Adjusted: " + id + " doesn't have 5 annotators: true: "
                                        + trueVotes.size() + " false: " + falseVotes.size());
                            }
                        } catch (IllegalStateException e) {
                            e.printStackTrace();
                        }
                        turkerVotes.trueAnnotations = trueVotes;
                        turkerVotes.falseAnnotations = falseVotes;
                        annotations.put(id, turkerVotes);
                    } else {
                        throw new IllegalStateException(
                                "Empty Sentence ID in " + f.getName() + " for turker " + turkerID);
                    }

            }
        }

    }
    File tmp = printHashMap(annotations, annotatorsIDs.size());

    String file = TEMP_DIR + "/" + tmp.getName();
    MACE.main(new String[] { "--prefix", file });

    //gets the keys of the documents and sentences
    ArrayList<String> lines = (ArrayList<String>) FileUtils.readLines(new File(file + ".prediction"));
    int i = 0;
    TreeMap<String, TreeMap<String, ArrayList<HashMap<String, String>>>> ids = new TreeMap<>();
    ArrayList<HashMap<String, String>> sentences;
    if (lines.size() != annotations.size()) {
        throw new IllegalStateException(
                "The size of prediction file is " + lines.size() + "but expected " + annotations.size());
    }
    for (Map.Entry entry : annotations.entrySet()) { //1001.xml_clueweb12-1905wb-13-07360_8783
        String key = (String) entry.getKey();
        String[] IDs = key.split("_");
        if (IDs.length > 2) {
            String queryID = IDs[0];
            String clueWebID = IDs[1];
            String sentenceID = IDs[2];
            TreeMap<String, ArrayList<HashMap<String, String>>> clueWebIDs = ids.get(queryID);
            if (clueWebIDs == null) {
                clueWebIDs = new TreeMap<>();
            }
            sentences = clueWebIDs.get(clueWebID);
            if (sentences == null) {
                sentences = new ArrayList<>();
            }
            HashMap<String, String> sentence = new HashMap<>();
            sentence.put(sentenceID, lines.get(i));
            sentences.add(sentence);
            clueWebIDs.put(clueWebID, sentences);
            ids.put(queryID, clueWebIDs);
        } else {
            throw new IllegalStateException("Wrong ID " + key);
        }

        i++;
    }

    for (Map.Entry entry : ids.entrySet()) {
        TreeMap<Integer, String> value = (TreeMap<Integer, String>) entry.getValue();
        String queryID = (String) entry.getKey();
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(new File(inputDir, queryID), "utf-8"));
        for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) {
            for (Map.Entry val : value.entrySet()) {
                String clueWebID = (String) val.getKey();
                if (clueWebID.equals(rankedResults.clueWebID)) {
                    List<QueryResultContainer.SingleSentenceRelevanceVote> goldEstimatedLabels = new ArrayList<>();
                    List<QueryResultContainer.SingleSentenceRelevanceVote> turkersVotes = new ArrayList<>();
                    int size = 0;
                    int hitSize = 0;
                    String hitID = "";
                    for (QueryResultContainer.MTurkRelevanceVote vote : rankedResults.mTurkRelevanceVotes) {
                        if (!hitID.equals(vote.hitID)) {
                            hitID = vote.hitID;
                            hitSize = vote.singleSentenceRelevanceVotes.size();
                            size = size + hitSize;
                            turkersVotes.addAll(vote.singleSentenceRelevanceVotes);
                        } else {
                            if (vote.singleSentenceRelevanceVotes.size() != hitSize) {
                                hitSize = vote.singleSentenceRelevanceVotes.size();
                                size = size + hitSize;
                                turkersVotes.addAll(vote.singleSentenceRelevanceVotes);
                            }
                        }
                    }
                    ArrayList<HashMap<String, String>> sentenceList = (ArrayList<HashMap<String, String>>) val
                            .getValue();
                    if (sentenceList.size() != turkersVotes.size()) {
                        try {
                            throw new IllegalStateException("Expected size of annotations is "
                                    + turkersVotes.size() + "but found " + sentenceList.size()
                                    + " for document " + rankedResults.clueWebID + " in " + queryID);
                        } catch (IllegalStateException ex) {
                            ex.printStackTrace();
                        }
                    }
                    for (QueryResultContainer.SingleSentenceRelevanceVote s : turkersVotes) {
                        String valSentence = null;
                        for (HashMap<String, String> anno : sentenceList) {
                            if (anno.keySet().contains(s.sentenceID)) {
                                valSentence = anno.get(s.sentenceID);
                            }
                        }
                        QueryResultContainer.SingleSentenceRelevanceVote singleSentenceVote = new QueryResultContainer.SingleSentenceRelevanceVote();
                        singleSentenceVote.sentenceID = s.sentenceID;
                        if (("false").equals(valSentence)) {
                            singleSentenceVote.relevant = "false";
                        } else if (("true").equals(valSentence)) {
                            singleSentenceVote.relevant = "true";
                        } else {
                            throw new IllegalStateException("Annotation value of sentence "
                                    + singleSentenceVote.sentenceID + " equals " + val.getValue());
                        }
                        goldEstimatedLabels.add(singleSentenceVote);
                    }
                    rankedResults.goldEstimatedLabels = goldEstimatedLabels;
                }
            }
        }
        File outputFile = new File(outputDir, queryID);
        FileUtils.writeStringToFile(outputFile, queryResultContainer.toXML(), "utf-8");
        System.out.println("Finished " + outputFile);
    }

    ArrayList<String> annotators = (ArrayList<String>) FileUtils.readLines(new File(file + ".competence"));
    FileWriter fileWriter;
    StringBuilder sb = new StringBuilder();
    for (int j = 0; j < annotatorsIDs.size(); j++) {
        String[] s = annotators.get(0).split("\t");
        Float score = Float.parseFloat(s[j]);
        String turkerID = annotatorsIDs.get(j);
        System.out.println(turkerID + " " + score + " " + countVotesForATurker.get(turkerID));
        sb.append(turkerID).append(" ").append(score).append(" ").append(countVotesForATurker.get(turkerID))
                .append("\n");
    }
    fileWriter = new FileWriter(turkersConfidence);
    fileWriter.append(sb.toString());
    fileWriter.close();

}