Java Code Examples for java.util.ArrayList#isEmpty()

The following examples show how to use java.util.ArrayList#isEmpty() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: android_9.0.0_r45   File: GestureStore.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Remove a gesture from the library. If there are no more gestures for the
 * given entry, the gesture entry will be removed.
 * 
 * @param entryName entry name
 * @param gesture
 */
public void removeGesture(String entryName, Gesture gesture) {
    ArrayList<Gesture> gestures = mNamedGestures.get(entryName);
    if (gestures == null) {
        return;
    }

    gestures.remove(gesture);

    // if there are no more samples, remove the entry automatically
    if (gestures.isEmpty()) {
        mNamedGestures.remove(entryName);
    }

    mClassifier.removeInstance(gesture.getID());

    mChanged = true;
}
 
Example 2
Source Project: KOMORAN   File: SorterQueryParser.java    License: Apache License 2.0 6 votes vote down vote up
public Sort getSorter(Map<String, String> inputParam) {
    ArrayList<HashMap<String, String>> sorters = this.parse(inputParam);
    Sort sortBy = null;

    if (sorters == null) {
        return null;
    } else if (sorters.isEmpty()) {
        sortBy = Sort.by("token").ascending();
    } else {
        for (HashMap<String, String> sorter : sorters) {
            Sort.Direction dir = sorter.get("dir").equalsIgnoreCase("asc") ? Sort.Direction.ASC : Sort.Direction.DESC;

            if (sortBy == null) {
                sortBy = Sort.by(dir, sorter.get("field"));
            } else {
                sortBy = sortBy.and(Sort.by(dir, sorter.get("field")));
            }
        }
    }

    return sortBy;
}
 
Example 3
Source Project: BaseProject   File: ASelectableDelegate.java    License: Apache License 2.0 6 votes vote down vote up
public boolean markItemDatasSelectedOrNot(boolean isToSelectOrNot, Collection<T> itemDatas) {
    if (curSelectableMode == MODE_MULTY_CHOICE) {
        if (!isToSelectOrNot) {
            if (selectedUniqueMarks == null || selectedUniqueMarks.isEmpty()) {
                return false;
            }
        }
        if (itemDatas != null) {
            ArrayList<Object> itemDataUniqueMarks = null;
            for (T itemData : itemDatas) {
                Object uniqueMarkOfItemData = toJudgeItemDataUniqueMark(itemData);
                if (uniqueMarkOfItemData != null) {
                    if (itemDataUniqueMarks == null) {
                        itemDataUniqueMarks = new ArrayList<>(itemDatas.size());
                    }
                    itemDataUniqueMarks.add(uniqueMarkOfItemData);
                }
            }
            if (itemDataUniqueMarks != null && !itemDataUniqueMarks.isEmpty()) {
                return markSelectedOrNot(isToSelectOrNot, itemDataUniqueMarks);
            }
        }
    }
    return false;
}
 
Example 4
Source Project: gcs   File: AdvantageOutline.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unused")
@Override
public void increment() {
    ArrayList<RowUndo> undos = new ArrayList<>();
    for (Advantage advantage : new FilteredIterator<>(getModel().getSelectionAsList(), Advantage.class)) {
        if (!advantage.canHaveChildren() && advantage.isLeveled()) {
            RowUndo undo = new RowUndo(advantage);
            advantage.adjustLevel(1);
            if (undo.finish()) {
                undos.add(undo);
            }
        }
    }
    if (!undos.isEmpty()) {
        repaintSelection();
        new MultipleRowUndo(undos);
    }
}
 
Example 5
public ArrayList<ResultRow> runQuery(Directive directive, Collection<Topic> contextTopics) throws QueryException {
    TopicMap tm=null;
    ArrayList<ResultRow> context=new ArrayList<ResultRow>();
    for(Topic t : contextTopics){
        if(tm==null) tm=t.getTopicMap();
        context.add(new ResultRow(t));
    }
    
    if(tm==null) return new ArrayList<ResultRow>(); // no topics in contextTopics
    
    QueryContext queryContext=new QueryContext(tm, "en");
    
    if(context.isEmpty()){
        return new ArrayList<ResultRow>();
    }
    else if(context.size()==1){
        return directive.doQuery(queryContext, context.get(0));
    }
    else{
        return directive.from(new Static(context)).doQuery(queryContext, context.get(0));
    }
}
 
Example 6
private static int mst(int N, ArrayList<Edge> edges, ArrayList<Edge> usedEdges) {
	int [] parent=new int [N];
	for (int v=0;v<N;v++) parent[v]=v;
	
	int cost=0;
	while (!edges.isEmpty()) {
		Edge e=edges.remove(0);
		int px=getParent(parent, e.x);
		int py=getParent(parent, e.y);
		if (px!=py) {
			if (px>py) parent[px]=py;
			else parent[py]=px;
			if (usedEdges!=null) usedEdges.add(e);
			cost+=e.dist;
		}
	}
	
	for (int i=1;i<parent.length;i++) if (getParent(parent,0)!=getParent(parent,i)) return Integer.MAX_VALUE;
	return cost;
}
 
Example 7
Source Project: flutter_contacts   File: ContactsServicePlugin.java    License: MIT License 6 votes vote down vote up
private Cursor getCursorForPhone(String phone) {
  if (phone.isEmpty())
    return null;

  Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
  String[] projection = new String[]{BaseColumns._ID};

  ArrayList<String> contactIds = new ArrayList<>();
  Cursor phoneCursor = contentResolver.query(uri, projection, null, null, null);
  while (phoneCursor != null && phoneCursor.moveToNext()){
    contactIds.add(phoneCursor.getString(phoneCursor.getColumnIndex(BaseColumns._ID)));
  }
  if (phoneCursor!= null)
    phoneCursor.close();

  if (!contactIds.isEmpty()) {
    String contactIdsListString = contactIds.toString().replace("[", "(").replace("]", ")");
    String contactSelection = ContactsContract.Data.CONTACT_ID + " IN " + contactIdsListString;
    return contentResolver.query(ContactsContract.Data.CONTENT_URI, PROJECTION, contactSelection, null, null);
  }

  return null;
}
 
Example 8
Source Project: litho   File: TransitionManager.java    License: Apache License 2.0 6 votes vote down vote up
private @Nullable AnimationBinding createAnimationsForTransitionSet(TransitionSet transitionSet) {
  final ArrayList<Transition> children = transitionSet.getChildren();
  final ArrayList<AnimationBinding> createdAnimations = new ArrayList<>();
  for (int i = 0, size = children.size(); i < size; i++) {
    final AnimationBinding animation = createAnimationsForTransition(children.get(i));
    if (animation != null) {
      createdAnimations.add(animation);
    }
  }

  if (createdAnimations.isEmpty()) {
    return null;
  }

  return transitionSet.createAnimation(createdAnimations);
}
 
Example 9
@Override
public void activate( Char ch ) {

	int nDrops = Random.NormalIntRange(3, 6);

	ArrayList<Integer> candidates = new ArrayList<>();
	for (int i : PathFinder.NEIGHBOURS8){
		if (Dungeon.level.passable[pos+i]
				&& pos+i != Dungeon.level.entrance
				&& pos+i != Dungeon.level.exit){
			candidates.add(pos+i);
		}
	}

	for (int i = 0; i < nDrops && !candidates.isEmpty(); i++){
		Integer c = Random.element(candidates);
		Dungeon.level.drop(new Dewdrop(), c).sprite.drop(pos);
		candidates.remove(c);
	}

}
 
Example 10
Source Project: bazel   File: CcCompilationContext.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Enter the TreeArtifactValues in each TreeArtifact into pathToLegalOutputArtifact. Returns
 * true on success.
 *
 * <p>If a TreeArtifact's value is missing, returns false, and leave pathToLegalOutputArtifact
 * unmodified.
 */
public static boolean handleTreeArtifacts(
    Environment env,
    Map<PathFragment, Artifact> pathToLegalOutputArtifact,
    ArrayList<Artifact> treeArtifacts)
    throws InterruptedException {
  if (!treeArtifacts.isEmpty()) {
    Map<SkyKey, SkyValue> valueMap = env.getValues(treeArtifacts);
    if (env.valuesMissing()) {
      return false;
    }
    for (SkyValue value : valueMap.values()) {
      Preconditions.checkState(value instanceof TreeArtifactValue);
      TreeArtifactValue treeArtifactValue = (TreeArtifactValue) value;
      for (TreeFileArtifact treeFileArtifact : treeArtifactValue.getChildren()) {
        pathToLegalOutputArtifact.put(treeFileArtifact.getExecPath(), treeFileArtifact);
      }
    }
  }
  return true;
}
 
Example 11
Source Project: Dainty   File: CollectionEditActivity.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * android 6.0 以上需要动态申请权限
 */
private void initPermission() {
    String permissions[] = {
            Manifest.permission.INSTALL_SHORTCUT,
            Manifest.permission.UNINSTALL_SHORTCUT
    };

    ArrayList<String> toApplyList = new ArrayList<>();

    for (String perm : permissions) {
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, perm)) {
            toApplyList.add(perm);
            // 进入到这里代表没有权限.

        }
    }
    String tmpList[] = new String[toApplyList.size()];
    if (!toApplyList.isEmpty()) {
        ActivityCompat.requestPermissions(this, toApplyList.toArray(tmpList), 123);
    }else {
        addShortCut();
    }
}
 
Example 12
Source Project: vespa   File: HtmlTable.java    License: Apache License 2.0 5 votes vote down vote up
public int getColumnCount() {
    int cols = 0;
    ArrayList<Integer> next = new ArrayList<Integer>();
    for (Row row : cells) {
        int rowCount = 0;
        if (!next.isEmpty()) {
            rowCount += next.get(0);
            next.remove(0);
        }
        for (Cell c : row.cells) {
            int width = 1;
            if (c.properties.colSpan != null && c.properties.colSpan > 1) {
                width = c.properties.colSpan;
            }
            rowCount += width;
            if (c.properties.rowSpan != null && c.properties.rowSpan > 1) {
                while (next.size() < c.properties.rowSpan - 1) {
                    next.add(0);
                }
                for (int i=1; i<c.properties.rowSpan; ++i) {
                    next.set(i - 1, next.get(i - 1) + width);
                }
            }
        }
        cols = Math.max(cols, rowCount);
    }
    return cols;
}
 
Example 13
Source Project: Concurnas   File: DefoAssignmentVisitor.java    License: MIT License 5 votes vote down vote up
@Override
public Object visit(ClassDef classDef) {
	HashMap<ConstructorDef, HashMap<String, ArrayList<AssignExisting>>> prevconstructorTovalsSetInConstructor = constructorTovalsSetInConstructor;
	HashMap<ConstructorDef, ConstructorDef>  prevconstructorCallsOwnConstructor = constructorCallsOwnConstructor;
	
	constructorTovalsSetInConstructor = new HashMap<ConstructorDef, HashMap<String, ArrayList<AssignExisting>>>();
	constructorCallsOwnConstructor = new HashMap<ConstructorDef, ConstructorDef>();
	
	HashSet<String> prev = valsAlreadySetWhenDeclaredAtClassLevel;
	
	valsAlreadySetWhenDeclaredAtClassLevel = new HashSet<String>();
	Object ret = super.visit(classDef);
	HashSet<String> setAlready = valsAlreadySetWhenDeclaredAtClassLevel;
	valsAlreadySetWhenDeclaredAtClassLevel = prev;
	
	//follow the trail and ensure all final vars are set
	TheScopeFrame tsf = classDef.getScopeFrame();
	if(null!= tsf){
		ArrayList<VarAtScopeLevel> finalFieldsInClass = tsf.getAllVariablesAtScopeLevel(true, true, false, false);
		if(!finalFieldsInClass.isEmpty()) {
			processFieldsAndErr(classDef, finalFieldsInClass, setAlready, true);
		}
		
		if(!classDef.objProvider) {
			ArrayList<VarAtScopeLevel> nonNullFields = tsf.getAllVariablesAtScopeLevel(false, true, false, true);
			if(!nonNullFields.isEmpty()) {
				processFieldsAndErr(classDef, nonNullFields, setAlready, false);
			}
		}
	}
	
	constructorTovalsSetInConstructor = prevconstructorTovalsSetInConstructor;
	constructorCallsOwnConstructor = prevconstructorCallsOwnConstructor;
	
	return ret;
}
 
Example 14
Source Project: sqlitemagic   File: OperationHelper.java    License: Apache License 2.0 5 votes vote down vote up
OperationHelper(@ConflictAlgorithm int conflictAlgorithm,
                @Op int op,
                @Nullable ArrayList<Column> operationByColumns) {
  this.conflictAlgorithm = conflictAlgorithm;
  this.ignoreConflict = conflictAlgorithm == CONFLICT_IGNORE;
  this.operationByColumns = operationByColumns;
  this.customSqlNeededForConflictAlgorithm = conflictAlgorithm != CONFLICT_NONE && conflictAlgorithm != CONFLICT_ABORT;
  this.customSqlNeededForUpdates = op != Op.INSERT && operationByColumns != null && !operationByColumns.isEmpty();
  if (customSqlNeededForConflictAlgorithm) {
    switch (op) {
      case 0:
        inserts = new SimpleArrayMap<>(SimpleArrayMap.BASE_SIZE);
        break;
      case 1:
        updates = new SimpleArrayMap<>(SimpleArrayMap.BASE_SIZE);
        break;
      case 2:
        inserts = new SimpleArrayMap<>(SimpleArrayMap.BASE_SIZE);
        updates = new SimpleArrayMap<>(SimpleArrayMap.BASE_SIZE);
        break;
      default:
        break;
    }
  }
  if (!customSqlNeededForConflictAlgorithm && customSqlNeededForUpdates) {
    updates = new SimpleArrayMap<>(SimpleArrayMap.BASE_SIZE);
  }
}
 
Example 15
Source Project: phtree   File: TestNearestNeighbourF.java    License: Apache License 2.0 5 votes vote down vote up
private ArrayList<double[]> nearestNeighborK(PhTreeF<?> tree, int k, double[] q) {
	double dMax = Double.MAX_VALUE;
	ArrayList<double[]> best = new ArrayList<>();
	PhIteratorF<?> i = tree.queryExtent();
	while (i.hasNext()) {
		double[] cand = i.nextKey();
		double dNew = dist(q, cand);
		if (dNew < dMax || best.size() < k) {
			if (best.isEmpty()) {
				dMax = dNew;
				best.add( cand );
			} else {
				int j = 0;
				for ( ; j < best.size(); j++) {
					double dJ = dist(q, best.get(j));
					if (dJ > dNew) {
						best.add(j, cand);
						break;
					}
				}
				if (j == best.size()) {
					best.add(cand);
				}
				if (best.size() > k) {
					best.remove(k); 
				}
				dMax = dist(q, best.get(best.size()-1)); 
			}
		}
	}
	return best;
}
 
Example 16
Source Project: BedwarsRel   File: Utils.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static String implode(String glue, ArrayList<String> strings) {
  if (strings.isEmpty()) {
    return "";
  }

  StringBuilder builder = new StringBuilder();
  builder.append(strings.remove(0));

  for (String str : strings) {
    builder.append(glue);
    builder.append(str);
  }

  return builder.toString();
}
 
Example 17
Source Project: LiveBlurListView   File: HanziToPinyin.java    License: Apache License 2.0 5 votes vote down vote up
private void addSubString(final ArrayList<Token> tokens, final ArrayList<String> shortSubStrOffset,
						StringBuilder subStrSet, StringBuilder offsets){
	if(tokens == null || tokens.isEmpty())
		return;
	
	int size = tokens.size();
	int len = 0;
	StringBuilder mShortSubStr = new StringBuilder();
	StringBuilder mShortSubStrOffsets = new StringBuilder();
	StringBuilder mShortSubStrSet = new StringBuilder();
	StringBuilder mShortSubStrOffsetsSet = new StringBuilder();
	
	for(int i=size-1; i>=0 ; i--){
		String mTempStr = tokens.get(i).target;
		len += mTempStr.length();
		String mTempOffset = shortSubStrOffset.get(i);
		if(mShortSubStr.length()>0){
			mShortSubStr.deleteCharAt(0);
			mShortSubStrOffsets.deleteCharAt(0);
		}
		mShortSubStr.insert(0, mTempStr);
		mShortSubStr.insert(0,(char)len);
		mShortSubStrOffsets.insert(0,mTempOffset);
		mShortSubStrOffsets.insert(0,(char)len);
		mShortSubStrSet.insert(0,mShortSubStr);
		mShortSubStrOffsetsSet.insert(0, mShortSubStrOffsets);
	}
	
	subStrSet.append(mShortSubStrSet);
	offsets.append(mShortSubStrOffsetsSet);
	tokens.clear();
	shortSubStrOffset.clear();
}
 
Example 18
Source Project: Mortar-architect   File: History.java    License: MIT License 5 votes vote down vote up
void init(Bundle bundle) {
    scopeNamer = bundle.getParcelable(SCOPES_NAMER_KEY);

    ArrayList<Bundle> entryBundles = bundle.getParcelableArrayList(ENTRIES_KEY);
    if (entryBundles != null) {
        entries = new ArrayList<>(entryBundles.size());
        if (!entryBundles.isEmpty()) {
            for (int i = 0; i < entryBundles.size(); i++) {
                entries.add(Entry.fromBundle(entryBundles.get(i), parceler));
            }
        }
    }
}
 
Example 19
public String processListDelete() throws PermissionException
{
  //log.info(this + ".processListDelete() in SyllabusTool");

  try
  {
    if (!isAddOrEdit())
    {
      return "permission_error";
    }
    else
    {
      ArrayList selected = getSelectedEntries();
      if (selected.isEmpty())
      {
        FacesContext.getCurrentInstance().addMessage(
            null,
            MessageFactory.getMessage(FacesContext.getCurrentInstance(),
                "error_delete_select", (Object) null));

        return null;
      }else{
      	//verify valid modifications:
      	for(DecoratedSyllabusEntry entry : (ArrayList<DecoratedSyllabusEntry>) selected){
      		String validate = entry.validateInput();
      		if(!"".equals(validate)){
      			String itemTitle = entry.getEntry().getTitle();
      			if(itemTitle == null || "".equals(itemTitle.trim())){
      				//title is null, so just point to the item #
      				itemTitle = MessageFactory.getMessage(FacesContext.getCurrentInstance(),
  							"error_invalid_entry_item", Integer.toString(entry.getEntry().getPosition())).getSummary();
      			}
      			//invalid entry:
      			FacesContext.getCurrentInstance().addMessage(
      					null,
      					MessageFactory.getMessage(FacesContext.getCurrentInstance(),
      							"error_invalid_entry", itemTitle, validate));
      			return null;
      		}
      	}
      	
      	return "delete_confirm";
      }
    }
  }
  catch (Exception e)
  {
    log.info(this + ".processListDelete in SyllabusTool: " + e);
    FacesContext.getCurrentInstance().addMessage(
        null,
        MessageFactory.getMessage(FacesContext.getCurrentInstance(),
            "error_general", (new Object[] { e.toString() })));
  }

  return null;
}
 
Example 20
/**
 * Merge the given DHT node into the marker sequence.  If there already
 * exist DHT marker segments in the sequence, then each table in the
 * node replaces the first table, in any DHT segment, with the same
 * table class and table id.  If none of the existing DHT segments contain
 * a table with the same class and id, then the table is added to the last
 * existing DHT segment.
 * If there are no DHT segments, then a new one is created and added
 * as follows:
 * If there are DQT segments, the new DHT segment is inserted immediately
 * following the last DQT segment.
 * If there are no DQT segments, the new DHT segment is inserted before
 * an SOF segment, if there is one.
 * If there is no SOF segment, the new DHT segment is inserted before
 * the first SOS segment, if there is one.
 * If there is no SOS segment, the new DHT segment is added to the end
 * of the sequence.
 */
private void mergeDHTNode(Node node) throws IIOInvalidTreeException {
    // First collect any existing DQT nodes into a local list
    ArrayList<DHTMarkerSegment> oldDHTs = new ArrayList<>();
    Iterator<MarkerSegment> iter = markerSequence.iterator();
    while (iter.hasNext()) {
        MarkerSegment seg = iter.next();
        if (seg instanceof DHTMarkerSegment) {
            oldDHTs.add((DHTMarkerSegment) seg);
        }
    }
    if (!oldDHTs.isEmpty()) {
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            NamedNodeMap attrs = child.getAttributes();
            int childID = MarkerSegment.getAttributeValue(child,
                                                          attrs,
                                                          "htableId",
                                                          0, 3,
                                                          true);
            int childClass = MarkerSegment.getAttributeValue(child,
                                                             attrs,
                                                             "class",
                                                             0, 1,
                                                             true);
            DHTMarkerSegment dht = null;
            int tableIndex = -1;
            for (int j = 0; j < oldDHTs.size(); j++) {
                DHTMarkerSegment testDHT = oldDHTs.get(j);
                for (int k = 0; k < testDHT.tables.size(); k++) {
                    DHTMarkerSegment.Htable testTable = testDHT.tables.get(k);
                    if ((childID == testTable.tableID) &&
                        (childClass == testTable.tableClass)) {
                        dht = testDHT;
                        tableIndex = k;
                        break;
                    }
                }
                if (dht != null) break;
            }
            if (dht != null) {
                dht.tables.set(tableIndex, dht.getHtableFromNode(child));
            } else {
                dht = oldDHTs.get(oldDHTs.size()-1);
                dht.tables.add(dht.getHtableFromNode(child));
            }
        }
    } else {
        DHTMarkerSegment newGuy = new DHTMarkerSegment(node);
        int lastDQT = findMarkerSegmentPosition(DQTMarkerSegment.class, false);
        int firstSOF = findMarkerSegmentPosition(SOFMarkerSegment.class, true);
        int firstSOS = findMarkerSegmentPosition(SOSMarkerSegment.class, true);
        if (lastDQT != -1) {
            markerSequence.add(lastDQT+1, newGuy);
        } else if (firstSOF != -1) {
            markerSequence.add(firstSOF, newGuy);
        } else if (firstSOS != -1) {
            markerSequence.add(firstSOS, newGuy);
        } else {
            markerSequence.add(newGuy);
        }
    }
}