When cloning this entity, we must also clone all entities in the ArrayCollection
510389
public function deepClone()
    {
        $items = $this->getItems();
        $this->items = new ArrayCollection();
        foreach ($items as $item) {
            $cloneItem = clone $item;
            $this->addItem($cloneItem);
        }
    }
58148
function copy( $collectionItemID )
    {
        $item = clone $this;
        $item->setAttribute( 'item_id', $collectionItemID );
        $item->store();
        return $item;
    }
642703
private void populateCollectionFromJoinTable(Object entity, EntityMetadata entityMetadata,
            PersistenceDelegator delegator, Relation relation)
    {
        JoinTableMetadata jtMetadata = relation.getJoinTableMetadata();
        Client pClient = delegator.getClient(entityMetadata);

        String schema = entityMetadata.getSchema();

        EntityMetadata owningEntityMetadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(),
                relation.getTargetEntity());
        Class columnJavaType = owningEntityMetadata.getIdAttribute().getJavaType();
        if (jtMetadata == null)
        {
            columnJavaType = entityMetadata.getIdAttribute().getJavaType();
            Relation owningEntityMetadataRelation = owningEntityMetadata.getRelation(relation.getMappedBy());
            jtMetadata = owningEntityMetadataRelation.getJoinTableMetadata();
            pClient = delegator.getClient(owningEntityMetadata);
            schema = owningEntityMetadata.getSchema();
        }

        String joinTableName = jtMetadata.getJoinTableName();

        Set<String> joinColumns = jtMetadata.getJoinColumns();
        Set<String> inverseJoinColumns = jtMetadata.getInverseJoinColumns();

        String joinColumnName = (String) joinColumns.toArray()[0];
        String inverseJoinColumnName = (String) inverseJoinColumns.toArray()[0];

        Object entityId = PropertyAccessorHelper.getId(entity, entityMetadata);
        List<?> foreignKeys = pClient.getColumnsById(schema, joinTableName, joinColumnName, inverseJoinColumnName,
                entityId, columnJavaType);

        List childrenEntities = new ArrayList();

        if (foreignKeys != null)
        {
            for (Object foreignKey : foreignKeys)
            {
                EntityMetadata childMetadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(),
                        relation.getTargetEntity());

                Object child = delegator.find(relation.getTargetEntity(), foreignKey);
                Object obj = child instanceof EnhanceEntity && child != null ? ((EnhanceEntity) child).getEntity()
                        : child;

                // If child has any bidirectional relationship, process them
                // here
                Field biDirectionalField = relation.getBiDirectionalField();
                boolean isBidirectionalRelation = (biDirectionalField != null);

                if (isBidirectionalRelation && obj != null)
                {
                    Object columnValue = PropertyAccessorHelper.getId(obj, childMetadata);
                    Object[] pKeys = pClient.findIdsByColumn(entityMetadata.getSchema(), joinTableName, joinColumnName,
                            inverseJoinColumnName, columnValue, entityMetadata.getEntityClazz());
                    List parents = delegator.find(entity.getClass(), pKeys);
                    PropertyAccessorHelper.set(obj, biDirectionalField,
                            ObjectUtils.getFieldInstance(parents, biDirectionalField));
                    PersistenceCacheManager.addEntityToPersistenceCache(obj, delegator, columnValue);
                }

                childrenEntities.add(obj);
            }
        }
        Field childField = relation.getProperty();

        try
        {
            PropertyAccessorHelper.set(
                    entity,
                    childField,
                    PropertyAccessorHelper.isCollection(childField.getType()) ? ObjectUtils.getFieldInstance(
                            childrenEntities, childField) : childrenEntities.get(0));
            PersistenceCacheManager.addEntityToPersistenceCache(entity, delegator, entityId);
        }
        catch (PropertyAccessException ex)
        {
            throw new EntityReaderException(ex);
        }
    }
552723
@Override
    public void putAll(Map<? extends K, ? extends V> in) {
        if (fast) {
            synchronized (this) {
                Map<K, V> temp = cloneMap(map);
                temp.putAll(in);
                map = temp;
            }
        } else {
            synchronized (map) {
                map.putAll(in);
            }
        }
    }
420727
static MemberMap cloneAdding(MemberMap source, MemberImpl... newMembers) {
        Map<Address, MemberImpl> addressMap = new LinkedHashMap<>(source.addressToMemberMap);
        Map<String, MemberImpl> uuidMap = new LinkedHashMap<>(source.uuidToMemberMap);

        for (MemberImpl member : newMembers) {
            putMember(addressMap, uuidMap, member);
        }

        return new MemberMap(source.version + newMembers.length, addressMap, uuidMap);
    }
429169
public static <T> CopyOnWriteArrayList<T> newCopyOnWriteArrayList(Collection<T> collection) {
		return (null == collection) ? (new CopyOnWriteArrayList<T>()) : (new CopyOnWriteArrayList<T>(collection));
	}
15213
private function fillFromCollection(
        ParameterDefinitionCollectionInterface $definitionCollection,
        ParameterCollectionInterface $parameters
    ): void {
        foreach ($definitionCollection->getParameterDefinitions() as $name => $definition) {
            $value = null;

            if ($parameters->hasParameter($name)) {
                $parameter = $parameters->getParameter($name);
                if ($parameter->getParameterDefinition()->getType()::getIdentifier() === $definition->getType()::getIdentifier()) {
                    $value = $parameter->getValue();
                    $value = is_object($value) ? clone $value : $value;
                }
            }

            $this->setParameterValue($name, $value);

            if ($definition instanceof CompoundParameterDefinition) {
                $this->fillFromCollection($definition, $parameters);
            }
        }
    }
956965
function(done) {
      var ret = this._data.concat([]); // make a shallow copy
      for(var i = 0; i < ret.length; i++) {
        ret[i] = this._clone(ret[i]);
      }
      done(null, ret);
    }
320661
function cloner(deep, item) {
  if (!item ||
      typeof item !== 'object' ||
      item instanceof Error ||
      item instanceof MonkeyDefinition ||
      item instanceof Monkey ||
      ('ArrayBuffer' in global && item instanceof ArrayBuffer))
    return item;

  // Array
  if (type.array(item)) {
    if (deep) {
      const a = new Array(item.length);

      for (let i = 0, l = item.length; i < l; i++)
        a[i] = cloner(true, item[i]);
      return a;
    }

    return slice(item);
  }

  // Date
  if (item instanceof Date)
    return new Date(item.getTime());

  // RegExp
  if (item instanceof RegExp)
    return cloneRegexp(item);

  // Object
  if (type.object(item)) {
    const o = {};

    // NOTE: could be possible to erase computed properties through `null`.
    const props = Object.getOwnPropertyNames(item);
    for (let i = 0, l = props.length; i < l; i++) {
      const name = props[i];
      const k = Object.getOwnPropertyDescriptor(item, name);
      if (k.enumerable === true) {
        if (k.get && k.get.isLazyGetter) {
          Object.defineProperty(o, name, {
            get: k.get,
            enumerable: true,
            configurable: true
          });
        }
        else {
          o[name] = deep ? cloner(true, item[name]) : item[name];
        }
      }
      else if (k.enumerable === false) {
        Object.defineProperty(o, name, {
          value: deep ? cloner(true, k.value) : k.value,
          enumerable: false,
          writable: true,
          configurable: true
        });
      }
    }
    return o;
  }

  return item;
}
655724
private void cloneAndSortMappings(IReaction reaction, IReaction copyOfReaction,
            Map<IAtomContainer, int[]> permutationMap) {

        // make a lookup for the indices of the atoms in the copy
        final Map<IChemObject, Integer> indexMap = new HashMap<IChemObject, Integer>();
        List<IAtomContainer> all = ReactionManipulator.getAllAtomContainers(copyOfReaction);
        int globalIndex = 0;
        for (IAtomContainer ac : all) {
            for (IAtom atom : ac.atoms()) {
                indexMap.put(atom, globalIndex);
                globalIndex++;
            }
        }

        Map<IAtom, IAtom> atomAtomMap = atomAtomMap(reaction, copyOfReaction, permutationMap);
        List<IMapping> map = cloneMappings(reaction, atomAtomMap);

        Comparator<IMapping> mappingSorter = new Comparator<IMapping>() {

            /**
             * {@inheritDoc}
             */
            @Override
            public int compare(IMapping o1, IMapping o2) {
                IChemObject o10 = o1.getChemObject(0);
                IChemObject o20 = o2.getChemObject(0);
                return indexMap.get(o10).compareTo(indexMap.get(o20));
            }

        };
        Collections.sort(map, mappingSorter);
        int mappingIndex = 0;
        for (IMapping mapping : map) {
            mapping.getChemObject(0).setProperty(CDKConstants.ATOM_ATOM_MAPPING, mappingIndex);
            mapping.getChemObject(1).setProperty(CDKConstants.ATOM_ATOM_MAPPING, mappingIndex);
            copyOfReaction.addMapping(mapping);
            mappingIndex++;
        }

    }
98992
public TokenMetadata cloneAfterAllLeft()
    {
        lock.readLock().lock();
        try
        {
            TokenMetadata allLeftMetadata = cloneOnlyTokenMap();

            for (InetAddress endpoint : leavingEndpoints)
                allLeftMetadata.removeEndpoint(endpoint);

            return allLeftMetadata;
        }
        finally
        {
            lock.readLock().unlock();
        }
    }
978217
@Override
	public boolean retainAll(Collection<?> collection) {
		if (dao == null) {
			return false;
		}
		boolean changed = false;
		CloseableIterator<T> iterator = closeableIterator();
		try {
			while (iterator.hasNext()) {
				T data = iterator.next();
				if (!collection.contains(data)) {
					iterator.remove();
					changed = true;
				}
			}
			return changed;
		} finally {
			IOUtils.closeQuietly(iterator);
		}
	}
541334
public EntityMakerBuilder reuseEntities(Collection<Object> entities) {
        for (Object entity : entities) {
            Class aClass = entity.getClass();
            valueHolder.putIfNotNull(aClass, entity);
        }
        return this;
    }
389300
@Override
	public AbstractMessage copy()
    {
        ObjectMessageImpl clone = new ObjectMessageImpl();
        copyCommonFields(clone);
        clone.body = this.body;
        
        return clone;
    }
878009
private void storeCollections(Object obj, ClassDescriptor cld, boolean insert) throws PersistenceBrokerException
    {
        // get all members of obj that are collections and store all their elements
        Collection listCods = cld.getCollectionDescriptors();
        // return if nothing to do
        if (listCods.size() == 0)
        {
            return;
        }
        Iterator i = listCods.iterator();
        while (i.hasNext())
        {
            CollectionDescriptor cod = (CollectionDescriptor) i.next();

            // if CASCADE_NONE was set, do nothing with referenced objects
            if (cod.getCascadingStore() != ObjectReferenceDescriptor.CASCADE_NONE)
            {
                Object referencedObjects = cod.getPersistentField().get(obj);
                if (cod.isMtoNRelation())
                {
                    storeAndLinkMtoN(false, obj, cod, referencedObjects, insert);
                }
                else
                {
                    storeAndLinkOneToMany(false, obj, cod, referencedObjects, insert);
                }

                // BRJ: only when auto-update = object (CASCADE_OBJECT)
                //
                if ((cod.getCascadingStore() == ObjectReferenceDescriptor.CASCADE_OBJECT)
                        && (referencedObjects instanceof ManageableCollection))
                {
                    ((ManageableCollection) referencedObjects).afterStore(this);
                }
            }
        }
    }
1170172
public function _clone()
    {
        $qb = $this->query->deepClone();

        $kwargs = array_merge(['resultMapper' => $this->resultMapper], $this->kwargs);

        $queryset = self::createObject($this->connection, $this->model, $qb, $kwargs);
//        $queryset->_resultsCache = $this->_resultsCache;
        $queryset->prefetchRelatedLookups = $this->prefetchRelatedLookups;

        return $queryset;
    }
816780
def duplicate(self, contributor=None, inherit_collections=False):
        """"""
        duplicate = Entity.objects.get(id=self.id)
        duplicate.pk = None
        duplicate.slug = None
        duplicate.name = 'Copy of {}'.format(self.name)
        duplicate.duplicated = now()
        if contributor:
            duplicate.contributor = contributor

        duplicate.save(force_insert=True)

        assign_contributor_permissions(duplicate)

        # Override fields that are automatically set on create.
        duplicate.created = self.created
        duplicate.save()

        # Duplicate entity's data objects.
        data = get_objects_for_user(contributor, 'view_data', self.data.all())  # pylint: disable=no-member
        duplicated_data = data.duplicate(contributor)
        duplicate.data.add(*duplicated_data)

        if inherit_collections:
            collections = get_objects_for_user(
                contributor,
                'add_collection',
                self.collections.all()  # pylint: disable=no-member
            )
            for collection in collections:
                collection.entity_set.add(duplicate)
                copy_permissions(collection, duplicate)
                collection.data.add(*duplicated_data)
                for datum in duplicated_data:
                    copy_permissions(collection, datum)

        return duplicate