Parse mutation field to get position and nts.
964231
def _parse_mut(mut):
    
    multiplier = 1
    if mut.startswith("-"):
        mut = mut[1:]
        multiplier = -1
    nt = mut.strip('0123456789')
    pos = int(mut[:-2]) * multiplier
    return nt, pos
723048
def _parse_status(bug_el):
    """"""
    bug = Bugreport()

    # plain fields
    for field in ('originator', 'subject', 'msgid', 'package', 'severity',
                  'owner', 'summary', 'location', 'source', 'pending',
                  'forwarded'):
        setattr(bug, field, _parse_string_el(bug_el(field)))

    bug.date = datetime.utcfromtimestamp(float(bug_el('date')))
    bug.log_modified = datetime.utcfromtimestamp(float(bug_el('log_modified')))
    bug.tags = [_uc(tag) for tag in str(bug_el('tags')).split()]
    bug.done = _parse_bool(bug_el('done'))
    bug.archived = _parse_bool(bug_el('archived'))
    bug.unarchived = _parse_bool(bug_el('unarchived'))
    bug.bug_num = int(bug_el('bug_num'))
    bug.mergedwith = [int(i) for i in str(bug_el('mergedwith')).split()]
    bug.blockedby = [int(i) for i in str(bug_el('blockedby')).split()]
    bug.blocks = [int(i) for i in str(bug_el('blocks')).split()]

    bug.found_versions = [_uc(str(el)) for el in
                          bug_el('found_versions').children() or []]
    bug.fixed_versions = [_uc(str(el)) for el in
                          bug_el('fixed_versions').children() or []]
    affects = [_f for _f in str(bug_el('affects')).split(',') if _f]
    bug.affects = [_uc(a).strip() for a in affects]
    # Also available, but unused or broken
    # bug.keywords = [_uc(keyword) for keyword in
    #                 str(bug_el('keywords')).split()]
    # bug.fixed = _parse_crappy_soap(tmp, "fixed")
    # bug.found = _parse_crappy_soap(tmp, "found")
    # bug.found_date = \
    #     [datetime.utcfromtimestamp(i) for i in tmp["found_date"]]
    # bug.fixed_date = \
    #     [datetime.utcfromtimestamp(i) for i in tmp["fixed_date"]]
    return bug
805852
def get_call_exprs(self, line):
        """"""
        line = line.lstrip()
        try:
            tree = self.ast.parse(line)
        except SyntaxError:
            return None
        for node in self.ast.walk(tree):
            if isinstance(node, self.ast.Call):
                offsets = []
                for arg in node.args:
                    # In Python 3.4 the col_offset is calculated wrong. See
                    # https://bugs.python.org/issue21295
                    if isinstance(arg, self.ast.Attribute) and (
                            (3, 4, 0) <= self.sys.version_info <= (3, 4, 3)):
                        offsets.append(arg.col_offset - len(arg.value.id) - 1)
                    else:
                        offsets.append(arg.col_offset)
                if node.keywords:
                    line = line[:node.keywords[0].value.col_offset]
                    line = self.re.sub(r'\w+\s*=\s*$', '', line)
                else:
                    line = self.re.sub(r'\s*\)\s*$', '', line)
                offsets.append(len(line))
                args = []
                for i in range(len(node.args)):
                    args.append(line[offsets[i]:offsets[i + 1]].rstrip(', '))
                return args
1284874
def _assemble_agent_str(agent):
    """"""
    agent_str = agent.name

    # Only do the more detailed assembly for molecular agents
    if not isinstance(agent, ist.Agent):
        return agent_str

    # Handle mutation conditions
    if agent.mutations:
        is_generic = False
        mut_strs = []
        for mut in agent.mutations:
            res_to = mut.residue_to if mut.residue_to else ''
            res_from = mut.residue_from if mut.residue_from else ''
            pos = mut.position if mut.position else ''
            mut_str = '%s%s%s' % (res_from, pos, res_to)
            # If this is the only mutation and there are no details
            # then this is a generic mutant
            if not mut_str and len(agent.mutations) == 1:
                is_generic = True
                break
            mut_strs.append(mut_str)
        if is_generic:
            agent_str = 'mutated ' + agent_str
        else:
            mut_strs = '/'.join(mut_strs)
            agent_str = '%s-%s' % (agent_str, mut_strs)

    # Handle location
    if agent.location is not None:
        agent_str += ' in the ' + agent.location

    if not agent.mods and not agent.bound_conditions and not agent.activity:
        return agent_str

    # Handle bound conditions
    bound_to = [bc.agent.name for bc in
                agent.bound_conditions if bc.is_bound]
    not_bound_to = [bc.agent.name for bc in
                agent.bound_conditions if not bc.is_bound]
    if bound_to:
        agent_str += ' bound to ' + _join_list(bound_to)
        if not_bound_to:
            agent_str += ' and not bound to ' +\
                _join_list(not_bound_to)
    else:
        if not_bound_to:
            agent_str += ' not bound to ' +\
                _join_list(not_bound_to)

    # Handle modification conditions
    if agent.mods:
        # Special case
        if len(agent.mods) == 1 and agent.mods[0].position is None:
            prefix = _mod_state_str(agent.mods[0].mod_type)
            if agent.mods[0].residue is not None:
                residue_str =\
                    ist.amino_acids[agent.mods[0].residue]['full_name']
                prefix = residue_str + '-' + prefix
            agent_str =  prefix + ' ' + agent_str
        else:
            if agent.bound_conditions:
                agent_str += ' and'
            agent_str += ' %s on ' % _mod_state_str(agent.mods[0].mod_type)
            mod_lst = []
            for m in agent.mods:
                if m.position is None:
                    if m.residue is not None:
                        residue_str =\
                            ist.amino_acids[m.residue]['full_name']
                        mod_lst.append(residue_str)
                    else:
                        mod_lst.append('an unknown residue')
                elif m.position is not None and m.residue is None:
                    mod_lst.append('amino acid %s' % m.position)
                else:
                    mod_lst.append(m.residue + m.position)
            agent_str += _join_list(mod_lst)


    # Handle activity conditions
    if agent.activity is not None:
        # Get the modifier specific to the activity type, if any
        pre_prefix = \
            activity_type_prefix.get(agent.activity.activity_type, '')
        if agent.activity.is_active:
            prefix = pre_prefix + 'active'
        else:
            # See if there is a special override for the inactive form
            if agent.activity.activity_type in inactivity_type_prefix_override:
                pre_prefix = inactivity_type_prefix_override[
                    agent.activity.activity_type]
            prefix = pre_prefix + 'inactive'
        agent_str = prefix + ' ' + agent_str

    return agent_str
950337
def parse_selection(lexer: Lexer) -> SelectionNode:
    """"""
    return (parse_fragment if peek(lexer, TokenKind.SPREAD) else parse_field)(lexer)
184968
def _get_update(self, variant):
        
        update = {
                '$inc': {
                    'homozygote': variant.get('homozygote', 0),
                    'hemizygote': variant.get('hemizygote', 0),
                    'observations': 1
                },
                '$set': {
                    'chrom': variant.get('chrom'),
                    'start': variant.get('pos'),
                    'end': variant.get('end'),
                    'ref': variant.get('ref'),
                    'alt': variant.get('alt'),
                }
             }
        if variant.get('case_id'):
            update['$push'] = {
                                'families': {
                                '$each': [variant.get('case_id')],
                                '$slice': -50
                                }
                            }
        return update
670414
def coerce(cls, key, value):
        """"""

        if isinstance(value, string_types):
            value = value.strip()
            if value[0] == '[':  # It's json encoded, probably
                try:
                    value = json.loads(value)
                except ValueError:
                    raise ValueError("Failed to parse JSON: '{}' ".format(value))
            else:
                value = value.split(',')

        if not value:
            value = []

        self = MutationList((MutationObj.coerce(key, v) for v in value))
        self._key = key
        return self
1116640
function getMutations(spec, attr) {
      var fns = compose(extraction, cleanup, stitch)(spec);
      return _.callmap(fns, attr);
    }
193143
def update_mutation_inputs(service):
    
    # grab the default list of field summaries
    inputs = _service_mutation_summaries(service)

    # visit each field
    for field in inputs:
        # if we're looking at the id field
        if field['name'] == 'id':
            # make sure its required
            field['required'] = True
        # but no other field
        else:
            # is required
            field['required'] = False

    # return the final list
    return inputs
278556
function getErrors(conf, path, props) {
    var originInfo = (path || props) ? "problem with prop: `" + props + "` at path: `" + path + "`" : '';
    var tradPatt = (conf.pattern === 'traditional');
    var setter = conf.setter;
    var deletor = conf.deletor;
    var prop = 'items';
    var mutationNameSet = tradPatt ? 'SET_' + prop.toUpperCase() : prop;
    var mutationNameDel = tradPatt ? 'DELETE_' + prop.toUpperCase() : prop;
    var exampleSetters__Wildcard = "\n    Correct usage examples:\n    // From Vue-components:\n    " + setter + "('" + prop + ".*', {'123': {name: 'the best item'}})\n\n    // From the Vuex store:\n    dispatch('" + setter + "/" + prop + ".*', {'123': {name: 'the best item'}})\n    // or\n    commit('" + mutationNameSet + ".*', {'123': {name: 'the best item'}})";
    var exampleSetters__DoubleWildcard = "\n    Correct usage examples:\n    // From Vue-components:\n    " + setter + "('" + prop + ".*.tags.*', ['123', {water: true}])\n\n    // From the Vuex store:\n    dispatch('" + setter + "/" + prop + ".*.tags.*', ['123', {water: true}])\n    // or\n    commit('" + mutationNameSet + ".*.tags.*', ['123', {water: true}])";
    var exampleDeletor = "\n    Correct usage examples:\n    // From Vue-components:\n    " + deletor + "('" + prop + ".*', '123')\n\n    // From the Vuex store:\n    dispatch('" + deletor + "/" + prop + ".*', '123')\n    // or\n    commit('" + mutationNameDel + ".*', '123')";
    return {
        mutationSetterNoId: originInfo + "\n      The payload needs to be an object with an `id` field.\n      " + exampleSetters__Wildcard,
        mutationSetterPropPathWildcardMissingItemDoesntExist: originInfo + "\n      The item does not exist! Make sure you first set the item.\n      " + exampleSetters__Wildcard,
        mutationSetterPropPathWildcardIdCount: originInfo + "\n      The amount of ids and wildcards `'*'` are not equal.\n      If you have multiple wildcards you need to pass an array, where each item is an ID and the last is the property you want to set.\n      " + exampleSetters__DoubleWildcard + "\n      ",
        mutationDeleteNoId: originInfo + "\n      The payload needs to be an object with an `id` field.\n      " + exampleDeletor + "\n      ",
        wildcardFormatWrong: originInfo + "\n      There was something wrong with the payload passed when using a path with wildcards.\n\n      A) Path with wildcard:\n      " + exampleSetters__Wildcard + "\n\n      B) Path with multiple wildcards:\n      " + exampleSetters__DoubleWildcard + "\n    ",
        missingDeleteMutation: "\n      There is no mutation set for '" + path + "'.\n      Something went wrong with your vuex-easy-access setup.\n      Did you manually add `...defaultMutations(state)` to your modules?\n      See the documentation here:\n        https://github.com/mesqueeb/VuexEasyAccess#setup\n\n\n      // You can also manually add a mutation like so in the correct module (not recommended!!):\n      mutations: {\n        '" + (tradPatt ? 'DELETE_' + props.toUpperCase() : '-' + props) + "': (state, payload) => {\n          this._vm.$delete(state." + props + ")\n        }\n      }\n    ",
        missingSetterMutation: "\n      There is no mutation set for '" + path + "'.\n      Something went wrong with your vuex-easy-access setup.\n      Did you manually add `...defaultMutations(state)` to your modules?\n      See the documentation here:\n        https://github.com/mesqueeb/VuexEasyAccess#setup\n\n\n      // You can also manually add a mutation like so in the correct module (not recommended!!):\n      mutations: {\n        '" + (tradPatt ? 'SET_' + props.toUpperCase() : props) + "': (state, payload) => {\n          state." + props + " = payload\n        }\n      }\n    ",
    };
}
637254
def get_info(node_cfg):
        """"""

        node_cfg = node_cfg if isinstance(node_cfg, dict) else {"name": node_cfg}

        return node_cfg.get("name"), node_cfg.get("fields", {})
150800
def _get_SEQRES_sequences(self):
        ''''''

        pdb_id = self.get_pdb_id()
        SEQRES_lines = self.parsed_lines["SEQRES"]

        modified_residue_mapping_3 = self.modified_residue_mapping_3
        # I commented this out since we do not need it for my current test cases
        #for k, v in self.modified_residues.iteritems():
        #    assert(v['modified_residue'] not in modified_residues)
        #    modified_residues[v['modified_residue']] = v['original_residue_3']

        for x in range(0, len(SEQRES_lines)):
            assert(SEQRES_lines[x][7:10].strip().isdigit())

        if not SEQRES_lines:
            #colortext.warning("WARNING: No SEQRES records were found. Kyle is trying to handle this gracefully, but Shane may need to fix it")
            return

        seqres_chain_order = []
        SEQRES_lines = [line[11:].rstrip() for line in SEQRES_lines] # we cannot strip the left characters as some cases e.g. 2MBP are missing chain identifiers

        # Collect all residues for all chains, remembering the chain order
        chain_tokens = {}
        for line in SEQRES_lines:
            chainID = line[0]
            if missing_chain_ids.get(self.pdb_id):
                chainID = missing_chain_ids[self.pdb_id]
            if chainID not in seqres_chain_order:
                seqres_chain_order.append(chainID)
            chain_tokens[chainID] = chain_tokens.get(chainID, [])
            chain_tokens[chainID].extend(line[6:].strip().split())

        sequences = {}
        self.chain_types = {}

        canonical_acid_types = set(residue_type_3to1_map.keys())
        canonical_acid_types.remove('UNK')
        assert(len(canonical_acid_types) == 20)

        for chain_id, tokens in chain_tokens.iteritems():

            # Determine whether the chain is DNA, RNA, or a protein chain
            # 1H38 is a good test for this - it contains DNA (chains E and G and repeated by H, K, N, J, M, P), RNA (chain F, repeated by I, L, O) and protein (chain D, repeated by A,B,C) sequences
            # 1ZC8 is similar but also has examples of DU
            # 4IHY has examples of DI (I is inosine)
            # 2GRB has RNA examples of I and U
            # 1LRP has protein chains with only CA atoms
            # This will throw an exception when a non-canonical is found which is not listed in basics.py. In that case, the list in basics.py should be updated.

            chain_type = None
            set_of_tokens = set(tokens)
            if (set_of_tokens.union(all_recognized_dna) == all_recognized_dna):# or (len(set_of_tokens) <= 5 and len(set_of_tokens.union(dna_nucleotides)) == len(set_of_tokens) + 1): # allow one unknown DNA residue
                chain_type = 'DNA'
            elif (set_of_tokens.union(all_recognized_rna) == all_recognized_rna):# or (len(set_of_tokens) <= 5 and len(set_of_tokens.union(dna_nucleotides)) == len(set_of_tokens) + 1): # allow one unknown DNA residue
                chain_type = 'RNA'
            elif len(set_of_tokens) == 1 and 'UNK' in set_of_tokens:
                chain_type = 'Unknown'
            elif not(set_of_tokens.intersection(canonical_acid_types)):
                # Zero canonical residues may imply a ligand or a heterogen chain
                chain_type = PDB._determine_heterogen_chain_type(set_of_tokens)
            else:
                assert(len(set(tokens).intersection(dna_nucleotides)) == 0)
                assert(len(set(tokens).intersection(rna_nucleotides)) == 0)
                assert(len(set(tokens).intersection(rna_nucleotides)) == 0)
                chain_type = 'Protein'
                if not self.chain_atoms.get(chain_id):
                    # possible for biological unit files
                    continue
                if self.chain_atoms[chain_id] == set(['CA']):
                    chain_type = 'Protein skeleton'

            # Get the sequence, mapping non-canonicals to the appropriate letter
            self.chain_types[chain_id] = chain_type

            sequence = []
            if chain_type == 'DNA':
                for r in tokens:
                    if dna_nucleotides_2to1_map.get(r):
                        sequence.append(dna_nucleotides_2to1_map[r])
                    else:
                        if non_canonical_dna.get(r):
                            sequence.append(non_canonical_dna[r])
                        else:
                            raise Exception("Unknown DNA residue %s." % r)
            elif chain_type == 'RNA':
                for r in tokens:
                    if r in rna_nucleotides:
                        sequence.append(r)
                    else:
                        if non_canonical_rna.get(r):
                            sequence.append(non_canonical_rna[r])
                        else:
                            raise Exception("Unknown RNA residue %s." % r)
            else:
                token_counter = 0
                for r in tokens:
                    token_counter += 1
                    if residue_type_3to1_map.get(r):
                        sequence.append(residue_type_3to1_map[r])
                    else:

                        if self.modified_residue_mapping_3.get(r):
                            sequence.append(residue_type_3to1_map[self.modified_residue_mapping_3.get(r)])
                        elif non_canonical_amino_acids.get(r):
                            #print('Mapping non-canonical residue %s to %s.' % (r, non_canonical_amino_acids[r]))
                            #print(SEQRES_lines)
                            #print(line)
                            sequence.append(non_canonical_amino_acids[r])
                        elif r == 'UNK':
                            continue
                        # Skip these residues
                        elif r == 'ACE' and token_counter == 1:
                            # Always allow ACE as the first residue of a chain
                            sequence.append('X')
                        elif r == 'ACE' and pdb_id in cases_with_ACE_residues_we_can_ignore:
                            sequence.append('X')
                            #continue
                        # End of skipped residues
                        else:
                            #print(modified_residue_mapping_3)
                            if modified_residue_mapping_3.get(r):
                                if modified_residue_mapping_3[r] == 'UNK':
                                    sequence.append('X')
                                else:
                                    assert(modified_residue_mapping_3[r] in residue_types_3)
                                    sequence.append(residue_type_3to1_map[modified_residue_mapping_3[r]])
                            else:
                                raise Exception("Unknown protein residue %s in chain %s." % (r, chain_id))
            sequences[chain_id] = "".join(sequence)

        self.seqres_chain_order = seqres_chain_order

        # Create Sequence objects for the SEQRES sequences
        for chain_id, sequence in sequences.iteritems():
            self.seqres_sequences[chain_id] = Sequence.from_sequence(chain_id, sequence, self.chain_types[chain_id])
749747
def num_mutations(self):
        '''
        
        '''
        self._initialize()
        res = super(Container, self).num_mutations()
        return res
85802
function checkMutations(mutations) {

	// Skip iterating the nodes, if a run is already scheduled, to improve performance
	if (scheduledCall && (scheduledCall._level < 3 || !scheduledCall._contexts)) {
		return;
	}

	var addedNodes = [];
	var stylesChanged = false;

	var replacedSheets = [];
	processedSheets.forEach(function(newNode) {
		replacedSheets.push(newNode);
	});

	arrayFrom(mutations).forEach(function(mutation) {

		addedNodes.push.apply(addedNodes, arrayFrom(mutation.addedNodes).filter(function(node) {
			return node.nodeType === 1;
		}));

		arrayFrom(mutation.removedNodes).forEach(function(node) {
			var index = addedNodes.indexOf(node);
			if (index !== -1) {
				addedNodes.splice(index, 1);
			}
			else if (
				(node.tagName === 'LINK' || node.tagName === 'STYLE')
				&& replacedSheets.indexOf(node) === -1
			) {
				stylesChanged = true;
			}
		});

	});

	addedNodes.forEach(function(node) {
		if (node.sheet && replacedSheets.indexOf(node) === -1) {
			stylesChanged = true;
		}
	});

	if (stylesChanged) {
		scheduleExecution(1);
	}
	else if (addedNodes.length) {
		scheduleExecution(3, false, addedNodes);
	}

}
80522
def check_mutate_fields( op, op_data ):
    

    mutate_fields = op_get_mutate_fields( op )
    assert mutate_fields is not None, "No mutate fields defined for %s" % op

    missing = []
    for field in mutate_fields:
        if not op_data.has_key(field):
            missing.append(field)

    assert len(missing) == 0, "Missing mutation fields for %s: %s" % (op, ",".join(missing))
    return True
1140426
function getSubstitution(matched, str, position, captures, namedCaptures, replacement) {
    var tailPos = position + matched.length;
    var m = captures.length;
    var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED;
    if (namedCaptures !== undefined) {
      namedCaptures = toObject(namedCaptures);
      symbols = SUBSTITUTION_SYMBOLS;
    }
    return $replace.call(replacement, symbols, function (match, ch) {
      var capture;
      switch (ch.charAt(0)) {
        case '$': return '$';
        case '&': return matched;
        case '`': return str.slice(0, position);
        case "'": return str.slice(tailPos);
        case '<':
          capture = namedCaptures[ch.slice(1, -1)];
          break;
        default: // \d\d?
          var n = +ch;
          if (n === 0) return match;
          if (n > m) {
            var f = floor(n / 10);
            if (f === 0) return match;
            if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1);
            return match;
          }
          capture = captures[n - 1];
      }
      return capture === undefined ? '' : capture;
    });
  }
309808
def ifposition(parser, token):
    
    bits = list(token.split_contents())
    end_tag = 'end' + bits[0]

    nofallback = False
    if bits[-1] == 'nofallback':
        nofallback = True
        bits.pop()

    if len(bits) >= 4 and bits[-2] == 'for':
        category = template.Variable(bits.pop())
        pos_names = bits[1:-1]
    else:
        raise TemplateSyntaxError('Invalid syntax: {% ifposition POSITION_NAME ... for CATEGORY [nofallback] %}')

    nodelist_true = parser.parse(('else', end_tag))
    token = parser.next_token()

    if token.contents == 'else':
        nodelist_false = parser.parse((end_tag,))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()

    return IfPositionNode(category, pos_names, nofallback, nodelist_true, nodelist_false)