Create the epic HTML for the FastQC sequence content heatmap
974054
def sequence_content_plot (self):
        

        # Prep the data
        data = OrderedDict()
        for s_name in sorted(self.fastqc_data.keys()):
            try:
                data[s_name] = {self.avg_bp_from_range(d['base']): d for d in self.fastqc_data[s_name]['per_base_sequence_content']}
            except KeyError:
                pass
            # Old versions of FastQC give counts instead of percentages
            for b in data[s_name]:
                tot = sum([data[s_name][b][base] for base in ['a','c','t','g']])
                if tot == 100.0:
                    break
                else:
                    for base in ['a','c','t','g']:
                        data[s_name][b][base] = (float(data[s_name][b][base])/float(tot)) * 100.0
        if len(data) == 0:
            log.debug('sequence_content not found in FastQC reports')
            return None

        html = '''<div id="fastqc_per_base_sequence_content_plot_div">
            <div class="alert alert-info">
               <span class="glyphicon glyphicon-hand-up"></span>
               Click a sample row to see a line plot for that dataset.
            </div>
            <h5><span class="s_name text-primary"><span class="glyphicon glyphicon-info-sign"></span> Rollover for sample name</span></h5>
            <button id="fastqc_per_base_sequence_content_export_btn"><span class="glyphicon glyphicon-download-alt"></span> Export Plot</button>
            <div class="fastqc_seq_heatmap_key">
                Position: <span id="fastqc_seq_heatmap_key_pos">-</span>
                <div><span id="fastqc_seq_heatmap_key_t"> %T: <span>-</span></span></div>
                <div><span id="fastqc_seq_heatmap_key_c"> %C: <span>-</span></span></div>
                <div><span id="fastqc_seq_heatmap_key_a"> %A: <span>-</span></span></div>
                <div><span id="fastqc_seq_heatmap_key_g"> %G: <span>-</span></span></div>
            </div>
            <div id="fastqc_seq_heatmap_div" class="fastqc-overlay-plot">
                <div id="fastqc_per_base_sequence_content_plot" class="hc-plot has-custom-export">
                    <canvas id="fastqc_seq_heatmap" height="100%" width="800px" style="width:100%;"></canvas>
                </div>
            </div>
            <div class="clearfix"></div>
        </div>
        <script type="text/javascript">
            fastqc_seq_content_data = {d};
            $(function () {{ fastqc_seq_content_heatmap(); }});
        </script>'''.format(d=json.dumps(data))

        self.add_section (
            name = 'Per Base Sequence Content',
            anchor = 'fastqc_per_base_sequence_content',
            description = 'The proportion of each base position for which each of the four normal DNA bases has been called.',
            helptext = '''
            To enable multiple samples to be shown in a single plot, the base composition data
            is shown as a heatmap. The colours represent the balance between the four bases:
            an even distribution should give an even muddy brown colour. Hover over the plot
            to see the percentage of the four bases under the cursor.

            **To see the data as a line plot, as in the original FastQC graph, click on a sample track.**

            From the [FastQC help](http://www.bioinformatics.babraham.ac.uk/projects/fastqc/Help/3%20Analysis%20Modules/4%20Per%20Base%20Sequence%20Content.html):

            _Per Base Sequence Content plots out the proportion of each base position in a
            file for which each of the four normal DNA bases has been called._

            _In a random library you would expect that there would be little to no difference
            between the different bases of a sequence run, so the lines in this plot should
            run parallel with each other. The relative amount of each base should reflect
            the overall amount of these bases in your genome, but in any case they should
            not be hugely imbalanced from each other._

            _It's worth noting that some types of library will always produce biased sequence
            composition, normally at the start of the read. Libraries produced by priming
            using random hexamers (including nearly all RNA-Seq libraries) and those which
            were fragmented using transposases inherit an intrinsic bias in the positions
            at which reads start. This bias does not concern an absolute sequence, but instead
            provides enrichement of a number of different K-mers at the 5' end of the reads.
            Whilst this is a true technical bias, it isn't something which can be corrected
            by trimming and in most cases doesn't seem to adversely affect the downstream
            analysis._
            ''',
            content = html
        )
400483
def render_workflow_html_template(filename, subtemplate, filelists, **kwargs):
    

    dirnam = os.path.dirname(filename)
    makedir(dirnam)

    try:
        filenames = [f.name for filelist in filelists for f in filelist if f is not None]
    except TypeError:
        filenames = []

    # render subtemplate
    subtemplate_dir = pycbc.results.__path__[0] + '/templates/wells'
    env = Environment(loader=FileSystemLoader(subtemplate_dir))
    env.globals.update(get_embedded_config=get_embedded_config)
    env.globals.update(path_exists=os.path.exists)
    env.globals.update(len=len)
    subtemplate = env.get_template(subtemplate)
    context = {'filelists' : filelists,
               'dir' : dirnam}
    context.update(kwargs)
    output = subtemplate.render(context)

    # save as html page
    kwds = {'render-function' : 'render_tmplt',
            'filenames' : ','.join(filenames)}
    save_html_with_metadata(str(output), filename, None, kwds)
605745
def weblogo(args):
    
    import numpy as np
    from jcvi.utils.progressbar import ProgressBar, Percentage, Bar, ETA

    p = OptionParser(weblogo.__doc__)
    p.add_option("-N", default=10, type="int",
                 help="Count the first and last N bases")
    p.add_option("--nreads", default=1000000, type="int",
                 help="Parse first N reads")
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    fastqfile, = args
    N = opts.N
    nreads = opts.nreads

    pat = "ATCG"
    L = np.zeros((4, N), dtype="int32")
    R = np.zeros((4, N), dtype="int32")
    p = dict((a, i) for (i, a) in enumerate(pat))
    L4, R3 = Counter(), Counter()
    widgets = ['Parse reads: ', Percentage(), ' ',
               Bar(marker='>', left='[', right=']'), ' ', ETA()]
    pr = ProgressBar(maxval=nreads, term_width=60, widgets=widgets).start()

    k = 0
    fw_L = open("L.fasta", "w")
    fw_R = open("R.fasta", "w")
    fastq = fastqfile.endswith(".fastq")
    it = iter_fastq(fastqfile) if fastq else \
        SeqIO.parse(must_open(fastqfile), "fasta")
    for rec in it:
        k += 1
        if k % 1000 == 0:
            pr.update(k)
        if k > nreads:
            break
        if rec is None:
            break
        s = str(rec.seq)
        for i, a in enumerate(s[:N]):
            if a in p:
                a = p[a]
                L[a][i] += 1
        for j, a in enumerate(s[-N:][::-1]):
            if a in p:
                a = p[a]
                R[a][N - 1 - j] += 1
        l4, r3 = s[:4], s[-3:]
        L4[l4] += 1
        R3[r3] += 1
        print(">{0}\n{1}".format(k, s[:N]), file=fw_L)
        print(">{0}\n{1}".format(k, s[-N:]), file=fw_R)

    fw_L.close()
    fw_R.close()

    cmd = "weblogo -F png -s large -f {0}.fasta -o {0}.png"
    cmd += " --color-scheme classic --composition none -U probability"
    cmd += " --title {1}"
    sh(cmd.format('L', "First_10_bases"))
    sh(cmd.format('R', "Last_10_bases"))

    np.savetxt("L.{0}.csv".format(pat), L, delimiter=',', fmt="%d")
    np.savetxt("R.{0}.csv".format(pat), R, delimiter=',', fmt="%d")

    fw = open("L4.common", "w")
    for p, c in L4.most_common(N):
        print("\t".join((p, str(c))), file=fw)
    fw.close()

    fw = open("R3.common", "w")
    for p, c in R3.most_common(N):
        print("\t".join((p, str(c))), file=fw)
    fw.close()
295137
function mdAstToHtml(ast, lines) {
    if (lines == undefined)
        lines = [];

    // Adds each element of the array as markdown 
    function addArray(ast) {
        for (let child of ast)
            mdAstToHtml(child, lines);
        return lines;
    }

    // Adds tagged content 
    function addTag(tag, ast, newLine) {
        lines.push(startTag(tag));
        if (ast instanceof Array)
            addArray(ast); 
        else
            mdAstToHtml(ast, lines);
        lines.push(endTag(tag));
        if (newLine)
            lines.push('\r\n');
        return lines;
    }

    function addLink(url, astOrText) {
        lines.push(startTag('a', { href:url }));
        if (astOrText) {
            if (astOrText.children)
                addArray(astOrText.children);
            else
               lines.push(astOrText);
        }        
        
        lines.push(endTag('a')) ;
        return lines;
    }

    function addImg(url) {
        lines.push(startTag('img', { src:url }));
        lines.push(endTag('img')) ;
        return lines;
    }

    switch (ast.name)
    {
        case "heading": 
            {
                let headingLevel = ast.children[0];
                let restOfLine = ast.children[1];
                let h = headingLevel.allText.length;
                switch (h)
                {
                    case 1: return addTag("h1", restOfLine, true); 
                    case 2: return addTag("h2", restOfLine, true); 
                    case 3: return addTag("h3", restOfLine, true); 
                    case 4: return addTag("h4", restOfLine, true); 
                    case 5: return addTag("h5", restOfLine, true); 
                    case 6: return addTag("h6", restOfLine, true); 
                    default: throw "Heading level must be from 1 to 6"
                }
            }
        case "paragraph":   
            return addTag("p", ast.children, true);
        case "unorderedList":
            return addTag("ul", ast.children, true);
        case "orderedList":
            return addTag("ol", ast.children, true);
        case "unorderedListItem":
            return addTag("li", ast.children, true);
        case "orderedListItem":
            return addTag("li", ast.children, true);
        case "inlineUrl":
            return addLink(ast.allText, ast.allText);
        case "bold":
            return addTag("b", ast.children);
        case "italic":
            return addTag("i", ast.children);
        case "code":
            return addTag("code", ast.children);
        case "codeBlock":
            return addTag("pre", ast.children);
        case "quote":
            return addTag("blockquote", ast.children, true);
        case "link":
            return addLink(ast.children[1].allText, ast.children[0]);
        case "image":
            return addImg(ast.children[0]);
        default:
            if (ast.isLeaf)
                lines.push(ast.allText);
            else 
                ast.children.forEach(function(c) { mdAstToHtml(c, lines); });
    }
    return lines;
}
317180
def fasta(args):
    
    p = OptionParser(fasta.__doc__)
    p.add_option("--seqtk", default=False, action="store_true",
                 help="Use seqtk to convert")
    p.set_outdir()
    p.set_outfile(outfile=None)
    opts, args = p.parse_args(args)

    if len(args) < 1:
        sys.exit(not p.print_help())

    fastqfiles = args
    outdir = opts.outdir
    if outdir and outdir != ".":
        mkdir(outdir)

    fastqfile = fastqfiles[0]
    pf = op.basename(fastqfile)
    gzinput = pf.endswith(".gz")
    if gzinput:
        pf = pf.rsplit(".", 1)[0]

    pf, sf = pf.rsplit(".", 1)
    if sf not in ("fq", "fastq"):
        logging.debug("Assumed FASTA: suffix not `fq` or `fastq`")
        return fastqfile, None

    fastafile, qualfile = pf + ".fasta", pf + ".qual"
    outfile = opts.outfile or fastafile
    outfile = op.join(outdir, outfile)
    if opts.seqtk:
        if need_update(fastqfiles, outfile):
            for i, fastqfile in enumerate(fastqfiles):
                cmd = "seqtk seq -A {0} -L 30 -l 70".format(fastqfile)
                # First one creates file, following ones append to it
                sh(cmd, outfile=outfile, append=i)
        else:
            logging.debug("Outfile `{0}` already exists.".format(outfile))
        return outfile, None

    for fastqfile in fastqfiles:
        SeqIO.convert(fastqfile, "fastq", fastafile, "fasta")
        SeqIO.convert(fastqfile, "fastq", qualfile, "qual")

    return fastafile, qualfile
921743
def build_parser(parser):
    
    parser.add_argument(
        'sequence_file',
        type=FileType('r'),
        help="""Input fastq file. A fasta-format file may also be provided
            if --input-qual is also specified.""")
    parser.add_argument(
        '--input-qual',
        type=FileType('r'),
        help="""The quality scores associated with the input file. Only
            used if input file is fasta.""")
    parser.add_argument(
        'output_file',
        type=FileType('w'),
        help="""Output file. Format determined from extension.""")

    output_group = parser.add_argument_group("Output")
    output_group.add_argument(
        '--report-out',
        type=FileType('w'),
        default=sys.stdout,
        help="""Output file for report [default:
            stdout]""")
    output_group.add_argument(
        '--details-out',
        type=FileType('w'),
        help="""Output file to report fate of each sequence""")
    output_group.add_argument(
        '--no-details-comment',
        action='store_false',
        default=True,
        dest='details_comment',
        help="""Do not write comment
            lines with version and call to start --details-out""")

    parser.add_argument(
        '--min-mean-quality',
        metavar='QUALITY',
        type=float,
        default=DEFAULT_MEAN_SCORE,
        help="""Minimum mean quality score for
            each read [default: %(default)s]""")
    parser.add_argument(
        '--min-length',
        metavar='LENGTH',
        type=int,
        default=200,
        help="""Minimum length to keep sequence [default:
            %(default)s]""")
    parser.add_argument(
        '--max-length',
        metavar='LENGTH',
        type=int,
        default=1000,
        help="""Maximum length to keep before truncating
            [default: %(default)s]. This operation occurs before
            --max-ambiguous""")

    window_group = parser.add_argument_group('Quality window options')
    window_group.add_argument(
        '--quality-window-mean-qual',
        type=float,
        help="""Minimum quality score within the window defined by
            --quality-window. [default: same as --min-mean-quality]""")
    window_group.add_argument(
        '--quality-window-prop',
        help="""Proportion of
            reads within quality window to that must pass filter. Floats are [default:
            %(default).1f]""",
        default=1.0,
        type=typed_range(float, 0.0, 1.0))
    window_group.add_argument(
        '--quality-window',
        type=int,
        metavar='WINDOW_SIZE',
        default=0,
        help="""Window size for truncating sequences.  When set
            to a non-zero value, sequences are truncated where the mean mean
            quality within the window drops below --min-mean-quality.
            [default: %(default)s]""")

    parser.add_argument(
        '--ambiguous-action',
        choices=('truncate', 'drop'),
        help="""Action to take on ambiguous base in sequence (N's).
            [default: no action]""")
    parser.add_argument(
        '--max-ambiguous',
        default=None,
        help="""Maximum number
            of ambiguous bases in a sequence. Sequences exceeding this count
            will be removed.""",
        type=int)
    parser.add_argument(
        '--pct-ambiguous',
        help="""Maximun percent of
            ambiguous bases in a sequence.  Sequences exceeding this percent
            will be removed.""",
        type=float)

    barcode_group = parser.add_argument_group('Barcode/Primer')
    primer_group = barcode_group.add_mutually_exclusive_group()
    primer_group.add_argument(
        '--primer', help="""IUPAC ambiguous primer to
            require""")
    primer_group.add_argument(
        '--no-primer',
        help="""Do not use a primer.""",
        action='store_const',
        const='',
        dest='primer')
    barcode_group.add_argument(
        '--barcode-file',
        help="""CSV file containing
            sample_id,barcode[,primer] in the rows. A single primer for all
            sequences may be specified with `--primer`, or `--no-primer` may be
            used to indicate barcodes should be used without a primer
            check.""",
        type=FileType('r'))
    barcode_group.add_argument(
        '--barcode-header',
        action='store_true',
        default=False,
        help="""Barcodes have a header row [default:
            %(default)s]""")
    barcode_group.add_argument(
        '--map-out',
        help="""Path to write
            sequence_id,sample_id pairs""",
        type=FileType('w'),
        metavar='SAMPLE_MAP')
    barcode_group.add_argument(
        '--quoting',
        help="""A string naming an
            attribute of the csv module defining the quoting behavior for
            `SAMPLE_MAP`.  [default: %(default)s]""",
        default='QUOTE_MINIMAL',
        choices=[s for s in dir(csv) if s.startswith('QUOTE_')])
319619
def _render_content(self):
        """"""
        if self.content_format == "rst" and docutils_publish is not None:
            doc_parts = docutils_publish(
                source=self.raw_content,
                writer_name="html4css1"
            )
            self.rendered_content = doc_parts['fragment']
        elif self.content_format == "rs" and docutils_publish is None:
            raise RuntimeError("Install docutils to pubilsh reStructuredText")
        elif self.content_format == "md" and markdown is not None:
            self.rendered_content = markdown(self.raw_content)
        elif self.content_format == "md" and markdown is None:
            raise RuntimeError("Install Markdown to pubilsh markdown")
        else:  # Assume we've got html
            self.rendered_content = self.raw_content
1147253
def _generate_html(self):
        
        logger.debug('Generating templated HTML')
        env = Environment(
            loader=PackageLoader('pypi_download_stats', 'templates'),
            extensions=['jinja2.ext.loopcontrols'])
        env.filters['format_date_long'] = filter_format_date_long
        env.filters['format_date_ymd'] = filter_format_date_ymd
        env.filters['data_columns'] = filter_data_columns
        template = env.get_template('base.html')

        logger.debug('Rendering template')
        html = template.render(
            project=self.project_name,
            cache_date=self._stats.as_of_datetime,
            user=getuser(),
            host=platform_node(),
            version=VERSION,
            proj_url=PROJECT_URL,
            graphs=self._graphs,
            graph_keys=self.GRAPH_KEYS,
            resources=Resources(mode='inline').render(),
            badges=self._badges
        )
        logger.debug('Template rendered')
        return html
1167952
def init_heatmap(x_vec, y_vec, hist_matrix, fig, colormap='Blues',
                 alpha=1, grid=False, colorbar=True,
                 vmax='auto', vmin='auto', crop=True):
    
    plt.figure(fig.number)
    ax = fig.gca()

    # set vmax and vmin
    vma = np.amax(hist_matrix) if vmax == 'auto' else vmax
    vmi = np.amin(hist_matrix) if vmin == 'auto' else vmin

    # an error check
    if vma <= vmi:
        vma = vmi + 1

    # grid the space for pcolormesh
    x_grid, y_grid = np.meshgrid(x_vec, y_vec)

    hmap = ax.pcolormesh(x_grid, y_grid, np.array(hist_matrix),
               cmap=colormap, alpha=alpha, shading='gouraud',
               vmax=vma, vmin=vmi)

    if colorbar:
        plt.colorbar(hmap)

    if not grid:
        ax.grid(False)

    if crop:
        ax.set_xlim([x_vec[0], x_vec[-1]])
        ax.set_ylim([y_vec[0], y_vec[-1]])
843045
def to_html(self):
        '''
        

        '''
        javascript_to_insert = '\n'.join([
            PackedDataUtils.full_content_of_javascript_files(),
            self.category_scatterplot_structure._visualization_data.to_javascript('getCategoryDataAndInfo'),
            self.category_scatterplot_structure.get_js_to_call_build_scatterplot(self.category_plot_interface),
            self.term_scatterplot_structure._visualization_data.to_javascript('getTermDataAndInfo'),
            self.term_scatterplot_structure.get_js_to_call_build_scatterplot(self.term_plot_interface),
        ])
        html_template = self._get_html_template()
        html_content = (
            html_template
                .replace('<!-- INSERT SCRIPT -->', javascript_to_insert, 1)
                .replace('<!--D3URL-->', self.d3_url_struct.get_d3_url(), 1)
                .replace('<!--D3SCALECHROMATIC-->', self.d3_url_struct.get_d3_scale_chromatic_url())
            # .replace('<!-- INSERT D3 -->', self._get_packaged_file_content('d3.min.js'), 1)
        )
        html_content = (html_content.replace('http://', self.protocol + '://'))
        if self.show_halo:
            axes_labels = self.category_projection.get_nearest_terms(
                num_terms=self.num_terms
            )
            for position, terms in axes_labels.items():
                html_content = html_content.replace('{%s}' % position, self._get_lexicon_html(terms))
        return html_content.replace('{width}', str(self.category_width)).replace('{height}', str(self.category_height))
447365
def heatmap(w, vmin=None, vmax=None, diverge_color=False,
            ncol=1,
            plot_name=None, vocab=["A", "C", "G", "T"], figsize=(6, 2)):
    
    # Generate y and x values from the dimension lengths
    assert len(vocab) == w.shape[0]
    plt_y = np.arange(w.shape[0] + 1) + 0.5
    plt_x = np.arange(w.shape[1] + 1) - 0.5
    z_min = w.min()
    z_max = w.max()

    if vmin is None:
        vmin = z_min
    if vmax is None:
        vmax = z_max

    if diverge_color:
        color_map = plt.cm.RdBu
    else:
        color_map = plt.cm.Blues

    fig = plt.figure(figsize=figsize)
    # multiple axis
    if len(w.shape) == 3:
        #
        n_plots = w.shape[2]
        nrow = math.ceil(n_plots / ncol)
    else:
        n_plots = 1
        nrow = 1
        ncol = 1

    for i in range(n_plots):
        if len(w.shape) == 3:
            w_cur = w[:, :, i]
        else:
            w_cur = w
        ax = plt.subplot(nrow, ncol, i + 1)
        plt.tight_layout()
        im = ax.pcolormesh(plt_x, plt_y, w_cur, cmap=color_map,
                           vmin=vmin, vmax=vmax, edgecolors="white")
        ax.grid(False)
        ax.set_yticklabels([""] + vocab, minor=False)
        ax.yaxis.set_major_locator(MaxNLocator(integer=True))
        ax.set_xticks(np.arange(w_cur.shape[1] + 1))
        ax.set_xlim(plt_x.min(), plt_x.max())
        ax.set_ylim(plt_y.min(), plt_y.max())

        # nice scale location:
        # http://stackoverflow.com/questions/18195758/set-matplotlib-colorbar-size-to-match-graph
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        fig.colorbar(im, cax=cax)

        if plot_name is not None:
            if n_plots > 0:
                pln = plot_name + " {0}".format(i)
            else:
                pln = plot_name
            ax.set_title(pln)
        ax.set_aspect('equal')
    return fig
766921
def render_template(template_name, context, format='png',
                    output=None, using=None, **options):
    
    # output stream, as required by casperjs_capture
    stream = BytesIO()
    out_f = None
    # the suffix=.html is a hack for phantomjs which *will*
    # complain about not being able to open source file
    # unless it has a 'html' extension.
    with NamedTemporaryFile(suffix='.html') as render_file:
        template_content = render_to_string(
            template_name,
            context,
            using=using,
        )
        # now, we need to replace all occurences of STATIC_URL
        # with the corresponding file://STATIC_ROOT, but only
        # if STATIC_URL doesn't contain a public URI (like http(s))
        static_url = getattr(settings, 'STATIC_URL', '')
        if settings.STATIC_ROOT and\
           static_url and not static_url.startswith('http'):
            template_content = template_content.replace(
                static_url,
                'file://%s' % settings.STATIC_ROOT
            )
        render_file.write(template_content.encode('utf-8'))
        # this is so that the temporary file actually gets filled
        # with the result.
        render_file.seek(0)

        casperjs_capture(
            stream,
            url='file://%s' % render_file.name,
            **options
        )

        # if no output was provided, use NamedTemporaryFile
        # (so it is an actual file) and return it (so that
        # after function ends, it gets automatically removed)
        if not output:
            out_f = NamedTemporaryFile()
        else:
            # if output was provided, write the rendered
            # content to it
            out_f = open(output, 'wb')
        out_f.write(stream.getvalue())
        out_f.seek(0)

        # return the output if NamedTemporaryFile was used
        if not output:
            return out_f
        else:
            # otherwise, just close the file.
            out_f.close()
1166375
function generateHTML(testResults) {
        var stepsHtml = '',
            header = '',
            isPassed = false,
            passedScenarios = 0,
            passedSteps = 0,
            stepsNumber = 0,
            scenariosNumber = 0,
            scenariosNumberInFeature = 0,
            passedScenariosNumberInFeature = 0,
            stepsNumberInFeature = 0,
            passedStepsInFeature = 0,
            scenariosHtml = '',
            element,
            step,
            stepDuration = 0;

        html = '';
        for (var i = 0; i < testResults.length; i++) {

            scenariosNumberInFeature = 0;
            passedScenariosNumberInFeature = 0;
            stepsNumberInFeature = 0;
            passedStepsInFeature = 0;
            scenariosHtml = '';
            if (testResults[i].elements) {
                for (var j = 0; j < testResults[i].elements.length; j++) {
                    element = testResults[i].elements[j];
                    if (element.type === 'scenario') {
                        scenariosNumber++;
                        scenariosNumberInFeature++;
                        stepsHtml = '';
                        isPassed = true;
                        for (var k = 0; k < testResults[i].elements[j].steps.length; k++) {
                            step = testResults[i].elements[j].steps[k];

                            if (isEmptyAfterStep(step) || isEmptyBeforeStep(step)) {
                                continue;
                            }

                            if (isAfterStepWithScreenshot(step)) {
                                stepsHtml += getAfterScreenshotStep(step);
                            } else {
                                stepsHtml += getStep(step);
                                stepDuration += (step.result.duration ? step.result.duration : 0);
                                stepsNumber++;
                                stepsNumberInFeature++;
                                if (step.result.status !== statuses.PASSED) {
                                    isPassed = false;
                                } else if (step.result.status === statuses.PASSED) {
                                    passedSteps++;
                                    passedStepsInFeature++;
                                }
                            }
                        }

                        if (isPassed) {
                            passedScenarios++;
                            passedScenariosNumberInFeature++;
                        }
                        scenariosHtml += getScenarioContainer(getScenario(element, isPassed, stepsHtml));
                    }
                }
            }
            html += getFeatureWithScenarios(getFeature(testResults[i], scenariosNumberInFeature, passedScenariosNumberInFeature, stepsNumberInFeature, passedStepsInFeature) + scenariosHtml);
        }
        header = getHeader(scenariosNumber, passedScenarios, stepsNumber, passedSteps, calculateDuration(stepDuration));
        return header + html;
    }
2125
function Heatmap() {
    var canvas = zrUtil.createCanvas();
    this.canvas = canvas;

    this.blurSize = 30;
    this.pointSize = 20;

    this.maxOpacity = 1;
    this.minOpacity = 0;

    this._gradientPixels = {};
}
557016
function renderTemplateFiles (skipInterpolation) {
  skipInterpolation = typeof skipInterpolation === 'string'
    ? [skipInterpolation]
    : skipInterpolation;
  return (files, metalsmith, done) => {
    const keys = Object.keys(files);
    const metalsmithMetadata = metalsmith.metadata();
    async.each(keys, (file, next) => {
      // skipping files with skipInterpolation option
      if (skipInterpolation && multimatch([file], skipInterpolation, { dot: true }).length) {
        return next();
      }
      const rawFileName = file;
      const rawBuffer = files[file];
      const contents = rawBuffer.contents.toString();
      // do not attempt to render files that do not have mustaches
      if (!/{{([^{}]+)}}/g.test(contents) && !/{{([^{}]+)}}/g.test(file)) {
        return next();
      }

      // first replace filename
      render(file, metalsmithMetadata, (err, res) => {
        if (err) {
          err.message = `[${file}] ${err.message}`;
          return next(err);
        }
        file = res;
        // second replace file contents
        render(contents, metalsmithMetadata, (err, res) => {
          if (err) {
            err.message = `[${file}] ${err.message}`;
            return next(err);
          }
          files[file] = rawBuffer;
          files[file].contents = new Buffer(res);

          // delete old buffer
          if (rawFileName !== file) {
            files[rawFileName] = null;
            delete files[rawFileName];
          }
          next();
        });
      });
    }, done);
  };
}
415336
def spatial_heatmap(array, path, title=None, color="Greens", figformat="png"):
    """"""
    logging.info("Nanoplotter: Creating heatmap of reads per channel using {} reads."
                 .format(array.size))
    activity_map = Plot(
        path=path + "." + figformat,
        title="Number of reads generated per channel")
    layout = make_layout(maxval=np.amax(array))
    valueCounts = pd.value_counts(pd.Series(array))
    for entry in valueCounts.keys():
        layout.template[np.where(layout.structure == entry)] = valueCounts[entry]
    plt.figure()
    ax = sns.heatmap(
        data=pd.DataFrame(layout.template, index=layout.yticks, columns=layout.xticks),
        xticklabels="auto",
        yticklabels="auto",
        square=True,
        cbar_kws={"orientation": "horizontal"},
        cmap=color,
        linewidths=0.20)
    ax.set_title(title or activity_map.title)
    activity_map.fig = ax.get_figure()
    activity_map.save(format=figformat)
    plt.close("all")
    return [activity_map]
563548
def buildhtml(self):
        
        self.buildcontent()
        self.buildhtmlheader()
        self.content = self._htmlcontent.decode('utf-8') # need to ensure unicode
        self._htmlcontent = self.template_page_highcharts.render(chart=self)
        return self._htmlcontent