Used to merge a reservoir sample into varopt, assuming the reservoir was built with items
of weight 1.0. Logic is very similar to mergeInto() for a sketch with no heavy items.
@param reservoir Reservoir sketch to merge into this union
184012
private void mergeReservoirInto(final ReservoirItemsSketch<T> reservoir) {
    final long reservoirN = reservoir.getN();
    if (reservoirN == 0) {
      return;
    }

    n_ += reservoirN;

    final int reservoirK = reservoir.getK();
    if (reservoir.getN() <= reservoirK) {
      // exact mode, so just insert and be done
      for (T item : reservoir.getRawSamplesAsList()) {
        gadget_.update(item, 1.0, false);
      }
    } else {
      // sampling mode. We'll replicate a weight-correcting iterator
      final double reservoirTau = reservoir.getImplicitSampleWeight();

      double cumWeight = 0.0;
      final ArrayList<T> samples = reservoir.getRawSamplesAsList();
      for (int i = 0; i < (reservoirK - 1); ++i) {
        gadget_.update(samples.get(i), reservoirTau, true);
        cumWeight += reservoirTau;
      }
      // correct for any numerical discrepancies with the last item
      gadget_.update(samples.get(reservoirK - 1), reservoir.getN() - cumWeight, true);

      // resolve tau
      final double outerTau = getOuterTau();

      if (outerTauDenom == 0) {
        // detect first estimation mode sketch and grab its tau
        outerTauNumer = reservoirN;
        outerTauDenom = reservoirK;
      } else if (reservoirTau > outerTau) {
        // switch to a bigger value of outerTau
        outerTauNumer = reservoirN;
        outerTauDenom = reservoirK;
      } else if (reservoirTau == outerTau) {
        // Ok if previous equality test isn't quite perfect. Mistakes in either direction should
        // be fairly benign.
        // Without conceptually changing outerTau, update number and denominator. In particular,
        // add the total weight of the incoming reservoir to the running total.
        outerTauNumer += reservoirN;
        outerTauDenom += reservoirK;
      }
      // do nothing if reservoir "tau" is no smaller than outerTau
    }
  }
473419
protected void mergeTemplate (Template template, InvocationContext context)
        throws ResourceNotFoundException, ParseErrorException, MethodInvocationException,
               UnsupportedEncodingException, IOException, Exception
    {
        HttpServletResponse response = context.getResponse();
        ServletOutputStream output = response.getOutputStream();
        // ASSUMPTION: response.setContentType() has been called.
        String encoding = response.getCharacterEncoding();

        VelocityWriter vw = null;
        try {
            vw = (VelocityWriter)_writerPool.get();
            if (vw == null) {
                vw = new VelocityWriter(new OutputStreamWriter(output, encoding), 4 * 1024, true);
            } else {
                vw.recycle(new OutputStreamWriter(output, encoding));
            }
            template.merge(context, vw);

        } catch (IOException ioe) {
            // the client probably crashed or aborted the connection ungracefully, so use log.info
            log.info("Failed to write response", "uri", context.getRequest().getRequestURI(),
                     "error", ioe);

        } finally {
            if (vw != null) {
                try {
                    // flush and put back into the pool don't close to allow us to play nicely with
                    // others.
                    vw.flush();
                } catch (IOException e) {
                    // do nothing
                }

                // Clear the VelocityWriter's reference to its internal OutputStreamWriter to allow
                // the latter to be GC'd while vw is pooled.
                vw.recycle(null);
                _writerPool.put(vw);
            }
        }
    }
890720
public void mergeFrom(MapFieldLite<K, V> other) {
        ensureMutable();
        if (!other.isEmpty()) {
            putAll(other);
        }
    }
736414
private Optional<IQ> mergeDefinitions(Collection<IQ> predicateDefinitions,
                                          Optional<ImmutableQueryModifiers> optionalTopModifiers) {
        if (predicateDefinitions.isEmpty())
            return Optional.empty();

        IQ firstDefinition = predicateDefinitions.iterator().next();
        if (predicateDefinitions.size() == 1) {
            return Optional.of(firstDefinition);
        }

        DistinctVariableOnlyDataAtom projectionAtom = firstDefinition.getProjectionAtom();

        VariableGenerator variableGenerator =  coreUtilsFactory.createVariableGenerator(firstDefinition.getTree().getKnownVariables());

        Stream<IQTree> renamedDefinitions = predicateDefinitions.stream()
                .skip(1)
                .map(def -> {
                    // Updates the variable generator
                    InjectiveVar2VarSubstitution disjointVariableSetRenaming = substitutionFactory.generateNotConflictingRenaming(
                            variableGenerator, def.getTree().getKnownVariables());

                    ImmutableSet<Variable> freshVariables = ImmutableSet.copyOf(
                            disjointVariableSetRenaming.getImmutableMap().values());

                    InjectiveVar2VarSubstitution headSubstitution = computeRenamingSubstitution(
                            disjointVariableSetRenaming.applyToDistinctVariableOnlyDataAtom(def.getProjectionAtom()),
                            projectionAtom)
                            .orElseThrow(() -> new IllegalStateException("Bug: unexpected incompatible atoms"));

                    InjectiveVar2VarSubstitution renamingSubstitution =
                            /*
                              fresh variables are excluded from the domain of the renaming substitution
                               since they are in use in the sub-query.

                               NB: this guarantees that the renaming substitution is injective
                             */
                            headSubstitution.composeWithAndPreserveInjectivity(disjointVariableSetRenaming, freshVariables)
                                    .orElseThrow(() -> new IllegalStateException("Bug: the renaming substitution is not injective"));

                    QueryRenamer queryRenamer = transformerFactory.createRenamer(renamingSubstitution);
                    return queryRenamer.transform(def).getTree();
                });

        ImmutableList<IQTree> unionChildren = Stream.concat(Stream.of(firstDefinition.getTree()), renamedDefinitions)
                .collect(ImmutableCollectors.toList());

        IQTree unionTree = iqFactory.createNaryIQTree(iqFactory.createUnionNode(projectionAtom.getVariables()),
                unionChildren);

        IQTree tree = optionalTopModifiers
                .map(m -> m.insertAbove(unionTree, iqFactory))
                .orElse(unionTree);

        return Optional.of(iqFactory.createIQ(projectionAtom, tree));
    }
428066
public static SetAclContext mergeFrom(SetAclPOptions.Builder optionsBuilder) {
    SetAclPOptions masterOptions = FileSystemOptions.setAclDefaults(ServerConfiguration.global());
    SetAclPOptions.Builder mergedOptionsBuilder =
        masterOptions.toBuilder().mergeFrom(optionsBuilder.build());
    return create(mergedOptionsBuilder);
  }
823211
public BuildableType.Builder mergeFrom(BuildableType.Builder template) {
    // Upcast to access private fields; otherwise, oddly, we get an access violation.
    BuildableType_Builder base = template;
    BuildableType_Builder defaults = new BuildableType.Builder();
    if (!base._unsetProperties.contains(Property.TYPE)
        && (defaults._unsetProperties.contains(Property.TYPE)
            || !Objects.equals(template.type(), defaults.type()))) {
      type(template.type());
    }
    if (!base._unsetProperties.contains(Property.BUILDER_TYPE)
        && (defaults._unsetProperties.contains(Property.BUILDER_TYPE)
            || !Objects.equals(template.builderType(), defaults.builderType()))) {
      builderType(template.builderType());
    }
    if (!base._unsetProperties.contains(Property.MERGE_BUILDER)
        && (defaults._unsetProperties.contains(Property.MERGE_BUILDER)
            || !Objects.equals(template.mergeBuilder(), defaults.mergeBuilder()))) {
      mergeBuilder(template.mergeBuilder());
    }
    if (!base._unsetProperties.contains(Property.PARTIAL_TO_BUILDER)
        && (defaults._unsetProperties.contains(Property.PARTIAL_TO_BUILDER)
            || !Objects.equals(template.partialToBuilder(), defaults.partialToBuilder()))) {
      partialToBuilder(template.partialToBuilder());
    }
    if (!base._unsetProperties.contains(Property.BUILDER_FACTORY)
        && (defaults._unsetProperties.contains(Property.BUILDER_FACTORY)
            || !Objects.equals(template.builderFactory(), defaults.builderFactory()))) {
      builderFactory(template.builderFactory());
    }
    if (!base._unsetProperties.contains(Property.SUPPRESS_UNCHECKED)
        && (defaults._unsetProperties.contains(Property.SUPPRESS_UNCHECKED)
            || !Objects.equals(template.suppressUnchecked(), defaults.suppressUnchecked()))) {
      suppressUnchecked(template.suppressUnchecked());
    }
    return (BuildableType.Builder) this;
  }
928281
public final ConfigurationModuleBuilder merge(final ConfigurationModule d) {
    if (d == null) {
      throw new NullPointerException("If merge() was passed a static final field that is initialized to non-null, " +
          "then this is almost certainly caused by a circular class dependency.");
    }
    try {
      d.assertStaticClean();
    } catch (final ClassHierarchyException e) {
      throw new ClassHierarchyException(ReflectionUtilities.getFullName(getClass()) +
          ": detected attempt to merge with ConfigurationModule that has had set() called on it", e);
    }
    final ConfigurationModuleBuilder c = deepCopy();
    final ConfigurationModuleBuilder builder = d.getBuilder();
    try {
      c.b.addConfiguration(builder.b.build());
    } catch (final BindException e) {
      throw new ClassHierarchyException(e);
    }
    c.reqDecl.addAll(builder.reqDecl);
    c.optDecl.addAll(builder.optDecl);
    c.reqUsed.addAll(builder.reqUsed);
    c.optUsed.addAll(builder.optUsed);
    c.setOpts.addAll(builder.setOpts);
    c.map.putAll(builder.map);
    c.freeImpls.putAll(builder.freeImpls);
    c.freeParams.putAll(builder.freeParams);
    c.lateBindClazz.putAll(builder.lateBindClazz);

    return c;
  }
334132
public static FreeContext mergeFrom(FreePOptions.Builder optionsBuilder) {
    FreePOptions masterOptions = FileSystemOptions.freeDefaults(ServerConfiguration.global());
    FreePOptions.Builder mergedOptionsBuilder =
        masterOptions.toBuilder().mergeFrom(optionsBuilder.build());
    return create(mergedOptionsBuilder);
  }
660306
public static void merge(Readable input,
                             ExtensionRegistry extensionRegistry,
                             Message.Builder builder) throws ParseException, IOException {
        // Read the entire input to a String then parse that.

        // If StreamTokenizer were not quite so crippled, or if there were a kind
        // of Reader that could read in chunks that match some particular regex,
        // or if we wanted to write a custom Reader to tokenize our stream, then
        // we would not have to read to one big String. Alas, none of these is
        // the case. Oh well.

        merge(toStringBuilder(input), extensionRegistry, builder);
    }
1047219
protected void mergeInto(FrameType other, FrameType result) throws DataflowAnalysisException {
        // Handle if result Frame or the other Frame is the special "TOP" value.
        if (result.isTop()) {
            // Result is the identity element, so copy the other Frame
            result.copyFrom(other);
            return;
        } else if (other.isTop()) {
            // Other Frame is the identity element, so result stays the same
            return;
        }

        // Handle if result Frame or the other Frame is the special "BOTTOM"
        // value.
        if (result.isBottom()) {
            // Result is the bottom element, so it stays that way
            return;
        } else if (other.isBottom()) {
            // Other Frame is the bottom element, so result becomes the bottom
            // element too
            result.setBottom();
            return;
        }

        // If the number of slots in the Frames differs,
        // then the result is the special "BOTTOM" value.
        if (result.getNumSlots() != other.getNumSlots()) {
            result.setBottom();
            return;
        }

        // Usual case: ordinary Frames consisting of the same number of values.
        // Merge each value in the two slot lists element-wise.
        for (int i = 0; i < result.getNumSlots(); ++i) {
            mergeValues(other, result, i);
        }
    }
1058872
public void update(final ReservoirItemsSketch<T> sketchIn) {
    if (sketchIn == null) {
      return;
    }

    final ReservoirItemsSketch<T> ris =
        (sketchIn.getK() <= maxK_ ? sketchIn : sketchIn.downsampledCopy(maxK_));

    // can modify the sketch if we downsampled, otherwise may need to copy it
    final boolean isModifiable = (sketchIn != ris);
    if (gadget_ == null) {
      createNewGadget(ris, isModifiable);
    } else {
      twoWayMergeInternal(ris, isModifiable);
    }
  }
618287
private void mergeInto(RootListNode<K, V> head, RootListNode<K, V> tail) {
        // if root list empty, just copy
        if (rootList.head == null) {
            rootList.head = head;
            rootList.tail = tail;
            return;
        }

        // initialize
        RootListNode<K, V> resultHead;
        RootListNode<K, V> resultTail;
        RootListNode<K, V> resultTailPrev = null;
        RootListNode<K, V> cur1 = rootList.head;
        RootListNode<K, V> cur2 = head;

        // add first node
        if (cur1.root.rank <= cur2.root.rank) {
            resultHead = cur1;
            resultTail = cur1;
            RootListNode<K, V> cur1next = cur1.next;
            cur1.next = null;
            cur1 = cur1next;
            if (cur1next != null) {
                cur1next.prev = null;
            }
        } else {
            resultHead = cur2;
            resultTail = cur2;
            RootListNode<K, V> cur2next = cur2.next;
            cur2.next = null;
            cur2 = cur2next;
            if (cur2next != null) {
                cur2next.prev = null;
            }
        }

        // merge
        int rank1, rank2;
        while (true) {
            int resultRank = resultTail.root.rank;

            // read rank1
            if (cur1 != null) {
                rank1 = cur1.root.rank;
            } else {
                if (cur2 != null && cur2.root.rank <= resultRank) {
                    rank1 = Integer.MAX_VALUE;
                } else {
                    break;
                }
            }

            // read rank2
            if (cur2 != null) {
                rank2 = cur2.root.rank;
            } else {
                if (cur1 != null && cur1.root.rank <= resultRank) {
                    rank2 = Integer.MAX_VALUE;
                } else {
                    break;
                }
            }

            if (rank1 <= rank2) {
                switch (Integer.compare(rank1, resultRank)) {
                case 0:
                    // combine into result
                    resultTail.root = combine(cur1.root, resultTail.root);
                    resultTail.root.parent = resultTail;
                    // remove cur1
                    RootListNode<K, V> cur1next = cur1.next;
                    cur1.next = null;
                    if (cur1next != null) {
                        cur1next.prev = null;
                    }
                    cur1 = cur1next;
                    break;
                case -1:
                    // can happen if three same ranks
                    cur1next = cur1.next;
                    // add before tail into result
                    cur1.next = resultTail;
                    resultTail.prev = cur1;
                    cur1.prev = resultTailPrev;
                    if (resultTailPrev != null) {
                        resultTailPrev.next = cur1;
                    } else {
                        resultHead = cur1;
                    }
                    resultTailPrev = cur1;
                    // advance cur1
                    if (cur1next != null) {
                        cur1next.prev = null;
                    }
                    cur1 = cur1next;
                    break;
                case 1:
                    // append into result
                    resultTail.next = cur1;
                    cur1.prev = resultTail;
                    resultTailPrev = resultTail;
                    resultTail = cur1;
                    // remove cur1
                    cur1 = cur1.next;
                    resultTail.next = null;
                    if (cur1 != null) {
                        cur1.prev = null;
                    }
                    break;
                }
            } else {
                // symmetric case rank2 < rank1
                switch (Integer.compare(rank2, resultRank)) {
                case 0:
                    // combine into result
                    resultTail.root = combine(cur2.root, resultTail.root);
                    resultTail.root.parent = resultTail;
                    // remove cur2
                    RootListNode<K, V> cur2next = cur2.next;
                    cur2.next = null;
                    if (cur2next != null) {
                        cur2next.prev = null;
                    }
                    cur2 = cur2next;
                    break;
                case -1:
                    // can happen if three same ranks
                    cur2next = cur2.next;
                    // add before tail into result
                    cur2.next = resultTail;
                    resultTail.prev = cur2;
                    cur2.prev = resultTailPrev;
                    if (resultTailPrev != null) {
                        resultTailPrev.next = cur2;
                    } else {
                        resultHead = cur2;
                    }
                    resultTailPrev = cur2;
                    // advance cur2
                    if (cur2next != null) {
                        cur2next.prev = null;
                    }
                    cur2 = cur2next;
                    break;
                case 1:
                    // append into result
                    resultTail.next = cur2;
                    cur2.prev = resultTail;
                    resultTailPrev = resultTail;
                    resultTail = cur2;
                    // remove cur2
                    cur2 = cur2.next;
                    resultTail.next = null;
                    if (cur2 != null) {
                        cur2.prev = null;
                    }
                    break;
                }
            }
        }

        // record up to which point a suffix minimum update is needed
        RootListNode<K, V> updateSuffixFix = resultTail;

        // here rank of cur1 is more than result rank
        if (cur1 != null) {
            cur1.prev = resultTail;
            resultTail.next = cur1;
            resultTail = rootList.tail;
        }

        // here rank of cur2 is more than result rank
        if (cur2 != null) {
            cur2.prev = resultTail;
            resultTail.next = cur2;
            resultTail = tail;
        }

        // update suffix minimum
        updateSuffixMin(updateSuffixFix);

        // store final list
        rootList.head = resultHead;
        rootList.tail = resultTail;
    }
360177
static void mergeInto(List<Path> parts, OutputStream out)
      throws IOException {
    for (final Path part : parts) {
      Files.copy(part, out);
      Files.delete(part);
    }
  }
1358398
private void twoWayMergeInternalWeighted(final ReservoirLongsSketch source) {
    // gadget_ capable of accepting (light) general weights
    assert (gadget_.getN() >= gadget_.getK());

    final int numSourceSamples = source.getK();

    final double sourceItemWeight = (source.getN() / (double) numSourceSamples);
    final double rescaled_prob = gadget_.getK() * sourceItemWeight; // K * weight
    double targetTotal = gadget_.getN(); // assumes fractional values during merge

    final int tgtK = gadget_.getK();

    for (int i = 0; i < numSourceSamples; ++i) {
      // inlining the update procedure, using targetTotal for the fractional N values
      // similar to ReservoirLongsSketch.update()
      // p(keep_new_item) = (k * w) / newTotal
      // require p(keep_new_item) < 1.0, meaning strict lightness

      targetTotal += sourceItemWeight;

      final double rescaled_one = targetTotal;
      assert (rescaled_prob < rescaled_one); // Use an exception to enforce strict lightness?
      final double rescaled_flip = rescaled_one * SamplingUtil.rand.nextDouble();
      if (rescaled_flip < rescaled_prob) {
        // Intentionally NOT doing optimization to extract slot number from rescaled_flip.
        // Grabbing new random bits to ensure all slots in play
        final int slotNo = SamplingUtil.rand.nextInt(tgtK);
        gadget_.insertValueAtPosition(source.getValueAtPosition(i), slotNo);
      } // end of inlined weight update
    } // end of loop over source samples


    // targetTotal was fractional but should now be an integer again. Could validate with
    // low tolerance, but for now just round to check.
    final long checkN = (long) Math.floor(0.5 + targetTotal);
    gadget_.forceIncrementItemsSeen(source.getN());
    assert (checkN == gadget_.getN());
  }
1105685
@SuppressWarnings("unchecked")
	public void merge(Parameter<?> parameter)
	{
		if (parameter.getValue() != null)
			value = (T) parameter.getValue();
	}
1197419
@Override
  public void merge(MtasDataCollector<?, ?> newDataCollector,
      Map<MtasDataCollector<?, ?>, MtasDataCollector<?, ?>> map,
      boolean increaseSourceNumber) throws IOException {
    closeNewList();
    if (!collectorType.equals(newDataCollector.getCollectorType())
        || !dataType.equals(newDataCollector.getDataType())
        || !statsType.equals(newDataCollector.getStatsType())
        || !(newDataCollector instanceof MtasDataBasic)) {
      throw new IOException("cannot merge different dataCollectors");
    } else {
      segmentRegistration = null;
      @SuppressWarnings("unchecked")
      MtasDataBasic<T1, T2> newMtasDataBasic = (MtasDataBasic<T1, T2>) newDataCollector;
      newMtasDataBasic.closeNewList();
      initNewList(newMtasDataBasic.getSize());
      if (collectorType.equals(DataCollector.COLLECTOR_TYPE_LIST)) {
        map.put(newDataCollector, this);
        for (int i = 0; i < newMtasDataBasic.getSize(); i++) {
          MtasDataCollector<?, ?>[] subCollectors = new MtasDataCollector[1];
          subCollectors[0] = add(newMtasDataBasic.keyList[i],
              increaseSourceNumber);
          setError(newCurrentPosition, newMtasDataBasic.errorNumber[i],
              newMtasDataBasic.errorList[i], newCurrentExisting);
          setValue(newCurrentPosition, newMtasDataBasic.basicValueSumList[i],
              newMtasDataBasic.basicValueNList[i], newCurrentExisting);
          if (hasSub() && newMtasDataBasic.hasSub()) {
            // single key implies exactly one subCollector if hasSub
            subCollectors[0].merge(
                newMtasDataBasic.subCollectorListNextLevel[i], map,
                increaseSourceNumber);
          }
        }
        closeNewList();
      } else if (collectorType.equals(DataCollector.COLLECTOR_TYPE_DATA)) {
        map.put(newDataCollector, this);
        if (newMtasDataBasic.getSize() > 0) {
          MtasDataCollector<?, ?> subCollector = add(increaseSourceNumber);
          setError(newCurrentPosition, newMtasDataBasic.errorNumber[0],
              newMtasDataBasic.errorList[0], newCurrentExisting);
          setValue(newCurrentPosition, newMtasDataBasic.basicValueSumList[0],
              newMtasDataBasic.basicValueNList[0], newCurrentExisting);
          if (hasSub() && newMtasDataBasic.hasSub()) {
            subCollector.merge(newMtasDataBasic.subCollectorNextLevel, map,
                increaseSourceNumber);
          }
        }
        closeNewList();
      } else {
        throw new IOException("cannot merge " + collectorType);
      }
    }
  }
455761
public TypeUsage.Builder mergeFrom(TypeUsage value) {
    TypeUsage_Builder defaults = new TypeUsage.Builder();
    if (defaults._unsetProperties.contains(Property.START) || value.start() != defaults.start()) {
      start(value.start());
    }
    if (defaults._unsetProperties.contains(Property.END) || value.end() != defaults.end()) {
      end(value.end());
    }
    if (defaults._unsetProperties.contains(Property.TYPE)
        || !Objects.equals(value.type(), defaults.type())) {
      type(value.type());
    }
    value.scope().ifPresent(this::scope);
    return (TypeUsage.Builder) this;
  }