Note: This method was moved from CollectionUtilities
176558
private static int matchesAt(CharSequence text, int offsetInText, CharSequence substring) {
        int len = substring.length();
        int textLength = text.length();
        if (textLength + offsetInText > len) {
            return -1;
        }
        int i = 0;
        for (int j = offsetInText; i < len; ++i, ++j) {
            char pc = substring.charAt(i);
            char tc = text.charAt(j);
            if (pc != tc) return -1;
        }
        return i;
    }
108991
@Deprecated
    public static Collection collectAll(Collection self, Collection collector, Closure transform) {
        return collectNested((Iterable)self, collector, transform);
    }
610228
public void clear()
    {
        Class collClass = getCollectionClass();

        // ECER: assure we notify all objects being removed, 
        // necessary for RemovalAwareCollections...
        if (IRemovalAwareCollection.class.isAssignableFrom(collClass))
        {
            getData().clear();
        }
        else
        {
            Collection coll;
            // BRJ: use an empty collection so isLoaded will return true
            // for non RemovalAwareCollections only !! 
            try
            {
                coll = (Collection) collClass.newInstance();
            }
            catch (Exception e)
            {
                coll = new ArrayList();
            }

            setData(coll);
        }
        _size = 0;
    }
943330
@Override
  public <T> List<T> remove(Collection<? extends T> batchToRemove, Class<T> entityClass) {
    return remove(batchToRemove, Util.determineCollectionName(entityClass));
  }
741347
@Override
  public <T> void updateCollectionSchema(CollectionSchemaUpdate update, String collectionName) {
    CollectionMetaData cmd = cmdMap.get(collectionName);
    @SuppressWarnings("unchecked")
    Map<Object, T> collection = (Map<Object, T>) collectionsRef.get().get(collectionName);
    if((null == cmd) || (null == collection)) {
      throw new InvalidJsonDbApiUsageException("Collection by name '" + collectionName + "' not found. Create collection first.");
    }
    boolean reloadCollectionAsSomethingChanged = false;
    //We only take care of ADD and RENAME, the deletes will be taken care of automatically.
    if (null != update) {
      Map<String, RenameOperation> renOps = update.getRenameOperations();
      if (renOps.size() > 0) {
        reloadCollectionAsSomethingChanged = true;
        cmd.getCollectionLock().writeLock().lock();
        
        for(Entry<String, RenameOperation> updateEntry: renOps.entrySet()) {
          String oldKey = updateEntry.getKey();
          
          RenameOperation op = updateEntry.getValue();
          String newKey = op.getNewName();

          JsonWriter jw;
          try {
            jw = new JsonWriter(dbConfig, cmd, collectionName, fileObjectsRef.get().get(collectionName));
          } catch (IOException ioe) {
            logger.error("Failed to obtain writer for " + collectionName, ioe);
            throw new JsonDBException("Failed to save " + collectionName, ioe);
          }
          jw.renameKeyInJsonFile(collection.values(), true, oldKey, newKey);
        }
        cmd.getCollectionLock().writeLock().unlock();
      }
      
      Map<String, AddOperation> addOps = update.getAddOperations();
      if (addOps.size() > 0) {
        reloadCollectionAsSomethingChanged = true;
        cmd.getCollectionLock().writeLock().lock();
        
        for(Entry<String, AddOperation> updateEntry: addOps.entrySet()) {
          AddOperation op = updateEntry.getValue();
          
          Object value = null;
          if (op.isSecret()) {
            value = dbConfig.getCipher().encrypt((String)op.getDefaultValue());
          } else {
            value = op.getDefaultValue();
          }
          
          String fieldName = updateEntry.getKey();
          Method setterMethod = cmd.getSetterMethodForFieldName(fieldName);
          for(T object : collection.values()) {
            Util.setFieldValueForEntity(object, value, setterMethod);
          }
        }
        
        JsonWriter jw;
        try {
          jw = new JsonWriter(dbConfig, cmd, collectionName, fileObjectsRef.get().get(collectionName));
        } catch (IOException ioe) {
          logger.error("Failed to obtain writer for " + collectionName, ioe);
          throw new JsonDBException("Failed to save " + collectionName, ioe);
        }
        jw.reWriteJsonFile(collection.values(), true);
        cmd.getCollectionLock().writeLock().unlock();
      }
      
      Map<String, DeleteOperation> delOps = update.getDeleteOperations();
      if ((renOps.size() < 1 && addOps.size() < 1) && (delOps.size() > 0)) {
        //There were no ADD operations but there are some DELETE operations so we have to just flush the collection once
        //This would not have been necessary if there was even 1 ADD operation
        
        reloadCollectionAsSomethingChanged = true;
        cmd.getCollectionLock().writeLock().lock();
        
        JsonWriter jw;
        try {
          jw = new JsonWriter(dbConfig, cmd, collectionName, fileObjectsRef.get().get(collectionName));
        } catch (IOException ioe) {
          logger.error("Failed to obtain writer for " + collectionName, ioe);
          throw new JsonDBException("Failed to save " + collectionName, ioe);
        }
        jw.reWriteJsonFile(collection.values(), true);
        cmd.getCollectionLock().writeLock().unlock();
      }
      if (reloadCollectionAsSomethingChanged) {
        reloadCollection(collectionName);
      }
    }
  }
1130033
def report_collection_diff(from_collection, to_collection, from_id, to_id):
    
    if from_collection == to_collection:
        return None

    diff = unified_diff(from_collection, to_collection, fromfile=from_id, tofile=to_id)
    error_message = (
        u"Different tests were collected between {from_id} and {to_id}. "
        u"The difference is:\n"
        u"{diff}"
    ).format(from_id=from_id, to_id=to_id, diff="\n".join(diff))
    msg = "\n".join([x.rstrip() for x in error_message.split("\n")])
    return msg
932513
private void processDatabaseMappingCollection(final Object databaseMappingCollection) {
        if (databaseMappingCollection == null || !isCastable("java.util.Collection", databaseMappingCollection.getClass())) {
            return;
        }

        final Collection<?> c = (Collection<?>) databaseMappingCollection;
        for (Object descriptor : c) {
            processDatabaseMappingObject(descriptor);
        }
    }
980060
@Override
  public void dropCollection(String collectionName) {
    CollectionMetaData cmd = cmdMap.get(collectionName);
    if((null == cmd) || (!collectionsRef.get().containsKey(collectionName))) {
      throw new InvalidJsonDbApiUsageException("Collection by name '" + collectionName + "' not found. Create collection first.");
    }
    cmd.getCollectionLock().writeLock().lock();
    try {
      File toDelete = fileObjectsRef.get().get(collectionName);
      try {
        Files.deleteIfExists(toDelete.toPath());
      } catch (IOException e) {
        logger.error("IO Exception deleting the collection file {}", toDelete.getName(), e);
        throw new InvalidJsonDbApiUsageException("Unable to create a collection file for collection: " + collectionName);
      }
      //cmdMap.remove(collectionName); //Do not remove it from the CollectionMetaData Map.
      //Someone might want to re insert a new collection of this type.
      fileObjectsRef.get().remove(collectionName);
      collectionsRef.get().remove(collectionName);
      contextsRef.get().remove(collectionName);
    } finally {
      cmd.getCollectionLock().writeLock().unlock();
    }
  }
240482
def remove(self, value, _sa_initiator=None):
        """"""

        key = self.keyfunc(value)
        # Let self[key] raise if key is not in this collection
        # testlib.pragma exempt:__ne__
        if not self.__contains__(key) or value not in self[key]:
            raise sa_exc.InvalidRequestError(
                "Can not remove '%s': collection holds '%s' for key '%s'. "
                "Possible cause: is the MappedCollection key function "
                "based on mutable properties or properties that only obtain "
                "values after flush?" %
                (value, self[key], key))
        self.__getitem__(key, _sa_initiator).remove(value)
365845
function isCollectionMethod(version, method) {
    return methodSupportsShorthand(version, method) || _.includes(expandAliases(version, ['reduce', 'reduceRight']), method)
}
270579
function( thing, method, internal ) {

                var thingName, thingMethod,
                    thingIsObject = $.isPlainObject( thing ),
                    thingObject = thingIsObject ? thing : {}

                if ( thing ) {

                    // If the thing isn’t an object, make it one.
                    if ( !thingIsObject ) {
                        thingObject[ thing ] = method
                    }

                    // Go through the things to bind to.
                    for ( thingName in thingObject ) {

                        // Grab the method of the thing.
                        thingMethod = thingObject[ thingName ]

                        // If it was an internal binding, prefix it.
                        if ( internal ) {
                            thingName = '_' + thingName
                        }

                        // Make sure the thing methods collection exists.
                        STATE.methods[ thingName ] = STATE.methods[ thingName ] || []

                        // Add the method to the relative method collection.
                        STATE.methods[ thingName ].push( thingMethod )
                    }
                }

                return P
            }
1188448
public static <K, V, C extends Collection<V>> void putIntoValueCollection(Map<K, C> map, K key, V value, CollectionFactory<V> cf) {
    C c = map.get(key);
    if (c == null) {
      c = ErasureUtils.<C>uncheckedCast(cf.newCollection());
      map.put(key, c);
    }
    c.add(value);
  }
1164063
@Override
	public boolean removeAll(Collection<?> collection) {
		if (booleanTerms == null) {
			return false;
		}
		return booleanTerms.removeAll(collection);
	}
277207
@Deprecated
    public Class<?> getClassFromCollection(final String collection) {
        final Set<MappedClass> mcs = mappedClassesByCollection.get(collection);
        if (mcs == null || mcs.isEmpty()) {
            throw new MappingException(format("The collection '%s' is not mapped to a java class.", collection));
        }
        if (mcs.size() > 1) {
            if (LOG.isInfoEnabled()) {
                LOG.info(format("Found more than one class mapped to collection '%s'%s", collection, mcs));
            }
        }
        return mcs.iterator().next().getClazz();
    }
531872
@Override
	protected List<OUT> executeOnCollections(List<IN> inputData, RuntimeContext ctx, ExecutionConfig executionConfig) throws Exception {
		MapPartitionFunction<IN, OUT> function = this.userFunction.getUserCodeObject();
		
		FunctionUtils.setFunctionRuntimeContext(function, ctx);
		FunctionUtils.openFunction(function, this.parameters);
		
		ArrayList<OUT> result = new ArrayList<OUT>(inputData.size() / 4);

		TypeSerializer<IN> inSerializer = getOperatorInfo().getInputType().createSerializer(executionConfig);
		TypeSerializer<OUT> outSerializer = getOperatorInfo().getOutputType().createSerializer(executionConfig);

		CopyingIterator<IN> source = new CopyingIterator<IN>(inputData.iterator(), inSerializer);
		CopyingListCollector<OUT> resultCollector = new CopyingListCollector<OUT>(result, outSerializer);

		function.mapPartition(source, resultCollector);

		result.trimToSize();
		FunctionUtils.closeFunction(function);
		return result;
	}
746723
private void processCollectionStore() {
        String fieldClassName = getDottedClassConstantOperand();
        if (fieldClassName.equals(className) && (stack.getStackDepth() > 0)) {
            OpcodeStack.Item item = stack.getStackItem(0);
            if (item.getUserValue() != null) {
                String fieldName = getNameConstantOperand();
                if (fieldName != null) {
                    FieldInfo fi = collectionFields.get(fieldName);
                    if (fi != null) {
                        fi.getFieldAnnotation().setSourceLines(SourceLineAnnotation.fromVisitedInstruction(this));
                        fi.setSynchronized();
                    }
                }
            }
        }
    }
1248075
function() {

		var old_uid = this._data_uids.pop(),
			old_value = this._data_values.pop(),
			old_name = this._data_names.pop(),
			count = this._count - 1;

		this._setLength(count);

		this._fire('items_removed', {
			uids: [old_uid],
			values: [old_value],
			names: [old_name]
		});

		this._fire('collection_changed');

		return old_value;
	}