Merge another link into this one. Expected that each link was created from each mate from a pair. We only know both distances to contig ends when we have read info from both mappings in a BAM file. All other info should be the same.
434206
def merge(self, other):
        ''''''
        assert self.refnames == other.refnames
        assert self.dirs == other.dirs
        assert self.lengths == other.lengths

        for i in range(2):
            if self.pos[i] is None:
                if other.pos[i] is None:
                   raise Error('Error merging these two links:\n' + str(self) + '\n' + str(other))
                self.pos[i] = other.pos[i]
            else:
                if other.pos[i] is not None:
                   raise Error('Error merging these two links:\n' + str(self) + '\n' + str(other))
591727
def combine_bam(in_files, out_file, config):
    
    runner = broad.runner_from_path("picard", config)
    runner.run_fn("picard_merge", in_files, out_file)
    for in_file in in_files:
        save_diskspace(in_file, "Merged into {0}".format(out_file), config)
    bam.index(out_file, config)
    return out_file
474353
def mergebed(args):
    
    p = OptionParser(mergebed.__doc__)
    p.add_option("-w", "--weightsfile", default="weights.txt",
                 help="Write weights to file")
    p.set_outfile("out.bed")
    opts, args = p.parse_args(args)

    if len(args) < 1:
        sys.exit(not p.print_help())

    maps = args
    outfile = opts.outfile
    fp = must_open(maps)
    b = Bed()
    mapnames = set()
    for row in fp:
        mapname = filename_to_mapname(fp.filename())
        mapnames.add(mapname)
        try:
            m = BedLine(row)
            m.accn = "{0}-{1}".format(mapname, m.accn)
            m.extra = ["{0}:{1}".format(m.seqid, m.start)]
            b.append(m)
        except (IndexError, ValueError):  # header or mal-formed line
            continue

    b.print_to_file(filename=outfile, sorted=True)
    logging.debug("A total of {0} markers written to `{1}`.".\
                        format(len(b), outfile))

    assert len(maps) == len(mapnames), "You have a collision in map names"
    write_weightsfile(mapnames, weightsfile=opts.weightsfile)
1283438
def concat(self, other, inplace=False):
        ''''''
        
        # Create new entity
        if inplace:
            obj = self
        else:
            obj = self.copy()
        
        # Stitch every attribute
        for name, attr in obj.__attributes__.items():
            attr.append(other.__attributes__[name])
            
        # Stitch every relation
        for name, rel in obj.__relations__.items():
            rel.append(other.__relations__[name])
        
        # Update maps
        
        # Update dimensions
        if obj.is_empty():
            obj.maps = {k: m.copy() for k, m in other.maps.items()}
            obj.dimensions = other.dimensions.copy()
        else:
            for (a, b), rel in obj.maps.items():
                rel.append(other.maps[a, b])
            for d in obj.dimensions:
                obj.dimensions[d] += other.dimensions[d]
        
        return obj
609463
function concat(a, b) {
	var aLen = a.size;
	var bLen = b.size;
	var newLen = aLen + bLen;

	if (aLen === 0) return b;
	if (bLen === 0) return a;

	if (!a.root || !b.root) {
		if (aLen + bLen <= _const.M) {
			let newTail = a.tail.concat(b.tail);
			newTail.height = 0;
			if (!a.editable) return new Tree(newLen, null, newTail);
			a.size = newLen;
			a.root = null;
			a.tail = newTail;
			return a;
		}
		if (!a.root && !b.root) {
			// newTail will overflow, but newRoot can't be over M
			let newRoot = a.tail.concat(b.tail.slice(0, _const.M - aLen));
			newRoot.height = 0;
			let newTail = b.tail.slice(_const.M - aLen);
			newTail.height = 0;
			if (!a.editable) return new Tree(newLen, newRoot, newTail);
			a.size = newLen;
			a.root = newRoot;
			a.tail = newTail;
			return a;
		}
		// else either a has a root or b does
		if (!b.root) {
			// b has no root
			let aTailLen = a.tail.length;
			let bTailLen = b.tail.length;
			// size left over in last root node in a
			let rightCut = _const.M - aTailLen;
			// create a new tail by concatting b until cut
			let newTail = a.tail.concat(b.tail.slice(0, rightCut));
			newTail.height = 0;
			let newRoot;
			// if tail would overflow, sink it and make leftover newTail
			if (aTailLen + bTailLen > _const.M) {
				newRoot = (0, _util.sinkTailIfSpace)(newTail, a.root, a.editable);
				newTail = b.tail.slice(rightCut);
				newTail.height = 0;
			} else {
				newRoot = a.root.slice(0);
				if(a.root.height) newRoot.sizes = a.root.sizes.slice(0);
				newRoot.height = a.root.height;
			}
			if (!a.editable) return new Tree(newLen, newRoot, newTail);
			a.size = newLen;
			a.root = newRoot;
			a.tail = newTail;
			return a;
		}
		// else a has no root
		// make a.tail a.root and concat b.root
		let newRoot = (0, _concat.concatRoot)((0, _util.parentise)(a.tail, 1), b.root, a.editable);
		let newTail = (0, _util.createLeafFrom)(b.tail, a.editable);
		if (!a.editable) return new Tree(newLen, newRoot, newTail);
		a.size = newLen;
		a.root = newRoot;
		a.tail = newTail;
		return a;
	} else {
		// both a and b have roots
		// if have a.tail, just sink a.tail and make b.tail new tail...
		let aRoot = a.tail.length === 0 ? a.root : (0, _util.sinkTailIfSpace)(a.tail, a.root, a.editable) || (0, _util.siblise)(a.root, (0, _util.parentise)(a.tail, a.root.height));
		let newRoot = (0, _concat.concatRoot)(aRoot, b.root, a.editable);
		let newTail = (0, _util.createLeafFrom)(b.tail, a.editable);
		if (!a.editable) return new Tree(newLen, newRoot, newTail);
		a.size = newLen;
		a.root = newRoot;
		a.tail = newTail;
		return a;
	}
}
1105152
public void merge(ClusteringFeature x) {
		assert (this.sumPoints.length == x.sumPoints.length);
		this.numPoints += x.numPoints;
		super.setWeight(this.numPoints);
		for (int i = 0; i < this.sumPoints.length; i++) {
			this.sumPoints[i] += x.sumPoints[i];
		}
		this.sumSquaredLength += x.sumSquaredLength;
	}
177408
def merge_extras(items, config):
    
    final = {}
    for extra_name in items[0]["disambiguate"].keys():
        in_files = []
        for data in items:
            in_files.append(data["disambiguate"][extra_name])
        out_file = "%s-allmerged%s" % os.path.splitext(in_files[0])
        if in_files[0].endswith(".bam"):
            merged_file = merge.merge_bam_files(in_files, os.path.dirname(out_file), items[0],
                                                out_file=out_file)
        else:
            assert extra_name == "summary", extra_name
            merged_file = _merge_summary(in_files, out_file, items[0])
        final[extra_name] = merged_file
    out = []
    for data in items:
        data["disambiguate"] = final
        out.append([data])
    return out
1111379
def merge(self, other):
        
        other = IntervalCell.coerce(other)
        if self.is_equal(other):
            # pick among dependencies
            return self
        elif other.is_entailed_by(self):
            return self
        elif self.is_entailed_by(other):
            self.low, self.high = other.low, other.high
        elif self.is_contradictory(other):
            #import traceback
            #for line in traceback.format_stack(): print line.strip()

            raise Contradiction("Cannot merge [%0.2f, %0.2f] with [%0.2f, %0.2f]" \
                    % (self.low, self.high, other.low, other.high))
        else:
            # information in both
            self.low = max(self.low, other.low)
            self.high = min(self.high, other.high)
        return self
285787
def merge_required_files(dirnames, out_dir):
    
    # The list of files to merge
    fn_to_merge = ("steps_summary.tex", "excluded_markers.txt",
                   "excluded_samples.txt")

    # Merging the files
    for fn in fn_to_merge:
        o_fn = os.path.join(out_dir, fn)
        with open(o_fn, "w") as o_file:
            for dn in dirnames:
                i_fn = os.path.join(dn, fn)
                with open(i_fn, "r") as i_file:
                    o_file.write(i_file.read())

    # Merging the result summary file
    o_fn = os.path.join(out_dir, "results_summary.txt")
    with open(o_fn, "w") as o_file:
        for i, dn in enumerate(dirnames):
            i_fn = os.path.join(dn, "results_summary.txt")
            with open(i_fn, "r") as i_file:
                if i != 0:
                    # We skip the first 4 lines (file descriptions)
                    [i_file.readline() for i in range(4)]
                o_file.write(i_file.read())

    # Merging the graphic paths file
    graphic_paths = set()
    for dn in dirnames:
        fn = os.path.join(dn, "graphic_paths.txt")
        if os.path.isfile(fn):
            with open(fn, "r") as i_file:
                graphic_paths.update({
                    os.path.join(dn, path)
                    for path in i_file.read().splitlines()
                })
    if len(graphic_paths) > 0:
        with open(os.path.join(out_dir, "graphic_paths.txt"), "w") as o_file:
            for path in sorted(graphic_paths):
                print >>o_file, os.path.relpath(path, out_dir)
424283
def merge(self, other):
        
        newstart = min(self._start, other.start)
        newend = max(self._end, other.end)
        return Range(newstart, newend)
926685
def picard_merge(picard, in_files, out_file=None,
                 merge_seq_dicts=False):
    
    if out_file is None:
        out_file = "%smerge.bam" % os.path.commonprefix(in_files)
    if not file_exists(out_file):
        with tx_tmpdir(picard._config) as tmp_dir:
            with file_transaction(picard._config, out_file) as tx_out_file:
                opts = [("OUTPUT", tx_out_file),
                        ("SORT_ORDER", "coordinate"),
                        ("MERGE_SEQUENCE_DICTIONARIES",
                         "true" if merge_seq_dicts else "false"),
                        ("USE_THREADING", "true"),
                        ("TMP_DIR", tmp_dir)]
                for in_file in in_files:
                    opts.append(("INPUT", in_file))
                picard.run("MergeSamFiles", opts)
    return out_file
1033173
private static String mergePaths(String path1, String path2)
  {
    return path1 + (path1.endsWith(Path.SEPARATOR) ? "" : Path.SEPARATOR) + path2;
  }
948362
function mergePathMaps(sourceMaps, targetMap, targetDir) {
    // Merge multiple source maps together, along with target path info.
    // Entries in later source maps override those in earlier source maps.
    // Target stats will be filled in below for targets that exist.
    var pathMap = {};
    sourceMaps.forEach(function (sourceMap) {
        Object.keys(sourceMap).forEach(function(sourceSubPath){
            var sourceEntry = sourceMap[sourceSubPath];
            pathMap[sourceSubPath] = {
                targetPath: path.join(targetDir, sourceSubPath),
                targetStats: null,
                sourcePath: path.join(sourceEntry.subDir, sourceSubPath),
                sourceStats: sourceEntry.stats
            };
        });
    });

    // Fill in target stats for targets that exist, and create entries
    // for targets that don't have any corresponding sources.
    Object.keys(targetMap).forEach(function(subPath){
        var entry = pathMap[subPath];
        if (entry) {
            entry.targetStats = targetMap[subPath].stats;
        } else {
            pathMap[subPath] = {
                targetPath: path.join(targetDir, subPath),
                targetStats: targetMap[subPath].stats,
                sourcePath: null,
                sourceStats: null
            };
        }
    });

    return pathMap;
}
560390
def merge(self, ontologies):
        
        if self.xref_graph is None:
            self.xref_graph = nx.MultiGraph()
        logger.info("Merging source: {} xrefs: {}".format(self, len(self.xref_graph.edges())))
        for ont in ontologies:
            logger.info("Merging {} into {}".format(ont, self))
            g = self.get_graph()
            srcg = ont.get_graph()
            for n in srcg.nodes():
                g.add_node(n, **srcg.node[n])
            for (o,s,m) in srcg.edges(data=True):
                g.add_edge(o,s,**m)
            if ont.xref_graph is not None:
                for (o,s,m) in ont.xref_graph.edges(data=True):
                    self.xref_graph.add_edge(o,s,**m)
703777
def _merge_all_bridged_contigs(self, nucmer_hits, ref_contigs, qry_contigs, log_fh=None, log_outprefix=None):
        ''''''
        writing_log_file = None not in [log_fh, log_outprefix]

        if len(nucmer_hits) == 0:
            if writing_log_file:
                print(log_outprefix, 'No nucmer hits, so will not make any merges', sep='\t', file=log_fh)
            return

        all_nucmer_hits = []
        for l in nucmer_hits.values():
            all_nucmer_hits.extend(l)
        nucmer_hits_by_qry = self._hits_hashed_by_query(all_nucmer_hits)
        bridges = self._get_possible_query_bridging_contigs(nucmer_hits_by_qry, log_fh=log_fh, log_outprefix=log_outprefix)
        if writing_log_file:
            print(log_outprefix, '\tPotential contigs to use for merging: ', ' '.join(sorted(bridges.keys())), sep='', file=log_fh)
        bridges = self._filter_bridging_contigs(bridges)
        if writing_log_file:
            print(log_outprefix, '\tContigs to use for merging after uniqueness filtering: ', ' '.join(sorted(bridges.keys())), sep='', file=log_fh)

        merged = set()
        made_a_join = False

        for qry_name, (start_hit, end_hit) in bridges.items():
            if start_hit.ref_name in merged or end_hit.ref_name in merged:
                continue
            self._merge_bridged_contig_pair(start_hit, end_hit, ref_contigs, qry_contigs, log_fh=log_fh, log_outprefix=log_outprefix)
            merged.add(start_hit.ref_name)
            merged.add(end_hit.ref_name)
            made_a_join = True

        if writing_log_file:
            print(log_outprefix, '\tMade at least one contig join: ', made_a_join, sep='', file=log_fh)

        return made_a_join
346529
function endStream(cb) {
        // If no files were passed in, no files go out ...
        if (!latestFile || (Object.keys(concats).length === 0 && concats.constructor === Object)) {
            cb();
            return;
        }

        // Prepare a method for pushing the stream
        const pushJoinedFile = (joinedBase) => {
            const joinedFile = new File({
                path: joinedBase,
                contents: concats[joinedBase].concat.content,
                stat: concats[joinedBase].stats
            });
            if (concats[joinedBase].concat.sourceMapping) {
                joinedFile.sourceMap = JSON.parse(concats[joinedBase].concat.sourceMap);
            }
            this.push(joinedFile);
            delete concats[joinedBase];
        };

        // Refine the dependency graph
        const refinedDependencyMap = [];
        dependencyGraph.forEach(edge => {
            if ((edge[0] in nameBaseMap) && (edge[1] in nameBaseMap)) {
                refinedDependencyMap.push([nameBaseMap[edge[0]], nameBaseMap[edge[1]]]);
            }
        });
        const sortedDependencies = refinedDependencyMap.length ? toposort(refinedDependencyMap).reverse() : [];
        sortedDependencies.map(pushJoinedFile);

        // Run through all registered contact instances
        for (const targetBase in concats) {
            pushJoinedFile(targetBase);
        }
        cb();
    }
683265
def merge(self, other):
        
        print "MERGING", self, other
        other = self.coerce(other)
        if self.is_contradictory(other):
            raise Contradiction("Cannot merge %s and %s" % (self, other))
        elif self.value is None and not other.value is None:
            self.r, self.g, self.b = other.r, other.g, other.b
            self.value = RGBColor(self.r, self.b, self.g, rgb_type='sRGB')
        # last cases:  other is none, or both are none 
        
        return self