Fixes for "java.lang.IndexOutOfBoundsException Invalid index 0, size is 0"
on "android.support.v4.view.ViewPager.performDrag"
337059
@Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        try {
            if (event == null || getAdapter() == null || getAdapter().getCount() == 0) {
                return false;
            }
            return super.onInterceptTouchEvent(event);
        } catch (RuntimeException e) {
            Log.e(TAG, "Exception during WrapContentViewPager onTouchEvent: " +
                    "index out of bound, or nullpointer even if we check the adapter before " + e.toString());
            return false;
        }
    }
1304157
private void doGetTLDs() throws PageException {
	lucee.runtime.type.Query qry = new QueryImpl(
		new String[] { "displayname", "namespace", "namespaceseparator", "shortname", "type", "description", "uri", "elclass", "elBundleName", "elBundleVersion",
			"source" },
		new String[] { "varchar", "varchar", "varchar", "varchar", "varchar", "varchar", "varchar", "varchar", "varchar", "varchar", "varchar" }, 0, "tlds");

	int dialect = "lucee".equalsIgnoreCase(getString("dialect", "cfml")) ? CFMLEngine.DIALECT_LUCEE : CFMLEngine.DIALECT_CFML;

	TagLib[] libs = config.getTLDs(dialect);
	for (int i = 0; i < libs.length; i++) {
	    qry.addRow();
	    qry.setAt("displayname", i + 1, libs[i].getDisplayName());
	    qry.setAt("namespace", i + 1, libs[i].getNameSpace());
	    qry.setAt("namespaceseparator", i + 1, libs[i].getNameSpaceSeparator());
	    qry.setAt("shortname", i + 1, libs[i].getShortName());
	    qry.setAt("type", i + 1, libs[i].getType());
	    qry.setAt("description", i + 1, libs[i].getDescription());
	    qry.setAt("uri", i + 1, Caster.toString(libs[i].getUri()));
	    qry.setAt("elclass", i + 1, libs[i].getELClassDefinition().getClassName());
	    qry.setAt("elBundleName", i + 1, libs[i].getELClassDefinition().getName());
	    qry.setAt("elBundleVersion", i + 1, libs[i].getELClassDefinition().getVersionAsString());
	    qry.setAt("source", i + 1, StringUtil.emptyIfNull(libs[i].getSource()));
	}
	pageContext.setVariable(getString("admin", action, "returnVariable"), qry);
    }
343312
public synchronized void insert(XEvent event, int index)
			throws IndexOutOfBoundsException, IOException {
		if (index < 0 || index > size) {
			throw new IndexOutOfBoundsException();
		}
		// check if we can append
		if (index == size) {
			append(event);
			return;
		}
		// adjust size and overflow size
		size++;
		overflowSize++;
		// add to overflow set
		for (int i = overflowSize - 2; i >= 0; i--) {
			if (overflowIndices[i] >= index) {
				overflowIndices[i + 1] = overflowIndices[i] + 1;
				overflowEntries[i + 1] = overflowEntries[i];
			} else {
				overflowIndices[i + 1] = index;
				overflowEntries[i + 1] = event;
				if (overflowSize == overflowIndices.length) {
					consolidate();
				}
				return;
			}
		}
		// if we arrive here, we must insert at zero
		overflowIndices[0] = index;
		overflowEntries[0] = event;
		if (overflowSize == overflowIndices.length) {
			consolidate();
		}
	}
348319
@Override
    public Status updateIndexes(List<ViewStore> inputViews) throws CouchbaseLiteException {
        synchronized (lockUpdateIndexes) {
            assert (inputViews != null);

            // workaround
            if (!inputViews.contains(this))
                inputViews.add(this);

            final ArrayList<View> views = new ArrayList<View>(inputViews.size());
            final ArrayList<Mapper> mapBlocks = new ArrayList<Mapper>(inputViews.size());
            final ArrayList<String> docTypes = new ArrayList<String>(inputViews.size());
            boolean useDocType = false;
            for (ViewStore v : inputViews) {
                ForestDBViewStore view = (ForestDBViewStore) v;
                ViewStoreDelegate delegate = view.getDelegate();
                Mapper map = delegate != null ? delegate.getMap() : null;
                if (map == null) {
                    Log.v(Log.TAG_VIEW, "    %s has no map block; skipping it", view.getName());
                    continue;
                }
                try {
                    view.openIndex();
                } catch (ForestException e) {
                    throw new CouchbaseLiteException(ForestBridge.err2status(e));
                }
                views.add(view._view);
                mapBlocks.add(map);
                String docType = delegate.getDocumentType();
                docTypes.add(docType);
                if (docType != null && !useDocType)
                    useDocType = true;
            }

            if (views.size() == 0) {
                Log.v(TAG, "    No input views to update the index");
                return new Status(Status.NOT_MODIFIED);
            }

            boolean success = false;
            Indexer indexer = null;
            try {
                indexer = new Indexer(views.toArray(new View[views.size()]));
                indexer.triggerOnView(this._view);
                DocumentIterator itr;
                try {
                    itr = indexer.iterateDocuments();
                    if (itr == null)
                        return new Status(Status.NOT_MODIFIED);
                } catch (ForestException e) {
                    if (e.code == FDBErrors.FDB_RESULT_SUCCESS)
                        return new Status(Status.NOT_MODIFIED);
                    else
                        throw new CouchbaseLiteException(ForestBridge.err2status(e));
                }
                // Now enumerate the docs:
                Document doc;
                while ((doc = itr.nextDocument()) != null) {
                    // For each updated document:
                    try {
                        String docType = useDocType ? doc.getType() : null;
                        // Skip design docs
                        boolean validDocToIndex =
                                !doc.deleted() && !doc.getDocID().startsWith("_design/");
                        // Read the document body:
                        Map<String, Object> body = ForestBridge.bodyOfSelectedRevision(doc);
                        body.put("_id", doc.getDocID());
                        body.put("_rev", doc.getRevID());
                        body.put("_local_seq", doc.getSequence());
                        if (doc.conflicted()) {
                            List<String> currentRevIDs = ForestBridge.getCurrentRevisionIDs(doc);
                            if (currentRevIDs != null && currentRevIDs.size() > 1)
                                body.put("_conflicts",
                                        currentRevIDs.subList(1, currentRevIDs.size()));
                        }
                        // Feed it to each view's map function:
                        for (int viewNumber = 0; viewNumber < views.size(); viewNumber++) {
                            if (!indexer.shouldIndex(doc, viewNumber))
                                continue;

                            boolean indexIt = validDocToIndex;
                            if (indexIt && useDocType) {
                                String viewDocType = docTypes.get(viewNumber);
                                if (viewDocType != null)
                                    indexIt = viewDocType.equals(docType);
                            }

                            if (indexIt)
                                emit(indexer, viewNumber, doc, body, mapBlocks.get(viewNumber));
                            else
                                emit(indexer, viewNumber, doc, body, null);
                        }
                    } finally {
                        doc.free();
                    }
                }
                success = true;
            } catch (ForestException e) {
                throw new CouchbaseLiteException(ForestBridge.err2status(e));
            } finally {
                if (indexer != null) {
                    try {
                        indexer.endIndex(success);
                    } catch (ForestException ex) {
                        Log.e(TAG, "Failed to call Indexer.endIndex(boolean)", ex);
                        if (success)
                            throw new CouchbaseLiteException(ForestBridge.err2status(ex));
                    }
                }
            }
            Log.v(TAG, "... Finished re-indexing (%s)", viewNames(inputViews));
            return new Status(Status.OK);
        }
    }
496968
void fillPage(final int position) {
        if (Constants.DEBUG) {
            Log.d("InfiniteViewPager", "setup Page " + position);
            printPageModels("before newPage");
        }
        final PageModel<T> oldModel = mPageModels[position];
        final PageModel<T> newModel = createPageModel(position);
        if (oldModel == null || newModel == null) {
            Log.w(Constants.LOG_TAG, "fillPage no model found " + oldModel + " " + newModel);
            return;
        }
        // moving the new created views to the page of the viewpager
        oldModel.removeAllChildren();
        for (final View newChild : newModel.getChildren()) {
            newModel.removeViewFromParent(newChild);
            oldModel.addChild(newChild);
        }

        mPageModels[position].setIndicator(newModel.getIndicator());
    }
700651
public void doTag()
            throws JspException
    {
        PageContext pageContext = getPageContext();

        // Were any error messages specified?
        ActionMessages errors = null;
        try {
            errors = RequestUtils.getActionMessages(pageContext, Globals.ERROR_KEY);
        }
        catch (JspException e) {
            RequestUtils.saveException(pageContext, e);
            throw e;
        }

        if ((errors == null) || errors.isEmpty()) {
            if (hasErrors())
                reportErrors();
            return;
        }

        String qualifiedBundle = InternalUtils.getQualifiedBundleName(_bundleName, pageContext.getRequest());

        boolean headerPresent = false;
        boolean footerPresent = false;
        boolean prefixPresent = false;
        boolean suffixPresent = false;

        String locale = _locale;
        if (!isMissingUserDefaultMessages(pageContext)) {
            try {
                // Check for presence of header and footer message keys
                headerPresent =
                        RequestUtils.present(pageContext, qualifiedBundle, locale, "errors.header");
                footerPresent =
                        RequestUtils.present(pageContext, qualifiedBundle, locale, "errors.footer");
                prefixPresent =
                        RequestUtils.present(pageContext, qualifiedBundle, locale, "errors.prefix");
                suffixPresent =
                        RequestUtils.present(pageContext, qualifiedBundle, locale, "errors.suffix");
            }
            catch (JspException e) {
                String s = Bundle.getString("Tags_ErrorsException",
                        new Object[]{e.getMessage()});
                registerTagError(s, null);
                reportErrors();
                return;
            }
        }

        // Render the error messages appropriately
        InternalStringBuilder results = new InternalStringBuilder(128);
        boolean headerDone = false;
        String message = null;
        Iterator reports = null;
        reports = errors.get();

        while (reports.hasNext()) {
            ActionMessage report = (ActionMessage) reports.next();
            if (!headerDone) {
                if (headerPresent) {
                    message = RequestUtils.message(pageContext, qualifiedBundle, locale, "errors.header");
                    results.append(message);
                    results.append("\r\n");
                }
                headerDone = true;
            }
            if (prefixPresent) {
                message = RequestUtils.message(pageContext, qualifiedBundle, locale, "errors.prefix");
                results.append(message);
            }
            message = getErrorMessage(report, qualifiedBundle);
            if (message != null) {
                results.append(message);
                results.append("\r\n");
            }
            if (suffixPresent) {
                message = RequestUtils.message(pageContext, qualifiedBundle, locale, "errors.suffix");
                results.append(message);
            }
        }
        if (headerDone && footerPresent) {
            message = RequestUtils.message(pageContext, qualifiedBundle, locale, "errors.footer");
            results.append(message);
            results.append("\r\n");
        }

        if (hasErrors())
            reportErrors();

        // Print the results to our output writer
        write(results.toString());
    }
856185
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
	@Override
	int calculateEndLeftBound(float xAxisDelta) {
		return (int) (getView().getX() + xAxisDelta);
	}
156371
@Override
    @InterfaceAudience.Private
    public Status updateIndexes(List<ViewStore> inputViews) throws CouchbaseLiteException {
        Log.v(Log.TAG_VIEW, "Re-indexing view: %s", name);
        if (getViewID() <= 0) {
            String msg = "getViewID() < 0";
            throw new CouchbaseLiteException(msg, Status.NOT_FOUND);
        }

        if (!store.beginTransaction())
            throw new CouchbaseLiteException("Error in beginTransaction()", Status.DB_ERROR);

        boolean success = false;
        Cursor cursor = null;
        try {
            // If the view the update is for doesn't need any update, don't do anything:
            final long dbMaxSequence = store.getLastSequence();
            final long forViewLastSequence = getLastSequenceIndexed();
            if (forViewLastSequence >= dbMaxSequence) {
                success = true;
                return new Status(Status.NOT_MODIFIED);
            }

            // Check whether we need to update at all,
            // and remove obsolete emitted results from the 'maps' table:
            long minLastSequence = dbMaxSequence;
            final long[] viewLastSequence = new long[inputViews.size()];
            int deletedCount = 0;
            int i = 0;
            final HashSet<String> docTypes = new HashSet<String>();
            HashMap<String, String> viewDocTypes = null;
            boolean allDocTypes = false;
            final HashMap<Integer, Integer> viewTotalRows = new HashMap<Integer, Integer>();
            final ArrayList<SQLiteViewStore> views = new ArrayList<SQLiteViewStore>();
            final ArrayList<Mapper> mapBlocks = new ArrayList<Mapper>();

            for (ViewStore v : inputViews) {
                assert (v != null);
                SQLiteViewStore view = (SQLiteViewStore) v;
                ViewStoreDelegate delegate = view.getDelegate();
                Mapper map = delegate != null ? delegate.getMap() : null;
                if (map == null) {
                    if (view == this) {
                        String msg = String.format(Locale.ENGLISH, "Cannot index view %s: " +
                                "no map block registered", view.getName());
                        Log.e(Log.TAG_VIEW, msg);
                        throw new CouchbaseLiteException(msg, Status.BAD_REQUEST);
                    }
                    Log.v(Log.TAG_VIEW, "    %s has no map block; skipping it", view.getName());
                    continue;
                }

                views.add(view);
                mapBlocks.add(map);

                int viewID = view.getViewID();
                if (viewID <= 0) {
                    String message = String.format(Locale.ENGLISH, "View '%s' not found in database",
                            view.getName());
                    Log.e(Log.TAG_VIEW, message);
                    throw new CouchbaseLiteException(message, Status.NOT_FOUND);
                }

                int totalRows = view.getTotalRows();
                viewTotalRows.put(viewID, totalRows);

                long last = view == this ? forViewLastSequence : view.getLastSequenceIndexed();
                viewLastSequence[i++] = last;
                if (last < 0) {
                    String msg = String.format(Locale.ENGLISH, "last < 0 (%d)", last);
                    throw new CouchbaseLiteException(msg, Status.INTERNAL_SERVER_ERROR);
                } else if (last < dbMaxSequence) {
                    if (last == 0)
                        view.createIndex();
                    minLastSequence = Math.min(minLastSequence, last);
                    Log.v(Log.TAG_VIEW, "    %s last indexed at #%d", view.getName(), last);

                    String docType = delegate.getDocumentType();
                    if (docType != null) {
                        docTypes.add(docType);
                        if (viewDocTypes == null)
                            viewDocTypes = new HashMap<String, String>();
                        viewDocTypes.put(view.getName(), docType);
                    } else {
                        allDocTypes = true;
                    }

                    int changes = 0;
                    if (last == 0) {
                        changes = store.getStorageEngine().delete(view.queryString("maps_#"), null, null);
                    } else {
                        store.optimizeSQLIndexes();
                        String[] args = {Long.toString(last), Long.toString(last)};
                        changes = store.getStorageEngine().delete(view.queryString("maps_#"),
                                "sequence IN (SELECT parent FROM revs " +
                                        "WHERE sequence>? AND +parent>0 AND +parent<=?)", args);
                    }

                    // Update #deleted rows:
                    deletedCount += changes;

                    // Only count these deletes as changes if this isn't a view reset to 0
                    if (last != 0) {
                        int newTotalRows = viewTotalRows.get(viewID) - changes;
                        viewTotalRows.put(viewID, newTotalRows);
                    }
                }
            }

            if (minLastSequence == dbMaxSequence) {
                Log.v(Log.TAG_VIEW, "minLastSequence (%d) == dbMaxSequence (%d), nothing to do",
                        minLastSequence, dbMaxSequence);
                success = true;
                return new Status(Status.NOT_MODIFIED);
            }

            Log.v(Log.TAG_VIEW, "Updating indexes of (%s) from #%d to #%d ...",
                    viewNames(views), minLastSequence, dbMaxSequence);

            // This is the emit() block, which gets called from within the user-defined map() block
            // that's called down below.
            final AtomicInteger insertedCount = new AtomicInteger(0);
            AbstractMapEmitBlock emitBlock = new AbstractMapEmitBlock() {
                @Override
                public void emit(Object key, Object value) {
                    if (key == null) {
                        Log.w(Log.TAG_VIEW, "emit() called with nil key; ignoring");
                        return;
                    }
                    try {
                        curView.emit(key, value, this.sequence); // emit block's sequence
                        int curViewID = curView.getViewID();
                        viewTotalRows.put(curViewID, viewTotalRows.get(curViewID) + 1);
                    } catch (Exception e) {
                        Log.e(Log.TAG_VIEW, "Error emitting", e);
                        throw new RuntimeException(e);
                    }
                }
            };

            // Now scan every revision added since the last time the view was indexed:

            // NOTE: Below is original Query. In case query result uses a lot of memory,
            //       Android SQLiteDatabase causes null value column. Then it causes the missing
            //       _index data because following logic skip result if column is null.
            //       To avoid the issue, retrieving json field is isolated from original query.
            //       Because json field could be large, maximum size is 2MB.
            // StringBuffer sql = new StringBuffer( "SELECT revs.doc_id, sequence, docid, revid,
            // json, no_attachments, deleted FROM revs, docs WHERE sequence>? AND current!=0 ");

            boolean checkDocTypes = docTypes.size() > 1 || (allDocTypes && docTypes.size() > 0);
            StringBuilder sql = new StringBuilder(
                    "SELECT revs.doc_id, sequence, docid, revid, no_attachments, deleted ");
            if (checkDocTypes)
                sql.append(", doc_type ");
            sql.append("FROM revs ");
            sql.append("JOIN docs ON docs.doc_id = revs.doc_id ");
            sql.append("WHERE sequence>? AND +current>0 ");
            if (minLastSequence == 0) {
                sql.append("AND +deleted=0 ");
            }
            if (!allDocTypes && docTypes.size() > 0) {
                String docTypesString = getJoinedSQLQuotedStrings(
                        docTypes.toArray(new String[docTypes.size()]));
                sql.append("AND doc_type IN (").append(docTypesString).append(") ");
            }
            // order result by deleted ASC so if multiple revs returned the non deleted are the first
            // NOTE: Views broken with concurrent update and delete
            // https://github.com/couchbase/couchbase-lite-java-core/issues/952
            sql.append("ORDER BY +revs.doc_id, +deleted, +revid DESC");
            String[] selectArgs = {Long.toString(minLastSequence)};
            cursor = store.getStorageEngine().rawQuery(sql.toString(), selectArgs);

            boolean keepGoing = cursor.moveToNext(); // Go to first result row
            while (keepGoing) {
                // NOTE: skip row if 1st column is null
                // https://github.com/couchbase/couchbase-lite-java-core/issues/497
                if (cursor.isNull(0)) {
                    keepGoing = cursor.moveToNext();
                    continue;
                }

                long docID = cursor.getLong(0);

                // Reconstitute the document as a dictionary:
                long sequence = cursor.getLong(1);
                String docId = cursor.getString(2);
                if (docId.startsWith("_design/")) {  // design docs don't get indexed!
                    keepGoing = cursor.moveToNext();
                    continue;
                }
                String revID = cursor.getString(3);
                boolean deleted = cursor.getInt(5) > 0;
                String docType = checkDocTypes ? cursor.getString(6) : null;

                // Skip rows with the same doc_id -- these are losing conflicts.
                // NOTE: Or Skip rows if 1st column is null
                // https://github.com/couchbase/couchbase-lite-java-core/issues/497
                ArrayList<String> conflicts = null;
                boolean isNull;
                while ((keepGoing = cursor.moveToNext()) &&
                        ((isNull = cursor.isNull(0)) || cursor.getLong(0) == docID)) {
                    if (isNull)
                        continue;
                    if (!deleted) {
                        if (conflicts == null)
                            conflicts = new ArrayList<String>();
                        conflicts.add(cursor.getString(3));
                    }
                }

                long realSequence = sequence; // because sequence may be changed, below
                if (minLastSequence > 0) {
                    // Find conflicts with documents from previous indexings.
                    Cursor cursor2 = null;
                    try {
                        String[] selectArgs2 = {Long.toString(docID), Long.toString(minLastSequence)};
                        cursor2 = store.getStorageEngine().rawQuery(
                                "SELECT revid, sequence FROM revs "
                                        + "WHERE doc_id=? AND sequence<=? AND current>0 AND deleted=0 "
                                        + "ORDER BY revID DESC ", selectArgs2);

                        if (cursor2.moveToNext()) {
                            String oldRevID = cursor2.getString(0);
                            // This is the revision that used to be the 'winner'.
                            // Remove its emitted rows:
                            long oldSequence = cursor2.getLong(1);
                            String[] args = {Long.toString(oldSequence)};
                            for (SQLiteViewStore view : views) {
                                int changes = view.store.getStorageEngine().
                                        delete(view.queryString("maps_#"), "sequence=?", args);
                                deletedCount += changes;
                                int thisViewID = view.getViewID();
                                int newTotalRows = viewTotalRows.get(thisViewID) - changes;
                                viewTotalRows.put(thisViewID, newTotalRows);
                            }

                            String conflictRevID = oldRevID;
                            if (deleted || RevisionInternal.CBLCompareRevIDs(oldRevID, revID) > 0) {
                                // It still 'wins' the conflict, so it's the one that
                                // should be mapped [again], not the current revision!
                                conflictRevID = revID;
                                revID = oldRevID;
                                deleted = false;
                                sequence = oldSequence;
                            }

                            if (!deleted) {
                                // Conflict revisions:
                                if (conflicts == null)
                                    conflicts = new ArrayList<String>();
                                conflicts.add(conflictRevID);
                                while (cursor2.moveToNext()) {
                                    conflicts.add(cursor2.getString(0));
                                }
                            }
                        }
                    } finally {
                        if (cursor2 != null) {
                            cursor2.close();
                        }
                    }
                }

                if (deleted)
                    continue;

                // Get json blob:
                String[] selectArgs3 = {Long.toString(sequence)};
                byte[] json = SQLiteUtils.byteArrayResultForQuery(store.getStorageEngine(),
                        "SELECT json FROM revs WHERE sequence=?", selectArgs3);

                // Get the document properties, to pass to the map function:
                Map<String, Object> curDoc = store.documentPropertiesFromJSON(
                        json,
                        docId,
                        revID,
                        false,
                        sequence
                );

                if (curDoc == null) {
                    Log.w(Log.TAG_VIEW, "Failed to parse JSON of doc %s rev %s", docID, revID);
                    continue;
                }
                curDoc.put("_local_seq", sequence);

                if (conflicts != null)
                    curDoc.put("_conflicts", conflicts);

                // Call the user-defined map() to emit new key/value pairs from this revision:
                i = -1;
                for (SQLiteViewStore view : views) {
                    curView = view;
                    ++i;
                    if (viewLastSequence[i] < realSequence) {
                        if (checkDocTypes) {
                            String viewDocType = viewDocTypes.get(view.getName());
                            if (viewDocType != null && !viewDocType.equals(docType))
                                continue; // skip; view's documentType doesn't match this doc
                        }
                        Log.v(Log.TAG_VIEW, "#%d: map '%s' for view %s...",
                                sequence, docID, view.getName());
                        try {
                            emitBlock.setSequence(sequence);
                            mapBlocks.get(i).map(curDoc, emitBlock);
                        } catch (Throwable e) {
                            String msg = String.format(Locale.ENGLISH, "Error when calling map block of view '%s'",
                                    view.getName());
                            Log.e(Log.TAG_VIEW, msg, e);
                            throw new CouchbaseLiteException(msg, e, Status.CALLBACK_ERROR);
                        }
                    }
                }
            }

            // Finally, record the last revision sequence number that was indexed and update #rows:
            for (SQLiteViewStore view : views) {
                view.finishCreatingIndex();
                int newTotalRows = viewTotalRows.get(view.getViewID());
                ContentValues updateValues = new ContentValues();
                updateValues.put("lastSequence", dbMaxSequence);
                updateValues.put("total_docs", newTotalRows);
                String[] whereArgs = {Integer.toString(view.getViewID())};
                store.getStorageEngine().update("views", updateValues, "view_id=?", whereArgs);
            }
            Log.v(Log.TAG_VIEW, "...Finished re-indexing (%s) to #%d (deleted %d, added %d)",
                    viewNames(views), dbMaxSequence, deletedCount, insertedCount.intValue());

            success = true;
            return new Status(Status.OK);
        } catch (SQLException ex) {
            throw new CouchbaseLiteException(ex, Status.DB_ERROR);
        } finally {
            curView = null;
            if (cursor != null)
                cursor.close();
            if (store != null) {
                if (!store.endTransaction(success))
                    throw new CouchbaseLiteException("Error in endTransaction()", Status.DB_ERROR);
            }
        }
    }
960405
private void updateDrawableBounds() {
        if (mDrawableRect == null) {
            mDrawableRect = new RectF();
        }
        Drawable d = getDrawable();
        if (d != null && d.getIntrinsicHeight() > 0 && d.getIntrinsicWidth() > 0) {
            mDrawableRect.set(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
        }
    }
246787
public <T extends View> T waitForAndGetView(int index, Class<T> classToFilterBy){
		long endTime = SystemClock.uptimeMillis() + Timeout.getSmallTimeout();
		while (SystemClock.uptimeMillis() <= endTime && !waitForView(classToFilterBy, index, true, true));
		int numberOfUniqueViews = searcher.getNumberOfUniqueViews();
		ArrayList<T> views = RobotiumUtils.removeInvisibleViews(viewFetcher.getCurrentViews(classToFilterBy, true));

		if(views.size() < numberOfUniqueViews){
			int newIndex = index - (numberOfUniqueViews - views.size());
			if(newIndex >= 0)
				index = newIndex;
		}

		T view = null;
		try{
			view = views.get(index);
		}catch (IndexOutOfBoundsException exception) {
			int match = index + 1;
			if(match > 1) {
				Assert.fail(match + " " + classToFilterBy.getSimpleName() +"s" + " are not found!");
			}
			else {
				Assert.fail(classToFilterBy.getSimpleName() + " is not found!");
			}
		}
		views = null;
		return view;
	}
171016
public static void handleFooterView(DrawerBuilder drawer, View.OnClickListener onClickListener) {
        Context ctx = drawer.mSliderLayout.getContext();

        //use the StickyDrawerItems if set
        if (drawer.mStickyDrawerItems != null && drawer.mStickyDrawerItems.size() > 0) {
            drawer.mStickyFooterView = DrawerUtils.buildStickyDrawerItemFooter(ctx, drawer, onClickListener);
        }

        //sticky footer view
        if (drawer.mStickyFooterView != null) {
            //add the sticky footer view and align it to the bottom
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 1);
            drawer.mStickyFooterView.setId(R.id.material_drawer_sticky_footer);
            drawer.mSliderLayout.addView(drawer.mStickyFooterView, layoutParams);

            if ((drawer.mTranslucentNavigationBar || drawer.mFullscreen) && Build.VERSION.SDK_INT >= 19) {
                drawer.mStickyFooterView.setPadding(0, 0, 0, UIUtils.getNavigationBarHeight(ctx));
            }

            //now align the recyclerView above the stickyFooterView ;)
            RelativeLayout.LayoutParams layoutParamsListView = (RelativeLayout.LayoutParams) drawer.mRecyclerView.getLayoutParams();
            layoutParamsListView.addRule(RelativeLayout.ABOVE, R.id.material_drawer_sticky_footer);
            drawer.mRecyclerView.setLayoutParams(layoutParamsListView);

            //handle shadow on top of the sticky footer
            if (drawer.mStickyFooterShadow) {
                drawer.mStickyFooterShadowView = new View(ctx);
                drawer.mStickyFooterShadowView.setBackgroundResource(R.drawable.material_drawer_shadow_top);
                drawer.mSliderLayout.addView(drawer.mStickyFooterShadowView, RelativeLayout.LayoutParams.MATCH_PARENT, ctx.getResources().getDimensionPixelSize(R.dimen.material_drawer_sticky_footer_elevation));
                //now align the shadow below the stickyHeader ;)
                RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) drawer.mStickyFooterShadowView.getLayoutParams();
                lps.addRule(RelativeLayout.ABOVE, R.id.material_drawer_sticky_footer);
                drawer.mStickyFooterShadowView.setLayoutParams(lps);
            }

            //remove the padding of the recyclerView again we have the footer below it
            drawer.mRecyclerView.setPadding(drawer.mRecyclerView.getPaddingLeft(), drawer.mRecyclerView.getPaddingTop(), drawer.mRecyclerView.getPaddingRight(), ctx.getResources().getDimensionPixelSize(R.dimen.material_drawer_padding));
        }

        // set the footer (do this before the setAdapter because some devices will crash else
        if (drawer.mFooterView != null) {
            if (drawer.mRecyclerView == null) {
                throw new RuntimeException("can't use a footerView without a recyclerView");
            }

            if (drawer.mFooterDivider) {
                drawer.getFooterAdapter().add(new ContainerDrawerItem().withView(drawer.mFooterView).withViewPosition(ContainerDrawerItem.Position.BOTTOM));
            } else {
                drawer.getFooterAdapter().add(new ContainerDrawerItem().withView(drawer.mFooterView).withViewPosition(ContainerDrawerItem.Position.NONE));
            }
        }
    }
275311
private void pldltptBK() throws Exception {
		//matrix S will be changed by the factorization, ad we do not want to change the matrix passed in by the client
		DoubleMatrix2D S = (rescaler==null)? this.Q.copy() : this.Q;
		int n = S.rows();
		DoubleMatrix2D A = S.copy();
		this.P = DoubleFactory2D.sparse.identity(n);
		this.D = DoubleFactory2D.sparse.make(n, n);
		this.L = DoubleFactory2D.sparse.make(n, n);
		DoubleMatrix2D LT = ALG.transpose(L);//@TODO: remove and work only with L
		double mu = (1 + Math.sqrt(17)) / 8;
		int s = 0;
		for (int j = 0; j < n; j++) {
			//log.debug("j: " + j);
			DoubleMatrix2D LPart = null;
			DoubleMatrix2D LTPart = null;
			DoubleMatrix2D APart = null;
			DoubleMatrix2D DPart = null;
			
			//Determine largest off-diagonal element in column j
			double lambda = -1;
			int r = -1;
			for(int rr = j+1; rr<n; rr++){
				double d = Math.abs(A.getQuick(rr, j)); 
				if(d > lambda){
					lambda = d;
					r = rr;
				}
			}
			double ajj = A.getQuick(j, j);
			if (Math.abs(ajj) > mu*lambda) {
				// Choose a 1 x 1 pivot,
				D.setQuick(j, j, ajj);
				s = 1;
			} else {
				//Determine largest off-diagonal element in row/column r
				double sigma = -1;
				for(int rr = 0; rr<n; rr++){
					if(rr==r){
						continue;
					}
					double d = Math.abs(A.getQuick(rr, r)); 
					if(d > sigma){
						sigma = d;
					}
				}
				if(sigma * Math.abs(ajj) > mu*lambda*lambda){
					//Choose a 1 x 1 pivot,
					D.setQuick(j, j, A.getQuick(j, j));
					s = 1;
				}else if(Math.abs(A.getQuick(r, r)) > mu*sigma){
					//Symmetrically permute row/column r to position j
				  A = ColtUtils.symmPermutation(A, r, j);
					P.setQuick(r, r, 0);
					P.setQuick(j, j, 0);
					P.setQuick(r, j, 1);
					P.setQuick(j, r, 1);
					//Choose a 1 x 1 pivot,
					D.setQuick(j, j, A.getQuick(j, j));
					s = 1;
				}else{
					//Symmetrically permute rows/columns r and p to positions j and j + 1 respectively
					int t = j+1;
					//int v = j+1;
					A = ColtUtils.symmPermutation(A, r, t);
					P.setQuick(r, r, 0);
					P.setQuick(t, t, 0);
					P.setQuick(r, t, 1);
					P.setQuick(t, r, 1);
//					A = Utils.symmPermutation(A, p, v);
//					P.setQuick(p, p, 0);
//					P.setQuick(v, v, 0);
//					P.setQuick(p, v, 1);
//					P.setQuick(v, p, 1);
					//Choose a 2 x pivot,
					//D(j:j+1)(j:j+1) =  A(j:j+1)(j:j+1)
					D.setQuick(j, j, A.getQuick(j, j));
					D.setQuick(j, j+1, A.getQuick(j, j+1));
					D.setQuick(j+1, j, A.getQuick(j+1, j));
					D.setQuick(j+1, j+1, A.getQuick(j+1, j+1));
					s = 2;
				}
			}
			//log.debug("s: " + s);

			// L(j:n)(j:j+s-1) = A(j:n)(j:j+s-1).DInv(j:j+s-1)(j:j+s-1)
			APart = A.viewPart(j, j, n - j, 1 + s - 1);
//			if(s==2){
//				try{
//					ColtUtils.invert2x2Matrix(D.viewPart(j, j, 1 + s - 1, 1 + s - 1));
//				}catch(Exception e){
//					throw e;
//				}
//			}
			DPart = ALG.inverse(D.viewPart(j, j, 1 + s - 1, 1 + s - 1));
			LPart = L.viewPart(j, j, n - j, 1 + s - 1);
			DoubleMatrix2D AD = ALG.mult(APart, DPart);
			for (int rr = 0; rr < LPart.rows(); rr++) {
				for (int cc = 0; cc < LPart.columns(); cc++) {
					LPart.setQuick(rr, cc, AD.getQuick(rr, cc));
				}
			}

			// A(j+s-1:n)(j+s-1:n) = A(j+s-1:n)(j+s-1:n) -
			// L(j+s-1:n)(j:j+s-1).D(j:j+s-1)(j:j+s-1).LT(j:j+s-1)(j+s-1:n)
			LPart = L.viewPart(j + s - 1, j, n - (j + s - 1), 1 + s - 1);
			DPart = D.viewPart(j, j, 1 + s - 1, 1 + s - 1);
			LTPart = LT.viewPart(j, j + s - 1, s, n - (j + s - 1));
			APart = A.viewPart(j + s - 1, j + s - 1, n - (j + s - 1), n - (j + s - 1));
			DoubleMatrix2D LDLT = ALG.mult(LPart, ALG.mult(DPart, LTPart));
			for (int rr = 0; rr < APart.rows(); rr++) {
				for (int cc = 0; cc < APart.columns(); cc++) {
					APart.setQuick(rr, cc, APart.getQuick(rr, cc) - LDLT.getQuick(rr, cc));
				}
			}
			//logger.debug("L: " + ArrayUtils.toString(L.toArray()));
			//logger.debug("A: " + ArrayUtils.toString(A.toArray()));

			j = j + s - 1;
		}
	}
1329370
public static void boundsCheck(int capacity, int index, int length) {
        if (capacity < 0 || index < 0 || length < 0 || (index > (capacity - length))) {
            throw new IndexOutOfBoundsException(String.format("index=%d, length=%d, capacity=%d", index, length, capacity));
        }
    }
609774
public RoadSegment removeRoadSegmentAt(int index) {
		if (index >= 0) {
			int b = 0;
			for (final RoadPath p : this.paths) {
				int end = b + p.size();
				if (index < end) {
					end = index - b;
					return removeRoadSegmentAt(p, end, null);
				}
				b = end;
			}
		}
		throw new IndexOutOfBoundsException();
	}
924933
public IndexOutOfBoundsException asJDKException() {
        IndexOutOfBoundsException e = new IndexOutOfBoundsException(getMessage()) {
            @Override
            public synchronized Throwable fillInStackTrace() {
                return this;
            }
        };
        e.setStackTrace(getStackTrace());
        return e;
    }
385875
public <T> ESDatas<T> searchAllParallel(String index,  final int fetchSize ,ScrollHandler<T> scrollHandler,final Class<T> type,int max) throws ElasticSearchException{
		if(!this.client.isV1()) {
			SliceScroll sliceScroll = new SliceScroll() {
				@Override
				public String buildSliceDsl(int sliceId, int max) {
					StringBuilder builder = new StringBuilder();
					String sliceDsl = builder.append("{\"slice\": {\"id\": ").append(sliceId).append(",\"max\": ")
							.append(max).append("},\"size\":").append(fetchSize).append(",\"query\": {\"match_all\": {}},\"sort\": [\"_doc\"]}").toString();
					return sliceDsl;
//				return buildSliceDsl(i,max, params, dslTemplate);
				}
			};

			return _slice(index + "/_search", scrollHandler, type, max, "1m", sliceScroll);
		}
		else{
			StringBuilder builder = new StringBuilder();
			String queryAll = builder.append("{ \"size\":").append(fetchSize).append(",\"query\": {\"match_all\": {}},\"sort\": [\"_doc\"]}").toString();
			builder.setLength(0);
			return this.scrollParallel(builder.append(index).append("/_search").toString(),queryAll,"10m",type,scrollHandler);
		}

	}
645007
public void checkSkipReadForFixLengthPart(AbstractPagedInputView source) throws IOException {
		// skip if there is no enough size.
		// Note: Use currentSegmentLimit instead of segmentSize.
		int available = source.getCurrentSegmentLimit() - source.getCurrentPositionInSegment();
		if (available < getSerializedRowFixedPartLength()) {
			source.advance();
		}
	}