Python IPython.display.HTML Examples

The following are 30 code examples of IPython.display.HTML(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module IPython.display , or try the search function .
Example #1
Source File: drawTopicModel.py    From CheTo with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def drawMolsByTopic(topicModel, topicIdx, idsLabelToShow=[0], topicProbThreshold = 0.5, baseRad=0.5, molSize=(250,150),\
                    numRowsShown=3, color=(.0,.0, 1.), maxMols=100):
    result = generateMoleculeSVGsbyTopicIdx(topicModel, topicIdx, idsLabelToShow=idsLabelToShow, \
                                             topicProbThreshold = topicProbThreshold, baseRad=baseRad,\
                                             molSize=molSize,color=color, maxMols=maxMols)
    if len(result)  == 1:
        print(result)
        return
        
    svgs, namesSVGs = result
    finalsvgs = []
    for svg in svgs:
        # make the svg scalable
        finalsvgs.append(svg.replace('<svg','<svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 '+str(molSize[0])\
                                     +' '+str(molSize[1])+'"'))
 
    tableHeader = 'Molecules in topic '+str(topicIdx)+' (sorted by decending probability)'
    
    return display(HTML(utilsDrawing.drawSVGsToHTMLGrid(finalsvgs[:maxMols],cssTableName='overviewTab',tableHeader=tableHeader,\
                                                 namesSVGs=namesSVGs[:maxMols], size=molSize, numRowsShown=numRowsShown, numColumns=4)))

# produces a svg grid of the molecules belonging to a certain topic and highlights this topic within the molecules 
Example #2
Source File: utils.py    From parliament2 with Apache License 2.0 6 votes vote down vote up
def post_execute(self):
        if self.isFirstPostExecute:
            self.isFirstPostExecute = False
            self.isFirstPreExecute = False
            return 0
        self.flag = False
        self.asyncCapturer.Wait()
        self.ioHandler.Poll()
        self.ioHandler.EndCapture()

        # Print for the notebook
        out = self.ioHandler.GetStdout()
        err = self.ioHandler.GetStderr()
        if not transformers:
            sys.stdout.write(out)
            sys.stderr.write(err)
        else:
            for t in transformers:
                (out, err, otype) = t(out, err)
                if otype == 'html':
                    IPython.display.display(HTML(out))
                    IPython.display.display(HTML(err))
        return 0 
Example #3
Source File: load_style.py    From metocean with The Unlicense 6 votes vote down vote up
def load_style(s):
    """Load a CSS stylesheet in the notebook by URL or filename.

    Examples::
    
        %load_style mystyle.css
        %load_style http://ipynbstyles.com/otherstyle.css
    """
    if s.startswith('http'):
        r =requests.get(s)
        style = r.text
    else:
        with open(s, 'r') as f:
            style = f.read()
    s = '<style>\n{style}\n</style>'.format(style=style)
    display(HTML(s)) 
Example #4
Source File: map_templates.py    From gbdxtools with MIT License 6 votes vote down vote up
def inject(self):
        try:
            from IPython.display import HTML, display, Javascript
        except:
            print("IPython is required to produce maps.")
            return
        display(HTML(Template('''
           <div id="$map_id"/>
           <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.52.0/mapbox-gl.css' rel='stylesheet' />
           <style>body{margin:0;padding:0;}#$map_id{position:relative;top:0;bottom:0;width:100%;height:400px;}</style>
           <style>
            #$map_id .mapboxgl-ctrl-icon.screencap-icon .download-btn {background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB2ZXJzaW9uPSIxLjEi%0D%0AIGlkPSJhdHRyYWN0aW9uLTE1IiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdp%0D%0AZHRoPSIxNXB4IiBoZWlnaHQ9IjE1cHgiIHZpZXdCb3g9IjAgMCAxNSAxNSI+CiAgPHBhdGggaWQ9%0D%0AInJlY3Q3MTQzIiBkPSJNNiwyQzUuNDQ2LDIsNS4yNDc4LDIuNTA0NSw1LDNMNC41LDRoLTJDMS42%0D%0ANjksNCwxLDQuNjY5LDEsNS41djVDMSwxMS4zMzEsMS42NjksMTIsMi41LDEyaDEwJiN4QTsmI3g5%0D%0AO2MwLjgzMSwwLDEuNS0wLjY2OSwxLjUtMS41di01QzE0LDQuNjY5LDEzLjMzMSw0LDEyLjUsNGgt%0D%0AMkwxMCwzQzkuNzUsMi41LDkuNTU0LDIsOSwySDZ6IE0yLjUsNUMyLjc3NjEsNSwzLDUuMjIzOSwz%0D%0ALDUuNSYjeEE7JiN4OTtTMi43NzYxLDYsMi41LDZTMiw1Ljc3NjEsMiw1LjVTMi4yMjM5LDUsMi41%0D%0ALDV6IE03LjUsNWMxLjY1NjksMCwzLDEuMzQzMSwzLDNzLTEuMzQzMSwzLTMsM3MtMy0xLjM0MzEt%0D%0AMy0zUzUuODQzMSw1LDcuNSw1eiYjeEE7JiN4OTsgTTcuNSw2LjVDNi42NzE2LDYuNSw2LDcuMTcx%0D%0ANiw2LDhsMCwwYzAsMC44Mjg0LDAuNjcxNiwxLjUsMS41LDEuNWwwLDBDOC4zMjg0LDkuNSw5LDgu%0D%0AODI4NCw5LDhsMCwwQzksNy4xNzE2LDguMzI4NCw2LjUsNy41LDYuNSYjeEE7JiN4OTtMNy41LDYu%0D%0ANXoiLz4KPC9zdmc+'); background-position: center;  background-repeat: no-repeat; cursor: default; padding: 5px; }
            #$map_id .mapboxgl-ctrl.mapboxgl-ctrl-group.ctrl-group-horizontal { height: 30px; }
            #$map_id .mapboxgl-ctrl.mapboxgl-ctrl-group.ctrl-group-horizontal > button { min-width: 30px; width: auto; height: 30px; display: inline-block !important; box-sizing: none; border-top: none; border-left: 1px solid #ddd; border-right: 1px solid #ddd;     vertical-align: top; }
            #$map_id .mapboxgl-ctrl.mapboxgl-ctrl-group.ctrl-group-horizontal > button > a { color: #6e6e6e; text-decoration: none; font: 12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif; }
            #$map_id .mapboxgl-ctrl.mapboxgl-ctrl-group.ctrl-group-horizontal > button:first-child,
            #$map_id .mapboxgl-ctrl.mapboxgl-ctrl-group.ctrl-group-horizontal > button:last-child { border: none; }
            #$map_id .mapboxgl-ctrl.mapboxgl-ctrl-group.ctrl-group-horizontal > button:not(:first-child) { padding: 0 4px 0 4px; }
            .mapboxgl-popup-content table tr { border: 1px solid #efefef; } .mapboxgl-popup-content table, td, tr { border: none; }
           <style>
        ''').substitute({"map_id": self.map_id})))

        display(Javascript(self.template)) 
Example #5
Source File: tutorial.py    From feets with MIT License 6 votes vote down vote up
def features_table():

    rows = []
    for feature, ext in feets.extractors.registered_extractors().items():
        if "Signature" in feature or "_harmonics_" in feature:
            continue
        row = (
            feature,
            ext.get_features().difference([feature]),
            ext.get_dependencies(),
            ext.get_data())
        rows.append(row)

    FourierComponents = feets.extractor_of("Freq2_harmonics_rel_phase_0")
    rows.append((
        "Freq{i}_harmonics_amplitude_{j}",
        ["Freq{i}_harmonics_amplitude_{j} and Freq{i}_harmonics_rel_phase_{j}"],
        FourierComponents.get_dependencies(), FourierComponents.get_data()
    ))

    return HTML(FEATURES_TABLE_TEMPLATE.render(rows=sorted(rows))) 
Example #6
Source File: visualization.py    From DOTA_models with Apache License 2.0 6 votes vote down vote up
def show_trace(self, trace, master_spec=None):
    """Returns a JS script HTML fragment, which will populate the container.

    Args:
      trace: binary-encoded MasterTrace string.
      master_spec: Master spec proto (parsed), which can improve the layout. May
        be required in future versions.

    Returns:
      unicode with HTML contents.
    """
    html = """
    <meta charset="utf-8"/>
    <script type='text/javascript'>
    document.getElementById("{elt_id}").innerHTML = "";  // Clear previous.
    visualizeToDiv({json}, "{elt_id}", {master_spec_json});
    </script>
    """.format(
        json=parse_trace_json(trace),
        master_spec_json=_optional_master_spec_json(master_spec),
        elt_id=self.elt_id)
    return unicode(html, 'utf-8')  # IPython expects unicode. 
Example #7
Source File: IPython_display.py    From feets with MIT License 6 votes vote down vote up
def anim_to_html(anim, fps=None, embed_frames=True, default_mode='loop'):
    """Generate HTML representation of the animation"""
    if fps is None and hasattr(anim, '_interval'):
        # Convert interval in ms to frames per second
        fps = 1000. / anim._interval

    plt.close(anim._fig)
    if hasattr(anim, "_html_representation"):
        return anim._html_representation
    else:
        # tempfile can't be used here: we need a filename, and this
        # fails on windows.  Instead, we use a custom filename generator
        #with tempfile.NamedTemporaryFile(suffix='.html') as f:
        with _NameOnlyTemporaryFile(suffix='.html') as f:
            anim.save(f.name,  writer=HTMLWriter(fps=fps,
                                                 embed_frames=embed_frames,
                                                 default_mode=default_mode))
            html = open(f.name).read()

        anim._html_representation = html
        return html 
Example #8
Source File: qutility.py    From sympsi with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def html_table(data):
    t_table = "<table>\n%s\n</table>"
    t_row = "<tr>%s</tr>"
    t_col = "<td>%s</td>"
    table_code = t_table % "".join(
        [t_row % "".join([t_col % ("$%s$" %
                                   latex(col).replace(r'\dag', r'\dagger'))
                          for col in row])
         for row in data])

    return HTML(table_code)


# -----------------------------------------------------------------------------
# Simplification of integrals
# 
Example #9
Source File: visualization.py    From Gun-Detector with Apache License 2.0 6 votes vote down vote up
def show_trace(self, trace, master_spec=None):
    """Returns a JS script HTML fragment, which will populate the container.

    Args:
      trace: binary-encoded MasterTrace string.
      master_spec: Master spec proto (parsed), which can improve the layout. May
        be required in future versions.

    Returns:
      unicode with HTML contents.
    """
    html = """
    <meta charset="utf-8"/>
    <script type='text/javascript'>
    document.getElementById("{elt_id}").innerHTML = "";  // Clear previous.
    visualizeToDiv({json}, "{elt_id}", {master_spec_json});
    </script>
    """.format(
        json=parse_trace_json(trace),
        master_spec_json=_optional_master_spec_json(master_spec),
        elt_id=self.elt_id)
    return unicode(html, 'utf-8')  # IPython expects unicode. 
Example #10
Source File: drawing.py    From discopy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def to_gif(diagram, *diagrams, path=None,
           timestep=500, loop=False, **params):  # pragma: no cover
    """
    Draws a sequence of diagrams.
    """
    steps, frames = (diagram, ) + diagrams, []
    path = path or os.path.basename(NamedTemporaryFile(
        suffix='.gif', prefix='tmp_', dir='.').name)
    with TemporaryDirectory() as directory:
        for i, _diagram in enumerate(steps):
            tmp_path = os.path.join(directory, '{}.png'.format(i))
            _diagram.draw(path=tmp_path, **params)
            frames.append(Image.open(tmp_path))
        if loop:
            frames = frames + frames[::-1]
        frames[0].save(path, format='GIF', append_images=frames[1:],
                       save_all=True, duration=timestep,
                       **{'loop': 0} if loop else {})
        return HTML('<img src="{}">'.format(path)) 
Example #11
Source File: backend_nbagg.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def __init__(self, manager):
        self.supports_binary = None
        self.manager = manager
        self.uuid = str(uuid.uuid4())
        # Publish an output area with a unique ID. The javascript can then
        # hook into this area.
        display(HTML("<div id=%r></div>" % self.uuid))
        try:
            self.comm = Comm('matplotlib', data={'id': self.uuid})
        except AttributeError:
            raise RuntimeError('Unable to create an IPython notebook Comm '
                               'instance. Are you in the IPython notebook?')
        self.comm.on_msg(self.on_message)

        manager = self.manager
        self._ext_close = False

        def _on_close(close_message):
            self._ext_close = True
            manager.remove_comm(close_message['content']['comm_id'])
            manager.clearup_closed()

        self.comm.on_close(_on_close) 
Example #12
Source File: drawTopicModel.py    From CheTo with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def drawMolsByLabel(topicModel, label, idLabelToMatch=0, baseRad=0.5, molSize=(250,150),\
                    numRowsShown=3, tableHeader='', maxMols=100):
        
    result = generateMoleculeSVGsbyLabel(topicModel, label, idLabelToMatch=idLabelToMatch,baseRad=baseRad,\
                                                              molSize=molSize, maxMols=maxMols)
    if len(result)  == 1:
        print(result)
        return
        
    svgs, namesSVGs = result
    finalsvgs = []
    for svg in svgs:
        # make the svg scalable
        finalsvgs.append(svg.replace('<svg','<svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 '+str(molSize[0])\
                                     +' '+str(molSize[1])+'"'))
    
    return display(HTML(utilsDrawing.drawSVGsToHTMLGrid(finalsvgs[:maxMols],cssTableName='overviewTab',tableHeader='Molecules of '+str(label),
                                                 namesSVGs=namesSVGs[:maxMols], size=molSize, numRowsShown=numRowsShown, numColumns=4)))

# produces a svg grid of the molecules of a certain label and highlights the most probable topic 
Example #13
Source File: backend_nbagg.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def __init__(self, manager):
        self.supports_binary = None
        self.manager = manager
        self.uuid = str(uuid.uuid4())
        # Publish an output area with a unique ID. The javascript can then
        # hook into this area.
        display(HTML("<div id=%r></div>" % self.uuid))
        try:
            self.comm = Comm('matplotlib', data={'id': self.uuid})
        except AttributeError:
            raise RuntimeError('Unable to create an IPython notebook Comm '
                               'instance. Are you in the IPython notebook?')
        self.comm.on_msg(self.on_message)

        manager = self.manager
        self._ext_close = False

        def _on_close(close_message):
            self._ext_close = True
            manager.remove_comm(close_message['content']['comm_id'])
            manager.clearup_closed()

        self.comm.on_close(_on_close) 
Example #14
Source File: load_style.py    From talk-2014-strata-sc with MIT License 6 votes vote down vote up
def load_style(s):
    """Load a CSS stylesheet in the notebook by URL or filename.

    Examples::
    
        %load_style mystyle.css
        %load_style http://ipynbstyles.com/otherstyle.css
    """
    if s.startswith('http'):
        r =requests.get(s)
        style = r.text
    else:
        with open(s, 'r') as f:
            style = f.read()
    s = '<style>\n{style}\n</style>'.format(style=style)
    display(HTML(s)) 
Example #15
Source File: display_util.py    From data-validation with Apache License 2.0 6 votes vote down vote up
def visualize_statistics(
    lhs_statistics: statistics_pb2.DatasetFeatureStatisticsList,
    rhs_statistics: Optional[
        statistics_pb2.DatasetFeatureStatisticsList] = None,
    lhs_name: Text = 'lhs_statistics',
    rhs_name: Text = 'rhs_statistics') -> None:
  """Visualize the input statistics using Facets.

  Args:
    lhs_statistics: A DatasetFeatureStatisticsList protocol buffer.
    rhs_statistics: An optional DatasetFeatureStatisticsList protocol buffer to
      compare with lhs_statistics.
    lhs_name: Name of the lhs_statistics dataset.
    rhs_name: Name of the rhs_statistics dataset.

  Raises:
    TypeError: If the input argument is not of the expected type.
    ValueError: If the input statistics protos does not have only one dataset.
  """
  html = get_statistics_html(lhs_statistics, rhs_statistics, lhs_name, rhs_name)
  display(HTML(html)) 
Example #16
Source File: backend_nbagg.py    From neural-network-animation with MIT License 6 votes vote down vote up
def __init__(self, manager):
        self.supports_binary = None
        self.manager = manager
        self.uuid = str(uuid())
        # Publish an output area with a unique ID. The javascript can then
        # hook into this area.
        display(HTML("<div id=%r></div>" % self.uuid))
        try:
            self.comm = Comm('matplotlib', data={'id': self.uuid})
        except AttributeError:
            raise RuntimeError('Unable to create an IPython notebook Comm '
                               'instance. Are you in the IPython notebook?')
        self.comm.on_msg(self.on_message)

        manager = self.manager
        self.comm.on_close(lambda close_message: manager.clearup_closed()) 
Example #17
Source File: nbinit.py    From msticpy with MIT License 6 votes vote down vote up
def _imp_from_package(
    nm_spc: Dict[str, Any], pkg: str, tgt: str = None, alias: str = None
):
    """Import object or submodule from `pkg`."""
    if not tgt:
        return _imp_module(nm_spc=nm_spc, module_name=pkg, alias=alias)
    try:
        # target could be a module
        obj = importlib.import_module(f".{tgt}", pkg)
    except (ImportError, ModuleNotFoundError):
        # if not, it must be an attribute (class, func, etc.)
        try:
            mod = importlib.import_module(pkg)
        except ImportError:
            display(HTML(_IMPORT_MODULE_MSSG.format(module=pkg)))
            raise
        obj = getattr(mod, tgt)
    if alias:
        nm_spc[alias] = obj
    else:
        nm_spc[tgt] = obj
    if _VERBOSE():  # type: ignore
        print(f"{tgt} imported from {pkg} (alias={alias})")
    return obj 
Example #18
Source File: visualization.py    From yolo_v2 with Apache License 2.0 6 votes vote down vote up
def show_trace(self, trace, master_spec=None):
    """Returns a JS script HTML fragment, which will populate the container.

    Args:
      trace: binary-encoded MasterTrace string.
      master_spec: Master spec proto (parsed), which can improve the layout. May
        be required in future versions.

    Returns:
      unicode with HTML contents.
    """
    html = """
    <meta charset="utf-8"/>
    <script type='text/javascript'>
    document.getElementById("{elt_id}").innerHTML = "";  // Clear previous.
    visualizeToDiv({json}, "{elt_id}", {master_spec_json});
    </script>
    """.format(
        json=parse_trace_json(trace),
        master_spec_json=_optional_master_spec_json(master_spec),
        elt_id=self.elt_id)
    return unicode(html, 'utf-8')  # IPython expects unicode. 
Example #19
Source File: backend_nbagg.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, manager):
        self.supports_binary = None
        self.manager = manager
        self.uuid = str(uuid.uuid4())
        # Publish an output area with a unique ID. The javascript can then
        # hook into this area.
        display(HTML("<div id=%r></div>" % self.uuid))
        try:
            self.comm = Comm('matplotlib', data={'id': self.uuid})
        except AttributeError:
            raise RuntimeError('Unable to create an IPython notebook Comm '
                               'instance. Are you in the IPython notebook?')
        self.comm.on_msg(self.on_message)

        manager = self.manager
        self._ext_close = False

        def _on_close(close_message):
            self._ext_close = True
            manager.remove_comm(close_message['content']['comm_id'])
            manager.clearup_closed()

        self.comm.on_close(_on_close) 
Example #20
Source File: notebook.py    From rsmtool with Apache License 2.0 5 votes vote down vote up
def color_highlighter(num, low=0, high=1, prec=3, absolute=False):
    """
    Instantiating ``custom_highlighter()`` with the ``color`` class as
    the default.

    Parameters:
    -----------
    num : float
        The floating point number to format.
    low : float
        The number will be displayed as an HTML span it is below this value.
        Defaults to 0.
    high : float
        The number will be displayed as an HTML span it is above this value.
        Defaults to 1.
    prec : int
        The number of decimal places to display for x.
        Defaults to 3.
    absolute: bool
        If True, use the absolute value of x for comparison.
        Defaults to False.

    Returns:
    --------
    ans : str
        The formatted highlighter with color class as default.
    """
    ans = custom_highlighter(num, low, high, prec, absolute, 'color')
    return ans 
Example #21
Source File: talktools.py    From metocean with The Unlicense 5 votes vote down vote up
def html_link(url, name=None):
    return HTML(simple_link(url, name))


# Utility functions 
Example #22
Source File: EventPlot.py    From trappy with Apache License 2.0 5 votes vote down vote up
def _add_css(self):
        """Append the CSS to the HTML code generated"""

        base_dir = os.path.dirname(os.path.realpath(__file__))
        css_file = os.path.join(base_dir, "css/EventPlot.css")
        self._html.append("<style>")

        with open(css_file, 'r') as css_fh:
            self._html += [l[:-1] for l in css_fh.readlines()]

        self._html.append("</style>") 
Example #23
Source File: chi2_analyzer.py    From assistant-dialog-skill-analysis with Apache License 2.0 5 votes vote down vote up
def chi2_overlap_check(ambiguous_unigram_df, ambiguous_bigram_df, intent1, intent2):
    """
    looks for intent overlap for specific intent or intent pairs
    :param ambiguous_unigram_df:
    :param ambiguous_bigram_df:
    :param intent1:
    :param intent2:
    """
    intent = intent1 + ", " + intent2 + "|" + intent2 + ", " + intent1
    part1 = None
    part2 = None
    if not ambiguous_unigram_df.empty:
        part1 = ambiguous_unigram_df[
            ambiguous_unigram_df["Intent Pairs"].str.contains(intent)
        ]

    if not ambiguous_bigram_df.empty:
        part2 = ambiguous_bigram_df[
            ambiguous_bigram_df["Intent Pairs"].str.contains(intent)
        ]

    if part1 is not None and part2 is not None:
        display(HTML(pd.concat([part1, part2]).to_html(index=False)))
    elif part1 is not None:
        display(HTML(part1.to_html(index=False)))
    elif part2 is not None:
        display(HTML(part2.to_html(index=False))) 
Example #24
Source File: notebook.py    From rsmtool with Apache License 2.0 5 votes vote down vote up
def show_thumbnail(path_to_image, image_id, path_to_thumbnail=None):
    """
    Given an path to an image file, display
    a click-able thumbnail version of the image.
    On click, open the full-sized version of the
    image in a new window.

    Parameters
    ----------
    path_to_image : str
        The absolute or relative path to the image.
        If an absolute path is provided, it will be
        converted to a relative path.
    image_id : int
        The id of the <img> tag in the HTML. This must
        be unique for each <img> tag.
    path_to_thumbnail : str or None, optional
        If you would like to use a different thumbnail
        image, specify the path to the thumbnail.
        Defaults to None.

    Displays
    --------
    display : IPython.core.display.HTML
        The HTML display of the thumbnail image.
    """
    display(HTML(get_thumbnail_as_html(path_to_image,
                                       image_id,
                                       path_to_thumbnail))) 
Example #25
Source File: notebook.py    From rsmtool with Apache License 2.0 5 votes vote down vote up
def bold_highlighter(num, low=0, high=1, prec=3, absolute=False):
    """
    Instantiating ``custom_highlighter()`` with the ``bold`` class as
    the default.

    Parameters:
    -----------
    num : float
        The floating point number to format.
    low : float
        The number will be displayed as an HTML span it is below this value.
        Defaults to 0.
    high : float
        The number will be displayed as an HTML span it is above this value.
        Defaults to 1.
    prec : int
        The number of decimal places to display for x.
        Defaults to 3.
    absolute: bool
        If True, use the absolute value of x for comparison.
        Defaults to False.

    Returns:
    --------
    ans : str
        The formatted highlighter with bold class as default.
    """
    ans = custom_highlighter(num, low, high, prec, absolute, 'bold')
    return ans 
Example #26
Source File: notebook.py    From docker-python with Apache License 2.0 5 votes vote down vote up
def _tensorboard_magic(line):
    """Line magic function.

    Makes an AJAX call to the Jupyter TensorBoard server extension and outputs
    an IFrame displaying the TensorBoard instance.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('--logdir', default='/kaggle/working')
    args = parser.parse_args(line.split())
    
    iframe_id = 'tensorboard-' + str(uuid.uuid4())
        
    html = """
<!-- JUPYTER_TENSORBOARD_TEST_MARKER -->
<script>
    const req = {
        method: 'POST',
        contentType: 'application/json',
        body: JSON.stringify({ 'logdir': '%s' }),
        headers: { 'Content-Type': 'application/json' }
    };

    const baseUrl = Jupyter.notebook.base_url;

    fetch(baseUrl + 'api/tensorboard', req)
        .then(res => res.json())
        .then(res => {
            const iframe = document.getElementById('%s');
            iframe.src = baseUrl + 'tensorboard/' + res.name;
            iframe.style.display = 'block';
        });
</script>

<iframe
    id="%s"
    style="width: 100%%; height: 620px; display: none;"
    frameBorder="0">
</iframe>
""" % (args.logdir, iframe_id, iframe_id)
    
    display(HTML(html)) 
Example #27
Source File: notebook.py    From rsmtool with Apache License 2.0 5 votes vote down vote up
def custom_highlighter(num,
                       low=0,
                       high=1,
                       prec=3,
                       absolute=False,
                       span_class='bold'):
    """
    Return the supplied float as an HTML <span> element with the specified
    class if its value is below ``low`` or above ``high``. If its value does
    not meet those constraints, then return as a plain string with the
    specified number of decimal places.

    Parameters:
    -----------
    num : float
        The floating point number to format.
    low : float
        The number will be displayed as an HTML span it is below this value.
        Defaults to 0.
    high : float
        The number will be displayed as an HTML span it is above this value.
        Defaults to 1.
    prec : int
        The number of decimal places to display for x. Defaults to 3.
    absolute: bool
        If True, use the absolute value of x for comparison.
        Defaults to False.
    span_class: str
        One of ``bold`` or ``color``. These are the two classes
        available for the HTML span tag.

    Returns:
    --------
    ans : str
        The formatted (plain or HTML) string representing the given number.
    """
    abs_num = abs(num) if absolute else num
    val = float_format_func(num, prec=prec)
    ans = ('<span class="highlight_{}">{}</span>'.format(span_class, val)
           if abs_num < low or abs_num > high else val)
    return ans 
Example #28
Source File: EventPlot.py    From trappy with Apache License 2.0 5 votes vote down vote up
def view(self):
        """Views the Graph Object"""

        # Defer installation of IPython components
        # to the .view call to avoid any errors at
        # when importing the module. This facilitates
        # the importing of the module from outside
        # an IPython notebook
        IPythonConf.iplot_install("EventPlot")
        display(HTML(self.html())) 
Example #29
Source File: __init__.py    From MPContribs with MIT License 5 votes vote down vote up
def pretty(self, attrs='class="table"'):
        return display(
            HTML(j2h.convert(json=remap(self, visit=visit), table_attributes=attrs))
        ) 
Example #30
Source File: EventPlot.py    From trappy with Apache License 2.0 5 votes vote down vote up
def __init__(
            self,
            data,
            keys,
            domain,
            lane_prefix="Lane: ",
            num_lanes=0,
            summary=True,
            stride=False,
            lanes=None,
            color_map=None):

        _data = deepcopy(data)
        self._html = []
        self._fig_name = self._generate_fig_name()
        # Function to get the average duration of each event
        avgFunc = lambda x: sum([(evt[1] - evt[0]) for evt in x]) / float(len(x) + 1)
        avg = {k: avgFunc(v) for k, v in data.items()}
        # Filter keys with zero average time
        keys = [x for x in avg if avg[x] != 0]
        graph = {}
        graph["lanes"] = self._get_lanes(lanes, lane_prefix, num_lanes, _data)
        graph["xDomain"] = domain
        graph["keys"] = sorted(keys, key=lambda x: avg[x], reverse=True)
        graph["showSummary"] = summary
        graph["stride"] = AttrConf.EVENT_PLOT_STRIDE
        graph["colorMap"] = color_map
        graph["data"] = self._group_data_by_lanes(_data)
        self._data = json.dumps(graph)

        # Initialize the HTML, CSS and JS Components
        self._add_css()
        self._init_html()