Returns a slash-formatted string from the given XML representation.
        The return value is a TokenString (for MBSP) or TaggedString (for Pattern).
963465
def parse_string(xml):
    
    string = ""
    # Traverse all the <sentence> elements in the XML.
    dom = XML(xml)
    for sentence in dom(XML_SENTENCE):
        _anchors.clear()     # Populated by calling _parse_tokens().
        _attachments.clear() # Populated by calling _parse_tokens().
        # Parse the language from <sentence language="">.
        language = sentence.get(XML_LANGUAGE, "en")
        # Parse the token tag format from <sentence token="">.
        # This information is returned in TokenString.tags,
        # so the format and order of the token tags is retained when exporting/importing as XML.
        format = sentence.get(XML_TOKEN, [WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA])
        format = not isinstance(format, basestring) and format or format.replace(" ","").split(",")
        # Traverse all <chunk> and <chink> elements in the sentence.
        # Find the <word> elements inside and create tokens.
        tokens = []
        for chunk in sentence:
            tokens.extend(_parse_tokens(chunk, format))
        # Attach PNP's to their anchors.
        # Keys in _anchors have linked anchor chunks (each chunk is a list of tokens).
        # The keys correspond to the keys in _attachments, which have linked PNP chunks.
        if ANCHOR in format:
            A, P, a, i = _anchors, _attachments, 1, format.index(ANCHOR)
            for id in sorted(A.keys()):
                for token in A[id]:
                    token[i] += "-"+"-".join(["A"+str(a+p) for p in range(len(P[id]))])
                    token[i]  = token[i].strip("O-")
                for p, pnp in enumerate(P[id]):
                    for token in pnp: 
                        token[i] += "-"+"P"+str(a+p)
                        token[i]  = token[i].strip("O-")
                a += len(P[id])
        # Collapse the tokens to string.
        # Separate multiple sentences with a new line.
        tokens = ["/".join([tag for tag in token]) for token in tokens]
        tokens = " ".join(tokens)
        string += tokens + "\n"
    # Return a TokenString, which is a unicode string that transforms easily
    # into a plain str, a list of tokens, or a Sentence.
    try:
        if MBSP: from mbsp import TokenString
        return TokenString(string.strip(), tags=format, language=language)
    except:
        return TaggedString(string.strip(), tags=format, language=language)
1223743
def pretty_xml(data):
    
    parsed_string = minidom.parseString(data.decode('utf-8'))
    return parsed_string.toprettyxml(indent='\t', encoding='utf-8')
378761
function getFormatStringFrom (formattedString) {
      var chunks = formattedString.match(R_FORMAT_CHUNKS);

      if (!chunks) {
        // chunks will be null if there were no tokens to parse in
        // formattedString (for example, if formattedString is '2').  Coerce
        // chunks to be useful here.
        chunks = ['', ''];

        // If there is only one chunk, assume that the string is a number
        // followed by a token...
        // NOTE: This may be an unwise assumption.
      } else if (chunks.length === 1 ||
          // ...or if the string starts with a number component (".", "-", or a
          // digit)...
          formattedString[0].match(R_NUMBER_COMPONENT)) {
        // ...prepend an empty string here to make sure that the formatted number
        // is properly replaced by VALUE_PLACEHOLDER
        chunks.unshift('');
      }

      return chunks.join(VALUE_PLACEHOLDER);
    }
205946
def xml(self, indent = ""):
        """"""
        xml = indent + "<" + self.__class__.__name__
        xml += ' id="'+self.id + '"'
        xml += ' name="'+xmlescape(self.name) + '"'
        xml += ' description="'+xmlescape(self.description) + '"'
        if self.paramflag:
            xml += ' flag="'+self.paramflag + '"'
        for key, v in self.kwargs.items():
            if key not in ('value','error','name','description','flag','paramflag', 'validator'):
                if isinstance(v, bool):
                    xml += ' ' + key + '="' + str(int(v))+ '"'
                elif isinstance(v, list):
                    xml += ' ' + key + '="'+xmlescape(",".join(v))+ '"'
                elif isinstance(v, str)  or ( sys.version < '3' and isinstance(v, unicode)): #pylint: disable=undefined-variable
                    xml += ' ' + key + '="'+xmlescape(v)+ '"'
                else:
                    xml += ' ' + key + '="'+xmlescape(str(v))+ '"'
        if self.hasvalue:
            if sys.version < '3':
                xml += ' value="'+xmlescape(unicode(self.value)) + '"' #pylint: disable=undefined-variable
            else:
                xml += ' value="'+xmlescape(str(self.value)) + '"'
        if self.error:
            xml += ' error="'+xmlescape(self.error) + '"'
        xml += " />"
        return xml
628379
def _to_string(self):
        
        return u"{}+{}@{}".format(text_type(self.definition_id), self.BLOCK_TYPE_PREFIX, self.block_type)
713351
def escapeXML( char )
      if @xmlEscapes.nil?
         @xmlEscapes = {}
         (0..255).each{ |i| @xmlEscapes[ i.chr ] = sprintf( "&#%03d;", i )  }
      end
      return @xmlEscapes[ char ] if @xmlEscapes[ char ]
      char
   end
825737
public static String decodeBackslash(String s) {
	  if(s==null || s.indexOf('\\')==-1) return(s);
    StringBuilder result = new StringBuilder();
    int[] eatLength = new int[1];
    while (s.length() != 0) {
      char c = eatBackslash(s, eatLength);
      if (eatLength[0] > 1) {
        result.append(c);
        s = s.substring(eatLength[0]);
      } else {
        result.append(s.charAt(0));
        s = s.substring(1);
      }
    }
    return (result.toString());
  }
199127
def xmltreefromstring(s):
    """"""
    if sys.version < '3':
        #Python 2
        if isinstance(s,unicode): #pylint: disable=undefined-variable
            s = s.encode('utf-8')
        try:
            return ElementTree.parse(StringIO(s), ElementTree.XMLParser(collect_ids=False))
        except TypeError:
            return ElementTree.parse(StringIO(s), ElementTree.XMLParser()) #older lxml, may leak!!!!
    else:
        #Python 3
        if isinstance(s,str):
            s = s.encode('utf-8')
        try:
            return ElementTree.parse(BytesIO(s), ElementTree.XMLParser(collect_ids=False))
        except TypeError:
            return ElementTree.parse(BytesIO(s), ElementTree.XMLParser())
886891
def back_slash_to_front_converter(string):
    
    try:
        if not string or not isinstance(string, str):
            return string
        return string.replace('\\', '/')
    except Exception:
        return string
507233
def to_string(self, indent="", newl="", addindent=""):
        '''
        
        '''
        buf = StringIO()
        self.to_xml().writexml(buf, indent=indent, addindent=addindent,
                               newl=newl)
        return buf.getvalue()
457250
private String consumeTokenString() throws JsonParserException {
    reusableBuffer.setLength(0);
    while (true) {
      char c = stringChar();

      switch (c) {
      case '\"':
        return reusableBuffer.toString();
      case '\\':
        int escape = advanceChar();
        switch (escape) {
        case -1:
          throw createParseException(null, "EOF encountered in the middle of a string escape", false);
        case 'b':
          reusableBuffer.append('\b');
          break;
        case 'f':
          reusableBuffer.append('\f');
          break;
        case 'n':
          reusableBuffer.append('\n');
          break;
        case 'r':
          reusableBuffer.append('\r');
          break;
        case 't':
          reusableBuffer.append('\t');
          break;
        case '"':
        case '/':
        case '\\':
          reusableBuffer.append((char)escape);
          break;
        case 'u':
          reusableBuffer.append((char)(stringHexChar() << 12 | stringHexChar() << 8 //
              | stringHexChar() << 4 | stringHexChar()));
          break;
        default:
          throw createParseException(null, "Invalid escape: \\" + (char)escape, false);
        }
        break;
      default:
        reusableBuffer.append(c);
      }
    }
  }
115608
def to_xml_string(str = '')
      # macro attribute should be optional!
      str << '<xdr:graphicFrame>'
      str << '<xdr:nvGraphicFramePr>'
      str << ('<xdr:cNvPr id="' << @anchor.drawing.index.to_s << '" name="' << 'item_' << @anchor.drawing.index.to_s << '"/>')
      str << '<xdr:cNvGraphicFramePr/>'
      str << '</xdr:nvGraphicFramePr>'
      str << '<xdr:xfrm>'
      str << '<a:off x="0" y="0"/>'
      str << '<a:ext cx="0" cy="0"/>'
      str << '</xdr:xfrm>'
      str << '<a:graphic>'
      str << ('<a:graphicData uri="' << XML_NS_C << '">')
      str << ('<c:chart xmlns:c="' << XML_NS_C << '" xmlns:r="' << XML_NS_R << '" r:id="' << rId << '"/>')
      str << '</a:graphicData>'
      str << '</a:graphic>'
      str << '</xdr:graphicFrame>'
    end
289893
public String convertString(String string)
    {
        if (string.indexOf("<xsl:import") != -1)
        {
            int iStart = string.indexOf("href=\"") + 6;
            int iEnd = string.indexOf('\"', iStart);
            if (iStart != 5)
                if (iEnd != -1)
                {
                    String strFilename = string.substring(iStart, iEnd);
                    
                    m_writer.write("<!-- " + "Import inlined from: " + strFilename + " - Do not modify this generated file." + "-->");
                    m_writer.println();
        
                    this.writeImport(strFilename);
                }
            return null;
        }
        if (Boolean.FALSE.toString().equals(this.getProperty(ROOT_FILE)))
        {
            if (string.indexOf("xsl:stylesheet") != -1)
                m_bSkipTag = true;
            if (string.indexOf("<?xml version=") != -1)
                m_bSkipTag = true;
        //          if (string.indexOf("<xsl:output method=") != -1)
        //              m_bSkipTag = true;
        }
        if (m_bSkipTag)
        {
            if (string.indexOf('>') != -1)
                m_bSkipTag = false;
            return null;
        }
        if (string.indexOf("<xsl:template ") != -1)
        {
            int iStart = string.indexOf("match=\"") + 7;
            int iEnd = string.indexOf('\"', iStart);
            if (iStart != 6)
                if (iEnd != -1)
                {
                    String strMatch = string.substring(iStart, iEnd);
                    if (m_parent instanceof XslImportScanListener)
                        m_bSkipTemplate = ((XslImportScanListener)m_parent).isMatch(strMatch);
                    if (!m_bSkipTemplate)
                        if (m_parent instanceof XslImportScanListener)
                            ((XslImportScanListener)m_parent).addMatch(strMatch, true);   // Make sure no one else adds it
                    if (m_bSkipTemplate)
                        System.out.println("Skip match " + strMatch);
        
                }               
            iStart = string.indexOf("name=\"") + 6;
            iEnd = string.indexOf('\"', iStart);
            if (iStart != 5)
                if (iEnd != -1)
                {
                    String strName = string.substring(iStart, iEnd);
                    if (m_parent instanceof XslImportScanListener)
                        m_bSkipTemplate = ((XslImportScanListener)m_parent).isName(strName);
                    if (!m_bSkipTemplate)
                        if (m_parent instanceof XslImportScanListener)
                            ((XslImportScanListener)m_parent).addName(strName, true); // Make sure no one else adds it
                    if (m_bSkipTemplate)
                        System.out.println("Skip name " + strName);
                }               
        }
        if (m_bSkipTemplate)
        {
            if (string.indexOf("</xsl:template>") != -1)
                m_bSkipTemplate = false;
            return null;
        }
        return string;
    }
683002
@Override
  public final String xmlEscape(final char pChar) throws Exception {
    if (pChar == '<') {
      return "&lt;";
    } else if (pChar == '>') {
      return "&gt;";
    } else if (pChar == '"') {
      return "&quot;";
    } else if (pChar == '\'') {
      return "&apos;";
    } else if (pChar == '&') {
      return "&amp;";
    }
    return String.valueOf(pChar);
  }
316670
protected Token fetchString() {
        char separator = input.current().getValue();
        char escapeChar = stringDelimiters.get(input.current().getValue());
        Token result = Token.create(Token.TokenType.STRING, input.current());
        result.addToTrigger(input.consume());
        while (!input.current().isNewLine() && !input.current().is(separator) && !input.current().isEndOfInput()) {
            if (escapeChar != '\0' && input.current().is(escapeChar)) {
                result.addToSource(input.consume());
                if (!handleStringEscape(separator, escapeChar, result)) {
                    problemCollector.add(ParseError.error(input.next(),
                                                          String.format("Cannot use '%s' as escaped character",
                                                                        input.next().getStringValue())));
                }
            } else {
                result.addToContent(input.consume());
            }
        }
        if (input.current().is(separator)) {
            result.addToSource(input.consume());
        } else {
            problemCollector.add(ParseError.error(input.current(), "Premature end of string constant"));
        }
        return result;
    }
604908
def toString(self):
        
        xprofile = self.toXml()
        projex.text.xmlindent(xprofile)
        return ElementTree.tostring(xprofile)
202999
def format_str(self):
        '''  '''
        if self.static:
            return self.route.replace('%','%%')
        out, i = '', 0
        for token, value in self.tokens():
            if token == 'TXT': out += value.replace('%','%%')
            elif token == 'ANON': out += '%%(anon%d)s' % i; i+=1
            elif token == 'VAR': out += '%%(%s)s' % value[1]
        return out