Imperfect code. Checks the last amino acid to see if a codon could have
translated a stop for it. Left in for the moment
175049
protected void trimStop(List<AminoAcidCompound> sequence) {
		AminoAcidCompound stop = sequence.get(sequence.size() - 1);
		boolean isStop = false;
		if (aminoAcidToCodon.containsKey(stop)) {
			for (Codon c : aminoAcidToCodon.get(stop)) {
				if (c.isStop()) {
					isStop = true;
					break;
				}
			}
		}

		if (isStop) {
			sequence.remove(sequence.size() - 1);
		}
	}
538885
def fix_text(s, ignore_sym_pat=False):

    if not ignore_sym_pat:
        # Fix descriptions like D7TDB1 (
        s = re.sub("([A-Z0-9]){6} \(", "", s)
        s = s.split(";")[0]

    # Fix parantheses containing names
    s = s.translate(None, "[]")
    s = s.replace("(-)", "[-]")
    s = s.replace("(+)", "[+]")
    s = s.replace("(Uncharacterized protein)", "")
    if not ignore_sym_pat:
        s = s.translate(None, "()")

    # fix minor typos, seen in `autonaming` output
    # change 'protei ' to 'protein '
    # change 'hypthetical' to 'hypothetical'
    # fix string starting with 'ytochrome'
    if 'protei ' in s: s = s.replace('protei ', 'protein ')
    if 'hypthetical' in s: s = s.replace('hypthetical', 'hypothetical')
    if s.startswith('ytochrome'): s = s.replace('ytochrome', 'cytochrome')

    # before trimming off at the first ";", check if name has glycosidic
    # linkage information (e.g 1,3 or 1,4). If so, also check if multiple
    # linkages are separated by ";". If so, replace ";" by "-"
    m = re.findall(glycosidic_link_pat, s)
    if m and ";" in s:
        s = re.sub(";\s*", "-", s)

    # remove underscore from description
    s = re.sub("_", " ", s)

    # Cellular locations
    # Any word that matches e.g. AT5G54690
    # Any word that matches e.g. Os02g0234800
    # (fragment)
    # UPF
    # Remove 'DDB_G\d+' ID
    # '_At[0-9]+g[0-9]+' to ''
    for pat in (loc_pat, osg_pat, frag_pat, upf_pat, ddb_pat):
        # below is a hack since word boundaries don't work on /
        s = s.strip() + " "
        s = re.sub(pat, "", s)

    # &apos;? => '
    s = re.sub(apos_pat, "'", s)
    # &gt => none
    s = re.sub(gt_pat, "", s)
    # reduce runs such as -- '''
    s = re.sub(r"[-]+", "-", s)
    s = re.sub(r"[']+", "'", s)

    s = s.strip()

    # -like to -like protein
    s = re.sub(like_pat, "-like protein", s)

    # 'repeat$' to 'repeat protein'
    if re.search(repeat_pat, s):
        s += "-containing protein"

    # 'binding$' to 'binding protein'
    if re.search(binding_pat, s):
        s += " protein"
        if re.match(Protein_pat, s):
            s = re.sub(Protein_pat, "", s)

    # 'domain$' to 'domain-containing protein'
    if re.search(domain_pat, s):
        s += "-containing protein"
        if re.search(r"-domain", s):
            s = re.sub(r"-domain", " domain", s)
        if re.match(Protein_pat, s):
            s = re.sub(Protein_pat, "", s)

    # 'related$' to '-like protein'
    if re.search(related_pat, s):
        s = re.sub(related_pat, "-like protein", s)
        if re.match(Protein_pat, s) and not re.match(r"Protein kinase", s):
            s = re.sub(Protein_pat, "", s)

    # '[0-9]+ homolog' to '-like protein'
    if re.search(homolog_pat1, s):
        s = re.sub(homolog_pat1, "-like protein", s)
        if re.match(Protein_pat, s):
            s = re.sub(Protein_pat, "", s)

    # 'Protein\s+(.*)\s+homolog' to '$1-like protein'
    match = re.search(homolog_pat2, s)
    if match and not re.match(r"Protein kinase", s):
        ret = match.group(1)
        s = re.sub(homolog_pat2, ret + "-like protein", s)
        s = re.sub(r"^\s+", "", s)
        s = s.capitalize()

    # 'homolog protein' to '-like protein'
    # 'homologue$' to '-like protein'
    # 'homolog$' to '-like protein'
    for pat in (homolog_pat3, homolog_pat5, homolog_pat6):
        if re.search(pat, s):
            s = re.sub(pat, "-like protein", s)

    # 'Agenet domain-containing protein / bromo-adjacent homology (BAH) domain-containing protein'
    # to 'Agenet and bromo-adjacent homology (BAH) domain-containing protein'
    if re.search(agenet_pat, s):
        s = re.sub(agenet_pat, "Agenet and ", s)

    # plural to singular
    if re.search(plural_pat, s):
        if (s.find('biogenesis') == -1 and s.find('Topors') == -1) or (not re.search(with_and_pat, s)):
            s = re.sub(r"s$", "", s)

    # 'like_TBP' or 'likeTBP' to 'like TBP'
    if re.search(tbp_pat, s):
        s = re.sub(tbp_pat, "like TBP", s)

    # 'protein protein' to 'protein'
    if re.search(prot_pat, s):
        s = re.sub(prot_pat, "protein", s)

    # 'dimerisation' to 'dimerization'
    if re.search(dimer_pat, s):
        s = re.sub(dimer_pat, "dimerization", s)

    # Any AHRD that matches e.g. "AT5G54690-like protein"
    # Any AHRD that contains the words '^Belongs|^Encoded|^Expression|^highly'
    for pat in (atg_pat, athila_pat1):
        if re.search(pat, s):
            s = Unknown

    # remove 'arabidopsis[ thaliana]' and/or embedded Atg IDs
    for pat in (atg_id_pat, athila_pat2, athila_pat3, athila_pat4):
        # below is a hack since word boundaries don't work on /
        s = s.strip() + " "
        s = re.sub(pat, "", s)

    # remove "\s+LENGTH=\d+" from TAIR deflines
    if re.search(length_pat, s):
        s = re.sub(length_pat, "", s)

    # if name has a dot followed by a space (". ") in it and contains multiple
    # parts separated by a comma, strip name starting from first occurrence of ","
    if re.search(r"\. ", s):
        if re.search(r",", s):
            s = s.split(",")[0]

    # if name contains any of the disallowed words,
    # remove word occurrence from name
    # if name contains references to any other organism, trim name upto
    # that occurrence
    for pat in (disallow_pat, organism_pat):
        if re.search(pat, s):
            s = re.sub(pat, "", s)

    s = s.strip()

    if not ignore_sym_pat:
        # 'homolog \d+' to '-like protein'
        if re.search(homolog_pat4, s):
            s = re.sub(homolog_pat4, "", s)

        # Trailing protein numeric copy (e.g. Myb 1)
        if re.search(trail_pat, s):
            s = re.sub(trail_pat, "", s)

        # if name is entirely a gene symbol-like (all capital letters, maybe followed by numbers)
        # add a "-like protein" at the end
        if (re.search(sym_pat, s) or re.search(lc_sym_pat, s)) \
                and not re.search(spada_pat, s):
            s = s + "-like protein"

        # if gene symbol in parantheses at EOL, remove symbol
        if re.search(eol_sym_pat, s):
            s = re.sub(eol_sym_pat, "", s)

        # if name terminates at a symbol([^A-Za-z0-9_]), trim it off
        if re.search(r"\W{1,}$", s) and not re.search(r"\)$", s):
            s = re.sub("\W{1,}$", "", s)

        if "uncharacterized" in s:
            s = "uncharacterized protein"

    # change sulfer to sulfur
    if re.search(sulfer_pat, s):
        s = re.sub(sulfer_pat, "sulfur", s)

    # change sulph to sulf
    if re.search(sulph_pat, s):
        s = re.sub(sulph_pat, "sulf", s)

    # change monoxy to monooxy
    if re.search(monoxy_pat, s):
        s = re.sub(monoxy_pat, "monooxy", s)

    # change proteine to protein
    if re.search(proteine_pat, s):
        s = re.sub(proteine_pat, "protein", s)

    # change signalling to signaling
    if re.search(signalling_pat, s):
        s = re.sub(signalling_pat, "signaling", s)

    # change aluminium to aluminum
    if re.search(aluminium_pat, s):
        s = re.sub(aluminium_pat, "aluminum", s)

    # change haem to heme
    if re.search(haem_pat, s):
        s = re.sub(haem_pat, "heme", s)

    # chage haemo to hemo
    if re.search(haemo_pat, s):
        s = re.sub(haemo_pat, "hemo", s)

    # change assessory to accessory
    if re.search(assessory_pat, s):
        s = re.sub(assessory_pat, "accessory", s)

    # change -ise/-ised/-isation to -ize/-ized/-ization
    match = re.search(ise_pat, s)
    if match:
        ret = match.group(1)
        if match.group(2):
            suff = match.group(2)
            s = re.sub(ise_pat, "{0}ize{1}".format(ret, suff), s)
        else:
            s = re.sub(ise_pat, "{0}ize".format(ret), s)

    match = re.search(isation_pat, s)
    if match:
        ret = match.group(1)
        s = re.sub(isation_pat, "{0}ization".format(ret), s)

    # change -bre to -ber
    match = re.search(bre_pat, s)
    if match:
        ret = match.group(1)
        s = re.sub(bre_pat, "{0}ber".format(ret), s)

    if not s.startswith(Hypothetical):
        # 'Candidate|Hypothetical|Novel|Predicted|Possible|Probable|Uncharacterized' to 'Putative'
        if s.startswith('Uncharacterized') and any(pat in s for pat in ('UCP', 'UPF', 'protein')):
            pass
        else:
            if re.search(put_pat, s):
                s = re.sub(put_pat, "Putative", s)

    
    sl = s.lower()

    # Any mention of `clone` or `contig` is not informative
    if "clone" in sl or "contig" in sl:
        s = Unknown

    # All that's left is `protein` is not informative
    if sl in ("protein", "protein, putative", ""):
        s = Unknown

    if Unknown.lower() in sl:
        s = Unknown

    if "FUNCTIONS IN".lower() in sl and "unknown" in sl:
        s = Unknown

    if "LOCATED IN".lower() in sl:
        s = Unknown

    s = re.sub(r"[,]*\s+putative$", "", s)

    if s == Unknown or s.strip() == "protein":
        s = Hypothetical

    # Compact all spaces
    s = ' '.join(s.split())

    assert s.strip()

    return s
114591
def check_padding_around_mutation(given_padding, epitope_lengths):
    
    min_required_padding = max(epitope_lengths) - 1
    if not given_padding:
        return min_required_padding
    else:
        require_integer(given_padding, "Padding around mutation")
        if given_padding < min_required_padding:
            raise ValueError(
                "Padding around mutation %d cannot be less than %d "
                "for epitope lengths %s" % (
                    given_padding,
                    min_required_padding,
                    epitope_lengths))
        return given_padding
1091134
def check(args, source_code, filename=None, options=None):
    """"""
    if args is None:
        return []
    if options is not None:
        args += options
    if any(['pyflakes' in arg for arg in args]):
        #  Pyflakes requires an ending new line (pycodestyle don't! -- see Issue 1123)
        #  Note: this code is not used right now as it is faster to invoke 
        #  pyflakes in current Python interpreter (see `check_with_pyflakes` 
        #  function above) than calling it through a subprocess
        source_code += '\n'
    if filename is None:
        # Creating a temporary file because file does not exist yet 
        # or is not up-to-date
        tempfd = tempfile.NamedTemporaryFile(suffix=".py", delete=False)
        tempfd.write(source_code)
        tempfd.close()
        args.append(tempfd.name)
    else:
        args.append(filename)
    cmd = args[0]
    cmdargs = args[1:]
    proc = programs.run_program(cmd, cmdargs)
    output = proc.communicate()[0].strip().decode().splitlines()
    if filename is None:
        os.unlink(tempfd.name)
    results = []
    coding = encoding.get_coding(source_code)
    lines = source_code.splitlines()
    for line in output:
        lineno = int(re.search(r'(\:[\d]+\:)', line).group()[1:-1])
        try:
            text = to_text_string(lines[lineno-1], coding)
        except TypeError:
            text = to_text_string(lines[lineno-1])
        except UnicodeDecodeError:
            # Needed to handle UnicodeDecodeError and force the use
            # of chardet to detect enconding. See issue 6970
            coding = encoding.get_coding(source_code, force_chardet=True)
            text = to_text_string(lines[lineno-1], coding)
        if 'analysis:ignore' not in text:
            message = line[line.find(': ')+2:]
            results.append((message, lineno))
    return results
889986
def determine_end_offset(block, tokens, source, expected_matcher)
      lines = source.lines
      last_line_number = lines.length
      end_offset = nil
      tokens.reverse_each do |token|
        # Break once we're through with the last line.
        break if token[0][0] != last_line_number

        # Look for expected match to block opener
        next if token[1] != expected_matcher
        next if token[1] == :on_kw && token[2] != END_STR

        # Raise if we've already found something that looks like a block end.
        raise AmbiguousSourceError.from_proc(block) if end_offset
        # Ending offset is the position of the ending token, plus the length of
        # that token.
        end_offset = token[0][1] + token[2].length
      end
      raise AmbiguousSourceError.from_proc(block) unless end_offset
      determine_end_offset_relative_to_source(end_offset, lines.last.length)
    end
379923
def check_unassigned(chars, bad_tables):
    
    bad_tables = (
        stringprep.in_table_a1,)

    violator = check_against_tables(chars, bad_tables)
    if violator is not None:
        raise ValueError("Input contains unassigned code point: "
                         "U+{:04x}".format(ord(violator)))
336544
function _checkExitCode(result, test) {

  var actual = result.exitcode;
  var expect = test.exitcode;
  var error;

  if (typeof expect === 'string') {
    expect = parseInt(expect, 10);
  }

  if (expect !== undefined && expect !== actual) {
    error = util.format('Exit code %d does not match expected %d', actual, expect);
  }

  return error;
}
662474
def next_code_is_indented(lines):
    """"""
    for line in lines:
        if _BLANK_LINE.match(line) or _PY_COMMENT.match(line):
            continue
        return _PY_INDENTED.match(line)
    return False
1345378
def _validate_translation(self, aligned_prot, aligned_nucl):
        
        codons = [''.join(i) for i in batch(str(aligned_nucl), 3)]
        for codon, aa in zip(codons, str(aligned_prot)):
            # Check gaps
            if codon == '---' and aa == '-':
                continue

            try:
                trans = self.translation_table.forward_table[codon]
                if not trans == aa:
                    raise ValueError("Codon {0} translates to {1}, not {2}".format(
                        codon, trans, aa))
            except (KeyError, CodonTable.TranslationError):
                if aa != 'X':
                    if self.unknown_action == 'fail':
                        raise ValueError("Unknown codon: {0} mapped to {1}".format(
                            codon, aa))
                    elif self.unknown_action == 'warn':
                        logging.warn('Cannot verify that unknown codon %s '
                                     'maps to %s', codon, aa)
        return True
1044737
private void validateOpcodeUsingFin(Opcode opcode, boolean fin) throws ProtocolDecoderException {
        switch (opcode) {
            case CONTINUATION:
                if (prevDataFin) {
                    throw new ProtocolDecoderException("Not expecting CONTINUATION frame");
                }
                break;

            case TEXT:
            case BINARY:
                if (!prevDataFin) {
                    throw new ProtocolDecoderException("Expecting CONTINUATION frame, but got "+opcode+" frame");
                }
                break;

            case PING:
            case PONG:
            case CLOSE:
                if (!fin) {
                    throw new ProtocolDecoderException("Expected FIN for "+opcode+" frame");
                }
                break;
        default:
            break;
        }
    }
119231
def make_codon_list(protein_seq, template_dna=None, include_stop=True):
    

    codon_list = []

    if template_dna is None:
        template_dna = []

    # Reverse translate each codon, preferring (in order):
    # 1. The codon with the most similarity to the template codon.
    # 2. The codon with the highest natural usage.

    for i, res in enumerate(protein_seq.upper()):
        try: template_codon = template_dna[3*i:3*i+3]
        except IndexError: template_codon = '---'

        # Already sorted by natural codon usage
        possible_codons = dna.ecoli_reverse_translate[res]

        # Sort by similarity.  Note that this is a stable sort.
        possible_codons.sort(
                key=lambda x: dna.num_mutations(x, template_codon))

        # Pick the best codon.
        codon_list.append(possible_codons[0])

    # Make sure the sequence ends with a stop codon.
    last_codon = codon_list[-1]
    stop_codons = dna.ecoli_reverse_translate['.']

    if include_stop and last_codon not in stop_codons:
        codon_list.append(stop_codons[0])

    return codon_list
1174069
private final void step5() {
        if (k == 0)
            return;
        /* for Bug 1 */ 
        switch (sb.charAt(k-1)) {
        case 'a':
            if (ends("al"))
                break;
            return;
        case 'c': 
            if (ends("ance"))
                break;
            if (ends("ence"))
                break;
            return;
        case 'e':
            if (ends("er"))
                break;
            return;
        case 'i':
            if (ends("ic"))
                break;
            return;
        case 'l':
            if (ends("able"))
                break;
            if (ends("ible"))
                break;
            return;
        case 'n':
            if (ends("ant"))
                break;
            if (ends("ement"))
                break;
            if (ends("ment"))
                break;
            /* element etc. not stripped before the m */
            if (ends("ent"))
                break;
            return;
        case 'o':
            if (ends("ion") && j >= 0 && (b[j] == 's' || b[j] == 't'))
                break;
            /* j >= 0 fixes Bug 2 */
            if (ends("ou"))
                break;
            return;
            /* takes care of -ous */
        case 's':
            if (ends("ism"))
                break;
            return;
        case 't': 
            if (ends("ate"))
                break;
            if (ends("iti"))
                break;
            return;
        case 'u':
            if (ends("ous"))
                break;
            return;
        case 'v':
            if (ends("ive"))
                break;
            return;
        case 'z':
            if (ends("ize"))
                break;
            return;
        default:
            return;
        }
        if (m() > 1) k = j;
    }
145852
private boolean isLineLastStament(TestMethod method, int codeLineIndex) {
        CodeLine codeLine = method.getCodeBody().get(codeLineIndex);
        if (codeLineIndex == method.getCodeBody().size() - 1) {
            return true;
        }

        CodeLine nextCodeLine = method.getCodeBody().get(codeLineIndex + 1);
        assert codeLine.getEndLine() <= nextCodeLine.getStartLine();
        if (codeLine.getEndLine() == nextCodeLine.getStartLine()) {
            // if next statement exists in the same line,
            // this statement is not the last statement for the line
            return false;
        }
        return true;
    }
1013677
public static AminoAcidSequence translate(NucleotideSequence ns, TranslationParameters translationParameters) {
        byte[] data;
        if (translationParameters.fromLeft == null) {
            data = new byte[(ns.size() + (translationParameters.includeIncomplete ? 2 : 0)) / 3];
            int aaLength = ns.size() / 3;
            int leftAALength = (aaLength + 1) / 2;
            int rightAALength = aaLength - leftAALength;
            GeneticCode.translate(data, 0, ns, 0, leftAALength * 3);
            GeneticCode.translate(data, data.length - rightAALength, ns, ns.size() - rightAALength * 3, rightAALength * 3);
            if (ns.size() % 3 != 0)
                data[leftAALength] = AminoAcidAlphabet.INCOMPLETE_CODON;
        } else if (translationParameters.fromLeft) {
            int aaLength = (ns.size() - translationParameters.frame + (translationParameters.includeIncomplete ? 2 : 0)) / 3;
            if (translationParameters.includeIncomplete && translationParameters.frame != 0)
                ++aaLength;
            data = new byte[aaLength];
            int pointer = 0;
            if (translationParameters.includeIncomplete && translationParameters.frame != 0)
                data[pointer++] = AminoAcidAlphabet.INCOMPLETE_CODON;
            int trLength = ((ns.size() - translationParameters.frame) / 3) * 3;
            GeneticCode.translate(data, pointer, ns, translationParameters.frame, trLength);
            pointer += trLength / 3;
            if (pointer != aaLength)
                data[data.length - 1] = AminoAcidAlphabet.INCOMPLETE_CODON;
        } else
            return translate(ns, translationParameters.convertToLeftBound(ns.size()));
        return new AminoAcidSequence(data, true);
    }
349170
def graftm_package_is_protein(graftm_package):
        '''

        '''
        found = None
        with open(graftm_package.alignment_hmm_path()) as f:
            r = f.read().split("\n")
        for line in r:
            if line=='ALPH  DNA':
                found = False
                break
            elif line=='ALPH  amino':
                found = True
                break
        if found is None:
            raise Exception("Unable to determine whether the HMM was amino acid or dna")
        return found
508233
function utf8CheckIncomplete(self, buf, i) {
  var j = buf.length - 1;
  if (j < i) return 0;
  var nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    if (nb > 0) self.lastNeed = nb - 1;
    return nb;
  }
  if (--j < i) return 0;
  nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    if (nb > 0) self.lastNeed = nb - 2;
    return nb;
  }
  if (--j < i) return 0;
  nb = utf8CheckByte(buf[j]);
  if (nb >= 0) {
    if (nb > 0) {
      if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
    }
    return nb;
  }
  return 0;
}
342415
public static AminoAcidSequence translate(NucleotideSequence sequence) {
        if (sequence.size() % 3 != 0)
            throw new IllegalArgumentException("Only nucleotide sequences with size multiple " +
                    "of three are supported (in-frame).");
        byte[] aaData = new byte[sequence.size() / 3];
        GeneticCode.translate(aaData, 0, sequence, 0, sequence.size());
        return new AminoAcidSequence(aaData, true);
    }