Given a string of RST, use docutils to generate html
547881
def rst_to_html(input_string: str) -> str:
    

    overrides = dict(input_encoding='unicode', doctitle_xform=True,
                     initial_header_level=1)
    parts = publish_parts(
        writer_name='html',
        source=input_string,
        settings_overrides=overrides
    )
    return parts['html_body']
235666
def htmlFormat(output, pathParts = (), statDict = None, query = None):
  """"""
  statDict = statDict or scales.getStats()
  if query:
    statDict = runQuery(statDict, query)
  _htmlRenderDict(pathParts, statDict, output)
793546
function HTMLOfENML(text, resources){

    resources = resources || [];

    var resource_map = {}
    resources.forEach(function(resource){

      var hex = [].map.call( resource.data.bodyHash, 
        function(v) { str = v.toString(16); 
        return str.length < 2 ? "0" + str : str;  }).join("");

      resource_map[hex] = resource;
    })

    var writer = new XMLWriter();
    var parser = new SaxParser(function(cb) {

      var mediaTagStarted = false;
      var linkTagStarted = false;
      var linkTitle;

      cb.onStartElementNS(function(elem, attrs, prefix, uri, namespaces) {

        if(elem == 'en-note'){
          writer.startElement('html');
          writer.startElement('head');

          writer.startElement('meta');
          writer.writeAttribute('http-equiv', 'Content-Type');
          writer.writeAttribute('content', 'text/html; charset=UTF-8');
          writer.endElement();

          writer.endElement();

          writer.startElement('body');
          if(!(attrs && attrs[0] && attrs[0][0] && attrs[0][0] === 'style'))
            writer.writeAttribute('style', 'word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;');
        } else if(elem == 'en-todo'){

          writer.startElement('input');
          writer.writeAttribute('type', 'checkbox');

        } else if(elem == 'en-media'){

          var type = null;
          var hash = null;
          var width = 0;
          var height = 0;

          if(attrs) attrs.forEach(function(attr) {
            if(attr[0] == 'type') type = attr[1];
            if(attr[0] == 'hash') hash = attr[1];
            if(attr[0] == 'width') width = attr[1];
            if(attr[0] == 'height') height = attr[1];
          });

          var resource = resource_map[hash];
          
          if(!resource) return;
          var resourceTitle = resource.title || '';
          
          if(type.match('image')) {

            writer.startElement('img');
            writer.writeAttribute('title', resourceTitle);

          } else if(type.match('audio')) {
            
            
            writer.writeElement('p', resourceTitle);
            writer.startElement('audio');
            writer.writeAttribute('controls', '');
            writer.text('Your browser does not support the audio tag.');
            writer.startElement('source');
            mediaTagStarted = true;

          } else if(type.match('video')) {
            writer.writeElement('p', resourceTitle);
            writer.startElement('video');
            writer.writeAttribute('controls', '');
            writer.text('Your browser does not support the video tag.');
            writer.startElement('source');
            mediaTagStarted = true;
          } else {
            writer.startElement('a');
            linkTagStarted = true;
            linkTitle = resourceTitle;
          }
          
          if(resource.data.body) {
            var b64encoded = base64ArrayBuffer(resource.data.body);
            var src = 'data:'+type+';base64,'+b64encoded;
            writer.writeAttribute('src', src)
          }

          if(width) writer.writeAttribute ('width', width);
          if(height) writer.writeAttribute('height', height);

        } else {
          writer.startElement(elem);
        }

        if(attrs) attrs.forEach(function(attr) {
          writer.writeAttribute(attr[0], attr[1]);
        });

      });
      cb.onEndElementNS(function(elem, prefix, uri) {

        if(elem == 'en-note'){
          writer.endElement(); //body
          writer.endElement(); //html
        }
        else if(elem == 'en-todo'){

        }
        else if(elem == 'en-media'){
          if(mediaTagStarted) {
            writer.endElement(); // source
            writer.endElement(); // audio or video
            writer.writeElement('br', '');
            mediaTagStarted = false;

          } else if(linkTagStarted) {
            writer.text(linkTitle);
            writer.endElement(); // a
            linkTagStarted = false;

          } else {
            writer.endElement();
          }

        } else {

          writer.endElement();
        }
      });
      cb.onCharacters(function(chars) {
        writer.text(chars);
      });

    });

    parser.parseString(text);
    return writer.toString();

  }
144338
def html(self, text=TEXT):
        
        self.logger.debug("Generating the HTML report{}..."
                          .format(["", " (text only)"][text]))
        html = []
        for piece in self._pieces:
            if isinstance(piece, string_types):
                html.append(markdown2.markdown(piece, extras=["tables"]))
            elif isinstance(piece, Element):
                html.append(piece.html())
        return "\n\n".join(html)
1225098
function unescapeHTML(html, nestingDepth) {
  var div = document.createElement('div');
  for (var i = 0; i < nestingDepth; i++) {
    div.innerHTML = `<iframe srcdoc="${html}"></iframe>`;
    html = div.childNodes[0].attributes.srcdoc.value;
  }
  return html;
}
221006
def convert_text(filename):
    """"""
    text_content = open(filename, "r")
    if ".md" in filename:
        text_cont1 = "\n" + markdown.markdown(text_content.read()) + "\n"
    elif ".docx" in filename:
        with open(os.path.join(cwd, "content", filename), "rb") as docx_file:
            result = mammoth.convert_to_html(docx_file)
            final_docx_html = result.value
        text_cont1 = "\n" + final_docx_html + "\n"
    elif ".tile" in filename:
        text_cont1 = "\n" + textile.textile(text_content.read()) + "\n"
    elif ".jade" in filename:
        text_cont1 = "\n" + pyjade.simple_convert(text_content.read()) + "\n"
    elif ".rst" in filename:
        text_cont1 = "\n" + \
            publish_parts(text_content.read(), writer_name='html')[
                'html_body'] + "\n"
    elif ".html" in filename:
        text_cont1 = text_content.read()
    elif ".txt" in filename:
        text_cont1 = text_content.read()
    else:
        print(filename + " is not a valid file type!")
        text_cont1 = "NULL"

    return text_cont1 + "\n\n"
1373620
def fromstring(cls, rs3_string):
        """"""
        temp = tempfile.NamedTemporaryFile(delete=False)
        temp.write(rs3_string)
        temp.close()
        rst_tree = cls(rs3_file=temp.name)
        os.unlink(temp.name)
        return rst_tree
1253962
def _parse_docstring(docstring):
    """"""
    params = {}

    if not docstring:
        return None, params

    try:
        help_msg = _DOCSTRING_REGEX.search(docstring).group()
        help_msg = _strip_lines(help_msg)
    except AttributeError:
        help_msg = None

    for param in _DOCSTRING_PARAM_REGEX.finditer(docstring):
        param_definition = param.group(1).rsplit(' ', 1)
        if len(param_definition) == 2:
            param_type, param_name = param_definition
        else:
            param_type = None
            param_name = param_definition[0]

        param_help = param.group(2).strip()
        params[param_name] = param_type, _strip_lines(param_help)
    return help_msg, params
909606
function generateMarkdown (doc, functions) {
  let text = ''

  // TODO: should escape HTML characters in text

  text += '<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->\n\n'

  text += '# Function ' + doc.name + '\n\n'

  text += doc.description + '\n\n\n'

  if (doc.syntax && doc.syntax.length) {
    text += '## Syntax\n\n' +
        '```js\n' +
        doc.syntax.join('\n') +
        '\n```\n\n'
  }

  if (doc.where && doc.where.length) {
    text += '### Where\n\n' + doc.where.join('\n') + '\n\n'
  }

  text += '### Parameters\n\n' +
      'Parameter | Type | Description\n' +
      '--------- | ---- | -----------\n' +
      doc.parameters.map(function (p) {
        return '`' + p.name + '` | ' +
            (p.types ? p.types.join(' &#124; ') : '') + ' | ' +
            p.description
      }).join('\n') +
      '\n\n'

  if (doc.returns) {
    text += '### Returns\n\n' +
        'Type | Description\n' +
        '---- | -----------\n' +
        (doc.returns.types ? doc.returns.types.join(' &#124; ') : '') + ' | ' + doc.returns.description +
        '\n\n\n'
  }

  if (doc.examples && doc.examples.length) {
    text += '## Examples\n\n' +
        '```js\n' +
        doc.examples.join('\n') +
        '\n```\n\n\n'
  }

  if (doc.seeAlso && doc.seeAlso.length) {
    text += '## See also\n\n' +
        doc.seeAlso.map(function (name) {
          return '[' + name + '](' + name + '.md)'
        }).join(',\n') +
        '\n'
  }

  return text
}
176240
def save(ctx, dest="docs.html", format="html"):
    """"""
    print("STEP: Generate docs in HTML format")
    build(ctx, builder=format)

    print("STEP: Save docs under %s/" % dest)
    source_dir = Path(ctx.config.sphinx.destdir)/format
    Path(dest).rmtree_p()
    source_dir.copytree(dest)

    # -- POST-PROCESSING: Polish up.
    for part in [ ".buildinfo", ".doctrees" ]:
        partpath = Path(dest)/part
        if partpath.isdir():
            partpath.rmtree_p()
        elif partpath.exists():
            partpath.remove_p()
783896
def strip_rst(docs):
    '''
    
    '''
    for func, docstring in six.iteritems(docs):
        log.debug('Stripping docstring for %s', func)
        if not docstring:
            continue
        docstring_new = docstring if six.PY3 else salt.utils.data.encode(docstring)
        for regex, repl in (
                (r' *.. code-block:: \S+\n{1,2}', ''),
                ('.. note::', 'Note:'),
                ('.. warning::', 'Warning:'),
                ('.. versionadded::', 'New in version'),
                ('.. versionchanged::', 'Changed in version')):
            if six.PY2:
                regex = salt.utils.data.encode(regex)
                repl = salt.utils.data.encode(repl)
            try:
                docstring_new = re.sub(regex, repl, docstring_new)
            except Exception:
                log.debug(
                    'Exception encountered while matching regex %r to '
                    'docstring for function %s', regex, func,
                    exc_info=True
                )
        if six.PY2:
            docstring_new = salt.utils.data.decode(docstring_new)
        if docstring != docstring_new:
            docs[func] = docstring_new
    return docs
1270904
def clean_html(self, html):
        """"""
        result_type = type(html)
        if isinstance(html, six.string_types):
            doc = html_fromstring(html)
        else:
            doc = copy.deepcopy(html)
        self(doc)
        if issubclass(result_type, six.binary_type):
            return tostring(doc, encoding='utf-8')
        elif issubclass(result_type, six.text_type):
            return tostring(doc, encoding='unicode')
        else:
            return doc
144643
def _from_docstring_rst(doc):
    

    def format_fn(line, status):
        """ format function """

        if re_from_data.match(line):
            line = re_from_data.sub(r"**\1** ", line)
            status["add_line"] = True
        line = re_from_defaults.sub(r"*\1*", line)
        if status["listing"]:
            # parameters
            if re_from_param.match(line):
                m = re_from_param.match(line)
                line = "  - ``{}`` {}".format(m.group(1), m.group(3))
            # status items
            elif re_from_status.match(line):
                m = re_from_status.match(line)
                line = "  - ``{}`` {}".format(m.group(1), m.group(3))
            # bullets
            elif re_from_item.match(line):
                line = re_from_item.sub(r"  -", line)
            # is continuation line
            else:
                line = " " * 4 + line.lstrip()
        # in .rst format code samples use double backticks vs single ones for
        # .md This converts them.
        line = re_lone_backtick.sub("``", line)
        return line

    return _reformat_docstring(doc, format_fn, code_newline="\n")
804870
def get_rst_excerpt(rst_doc: document, paragraphs: int = 1) -> str:
    

    texts = []
    for count, p in enumerate(rst_doc.traverse(paragraph)):
        texts.append(p.astext())
        if count + 1 == paragraphs:
            break
    return ' '.join(texts)
443271
function html(obj, indents) {
  indents = indents || 1;

  function indent() {
    return Array(indents).join('  ');
  }

  if ('string' == typeof obj) {
    var str = escape(obj);
    if (urlRegex().test(obj)) {
      str = '<a href="' + str + '">' + str + '</a>';
    }
    return span('string value', '"' + str + '"');
  }

  if ('number' == typeof obj) {
    return span('number', obj);
  }

  if ('boolean' == typeof obj) {
    return span('boolean', obj);
  }

  if (null === obj) {
    return span('null', 'null');
  }

  var buf;

  if (Array.isArray(obj)) {
    ++indents;

    buf = '[\n' + obj.map(function(val){
      return indent() + html(val, indents);
    }).join(',\n');

    --indents;
    buf += '\n' + indent() + ']';
    return buf;
  }

  buf = '{';
  var keys = Object.keys(obj);
  var len = keys.length;
  if (len) buf += '\n';

  ++indents;
  buf += keys.map(function(key){
    var val = obj[key];
    key = '"' + key + '"';
    key = span('string key', key);
    return indent() + key + ': ' + html(val, indents);
  }).join(',\n');
  --indents;

  if (len) buf += '\n' + indent();
  buf += '}';

  return buf;
}
196917
function HTML(strings, ...values) {
  var dummy = document.createElement('div');
  var fragment = document.createDocumentFragment();
  dummy.innerHTML = compose(strings, ...values);
  forEach.call(dummy.childNodes, appendChild, fragment);
  return fragment;
}
1182860
def rst_to_docs_rst(infile, outfile):
    """"""

    # Read infile into a list of lines
    with open(infile, 'r') as fin:
        rst = fin.readlines()

    # Inspect outfile path components to determine whether outfile
    # is in the root of the examples directory or in a subdirectory
    # thererof
    ps = pathsplit(outfile)[-3:]
    if ps[-2] == 'examples':
        ps = ps[-2:]
        idx = 'index'
    else:
        idx = ''

    # Output string starts with a cross-reference anchor constructed from
    # the file name and path
    out = '.. _' + '_'.join(ps) + ':\n\n'

    # Iterate over lines from infile
    it = iter(rst)
    for line in it:
        if line[0:12] == '.. toc-start':  # Line has start of toc marker
            # Initialise current toc array and iterate over lines until
            # end of toc marker encountered
            toc = []
            for line in it:
                if line == '\n':  # Drop newline lines
                    continue
                elif line[0:10] == '.. toc-end':  # End of toc marker
                    # Add toctree section to output string
                    out += '.. toctree::\n   :maxdepth: 1\n\n'
                    for c in toc:
                        out += '   %s <%s>\n' % c
                    break
                else:  #  Still within toc section
                    # Extract link text and target url and append to
                    # toc array
                    m = re.search(r'`(.*?)\s*<(.*?)(?:.py)?>`', line)
                    if m:
                        if idx == '':
                            toc.append((m.group(1), m.group(2)))
                        else:
                            toc.append((m.group(1),
                                        os.path.join(m.group(2), idx)))
        else:  # Not within toc section
            out += line

    with open(outfile, 'w') as fout:
        fout.write(out)