Example usage for java.lang Long MIN_VALUE

List of usage examples for java.lang Long MIN_VALUE

Introduction

In this page you can find the example usage for java.lang Long MIN_VALUE.

Prototype

long MIN_VALUE

To view the source code for java.lang Long MIN_VALUE.

Click Source Link

Document

A constant holding the minimum value a long can have, -263.

Usage

From source file:edu.usc.scrc.PriorityPruner.CommandLineOptions.java

/**
 * Parses command line arguments, evaluates them, and stores values if
 * they're correct.//from w w  w  .j a v  a  2  s .c  o  m
 * 
 * @param options
 *            collection of Option-objects
 * @param args
 *            command line arguments
 * @throws PriorityPrunerException
 *             if error occurs during parsing
 */
private void parse(Options options, String[] args) throws PriorityPrunerException {
    try {
        CommandLineParser cmdLineParser = new GnuParser();
        CommandLine commandLine = cmdLineParser.parse(options, args);
        setParsedOptions(commandLine.getOptions());
        // gets set to true if -tfile option is entered through the command
        // line
        //boolean tFlag = false;
        // counts --tped & --tfam options entered through the command line
        //int tpedCount = 0;
        //int tfamCount = 0;

        // loops through all options to save the ones in effect as a String
        // for printing
        String tmp = "Options in effect:";
        for (Option opt : commandLine.getOptions()) {
            tmp += ("\r\n   -" + opt.getOpt());
            if (opt.getValues() != null) {
                for (int i = 0; i < opt.getValues().length; i++) {
                    tmp += (" " + opt.getValues()[i]);
                }
            }
        }

        // saves options in effect for printing
        this.setOptionsInEffect(tmp + "\r\n");

        // parse max_distance
        if (commandLine.hasOption("max_distance")) {
            this.maxDistance(getLongArgument("max_distance", commandLine.getOptionValue("max_distance"), 0,
                    Long.MAX_VALUE));
            checkInput(1, "max_distance", commandLine);
        }

        // parse min_maf
        if (commandLine.hasOption("min_maf")) {
            this.setMinMaf(getDoubleArgument("min_maf", commandLine.getOptionValue("min_maf"), 0, 0.5));
            checkInput(1, "min_maf", commandLine);
        }

        // parse min_hwe
        //         if (commandLine.hasOption("min_hwe")) {
        //            this.setMinHwe(getDoubleArgument("min_hwe",
        //                  commandLine.getOptionValue("min_hwe"), 0, 1));
        //            checkInput(1, "min_hwe", commandLine);
        //         }

        // parses min_snp_callrate
        if (commandLine.hasOption("min_snp_callrate")) {
            this.setMinSnpCallRate(getDoubleArgument("min_snp_callrate",
                    commandLine.getOptionValue("min_snp_callrate"), 0, 1));
            checkInput(1, "min_snp_callrate", commandLine);
        }

        // parses min_design_score
        if (commandLine.hasOption("min_design_score")) {
            this.setMinDesignScore(getDoubleArgument("min_design_score",
                    commandLine.getOptionValue("min_design_score"), 0, Double.MAX_VALUE));
            checkInput(1, "min_design_score", commandLine);
        }

        //         // parses option that sets the absolute minimum design score
        //         // value, allowed arguments are doubles between 0.0 and
        //         // Double.MAX_VALUE
        //         if (commandLine.hasOption("amds")) {
        //            this.setAbsoluteMinDesignScore(getDoubleArgument(
        //                  "absmindesignscore",
        //                  commandLine.getOptionValue("amds"), 0, Double.MAX_VALUE));
        //            checkInput(1, "amds", commandLine);
        //         }

        // parse metric
        if (commandLine.hasOption("metric")) {
            String[] str = commandLine.getOptionValues("metric");
            if (str.length % 2 == 1) {
                throw new PriorityPrunerException(
                        "Only one argument specified for option \"metric\", a column name (text string) and a weight (decimal number) are required.");
            } else {
                for (int i = 0; i < str.length; i++) {
                    if (str[i].equals("design_score")) {
                        throw new PriorityPrunerException("Invalid metric: \"" + str[i]
                                + "\". To filter on design score, simply add correct column in the SNP input file, no metric is needed.");
                    }
                    addMetric(str[i], this.getDoubleArgument("metric", str[i + 1], 0, Double.MAX_VALUE));
                    i++;
                }
            }
        }

        // parse st
        if (commandLine.hasOption("st")) {
            String[] str = commandLine.getOptionValues("st");
            if (str.length % 2 == 1) {
                throw new PriorityPrunerException(
                        "Only one argument specified for option: \"st\", a p-value (decimal number) and a number of surrogates (integer) are are required.");
            } else {
                for (int i = 0; i < str.length; i++) {
                    addSurrogateThreshold(this.getDoubleArgument("st", str[i], 0, 1),
                            this.getIntegerArgument("st", str[i + 1], 0, Integer.MAX_VALUE));
                    i++;
                }
            }
        }

        // parse r2t
        if (commandLine.hasOption("r2t")) {
            String[] str = commandLine.getOptionValues("r2t");
            if (str.length % 2 == 1) {
                throw new PriorityPrunerException(
                        "Only one argument specified for option: \"r2t\", a p-value and a threshold (decimal numbers between 0 and 1) are required.");
            } else {
                for (int i = 0; i < str.length; i++) {
                    addR2Threshold(this.getDoubleArgument("r2t", str[i], 0, 1),
                            this.getDoubleArgument("r2t", str[i + 1], 0, 1));
                    i++;
                }
            }
        }

        // parse r2
        if (commandLine.hasOption("r2")) {
            String value = commandLine.getOptionValue("r2");
            this.addR2Threshold(1, this.getDoubleArgument("r2", value, 0, 1));
            checkInput(1, "r2", commandLine);
        }

        // parse chr
        if (commandLine.hasOption("chr")) {
            String value = commandLine.getOptionValue("chr");
            // recoding chromosome X-representations to "23"
            if (value.toUpperCase().equals("X") || value.toUpperCase().equals("CHRX")) {
                //value = "23";
            }
            // if chromosome Y or mitochondrial DNA is encountered, an
            // exception is thrown
            else if (value.toUpperCase().equals("M") || value.toUpperCase().equals("MT")
                    || value.toUpperCase().equals("CHRM") || value.toUpperCase().equals("CHRMT")
                    || value.toUpperCase().equals("Y") || value.toUpperCase().equals("CHRY")
                    || value.toUpperCase().equals("24")) {
                throw new PriorityPrunerException("Chromosome \"" + value
                        + "\" specified in the command line, is not supported. Please update input files and rerun program.");
            }
            this.setChr(value);
            checkInput(1, "chr", commandLine);
        }

        // parse out
        if (commandLine.hasOption("out")) {
            String value = commandLine.getOptionValue("out");
            if (value.endsWith("/")) {
                value = new StringBuilder(value).append("prioritypruner").toString();
            }
            this.setOutputPrefix(value);
            checkInput(1, "out", commandLine);
        }

        //         // parse forceInclude
        //         if (commandLine.hasOption("force_include")) {
        //            String value = commandLine.getOptionValue("force_include");
        //            this.setForceIncludeFilePath(value);
        //            checkInput(1, "force_include", commandLine);
        //         }

        // parse do_not_pick_force_included_snps_first
        if (commandLine.hasOption("do_not_pick_force_included_snps_first")) {
            this.setSortByForceIncludeAndPValue(false);
        }

        // parse snp_table
        if (commandLine.hasOption("snp_table")) {
            String[] str = commandLine.getOptionValues("snp_table");
            this.setSnpTablePath(str[0]);
            // counts number of metrics added to command line
            int metrics = 0;
            for (int i = 0; i < getParsedOptions().length; i++) {
                if (getParsedOptions()[i].getOpt().equals("metric")) {
                    metrics++;
                }
            }
            this.setNumMetrics(metrics);
            checkInput(1, "snp_table", commandLine);
        }

        // parse tped
        if (commandLine.hasOption("tped")) {
            String value = commandLine.getOptionValue("tped");
            checkInput(1, "tped", commandLine);
            this.setTped(value);
        }

        // parse tfam
        if (commandLine.hasOption("tfam")) {
            String value = commandLine.getOptionValue("tfam");
            checkInput(1, "tfam", commandLine);
            this.setTfam(value);
        }

        // parse tfile
        if (commandLine.hasOption("tfile")) {
            String value = commandLine.getOptionValue("tfile");
            checkInput(1, "tfile", commandLine);
            this.setTped(value + ".tped");
            this.setTfam(value + ".tfam");
            this.setTfile(value);
        }

        // parse use_surrogate_for_non_passing_index_snps
        //         if (commandLine.hasOption("use_surrogate_for_non_passing_index_snps")) {
        //            this.setUseSurrogateForNonPassingIndexSnp(true);
        //         }

        // parses verbose
        if (commandLine.hasOption("verbose")) {
            this.setVerbose(true);
        }

        // parse outputLDTable
        if (commandLine.hasOption("ld")) {
            this.setOutputLDTable(true);
        }

        // parse remove
        if (commandLine.hasOption("remove")) {
            String value = commandLine.getOptionValue("remove");
            checkInput(1, "remove", commandLine);
            this.setRemove(value);
        }

        // parse keep
        if (commandLine.hasOption("keep")) {
            String value = commandLine.getOptionValue("keep");
            checkInput(1, "keep", commandLine);
            this.setKeep(value);
        }

        // parse keep_random
        if (commandLine.hasOption("keep_random")) {
            String value = commandLine.getOptionValue("keep_random");
            this.setKeepPercentage(this.getDoubleArgument("keep_random", value, 0, 1));
            checkInput(1, "keep_random", commandLine);
        }

        // parse no_surrogates_for_force_included_snps
        if (commandLine.hasOption("no_surrogates_for_force_included_snps")) {
            this.setAddSurrogatesForForceIncludedSnps(false);
        }

        // parse seed
        if (commandLine.hasOption("seed")) {
            String value = commandLine.getOptionValue("seed");
            this.seed = new Long(this.getLongArgument("seed", value, Long.MIN_VALUE, Long.MAX_VALUE));
        }

        // check that we have all required arguments
        checkRequiredArguments(commandLine);

        // checks if any unrecognized arguments been entered
        checkLeftArguments(commandLine);

        // if several options from the same options group been entered,
        // an AlreadySelectedException gets thrown. A custom message is
        // generated since we wanted another design than the one provided in
        // the library gave
    } catch (AlreadySelectedException e) {
        String message = "";
        for (int i = 0; i < e.getOptionGroup().getNames().toArray().length; i++) {
            message += "\"" + e.getOptionGroup().getNames().toArray()[i] + "\" ";
        }
        throw new PriorityPrunerException(
                "The options: " + message + " may not both be defined. Type --help for help.");

        // if an undefined option is entered an UnrecognizedOptionException
        // gets thrown
    } catch (UnrecognizedOptionException e) {
        throw new PriorityPrunerException(e.getOption() + " is not a valid option. Type --help for help.");

        // if an option that is supposed to have arguments is missing,
        // a MissingArgumentException gets thrown
    } catch (MissingArgumentException e) {
        throw new PriorityPrunerException("Missing argument for option \"" + e.getOption().getOpt()
                + "\". Expected: " + e.getOption().getArgName() + ". Type --help for help.");

        // if a required option is missing, a MissingOptionException gets
        // thrown
    } catch (MissingOptionException e) {
        // if any other problem occurs while parsing, a general
        // ParseException gets thrown
    } catch (ParseException parseException) {
        throw new PriorityPrunerException("Invalid command line options. Type --help for help.");
    }
}

From source file:net.sf.json.TestJSONObject.java

public void testFromObject_use_wrappers() {
    JSONObject json = JSONObject.fromObject(Boolean.TRUE);
    assertTrue(json.isEmpty());//w w w  .  ja  v a  2s  .  co m
    json = JSONObject.fromObject(new Byte(Byte.MIN_VALUE));
    assertTrue(json.isEmpty());
    json = JSONObject.fromObject(new Short(Short.MIN_VALUE));
    assertTrue(json.isEmpty());
    json = JSONObject.fromObject(new Integer(Integer.MIN_VALUE));
    assertTrue(json.isEmpty());
    json = JSONObject.fromObject(new Long(Long.MIN_VALUE));
    assertTrue(json.isEmpty());
    json = JSONObject.fromObject(new Float(Float.MIN_VALUE));
    assertTrue(json.isEmpty());
    json = JSONObject.fromObject(new Double(Double.MIN_VALUE));
    assertTrue(json.isEmpty());
    json = JSONObject.fromObject(new Character('A'));
    assertTrue(json.isEmpty());
}

From source file:fi.ni.IFC_ClassModel.java

/**
 * To long.//from  w  ww.j av  a2 s.c o  m
 * 
 * @param txt
 *            the txt
 * @return the long
 */
private Long toLong(String txt) {
    try {
        return Long.valueOf(txt);
    } catch (Exception e) {
        return Long.MIN_VALUE;
    }
}

From source file:net.tourbook.tour.photo.TourPhotoManager.java

private void loadToursFromDb_Runnable(final long dbStartDate, final long dbEndDate) {

    //      final long start = System.currentTimeMillis();

    _allDbTourPhotoLinks.clear();/*from   w  ww  . ja v  a 2 s.com*/

    try {

        if (_sqlConnection == null) {

            final SQLFilter sqlFilter = new SQLFilter(false);

            final String sql = UI.EMPTY_STRING //

                    + "SELECT " //$NON-NLS-1$

                    + " TourId, " //               1 //$NON-NLS-1$
                    + " TourStartTime, " //            2 //$NON-NLS-1$
                    + " TourEndTime, " //            3 //$NON-NLS-1$
                    + " TourType_TypeId, " //         4 //$NON-NLS-1$

                    + " numberOfPhotos, " //         5 //$NON-NLS-1$
                    + " photoTimeAdjustment " //      6 //$NON-NLS-1$

                    + UI.NEW_LINE

                    + (" FROM " + TourDatabase.TABLE_TOUR_DATA + UI.NEW_LINE) //$NON-NLS-1$

                    + " WHERE" //$NON-NLS-1$
                    + (" TourStartTime >= ?") //$NON-NLS-1$
                    + (" AND TourEndTime <= ?") //$NON-NLS-1$

                    + sqlFilter.getWhereClause()

                    + UI.NEW_LINE

                    + (" ORDER BY TourStartTime"); //$NON-NLS-1$

            _sqlConnection = TourDatabase.getInstance().getConnection();
            _sqlStatement = _sqlConnection.prepareStatement(sql);

            sqlFilter.setParameters(_sqlStatement, 3);
        }

        _sqlStatement.setLong(1, dbStartDate);
        _sqlStatement.setLong(2, dbEndDate);

        _sqlTourStart = Long.MAX_VALUE;
        _sqlTourEnd = Long.MIN_VALUE;

        final ResultSet result = _sqlStatement.executeQuery();

        while (result.next()) {

            final long dbTourId = result.getLong(1);
            final long dbTourStart = result.getLong(2);
            final long dbTourEnd = result.getLong(3);
            final Object dbTourTypeId = result.getObject(4);
            final int dbNumberOfPhotos = result.getInt(5);
            final int dbPhotoTimeAdjustment = result.getInt(6);

            final TourPhotoLink dbTourPhotoLink = new TourPhotoLink(dbTourId, dbTourStart, dbTourEnd,
                    dbNumberOfPhotos, dbPhotoTimeAdjustment);

            dbTourPhotoLink.tourTypeId = (dbTourTypeId == null ? //
                    TourDatabase.ENTITY_IS_NOT_SAVED : (Long) dbTourTypeId);

            _allDbTourPhotoLinks.add(dbTourPhotoLink);

            // get range of all tour start/end
            if (dbTourStart < _sqlTourStart) {
                _sqlTourStart = dbTourStart;
            }
            if (dbTourEnd > _sqlTourEnd) {
                _sqlTourEnd = dbTourEnd;
            }
        }

    } catch (final SQLException e) {
        net.tourbook.ui.UI.showSQLException(e);
    }
    //      System.out.println("loadToursFromDb_Runnable()\t"
    //            + (System.currentTimeMillis() - start)
    //            + " ms\t"
    //            + (new DateTime(_sqlTourStart))
    //            + "\t"
    //            + new DateTime(_sqlTourEnd));
    //      // TODO remove SYSTEM.OUT.PRINTLN
}

From source file:com.juick.android.JuickMessagesAdapter.java

public static ParsedMessage formatMessageText(final Context ctx, final JuickMessage jmsg, boolean condensed) {
    if (jmsg.parsedText != null) {
        return (ParsedMessage) jmsg.parsedText; // was parsed before
    }//from w  ww.  j  a  v  a2  s .  c  om
    getColorTheme(ctx);
    SpannableStringBuilder ssb = new SpannableStringBuilder();
    int spanOffset = 0;
    final boolean isMainMessage = jmsg.getRID() == 0;
    final boolean doCompactComment = !isMainMessage && compactComments;
    if (jmsg.continuationInformation != null) {
        ssb.append(jmsg.continuationInformation + "\n");
        ssb.setSpan(new StyleSpan(Typeface.ITALIC), spanOffset, ssb.length() - 1,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    //
    // NAME
    //
    spanOffset = ssb.length();
    String name = '@' + jmsg.User.UName;
    int userNameStart = ssb.length();
    ssb.append(name);
    int userNameEnd = ssb.length();
    StyleSpan userNameBoldSpan;
    ForegroundColorSpan userNameColorSpan;
    ssb.setSpan(userNameBoldSpan = new StyleSpan(Typeface.BOLD), spanOffset, ssb.length(),
            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    ssb.setSpan(
            userNameColorSpan = new ForegroundColorSpan(
                    colorTheme.getColor(ColorsTheme.ColorKey.USERNAME, 0xFFC8934E)),
            spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    if (helvNueFonts) {
        ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.helvNueBold), spanOffset, ssb.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    ssb.append(' ');
    spanOffset = ssb.length();

    if (!condensed) {
        //
        // TAGS
        //
        String tags = jmsg.getTags();
        if (feedlyFonts)
            tags = tags.toUpperCase();
        ssb.append(tags + "\n");
        if (tags.length() > 0) {
            ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.TAGS, 0xFF0000CC)),
                    spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            if (feedlyFonts) {
                ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.dinWebPro), spanOffset,
                        ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else if (helvNueFonts) {
                ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.helvNue), spanOffset,
                        ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

        }
        spanOffset = ssb.length();
    }
    if (jmsg.translated) {
        //
        // 'translated'
        //
        ssb.append("translated: ");
        ssb.setSpan(
                new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.TRANSLATED_LABEL, 0xFF4ec856)),
                spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ssb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), spanOffset, ssb.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanOffset = ssb.length();
    }
    int bodyOffset = ssb.length();
    int messageNumberStart = -1, messageNumberEnd = -1;
    if (showNumbers(ctx) && !condensed) {
        //
        // numbers
        //
        if (isMainMessage) {
            messageNumberStart = ssb.length();
            ssb.append(jmsg.getDisplayMessageNo());
            messageNumberEnd = ssb.length();
        } else {
            ssb.append("/" + jmsg.getRID());
            if (jmsg.getReplyTo() != 0) {
                ssb.append("->" + jmsg.getReplyTo());
            }
        }
        ssb.append(" ");
        ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.MESSAGE_ID, 0xFFa0a5bd)),
                spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanOffset = ssb.length();
    }
    //
    // MESSAGE BODY
    //
    String txt = Censor.getCensoredText(jmsg.Text);
    if (!condensed) {
        if (jmsg.Photo != null) {
            txt = jmsg.Photo + "\n" + txt;
        }
        if (jmsg.Video != null) {
            txt = jmsg.Video + "\n" + txt;
        }
    }
    ssb.append(txt);
    boolean ssbChanged = false; // allocation optimization
    // Highlight links http://example.com/
    ArrayList<ExtractURLFromMessage.FoundURL> foundURLs = ExtractURLFromMessage.extractUrls(txt, jmsg.getMID());
    ArrayList<String> urls = new ArrayList<String>();
    for (ExtractURLFromMessage.FoundURL foundURL : foundURLs) {
        setSSBSpan(ssb, new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.URLS, 0xFF0000CC)),
                spanOffset + foundURL.start, spanOffset + foundURL.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        urls.add(foundURL.url);
        if (foundURL.title != null) {
            ssb.replace(spanOffset + foundURL.title.start - 1, spanOffset + foundURL.title.start, " ");
            ssb.replace(spanOffset + foundURL.title.end, spanOffset + foundURL.title.end + 1, " ");
            ssb.replace(spanOffset + foundURL.start - 1, spanOffset + foundURL.start, "(");
            ssb.replace(spanOffset + foundURL.end, spanOffset + foundURL.end + 1, ")");
            ssb.setSpan(new StyleSpan(Typeface.BOLD), spanOffset + foundURL.title.start,
                    spanOffset + foundURL.title.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        ssbChanged = true;
    }
    // bold italic underline
    if (jmsg.Text.indexOf("*") != -1) {
        setStyleSpans(ssb, spanOffset, Typeface.BOLD, "*");
        ssbChanged = true;
    }
    if (jmsg.Text.indexOf("/") != 0) {
        setStyleSpans(ssb, spanOffset, Typeface.ITALIC, "/");
        ssbChanged = true;
    }
    if (jmsg.Text.indexOf("_") != 0) {
        setStyleSpans(ssb, spanOffset, UnderlineSpan.class, "_");
        ssbChanged = true;
    }
    if (ssbChanged) {
        txt = ssb.subSequence(spanOffset, ssb.length()).toString(); // ssb was modified in between
    }

    // Highlight nick
    String accountName = XMPPService.getMyAccountName(jmsg.getMID(), ctx);
    if (accountName != null) {
        int scan = spanOffset;
        String nickScanArea = (ssb + " ").toUpperCase();
        while (true) {
            int myNick = nickScanArea.indexOf("@" + accountName.toUpperCase(), scan);
            if (myNick != -1) {
                if (!isNickPart(nickScanArea.charAt(myNick + accountName.length() + 1))) {
                    setSSBSpan(ssb,
                            new BackgroundColorSpan(
                                    colorTheme.getColor(ColorsTheme.ColorKey.USERNAME_ME, 0xFF938e00)),
                            myNick - 1, myNick + accountName.length() + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                scan = myNick + 1;
            } else {
                break;
            }
        }
    }

    // Highlight messages #1234
    int pos = 0;
    Matcher m = getCrossReferenceMsgPattern(jmsg.getMID()).matcher(txt);
    while (m.find(pos)) {
        ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.URLS, 0xFF0000CC)),
                spanOffset + m.start(), spanOffset + m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        pos = m.end();
    }

    SpannableStringBuilder compactDt = null;
    if (!condensed) {

        // found messages count (search results)
        if (jmsg.myFoundCount != 0 || jmsg.hisFoundCount != 0) {
            ssb.append("\n");
            int where = ssb.length();
            if (jmsg.myFoundCount != 0) {
                ssb.append(ctx.getString(R.string.MyReplies_) + jmsg.myFoundCount + "  ");
            }
            if (jmsg.hisFoundCount != 0) {
                ssb.append(ctx.getString(R.string.UserReplies_) + jmsg.hisFoundCount);
            }
            ssb.setSpan(
                    new ForegroundColorSpan(
                            colorTheme.getColor(ColorsTheme.ColorKey.TRANSLATED_LABEL, 0xFF4ec856)),
                    where, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        int rightPartOffset = spanOffset = ssb.length();

        if (!doCompactComment) {
            //
            // TIME (bottom of message)
            //

            try {
                DateFormat df = new SimpleDateFormat("HH:mm dd/MMM/yy");
                String date = jmsg.Timestamp != null ? df.format(jmsg.Timestamp) : "[bad date]";
                if (date.endsWith("/76"))
                    date = date.substring(0, date.length() - 3); // special case for no year in datasource
                ssb.append("\n" + date + " ");
            } catch (Exception e) {
                ssb.append("\n[fmt err] ");
            }

            ssb.setSpan(new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.DATE, 0xFFAAAAAA)),
                    spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
            compactDt = new SpannableStringBuilder();
            try {
                if (true || jmsg.deltaTime != Long.MIN_VALUE) {
                    compactDt.append(com.juickadvanced.Utils.toRelaviteDate(jmsg.Timestamp.getTime(), russian));
                } else {
                    DateFormat df = new SimpleDateFormat("HH:mm dd/MMM/yy");
                    String date = jmsg.Timestamp != null ? df.format(jmsg.Timestamp) : "[bad date]";
                    if (date.endsWith("/76"))
                        date = date.substring(0, date.length() - 3); // special case for no year in datasource
                    compactDt.append(date);
                }
            } catch (Exception e) {
                compactDt.append("\n[fmt err] ");
            }
            compactDt.setSpan(
                    new ForegroundColorSpan(colorTheme.getColor(ColorsTheme.ColorKey.DATE, 0xFFAAAAAA)), 0,
                    compactDt.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        }

        spanOffset = ssb.length();

        //
        // Number of REPLIES
        //
        if (jmsg.replies > 0) {
            String replies = Replies + jmsg.replies;
            ssb.append(" " + replies);
            ssb.setSpan(
                    new ForegroundColorSpan(
                            colorTheme.getColor(ColorsTheme.ColorKey.NUMBER_OF_COMMENTS, 0xFFC8934E)),
                    spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            ssb.setSpan(new WrapTogetherSpan() {
            }, spanOffset, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        if (!doCompactComment) {
            // right align
            ssb.setSpan(new AlignmentSpan.Standard(Alignment.ALIGN_OPPOSITE), rightPartOffset, ssb.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }

    if (helvNueFonts) {
        ssb.setSpan(new CustomTypefaceSpan("", JuickAdvancedApplication.helvNue), bodyOffset, ssb.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    LeadingMarginSpan.LeadingMarginSpan2 userpicSpan = null;
    if (showUserpics(ctx) && !condensed) {
        userpicSpan = new LeadingMarginSpan.LeadingMarginSpan2() {
            @Override
            public int getLeadingMarginLineCount() {
                if (_wrapUserpics) {
                    return 2;
                } else {
                    return 22222;
                }
            }

            @Override
            public int getLeadingMargin(boolean first) {
                if (first) {
                    return (int) (2 * getLineHeight(ctx, (double) textScale));
                } else {
                    return 0;
                }
            }

            @Override
            public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom,
                    CharSequence text, int start, int end, boolean first, Layout layout) {
            }
        };
        ssb.setSpan(userpicSpan, 0, ssb.length(), 0);
    }
    ParsedMessage parsedMessage = new ParsedMessage(ssb, urls);
    parsedMessage.userpicSpan = userpicSpan;
    parsedMessage.userNameBoldSpan = userNameBoldSpan;
    parsedMessage.userNameColorSpan = userNameColorSpan;
    parsedMessage.userNameStart = userNameStart;
    parsedMessage.userNameEnd = userNameEnd;
    parsedMessage.messageNumberStart = messageNumberStart;
    parsedMessage.messageNumberEnd = messageNumberEnd;
    parsedMessage.compactDate = compactDt;
    return parsedMessage;
}

From source file:org.amanzi.awe.statistics.model.impl.StatisticsModel.java

@Override
public Iterable<IStatisticsRow> getStatisticsRows(final String period) throws ModelException {
    return getStatisticsRowsInTimeRange(period, Long.MIN_VALUE, Long.MAX_VALUE);
}

From source file:com.ggvaidya.scinames.model.Dataset.java

/**
 * Attempt to load a dataset from a file. We use regular expressions to try to guess the file type,
 * and then delegate the job out. Rather cleverly, we try extracting the names using every extractor
 * this project knows about, and then pick the one that gives us the most number of names.
 * //  w w w . j a  va  2s  . c  om
 * @param proj The project doing the loading, used to get the name extractors.
 * @param f The file to open.
 * @return The dataset loaded from that file.
 * @throws IOException If there was an error loading the file.
 */
public static Dataset loadFromFile(Project proj, File f) throws IOException {
    Dataset ds;

    // Excel file? Handle separately!
    String fileName = f.getName().toLowerCase();
    if (fileName.endsWith(".xlsx") || fileName.endsWith(".xls")) {
        ds = new ExcelImporter(f).asDataset(0);
    } else if (fileName.endsWith(".csv") || fileName.endsWith(".tsv")) {
        CSVFormat csvFormat = CSVFormat.DEFAULT;
        if (fileName.endsWith(".tsv"))
            csvFormat = CSVFormat.TDF.withQuote(null); // We need this to load the AmphibiaWeb files.

        ds = Dataset.fromCSV(csvFormat, f);
    } else {
        // Text-based file? Try using the first line to figure out what's going on.
        String firstLine;
        try (LineNumberReader r = new LineNumberReader(new FileReader(f))) {
            // Load the first line to try to identify the file type.
            firstLine = r.readLine();
        }

        // The most basic type of file is a TaxDiff file, which always
        // begins with:
        if (ChecklistDiff.pTaxDiffFirstLine.matcher(firstLine).matches()) {
            // Note that checklist diffs don't need name extractors!
            return ChecklistDiff.fromTaxDiffFile(f);
        }

        // If all else fails, try loading it as a checklist. Also don't need name extractors!
        return Checklist.fromListInFile(f);
    }

    // If we're here, we need name extractors.

    // Try all name extractors, see which one matches the most names.
    Set<List<NameExtractor>> allAvailableNameExtractors = proj.getNameExtractors();
    allAvailableNameExtractors.add(NameExtractorFactory.getDefaultExtractors());

    LOGGER.info("Starting name extractor comparisons");
    List<NameExtractor> bestExtractor = null;
    long bestExtractorCount = Long.MIN_VALUE;
    for (List<NameExtractor> extractor : allAvailableNameExtractors) {
        long count = ds.rows.stream()
                .flatMap(row -> NameExtractorFactory.extractNamesUsingExtractors(extractor, row).stream())
                .distinct().count();

        if (count > bestExtractorCount) {
            bestExtractorCount = count;
            bestExtractor = extractor;
        }
    }
    LOGGER.info("Finished name extractor comparisons: best extractor at " + bestExtractorCount + " names was "
            + NameExtractorFactory.serializeExtractorsToString(bestExtractor));

    try {
        ds.setNameExtractorsString(NameExtractorFactory.serializeExtractorsToString(bestExtractor));
    } catch (NameExtractorParseException ex) {
        // Forget about it. We'll go with the default.
    }

    return ds;
}

From source file:org.apache.flink.streaming.connectors.kinesis.internals.KinesisDataFetcherTest.java

@Test
public void testPeriodicWatermark() {
    final MutableLong clock = new MutableLong();
    final MutableBoolean isTemporaryIdle = new MutableBoolean();
    final List<Watermark> watermarks = new ArrayList<>();

    String fakeStream1 = "fakeStream1";
    StreamShardHandle shardHandle = new StreamShardHandle(fakeStream1,
            new Shard().withShardId(KinesisShardIdGenerator.generateFromShardOrder(0)));

    TestSourceContext<String> sourceContext = new TestSourceContext<String>() {
        @Override//  w  w w.ja  va 2  s  . c  om
        public void emitWatermark(Watermark mark) {
            watermarks.add(mark);
        }

        @Override
        public void markAsTemporarilyIdle() {
            isTemporaryIdle.setTrue();
        }
    };

    HashMap<String, String> subscribedStreamsToLastSeenShardIdsUnderTest = new HashMap<>();

    final KinesisDataFetcher<String> fetcher = new TestableKinesisDataFetcher<String>(
            Collections.singletonList(fakeStream1), sourceContext, new java.util.Properties(),
            new KinesisDeserializationSchemaWrapper<>(
                    new org.apache.flink.streaming.util.serialization.SimpleStringSchema()),
            1, 1, new AtomicReference<>(), new LinkedList<>(), subscribedStreamsToLastSeenShardIdsUnderTest,
            FakeKinesisBehavioursFactory.nonReshardedStreamsBehaviour(new HashMap<>())) {

        @Override
        protected long getCurrentTimeMillis() {
            return clock.getValue();
        }
    };
    Whitebox.setInternalState(fetcher, "periodicWatermarkAssigner", watermarkAssigner);

    SequenceNumber seq = new SequenceNumber("fakeSequenceNumber");
    // register shards to subsequently emit records
    int shardIndex = fetcher.registerNewSubscribedShardState(new KinesisStreamShardState(
            KinesisDataFetcher.convertToStreamShardMetadata(shardHandle), shardHandle, seq));

    StreamRecord<String> record1 = new StreamRecord<>(String.valueOf(Long.MIN_VALUE), Long.MIN_VALUE);
    fetcher.emitRecordAndUpdateState(record1.getValue(), record1.getTimestamp(), shardIndex, seq);
    Assert.assertEquals(record1, sourceContext.getCollectedOutputs().poll());

    fetcher.emitWatermark();
    Assert.assertTrue("potential watermark equals previous watermark", watermarks.isEmpty());

    StreamRecord<String> record2 = new StreamRecord<>(String.valueOf(1), 1);
    fetcher.emitRecordAndUpdateState(record2.getValue(), record2.getTimestamp(), shardIndex, seq);
    Assert.assertEquals(record2, sourceContext.getCollectedOutputs().poll());

    fetcher.emitWatermark();
    Assert.assertFalse("watermark advanced", watermarks.isEmpty());
    Assert.assertEquals(new Watermark(record2.getTimestamp()), watermarks.remove(0));
    Assert.assertFalse("not idle", isTemporaryIdle.booleanValue());

    // test idle timeout
    long idleTimeout = 10;
    // advance clock idleTimeout
    clock.add(idleTimeout + 1);
    fetcher.emitWatermark();
    Assert.assertFalse("not idle", isTemporaryIdle.booleanValue());
    Assert.assertTrue("not idle, no new watermark", watermarks.isEmpty());

    // activate idle timeout
    Whitebox.setInternalState(fetcher, "shardIdleIntervalMillis", idleTimeout);
    fetcher.emitWatermark();
    Assert.assertTrue("idle", isTemporaryIdle.booleanValue());
    Assert.assertTrue("idle, no watermark", watermarks.isEmpty());
}

From source file:com.mirth.connect.server.controllers.DonkeyMessageController.java

private Map<Long, MessageSearchResult> searchAll(SqlSession session, Map<String, Object> params,
        MessageFilter filter, Long localChannelId, boolean includeMessageData, FilterOptions filterOptions) {
    Map<Long, MessageSearchResult> foundMessages = new HashMap<Long, MessageSearchResult>();

    // Search the message table to find which message ids meet the search criteria.
    List<MessageTextResult> messageResults = session.selectList("Message.searchMessageTable", params);
    /*//from  w  ww. j  a va  2s  . c  om
     * If the message table search provided no records then there is no need to perform any more
     * searches on this range of message ids.
     */
    if (!messageResults.isEmpty()) {
        Set<Long> messageIdSet = new HashSet<Long>(messageResults.size());
        for (MessageTextResult messageResult : messageResults) {
            messageIdSet.add(messageResult.getMessageId());
        }

        /*
         * Search the metadata table to find which message and metadataids meet the search
         * criteria. If a text search is being performed, we also check the connector name
         * column while we're at it.
         */

        List<MessageTextResult> metaDataResults = session.selectList("Message.searchMetaDataTable", params);
        /*
         * Messages that matched the text search criteria. Since text search spans across
         * multiple tables (metadata, content, custom metadata), the map is created it can be
         * used for the searches on each table.
         */
        Map<Long, MessageSearchResult> textMessages = new HashMap<Long, MessageSearchResult>();
        /*
         * Messages that met the criteria on the message and metadata tables and still need to
         * have lengthy search run on them.
         */
        Map<Long, MessageSearchResult> potentialMessages = new HashMap<Long, MessageSearchResult>();
        for (MessageTextResult metaDataResult : metaDataResults) {
            if (messageIdSet.contains(metaDataResult.getMessageId())) {
                if (filterOptions.isSearchText() && metaDataResult.isTextFound() != null
                        && metaDataResult.isTextFound()) {
                    /*
                     * Text search was found in the metadata table so add the message/metadata
                     * id to the text messages.
                     */
                    addMessageToMap(textMessages, metaDataResult.getMessageId(),
                            metaDataResult.getMetaDataId());

                    if (filterOptions.isSearchCustomMetaData() || filterOptions.isSearchContent()) {
                        /*
                         * If content or custom metadata is being searched, still add the
                         * message to potentialMessages so the lengthy search will be run.
                         */
                        addMessageToMap(potentialMessages, metaDataResult.getMessageId(),
                                metaDataResult.getMetaDataId());
                    }
                } else if (filterOptions.isSearchCustomMetaData() || filterOptions.isSearchContent()
                        || filterOptions.isSearchText()) {
                    /*
                     * If no text search was found and any lengthy search is required, add the
                     * message to potentialMessages.
                     */
                    addMessageToMap(potentialMessages, metaDataResult.getMessageId(),
                            metaDataResult.getMetaDataId());
                } else {
                    /*
                     * If no lengthy search is required, just add the message to foundMesages.
                     */
                    addMessageToMap(foundMessages, metaDataResult.getMessageId(),
                            metaDataResult.getMetaDataId());
                }
            }
        }

        // These are no longer used so allow GC to reclaim their memory
        metaDataResults = null;
        messageIdSet = null;
        if (!includeMessageData) {
            messageResults = null;
        }

        if (potentialMessages.isEmpty()) {
            // If lengthy search is not being run, add all text messages to found messages
            foundMessages.putAll(textMessages);
        } else {
            long potentialMin = Long.MAX_VALUE;
            long potentialMax = Long.MIN_VALUE;

            for (long key : potentialMessages.keySet()) {
                if (key < potentialMin) {
                    potentialMin = key;
                }
                if (key > potentialMax) {
                    potentialMax = key;
                }
            }

            Map<String, Object> contentParams = new HashMap<String, Object>();
            contentParams.put("localChannelId", localChannelId);
            contentParams.put("includedMetaDataIds", filter.getIncludedMetaDataIds());
            contentParams.put("excludedMetaDataIds", filter.getExcludedMetaDataIds());
            contentParams.put("minMessageId", potentialMin);
            contentParams.put("maxMessageId", potentialMax);

            boolean searchCustomMetaData = filterOptions.isSearchCustomMetaData();
            boolean searchContent = filterOptions.isSearchContent();
            boolean searchText = filterOptions.isSearchText();

            /*
             * The map of messages that contains the combined results from all of the lengthy
             * searches. For all searches that are being performed, a message and metadata id
             * must be found in all three in order for the message to remain in this map
             */
            Map<Long, MessageSearchResult> tempMessages = null;

            if (searchCustomMetaData) {
                tempMessages = new HashMap<Long, MessageSearchResult>();
                // Perform the custom metadata search
                searchCustomMetaData(session, new HashMap<String, Object>(contentParams), potentialMessages,
                        tempMessages, filter.getMetaDataSearch());

                /*
                 * If tempMessages is empty, there is no need to search on either the content or
                 * text because the join will never return any results
                 */
                if (tempMessages.isEmpty()) {
                    searchContent = false;
                    searchText = false;
                }
            }
            if (searchContent) {
                Map<Long, MessageSearchResult> contentMessages = new HashMap<Long, MessageSearchResult>();
                // Perform the content search
                searchContent(session, new HashMap<String, Object>(contentParams), potentialMessages,
                        contentMessages, filter.getContentSearch());

                if (tempMessages == null) {
                    /*
                     * If temp messages has not been created yet, then there is no need to join
                     * the results from this search and previous searches. Just set the current
                     * messages as the temp messages
                     */
                    tempMessages = contentMessages;
                } else {
                    /*
                     * Otherwise join the two maps so that the only results left in tempMessages
                     * are those that also exist in the current message map
                     */
                    joinMessages(tempMessages, contentMessages);
                }

                /*
                 * If tempMessages is empty, there is no need to search on either the text
                 * because the join will never return any results
                 */
                if (tempMessages.isEmpty()) {
                    searchText = false;
                }
            }
            if (searchText) {
                // Perform the text search
                searchText(session, new HashMap<String, Object>(contentParams), potentialMessages, textMessages,
                        filter.getTextSearchRegex(), filter.getTextSearch(),
                        filter.getTextSearchMetaDataColumns());

                if (tempMessages == null) {
                    /*
                     * If temp messages has not been created yet, then there is no need to join
                     * the results from this search and previous searches. Just set the current
                     * messages as the temp messages
                     */
                    tempMessages = textMessages;
                } else {
                    /*
                     * Otherwise join the two maps so that the only results left in tempMessages
                     * are those that also exist in the current message map
                     */
                    joinMessages(tempMessages, textMessages);
                }
            }

            /*
             * Add all the results from tempMessages after all the joins have been completed
             * into foundMessages
             */
            foundMessages.putAll(tempMessages);
        }

        /*
         * If message data was requested then copy it from the message search into the final
         * results
         */
        if (!foundMessages.isEmpty() && includeMessageData) {
            // Build a map of the message data results for quicker access
            Map<Long, MessageTextResult> messageDataResults = new HashMap<Long, MessageTextResult>(
                    messageResults.size());
            for (MessageTextResult messageResult : messageResults) {
                messageDataResults.put(messageResult.getMessageId(), messageResult);
            }

            /*
             * For each found result, copy over any message data that may have been retrieved
             * already
             */
            for (Entry<Long, MessageSearchResult> entry : foundMessages.entrySet()) {
                Long messageId = entry.getKey();
                MessageSearchResult result = entry.getValue();

                MessageTextResult textResult = messageDataResults.get(messageId);
                if (textResult != null) {
                    result.setImportId(textResult.getImportId());
                    result.setProcessed(textResult.getProcessed());
                }
            }
        }
    }

    return foundMessages;
}

From source file:hudson.model.Computer.java

/**
 * Returns the time when this computer last became idle.
 *
 * <p>//  w  w w  . j  av a  2 s. co  m
 * If this computer is already idle, the return value will point to the
 * time in the past since when this computer has been idle.
 *
 * <p>
 * If this computer is busy, the return value will point to the
 * time in the future where this computer will be expected to become free.
 */
public final long getIdleStartMilliseconds() {
    long firstIdle = Long.MIN_VALUE;
    for (Executor e : oneOffExecutors) {
        firstIdle = Math.max(firstIdle, e.getIdleStartMilliseconds());
    }
    for (Executor e : executors) {
        firstIdle = Math.max(firstIdle, e.getIdleStartMilliseconds());
    }
    return firstIdle;
}