List of usage examples for java.util ArrayList clear
public void clear()
From source file:hd3gtv.mydmam.useraction.fileoperation.UAFileOperationDelete.java
@Override public void process(JobProgression progression, UserProfile userprofile, UAConfigurator user_configuration, HashMap<String, SourcePathIndexerElement> source_elements) throws Exception { Log2Dump dump = new Log2Dump(); dump.add("user", userprofile.key); progression.updateStep(1, source_elements.size()); ArrayList<File> items_to_delete = new ArrayList<File>(); for (Map.Entry<String, SourcePathIndexerElement> entry : source_elements.entrySet()) { progression.incrStep();//ww w .j a va 2 s . co m File current_element = Explorer.getLocalBridgedElement(entry.getValue()); CopyMove.checkExistsCanRead(current_element); CopyMove.checkIsWritable(current_element.getParentFile()); if (current_element.isFile() | FileUtils.isSymlink(current_element)) { if (current_element.delete() == false) { Log2.log.debug("Can't delete correctly file", dump); throw new IOException("Can't delete correctly file: " + current_element.getPath()); } if (stop) { return; } } else { items_to_delete.clear(); items_to_delete.add(current_element); boolean can_delete_all = true; recursivePath(current_element, items_to_delete); progression.updateProgress(1, items_to_delete.size()); for (int pos_idel = items_to_delete.size() - 1; pos_idel > -1; pos_idel--) { progression.updateProgress(items_to_delete.size() - pos_idel, items_to_delete.size()); if (items_to_delete.get(pos_idel).delete() == false) { dump.add("item", items_to_delete.get(pos_idel)); can_delete_all = false; } if (stop) { return; } } if (can_delete_all == false) { Log2.log.debug("Can't delete correctly multiple files", dump); throw new IOException("Can't delete multiple files from: " + current_element.getPath()); } } if (stop) { return; } ElasticsearchBulkOperation bulk = Elasticsearch.prepareBulk(); /** * Delete mtds */ Container container = ContainerOperations.getByPathIndexId(entry.getKey()); if (container != null) { ContainerOperations.requestDelete(container, bulk); RenderedFile.purge(entry.getKey()); } explorer.deleteStoragePath(bulk, Arrays.asList(entry.getValue())); bulk.terminateBulk(); if (stop) { return; } } }
From source file:com.ushahidi.android.ui.fragment.ListDeploymentFragment.java
private void swipeToDeleteUndo() { mListViewTouchListener = new SwipeDismissRecyclerViewTouchListener(mDeploymentRecyclerView, new SwipeDismissRecyclerViewTouchListener.DismissCallbacks() { @Override//from w w w . ja v a 2 s .c om public boolean canDismiss(int position) { return true; } @Override public void onDismiss(RecyclerView listView, int[] reverseSortedPositions) { isDismissToDelete = true; mInteractiveToast .setInteractiveToastListener(new InteractiveToast.InteractiveToastListener() { @Override public void onPressed(Parcelable token) { Bundle b = (Bundle) token; final ArrayList<DeploymentRecyclerView.DeploymentParcelable> items = b .getParcelableArrayList(INTERACTIVE_TOAST_BUNDLE_KEY); if (!items.isEmpty()) { for (DeploymentRecyclerView.DeploymentParcelable deploymentModel : items) { mRecyclerViewAdapter.addItem(deploymentModel.getDeploymentModel(), deploymentModel.getPosition()); } items.clear(); } } }); mInteractiveToast.setOnHideListener(new InteractiveToast.OnHideListener() { @Override public void onHide(Parcelable token) { Bundle b = (Bundle) token; final ArrayList<DeploymentParcelable> items = b .getParcelableArrayList(INTERACTIVE_TOAST_BUNDLE_KEY); if (!items.isEmpty()) { for (DeploymentParcelable deploymentModel : items) { if (deploymentModel.getDeploymentModel() .getStatus() == DeploymentModel.Status.ACTIVATED) { mPrefs.getActiveDeploymentUrl().delete(); } mDeleteDeploymentPresenter .deleteDeployment(deploymentModel.getDeploymentModel()); } items.clear(); } } }); ArrayList<DeploymentParcelable> items = new ArrayList<>(); if (reverseSortedPositions.length > 0) { for (int i : reverseSortedPositions) { DeploymentParcelable parcelable = new DeploymentParcelable( mRecyclerViewAdapter.getItem(i), i); items.add(parcelable); mRecyclerViewAdapter.removeItem(mRecyclerViewAdapter.getItem(i)); } } // Stores the selected models into a bundle for later reuse. Bundle b = new Bundle(); b.putParcelableArrayList(INTERACTIVE_TOAST_BUNDLE_KEY, items); mInteractiveToast.show(getString(R.string.items_deleted, reverseSortedPositions.length), getString(R.string.undo), R.drawable.ic_undo, b); } }); }
From source file:edu.nyu.vida.data_polygamy.standard_techniques.CorrelationTechniquesReducer.java
@SuppressWarnings("unchecked") @Override//from ww w . ja va2s . c om public void reduce(PairAttributeWritable key, Iterable<SpatioTemporalValueWritable> values, Context context) throws IOException, InterruptedException { resolutionHandler(key.getSpatialResolution(), key.getTemporalResolution()); int size = 0; switch (spatial) { case FrameworkUtils.NBHD: size = spatialGraph.nbNodes(); break; case FrameworkUtils.ZIP: size = zipGraph.nbNodes(); break; case FrameworkUtils.GRID: size = gridSize; break; case FrameworkUtils.CITY: size = 1; break; default: size = 1; break; } timeSeries = (ArrayList<TreeMap<Integer, Float>>[]) new ArrayList[size]; for (int i = 0; i < size; i++) { ArrayList<TreeMap<Integer, Float>> spatialTimeSeries = new ArrayList<TreeMap<Integer, Float>>(); spatialTimeSeries.add(new TreeMap<Integer, Float>()); // 0 spatialTimeSeries.add(new TreeMap<Integer, Float>()); // 1 timeSeries[i] = spatialTimeSeries; } // initializing some variables dataset1 = key.getFirstDataset(); dataset2 = key.getSecondDataset(); fileName = datasets.get(dataset1) + "-" + datasets.get(dataset2) + "/" + utils.temporalResolutionStr(key.getTemporalResolution()) + "-" + utils.spatialResolutionStr(key.getSpatialResolution()) + "/data"; Iterator<SpatioTemporalValueWritable> it = values.iterator(); SpatioTemporalValueWritable st; while (it.hasNext()) { st = it.next(); int dataset = st.getDataset(); int temporal = st.getTemporal(); int spatial = st.getSpatial(); float val = st.getValue(); int datasetKey = 0; if (dataset == dataset1) datasetKey = dataset1Key; else datasetKey = dataset2Key; TreeMap<Integer, Float> map = timeSeries[spatial].get(datasetKey); map.put(temporal, val); timeSeries[spatial].set(datasetKey, map); } double corr = 0; // Pearsons Correlations double mi = 0; // Mutual Information double dtw = 0; // DTW int count = 0; for (int i = 0; i < size; i++) { double[] tempValues = computeCorrelationTechniques(timeSeries, i, i, false); if (tempValues == null) continue; corr += tempValues[0]; mi += tempValues[1]; dtw += tempValues[2]; count++; } if (count == 0) return; corr = corr / count; mi = mi / count; dtw = dtw / count; /* * Monte Carlo Permutation Test */ double pValueCorr = 0; double pValueMI = 0; double pValueDTW = 0; ArrayList<Integer[]> pairs = new ArrayList<Integer[]>(); switch (spatial) { case FrameworkUtils.NBHD: for (int j = 0; j < repetitions; j++) { double mcCorr = 0; pairs.clear(); pairs = bfsShift(true); count = 0; for (int i = 0; i < pairs.size(); i++) { Integer[] pair = pairs.get(i); double[] tempValues = computeCorrelationTechniques(timeSeries, pair[0], pair[1], false); if (tempValues == null) continue; corr += tempValues[0]; //mi += tempValues[1]; //dtw += tempValues[2]; count++; } mcCorr = (count == 0) ? 0 : mcCorr / count; if (corr > 0) { if (mcCorr >= corr) pValueCorr += 1; } else { if (mcCorr <= corr) pValueCorr += 1; } if (pValueCorr > (alpha * repetitions)) break; // pruning } pValueCorr = pValueCorr / ((double) (repetitions)); emitKeyValue(key, corr, mi, dtw, pValueCorr, pValueMI, pValueDTW); break; case FrameworkUtils.ZIP: for (int j = 0; j < repetitions; j++) { double mcCorr = 0; pairs.clear(); pairs = bfsShift(false); count = 0; for (int i = 0; i < pairs.size(); i++) { Integer[] pair = pairs.get(i); double[] tempValues = computeCorrelationTechniques(timeSeries, pair[0], pair[1], false); if (tempValues == null) continue; corr += tempValues[0]; //mi += tempValues[1]; //dtw += tempValues[2]; count++; } mcCorr = (count == 0) ? 0 : mcCorr / count; if (corr > 0) { if (mcCorr >= corr) pValueCorr += 1; } else { if (mcCorr <= corr) pValueCorr += 1; } if (pValueCorr > (alpha * repetitions)) break; // pruning } pValueCorr = pValueCorr / ((double) (repetitions)); emitKeyValue(key, corr, mi, dtw, pValueCorr, pValueMI, pValueDTW); break; case FrameworkUtils.GRID: for (int j = 0; j < repetitions; j++) { double mcCorr = 0; pairs.clear(); pairs = toroidalShift(); count = 0; for (int i = 0; i < pairs.size(); i++) { Integer[] pair = pairs.get(i); double[] tempValues = computeCorrelationTechniques(timeSeries, pair[0], pair[1], false); if (tempValues == null) continue; corr += tempValues[0]; //mi += tempValues[1]; //dtw += tempValues[2]; count++; } mcCorr = (count == 0) ? 0 : mcCorr / count; if (corr > 0) { if (mcCorr >= corr) pValueCorr += 1; } else { if (mcCorr <= corr) pValueCorr += 1; } if (pValueCorr > (alpha * repetitions)) break; // pruning } pValueCorr = pValueCorr / ((double) (repetitions)); emitKeyValue(key, corr, mi, dtw, pValueCorr, pValueMI, pValueDTW); break; case FrameworkUtils.CITY: for (int j = 0; j < repetitions; j++) { double[] tempValues = computeCorrelationTechniques(timeSeries, 0, 0, true); double mcCorr = (tempValues == null) ? 0 : tempValues[0]; double mcMI = (tempValues == null) ? 0 : tempValues[1]; double mcDTW = (tempValues == null) ? 0 : tempValues[2]; if (corr > 0) { if (mcCorr >= corr) pValueCorr += 1; } else { if (mcCorr <= corr) pValueCorr += 1; } if (mcMI >= mi) pValueMI += 1; if (dtw > 0) { if (mcDTW >= dtw) pValueDTW += 1; } else { if (mcDTW <= dtw) pValueDTW += 1; } } pValueCorr = pValueCorr / ((double) (repetitions)); pValueMI = pValueMI / ((double) (repetitions)); pValueDTW = pValueDTW / ((double) (repetitions)); emitKeyValue(key, corr, mi, dtw, pValueCorr, pValueMI, pValueDTW); break; default: // do nothing break; } }
From source file:com.holo.fileexplorer.MainActivity.java
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Toast.makeText(this, "Tapped home", Toast.LENGTH_SHORT).show(); break;/*from w w w .j a v a 2 s. c om*/ case R.id.action_rw: String currentPath = mViewPager.getFragment(mPager, mPager.getCurrentItem()).getCurrentDir() .getAbsolutePath(); boolean result = RootTools.remount(currentPath, "rw"); ArrayList<Mount> mounts = new ArrayList<Mount>(); try { mounts = RootTools.getMounts(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } mounts.clear(); Log.v("MOUNT RW?", "RW WRITABLE? " + new File(currentPath).canWrite()); break; case R.id.action_ro: RootTools.remount( mViewPager.getFragment(mPager, mPager.getCurrentItem()).getCurrentDir().getAbsolutePath(), "ro"); break; case R.id.action_up: mViewPager.getFragment(mPager, mPager.getCurrentItem()).upOneLevel(); break; case R.id.action_new_folder: LayoutInflater inflater = LayoutInflater.from(this); View view = inflater.inflate(R.layout.dialog_new_folder, null); final EditText et = (EditText) view.findViewById(R.id.foldername); et.setText(""); new AlertDialog.Builder(this).setTitle(R.string.create_new_folder).setView(view) .setPositiveButton(android.R.string.ok, new OnClickListener() { public void onClick(DialogInterface dialog, int which) { mViewPager.getFragment(mPager, mPager.getCurrentItem()) .createNewFolder(et.getText().toString()); } }).setNegativeButton(android.R.string.cancel, new OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Cancel should not do anything beyond // closing the dialog. } }).show(); break; case R.id.action_open_bookmarks: Toast.makeText(this, "Tapped bookmarks (Not implemented yet. Patience.)", Toast.LENGTH_SHORT).show(); break; case R.id.action_refresh: // getSupportActionBarHelper().setRefreshActionItemState(true); refreshCurrentPage(); // TODO: preserve scroll position and show // progress // getSupportActionBarHelper().setRefreshActionItemState(false); Toast.makeText(this, "Folder Refreshed", Toast.LENGTH_SHORT).show(); break; case R.id.action_search: Toast.makeText(this, "Tapped search (Not implemented yet. Patience.)", Toast.LENGTH_SHORT).show(); break; // case R.id.action_storage_summary: // Toast.makeText(this, // "Tapped storage summary (Not implemented yet. It'll be good though.)", // Toast.LENGTH_SHORT).show(); // break; case R.id.action_sort: // Do nothing. This has a submenu break; case R.id.sort_alphabetical: item.setChecked(true); mViewPager.getFragment(mPager, mPager.getCurrentItem()).sort(FileListFragment.SORT_ALPHABETICAL); break; case R.id.sort_last_modified: item.setChecked(true); mViewPager.getFragment(mPager, mPager.getCurrentItem()).sort(FileListFragment.SORT_LAST_MODIFIED); break; case R.id.sort_reverse: // Toggle the checked state Boolean newState = !item.isChecked(); item.setChecked(newState); mViewPager.getFragment(mPager, mPager.getCurrentItem()).sortDirection(newState); break; case R.id.action_settings: if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { Intent intent = new Intent(this, EditPreferences.class); intent.putExtra("themeid", mThemeId); startActivity(new Intent(this, EditPreferences.class)); } else { startActivity(new Intent(this, EditPreferencesHC.class)); } break; case R.id.action_exit: // finish(); android.os.Process.killProcess(android.os.Process.myPid()); break; } return super.onOptionsItemSelected(item); }
From source file:gdsc.smlm.results.match.MatchCalculator.java
/** * Calculate the match results for the given actual and predicted fluorophore pulses. * Points that are within the distance threshold are identified as a match. The score is calculated using half the * distance threshold and the overlap in time. Assignments are made using the highest scoring matches. * <p>/* www.ja va 2s . c o m*/ * The total score is stored in the RMSD field of the MatchResult. The number of true positives, false positives and * false negatives are calculated. * * @param actualPoints * @param predictedPoints * @param dThreshold * The distance threshold * @param TP * True Positives * @param FP * False Positives * @param FN * False Negatives * @param matches * The matched true positives (point1 = actual, point2 = predicted) * @return The match results */ public static MatchResult analyseResults2D(Pulse[] actualPoints, Pulse[] predictedPoints, final double dThreshold, List<Pulse> TP, List<Pulse> FP, List<Pulse> FN, List<PointPair> matches) { // We will use the squared distance for speed final double halfDThreshold2 = (dThreshold * 0.5) * (dThreshold * 0.5); final float floatDThreshold = (float) dThreshold; final double dThreshold2 = dThreshold * dThreshold; final int predictedPointsLength = (predictedPoints != null) ? predictedPoints.length : 0; final int actualPointsLength = (actualPoints != null) ? actualPoints.length : 0; int tp = 0; // true positives (actual with matched predicted point) int fp = predictedPointsLength; // false positives (actual with no matched predicted point) int fn = actualPointsLength; // false negatives (predicted point with no actual point) double score = 0; if (predictedPointsLength == 0 || actualPointsLength == 0) { if (FP != null) FP.addAll(asList(predictedPoints)); if (FN != null) FN.addAll(asList(actualPoints)); return new MatchResult(tp, fp, fn, score); } // loop over the two arrays assigning the closest unassigned pair boolean[] resultAssignment = new boolean[predictedPointsLength]; boolean[] roiAssignment = new boolean[fn]; ArrayList<Assignment> assignments = new ArrayList<Assignment>(predictedPointsLength); int[] falsePositives = null, falseNegatives = null; if (FP != null) { falsePositives = ascendingArray(predictedPointsLength); } if (FN != null) { falseNegatives = ascendingArray(actualPointsLength); } // Sort by time to allow efficient looping Arrays.sort(actualPoints); Arrays.sort(predictedPoints); // Pre-calculate all-vs-all distance matrix if it can fit in memory int size = predictedPointsLength * actualPointsLength; float[][] dMatrix = null; if (size < 200 * 200) { dMatrix = new float[predictedPointsLength][actualPointsLength]; for (int predictedId = 0; predictedId < predictedPointsLength; predictedId++) { final float x = predictedPoints[predictedId].getX(); final float y = predictedPoints[predictedId].getY(); for (int actualId = 0; actualId < actualPointsLength; actualId++) { dMatrix[predictedId][actualId] = (float) actualPoints[actualId].distance2(x, y); } } } do { assignments.clear(); // Process each result for (int predictedId = 0; predictedId < predictedPointsLength; predictedId++) { if (resultAssignment[predictedId]) continue; // Already assigned final float x = predictedPoints[predictedId].getX(); final float y = predictedPoints[predictedId].getY(); final int start = predictedPoints[predictedId].getStart(); final int end = predictedPoints[predictedId].getEnd(); // Find first overlapping pulse int actualId = 0; while (actualId < actualPointsLength && actualPoints[actualId].getEnd() < start) { actualId++; } // Find highest scoring point within the distance limit double scoreMax = 0; int targetId = -1; for (; actualId < actualPointsLength; actualId++) { if (roiAssignment[actualId]) continue; // Already assigned if (actualPoints[actualId].getStart() > end) break; // No more overlap in time double d2; if (dMatrix != null) { d2 = dMatrix[predictedId][actualId]; } else { Coordinate actualPoint = actualPoints[actualId]; // Calculate in steps for increased speed (allows early exit) float dx = Math.abs(actualPoint.getX() - x); if (dx > floatDThreshold) continue; float dy = Math.abs(actualPoint.getY() - y); if (dy > floatDThreshold) continue; d2 = dx * dx + dy * dy; } // Do we need to exclude using the distance threshold? This is useful for binary classification // but will truncate the continuous nature of the score. if (d2 > dThreshold2) continue; double s = predictedPoints[predictedId].score(actualPoints[actualId], d2, halfDThreshold2); if (scoreMax < s) { scoreMax = s; targetId = actualId; } } // Store highest scoring point if (targetId > -1) { assignments.add(new Assignment(targetId, predictedId, scoreMax)); } } // If there are assignments if (!assignments.isEmpty()) { // Process highest scoring first Collections.sort(assignments); Collections.reverse(assignments); // Process in order of score for (Assignment closest : assignments) { // Skip those that have already been assigned since this will be a lower score. // Note at least one assignment should be processed as potential assignments are made // using only unassigned points. if (resultAssignment[closest.getPredictedId()] || roiAssignment[closest.getTargetId()]) continue; resultAssignment[closest.getPredictedId()] = true; roiAssignment[closest.getTargetId()] = true; tp++; fn--; fp--; score += closest.getDistance(); // This is the scoreMax (not the distance) if (TP != null) { TP.add(predictedPoints[closest.getPredictedId()]); } if (FP != null) { falsePositives[closest.getPredictedId()] = -1; } if (FN != null) { falseNegatives[closest.getTargetId()] = -1; } if (matches != null) matches.add(new PointPair(actualPoints[closest.getTargetId()], predictedPoints[closest.getPredictedId()])); } } } while (!assignments.isEmpty()); // Add to lists if (FP != null) { for (int i = 0; i < predictedPointsLength; i++) { if (falsePositives[i] >= 0) FP.add(predictedPoints[i]); } } if (FN != null) { for (int i = 0; i < actualPointsLength; i++) { if (falseNegatives[i] >= 0) FN.add(actualPoints[i]); } } // Every time-point has the chance to contribute to the score. // Normalise score by the maximum of the number of actual/predicted time points. // This penalises too few or too many predictions int p1 = countTimePoints(actualPoints); int p2 = countTimePoints(predictedPoints); score /= FastMath.max(p1, p2); return new MatchResult(tp, fp, fn, score); }
From source file:com.zimbra.common.util.HttpUtil.java
/** * The main difference between java.net.URLDecoder.decode() * and this method is the handling of "+" sign. URLDecoder * will turn + into ' ' (space), and not suitable for * decoding URL used in HTTP request./*w ww .ja va 2s . co m*/ */ public static String urlUnescape(String escaped) { // all the encoded byte groups should be converted to // string together ArrayList<Byte> segment = new ArrayList<Byte>(); StringBuilder buf = null; for (int i = 0; i < escaped.length(); i++) { char c = escaped.charAt(i); if (c == '%' && i < (escaped.length() - 2)) { String bytes = escaped.substring(i + 1, i + 3); try { // java Byte type is signed with range of -0x80 to 0x7F. // it cannot convert segment of encoded UTF-8 string // with high bit set. we'll parse using Integer // then cast the result back to signed Byte. // e.g. 0xED becomes 237 as Integer, then -19 as Byte int b = Integer.parseInt(bytes, 16); segment.add(Byte.valueOf((byte) b)); } catch (NumberFormatException e) { } if (buf == null) { buf = new StringBuilder(escaped.substring(0, i)); } i += 2; // append to the buffer if we are at the end of the string, // or if this is the last encoded character in the segment. if (i + 1 == escaped.length() || escaped.charAt(i + 1) != '%') { try { buf.append(new String(Bytes.toArray(segment), "UTF-8")); } catch (UnsupportedEncodingException e) { } segment.clear(); } continue; } if (buf != null) { buf.append(c); } } if (buf != null) return buf.toString(); return escaped; }
From source file:accumulo.balancer.GroupBalancer.java
private void balanceExtraMultiple(Map<TServerInstance, TserverGroupInfo> tservers, int maxExtraGroups, Moves moves, Multimap<String, TserverGroupInfo> extraMultiple, boolean alwaysAdd) { ArrayList<Pair<String, TserverGroupInfo>> serversToRemove = new ArrayList<>(); for (TserverGroupInfo destTgi : tservers.values()) { Map<String, Integer> extras = destTgi.getExtras(); if (alwaysAdd || extras.size() < maxExtraGroups) { serversToRemove.clear(); for (String group : extraMultiple.keySet()) { if (!extras.containsKey(group)) { Collection<TserverGroupInfo> sources = extraMultiple.get(group); Iterator<TserverGroupInfo> iter = sources.iterator(); TserverGroupInfo srcTgi = iter.next(); int num = srcTgi.getExtras().get(group); moves.move(group, 1, srcTgi, destTgi); if (num == 2) { serversToRemove.add(new Pair<String, TserverGroupInfo>(group, srcTgi)); }//from w w w . j a v a 2 s. c om if (destTgi.getExtras().size() >= maxExtraGroups || moves.size() >= getMaxMigrations()) { break; } } } for (Pair<String, TserverGroupInfo> pair : serversToRemove) { extraMultiple.remove(pair.getFirst(), pair.getSecond()); } if (extraMultiple.size() == 0 || moves.size() >= getMaxMigrations()) { break; } } } }
From source file:com.ushahidi.android.presentation.view.ui.animators.BaseItemAnimator.java
@Override public void runPendingAnimations() { boolean removalsPending = !mPendingRemovals.isEmpty(); boolean movesPending = !mPendingMoves.isEmpty(); boolean changesPending = !mPendingChanges.isEmpty(); boolean additionsPending = !mPendingAdditions.isEmpty(); if (!removalsPending && !movesPending && !additionsPending && !changesPending) { // nothing to animate return;//from ww w . j a v a2s . c o m } // First, remove stuff for (ViewHolder holder : mPendingRemovals) { animateRemoveImpl(holder); } mPendingRemovals.clear(); // Next, move stuff if (movesPending) { final ArrayList<MoveInfo> moves = new ArrayList<>(); moves.addAll(mPendingMoves); mMovesList.add(moves); mPendingMoves.clear(); Runnable mover = () -> { for (MoveInfo moveInfo : moves) { animateMoveImpl(moveInfo.holder, moveInfo.fromX, moveInfo.fromY, moveInfo.toX, moveInfo.toY); } moves.clear(); mMovesList.remove(moves); }; if (removalsPending) { View view = moves.get(0).holder.itemView; ViewCompat.postOnAnimationDelayed(view, mover, getRemoveDuration()); } else { mover.run(); } } // Next, change stuff, to run in parallel with move animations if (changesPending) { final ArrayList<ChangeInfo> changes = new ArrayList<>(); changes.addAll(mPendingChanges); mChangesList.add(changes); mPendingChanges.clear(); Runnable changer = () -> { for (ChangeInfo change : changes) { animateChangeImpl(change); } changes.clear(); mChangesList.remove(changes); }; if (removalsPending) { ViewHolder holder = changes.get(0).oldHolder; ViewCompat.postOnAnimationDelayed(holder.itemView, changer, getRemoveDuration()); } else { changer.run(); } } // Next, add stuff if (additionsPending) { final ArrayList<ViewHolder> additions = new ArrayList<>(); additions.addAll(mPendingAdditions); mAdditionsList.add(additions); mPendingAdditions.clear(); Runnable adder = () -> { for (ViewHolder holder : additions) { animateAddImpl(holder); } additions.clear(); mAdditionsList.remove(additions); }; if (removalsPending || movesPending || changesPending) { long removeDuration = removalsPending ? getRemoveDuration() : 0; long moveDuration = movesPending ? getMoveDuration() : 0; long changeDuration = changesPending ? getChangeDuration() : 0; long totalDelay = removeDuration + Math.max(moveDuration, changeDuration); View view = additions.get(0).itemView; ViewCompat.postOnAnimationDelayed(view, adder, totalDelay); } else { adder.run(); } } }
From source file:com.cloudera.impala.planner.PlannerTestBase.java
private void checkScanRangeLocations(TestCase testCase, TExecRequest execRequest, StringBuilder errorLog, StringBuilder actualOutput) { String query = testCase.getQuery(); // Query exec request may not be set for DDL, e.g., CTAS. String locationsStr = null;/*from w w w. j a va2s . c o m*/ if (execRequest != null && execRequest.isSetQuery_exec_request()) { buildMaps(execRequest.query_exec_request); // If we optimize the partition key scans, we may get all the partition key values // from the metadata and don't reference any table. Skip the check in this case. TQueryOptions options = execRequest.getQuery_options(); if (!(options.isSetOptimize_partition_key_scans() && options.optimize_partition_key_scans)) { testHdfsPartitionsReferenced(execRequest.query_exec_request, query, errorLog); } locationsStr = printScanRangeLocations(execRequest.query_exec_request).toString(); } // compare scan range locations LOG.info("scan range locations: " + locationsStr); ArrayList<String> expectedLocations = testCase.getSectionContents(Section.SCANRANGELOCATIONS); if (expectedLocations.size() > 0 && locationsStr != null) { // Locations' order does not matter. String result = TestUtils.compareOutput(Lists.newArrayList(locationsStr.split("\n")), expectedLocations, false, false); if (!result.isEmpty()) { errorLog.append("section " + Section.SCANRANGELOCATIONS + " of query:\n" + query + "\n" + result); } actualOutput.append(Section.SCANRANGELOCATIONS.getHeader() + "\n"); // Print the locations out sorted since the order is random and messed up // the diffs. The values in locationStr contains "Node X" labels as well // as paths. ArrayList<String> locations = Lists.newArrayList(locationsStr.split("\n")); ArrayList<String> perNodeLocations = Lists.newArrayList(); for (int i = 0; i < locations.size(); ++i) { if (locations.get(i).startsWith("NODE")) { if (!perNodeLocations.isEmpty()) { Collections.sort(perNodeLocations); actualOutput.append(Joiner.on("\n").join(perNodeLocations)).append("\n"); perNodeLocations.clear(); } actualOutput.append(locations.get(i)).append("\n"); } else { perNodeLocations.add(locations.get(i)); } } if (!perNodeLocations.isEmpty()) { Collections.sort(perNodeLocations); actualOutput.append(Joiner.on("\n").join(perNodeLocations)).append("\n"); } // TODO: check that scan range locations are identical in both cases } }
From source file:com.xabber.android.ui.activity.ContactList.java
/** * Open chat with specified contact./*w w w.j a v a 2s . co m*/ * <p/> * Show dialog to choose account if necessary. * * @param user * @param text can be <code>null</code>. */ private void openChat(String user, String text) { String bareAddress = Jid.getBareAddress(user); ArrayList<BaseEntity> entities = new ArrayList<>(); for (AbstractChat check : MessageManager.getInstance().getChats()) { if (check.isActive() && check.getUser().equals(bareAddress)) { entities.add(check); } } if (entities.size() == 1) { openChat(entities.get(0), text); return; } entities.clear(); for (RosterContact check : RosterManager.getInstance().getContacts()) { if (check.isEnabled() && check.getUser().equals(bareAddress)) { entities.add(check); } } if (entities.size() == 1) { openChat(entities.get(0), text); return; } Collection<String> accounts = AccountManager.getInstance().getAccounts(); if (accounts.isEmpty()) { return; } if (accounts.size() == 1) { openChat(new BaseEntity(accounts.iterator().next(), bareAddress), text); return; } AccountChooseDialogFragment.newInstance(bareAddress, text).show(getFragmentManager(), "OPEN_WITH_ACCOUNT"); }