Return a cigar string of aligned sequences.

        @param output: a C{tup} of strings (align1, align, align2)
        @return: a C{str} containing the cigar string. Eg with input:
            'GGCCCGCA' and 'GG-CTGCA', return 2=1D1=1X3=
168524
def _cigarString(self, output):
        
        cigar = []
        count = 0
        align1 = output[0]
        align2 = output[2]
        for nt1, nt2 in zip(align1, align2):
            if nt1 == nt2:
                cigar.append('=')
            elif nt1 == '-':
                cigar.append('I')
            elif nt2 == '-':
                cigar.append('D')
            else:
                cigar.append('X')
        # Initially create a list of characters,
        # eg ['=', '=', 'D', '=', 'X', '=', '=', '=']
        cigar.append('*')
        # Append an arbitrary character to ensure parsing below functions
        cigarString = ''
        previousCharacter = ''
        count = 0
        first = True
        for character in cigar:
            if first:
                previousCharacter = character
                count += 1
                first = False
            else:
                if character == previousCharacter:
                    count += 1
                else:
                    cigarString += (str(count) + str(previousCharacter))
                    count = 1
                previousCharacter = character
        return cigarString
395665
def align(self, alignment_tool = 'clustalw', gap_opening_penalty = 0.2, ignore_bad_chains = False):
        ''''''
        if len(self.pdb_chains) > 1:
            sa = SequenceAligner(alignment_tool = alignment_tool, gap_opening_penalty = gap_opening_penalty)
            for pdb_chain in self.pdb_chains:
                sa.add_sequence('%s_%s' % (pdb_chain['pdb_id'], pdb_chain['chain_id']), pdb_chain['sequence'], ignore_bad_chains = ignore_bad_chains)
            best_matches = sa.align()
            return sa.alignment_output, best_matches
        else:
            raise Exception('Cannot align sequences - less than two chains were specified.')
961109
def construct_cigar(self,min_intron_size=68):
    

    # goes target query
    ar = self.alignment_ranges
    cig = ''
    if ar[0][1].start > 1: # soft clipped
      cig += str(ar[0][1].start-1)+'S'
    for i in range(len(ar)):
      exlen = ar[i][0].length
      cig += str(exlen)+'M'
      if i < len(ar)-1:
        # we can look at distances
        dt = ar[i+1][0].start-ar[i][0].end-1
        dq = ar[i+1][1].start-ar[i][1].end-1
        if dq > 0: cig += str(dq)+'I'
        if dt >= min_intron_size:
          cig += str(dt)+'N'
        elif dt > 0: cig += str(dt)+'D'
        elif dq <= 0:
          sys.stderr.write("ERROR cant form alignment\n")
          sys.exit()

    if ar[-1][1].end < self.query_sequence_length: # soft clipped
      cig += str(self.query_sequence_length-ar[-1][1].end)+'S'
    return cig
571534
def coalesce_streams(outputs):
    
    if not outputs:
        return outputs

    new_outputs = []
    streams = {}
    for output in outputs:
        if (output.output_type == 'stream'):
            if output.name in streams:
                streams[output.name].text += output.text
            else:
                new_outputs.append(output)
                streams[output.name] = output
        else:
            new_outputs.append(output)

    # process \r and \b characters
    for output in streams.values():
        old = output.text
        while len(output.text) < len(old):
            old = output.text
            # Cancel out anything-but-newline followed by backspace
            output.text = backspace_pat.sub('', output.text)
        # Replace all carriage returns not followed by newline
        output.text = carriagereturn_pat.sub('', output.text)

    return new_outputs
1324514
public static String alignLeft(Object o, int width, char c) {
        if (null == o)
            return null;
        String s      = o.toString();
        int    length = s.length();
        if (length >= width)
            return s;
        return s + dup(c, width - length);
    }
1339857
def _output(cls,
            tensors: Sequence[tf.Tensor],
            dtypes: Sequence[tf.DType]) -> Sequence[tf.Tensor]:
        ''''''
        outputs = []
        for tensor, dtype in zip(tensors, dtypes):
            tensor = tensor[0]
            if tensor.dtype != dtype:
                tensor = tf.cast(tensor, dtype)
            outputs.append(tensor)
        return tuple(outputs)
852623
def build_alignment(self,score,pieces):
		""""""
	 	# build text
		self.open_seqs()
		text1 = text2 = ""
		end1  = end2  = None
		for (start1,start2,length,pctId) in pieces:
			if (end1 != None):
				if (start1 == end1): # insertion in sequence 2
					text1 += self.seq1_gap * (start2-end2)
					text2 += self.seq2_file.get(end2,start2-end2)
				else: # insertion in sequence 1
					text1 += self.seq1_file.get(end1,start1-end1)
					text2 += self.seq2_gap * (start1-end1)

			text1 += self.seq1_file.get(start1,length)
			text2 += self.seq2_file.get(start2,length)
			end1 = start1 + length
			end2 = start2 + length
		# create alignment
		start1 = pieces[0][0]
		start2 = pieces[0][1]
		end1   = pieces[-1][0] + pieces[-1][2]
		end2   = pieces[-1][1] + pieces[-1][2]
		size1  = end1 - start1
		size2  = end2 - start2
		a = Alignment(score=score,species_to_lengths=self.species_to_lengths)
		#if (self.seq1_strand == "-"): start1 = self.seq1_file.length - end1
		a.add_component(Component(self.seq1_src,start1,size1,self.seq1_strand,text=text1))
		#if (self.seq2_strand == "-"): start2 = self.seq2_file.length - end2
		a.add_component(Component(self.seq2_src,start2,size2,self.seq2_strand,text=text2))
		return a
468541
def _form_output(span_doc: span, output_format: str, relations: Dict, patterns: List) -> str:
        

        format_value = []
        output_inf = [a_pattern.in_output for a_pattern in patterns]
        for i in range(len(output_inf)):
            token_range = relations[i]
            if token_range and output_inf[i]:
                format_value.append(span_doc[token_range[0]:token_range[1]].text)

        if not output_format:
            return " ".join(format_value)

        result_str = re.sub("{}", " ".join(format_value), output_format)

        positions = re.findall("{[0-9]+}", result_str)

        if not positions:
            return result_str

        position_indices = [int(x[1:-1]) for x in positions]
        if max(position_indices) < len(format_value):
            result_str = result_str.format(*format_value)
        else:
            try:
                result_str = result_str.format("", *format_value)
            except:
                positions = [x for x in positions if int(x[1:-1]) > len(format_value)-1 or int(x[1:-1]) < 0]
                for pos in positions:
                    result_str = result_str.replace(pos, "")
                result_str = result_str.format(*format_value)

        return result_str
301265
def format_output(data, fmt='table'):  # pylint: disable=R0911,R0912
    
    if isinstance(data, utils.string_types):
        if fmt in ('json', 'jsonraw'):
            return json.dumps(data)
        return data

    # responds to .prettytable()
    if hasattr(data, 'prettytable'):
        if fmt == 'table':
            return str(format_prettytable(data))
        elif fmt == 'raw':
            return str(format_no_tty(data))

    # responds to .to_python()
    if hasattr(data, 'to_python'):
        if fmt == 'json':
            return json.dumps(
                format_output(data, fmt='python'),
                indent=4,
                cls=CLIJSONEncoder)
        elif fmt == 'jsonraw':
            return json.dumps(format_output(data, fmt='python'),
                              cls=CLIJSONEncoder)
        elif fmt == 'python':
            return data.to_python()

    # responds to .formatted
    if hasattr(data, 'formatted'):
        if fmt == 'table':
            return data.formatted

    # responds to .separator
    if hasattr(data, 'separator'):
        output = [format_output(d, fmt=fmt) for d in data if d]
        return str(SequentialOutput(data.separator, output))

    # is iterable
    if isinstance(data, list) or isinstance(data, tuple):
        output = [format_output(d, fmt=fmt) for d in data]
        if fmt == 'python':
            return output
        return format_output(listing(output, separator=os.linesep))

    # fallback, convert this odd object to a string
    return data
977168
public int /* reg12 */output() {
		// It may seem cleaner to use an array of member functions to return
		// waveform output; however a switch with inline functions is faster.

		switch (waveform) {
		default:
		case 0x0:
			return output____();
		case 0x1:
			return output___T();
		case 0x2:
			return output__S_();
		case 0x3:
			return output__ST();
		case 0x4:
			return output_P__();
		case 0x5:
			return output_P_T();
		case 0x6:
			return output_PS_();
		case 0x7:
			return output_PST();
		case 0x8:
			return outputN___();
		case 0x9:
			return outputN__T();
		case 0xa:
			return outputN_S_();
		case 0xb:
			return outputN_ST();
		case 0xc:
			return outputNP__();
		case 0xd:
			return outputNP_T();
		case 0xe:
			return outputNPS_();
		case 0xf:
			return outputNPST();
		}
	}
575844
def variant_context_w_alignment(am, var, margin=20, tx_ac=None):
    """"""
    from uta_align.align.algorithms import align, cigar_alignment

    fh = full_house(am, var, tx_ac=tx_ac)
    tm = am._fetch_AlignmentMapper(fh['n'].ac, fh['g'].ac, am.alt_aln_method)
    strand = tm.strand
    span_g = _ival_to_span(fh['g'].posedit.pos)
    span_g = (span_g[0] - margin, span_g[1] + margin)
    ival_g = Interval(SimplePosition(span_g[0]), SimplePosition(span_g[1]))
    ival_n = tm.g_to_n(ival_g)
    assert ival_n.start.offset == 0 and ival_n.end.offset == 0, "limited to coding variants"
    span_n = _ival_to_span(ival_n)
    ival_c = tm.g_to_c(ival_g)
    span_c = _ival_to_span(ival_c)
    seq_gt = am.hdp.get_seq(fh['g'].ac, span_g[0] - 1, span_g[1])
    seq_gb = complement(seq_gt)
    seq_n = am.hdp.get_seq(fh['n'].ac, span_n[0] - 1, span_n[1])
    if strand == 1:
        a = align(bytes(seq_gt), bytes(seq_n), b'global', extended_cigar=True)
    else:
        seq_n = ''.join(reversed(seq_n))
        a = align(bytes(seq_gb), bytes(seq_n), b'global', extended_cigar=True)

    aseq_gt, _ = cigar_alignment(seq_gt, a.query, a.cigar, hide_match=False)
    aseq_gb, aseq_n = cigar_alignment(seq_gb, a.query, a.cigar, hide_match=False)
    aln_str = _reformat_aln_str(cigar_alignment(a.ref, a.query, a.cigar, hide_match=True)[1])
    s_dir = '>' if strand == 1 else '<'

    lines = [
        [
            1,
            0,
            seq_line_fmt(
                var=fh['c'],
                span=span_c if strand == 1 else list(reversed(span_c)),
                content='',
                dir=s_dir),
        ],
        [
            2,
            0,
            seq_line_fmt(
                var=fh['n'],
                span=span_n if strand == 1 else list(reversed(span_n)),
                content=aseq_n,
                dir=s_dir),
        ],
        [
            3,
            0,
            _line_fmt.format(pre='', content=aln_str, post=a.cigar.to_string(), comment=''),
        ],
        [
            4,
            1,
            seq_line_fmt(var=fh['g'], span=span_g, content=aseq_gt, dir='>'),
        ],
        [
            4,
            2,
            seq_line_fmt(var=fh['g'], span=span_g, content=aseq_gb, dir='<'),
        ],
        [
            5,
            0,
            pointer_line(var=fh['g'], span=span_g),
        ],
    ]
    if strand == -1:
        lines.sort(key=lambda e: (-e[0], e[1]))
    return '\n'.join(r[2] for r in lines)
979960
def _get_seqprop_to_seqprop_alignment(self, seqprop1, seqprop2):
        """"""
        if isinstance(seqprop1, str):
            seqprop1_id = seqprop1
        else:
            seqprop1_id = seqprop1.id
        if isinstance(seqprop2, str):
            seqprop2_id = seqprop2
        else:
            seqprop2_id = seqprop2.id

        aln_id = '{}_{}'.format(seqprop1_id, seqprop2_id)

        if self.sequence_alignments.has_id(aln_id):
            alignment = self.sequence_alignments.get_by_id(aln_id)
            return alignment
        else:
            raise ValueError('{}: sequence alignment not found, please run the alignment first'.format(aln_id))
128185
def _parse_fmdump(output):
    '''
    
    '''
    result = []
    output = output.split("\n")

    # extract header
    header = [field for field in output[0].lower().split(" ") if field]
    del output[0]

    # parse entries
    for entry in output:
        entry = [item for item in entry.split(" ") if item]
        entry = ['{0} {1} {2}'.format(entry[0], entry[1], entry[2])] + entry[3:]

        # prepare faults
        fault = OrderedDict()
        for field in header:
            fault[field] = entry[header.index(field)]

        result.append(fault)

    return result
722684
def write(self):
        

        return '{0}\t{1}\t{2}\t{3}\t{4}\t' \
               '{5}\t{6}\t{7}\t{8}\t{9}\t' \
               '{10}{11}'.format(self.qname,
                                 str(self.flag),
                                 self.rname,
                                 str(self.pos),
                                 str(self.mapq),
                                 self.cigar,
                                 self.rnext,
                                 str(self.pnext),
                                 str(self.tlen),
                                 self.seq,
                                 self.qual,
                                 os.linesep)
277707
def _output(cls, fluents: Sequence[FluentPair]) -> Sequence[tf.Tensor]:
        ''''''
        return tuple(cls._dtype(t) for t in cls._tensors(fluents))
1355459
def output(self,delimiter = '\t', addnormalised=False):
        """"""
        for type, count in self:
            if isinstance(type,tuple) or isinstance(type,list):
                if addnormalised:
                    yield " ".join((u(x) for x in type)) + delimiter + str(count) + delimiter + str(count/self.total)
                else:
                    yield " ".join((u(x) for x in type)) + delimiter + str(count)
            elif isstring(type):
                if addnormalised:
                    yield type + delimiter + str(count) + delimiter + str(count/self.total)
                else:
                    yield type + delimiter + str(count)
            else:
                if addnormalised:
                    yield str(type) + delimiter + str(count) + delimiter + str(count/self.total)
                else:
                    yield str(type) + delimiter + str(count)
1323759
def multicharacters(input)
      output = input.gsub(/\([Cc]\)/, "©")
      output = output.gsub(/\([Pp]\)/, "℗")
      output = output.gsub(/\([Rr]\)/, "®")
      output = output.gsub(/\((SM|sm|Sm)\)/, "℠")
      output = output.gsub(/\((TM|tm|Tm)\)/, "™")
      output = output.gsub(/\+-/, "±")
      output = output.gsub(/-\+/, "∓")
      output = output.gsub(/N[oO]\.?\s*(\d+)/, '№\1')
      output = output.gsub(/°C/, '℃')
      output = output.gsub(/°F/, '℉')
    end