Write the HTML of a page to a file and open it.
 (probably only works on OS X)
358589
def code_me
      html = browser.get_html_source
      filename = "#{Rails.root.join('tmp')}/pyrite-#{Time.now.to_i}.html"
      code = File.open(filename, 'w') { |f| f.write(html) }
      puts `open #{code}`
    end
914511
def build_document(html_content, base_href=None):
    """"""
    assert html_content is not None

    if isinstance(html_content, unicode):
        html_content = html_content.encode("utf8", "xmlcharrefreplace")

    try:
        document = document_fromstring(html_content, parser=UTF8_PARSER)
    except (ParserError, XMLSyntaxError):
        raise ValueError("Failed to parse document contents.")

    if base_href:
        document.make_links_absolute(base_href, resolve_base_href=True)
    else:
        document.resolve_base_href()

    return document
116507
def render_html(html_str):
    
    import utool as ut
    from os.path import abspath
    import webbrowser

    try:
        html_str = html_str.decode('utf8')
    except Exception:
        pass

    html_dpath = ut.ensure_app_resource_dir('utool', 'temp_html')
    fpath = abspath(ut.unixjoin(html_dpath, 'temp.html'))
    url = 'file://' + fpath
    ut.writeto(fpath, html_str)
    webbrowser.open(url)
385955
def _generate_html(data, out):
    '''
    
    '''
    print('<html>', file=out)
    print('<body>', file=out)
    _generate_html_table(data, out, 0)
    print('</body>', file=out)
    print('</html>', file=out)
1301528
def parse_safari (url_data):
    """"""
    from ..bookmarks.safari import parse_bookmark_data
    for url, name in parse_bookmark_data(url_data.get_content()):
        url_data.add_url(url, name=name)
367396
def create_html(api_key, attrs):
    ''''''
    gif = get_gif(api_key, attrs['gif_id'])

    if 'alt' not in attrs.keys():
        attrs['alt'] = 'source: {}'.format(gif['data']['source'])

    html_out = '<a href="{}">'.format(gif['data']['url'])
    html_out += '<img src="{}" alt="{}">'.format(
        gif['data']['images']['original']['url'],
        attrs['alt'])
    html_out += '</a>'

    return html_out
663445
def create_html(self, filename=None):
        """"""
        
        if isinstance(self.style, str):
            style = "'{}'".format(self.style)
        else:
            style = self.style
        
        options = dict(
            gl_js_version=GL_JS_VERSION,
            accessToken=self.access_token,
            div_id=self.div_id,
            style=style,
            center=list(self.center),
            zoom=self.zoom,
            geojson_data=json.dumps(self.data, ensure_ascii=False),
            belowLayer=self.below_layer,
            opacity=self.opacity,
            minzoom=self.min_zoom,
            maxzoom=self.max_zoom,
            pitch=self.pitch, 
            bearing=self.bearing,
            boxZoomOn=json.dumps(self.box_zoom_on),
            doubleClickZoomOn=json.dumps(self.double_click_zoom_on),
            scrollZoomOn=json.dumps(self.scroll_zoom_on),
            touchZoomOn=json.dumps(self.touch_zoom_on),
            popupOpensOnHover=self.popup_open_action=='hover',
            includeSnapshotLinks=self.add_snapshot_links,
            preserveDrawingBuffer=json.dumps(self.add_snapshot_links),
            showScale=self.scale,
            scaleUnits=self.scale_unit_system,
            scaleBorderColor=self.scale_border_color,
            scalePosition=self.scale_position,
            scaleFillColor=self.scale_background_color,
            scaleTextColor=self.scale_text_color,
        )

        if self.legend:

            if all([self.legend, self.legend_gradient, self.legend_function == 'radius']):
                raise LegendError(' '.join(['Gradient legend format not compatible with a variable radius legend.',
                                            'Please either change `legend_gradient` to False or `legend_function` to "color".']))

            options.update(
                showLegend=self.legend,
                legendLayout=self.legend_layout,
                legendFunction=self.legend_function,
                legendStyle=self.legend_style, # reserve for custom CSS
                legendGradient=json.dumps(self.legend_gradient),
                legendFill=self.legend_fill,
                legendHeaderFill=self.legend_header_fill,
                legendTextColor=self.legend_text_color,
                legendNumericPrecision=json.dumps(self.legend_text_numeric_precision),
                legendTitleHaloColor=self.legend_title_halo_color,
                legendKeyShape=self.legend_key_shape,
                legendKeyBordersOn=json.dumps(self.legend_key_borders_on)
            )

        if self.vector_source:
            options.update(
                vectorUrl=self.vector_url,
                vectorLayer=self.vector_layer_name,
                vectorJoinDataProperty=self.vector_join_property,
                joinData=json.dumps(False),
                dataJoinProperty=self.data_join_property,
                enableDataJoin=not self.disable_data_join
            )
            data = geojson_to_dict_list(self.data)
            if bool(data):
                options.update(joinData=json.dumps(data, ensure_ascii=False))

        if self.label_property is None:
            options.update(labelProperty=None)
        else:
            options.update(labelProperty='{' + self.label_property + '}')
        
        options.update(
            labelColor=self.label_color,
            labelSize=self.label_size,
            labelHaloColor=self.label_halo_color,
            labelHaloWidth=self.label_halo_width
        )

        self.add_unique_template_variables(options)

        if filename:
            html = templates.format(self.template, **options)
            with codecs.open(filename, "w", "utf-8-sig") as f:
                f.write(html)
            return None
        else:
            return templates.format(self.template, **options)
998465
def create_html(self):
        """"""

        html_table = ""
        columns = [panel.get_html_column() for panel in self.panels]
        trs = len(columns[0])
        html_table += os.linesep.join(
            [
                "<tr>{}</tr>".format("".join(["<td>{}</td>".format(columns[col][row]) for col in range(len(columns))]))
                for row in range(trs)
            ]
        )

        with open(self._html_fn, "w+") as f:
            css_src = textwrap.dedent(
                """\
					.main_table                       {border-collapse:collapse;margin-top:15px;}
					td                                {border: solid #aaaaff 1px;padding:4px;vertical-alignment:top;}
					colgroup, thead                   {border: solid black 2px;padding 2px;}
					.configuration                    {font-size:85%;}
					.configuration, .configuration *  {margin:0;padding:0;}
					.formats                          {text-align:center;margin:20px 0px;}
					img                               {min-width:640px}
			"""
            )

            html_src = """<!DOCTYPE html>
			<html>
			<head>
				<meta charset="UTF-8" />
				<title>{title}</title>
				<style type="text/css">
				{css}
				</style>
			</head>
			<body>
				<h1>{title}</h1>
				<strong>{description}</strong>

				<table class="main_table">
				{html_table}
				</table>

			</body>
			""".format(
                html_table=html_table,
                css=css_src,
                title=self.title,
                description=self.description,
            )

            tidy_html_src = bs4.BeautifulSoup(html_src).prettify()
            f.write(tidy_html_src)
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)
918821
def save_html(out_file, plot_html):
    

    internal_open = False
    if type(out_file) == str:
        out_file = open(out_file, "w")
        internal_open = True
    out_file.write("<html><head><script>\n")

    # dump the js code
    bundle_path = os.path.join(os.path.split(__file__)[0], "resources", "bundle.js")
    with io.open(bundle_path, encoding="utf-8") as f:
        bundle_data = f.read()
    out_file.write(bundle_data)
    out_file.write("</script></head><body>\n")

    out_file.write(plot_html.data)

    out_file.write("</body></html>\n")

    if internal_open:
        out_file.close()
139357
def save(filename, html):
    
    try:
        out_file = open(filename, "w")
        out_file.write(html)
        out_file.close()
    except IOError as ex:
        parser.error("Could not write baked HTML to local file {name}. ({ex})".format(name=filename, ex=ex))
1158493
def to_html(data):
    
    base_html_template = Template('''
        <html>
            <head>
                {% if style %}
                <style type="text/css">
                    {{ style }}
                </style>
                {% endif %}
            </head>
            <body>
                {% if style %}
                    {{ body|safe }}
                {% else %}
                    <pre></code>{{ body }}</code></pre>
                {% endif %}
            </body>
        </html>
        ''')

    code = to_json(data, indent=4)
    if PYGMENTS_INSTALLED:
        c = Context({
            'body': highlight(code, JSONLexer(), HtmlFormatter()),
            'style': HtmlFormatter().get_style_defs('.highlight')
        })
        html = base_html_template.render(c)
    else:
        c = Context({'body': code})
        html = base_html_template.render(c)
    return html
584415
def to_html(threshold=30)
      table_thead = to_html_thead
      table_tbody = to_html_tbody(threshold)
      path = if index.is_a?(MultiIndex)
               File.expand_path('../iruby/templates/dataframe_mi.html.erb', __FILE__)
             else
               File.expand_path('../iruby/templates/dataframe.html.erb', __FILE__)
             end
      ERB.new(File.read(path).strip).result(binding)
    end
1295281
def write_file(self, html, outfile):
        
        try:
            with open(outfile, 'wt') as file:
                file.write(html)
        except (IOError, OSError) as e:
            err_exit('Error writing %s: %s' % (outfile, e.strerror or e))
1159898
def render(file):
    """"""
    fp = file.open()
    content = fp.read()
    fp.close()

    notebook = nbformat.reads(content.decode('utf-8'), as_version=4)

    html_exporter = HTMLExporter()
    html_exporter.template_file = 'basic'
    (body, resources) = html_exporter.from_notebook_node(notebook)
    return body, resources
660834
function toJavascript() {

	// find each matching pair of handlebars blocks
	var text = this.html;
	var pairs = [];
	var opens = [];
	var opener = -1;
	var closer = -1;
	var cursor = 0;
	var block = '';
	var blocks = [];
	var snipped = '';
	var openexpr = null;
	var closexpr = null;
	var nextopen = null;
	var template = this;
	var i;


	// FIND ONLY THE OUTER BLOCKS
	// 
	// Continuously find next token (opener or closer)
	// 	if opener, opens.push(opener)
	// 	elseif closer
	// 		pop and pair IFF opens.length == 0
	// 		
	cursor = 0;
	do {

		// Find next opener and closer relative to the cursor
		opener = text.indexOf('{{#', cursor);
		closer = text.indexOf('{{/', cursor);

		// Next token is an opener?
		if ((opener > -1) && ((closer == -1) || (opener < closer))) {
			opens.push(opener);
			cursor = opener + 3;
		}

		// Next token is a closer?
		else if ((closer > -1) && ((opener == -1) || (closer < opener))) {
			if (opens.length == 0) {
				throw new Error('Unmatched close block');
			}
			opener = opens.pop();
			if (opens.length === 0) {
				pairs.push([opener, closer]);
			}
			cursor = closer + 3;
		}

	} while ((opener > -1) || (closer > -1));


	// this should never happen
	if (opens.length > 0) {
		throw new Error('Unmatched open block');
	}

	// snip 
	cursor = 0;
	snipped = '';
	for (i=0; i<pairs.length; i++) {
		openexpr = readExpression(text, pairs[i][0]);
		closexpr = readExpression(text, pairs[i][1]);
		snipped += text.substr(cursor, pairs[i][0] - cursor);
		snipped += _blockStub;
		cursor = pairs[i][0] + openexpr.length; // move cursor to the end of the open block tag
		block = text.substr(cursor, pairs[i][1] - cursor);
		this.blocks.push(new Block(Expression.delimited(openexpr), new Template(block, {newStack: false})));
		cursor = pairs[i][1] + closexpr.length; // move cursor to the end of the close block tag
	}
	snipped += text.substr(cursor);
	
	
	// Parse HTML or Text
	// This is where the blocks are unraveled
	// This is where the text is parseInterpolated
	switch(this.type) {

		// htmlparser2
		case 'html':
			if (!this.parser) {
				this.parser = new htmlparser.Parser({
					// Let's ignore comments for now
					// This does not enable the <!DOCTYPE>
					// oncomment: function(data) {
					// 	template.appendChild(new VText(data));
					// },
					onopentag: function(tagname, attributes){
						// TODO: improve so VNode does not hold attributes as javascript (use Attributes object)
						template.appendChild(new VNode(ontext(template, tagname, {virtual: false}).pop(), attributesToJavascript(template, attributes)));
						template.push();
					},
					ontext: function(text) {
						template.appendChildren(ontext(template, text));
					},
					onclosetag: function(tagname){
						template.pop();
					}
				});
			}

			this.parser.write(snipped);
			break;

		// plaintext
		default:
			ontext(this, snipped);
			break;
	}

	// compile to js
	return [
		'(function(context){',
			this.newStack ? 'var stack = [], env = ' + Template.Runtime + ';' : '',
			'return (function(){',
				'stack.push(this);',
				'var r = ', this.root.children.toJavascript(), ';',
				'stack.pop();',
				'return r;',
			'}).call(context);',
		'})'
	].join('');
}
63071
def _print_html(self):
        
        cur_path = os.path.dirname(os.path.realpath(sys.argv[0]))
        shutil.copytree(cur_path+'webpage/template/', '')