Perform a merge of two callsets using SURVIVOR,
343156
def _survivor_merge(call_vcf, truth_vcf, stats, work_dir, data):
    
    out_file = os.path.join(work_dir, "eval-merge.vcf")
    if not utils.file_uptodate(out_file, call_vcf):
        in_call_vcf = call_vcf.replace(".vcf.gz", ".vcf")
        if not utils.file_exists(in_call_vcf):
            with file_transaction(data, in_call_vcf) as tx_in_call_vcf:
                do.run("gunzip -c {call_vcf} > {tx_in_call_vcf}".format(**locals()))
        in_truth_vcf = truth_vcf.replace(".vcf.gz", ".vcf")
        if not utils.file_exists(in_truth_vcf):
            with file_transaction(data, in_truth_vcf) as tx_in_truth_vcf:
                do.run("gunzip -c {truth_vcf} > {tx_in_truth_vcf}".format(**locals()))
        in_list_file = os.path.join(work_dir, "eval-inputs.txt")
        with open(in_list_file, "w") as out_handle:
            out_handle.write("%s\n%s\n" % (in_call_vcf, in_truth_vcf))
        with file_transaction(data, out_file) as tx_out_file:
            cmd = ("SURVIVOR merge {in_list_file} {stats[merge_size]} 1 0 0 0 {stats[min_size]} {tx_out_file}")
            do.run(cmd.format(**locals()), "Merge SV files for validation: %s" % dd.get_sample_name(data))
    return out_file
280517
def _merge_cdicts(self, clut, exdict, separator):
    """"""
    if not self._full_cname:
        return
    # Find all callables that are not in self exceptions dictionary
    # and create new tokens for them
    repl_dict = {}
    for key, value in _sorted_keys_items(clut):
        otoken = self._clut.get(key, None)
        if not otoken:
            otoken = str(len(self._clut))
            self._clut[key] = otoken
        repl_dict[value] = otoken
    # Update other dictionaries to the mapping to self
    # exceptions dictionary
    for fdict in exdict.values():
        for entry in fdict.values():
            olist = []
            for item in entry["function"]:
                if item is None:
                    # Callable name is None when callable is
                    # part of exclude list
                    olist.append(None)
                else:
                    itokens = item.split(separator)
                    itokens = [repl_dict.get(itoken) for itoken in itokens]
                    olist.append(separator.join(itokens))
            entry["function"] = olist
135307
public void mergeCalls(String connId, String otherConnId) throws WorkspaceApiException {
        this.mergeCalls(connId, otherConnId, null, null);
    }
61722
public ParameterTool mergeWith(ParameterTool other) {
		final Map<String, String> resultData = new HashMap<>(data.size() + other.data.size());
		resultData.putAll(data);
		resultData.putAll(other.data);

		final ParameterTool ret = new ParameterTool(resultData);

		final HashSet<String> requestedParametersLeft = new HashSet<>(data.keySet());
		requestedParametersLeft.removeAll(unrequestedParameters);

		final HashSet<String> requestedParametersRight = new HashSet<>(other.data.keySet());
		requestedParametersRight.removeAll(other.unrequestedParameters);

		ret.unrequestedParameters.removeAll(requestedParametersLeft);
		ret.unrequestedParameters.removeAll(requestedParametersRight);

		return ret;
	}
209165
@CheckReturnValue
	@VisibleForTesting
	ImmutableList<Server> mergeServerLists(List<Server> firstList, List<Server> secondList) {
		ImmutableList.Builder<Server> results = ImmutableList.builder();
		List<Server> toProcess = new ArrayList<>(secondList);
		for (Server firstServer : firstList) {
			if (toProcess.contains(firstServer)) {
				Server found = toProcess.get(secondList.indexOf(firstServer));
				results.add(merge(firstServer, found));
				// remove server as it is already merged
				toProcess.remove(found);
			} else {
				results.add(firstServer);
			}
		}
		// add servers from the second list that are not in the first one
		results.addAll(toProcess);
		return results.build();
	}
189778
private void merge(ExecutionStatistics otherStatistics) {
        for (String s : otherStatistics.executionInfo.keySet())
        {
            TimingData thisStats = this.executionInfo.get(s);
            TimingData otherStats = otherStatistics.executionInfo.get(s);
            if(thisStats == null) {
                this.executionInfo.put(s,otherStats);
            } else {
                thisStats.merge(otherStats);
            }

        }
    }
818256
private void merge(Map<String, NodeT> source, Map<String, NodeT> target) {
        for (Map.Entry<String, NodeT> entry : source.entrySet()) {
            String key = entry.getKey();
            if (!target.containsKey(key)) {
                target.put(key, entry.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);
      }
    }
  }
512475
public void mutationMayCallWriter() {
    CacheWriter<K, V> _writer = writer();
    if (_writer == null) {
      skipWritingNoWriter();
      return;
    }
    if (remove) {
      try {
        entry.nextProcessingStep(WRITE);
        _writer.delete(key);
      } catch (Throwable t) {
        onWriteFailure(t);
        return;
      }
      onWriteSuccess();
      return;
    }
    if (newValueOrException instanceof ExceptionWrapper) {
      skipWritingForException();
      return;
    }
    entry.nextProcessingStep(WRITE);
    try {
      _writer.write(key, newValueOrException);
    } catch (Throwable t) {
      onWriteFailure(t);
      return;
    }
    onWriteSuccess();
  }
963097
public void merge(String parity, String source, String codecId, int[] checksums) 
    throws IOException {
    if(FSNamesystem.LOG.isDebugEnabled()) {
      FSNamesystem.LOG.debug("merge " + parity + " to " + source);
    }
    if (isInSafeMode()) {
      throw new SafeModeException("merge: cannot merge " + parity + " to " 
                                  + source, safeMode);
    }
    // Verify parity and source 
    if (source == null || source.isEmpty() || parity == null || parity.isEmpty()) {
      throw new IOException(
          "merge: source file name or parity file name is empty");
    }
    // Verify checksums
    if (checksums == null || checksums.length == 0) {
      throw new IOException("merge: checksum array is empty or null");
    }
    // Verify codec
    RaidCodec codec = RaidCodec.getCodec(codecId);
    if (codec == null) {
      throw new IOException("merge: codec " + codecId + " doesn't exist");
    }
    
    INode[] sourceINodes = dir.getExistingPathINodes(source);
    INode[] parityINodes = dir.getExistingPathINodes(parity);
    writeLock();
    try {
      // write permissions for the source
      if (isPermissionEnabled) {
        if (isPermissionCheckingEnabled(sourceINodes)) {
          checkPathAccess(source, sourceINodes, FsAction.WRITE); 
        }
        if (isPermissionCheckingEnabled(parityINodes)) {
          checkPathAccess(parity, parityINodes, FsAction.READ); // read the file
          checkParentAccess(parity, parityINodes, FsAction.WRITE); // for delete
        }
      }
      INode sinode = sourceINodes[sourceINodes.length - 1];
      INode pinode = parityINodes[parityINodes.length - 1];
      
      if (sinode == null || pinode == null) {
        throw new IOException(
            "merge: source file or parity file doesn't exist");
      }
      
      if (sinode.isUnderConstruction() || pinode.isUnderConstruction()) {
        throw new IOException(
            "merge: source file or parity file is under construction");
      }
      
      if (sinode.isDirectory() || pinode.isDirectory()) {
        throw new IOException(
            "merge: source file or parity file is a directory");
      }
      
      if (sinode instanceof INodeHardLinkFile ||
          pinode instanceof INodeHardLinkFile) { 
        throw new IOException("merge: source file or parity file is hardlinked");  
      }

      INodeFile sourceINode = (INodeFile) sinode;
      INodeFile parityINode = (INodeFile) pinode;

      if (sourceINode.getStorageType() != StorageType.REGULAR_STORAGE
          || parityINode.getStorageType() != StorageType.REGULAR_STORAGE) {
        throw new IOException(
            "merge: source file or parity file doesn't support merge");
      }
      if (sourceINode.getModificationTime() != parityINode.getModificationTime()) {
        throw new IOException(
            "merge: source file and parity file doesn't have the same modification time");
      }
      if (parityINode.getReplication() != codec.parityReplication) {
        throw new IOException(
            "merge: parity file's replication doesn't match codec's parity replication");
      }
      
      BlockInfo[] sourceBlks = sourceINode.getBlocks();
      BlockInfo[] parityBlks = parityINode.getBlocks();
      
      if (sourceBlks == null || sourceBlks.length == 0) {
        throw new IOException("merge: " + source + " is empty");
      }
      if (parityBlks == null || parityBlks.length == 0) {
        throw new IOException("merge: " + parity + " is empty");
      }
      if (checksums.length != sourceBlks.length) {
        throw new IOException("merge: checksum length " + checksums.length +
            " doesn't match number of source blocks " + sourceBlks.length);
      }
      int expectedParityBlocks = codec.getNumStripes(sourceBlks.length) 
          * codec.numParityBlocks;
      if (expectedParityBlocks != parityBlks.length) {
        throw new IOException("merge: expect parity blocks " + 
            expectedParityBlocks + " doesn't match number of parity blocks " + 
            parityBlks.length);
      }

      if(NameNode.stateChangeLog.isDebugEnabled()) {
        NameNode.stateChangeLog.debug("DIR* NameSystem.merge: " +
            parity + " to " + source);
      }
      
      dir.mergeInternal(parityINodes, sourceINodes, parity, source, codec,
                        checksums);
    } finally {
      writeUnlock();
    }
    getEditLog().logSync();

    if (auditLog.isInfoEnabled()) {
      logAuditEvent(getCurrentUGI(),
                    Server.getRemoteIp(),
                    "merge", parity, source, 
                    getLastINode(sourceINodes));
    }
  }
980200
def combine_calls(*args):
    
    if len(args) == 3:
        is_cwl = False
        batch_id, samples, data = args
        caller_names, vrn_files = _organize_variants(samples, batch_id)
    else:
        is_cwl = True
        samples = [utils.to_single_data(x) for x in args]
        samples = [cwlutils.unpack_tarballs(x, x) for x in samples]
        data = samples[0]
        batch_id = data["batch_id"]
        caller_names = data["variants"]["variantcallers"]
        vrn_files = data["variants"]["calls"]
    logger.info("Ensemble consensus calls for {0}: {1}".format(
        batch_id, ",".join(caller_names)))
    edata = copy.deepcopy(data)
    base_dir = utils.safe_makedir(os.path.join(edata["dirs"]["work"], "ensemble", batch_id))
    if any([vcfutils.vcf_has_variants(f) for f in vrn_files]):
        # Decompose multiallelic variants and normalize
        passonly = not tz.get_in(["config", "algorithm", "ensemble", "use_filtered"], edata, False)
        vrn_files = [normalize.normalize(f, data, passonly=passonly, rerun_effects=False, remove_oldeffects=True,
                                         nonrefonly=True,
                                         work_dir=utils.safe_makedir(os.path.join(base_dir, c)))
                     for c, f in zip(caller_names, vrn_files)]
        if "classifiers" not in (dd.get_ensemble(edata) or {}):
            callinfo = _run_ensemble_intersection(batch_id, vrn_files, caller_names, base_dir, edata)
        else:
            config_file = _write_config_file(batch_id, caller_names, base_dir, edata)
            callinfo = _run_ensemble(batch_id, vrn_files, config_file, base_dir,
                                     dd.get_ref_file(edata), edata)
            callinfo["vrn_file"] = vcfutils.bgzip_and_index(callinfo["vrn_file"], data["config"])
        # After decomposing multiallelic variants and normalizing, re-evaluate effects
        ann_ma_file, _ = effects.add_to_vcf(callinfo["vrn_file"], data)
        if ann_ma_file:
            callinfo["vrn_file"] = ann_ma_file

        edata["config"]["algorithm"]["variantcaller"] = "ensemble"
        edata["vrn_file"] = callinfo["vrn_file"]
        edata["ensemble_bed"] = callinfo["bed_file"]
        callinfo["validate"] = validate.compare_to_rm(edata)[0][0].get("validate")
    else:
        out_vcf_file = os.path.join(base_dir, "{0}-ensemble.vcf".format(batch_id))
        vcfutils.write_empty_vcf(out_vcf_file, samples=[dd.get_sample_name(d) for d in samples])
        callinfo = {"variantcaller": "ensemble",
                    "vrn_file": vcfutils.bgzip_and_index(out_vcf_file, data["config"]),
                    "bed_file": None}
    if is_cwl:
        callinfo["batch_samples"] = data["batch_samples"]
        callinfo["batch_id"] = batch_id
        return [{"ensemble": callinfo}]
    else:
        return [[batch_id, callinfo]]
529433
public void execute() throws MojoExecutionException, MojoFailureException {
        // iterate through all <merge />
        for (Merger merger : mergers) {
            // get target file name...
            final File target = merger.getTarget();
            // get list of source files
            final List<File> sources = Arrays.asList(merger.getSources());
            // ...and use a stream
            final OutputStream targetStream = initOutput(target);
            // iterate source files
            for (File source : sources) {
                final InputStream sourceStream = initInput(source);
                // append
                appendStream(sourceStream, targetStream);
                // close source
                if (null != sourceStream) {
                    try {
                        sourceStream.close();
                    } catch (IOException e) {
                        throw new MojoExecutionException(
                            "Could not close file: "
                                + source.getAbsolutePath(), e);
                    }
                }
            }
            // close target
            if (null != targetStream) {
                try {
                    targetStream.close();
                } catch (IOException e) {
                    throw new MojoExecutionException("Could not close file: "
                        + target.getAbsolutePath(), e);
                }
            }
        }
    }
207713
@Override
	protected void mergeBranchPlanMaps(Map<OptimizerNode, PlanNode> branchPlan1, Map<OptimizerNode,
			PlanNode> branchPlan2){

	}
603698
function mergeInner(base, mixin, mergeArrays) {
    if (base === null || typeof base !== 'object' || Array.isArray(base)) {
        throw new Error('base must be object');
    }
    if (mixin === null || typeof mixin !== 'object' || Array.isArray(mixin)) {
        throw new Error('mixin must be object');
    }
    Object.keys(mixin).forEach((name) => {
        mergeHelper(base, mixin, name, mergeArrays);
    });
}
1361783
def merge(items, amap, load=False):

    """"""

    for target, source in items:
        if amap.get(target):
            logger.warn('overwriting {0}'.format(target))
        if load:
            amap[target] = open(source).read()
        else:
            amap[target] = source
449609
function merge ( obj1, obj2 ) {
    var args = argsToArray( arguments ), res;
    if ( 0 === args.length ) return {};
    if ( 1 === args.length ) return obj1;
    if ( 2 === args.length ) return mergeTwo( obj1, obj2 );

    // More then two objects
    res  = mergeTwo( obj1, obj2 );
    args = args.slice( 2 );

    while ( args.length ) {
        res = mergeTwo( res, args[ 0 ] );
        args = args.slice( 1 );
    }

    return res;

    function mergeTwo ( obj1, obj2 ) {
        if ( !isDefined( obj1 ) ) return obj2;
        if ( !isDefined( obj2 ) ) return obj1;

        for (var key in obj2) {
            obj1[ key ] = obj2[ key ];
        }

        return obj1;
    }
}
52617
static void merge(Map<ConfigurationKey, Object> original, Map<ConfigurationKey, Object> toMerge, String mergedSourceDescription) {
        for (Entry<ConfigurationKey, Object> entry : toMerge.entrySet()) {
            Object existing = original.get(entry.getKey());
            if (existing != null) {
                ConfigurationLogger.LOG.configurationKeyAlreadySet(entry.getKey().get(), existing, entry.getValue(), mergedSourceDescription);
            } else {
                original.put(entry.getKey(), entry.getValue());
            }
        }
    }