Parse a compound specification.

    If no compartment is specified in the string, the global compartment
    will be used.
359568
def parse_compound(s, global_compartment=None):
    
    m = re.match(r'^\|(.*)\|$', s)
    if m:
        s = m.group(1)

    m = re.match(r'^(.+)\[(\S+)\]$', s)
    if m:
        compound_id = m.group(1)
        compartment = m.group(2)
    else:
        compound_id = s
        compartment = global_compartment

    return Compound(compound_id, compartment=compartment)
909315
def parse_format_specifier(specification):
    
    m = _parse_format_specifier_regex.match(specification)
    if m is None:
        raise ValueError(
            "Invalid format specifier: {!r}".format(specification))
    format_dict = m.groupdict('')

    # Convert zero-padding into fill and alignment.
    zeropad = format_dict.pop('zeropad')
    if zeropad:
        # If zero padding is requested, fill and align fields should be absent.
        if format_dict['align']:
            raise ValueError(
                "Invalid format specifier: {!r}".format(specification))
        # Impossible to have 'fill' without 'align'.
        assert not format_dict['fill']
        format_dict['align'] = '='
        format_dict['fill'] = '0'

    # Default alignment is right-aligned.
    if not format_dict['align']:
        format_dict['align'] = '>'

    # Default fill character is space.
    if not format_dict['fill']:
        format_dict['fill'] = ' '

    # Default sign is '-'.
    if not format_dict['sign']:
        format_dict['sign'] = '-'

    # Convert minimum width to an int; default is zero.
    format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')

    # Convert precision to an int, or `None` if no precision given.
    if format_dict['precision']:
        format_dict['precision'] = int(format_dict['precision'][1:])
    else:
        format_dict['precision'] = None

    # If no rounding mode is given, assume 'N'.
    if not format_dict['rounding']:
        format_dict['rounding'] = 'N'

    return format_dict
1064377
private void parse()
   {
      template = text;
      if (StringUtils.isEmptyTrimmed(template))
         return;
      int index = 0;
      while (template.indexOf("${") != -1)
      {
         int from = template.lastIndexOf("${");
         int to = template.indexOf("}", from + 2);
         if (to == -1)
         {
            template = text;
            complex = false;
            entities.clear();
            return;
         }

         int dv = template.indexOf(":", from + 2);
         if (dv != -1 && dv > to)
         {
            dv = -1;
         }
         String systemProperty = null;
         String defaultValue = null;
         String s = template.substring(from + 2, to);
         if ("/".equals(s))
         {
            systemProperty = File.separator;
         }
         else if (":".equals(s))
         {
            systemProperty = File.pathSeparator;
            dv = -1;
         }
         else
         {
            systemProperty = SecurityActions.getSystemProperty(s);
         }

         if (dv != -1)
         {
            s = template.substring(from + 2, dv);
            systemProperty = SecurityActions.getSystemProperty(s);
            defaultValue = template.substring(dv + 1, to);
         }
         String prefix = "";
         String postfix = "";
         String key = StringUtils.createKey(index++);
         updateComplex(defaultValue);
         entities.put(key, new Expression(s, defaultValue, systemProperty));

         if (from != 0)
         {
            prefix = template.substring(0, from);
         }
         if (to + 1 < template.length())
         {
            postfix = template.substring(to + 1);
         }
         template = prefix + key + postfix;
      }
      updateComplex(template);
   }
1050589
def parse_reaction_equation(equation_def, default_compartment):
    

    def parse_compound_list(l, compartment):
        """Parse a list of reactants or metabolites"""
        for compound_def in l:
            compound_id = compound_def.get('id')
            _check_id(compound_id, 'Compound')

            value = compound_def.get('value')
            if value is None:
                raise ParseError('Missing value for compound {}'.format(
                    compound_id))

            compound_compartment = compound_def.get('compartment')
            if compound_compartment is None:
                compound_compartment = compartment

            compound = Compound(compound_id, compartment=compound_compartment)
            yield compound, value

    if isinstance(equation_def, string_types):
        return parse_reaction_equation_string(
            equation_def, default_compartment)
    else:
        compartment = equation_def.get('compartment', default_compartment)
        reversible = bool(equation_def.get('reversible', True))
        left = equation_def.get('left', [])
        right = equation_def.get('right', [])
        if len(left) == 0 and len(right) == 0:
            raise ParseError('Reaction values are missing')

        return Reaction(Direction.Both if reversible else Direction.Forward,
                        parse_compound_list(left, compartment),
                        parse_compound_list(right, compartment))
1189780
def _parse_pot(pot):
    """"""
    from .integrateFullOrbit import _parse_scf_pot
    #Figure out what's in pot
    if not isinstance(pot,list):
        pot= [pot]
    #Initialize everything
    pot_type= []
    pot_args= []
    npot= len(pot)
    for p in pot:
        # Prepare for wrappers
        if ((isinstance(p,planarPotentialFromFullPotential) \
          or isinstance(p,planarPotentialFromRZPotential)) \
          and isinstance(p._Pot,parentWrapperPotential)) \
        or isinstance(p,parentWrapperPotential):
            if not isinstance(p,parentWrapperPotential):
                wrap_npot, wrap_pot_type, wrap_pot_args= \
                    _parse_pot(potential.toPlanarPotential(p._Pot._pot))
            else:
                wrap_npot, wrap_pot_type, wrap_pot_args= _parse_pot(p._pot)
        if (isinstance(p,planarPotentialFromRZPotential) 
            or isinstance(p,planarPotentialFromFullPotential) ) \
                 and isinstance(p._Pot,potential.LogarithmicHaloPotential):
            pot_type.append(0)
            if p._Pot.isNonAxi:
                pot_args.extend([p._Pot._amp,p._Pot._q,
                                 p._Pot._core2,p._Pot._1m1overb2])
            else:
                pot_args.extend([p._Pot._amp,p._Pot._q,p._Pot._core2,2.]) # 1m1overb2 > 1: axi
        elif isinstance(p,planarPotentialFromFullPotential) \
                 and isinstance(p._Pot,potential.DehnenBarPotential):
            pot_type.append(1)
            pot_args.extend([p._Pot._amp*p._Pot._af,p._Pot._tform,
                             p._Pot._tsteady,p._Pot._rb,p._Pot._omegab,
                             p._Pot._barphi])
        elif isinstance(p,potential.TransientLogSpiralPotential):
            pot_type.append(2)
            pot_args.extend([p._amp,p._A,p._to,p._sigma2,p._alpha,p._m,
                             p._omegas,p._gamma])
        elif isinstance(p,potential.SteadyLogSpiralPotential):
            pot_type.append(3)
            if p._tform is None:
                pot_args.extend([p._amp,float('nan'), float('nan'),
                                 p._A,p._alpha,p._m,
                                 p._omegas,p._gamma])
            else:
                pot_args.extend([p._amp,p._tform,p._tsteady,p._A,p._alpha,p._m,
                                 p._omegas,p._gamma])
        elif isinstance(p,potential.EllipticalDiskPotential):
            pot_type.append(4)
            if p._tform is None:
                pot_args.extend([p._amp,float('nan'), float('nan'),
                                 p._twophio,p._p,p._phib])
            else:
                pot_args.extend([p._amp,p._tform,p._tsteady,
                                 p._twophio,p._p,p._phib])
        elif isinstance(p,planarPotentialFromRZPotential) \
                 and isinstance(p._Pot,potential.MiyamotoNagaiPotential):
            pot_type.append(5)
            pot_args.extend([p._Pot._amp,p._Pot._a,p._Pot._b])
        elif isinstance(p,potential.LopsidedDiskPotential):
            pot_type.append(6)
            pot_args.extend([p._amp,p._mphio,p._p,p._phib])
        elif isinstance(p,planarPotentialFromRZPotential) \
                 and isinstance(p._Pot,potential.PowerSphericalPotential):
            pot_type.append(7)
            pot_args.extend([p._Pot._amp,p._Pot.alpha])
        elif isinstance(p,planarPotentialFromRZPotential) \
                 and isinstance(p._Pot,potential.HernquistPotential):
            pot_type.append(8)
            pot_args.extend([p._Pot._amp,p._Pot.a])
        elif isinstance(p,planarPotentialFromRZPotential) \
                 and isinstance(p._Pot,potential.NFWPotential):
            pot_type.append(9)
            pot_args.extend([p._Pot._amp,p._Pot.a])
        elif isinstance(p,planarPotentialFromRZPotential) \
                 and isinstance(p._Pot,potential.JaffePotential):
            pot_type.append(10)
            pot_args.extend([p._Pot._amp,p._Pot.a])
        elif isinstance(p,planarPotentialFromRZPotential) \
                and isinstance(p._Pot,potential.DoubleExponentialDiskPotential):
            pot_type.append(11)
            pot_args.extend([p._Pot._amp,p._Pot._alpha,
                             p._Pot._beta,p._Pot._kmaxFac,
                             p._Pot._nzeros,p._Pot._glorder])
            pot_args.extend([p._Pot._glx[ii] for ii in range(p._Pot._glorder)])
            pot_args.extend([p._Pot._glw[ii] for ii in range(p._Pot._glorder)])
            pot_args.extend([p._Pot._j0zeros[ii] for ii in range(p._Pot._nzeros+1)])
            pot_args.extend([p._Pot._dj0zeros[ii] for ii in range(p._Pot._nzeros+1)])
            pot_args.extend([p._Pot._j1zeros[ii] for ii in range(p._Pot._nzeros+1)])
            pot_args.extend([p._Pot._dj1zeros[ii] for ii in range(p._Pot._nzeros+1)])
            pot_args.extend([p._Pot._kp._amp,p._Pot._kp.alpha])
        elif isinstance(p,planarPotentialFromRZPotential) \
                and isinstance(p._Pot,potential.FlattenedPowerPotential):
            pot_type.append(12)
            pot_args.extend([p._Pot._amp,p._Pot.alpha,p._Pot.core2])
        elif isinstance(p,planarPotentialFromRZPotential) \
                 and isinstance(p._Pot,potential.IsochronePotential):
            pot_type.append(14)
            pot_args.extend([p._Pot._amp,p._Pot.b])
        elif isinstance(p,planarPotentialFromRZPotential) \
                 and isinstance(p._Pot,potential.PowerSphericalPotentialwCutoff):
            pot_type.append(15)
            pot_args.extend([p._Pot._amp,p._Pot.alpha,p._Pot.rc])
        elif isinstance(p,planarPotentialFromRZPotential) \
                 and isinstance(p._Pot,potential.MN3ExponentialDiskPotential):
            # Three Miyamoto-Nagai disks
            npot+= 2
            pot_type.extend([5,5,5])
            pot_args.extend([p._Pot._amp*p._Pot._mn3[0]._amp,
                             p._Pot._mn3[0]._a,p._Pot._mn3[0]._b,
                             p._Pot._amp*p._Pot._mn3[1]._amp,
                             p._Pot._mn3[1]._a,p._Pot._mn3[1]._b,
                             p._Pot._amp*p._Pot._mn3[2]._amp,
                             p._Pot._mn3[2]._a,p._Pot._mn3[2]._b])
        elif isinstance(p,planarPotentialFromRZPotential) \
                 and isinstance(p._Pot,potential.KuzminKutuzovStaeckelPotential):
            pot_type.append(16)
            pot_args.extend([p._Pot._amp,p._Pot._ac,p._Pot._Delta])
        elif isinstance(p,planarPotentialFromRZPotential) \
                 and isinstance(p._Pot,potential.PlummerPotential):
            pot_type.append(17)
            pot_args.extend([p._Pot._amp,p._Pot._b])
        elif isinstance(p,planarPotentialFromRZPotential) \
                 and isinstance(p._Pot,potential.PseudoIsothermalPotential):
            pot_type.append(18)
            pot_args.extend([p._Pot._amp,p._Pot._a])
        elif isinstance(p,planarPotentialFromRZPotential) \
                 and isinstance(p._Pot,potential.KuzminDiskPotential):
            pot_type.append(19)
            pot_args.extend([p._Pot._amp,p._Pot._a])
        elif isinstance(p,planarPotentialFromRZPotential) \
                 and isinstance(p._Pot,potential.BurkertPotential):
            pot_type.append(20)
            pot_args.extend([p._Pot._amp,p._Pot.a])
        elif (isinstance(p,planarPotentialFromFullPotential) or isinstance(p,planarPotentialFromRZPotential)) \
                and isinstance(p._Pot,potential.EllipsoidalPotential.EllipsoidalPotential):
            pot_args.append(p._Pot._amp)
            pot_args.extend([0.,0.,0.,0.,0.,0.]) # for caching
            if isinstance(p._Pot,potential.TriaxialHernquistPotential):
                pot_type.append(21)
                pot_args.extend([2,p._Pot.a,p._Pot.a4]) # for psi, mdens, mdens_deriv
            if isinstance(p._Pot,potential.TriaxialNFWPotential):
                pot_type.append(22)
                pot_args.extend([2,p._Pot.a,p._Pot.a3]) # for psi, mdens, mdens_deriv
            if isinstance(p._Pot,potential.TriaxialJaffePotential):
                pot_type.append(23)
                pot_args.extend([2,p._Pot.a,p._Pot.a2]) # for psi, mdens, mdens_deriv
            elif isinstance(p._Pot,potential.PerfectEllipsoidPotential):
                pot_type.append(30)
                pot_args.extend([1,p._Pot.a2]) # for psi, mdens, mdens_deriv
            pot_args.extend([p._Pot._b2,p._Pot._c2,
                             int(p._Pot._aligned)]) # Reg. Ellipsoidal
            if not p._Pot._aligned:
                pot_args.extend(list(p._Pot._rot.flatten()))
            else:
                pot_args.extend(list(nu.eye(3).flatten())) # not actually used
            pot_args.append(p._Pot._glorder)
            pot_args.extend([p._Pot._glx[ii] for ii in range(p._Pot._glorder)])
            # this adds some common factors to the integration weights
            pot_args.extend([-4.*nu.pi*p._Pot._glw[ii]*p._Pot._b*p._Pot._c\
                            /nu.sqrt(( 1.+(p._Pot._b2-1.)*p._Pot._glx[ii]**2.)
                                     *(1.+(p._Pot._c2-1.)*p._Pot._glx[ii]**2.))
                             for ii in range(p._Pot._glorder)])
        elif (isinstance(p,planarPotentialFromFullPotential) or isinstance(p,planarPotentialFromRZPotential)) \
                 and isinstance(p._Pot,potential.SCFPotential):
            pt,pa= _parse_scf_pot(p._Pot)
            pot_type.append(pt)
            pot_args.extend(pa)
        elif isinstance(p,planarPotentialFromFullPotential) \
                 and isinstance(p._Pot,potential.SoftenedNeedleBarPotential):
            pot_type.append(25)
            pot_args.extend([p._Pot._amp,p._Pot._a,p._Pot._b,p._Pot._c2,
                             p._Pot._pa,p._Pot._omegab])
            pot_args.extend([0.,0.,0.,0.,0.,0.,0.]) # for caching
        elif (isinstance(p,planarPotentialFromFullPotential) or isinstance(p,planarPotentialFromRZPotential)) \
                and isinstance(p._Pot,potential.DiskSCFPotential):
            # Need to pull this apart into: (a) SCF part, (b) constituent
            # [Sigma_i,h_i] parts
            # (a) SCF, multiply in any add'l amp
            pt,pa= _parse_scf_pot(p._Pot._scf,extra_amp=p._Pot._amp)
            pot_type.append(pt)
            pot_args.extend(pa)
            # (b) constituent [Sigma_i,h_i] parts
            for Sigma,hz in zip(p._Pot._Sigma_dict,p._Pot._hz_dict):
                npot+= 1
                pot_type.append(26)
                stype= Sigma.get('type','exp')
                if stype == 'exp' \
                        or (stype == 'exp' and 'Rhole' in Sigma):
                    pot_args.extend([3,0,
                                     4.*nu.pi*Sigma.get('amp',1.)*p._Pot._amp,
                                     Sigma.get('h',1./3.)])
                elif stype == 'expwhole' \
                        or (stype == 'exp' and 'Rhole' in Sigma):
                    pot_args.extend([4,1,
                                     4.*nu.pi*Sigma.get('amp',1.)*p._Pot._amp,
                                     Sigma.get('h',1./3.),
                                     Sigma.get('Rhole',0.5)])
                hztype= hz.get('type','exp')
                if hztype == 'exp':
                    pot_args.extend([0,hz.get('h',0.0375)])
                elif hztype == 'sech2':
                    pot_args.extend([1,hz.get('h',0.0375)])
        elif isinstance(p,planarPotentialFromFullPotential) \
                and isinstance(p._Pot, potential.SpiralArmsPotential):
            pot_type.append(27)
            pot_args.extend([len(p._Pot._Cs), p._Pot._amp, p._Pot._N, p._Pot._sin_alpha,
                             p._Pot._tan_alpha, p._Pot._r_ref, p._Pot._phi_ref, p._Pot._Rs, p._Pot._H, p._Pot._omega])
            pot_args.extend(p._Pot._Cs)
        elif isinstance(p,potential.CosmphiDiskPotential):
            pot_type.append(28)
            pot_args.extend([p._amp,p._mphio,p._p,p._mphib,p._m,
                             p._rb,p._rbp,p._rb2p,p._r1p])
        elif isinstance(p,potential.HenonHeilesPotential):
            pot_type.append(29)
            pot_args.extend([p._amp])
        # 30: PerfectEllipsoidPotential, done with other EllipsoidalPotentials above
        ############################## WRAPPERS ###############################
        elif ((isinstance(p,planarPotentialFromFullPotential) or isinstance(p,planarPotentialFromRZPotential)) \
              and isinstance(p._Pot,potential.DehnenSmoothWrapperPotential)) \
              or isinstance(p,potential.DehnenSmoothWrapperPotential):
            if not isinstance(p,potential.DehnenSmoothWrapperPotential):
                p= p._Pot
            pot_type.append(-1)
            # wrap_pot_type, args, and npot obtained before this horrible if
            pot_args.append(wrap_npot)
            pot_type.extend(wrap_pot_type)
            pot_args.extend(wrap_pot_args)
            pot_args.extend([p._amp,p._tform,p._tsteady,int(p._grow)])
        elif ((isinstance(p,planarPotentialFromFullPotential) or isinstance(p,planarPotentialFromRZPotential)) \
          and isinstance(p._Pot,potential.SolidBodyRotationWrapperPotential)) \
          or isinstance(p,potential.SolidBodyRotationWrapperPotential):
            if not isinstance(p,potential.SolidBodyRotationWrapperPotential):
                p= p._Pot
            pot_type.append(-2)
            # wrap_pot_type, args, and npot obtained before this horrible if
            pot_args.append(wrap_npot)
            pot_type.extend(wrap_pot_type)
            pot_args.extend(wrap_pot_args)
            pot_args.extend([p._amp,p._omega,p._pa])
        elif ((isinstance(p,planarPotentialFromFullPotential) or isinstance(p,planarPotentialFromRZPotential)) \
          and isinstance(p._Pot,potential.CorotatingRotationWrapperPotential)) \
          or isinstance(p,potential.CorotatingRotationWrapperPotential):
            if not isinstance(p,potential.CorotatingRotationWrapperPotential):
                p= p._Pot
            pot_type.append(-4)
            # wrap_pot_type, args, and npot obtained before this horrible if
            pot_args.append(wrap_npot)
            pot_type.extend(wrap_pot_type)
            pot_args.extend(wrap_pot_args)
            pot_args.extend([p._amp,p._vpo,p._beta,p._pa,p._to])
        elif ((isinstance(p,planarPotentialFromFullPotential) or isinstance(p,planarPotentialFromRZPotential)) \
              and isinstance(p._Pot,potential.GaussianAmplitudeWrapperPotential)) \
              or isinstance(p,potential.GaussianAmplitudeWrapperPotential):
            if not isinstance(p,potential.GaussianAmplitudeWrapperPotential):
                p= p._Pot
            pot_type.append(-5)
            # wrap_pot_type, args, and npot obtained before this horrible if
            pot_args.append(wrap_npot)
            pot_type.extend(wrap_pot_type)
            pot_args.extend(wrap_pot_args)
            pot_args.extend([p._amp,p._to,p._sigma2])
    pot_type= nu.array(pot_type,dtype=nu.int32,order='C')
    pot_args= nu.array(pot_args,dtype=nu.float64,order='C')
    return (npot,pot_type,pot_args)
43206
def parse_string(contents, name='tmp.cpp', **kwargs):
    
    idx = clang.cindex.Index.create()
    tu = idx.parse(name, unsaved_files=[(name, contents)], **kwargs)
    return _ensure_parse_valid(tu)
36551
def parse_compartments(self):
        

        compartments = OrderedDict()
        boundaries = set()

        if 'compartments' in self._model:
            boundary_map = {}
            for compartment_def in self._model['compartments']:
                compartment_id = compartment_def.get('id')
                _check_id(compartment_id, 'Compartment')
                if compartment_id in compartments:
                    raise ParseError('Duplicate compartment ID: {}'.format(
                        compartment_id))

                props = dict(compartment_def)
                adjacent_to = props.pop('adjacent_to', None)
                if adjacent_to is not None:
                    if not isinstance(adjacent_to, list):
                        adjacent_to = [adjacent_to]
                    for other in adjacent_to:
                        boundary_map.setdefault(other, set()).add(
                            compartment_id)

                mark = FileMark(self._context, None, None)
                compartment = CompartmentEntry(props, mark)
                compartments[compartment_id] = compartment

            # Check boundaries from boundary_map
            for source, dest_set in iteritems(boundary_map):
                if source not in compartments:
                    raise ParseError(
                        'Invalid compartment {} referenced'
                        ' by compartment {}'.format(
                            source, ', '.join(dest_set)))
                for dest in dest_set:
                    boundaries.add(tuple(sorted((source, dest))))

        return itervalues(compartments), frozenset(boundaries)
1117433
def parse_compound(self):
        """"""
        compound_tag = Compound()

        for token in self.collect_tokens_until('CLOSE_COMPOUND'):
            item_key = token.value
            if token.type not in ('NUMBER', 'STRING', 'QUOTED_STRING'):
                raise self.error(f'Expected compound key but got {item_key!r}')

            if token.type == 'QUOTED_STRING':
                item_key = self.unquote_string(item_key)

            if self.next().current_token.type != 'COLON':
                raise self.error(f'Expected colon but got '
                                 f'{self.current_token.value!r}')
            self.next()
            compound_tag[item_key] = self.parse()
        return compound_tag
1248552
def parse(self, buffer, inlineparent = None):
        '''
        
        '''
        size = 0
        v = []
        for i in range(0, self.size):  # @UnusedVariable
            r = self.innerparser.parse(buffer[size:], None)
            if r is None:
                return None
            v.append(r[0])
            size += r[1]
        return (v, size)
559828
def parse(self, instr):
        # type: (bytes) -> bool
        '''
        
        '''
        if self._initialized:
            raise pycdlibexception.PyCdlibInternalError('This IsoHybrid object is already initialized')

        if len(instr) != 512:
            raise pycdlibexception.PyCdlibInvalidISO('Invalid size of the instr')

        if instr[0:32] == self.ORIG_HEADER:
            self.header = self.ORIG_HEADER
        elif instr[0:32] == self.MAC_AFP:
            self.header = self.MAC_AFP
        else:
            # If we didn't see anything that we expected, then this is not an
            # IsoHybrid ISO, so just quietly return False
            return False

        (self.mbr, self.rba, unused1, self.mbr_id,
         unused2) = struct.unpack_from(self.FMT, instr[:32 + struct.calcsize(self.FMT)], 32)

        if unused1 != 0:
            raise pycdlibexception.PyCdlibInvalidISO('Invalid IsoHybrid section')

        if unused2 != 0:
            raise pycdlibexception.PyCdlibInvalidISO('Invalid IsoHybrid section')

        offset = 32 + struct.calcsize(self.FMT)
        for i in range(1, 5):
            if bytes(bytearray([instr[offset]])) == b'\x80':
                self.part_entry = i
                (const_unused, self.bhead, self.bsect, self.bcyle, self.ptype,
                 self.ehead, self.esect, self.ecyle, self.part_offset,
                 self.psize) = struct.unpack_from('=BBBBBBBBLL', instr[:offset + 16], offset)
                break
            offset += 16
        else:
            raise pycdlibexception.PyCdlibInvalidISO('No valid partition found in IsoHybrid!')

        if bytes(bytearray([instr[-2]])) != b'\x55' or bytes(bytearray([instr[-1]])) != b'\xaa':
            raise pycdlibexception.PyCdlibInvalidISO('Invalid tail on isohybrid section')

        self.geometry_heads = self.ehead + 1
        # FIXME: I can't see any way to compute the number of sectors from the
        # available information.  For now, we just hard-code this at 32 and
        # hope for the best.
        self.geometry_sectors = 32

        self._initialized = True

        return True
553746
def parse_compounds(self):
        """"""

        if 'compounds' in self._model:
            for compound in parse_compound_list(
                    self._context, self._model['compounds']):
                yield compound
639420
function parse(str, opts) {
  var parser = new Parser(str, opts);
  return {attrs: parser._readProtocol(), imports: parser._imports};
}
834677
function (spec_str) {

	// Specification string
	this.specStr = spec_str;

	// Variable type
	this.VARIABLE_TYPES = ['BOOLEAN', 'FLOAT', 'INTEGER', 'NUMBER', 'STRING', 'TEXT'];
	this.type = null;

	// Range of value
	this.min = null;
	this.max = null;

	// Additonal options
	this.OPTION_KEYS = ['DEFAULT', 'REGEXP'];

	// Additonal options - Default value
	this.default = null;

	// Additonal options - Regular Expression for STRING or TEXT
	this.regExp = null;

	// ---

	// Parse the specification string
	this._parseSpec(this.specStr);

}
633369
def _parse_tsplib(f):
    """"""
    line = ''

    specs = {}

    used_specs = ['NAME', 'COMMENT', 'DIMENSION', 'CAPACITY', 'TYPE', 'EDGE_WEIGHT_TYPE']
    used_data = ['DEMAND_SECTION', 'DEPOT_SECTION']

    # Parse specs part
    for line in f:
        line = strip(line)

        # Arbitrary sort, so we test everything out
        s = None
        for s in used_specs:
            if line.startswith(s):
                specs[s] = line.split('{} :'.format(s))[-1].strip() # get value data part
                break

        if s == 'EDGE_WEIGHT_TYPE' and s in specs and specs[s] == 'EXPLICIT':
            used_specs.append('EDGE_WEIGHT_FORMAT')

        # All specs read
        if len(specs) == len(used_specs):
            break

    if len(specs) != len(used_specs):
        missing_specs = set(used_specs).symmetric_difference(set(specs))
        raise ParseException('Error parsing TSPLIB data: specs {} missing'.format(missing_specs))

    print(specs)

    if specs['EDGE_WEIGHT_TYPE'] == 'EUC_2D':
        used_data.append('NODE_COORD_SECTION')
    elif specs['EDGE_WEIGHT_FORMAT'] == 'FULL_MATRIX':
        used_data.append('EDGE_WEIGHT_SECTION')
    else:
        raise ParseException('EDGE_WEIGHT_TYPE or EDGE_WEIGHT_FORMAT not supported')

    _post_process_specs(specs)

    # Parse data part
    for line in f:
        line = strip(line)

        for d in used_data:
            if line.startswith(d):
                if d == 'DEPOT_SECTION':
                    specs[d] = _parse_depot_section(f)
                elif d in ['NODE_COORD_SECTION', 'DEMAND_SECTION']:
                    specs[d] = _parse_nodes_section(f, d, specs['DIMENSION'])
                elif d == 'EDGE_WEIGHT_SECTION':
                    specs[d] = _parse_edge_weight(f, specs['DIMENSION'])

        if len(specs) == len(used_specs) + len(used_data):
            break

    if len(specs) != len(used_specs) + len(used_data):
        missing_specs = set(specs).symmetric_difference(set(used_specs).union(set(used_data)))
        raise ParseException('Error parsing TSPLIB data: specs {} missing'.format(missing_specs))

    _post_process_data(specs)

    return specs
303784
private ParseTree parseExportSpecifier() {
    SourcePosition start = getTreeStartLocation();
    IdentifierToken importedName = eatIdOrKeywordAsId();
    IdentifierToken destinationName = null;
    if (peekPredefinedString(PredefinedName.AS)) {
      eatPredefinedString(PredefinedName.AS);
      destinationName = eatIdOrKeywordAsId();
    }
    return new ExportSpecifierTree(
        getTreeLocation(start), importedName, destinationName);
  }
1202242
def parse_reaction(s):
    """"""

    def parse_count(s):
        m = re.match(r'^\((.+)\)$', s)
        if m is not None:
            s = m.group(1)

        m = re.match(r'^\d+$', s)
        if m is not None:
            return int(m.group(0))

        return Expression(s)

    def parse_compound(s):
        m = re.match(r'(.+)\((.+)\)', s)
        if m is not None:
            return Compound(m.group(1), arguments=[Expression(m.group(2))])
        return Compound(s)

    def parse_compound_list(s):
        for cpd in s.split(' + '):
            if cpd == '':
                continue

            fields = cpd.strip().split(' ')
            if len(fields) > 2:
                raise ParseError(
                    'Malformed compound specification: {}'.format(cpd))
            if len(fields) == 1:
                count = 1
                compound = parse_compound(fields[0])
            else:
                count = parse_count(fields[0])
                compound = parse_compound(fields[1])

            yield compound, count

    cpd_left, cpd_right = s.split('<=>')
    left = parse_compound_list(cpd_left.strip())
    right = parse_compound_list(cpd_right.strip())

    return Reaction(Direction.Both, left, right)
1216496
def _parse(self):
        

        # CPE Name must not have whitespaces
        if (self._str.find(" ") != -1):
            msg = "Bad-formed CPE Name: it must not have whitespaces"
            raise ValueError(msg)

        # Partitioning of CPE Name
        parts_match = CPE2_3_FS._parts_rxc.match(self._str)

        # Validation of CPE Name parts
        if (parts_match is None):
            msg = "Bad-formed CPE Name: validation of parts failed"
            raise ValueError(msg)

        components = dict()
        parts_match_dict = parts_match.groupdict()

        for ck in CPEComponent.CPE_COMP_KEYS_EXTENDED:
            if ck in parts_match_dict:
                value = parts_match.group(ck)

                if (value == CPEComponent2_3_FS.VALUE_ANY):
                    comp = CPEComponentAnyValue()
                elif (value == CPEComponent2_3_FS.VALUE_NA):
                    comp = CPEComponentNotApplicable()
                else:
                    try:
                        comp = CPEComponent2_3_FS(value, ck)
                    except ValueError:
                        errmsg = "Bad-formed CPE Name: not correct value: {0}".format(
                            value)
                        raise ValueError(errmsg)
            else:
                errmsg = "Component {0} should be specified".format(ck)
                raise ValueError(ck)

            components[ck] = comp

        # #######################
        #  Storage of CPE Name  #
        # #######################

        part_comp = components[CPEComponent.ATT_PART]
        if isinstance(part_comp, CPEComponentLogical):
            elements = []
            elements.append(components)
            self[CPE.KEY_UNDEFINED] = elements
        else:
            # Create internal structure of CPE Name in parts:
            # one of them is filled with identified components,
            # the rest are empty
            system = parts_match.group(CPEComponent.ATT_PART)
            if system in CPEComponent.SYSTEM_VALUES:
                self._create_cpe_parts(system, components)
            else:
                self._create_cpe_parts(CPEComponent.VALUE_PART_UNDEFINED,
                                       components)

        # Fills the empty parts of internal structure of CPE Name
        for pk in CPE.CPE_PART_KEYS:
            if pk not in self.keys():
                # Empty part
                self[pk] = []