Create report in html format
515596
def report(args):
    
    logger.info("reading sequeces")
    data = load_data(args.json)

    logger.info("create profile")
    data = make_profile(data, os.path.join(args.out, "profiles"), args)
    logger.info("create database")
    make_database(data, "seqcluster.db", args.out)

    logger.info("Done. Download https://github.com/lpantano/seqclusterViz/archive/master.zip to browse the output.")
1200489
def generate_report(self):
        """"""
        logs_path = self.out_dir / 'logs'

        boilerplate = []
        boiler_idx = 0

        if (logs_path / 'CITATION.html').exists():
            text = (logs_path / 'CITATION.html').read_text(encoding='UTF-8')
            text = '<div class="boiler-html">%s</div>' % re.compile(
                '<body>(.*?)</body>',
                re.DOTALL | re.IGNORECASE).findall(text)[0].strip()
            boilerplate.append((boiler_idx, 'HTML', text))
            boiler_idx += 1

        if (logs_path / 'CITATION.md').exists():
            text = '<pre>%s</pre>\n' % (logs_path / 'CITATION.md').read_text(encoding='UTF-8')
            boilerplate.append((boiler_idx, 'Markdown', text))
            boiler_idx += 1

        if (logs_path / 'CITATION.tex').exists():
            text = (logs_path / 'CITATION.tex').read_text(encoding='UTF-8')
            text = re.compile(
                r'\\begin{document}(.*?)\\end{document}',
                re.DOTALL | re.IGNORECASE).findall(text)[0].strip()
            text = '<pre>%s</pre>\n' % text
            text += '<h3>Bibliography</h3>\n'
            text += '<pre>%s</pre>\n' % Path(
                pkgrf(self.packagename, 'data/boilerplate.bib')).read_text(encoding='UTF-8')
            boilerplate.append((boiler_idx, 'LaTeX', text))
            boiler_idx += 1

        env = jinja2.Environment(
            loader=jinja2.FileSystemLoader(searchpath=str(self.template_path.parent)),
            trim_blocks=True, lstrip_blocks=True
        )
        report_tpl = env.get_template(self.template_path.name)
        report_render = report_tpl.render(sections=self.sections, errors=self.errors,
                                          boilerplate=boilerplate)

        # Write out report
        (self.out_dir / self.out_filename).write_text(report_render, encoding='UTF-8')
        return len(self.errors)
1337315
def gen_report(report, sdir='./', report_name='report.html'):
    

    # Create report directory
    if not os.path.exists(sdir):
        os.makedirs(sdir)

    # Add a slash to file directory if not included to avoid DirNameFleName
    # instead of DirName/FileName being creaated
    if sdir[-1] != '/':
        sdir += '/'

    report_html = '<html><body>'

    if 'method' in report.keys():

        report_html += "<h1>Method: " + report['method'] + "</h1><p>"

        for i in report[report['method']]:

            if i == 'taper_window':

                fig, ax = plt.subplots(1)
                ax.plot(report[report['method']]['taper_window'],
                        report[report['method']]['taper'])
                ax.set_xlabel('Window (time). 0 in middle of window.')
                ax.set_title(
                    'Taper from ' + report[report['method']]['distribution'] + ' distribution (PDF).')
                fig.savefig(sdir + 'taper.png')

                report_html += "<img src='./taper.png' width=500>" + "<p>"

            else:

                report_html += "- <b>" + i + "</b>: " + \
                    str(report[report['method']][i]) + "<br>"

    if 'postprocess' in report.keys():

        report_html += "<p><h2>Postprocessing:</h2><p>"

        report_html += "<b>Pipeline: </b>"

        for i in report['postprocess']:

            report_html += " " + i + ","

        for i in report['postprocess']:

            report_html += "<p><h3>" + i + "</h3><p>"

            for j in report[i]:

                if j == 'lambda':

                    report_html += "- <b>" + j + "</b>: " + "<br>"

                    lambda_val = np.array(report['boxcox']['lambda'])
                    fig, ax = plt.subplots(1)
                    ax.hist(lambda_val[:, -1])
                    ax.set_xlabel('lambda')
                    ax.set_ylabel('frequency')
                    ax.set_title('Histogram of lambda parameter')
                    fig.savefig(sdir + 'boxcox_lambda.png')

                    report_html += "<img src='./boxcox_lambda.png' width=500>" + "<p>"
                    report_html += "Data located in " + sdir + "boxcox_lambda.csv <p>"

                    np.savetxt(sdir + "boxcox_lambda.csv",
                               lambda_val, delimiter=",")

                else:

                    report_html += "- <b>" + j + "</b>: " + \
                        str(report[i][j]) + "<br>"

    report_html += '</body></html>'

    with open(sdir + report_name, 'w') as file:
        file.write(report_html)
    file.close()
210067
def to_html(ds: Any) -> str:
	
	rm = min(10, ds.shape[0])
	cm = min(10, ds.shape[1])
	html = "<p>"
	if ds.attrs.__contains__("title"):
		html += "<strong>" + ds.attrs["title"] + "</strong> "
	html += f"{ds.shape[0]} rows, {ds.shape[1]} columns, {len(ds.layers)} layer{'s' if len(ds.layers) > 1 else ''}<br/>(showing up to 10x10)<br/>"
	html += ds.filename + "<br/>"
	for (name, val) in ds.attrs.items():
		html += f"name: <em>{val}</em><br/>"
	html += "<table>"
	# Emit column attributes
	for ca in ds.col_attrs.keys():
		html += "<tr>"
		for ra in ds.row_attrs.keys():
			html += "<td>&nbsp;</td>"  # Space for row attrs
		html += "<td><strong>" + ca + "</strong></td>"  # Col attr name
		for v in ds.col_attrs[ca][:cm]:
			html += "<td>" + str(v) + "</td>"
		if ds.shape[1] > cm:
			html += "<td>...</td>"
		html += "</tr>"

	# Emit row attribute names
	html += "<tr>"
	for ra in ds.row_attrs.keys():
		html += "<td><strong>" + ra + "</strong></td>"  # Row attr name
	html += "<td>&nbsp;</td>"  # Space for col attrs
	for v in range(cm):
		html += "<td>&nbsp;</td>"
	if ds.shape[1] > cm:
		html += "<td>...</td>"
	html += "</tr>"

	# Emit row attr values and matrix values
	for row in range(rm):
		html += "<tr>"
		for ra in ds.row_attrs.keys():
			html += "<td>" + str(ds.row_attrs[ra][row]) + "</td>"
		html += "<td>&nbsp;</td>"  # Space for col attrs

		for v in ds[row, :cm]:
			html += "<td>" + str(v) + "</td>"
		if ds.shape[1] > cm:
			html += "<td>...</td>"
		html += "</tr>"
	# Emit ellipses
	if ds.shape[0] > rm:
		html += "<tr>"
		for v in range(rm + 1 + len(ds.row_attrs.keys())):
			html += "<td>...</td>"
		if ds.shape[1] > cm:
			html += "<td>...</td>"
		html += "</tr>"
	html += "</table>"
	return html
607196
def _create_text_report(inputfile, motifs, closest_match, stats, outdir):
    """"""
    my_stats = {}
    for motif in motifs:
        match = closest_match[motif.id]
        my_stats[str(motif)] = {}
        for bg in list(stats.values())[0].keys():
            if str(motif) not in stats:
                logger.error("####")
                logger.error("{} not found".format(str(motif)))
                for s in sorted(stats.keys()):
                    logger.error(s)
                logger.error("####")
            else:
                my_stats[str(motif)][bg] = stats[str(motif)][bg].copy()
                my_stats[str(motif)][bg]["best_match"] = "_".join(match[0].split("_")[:-1])
                my_stats[str(motif)][bg]["best_match_pvalue"] = match[1][-1]
    
    header = ("# GimmeMotifs version {}\n"
             "# Inputfile: {}\n"
             ).format(__version__, inputfile)

    write_stats(my_stats, os.path.join(outdir, "stats.{}.txt"), header=header)
869443
def as_html(self, max_rows=0):
        """"""
        if not max_rows or max_rows > self.num_rows:
            max_rows = self.num_rows
        omitted = max(0, self.num_rows - max_rows)
        labels = self.labels
        lines = [
            (0, '<table border="1" class="dataframe">'),
            (1, '<thead>'),
            (2, '<tr>'),
            (3, ' '.join('<th>' + label + '</th>' for label in labels)),
            (2, '</tr>'),
            (1, '</thead>'),
            (1, '<tbody>'),
        ]
        fmts = self._get_column_formatters(max_rows, True)
        for row in itertools.islice(self.rows, max_rows):
            lines += [
                (2, '<tr>'),
                (3, ' '.join('<td>' + fmt(v, label=False) + '</td>' for
                    v, fmt in zip(row, fmts))),
                (2, '</tr>'),
            ]
        lines.append((1, '</tbody>'))
        lines.append((0, '</table>'))
        if omitted:
            lines.append((0, '<p>... ({} rows omitted)</p>'.format(omitted)))
        return '\n'.join(4 * indent * ' ' + text for indent, text in lines)
292777
def generate_xhtml(path, dirs, files):
    """"""
    # Prepare the path to display.
    if path != '/':
        dirs.insert(0, '..')
    if not path.endswith('/'):
        path += '/'

    def itemize(item):
        return '<a href="%s">%s</a>' % (item, path+item)
    dirs = [d + '/' for d in dirs]
    return """
    <html>
     <body>
      <h1>%s</h1>
       <pre>%s\n%s</pre>
     </body>
    </html>
    """ % (path, '\n'.join(itemize(dir) for dir in dirs), '\n'.join(itemize(file) for file in files))
38731
public static String reportToXml(Report report) {
		XStream xstream = XStreamFactory.createXStream();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		xstream.toXML(report, bos);
		return bos.toString();
	}
275605
def build_report
      options = ReportBuilder.options

      groups = get_groups options[:input_path]

      json_report_path = options[:json_report_path] || options[:report_path]
      if options[:report_types].include? 'JSON'
        File.open(json_report_path + '.json', 'w') do |file|
          file.write JSON.pretty_generate(groups.size > 1 ? groups : groups.first['features'])
        end
      end

      if options[:additional_css] and Pathname.new(options[:additional_css]).file?
        options[:additional_css] = File.read(options[:additional_css])
      end

      if options[:additional_js] and Pathname.new(options[:additional_js]).file?
        options[:additional_js] = File.read(options[:additional_js])
      end

      html_report_path = options[:html_report_path] || options[:report_path]
      if options[:report_types].include? 'HTML'
        File.open(html_report_path + '.html', 'w') do |file|
          file.write get(groups.size > 1 ? 'group_report' : 'report').result(binding).gsub('  ', '').gsub("\n\n", '')
        end
      end

      retry_report_path = options[:retry_report_path] || options[:report_path]
      if options[:report_types].include? 'RETRY'
        File.open(retry_report_path + '.retry', 'w') do |file|
          groups.each do |group|
            group['features'].each do |feature|
              if feature['status'] == 'broken'
                feature['elements'].each do |scenario|
                  file.puts "#{feature['uri']}:#{scenario['line']}" if scenario['status'] == 'failed'
                end
              end
            end
          end
        end
      end
      [json_report_path, html_report_path, retry_report_path]
    end
859345
function (collector, options) {
	if (typeof options == 'string' || options instanceof String) {
		// default to html report at options directory
		writeReport('html', {
			dir: options
		}, collector);
	} else if (options instanceof Array) {
		// multiple reports
		for (var i = 0; i < options.length; i = i + 1) {
			var report = options[i];
			writeReport(report.type, report.options, collector);
		}
	} else {
		// single report
		writeReport(options.type, options.options, collector);
	}
}
1247020
def make_html_page(self, valumap):
        
        logger.info('Making an html report using template %r.', self.html_template)
        fh = open(self.html_template)
        template = fh.read()
        fh.close()

        parts = []
        for sr in self.subreports:
            report_data = [item.html for item in sr.report_data if item.html]
            if report_data:
                parts.append('\n<h2>{1}</h2>\n'.format(sr.title, sr.reptext))
                parts.extend(report_data)
                parts.append('\n<hr/>')
        
        valumap['subreports'] = '\n'.join(parts) # or "\n<<NO SUBREPORT RELATED EVENTS>>\n"
        html_page = Template(template).safe_substitute(valumap)
        return TextPart(fmt='html', text=html_page, ext='html')
7084
private void generateHTMLReport(BufferedWriter writer, BufferedReader templateReader, String jsonReport)
            throws IOException {

        logger.entering(new Object[] { writer, templateReader, jsonReport });

        String readLine = null;
        while ((readLine = templateReader.readLine()) != null) {
            if (readLine.trim().equals("${reports}")) {
                writer.write(jsonReport);
                writer.newLine();
            } else {
                writer.write(readLine);
                writer.newLine();
            }
        }
        logger.exiting();
    }
719410
def _init_report(self):
        """"""
        self.sections = []
        self.section_names = []


        # if the directory already exists, print a warning
        try:
            if os.path.isdir(self.directory) is False:
                if self.verbose:
                    print("Created directory {}".format(self.directory))
                os.mkdir(self.directory)
            # list of directories created in the constructor
            for this in self._to_create:
                try:
                    os.mkdir(self.directory + os.sep + this)
                except:
                    pass # already created ?
        except Exception:
            pass
        finally:
            # Once the main directory is created, copy files required
            temp_path = easydev.get_package_location("reports")
            temp_path += os.sep + "reports" + os.sep + "resources"

            # Copy the CSS from reports/resources/css
            filenames = glob.glob(os.sep.join([temp_path, "css", "*.css"]))

            # If there are CSS in the directory with JINJA templates, use them
            # as well
            filenames += glob.glob(os.sep.join([self.searchpath, '*.css']))


            # In addition, the user may also provide his own CSS as a list
            filenames += self.extra_css_list
            for filename in filenames:
                target = os.sep.join([self.directory, 'css' ])
                if os.path.isfile(target) is False:
                    shutil.copy(filename, target)

            # We copy all javascript from reports resources
            for filename in ['sorttable.js', 'highlight.pack.js', "jquery-1.12.3.min.js"]:
                target = os.sep.join([self.directory, 'js', filename ])
                if os.path.isfile(target) is False:
                    filename = os.sep.join([temp_path, "javascript", filename])
                    shutil.copy(filename, target)
            for filename in self.extra_js_list:
                basename = os.path.basename(filename)
                target = os.sep.join([self.directory, 'js', basename ])
                if os.path.isfile(target) is False:
                    shutil.copy(filename, target)
815858
def to_html(doc, output="/tmp", style="dep"):
    
    # generate filename from first six non-punct tokens
    file_name = "-".join([w.text for w in doc[:6] if not w.is_punct]) + ".html"
    html = displacy.render(doc, style=style, page=True)  # render markup
    if output is not None:
        output_path = Path(output)
        if not output_path.exists():
            output_path.mkdir()
        output_file = Path(output) / file_name
        output_file.open("w", encoding="utf-8").write(html)  # save to file
        print("Saved HTML to {}".format(output_file))
    else:
        print(html)
70329
def printFromHTML(self, sr_html):
        
        # HTML written to debug file
        debug_mode = App.config.getConfiguration().debug_mode
        if debug_mode:
            tmp_fn = tempfile.mktemp(suffix=".html")
            open(tmp_fn, "wb").write(sr_html)

        # Creates the pdf
        # we must supply the file ourself so that createPdf leaves it alone.
        pdf_fn = tempfile.mktemp(suffix=".pdf")
        pdf_report = createPdf(htmlreport=sr_html, outfile=pdf_fn)
        return pdf_report
679321
def afterSummaryReport(self, event):
        
        logger.info('Generating HTML report...')

        sorted_test_results = self._sort_test_results()

        context = {
            'test_report_title': 'Test Report',
            'test_summary': self.summary_stats,
            'test_results': sorted_test_results,
            'autocomplete_terms': json.dumps(self._generate_search_terms()),
            'timestamp': datetime.utcnow().strftime('%Y/%m/%d %H:%M:%S UTC')
        }
        template = load_template(self._config['template'])
        rendered_template = render_template(template, context)
        with open(self._config['report_path'], 'w') as template_file:
            template_file.write(rendered_template)
1031274
def add_html_report_optgroup(parser):
    

    g = parser.add_argument_group("HTML Report Options")

    g.add_argument("--html-stylesheet", action="append",
                   dest="html_stylesheets", default=list())

    g.add_argument("--html-javascript", action="append",
                   dest="html_javascripts", default=list())

    g.add_argument("--html-copy-data", action="store", default=None,
                   help="Copy default resources to the given directory and"
                   " enable them in the template")