List of usage examples for java.util ArrayList clear
public void clear()
From source file:gdsc.core.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>//from www.j a v a 2 s . c om * 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; clear(TP, FP, FN, matches); 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<ImmutableAssignment> assignments = new ArrayList<ImmutableAssignment>(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 = abs(actualPoint.getX() - x); if (dx > floatDThreshold) continue; float dy = 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 ImmutableAssignment(targetId, predictedId, scoreMax)); } } // If there are assignments if (!assignments.isEmpty()) { // Process highest scoring first AssignmentComparator.sort(assignments); Collections.reverse(assignments); // Process in order of score for (ImmutableAssignment 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:cn.iterlog.xmimagepicker.anim.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 www. j a v a 2 s.c o m*/ } // First, remove stuff for (RecyclerView.ViewHolder holder : mPendingRemovals) { doAnimateRemove(holder); } mPendingRemovals.clear(); // Next, move stuff if (movesPending) { final ArrayList<MoveInfo> moves = new ArrayList<MoveInfo>(); moves.addAll(mPendingMoves); mMovesList.add(moves); mPendingMoves.clear(); Runnable mover = new Runnable() { @Override public void run() { 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<ChangeInfo>(); changes.addAll(mPendingChanges); mChangesList.add(changes); mPendingChanges.clear(); Runnable changer = new Runnable() { @Override public void run() { for (ChangeInfo change : changes) { animateChangeImpl(change); } changes.clear(); mChangesList.remove(changes); } }; if (removalsPending) { RecyclerView.ViewHolder holder = changes.get(0).oldHolder; ViewCompat.postOnAnimationDelayed(holder.itemView, changer, getRemoveDuration()); } else { changer.run(); } } // Next, add stuff if (additionsPending) { final ArrayList<RecyclerView.ViewHolder> additions = new ArrayList<RecyclerView.ViewHolder>(); additions.addAll(mPendingAdditions); mAdditionsList.add(additions); mPendingAdditions.clear(); Runnable adder = new Runnable() { public void run() { for (RecyclerView.ViewHolder holder : additions) { doAnimateAdd(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.dattasmoon.pebble.plugin.EditNotificationActivity.java
public void save() { String selectedPackages = ""; ArrayList<String> tmpArray = new ArrayList<String>(); if (lvPackages == null || lvPackages.getAdapter() == null) { return;/*from w w w .j ava2 s . co m*/ } for (String strPackage : ((packageAdapter) lvPackages.getAdapter()).selected) { if (!strPackage.isEmpty()) { if (!tmpArray.contains(strPackage)) { tmpArray.add(strPackage); selectedPackages += strPackage + ","; } } } tmpArray.clear(); tmpArray = null; if (!selectedPackages.isEmpty()) { selectedPackages = selectedPackages.substring(0, selectedPackages.length() - 1); } if (Constants.IS_LOGGABLE) { switch (mMode) { case OFF: Log.i(Constants.LOG_TAG, "Mode is: off"); break; case EXCLUDE: Log.i(Constants.LOG_TAG, "Mode is: exclude"); break; case INCLUDE: Log.i(Constants.LOG_TAG, "Mode is: include"); break; } Log.i(Constants.LOG_TAG, "Package list is: " + selectedPackages); } if (mode == Mode.STANDARD) { Editor editor = sharedPreferences.edit(); editor.putInt(Constants.PREFERENCE_MODE, mMode.ordinal()); editor.putString(Constants.PREFERENCE_PACKAGE_LIST, selectedPackages); editor.putString(Constants.PREFERENCE_PKG_RENAMES, arrayRenames.toString()); // we saved via the application, reset the variable if it exists editor.remove(Constants.PREFERENCE_TASKER_SET); // clear out legacy preference, if it exists editor.remove(Constants.PREFERENCE_EXCLUDE_MODE); // save! editor.commit(); // notify service via file that it needs to reload the preferences File watchFile = new File(getFilesDir() + "PrefsChanged.none"); if (!watchFile.exists()) { try { watchFile.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } watchFile.setLastModified(System.currentTimeMillis()); } else if (mode == Mode.LOCALE) { if (!isCanceled()) { final Intent resultIntent = new Intent(); final Bundle resultBundle = new Bundle(); // set the version, title and body resultBundle.putInt(Constants.BUNDLE_EXTRA_INT_VERSION_CODE, Constants.getVersionCode(getApplicationContext())); resultBundle.putInt(Constants.BUNDLE_EXTRA_INT_TYPE, Constants.Type.SETTINGS.ordinal()); resultBundle.putInt(Constants.BUNDLE_EXTRA_INT_MODE, mMode.ordinal()); resultBundle.putString(Constants.BUNDLE_EXTRA_STRING_PACKAGE_LIST, selectedPackages); resultBundle.putString(Constants.BUNDLE_EXTRA_STRING_PKG_RENAMES, arrayRenames.toString()); String blurb = ""; switch (mMode) { case OFF: blurb = getResources().getStringArray(R.array.mode_choices)[0]; break; case INCLUDE: blurb = getResources().getStringArray(R.array.mode_choices)[2]; break; case EXCLUDE: blurb = getResources().getStringArray(R.array.mode_choices)[1]; } Log.i(Constants.LOG_TAG, resultBundle.toString()); resultIntent.putExtra(com.twofortyfouram.locale.Intent.EXTRA_BUNDLE, resultBundle); resultIntent.putExtra(com.twofortyfouram.locale.Intent.EXTRA_STRING_BLURB, blurb); setResult(RESULT_OK, resultIntent); } } }
From source file:com.flexible.flexibleadapter.common.FlexibleItemAnimator.java
private void runChangeAnimation(boolean removalsPending, boolean changesPending) { // Change animation to run in parallel with move animations if (changesPending) { final ArrayList<ChangeInfo> changes = new ArrayList<>(); changes.addAll(mPendingChanges); mChangesList.add(changes);//w w w . j ava2s . c o m mPendingChanges.clear(); Runnable changer = new Runnable() { @Override public void run() { 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(); } } }
From source file:com.dycode.jepretstory.mediachooser.activity.BucketHomeFragmentActivity.java
private void addMediaModel(ArrayList<MediaModel> existing, ArrayList<Parcelable> source) { List<MediaModel> newList = new ArrayList<MediaModel>(source.size()); for (Parcelable model : source) { newList.add((MediaModel) model); if (!existing.contains(model)) { //add to media selected view onMediaSelected((MediaModel) model); }/*from w ww. j av a2s.c o m*/ } for (MediaModel model : existing) { if (!newList.contains(model)) { //remove from media selected view onMediaUnselected(model); } } existing.clear(); existing.addAll(newList); }
From source file:com.espertech.esper.epl.join.base.JoinSetComposerPrototypeImpl.java
public JoinSetComposerDesc create(Viewable[] streamViews, boolean isFireAndForget) { // Build indexes Map<String, EventTable>[] indexesPerStream = new HashMap[indexSpecs.length]; for (int streamNo = 0; streamNo < indexSpecs.length; streamNo++) { if (indexSpecs[streamNo] == null) { continue; }/*from w w w .j a v a 2 s.co m*/ Map<String, QueryPlanIndexItem> items = indexSpecs[streamNo].getItems(); indexesPerStream[streamNo] = new LinkedHashMap<String, EventTable>(); for (Map.Entry<String, QueryPlanIndexItem> entry : items.entrySet()) { EventTable index; if (streamJoinAnalysisResult.getViewExternal()[streamNo] != null) { index = streamJoinAnalysisResult.getViewExternal()[streamNo] .getJoinIndexTable(items.get(entry.getKey())); } else { index = EventTableUtil.buildIndex(streamNo, items.get(entry.getKey()), streamTypes[streamNo], false, entry.getValue().isUnique(), null); } indexesPerStream[streamNo].put(entry.getKey(), index); } } // Build strategies QueryPlanNode[] queryExecSpecs = queryPlan.getExecNodeSpecs(); QueryStrategy[] queryStrategies = new QueryStrategy[queryExecSpecs.length]; for (int i = 0; i < queryExecSpecs.length; i++) { QueryPlanNode planNode = queryExecSpecs[i]; if (planNode == null) { log.debug(".makeComposer No execution node for stream " + i + " '" + streamNames[i] + "'"); continue; } ExecNode executionNode = planNode.makeExec(statementName, statementId, annotations, indexesPerStream, streamTypes, streamViews, historicalStreamIndexLists, streamJoinAnalysisResult.getViewExternal()); if (log.isDebugEnabled()) { log.debug(".makeComposer Execution nodes for stream " + i + " '" + streamNames[i] + "' : \n" + ExecNode.print(executionNode)); } queryStrategies[i] = new ExecNodeQueryStrategy(i, streamTypes.length, executionNode); } // If this is not unidirectional and not a self-join (excluding self-outer-join) JoinSetComposerDesc joinSetComposerDesc; if ((!streamJoinAnalysisResult.isUnidirectional()) && (!streamJoinAnalysisResult.isPureSelfJoin() || outerJoinDescList.length > 0)) { JoinSetComposer composer; if (historicalViewableDesc.isHasHistorical()) { composer = new JoinSetComposerHistoricalImpl(indexesPerStream, queryStrategies, streamViews, exprEvaluatorContext); } else { if (isFireAndForget) { composer = new JoinSetComposerFAFImpl(indexesPerStream, queryStrategies, streamJoinAnalysisResult.isPureSelfJoin(), exprEvaluatorContext, joinRemoveStream, isOuterJoins); } else { composer = new JoinSetComposerImpl(indexesPerStream, queryStrategies, streamJoinAnalysisResult.isPureSelfJoin(), exprEvaluatorContext, joinRemoveStream); } } // rewrite the filter expression for all-inner joins in case "on"-clause outer join syntax was used to include those expressions ExprNode filterExpression = getFilterExpressionInclOnClause(optionalFilterNode, outerJoinDescList); ExprEvaluator postJoinEval = filterExpression == null ? null : filterExpression.getExprEvaluator(); joinSetComposerDesc = new JoinSetComposerDesc(composer, postJoinEval); } else { QueryStrategy driver; int unidirectionalStream; if (streamJoinAnalysisResult.getUnidirectionalStreamNumber() != -1) { unidirectionalStream = streamJoinAnalysisResult.getUnidirectionalStreamNumber(); driver = queryStrategies[unidirectionalStream]; } else { unidirectionalStream = 0; driver = queryStrategies[0]; } JoinSetComposer composer = new JoinSetComposerStreamToWinImpl(indexesPerStream, streamJoinAnalysisResult.isPureSelfJoin(), unidirectionalStream, driver, streamJoinAnalysisResult.getUnidirectionalNonDriving()); ExprEvaluator postJoinEval = optionalFilterNode == null ? null : optionalFilterNode.getExprEvaluator(); joinSetComposerDesc = new JoinSetComposerDesc(composer, postJoinEval); } // compile prior events per stream to preload any indexes EventBean[][] eventsPerStream = new EventBean[streamNames.length][]; ArrayList<EventBean> events = new ArrayList<EventBean>(); for (int i = 0; i < eventsPerStream.length; i++) { // For named windows, we don't need to preload indexes from the iterators as this is always done already if (streamJoinAnalysisResult.getNamedWindow()[i]) { continue; } Iterator<EventBean> it = null; if (!(streamViews[i] instanceof HistoricalEventViewable) && !(streamViews[i] instanceof DerivedValueView)) { try { it = streamViews[i].iterator(); } catch (UnsupportedOperationException ex) { // Joins do not support the iterator } } if (it != null) { for (; it.hasNext();) { events.add(it.next()); } eventsPerStream[i] = events.toArray(new EventBean[events.size()]); events.clear(); } else { eventsPerStream[i] = new EventBean[0]; } } // init joinSetComposerDesc.getJoinSetComposer().init(eventsPerStream); return joinSetComposerDesc; }
From source file:com.calciumion.widget.BasePagerAdapter.java
@Override public final void finishUpdate(ViewGroup container) { ArrayList<View> recycledViews = new ArrayList<View>(); // Remove views backing destroyed items from the specified container, // and queue them for recycling. for (int i = 0; destroyedItems.size() > 0 && i < container.getChildCount(); i++) { View v = container.getChildAt(i); Iterator<Object> it = destroyedItems.iterator(); while (it.hasNext()) { if (isViewFromObject(v, it.next())) { container.removeView(v); recycledViews.add(v);/*from w w w . ja v a 2 s .c o m*/ it.remove(); break; } } } // Render views and attach them to the container. Page views are reused // whenever possible. for (Object instantiatedItem : instantiatedItems) { View convertView = null; if (recycledViews.size() > 0) convertView = recycledViews.remove(0); convertView = getView(instantiatedItem, convertView, container); convertView.setTag(instantiatedItem); container.addView(convertView); } instantiatedItems.clear(); recycledViews.clear(); }
From source file:org.apache.hadoop.hive.ql.parse.NewGroupByUtils1.java
private void genDistTag2Aggr(QB qb, String dest, ArrayList<ArrayList<Integer>> tag2AggrPos, ArrayList<ArrayList<ASTNode>> distTag2AggrParamAst, HashMap<Integer, ArrayList<Integer>> nonDistPos2TagOffs) { HashMap<String, ASTNode> aggregationTrees = qb.getParseInfo().getAggregationExprsForClause(dest); if (aggregationTrees == null || aggregationTrees.isEmpty()) { return;// w ww. ja v a 2 s .c o m } tag2AggrPos.clear(); distTag2AggrParamAst.clear(); tag2AggrPos.add(new ArrayList<Integer>()); distTag2AggrParamAst.add(new ArrayList<ASTNode>()); HashMap<String, Integer> treeidx = new HashMap<String, Integer>(); HashMap<Integer, HashSet<String>> tag2paramaststr = new HashMap<Integer, HashSet<String>>(); int pos = 0; for (Map.Entry<String, ASTNode> entry : aggregationTrees.entrySet()) { ASTNode value = entry.getValue(); String[] params = new String[value.getChildCount() - 1]; for (int i = 1; i < value.getChildCount(); i++) { params[i - 1] = value.getChild(i).toStringTree(); } Arrays.sort(params); ArrayList<String> params1 = new ArrayList<String>(); params1.add(params[0]); String curr = params[0]; for (int i = 1; i < params.length; i++) { if (!curr.equalsIgnoreCase(params[i])) { params1.add(params[i]); curr = params[i]; } } StringBuffer sb = new StringBuffer(); sb.append(value.getToken().getType()); for (int i = 0; i < params1.size(); i++) { sb.append(params1.get(i)); } String asttree = sb.toString(); if (!treeidx.containsKey(asttree)) { if (value.getToken().getType() == HiveParser.TOK_FUNCTIONDI) { int disttag = tag2AggrPos.size(); treeidx.put(asttree, disttag); tag2AggrPos.add(new ArrayList<Integer>()); distTag2AggrParamAst.add(new ArrayList<ASTNode>()); if (!tag2paramaststr.containsKey(disttag)) { tag2paramaststr.put(disttag, new HashSet<String>()); } for (int i = 1; i < value.getChildCount(); i++) { ASTNode param = (ASTNode) value.getChild(i); if (!tag2paramaststr.get(disttag).contains(param.toStringTree())) { tag2paramaststr.get(disttag).add(param.toStringTree()); distTag2AggrParamAst.get(distTag2AggrParamAst.size() - 1).add(param); } } } else { if (!tag2paramaststr.containsKey(0)) { tag2paramaststr.put(0, new HashSet<String>()); } treeidx.put(asttree, 0); for (int i = 1; i < value.getChildCount(); i++) { ASTNode param = (ASTNode) value.getChild(i); if (!tag2paramaststr.get(0).contains(param.toStringTree())) { tag2paramaststr.get(0).add(param.toStringTree()); distTag2AggrParamAst.get(0).add(param); } } } } if (value.getToken().getType() != HiveParser.TOK_FUNCTIONDI) { nonDistPos2TagOffs.put(pos, new ArrayList<Integer>()); for (int i = 1; i < value.getChildCount(); i++) { String param = value.getChild(i).toStringTree(); int idx = -1; for (int j = 0; j < distTag2AggrParamAst.get(0).size(); j++) { if (distTag2AggrParamAst.get(0).get(j).toStringTree().equals(param)) { idx = j; break; } } nonDistPos2TagOffs.get(pos).add(idx); } } tag2AggrPos.get(treeidx.get(asttree)).add(pos); pos++; } LOG.debug("distTag2AggrPos:\t" + tag2AggrPos); for (int i = 0; i < tag2AggrPos.size(); i++) { LOG.debug("distTag2AggrPos[" + i + "]:\t" + tag2AggrPos.get(i)); } LOG.debug("distTag2AggrParamAst:\t" + distTag2AggrParamAst); for (int i = 0; i < distTag2AggrParamAst.size(); i++) { StringBuffer sb = new StringBuffer(); for (int j = 0; j < distTag2AggrParamAst.get(i).size(); j++) { sb.append(distTag2AggrParamAst.get(i).get(j).toStringTree()).append("\t"); } LOG.debug("distTag2AggrParamAst[" + i + "]:\t" + sb.toString()); } LOG.debug("nonDistPos2TagOffs:\t" + nonDistPos2TagOffs); for (Integer key : nonDistPos2TagOffs.keySet()) { LOG.debug("nonDistPos2TagOffs[" + key + "]:\t" + nonDistPos2TagOffs.get(key)); } }
From source file:com.facebook.RequestTests.java
@LargeTest public void testLastOnProgressCallbackIsCalledOnce() { Bitmap image = Bitmap.createBitmap(128, 128, Bitmap.Config.ALPHA_8); GraphRequest request = GraphRequest.newUploadPhotoRequest(null, ShareInternalUtility.MY_PHOTOS, image, null, null, null);//from ww w . j a v a 2s .c om assertTrue(request != null); final ArrayList<Boolean> calledBack = new ArrayList<Boolean>(); request.setCallback(new GraphRequest.OnProgressCallback() { @Override public void onCompleted(GraphResponse response) { } @Override public void onProgress(long current, long max) { if (current == max) calledBack.add(true); else if (current > max) calledBack.clear(); } }); GraphResponse response = request.executeAndWait(); assertNotNull(response); assertEquals(1, calledBack.size()); }
From source file:geva.Operator.Operations.GrowInitialiser.java
/** * Recursively builds a tree.//from ww w .ja v a 2 s.c o m * @param dt Tree to grow on * @return If the tree is valid **/ public boolean grow(NimbleTree<Symbol> dt) { Rule rule; Iterator<Production> prodIt; ArrayList<Integer> possibleRules = new ArrayList<Integer>(); Production prod; int prodVal; boolean result; int newMaxDepth; Iterator<Symbol> symIt; Symbol symbol; try { if (dt.getCurrentNode().getData().getType() == Enums.SymbolType.TSymbol) { //Check if it is for ADF if (dt.getCurrentNode().getData().getSymbolString().contains("BRR")) { this.extraCodons++; } return true; } if (dt.getCurrentLevel() > this.maxDepth) { //System.out.println("Too deep:"+dt.getCurrentLevel()+">"+this.maxDepth); return false; } rule = grammar.findRule(dt.getCurrentNode().getData()); if (rule != null) { prodIt = rule.iterator(); possibleRules.clear(); int ii = 0; //System.out.print(rule.getLHS().getSymbolString()+" minD:"+rule.getMinimumDepth()+" maxD:"+maxDepth+" cD:"+dt.getCurrentLevel()); while (prodIt.hasNext()) { prod = prodIt.next(); if ((dt.getCurrentLevel() + prod.getMinimumDepth()) <= this.maxDepth) { possibleRules.add(ii); } ii++; } //System.out.print(" \n"); if (possibleRules.isEmpty()) { //System.out.println("EmptyPossible rules:"+rule); return false; } else { prodVal = this.rng.nextInt(possibleRules.size()); int modVal = possibleRules.get(prodVal); int tmp1 = this.rng.nextInt((Integer.MAX_VALUE - rule.size())); int tmp; int mod = tmp1 % rule.size(); int diff; if (mod > modVal) { diff = mod - modVal; tmp = tmp1 - diff; } else { diff = modVal - mod; tmp = tmp1 + diff; } int newMod = tmp % rule.size(); if (newMod != modVal) { logger.info("modVal:" + modVal + " tmp1:" + tmp1 + " mod:" + mod + " tmp:" + tmp + " rule.size():" + rule.size() + " newMod:" + newMod); } if (rule.size() > 1) { this.chromosome.add(tmp); //correct choosing of production?? prod = rule.get(possibleRules.get(prodVal)); } else { // only one rule does not use a codon //this.chromosome.add(tmp); //correct choosing of production?? prod = rule.get(0); } } result = true; newMaxDepth = dt.getDepth(); symIt = prod.iterator(); while (symIt.hasNext() && result) { symbol = symIt.next(); dt.addChild(symbol); dt.setCurrentNode(dt.getCurrentNode().getEnd()); dt.setCurrentLevel(dt.getCurrentLevel() + 1); result = grow(dt); dt.setCurrentLevel(dt.getCurrentLevel() - 1); if (newMaxDepth < dt.getDepth()) { newMaxDepth = dt.getDepth(); } } chromosome.setValid(result); dt.setDepth(newMaxDepth); return result; } else { if (!checkGECodonValue(dt)) { throw new InitializationException( "Non-existent rule, maybe GECODON not yet impelemnted. Could not find" + dt.getCurrentNode().getData().getSymbolString()); } return true; } } catch (InitializationException e) { logger.error("Exception initializing", e); return false; } }