Example usage for java.util List get

List of usage examples for java.util List get

Introduction

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

Prototype

E get(int index);

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:br.com.autonomiccs.cloudTraces.main.CloudTracesSimulator.java

public static void main(String[] args) {
    validateInputFile(args);/*from  w  w w  .j ava2 s  .co  m*/

    String cloudTracesFile = args[0];
    Collection<VirtualMachine> virtualMachines = getAllVirtualMachinesFromCloudTraces(cloudTracesFile);
    logger.info(String.format("#VirtualMachines [%d] found on [%s].", virtualMachines.size(), cloudTracesFile));

    Map<Integer, List<VirtualMachine>> mapVirtualMachinesTaskExecutionByTime = createMapVirtualMachinesTaskExecutionByTime(
            virtualMachines);
    logger.info(String.format("#Times [%d] that have tasks being executed by VMs ",
            mapVirtualMachinesTaskExecutionByTime.size()));

    Cloud cloud = createCloudEnvirtonmentToStartsimulation();
    logger.info("Cloud configuration: " + cloud);

    List<Integer> timesToExecuteTasks = new ArrayList<>(mapVirtualMachinesTaskExecutionByTime.keySet());
    Collections.sort(timesToExecuteTasks);

    Integer firstTimeInTimeUnitOfUsedCloudData = timesToExecuteTasks.get(0);
    Integer lastTimeInTimeUnitOfUserCloudData = timesToExecuteTasks.get(timesToExecuteTasks.size() - 1);

    logger.info("First time: " + firstTimeInTimeUnitOfUsedCloudData);
    logger.info("Last time: " + lastTimeInTimeUnitOfUserCloudData);

    double timeUnitPerLoopIteration = getTimeUnitPerLoopIteration(firstTimeInTimeUnitOfUsedCloudData,
            lastTimeInTimeUnitOfUserCloudData);
    logger.info("The time unit converted to trace time: " + timeUnitPerLoopIteration);

    double currentTime = firstTimeInTimeUnitOfUsedCloudData;

    long highetResourceAllocation = Long.MIN_VALUE;
    String cloudStateHighestMemoryAllocation = "";

    while (currentTime < lastTimeInTimeUnitOfUserCloudData + 2 * timeUnitPerLoopIteration) {
        logger.debug("Current time of iteration: " + currentTime);
        if (cloud.getMemoryAllocatedInBytes() > highetResourceAllocation) {
            highetResourceAllocation = cloud.getMemoryAllocatedInBytes();
            cloudStateHighestMemoryAllocation = cloud.toString();
        }
        applyLoadOnCloudForCurrentTime(mapVirtualMachinesTaskExecutionByTime, cloud, currentTime);
        destroyVirtualMachinesIfNeeded(cloud, currentTime);

        logger.info(String.format("Time [%.3f], cloud state [%s] ", currentTime, cloud));

        executeManagement(cloud, currentTime);
        logClustersConfigurationsAndStdAtTime(cloud.getClusters(), currentTime);

        currentTime += timeUnitPerLoopIteration;
    }
    logger.info("Cloud configuration after simulation: " + cloud);
    logger.info("Cloud highestResourceUsage: " + cloudStateHighestMemoryAllocation);
}

From source file:com.mapr.PurchaseLog.java

public static void main(String[] args) throws IOException {
    Options opts = new Options();
    CmdLineParser parser = new CmdLineParser(opts);
    try {/*from   w  w w. ja va 2s  . c om*/
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println("Usage: -count <number>G|M|K [ -users number ]  log-file user-profiles");
        return;
    }

    Joiner withTab = Joiner.on("\t");

    // first generate lots of user definitions
    SchemaSampler users = new SchemaSampler(
            Resources.asCharSource(Resources.getResource("user-schema.txt"), Charsets.UTF_8).read());
    File userFile = File.createTempFile("user", "tsv");
    BufferedWriter out = Files.newBufferedWriter(userFile.toPath(), Charsets.UTF_8);
    for (int i = 0; i < opts.users; i++) {
        out.write(withTab.join(users.sample()));
        out.newLine();
    }
    out.close();

    // now generate a session for each user
    Splitter onTabs = Splitter.on("\t");
    Splitter onComma = Splitter.on(",");

    Random gen = new Random();
    SchemaSampler intermediate = new SchemaSampler(
            Resources.asCharSource(Resources.getResource("hit_step.txt"), Charsets.UTF_8).read());

    final int COUNTRY = users.getFieldNames().indexOf("country");
    final int CAMPAIGN = intermediate.getFieldNames().indexOf("campaign_list");
    final int SEARCH_TERMS = intermediate.getFieldNames().indexOf("search_keywords");
    Preconditions.checkState(COUNTRY >= 0, "Need country field in user schema");
    Preconditions.checkState(CAMPAIGN >= 0, "Need campaign_list field in step schema");
    Preconditions.checkState(SEARCH_TERMS >= 0, "Need search_keywords field in step schema");

    out = Files.newBufferedWriter(new File(opts.out).toPath(), Charsets.UTF_8);

    for (String line : Files.readAllLines(userFile.toPath(), Charsets.UTF_8)) {
        long t = (long) (TimeUnit.MILLISECONDS.convert(30, TimeUnit.DAYS) * gen.nextDouble());
        List<String> user = Lists.newArrayList(onTabs.split(line));

        // pick session length
        int n = (int) Math.floor(-30 * Math.log(gen.nextDouble()));

        for (int i = 0; i < n; i++) {
            // time on page
            int dt = (int) Math.floor(-20000 * Math.log(gen.nextDouble()));
            t += dt;

            // hit specific values
            JsonNode step = intermediate.sample();

            // check for purchase
            double p = 0.01;
            List<String> campaigns = Lists.newArrayList(onComma.split(step.get("campaign_list").asText()));
            List<String> keywords = Lists.newArrayList(onComma.split(step.get("search_keywords").asText()));
            if ((user.get(COUNTRY).equals("us") && campaigns.contains("5"))
                    || (user.get(COUNTRY).equals("jp") && campaigns.contains("7")) || keywords.contains("homer")
                    || keywords.contains("simpson")) {
                p = 0.5;
            }

            String events = gen.nextDouble() < p ? "1" : "-";

            out.write(Long.toString(t));
            out.write("\t");
            out.write(line);
            out.write("\t");
            out.write(withTab.join(step));
            out.write("\t");
            out.write(events);
            out.write("\n");
        }
    }
    out.close();
}

From source file:is.hi.bok.deduplicator.DigestIndexer.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(String[] args) throws Exception {
    CommandLineParser clp = new CommandLineParser(args, new PrintWriter(System.out));
    long start = System.currentTimeMillis();

    // Set default values for all settings.
    boolean etag = false;
    boolean equivalent = false;
    boolean timestamp = false;
    String indexMode = MODE_BOTH;
    boolean addToIndex = false;
    String mimefilter = "^text/.*";
    boolean blacklist = true;
    String iteratorClassName = CrawlLogIterator.class.getName();
    String origin = null;// w w  w.j ava2 s .  co  m
    boolean skipDuplicates = false;

    // Process the options
    Option[] opts = clp.getCommandLineOptions();
    for (int i = 0; i < opts.length; i++) {
        Option opt = opts[i];
        switch (opt.getId()) {
        case 'w':
            blacklist = false;
            break;
        case 'a':
            addToIndex = true;
            break;
        case 'e':
            etag = true;
            break;
        case 'h':
            clp.usage(0);
            break;
        case 'i':
            iteratorClassName = opt.getValue();
            break;
        case 'm':
            mimefilter = opt.getValue();
            break;
        case 'o':
            indexMode = opt.getValue();
            break;
        case 's':
            equivalent = true;
            break;
        case 't':
            timestamp = true;
            break;
        case 'r':
            origin = opt.getValue();
            break;
        case 'd':
            skipDuplicates = true;
            break;
        default:
            System.err.println("Unhandled option id: " + opt.getId());
        }
    }

    List cargs = clp.getCommandLineArguments();

    if (cargs.size() != 2) {
        // Should be exactly two arguments. Source and target!
        clp.usage(0);
    }

    // Get the CrawlDataIterator
    // Get the iterator classname or load default.
    Class cl = Class.forName(iteratorClassName);
    Constructor co = cl.getConstructor(new Class[] { String.class });
    CrawlDataIterator iterator = (CrawlDataIterator) co.newInstance(new Object[] { (String) cargs.get(0) });

    // Print initial stuff
    System.out.println("Indexing: " + cargs.get(0));
    System.out.println(" - Mode: " + indexMode);
    System.out.println(" - Mime filter: " + mimefilter + " (" + (blacklist ? "blacklist" : "whitelist") + ")");
    System.out.println(" - Includes" + (equivalent ? " <equivalent URL>" : "")
            + (timestamp ? " <timestamp>" : "") + (etag ? " <etag>" : ""));
    System.out.println(" - Skip duplicates: " + (skipDuplicates ? "yes" : "no"));
    System.out.println(" - Iterator: " + iteratorClassName);
    System.out.println("   - " + iterator.getSourceType());
    System.out.println("Target: " + cargs.get(1));
    if (addToIndex) {
        System.out.println(" - Add to existing index (if any)");
    } else {
        System.out.println(" - New index (erases any existing index at " + "that location)");
    }

    DigestIndexer di = new DigestIndexer((String) cargs.get(1), indexMode, equivalent, timestamp, etag,
            addToIndex);

    // Create the index
    di.writeToIndex(iterator, mimefilter, blacklist, origin, true, skipDuplicates);

    // Clean-up
    di.close();

    System.out.println("Total run time: "
            + ArchiveUtils.formatMillisecondsToConventional(System.currentTimeMillis() - start));
}

From source file:IrqaQuery.java

/** Simple command-line based search demo. */
public static void main(String[] args) throws Exception {
    String basedir = "/Users/bong/works/research/irqa";
    //        String basedir = "/home/bgshin/works/irqa";

    List<String> exps = new ArrayList<>();

    exps.add("_c_2048");
    //        exps.add("_c_1024");
    //        exps.add("_c_512");
    //        exps.add("_c_256");
    //        exps.add("_c_128");
    //        exps.add("_c_64");
    //        exps.add("_c_32");
    //        exps.add("_c_16");
    //        exps.add("_c_8");
    //        exps.add("_c_4");
    //        exps.add("_c_2");
    //        exps.add("_c_0");

    for (int i = 0; i < exps.size(); i++) {
        String indexpath = exps.get(i);
        batch_query(basedir, indexpath);
    }// w  w w . ja  v  a2  s. c  om

    // pipeline //////////////////////////////////////////////////////////////

    //        JSONParser parser = new JSONParser();
    //        String lookup_sentfn = basedir+"/data/wikilookup_clean_sentence.json";
    //        Object obj1 = parser.parse(new FileReader(lookup_sentfn));
    //        JSONObject lookup_sent = (JSONObject) obj1;
    //
    //        for (int i=0; i<exps.size(); i++) {
    //            String indexpath = exps.get(i);
    //            pipeline(basedir, indexpath, "dev", lookup_sent);
    //            pipeline(basedir, indexpath, "test", lookup_sent);
    //            pipeline(basedir, indexpath, "train", lookup_sent);
    //        }
    // pipeline //////////////////////////////////////////////////////////////

}

From source file:com.strider.datadefender.DataDefender.java

@SuppressWarnings("unchecked")
public static void main(final String[] args) throws ParseException, DatabaseDiscoveryException, IOException,
        SAXException, TikaException, java.text.ParseException, FileDiscoveryException {
    final long startTime = System.currentTimeMillis();

    // Ensure we are not trying to run second instance of the same program
    final ApplicationLock al = new ApplicationLock("DataDefender");

    if (al.isAppActive()) {
        LOG.error("Another instance of this program is already active");
        displayExecutionTime(startTime);
        System.exit(1);/*w  w w  .j  av a  2 s .  c  o m*/
    }

    LOG.info("Command-line arguments: " + Arrays.toString(args));

    final Options options = createOptions();
    final CommandLine line = getCommandLine(options, args);
    @SuppressWarnings("unchecked")
    List<String> unparsedArgs = line.getArgList();

    if (line.hasOption("help") || (args.length == 0) || (unparsedArgs.size() < 1)) {
        help(options);
        displayExecutionTime(startTime);

        return;
    }

    if (line.hasOption("debug")) {
        LogManager.getRootLogger().setLevel(Level.DEBUG);
    } else {
        LogManager.getRootLogger().setLevel(Level.INFO);
    }

    final String cmd = unparsedArgs.get(0); // get & remove command arg

    unparsedArgs = unparsedArgs.subList(1, unparsedArgs.size());

    List<String> errors = new ArrayList();

    if ("file-discovery".equals(cmd)) {
        errors = PropertyCheck.check(cmd, ' ');

        if (errors.size() > 0) {
            displayErrors(errors);
            displayExecutionTime(startTime);

            return;
        }

        final String fileDiscoveryPropertyFile = line.getOptionValue('F', "filediscovery.properties");
        final Properties fileDiscoveryProperties = loadPropertiesFromClassPath(fileDiscoveryPropertyFile);
        final FileDiscoverer discoverer = new FileDiscoverer();

        discoverer.discover(fileDiscoveryProperties);
        displayExecutionTime(startTime);

        return;
    }

    // Get db properties file from command line argument or use default db.properties
    final String dbPropertiesFile = line.getOptionValue('P', "db.properties");

    errors = PropertyCheck.checkDtabaseProperties(dbPropertiesFile);

    if (errors.size() > 0) {
        displayErrors(errors);
        displayExecutionTime(startTime);

        return;
    }

    final Properties props = loadProperties(dbPropertiesFile);

    try (final IDBFactory dbFactory = IDBFactory.get(props);) {
        switch (cmd) {
        case "anonymize":
            errors = PropertyCheck.check(cmd, ' ');

            if (errors.size() > 0) {
                displayErrors(errors);
                displayExecutionTime(startTime);

                return;
            }

            final String anonymizerPropertyFile = line.getOptionValue('A', "anonymizer.properties");
            final Properties anonymizerProperties = loadProperties(anonymizerPropertyFile);
            final IAnonymizer anonymizer = new DatabaseAnonymizer();

            anonymizer.anonymize(dbFactory, anonymizerProperties);

            break;

        case "generate":
            errors = PropertyCheck.check(cmd, ' ');

            if (errors.size() > 0) {
                displayErrors(errors);
                displayExecutionTime(startTime);

                return;
            }

            final IGenerator generator = new DataGenerator();
            final String generatorPropertyFile = line.getOptionValue('A', "anonymizer.properties");
            final Properties generatorProperties = loadProperties(generatorPropertyFile);

            generator.generate(dbFactory, generatorProperties);

            break;

        case "database-discovery":
            if (line.hasOption('c')) {
                errors = PropertyCheck.check(cmd, 'c');

                if (errors.size() > 0) {
                    displayErrors(errors);
                    displayExecutionTime(startTime);

                    return;
                }

                final String columnPropertyFile = line.getOptionValue('C', "columndiscovery.properties");
                final Properties columnProperties = loadProperties(columnPropertyFile);
                final ColumnDiscoverer discoverer = new ColumnDiscoverer();

                discoverer.discover(dbFactory, columnProperties, props.getProperty("vendor"));

                if (line.hasOption('r')) {
                    discoverer.createRequirement("Sample-Requirement.xml");
                }
            } else if (line.hasOption('d')) {
                errors = PropertyCheck.check(cmd, 'd');

                if (errors.size() > 0) {
                    displayErrors(errors);
                    displayExecutionTime(startTime);

                    return;
                }

                final String datadiscoveryPropertyFile = line.getOptionValue('D', "datadiscovery.properties");
                final Properties dataDiscoveryProperties = loadProperties(datadiscoveryPropertyFile);
                final DatabaseDiscoverer discoverer = new DatabaseDiscoverer();

                discoverer.discover(dbFactory, dataDiscoveryProperties, props.getProperty("vendor"));

                if (line.hasOption('r')) {
                    discoverer.createRequirement("Sample-Requirement.xml");
                }
            }

            break;

        default:
            help(options);

            break;
        }
    }

    displayExecutionTime(startTime);
}

From source file:FileList.java

public static void main(String[] args) {
    final int assumedLineLength = 50;
    File file = new File(args[0]);
    List<String> fileList = new ArrayList<String>((int) (file.length() / assumedLineLength) * 2);
    BufferedReader reader = null;
    int lineCount = 0;
    try {//  w w  w.  j ava 2s . c  o m
        reader = new BufferedReader(new FileReader(file));
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            fileList.add(line);
            lineCount++;
        }
    } catch (IOException e) {
        System.err.format("Could not read %s: %s%n", file, e);
        System.exit(1);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
            }
        }
    }
    int repeats = Integer.parseInt(args[1]);
    Random random = new Random();
    for (int i = 0; i < repeats; i++) {
        System.out.format("%d: %s%n", i, fileList.get(random.nextInt(lineCount - 1)));
    }
}

From source file:PopClean.java

public static void main(String args[]) {
    try {/*from   ww  w  . j av a 2  s  .  com*/
        String hostname = null, username = null, password = null;
        int port = 110;
        int sizelimit = -1;
        String subjectPattern = null;
        Pattern pattern = null;
        Matcher matcher = null;
        boolean delete = false;
        boolean confirm = true;

        // Handle command-line arguments
        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("-user"))
                username = args[++i];
            else if (args[i].equals("-pass"))
                password = args[++i];
            else if (args[i].equals("-host"))
                hostname = args[++i];
            else if (args[i].equals("-port"))
                port = Integer.parseInt(args[++i]);
            else if (args[i].equals("-size"))
                sizelimit = Integer.parseInt(args[++i]);
            else if (args[i].equals("-subject"))
                subjectPattern = args[++i];
            else if (args[i].equals("-debug"))
                debug = true;
            else if (args[i].equals("-delete"))
                delete = true;
            else if (args[i].equals("-force")) // don't confirm
                confirm = false;
        }

        // Verify them
        if (hostname == null || username == null || password == null || sizelimit == -1)
            usage();

        // Make sure the pattern is a valid regexp
        if (subjectPattern != null) {
            pattern = Pattern.compile(subjectPattern);
            matcher = pattern.matcher("");
        }

        // Say what we are going to do
        System.out
                .println("Connecting to " + hostname + " on port " + port + " with username " + username + ".");
        if (delete) {
            System.out.println("Will delete all messages longer than " + sizelimit + " bytes");
            if (subjectPattern != null)
                System.out.println("that have a subject matching: [" + subjectPattern + "]");
        } else {
            System.out.println("Will list subject lines for messages " + "longer than " + sizelimit + " bytes");
            if (subjectPattern != null)
                System.out.println("that have a subject matching: [" + subjectPattern + "]");
        }

        // If asked to delete, ask for confirmation unless -force is given
        if (delete && confirm) {
            System.out.println();
            System.out.print("Do you want to proceed (y/n) [n]: ");
            System.out.flush();
            BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
            String response = console.readLine();
            if (!response.equals("y")) {
                System.out.println("No messages deleted.");
                System.exit(0);
            }
        }

        // Connect to the server, and set up streams
        s = new Socket(hostname, port);
        in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));

        // Read the welcome message from the server, confirming it is OK.
        System.out.println("Connected: " + checkResponse());

        // Now log in
        send("USER " + username); // Send username, wait for response
        send("PASS " + password); // Send password, wait for response
        System.out.println("Logged in");

        // Check how many messages are waiting, and report it
        String stat = send("STAT");
        StringTokenizer t = new StringTokenizer(stat);
        System.out.println(t.nextToken() + " messages in mailbox.");
        System.out.println("Total size: " + t.nextToken());

        // Get a list of message numbers and sizes
        send("LIST"); // Send LIST command, wait for OK response.
        // Now read lines from the server until we get . by itself
        List msgs = new ArrayList();
        String line;
        for (;;) {
            line = in.readLine();
            if (line == null)
                throw new IOException("Unexpected EOF");
            if (line.equals("."))
                break;
            msgs.add(line);
        }

        // Now loop through the lines we read one at a time.
        // Each line should specify the message number and its size.
        int nummsgs = msgs.size();
        for (int i = 0; i < nummsgs; i++) {
            String m = (String) msgs.get(i);
            StringTokenizer st = new StringTokenizer(m);
            int msgnum = Integer.parseInt(st.nextToken());
            int msgsize = Integer.parseInt(st.nextToken());

            // If the message is too small, ignore it.
            if (msgsize <= sizelimit)
                continue;

            // If we're listing messages, or matching subject lines
            // find the subject line for this message
            String subject = null;
            if (!delete || pattern != null) {
                subject = getSubject(msgnum); // get the subject line

                // If we couldn't find a subject, skip the message
                if (subject == null)
                    continue;

                // If this subject does not match the pattern, then
                // skip the message
                if (pattern != null) {
                    matcher.reset(subject);
                    if (!matcher.matches())
                        continue;
                }

                // If we are listing, list this message
                if (!delete) {
                    System.out.println("Subject " + msgnum + ": " + subject);
                    continue; // so we never delete it
                }
            }

            // If we were asked to delete, then delete the message
            if (delete) {
                send("DELE " + msgnum);
                if (pattern == null)
                    System.out.println("Deleted message " + msgnum);
                else
                    System.out.println("Deleted message " + msgnum + ": " + subject);
            }
        }

        // When we're done, log out and shutdown the connection
        shutdown();
    } catch (Exception e) {
        // If anything goes wrong print exception and show usage
        System.err.println(e);
        usage();
        // Always try to shutdown nicely so the server doesn't hang on us
        shutdown();
    }
}

From source file:org.openimaj.demos.sandbox.PlotFlickrGeo.java

public static void main(String[] args) throws IOException {
    File inputcsv = new File("/Users/jsh2/Desktop/world-geo.csv");
    List<float[]> data = new ArrayList<float[]>(10000000);

    //read in images
    BufferedReader br = new BufferedReader(new FileReader(inputcsv));
    String line;/*from w ww  .j  av a 2 s. c  o m*/
    int i = 0;
    while ((line = br.readLine()) != null) {
        String[] parts = line.split(",");

        float longitude = Float.parseFloat(parts[0]);
        float latitude = Float.parseFloat(parts[1]);

        data.add(new float[] { longitude, latitude });

        if (i++ % 10000 == 0)
            System.out.println(i);
    }

    System.out.println("Done reading");

    float[][] dataArr = new float[2][data.size()];
    for (i = 0; i < data.size(); i++) {
        dataArr[0][i] = data.get(i)[0];
        dataArr[1][i] = data.get(i)[1];
    }

    NumberAxis domainAxis = new NumberAxis("X");
    domainAxis.setRange(-180, 180);
    NumberAxis rangeAxis = new NumberAxis("Y");
    rangeAxis.setRange(-90, 90);
    FastScatterPlot plot = new FastScatterPlot(dataArr, domainAxis, rangeAxis);

    JFreeChart chart = new JFreeChart("Fast Scatter Plot", plot);
    chart.getRenderingHints().put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
    final ApplicationFrame frame = new ApplicationFrame("Title");
    frame.setContentPane(chartPanel);
    frame.pack();
    frame.setVisible(true);
}

From source file:com.yobidrive.diskmap.DiskMapStore.java

public static void main(String[] args) {

    try {/*  ww w  .j  ava2  s  .  com*/
        BasicConfigurator.configure();
        //   (String storeName, String logPath, String keyPath, long ckeckPointPeriod, long logSize, int keySize,
        //      long mapSize, int packInterval, int readThreads, long needleCachedEntries, long bucketCachedBytes, short nodeId)

        /* String path = "/Users/david/Documents/NEEDLES";
        if ( args.length > 0) {
           path = args[0];
        }
        System.out.println("Using directory:" + path);
        */

        DiskMapStore dms = new DiskMapStore("teststore", "/drive_hd1;/drive_hd2", "/drive_ssd/storage_indexes",
                1000L, // Synching period
                60000 * 5L, // Checkpointing period
                2000000000L, // Log file size
                100, // Key max size
                2048, // Nb of buffers
                32768, // Nb of entries (buckets) per buffer
                60, // Compact interval
                8, // Read threads
                TEST_COUNT / 3 * 2 * 140, // NeedleHeaderCachedEntries (1/20 in cache, 1/2 of typical data set)
                TEST_COUNT / 3 * 2 * 140, // NeedleCachedBytes (3% of Map, weights 120 bytes/entry)
                true, // Use needle average age instead of needle yougest age
                (short) 0, 1, 1, 1);
        // dmm.getBtm().getCheckPoint().copyFrom(new NeedlePointer()) ; // Removes checkpoint
        dms.initialize();
        // System.out.println("Start read for "+TEST_COUNT+" pointers") ;
        Date startDate = new Date();
        Date lapDate = new Date();
        System.out.println("Start read test for " + TEST_COUNT + " pointers");
        long counter = 0;
        long lapCounter = 0;
        startDate = new Date();
        lapDate = new Date();
        long failCount = 0;
        counter = 0;
        while (counter < TEST_COUNT) {
            String key = "MYVERYNICELEY" + counter;
            // System.out.println("key="+key+"...") ;
            List<Versioned<byte[]>> values = dms.get(new ByteArray(key.getBytes("UTF-8")), null);
            if (values.size() <= 0) {
                failCount++;
            } else {
                // Gets previous version   
                byte[] value = values.get(0).getValue();
                if (value == null)
                    failCount++;
                else if (value[0] != (byte) ((short) counter % 128))
                    failCount++;
            }
            counter++;
            Date lapDate2 = new Date();
            long spent = lapDate2.getTime() - lapDate.getTime();
            if (spent >= 1000 || (counter - lapCounter > TARGET_TPSR)) { // Check each second or target tps
                if (spent < 1000) { // pause when tps reached
                    Thread.sleep(1000 - spent);
                    // System.out.print(".") ;
                } else
                    // System.out.print("*") ;
                    lapDate = lapDate2; // Reset lap time
                lapCounter = counter; // Reset tps copunter
            }
        }
        long timeSpent = new Date().getTime() - startDate.getTime();
        System.out.println("\n\nProcessed reading of " + TEST_COUNT + " pointers \n" + "\tTotal time: "
                + timeSpent / 1000 + "s\n" + "\tThroughput: " + (TEST_COUNT * 1000 / timeSpent) + " tps\n"
                + "\tBad results: " + failCount);

        startDate = new Date();
        lapDate = new Date();
        System.out.println("Start write test for " + TEST_COUNT + " pointers");
        counter = 0;
        lapCounter = 0;

        while (counter < TEST_COUNT) {
            String key = "MYVERYNICELEY" + counter;
            // System.out.println("key="+key+"...") ;
            byte[] value = new byte[128000];
            value[0] = (byte) ((short) counter % 128);
            long chaseDurer = new Date().getTime();
            List<Versioned<byte[]>> previousValues = dms.get(new ByteArray(key.getBytes("UTF-8")), null);
            long chaseDurer2 = new Date().getTime();
            // System.out.println("Get in "+(chaseDurer2 -chaseDurer)+"ms") ;
            chaseDurer = chaseDurer2;
            Version newVersion = null;
            if (previousValues.size() <= 0) {
                newVersion = new VectorClock();
            } else {
                // Gets previous version
                newVersion = previousValues.get(0).cloneVersioned().getVersion();
            }
            // Increment version before writing
            ((VectorClock) newVersion).incrementVersion(0, new Date().getTime());
            Versioned<byte[]> versionned = new Versioned<byte[]>(
                    previousValues.size() <= 0 ? value : previousValues.get(0).cloneVersioned().getValue(),
                    newVersion);
            dms.put(new ByteArray(key.getBytes("UTF-8")), versionned, null);
            chaseDurer2 = new Date().getTime();
            // System.out.println("Put in "+(chaseDurer2 -chaseDurer)+"ms") ;
            // dmm.putValue(key.getBytes("UTF-8"), value) ;
            counter++;
            Date lapDate2 = new Date();
            long spent = lapDate2.getTime() - lapDate.getTime();
            if (spent >= 1000 || (counter - lapCounter > TARGET_TPS)) { // Check each second or target tps
                if (spent < 1000) { // pause when tps reached
                    Thread.sleep(1000 - spent);
                    // System.out.print("("+counter+")") ;
                } else
                    // System.out.print("["+counter+"]") ;
                    lapDate = lapDate2; // Reset lap time
                lapCounter = counter; // Reset tps copunter
            }
        }

        timeSpent = new Date().getTime() - startDate.getTime();
        System.out.println("\n\nWriting before cache commit of " + TEST_COUNT + " pointers \n"
                + "\tTotal time: " + timeSpent / 1000 + "s\n" + "\tThroughput: "
                + (TEST_COUNT * 1000 / timeSpent) + " tps");

        System.out.println("Start read for " + TEST_COUNT + " pointers");
        startDate = new Date();
        lapDate = new Date();
        failCount = 0;
        counter = 0;
        while (counter < TEST_COUNT) {
            String key = "MYVERYNICELEY" + counter;
            // System.out.println("key="+key+"...") ;
            List<Versioned<byte[]>> values = dms.get(new ByteArray(key.getBytes("UTF-8")), null);
            if (values.size() <= 0) {
                failCount++;
            } else {
                // Gets previous version   
                byte[] value = values.get(0).getValue();
                if (value == null)
                    failCount++;
                else if (value[0] != (byte) ((short) counter % 128))
                    failCount++;
            }
            counter++;
            Date lapDate2 = new Date();
            long spent = lapDate2.getTime() - lapDate.getTime();
            if (spent >= 1000 || (counter - lapCounter > TARGET_TPSR)) { // Check each second or target tps
                if (spent < 1000) { // pause when tps reached
                    Thread.sleep(1000 - spent);
                    // System.out.print(".") ;
                } else
                    // System.out.print("*") ;
                    lapDate = lapDate2; // Reset lap time
                lapCounter = counter; // Reset tps copunter
            }
        }
        timeSpent = new Date().getTime() - startDate.getTime();
        System.out.println("\n\nProcessed reading of " + TEST_COUNT + " pointers \n" + "\tTotal time: "
                + timeSpent / 1000 + "s\n" + "\tThroughput: " + (TEST_COUNT * 1000 / timeSpent) + " tps\n"
                + "\tBad results: " + failCount);

        dms.close();
        // System.out.println("Max cycle time = "+ (dms.getBtm().getMaxCycleTimePass1()+dmm.getBtm().getMaxCycleTimePass2())) ;

    } catch (Throwable th) {
        th.printStackTrace();
    }

}

From source file:com.sccl.attech.common.utils.excel.ExportExcel.java

/**
 * /*w  ww  .j  av  a2  s .  c  o m*/
 */
public static void main(String[] args) throws Throwable {

    List<String> headerList = Lists.newArrayList();
    headerList.add("??");
    headerList.add("??");
    headerList.add("");
    headerList.add("?");
    headerList.add("");

    List<String> dataRowList = Lists.newArrayList();
    for (int i = 1; i <= headerList.size(); i++) {
        dataRowList.add("?" + i);
    }

    List<List<String>> dataList = Lists.newArrayList();
    for (int i = 1; i <= 100; i++) {
        dataList.add(dataRowList);
    }

    ExportExcel ee = new ExportExcel(null, headerList);

    for (int i = 0; i < dataList.size(); i++) {
        Row row = ee.addRow();
        for (int j = 0; j < dataList.get(i).size(); j++) {
            ee.addCell(row, j, dataList.get(i).get(j));
        }
    }
    ee.createAddMergedRegion();
    StringBuilder sb = new StringBuilder();
    sb.append("????").append("\r\n");
    sb.append(
            "???64????? ?: ; { } !  @ $  ^ & | , . / ? [ ] ~ * # <+ - = ")
            .append("\r");
    sb.append("??:").append("").append("'").append("%")
            .append("\\").append("?   ")
            .append("\r");
    sb.append(
            "?? ?60?????? : ; { } !  @ $  ^ & | , . / ? [ ] ~ * # < +- = ")
            .append("\r");
    sb.append(
            " ????")
            .append("\r");
    sb.append(
            "??180???1590???15???? :")
            .append("\r");
    sb.append(
            "79.000000000000000?GPS???????6?")
            .append("\r");
    sb.append(
            "* ??2000??2000?????")
            .append("\r");
    sb.append("* EXCEL???.xls97-2003").append("\r");
    sb.append("* ??????").append("\r");
    sb.append(
            "*   ??")
            .append("\r");
    sb.append(
            "* ????POI??POI??????")
            .append("\r");
    ee.addCellStyle(ee.getExistRow(1), 6, sb.toString());

    //demo
    ee.initializeDemo(null, headerList);
    ee.addCellStyle(ee.getExistRow(25), 6, "?");
    ee.addCellStyle(ee.getExistRow(25), 7, "");
    ee.addCellStyle(ee.getExistRow(25), 8, "");
    ee.addCellStyle(ee.getExistRow(25), 9, "116.35526644472");
    ee.addCellStyle(ee.getExistRow(25), 10, "40.03711432476");
    //ee.addCell(ee.getExistRow(26), 6, dataList.get(i).get(j));

    ee.writeFile("D:\\export.xlsx");

    ee.dispose();

    log.debug("Export success.");

}