Example usage for java.lang CharSequence length

List of usage examples for java.lang CharSequence length

Introduction

In this page you can find the example usage for java.lang CharSequence length.

Prototype

int length();

Source Link

Document

Returns the length of this character sequence.

Usage

From source file:br.msf.commons.util.CharSequenceUtils.java

public static int countConsonantChain(final CharSequence sequence) {
    if (isBlankOrNull(sequence)) {
        return 0;
    } else if (length(sequence) == 1) {
        return hasConsonant(sequence) ? 1 : 0;
    }//from www.  jav  a 2s.c om
    int max = 0;
    int count = 0;
    for (int i = 0; i < sequence.length(); i++) {
        if (isConsonant(sequence.charAt(i))) {
            count++;
        } else {
            if (count > max) {
                max = count;
            }
            count = 0;
        }
    }
    if (count > max) {
        max = count;
    }
    return max;
}

From source file:edu.cornell.med.icb.goby.modes.VCFSubsetMode.java

private void processOneFile(File inputFile) throws IOException {
    System.out.printf("Preparing to process %s..%n", inputFile);
    // eliminate lines from the header that try to define some field in ALT:
    final GrepReader filter = new GrepReader(inputFile.getPath(), "^##ALT=");

    final VCFParser parser = new VCFParser(filter);
    final Columns columns = new Columns();
    final ObjectArrayList<String> sampleIdList = new ObjectArrayList<String>();
    boolean[] includeField = null;
    try {/*  w  ww  .j  a v a2 s  . co m*/
        parser.readHeader();
        final Columns fileColumns = parser.getColumns();

        includeField = new boolean[parser.countAllFields()];

        for (final ColumnInfo col : fileColumns) {
            if (columns.find(col.getColumnName()) == null) {
                columns.add(col);
                if (col.useFormat) {
                    final String sampleId = col.getColumnName();
                    if (!sampleIdList.contains(sampleId) && includeSampleId(sampleId)) {
                        for (final ColumnField field : col.fields) {
                            includeField[field.globalFieldIndex] = true;
                        }
                        sampleIdList.add(sampleId);

                    }
                } else {
                    for (final ColumnField field : col.fields) {
                        includeField[field.globalFieldIndex] = true;
                    }
                }
            }
        }
        if (sampleIdList.size() == 0) {
            System.err.println(
                    "Column selection matched no samples. Only the header would be written to the output. Aborted.");
            System.out
                    .println("Sample names were: " + ObjectArrayList.wrap(parser.getColumnNamesUsingFormat()));
            System.exit(1);
        }
    } catch (VCFParser.SyntaxException e) {
        e.printStackTrace();
        System.exit(1);
    }
    final String inputFilename = removeExtensions(inputFile);

    final int chromosomeFieldIndex = getGlobalFieldIndex(columns, "CHROM");
    final int positionFieldIndex = getGlobalFieldIndex(columns, "POS");
    final int idFieldIndex = getGlobalFieldIndex(columns, "ID");
    final int refFieldIndex = getGlobalFieldIndex(columns, "REF");
    final int altFieldIndex = getGlobalFieldIndex(columns, "ALT");
    final int qualFieldIndex = getGlobalFieldIndex(columns, "QUAL");
    final int filterFieldIndex = getGlobalFieldIndex(columns, "FILTER");
    final int[] requiredFields = new int[requiredInfoFlags.length];
    for (int i = 0; i < requiredInfoFlags.length; i++) {
        requiredFields[i] = parser.getGlobalFieldIndex("INFO", requiredInfoFlags[i]);
    }
    final IntSet infoFieldGlobalIndices = new IntOpenHashSet();
    sampleIndexToDestinationIndex = new int[parser.countAllFields()];
    for (final ColumnField infoField : parser.getColumns().find("INFO").fields) {
        infoFieldGlobalIndices.add(infoField.globalFieldIndex);
    }

    final IntSet formatFieldGlobalIndices = new IntOpenHashSet();
    final Int2IntMap globalIndexToSampleIndex = new Int2IntOpenHashMap();
    int sampleIndex = 0;

    for (ColumnInfo col : columns) {
        if (col.useFormat) {

            for (ColumnField field : col.fields) {
                String sampleId = col.getColumnName();
                if (sampleIdList.contains(sampleId)) {
                    sampleIndexToDestinationIndex[sampleIndex] = sampleIdList.indexOf(sampleId);
                }
                globalIndexToSampleIndex.put(field.globalFieldIndex, sampleIndex++);
                formatFieldGlobalIndices.add(field.globalFieldIndex);
            }
        }
    }

    int infoFieldIndex = 0;
    int formatFieldCount = 0;
    int previousSampleIndex = -1;

    // transfer the reduced schema to the output writer:
    VCFWriter writer = new VCFWriter(
            new BlockCompressedOutputStream(inputFilename + outputFilename + ".vcf.gz"));

    writer.defineSchema(columns);
    writer.defineSamples(sampleIdList.toArray(new String[sampleIdList.size()]));
    writer.writeHeader();
    System.out.printf("Loading %s..%n", inputFilename);
    int index = 0;
    final ProgressLogger pg = new ProgressLogger(LOG);
    pg.displayFreeMemory = true;
    pg.start();
    final int fieldCount = parser.countAllFields();
    final IntArrayList fieldsToTraverse = new IntArrayList();
    fieldsToTraverse.addAll(infoFieldGlobalIndices);
    fieldsToTraverse.addAll(formatFieldGlobalIndices);
    for (int i = 0; i < filterFieldIndex; i++) {
        fieldsToTraverse.add(i);
    }
    Collections.sort(fieldsToTraverse);
    // assume the field has constant format columns. This optimization saves a lot of time.
    if (optimizeForContantFormat) {
        parser.setCacheFieldPermutation(true);
    }
    try {
        while (parser.hasNextDataLine()) {
            boolean allGenotypeHomozygous = true;

            final String format = parser.getStringColumnValue(columns.find("FORMAT").columnIndex);
            final String[] formatTokens = format.split(":");
            final int numFormatFields = columns.find("FORMAT").fields.size();

            int formatFieldIndex = 0;
            infoFieldIndex = 0;
            int position = 0;
            for (final int globalFieldIndex : fieldsToTraverse) {
                final String value = parser.getStringFieldValue(globalFieldIndex);
                if (globalFieldIndex == chromosomeFieldIndex) {
                    writer.setChromosome(value);
                } else if (globalFieldIndex == positionFieldIndex) {
                    position = Integer.parseInt(value);
                    writer.setPosition(position);

                } else if (globalFieldIndex == idFieldIndex) {
                    writer.setId(value);
                } else if (globalFieldIndex == refFieldIndex) {
                    writer.setReferenceAllele(value);
                } else if (globalFieldIndex == altFieldIndex) {
                    writer.setAlternateAllele(value);
                } else if (globalFieldIndex == qualFieldIndex) {
                    writer.setQual(value);
                } else if (globalFieldIndex == filterFieldIndex) {
                    writer.setFilter(value);
                }
                if (infoFieldGlobalIndices.contains(globalFieldIndex)) {
                    writer.setInfo(infoFieldIndex++, value);
                }

                if (formatFieldGlobalIndices.contains(globalFieldIndex)) {

                    if (formatFieldIndex < formatTokens.length) {
                        if (!"".equals(formatTokens[formatFieldIndex])) {
                            if (includeField[globalFieldIndex]) {
                                final int destinationSampleIndex = sampleIndexToDestinationIndex[globalIndexToSampleIndex
                                        .get(globalFieldIndex)];
                                writer.setSampleValue(formatTokens[formatFieldIndex], destinationSampleIndex,
                                        value);
                                if (excludeRef) {

                                    if ("GT".equals(formatTokens[formatFieldIndex])) {
                                        allGenotypeHomozygous &= "0|0".equals(value) || "0/0".equals(value)
                                                || ".|.".equals(value) || "./.".equals(value);
                                    }
                                } else {
                                    allGenotypeHomozygous = false;
                                }
                            }
                        }
                        formatFieldCount++;
                        if (value.length() != 0) {
                            formatFieldIndex++;
                        }
                        if (formatFieldCount == numFormatFields) {
                            formatFieldIndex = 0;
                            formatFieldCount = 0;
                            sampleIndex++;
                        }
                    }
                }
            }
            // check that all required fields are present in the record:
            boolean requiredFlagsAllPresent = true;
            for (final int fieldIndex : requiredFields) {
                final CharSequence fieldValue = parser.getFieldValue(fieldIndex);
                requiredFlagsAllPresent &= fieldValue != null && fieldValue.length() > 0;
            }
            parser.next();
            pg.lightUpdate();

            final boolean keepRecord = !allGenotypeHomozygous && requiredFlagsAllPresent;

            if (keepRecord) {
                writer.writeRecord();
            } else {
                writer.clear();
            }
        }
    } finally {
        pg.stop("Done with file " + inputFilename);
        parser.close();
        writer.close();
    }
}

From source file:com.google.zxing.client.android.result.ResultHandler.java

/**
 * Do a geo search using the address as the query.
 *
 * @param address The address to find//www  . j a  v a 2s  .  c  o m
 * @param title An optional title, e.g. the name of the business at this address
 */
final void searchMap(String address, CharSequence title) {
    String query = address;
    if (title != null && title.length() > 0) {
        query += " (" + title + ')';
    }
    launchIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + Uri.encode(query))));
}

From source file:io.selendroid.server.model.AndroidNativeElement.java

public JSONObject toJson() throws JSONException {
    JSONObject object = new JSONObject();
    JSONObject l10n = new JSONObject();
    l10n.put("matches", 0);
    object.put("l10n", l10n);
    CharSequence cd = getView().getContentDescription();
    if (cd != null && cd.length() > 0) {
        String label = String.valueOf(cd);
        object.put("name", label);
    } else {//from  ww  w  .j a  va2  s  .  co m
        object.put("name", "");
    }
    String id = getNativeId();
    object.put("id", id.startsWith("id/") ? id.replace("id/", "") : id);
    JSONObject rect = new JSONObject();

    object.put("rect", rect);
    JSONObject origin = new JSONObject();
    Point location = getLocation();
    origin.put("x", location.x);
    origin.put("y", location.y);
    rect.put("origin", origin);

    JSONObject size = new JSONObject();
    Dimension s = getSize();
    size.put("height", s.getHeight());
    size.put("width", s.getWidth());
    rect.put("size", size);

    object.put("ref", ke.getIdOfElement(this));
    object.put("type", getView().getClass().getSimpleName());
    String value = "";
    if (getView() instanceof TextView) {
        value = String.valueOf(((TextView) getView()).getText());
    }
    object.put("value", value);
    object.put("shown", getView().isShown());
    if (getView() instanceof WebView) {
        final WebView webview = (WebView) getView();
        final WebViewSourceClient client = new WebViewSourceClient();
        instrumentation.getCurrentActivity().runOnUiThread(new Runnable() {
            public void run() {
                synchronized (syncObject) {
                    webview.getSettings().setJavaScriptEnabled(true);

                    webview.setWebChromeClient(client);
                    String script = "document.body.parentNode.innerHTML";
                    webview.loadUrl("javascript:alert('selendroidSource:'+" + script + ")");
                }
            }
        });
        long end = System.currentTimeMillis() + 10000;
        waitForDone(end, UI_TIMEOUT, "Error while grabbing web view source code.");
        object.put("source", "<html>" + client.result + "</html>");
    }

    return object;
}

From source file:com.cyberway.issue.extractor.RegexpHTMLLinkExtractor.java

/**
 * @param sequence/*from w ww .j  av  a  2 s.co  m*/
 * @param endOfOpenTag
 */
protected void processStyle(CharSequence sequence, int endOfOpenTag) {
    // First, get attributes of script-open tag as per any other tag.
    processGeneralTag(sequence.subSequence(0, 6), sequence.subSequence(0, endOfOpenTag));

    // then, parse for URIs
    RegexpCSSLinkExtractor.extract(sequence.subSequence(endOfOpenTag, sequence.length()), source, base, next,
            extractErrorListener);
}

From source file:com.halzhang.android.apps.startupnews.ui.tablet.DiscussFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    setHasOptionsMenu(true);//from www . j  ava2  s .  co  m
    View view = inflater.inflate(R.layout.fragment_discuss, null);
    mListView = (ListView) view.findViewById(android.R.id.list);
    mListView.setOnItemClickListener(this);
    mSnDiscuss = new SNDiscuss();
    Bundle args = getArguments();
    SNNew snNew = null;
    if (args != null && args.containsKey(DiscussActivity.ARG_DISCUSS_URL)) {
        mDiscussURL = args.getString(DiscussActivity.ARG_DISCUSS_URL);
    } else {
        throw new IllegalArgumentException("Discuss URL is required!");
    }
    if (args.containsKey(DiscussActivity.ARG_SNNEW)) {
        snNew = (SNNew) args.getSerializable(DiscussActivity.ARG_SNNEW);
        mSnDiscuss.setSnNew(snNew);
    }
    mAdapter = new DiscussCommentAdapter();
    View headerView = inflater.inflate(R.layout.discuss_header_view, null);
    mTitle = (TextView) headerView.findViewById(R.id.discuss_news_title);
    mSubTitle = (TextView) headerView.findViewById(R.id.discuss_news_subtitle);
    mText = (TextView) headerView.findViewById(R.id.discuss_text);

    mSendBtn = (ImageButton) view.findViewById(R.id.discuss_comment_send_btn);
    mSendBtn.setEnabled(false);
    mSendBtn.setOnClickListener(mSendBtnClickListener);
    mCommentEdit = (EditText) view.findViewById(R.id.discuss_comment_edit);
    mCommentEdit.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            mSendBtn.setEnabled(s.length() > 0);
        }
    });
    mListView.addHeaderView(headerView);
    mListView.setAdapter(mAdapter);
    wrapHeaderView(snNew);
    loadData();
    return view;
}

From source file:it.unimi.dsi.util.ImmutableExternalPrefixMap.java

private boolean isEncodable(final CharSequence s) {
    for (int i = s.length(); i-- != 0;)
        if (!char2symbol.containsKey(s.charAt(i)))
            return false;
    return true;// w w  w  .j  av  a  2 s . c o m
}

From source file:com.asakusafw.runtime.io.text.driver.InputDriver.java

private boolean compareHeader() throws IOException {
    int matched = 0;
    for (FieldDriver<?, ?> field : fields) {
        while (reader.nextField()) {
            CharSequence value = reader.getContent();
            String label = field.name;
            if (value != null) {
                if (trimExtraInput) {
                    value = trimmer.wrap(value);
                    label = label.trim();
                }//from  w  ww .j  a v  a2 s.  c  om
                if (value.length() == 0 && field.skipEmptyInput) {
                    if (LOG.isTraceEnabled()) {
                        LOG.trace(String.format("skip empty header field: path=%s, column=%,d", path,
                                reader.getFieldIndex()));
                    }
                    continue;
                }
            }
            if (value == null || label.contentEquals(value) == false) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug(String.format("header mismatch: path=%s, column=%,d, expected=%s, appeared=%s", //$NON-NLS-1$
                            path, reader.getFieldIndex(), TextUtil.quote(field.name),
                            value == null ? "null" : TextUtil.quote(value))); //$NON-NLS-1$
                }
                return false;
            }
            matched++;
            break;
        }
    }
    if (checkHeaderFieldCount(matched, onLessInput) == false) {
        return false;
    }
    if (checkHeaderFieldCount(fields.length + countRest(), onMoreInput) == false) {
        return false;
    }
    return true;
}

From source file:com.android.screenspeak.eventprocessor.ProcessorPhoneticLetters.java

/**
 * Handle an event that indicates a text is being traversed at character
 * granularity./*  www  .  ja v  a 2s .  c om*/
 */
private void processTraversalEvent(AccessibilityEvent event) {
    final CharSequence text = AccessibilityEventUtils.getEventTextOrDescription(event);
    if (TextUtils.isEmpty(text)) {
        return;
    }

    String letter;
    if ((event.getAction() == AccessibilityNodeInfoCompat.ACTION_NEXT_AT_MOVEMENT_GRANULARITY
            || event.getAction() == AccessibilityNodeInfoCompat.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY)
            && event.getFromIndex() >= 0 && event.getFromIndex() < text.length()) {
        letter = String.valueOf(text.charAt(event.getFromIndex()));
    } else {
        return;
    }

    String phoneticLetter = getPhoneticLetter(Locale.getDefault().toString(), letter);
    if (phoneticLetter != null) {
        postPhoneticLetterRunnable(phoneticLetter);
    }
}

From source file:org.bwgz.quotation.activity.QuotationActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    boolean result = false;

    switch (item.getItemId()) {
    case R.id.actionbar_back: {
        Log.d(TAG, String.format("onOptionsItemSelected - actionbar_back"));
        if (history.hasBack()) {
            loadQuote(history.back());//from  ww w  .j a  v a2 s  .  c  o  m
        }

        menu.findItem(R.id.actionbar_back).setEnabled(history.hasBack());
        menu.findItem(R.id.actionbar_forward).setEnabled(history.hasForward());

        EasyTracker.getInstance(this)
                .send(MapBuilder.createEvent("ui_action", "button_press", "menu_back", null).build());
        result = true;
        break;
    }
    case R.id.actionbar_forward: {
        Log.d(TAG, String.format("onOptionsItemSelected - actionbar_forward"));
        if (history.hasForward()) {
            loadQuote(history.forward());
        }

        menu.findItem(R.id.actionbar_back).setEnabled(history.hasBack());
        menu.findItem(R.id.actionbar_forward).setEnabled(history.hasForward());

        EasyTracker.getInstance(this)
                .send(MapBuilder.createEvent("ui_action", "button_press", "menu_forward", null).build());
        result = true;
        break;
    }
    case R.id.actionbar_new: {
        loadRandomQuote();

        EasyTracker.getInstance(this)
                .send(MapBuilder.createEvent("ui_action", "button_press", "menu_new", null).build());
        result = true;
        break;
    }
    case R.id.actionbar_share: {
        CharSequence text = ((TextView) findViewById(R.id.quotation)).getText();
        if (text != null && text.length() != 0) {
            StringBuilder buffer = new StringBuilder();
            buffer.append(text);

            text = ((TextView) findViewById(R.id.author)).getText();
            if (text != null && text.length() != 0) {
                buffer.append(" ... ");
                buffer.append(text);
            }

            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_TEXT, buffer.toString());
            startActivity(Intent.createChooser(intent, getResources().getText(R.string.sharing_quote)));
        }

        EasyTracker.getInstance(this)
                .send(MapBuilder.createEvent("ui_action", "button_press", "menu_share", null).build());
        result = true;
        break;
    }
    case R.id.settings: {
        Intent intent = new Intent().setClass(this, SettingsActivity.class);
        startActivity(intent);

        EasyTracker.getInstance(this)
                .send(MapBuilder.createEvent("ui_action", "button_press", "menu_settings", null).build());
        result = true;
        break;
    }
    }

    return result;
}