Python IPython.display.Javascript() Examples

The following are 30 code examples of IPython.display.Javascript(). 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: __init__.py    From paramnb with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def run_next_cells(n):
    if n=='all':
        n = 'NaN'
    elif n<1:
        return

    js_code = """
       var num = {0};
       var run = false;
       var current = $(this)[0];
       $.each(IPython.notebook.get_cells(), function (idx, cell) {{
          if ((cell.output_area === current) && !run) {{
             run = true;
          }} else if ((cell.cell_type == 'code') && !(num < 1) && run) {{
             cell.execute();
             num = num - 1;
          }}
       }});
    """.format(n)

    display(Javascript(js_code)) 
Example #2
Source File: files.py    From SlicerJupyter with MIT License 6 votes vote down vote up
def notebookSaveCheckpoint():
    """Save a checkpoint of current notebook. Returns True on success."""
    try:
      from IPython.display import Javascript
      from IPython.display import display
    except ModuleNotFoundError:
      import logging
      logging.error("notebookSaveCheckpoint requires ipywidgets. It can be installed by running this command:\n\n    pip_install('ipywidgets')\n")
      return False

    script = '''
    require(["base/js/namespace"],function(Jupyter) {
        Jupyter.notebook.save_checkpoint();
    });
    '''
    display(Javascript(script))
    return True 
Example #3
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 #4
Source File: javascript_magic.py    From metakernel with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def cell_javascript(self):
        """
        %%javascript - send contents of cell as JavaScript

        This cell magic will execute the contents of the cell as
        JavaScript in the browser.

        Example:
            %%javascript

            element.html("Hello this is <b>bold</b>!")

        """
        if self.code.strip():
            jscode = Javascript(self.code)
            self.kernel.Display(jscode)
            self.evaluate = False 
Example #5
Source File: zmqshell.py    From Computable with MIT License 6 votes vote down vote up
def autosave(self, arg_s):
        """Set the autosave interval in the notebook (in seconds).
        
        The default value is 120, or two minutes.
        ``%autosave 0`` will disable autosave.
        
        This magic only has an effect when called from the notebook interface.
        It has no effect when called in a startup file.
        """
        
        try:
            interval = int(arg_s)
        except ValueError:
            raise UsageError("%%autosave requires an integer, got %r" % arg_s)
        
        # javascript wants milliseconds
        milliseconds = 1000 * interval
        display(Javascript("IPython.notebook.set_autosave_interval(%i)" % milliseconds),
            include=['application/javascript']
        )
        if interval:
            print("Autosaving every %i seconds" % interval)
        else:
            print("Autosave disabled") 
Example #6
Source File: archive.py    From holoviews with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def auto(self, enabled=True, clear=False, **kwargs):
        """
        Method to enable or disable automatic capture, allowing you to
        simultaneously set the instance parameters.
        """
        self.namespace = self.get_namespace()
        self.notebook_name = "{notebook}"
        self._timestamp = tuple(time.localtime())
        kernel = r'var kernel = IPython.notebook.kernel; '
        nbname = r"var nbname = IPython.notebook.get_notebook_name(); "
        nbcmd = (r"var name_cmd = '%s.notebook_name = \"' + nbname + '\"'; " % self.namespace)
        cmd = (kernel + nbname + nbcmd + "kernel.execute(name_cmd); ")
        display(Javascript(cmd))
        time.sleep(0.5)
        self._auto=enabled
        self.param.set_param(**kwargs)
        tstamp = time.strftime(" [%Y-%m-%d %H:%M:%S]", self._timestamp)
        # When clear == True, it clears the archive, in order to start a new auto capture in a clean archive
        if clear:
            FileArchive.clear(self)
        print("Automatic capture is now %s.%s"
              % ('enabled' if enabled else 'disabled',
                 tstamp if enabled else '')) 
Example #7
Source File: jupyter_cells.py    From pylustrator with GNU General Public License v3.0 6 votes vote down vote up
def setJupyterCellText(text: str):
    """ the function replaces the text in the current jupyter cell with the given text """
    from IPython.display import Javascript, display
    text = text.replace("\n", "\\n").replace("'", "\\'")
    js = """
    var output_area = this;
    // find my cell element
    var cell_element = output_area.element.parents('.cell');
    // which cell is it?
    var cell_idx = Jupyter.notebook.get_cell_elements().index(cell_element);
    // get the cell object
    var cell = Jupyter.notebook.get_cell(cell_idx);
    cell.get_text();
    cell.set_text('"""+text+"""');
    console.log('"""+text+"""');
    """
    display(Javascript(js)) 
Example #8
Source File: jupyternotify.py    From jupyter-notify with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def display_notification(self, options=None, notification_uuid=None):
        if options is None:
            options = self.options
        if notification_uuid is None:
            notification_uuid = uuid.uuid4()

        # display our browser notification using javascript
        with open(resource_filename("jupyternotify", "js/notify.js")) as jsFile:
            jsString = jsFile.read()
        display(Javascript(jsString % {
            "notification_uuid": notification_uuid,
            "options": json.dumps(options),
        })) 
Example #9
Source File: Progress_Bar.py    From qkit with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, max_it, name = 'Progress:',est_cycle_time=None,dummy=False):
            if debug:
                print("old style progress bar")
            #create HTML progress bar
            self._dummy = dummy
            if self._dummy:
                return
            self.divid = str(uuid.uuid4())
            self.max_it = max_it
            self.name = name
            self.progr = 0

            #delete existing progress bar with same name
            display(Javascript("if(document.getElementById('%st') !== null) document.getElementById('%st').parentNode.remove()"%(self.name,self.name)))
            #display(Javascript("if(document.getElementById('%s') !== null) document.getElementById('%s').remove()"%(self.name,self.name)))
               
            outp = "<table style='width:100%%;border:none'><tr style='border:none'><td style='border:none'>%s (%i/%i) </td><td style='border:none'>&#9992; %s    </td><td style='border:none'>&#128336;  %s   (estimated)</td><td style='border:none'>&#10010;  %s (elapsed) </td><td style='border:none'>&#9866;  %s (remaining)</td></tr></table>"%("",
                    0,
                    self.max_it,
                    "-?-" if est_cycle_time==None else time.strftime('%Y-%m-%d (%a) %H:%M:%S', time.localtime(time.time() + est_cycle_time * self.max_it )),
                    "--:--:--" if est_cycle_time==None else hourformat(est_cycle_time*self.max_it),
                    "00:00:00",
                    "--:--:--" if est_cycle_time==None else hourformat(est_cycle_time*self.max_it))
           
            self.pb = HTML(
            """
            <div id="%s_title"> %s</div>
            <div id="%s1" style="border: 1px solid black; width:900px">
              <div id="%s0" style="text-align: center; color:white; background-color:blue; width:0%%">&nbsp;</div>
            </div>
            <div id="%s_text">%s</div>
            """ % (self.divid,self.name,self.divid,self.divid,self.divid,outp))
            display(self.pb)
            display(Javascript("$('div#%s').width('%i%%')" % (self.divid, 100*self.progr/self.max_it)))
            sys.stdout.flush()
            self.starttime = time.time()
            self.start_eta_time = time.time() 
Example #10
Source File: Progress_Bar.py    From qkit with GNU General Public License v2.0 5 votes vote down vote up
def _update(self,param=""):
            if self._dummy:
                return
            display(Javascript("$('div#%s0').width('%i%%');" % (self.divid, 100*self.progr/self.max_it)))
            outp = "<table style='width:100%%;border:none'><tr style='border:none'><td style='border:none'>%s (%i/%i) </td><td style='border:none'>&#9992; %s    </td><td style='border:none'>&#128336;  %s   (estimated)</td><td style='border:none'>&#10010;  %s (elapsed) </td><td style='border:none'>&#9866;  %s (remaining)</td></tr></table>"%(param,     #"%s (%i/%i) &#10148;  ETA: %s &#10148; Time elapsed: %s" %(param,
                    self.progr,
                    self.max_it,
                    time.strftime('%Y-%m-%d (%a) %H:%M:%S', time.localtime(time.time() + float(time.time()-self.start_eta_time)/(self.progr-(0 if self.progr == 1 else 1)) * (self.max_it  - self.progr))), #ETA
                    hourformat(self.start_eta_time-self.starttime+float(time.time()-self.start_eta_time)/(self.progr-(0 if self.progr == 1 else 1)) * (self.max_it )), #estimated
                    hourformat(time.time()-self.starttime), #elapsed
                    hourformat(float(time.time()-self.start_eta_time)/(self.progr-(0 if self.progr == 1 else 1)) * (self.max_it  - self.progr))) #remaining
            if self.progr == 1:
                "this is a little academic, but the time between the first and the second iteration has usually a time lag."
                self.start_eta_time = time.time()
            #outp = "%s (%i/%i) &#10148;  ETA: %s &#10148; Time elapsed: %s"%(param,self.progr,self.max_it,time.ctime(time.time() + float(time.time()-self.starttime)/self.progr * (self.max_it - self.progr)),time.strftime('%H:%M:%S',time.gmtime(time.time()-self.starttime)))
            display(Javascript("document.getElementById('%s_text').innerHTML = \"%s\";"%(self.divid,outp)))

            if self.progr == self.max_it:   #end of progress bar
                #Turn the status bar into green
                #Delete all <div> containers
                outp = "%s (%i/%i) &#9992; %s    &#10010;  %s  "%(param,     #"%s (%i/%i) &#10148;  ETA: %s &#10148; Time elapsed: %s" %(param,
                    self.progr,
                    self.max_it,
                    time.strftime('%Y-%m-%d (%a) %H:%M:%S'),
                    hourformat(time.time()-self.starttime))
                display(Javascript("document.getElementById('%s_title').parentNode.remove();"%self.divid)) #title
                self.pb = HTML(
                """
                <div id="%st"> %s</div>
                <div id="%s" style="border: 1px solid black; width:900px;text-align: center; color:white; background-color:green;">%s
                </div>
                """ % (self.name, self.name, self.name, outp))
                display(self.pb) 
Example #11
Source File: Progress_Bar.py    From qkit with GNU General Public License v2.0 5 votes vote down vote up
def abort(self):
            if self._dummy:
                return
            display(Javascript("$('div#%s0').css('background-color', 'red');" % (self.divid))) 
Example #12
Source File: backend_nbagg.py    From ImageFusion with MIT License 5 votes vote down vote up
def display_js(self):
        # XXX How to do this just once? It has to deal with multiple
        # browser instances using the same kernel (require.js - but the
        # file isn't static?).
        display(Javascript(FigureManagerNbAgg.get_javascript())) 
Example #13
Source File: lab_black.py    From nb_black with MIT License 5 votes vote down vote up
def __set_cell(self, unformatted_cell, cell, cell_id=None):
        if self.is_lab:
            self.shell.set_next_input(cell, replace=True)
        else:
            js_code = """
            setTimeout(function() {
                var nbb_cell_id = %d;
                var nbb_unformatted_code = %s;
                var nbb_formatted_code = %s;
                var nbb_cells = Jupyter.notebook.get_cells();
                for (var i = 0; i < nbb_cells.length; ++i) {
                    if (nbb_cells[i].input_prompt_number == nbb_cell_id) {
                        if (nbb_cells[i].get_text() == nbb_unformatted_code) {
                             nbb_cells[i].set_text(nbb_formatted_code);
                        }
                        break;
                    }
                }
            }, 500);
            """
            js_code = js_code % (
                cell_id,
                json.dumps(unformatted_cell),
                json.dumps(cell),
            )
            display(Javascript(js_code)) 
Example #14
Source File: archive.py    From holoviews with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def export(self, timestamp=None):
        """
        Get the current notebook data and export.
        """
        if self._timestamp is None:
            raise Exception("No timestamp set. Has the archive been initialized?")
        if self.skip_notebook_export:
            super(NotebookArchive, self).export(timestamp=self._timestamp,
                                                info={'notebook':self.notebook_name})
            return

        self.export_success = None
        name = self.get_namespace()
        # Unfortunate javascript hacks to get at notebook data
        capture_cmd = ((r"var capture = '%s._notebook_data=r\"\"\"'" % name)
                       + r"+json_string+'\"\"\"'; ")
        cmd = (r'var kernel = IPython.notebook.kernel; '
               + r'var json_data = IPython.notebook.toJSON(); '
               + r'var json_string = JSON.stringify(json_data); '
               + capture_cmd
               + "var pycmd = capture + ';%s._export_with_html()'; " % name
               + r"kernel.execute(pycmd)")

        tstamp = time.strftime(self.timestamp_format, self._timestamp)
        export_name = self._format(self.export_name, {'timestamp':tstamp, 'notebook':self.notebook_name})
        print(('Export name: %r\nDirectory    %r' % (export_name,
                                                     os.path.join(os.path.abspath(self.root))))
               + '\n\nIf no output appears, please check holoviews.archive.last_export_status()')
        display(Javascript(cmd)) 
Example #15
Source File: jupyternotify.py    From jupyter-notify with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, shell, require_interaction=False):
        super(JupyterNotifyMagics, self).__init__(shell)
        with open(resource_filename("jupyternotify", "js/init.js")) as jsFile:
            jsString = jsFile.read()
        display(Javascript(jsString))
        self.options = {
            "requireInteraction": require_interaction,
            "icon": "/static/base/images/favicon.ico",
        } 
Example #16
Source File: _history.py    From colabtools with Apache License 2.0 5 votes vote down vote up
def _history_with_cells_as_json(self):
    """Utility accessor to allow frontends an expression to fetch history.

    Returns:
      A Javascript display object with the execution history.
    """
    # To be able to access the raw string as an expression we need to transfer
    # the plain string rather than the quoted string representation. The
    # Javascript display wrapper is used for that.
    return display.Javascript(json.dumps(self._input_hist_cells)) 
Example #17
Source File: util.py    From ppci with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run_wasm_in_notebook(wasm):
    """ Load a WASM module in the Jupyter notebook.
    """
    from .components import Module
    from IPython.display import display, HTML, Javascript

    if isinstance(wasm, Module):
        wasm = wasm.to_bytes()
    elif isinstance(wasm, bytes):
        if not wasm.startswith(b"\x00asm"):
            raise ValueError("given bytes do not look like a wasm module.")
    else:
        raise TypeError("expects a wasm module or bytes.")

    wasm_text = str(list(wasm))  # [0, 1, 12, ...]

    # Read templates
    src_filename_js = os.path.join(os.path.dirname(__file__), "template.js")
    with open(src_filename_js, "rb") as f:
        js = f.read().decode()

    # Get id
    global _nb_output
    _nb_output += 1
    id = "wasm_output_%u" % _nb_output

    # Produce JS
    js = js.replace("wasm_output", id)
    js = js.replace("MAIN_JS_PLACEHOLDER", "")
    js = js.replace(
        "WASM_PLACEHOLDER",
        "var wasm_data = new Uint8Array(" + wasm_text + ");",
    )
    js = "(function() {\n%s;\ncompile_my_wasm();\n})();" % js

    # Output in current cell
    display(HTML("<div style='border: 2px solid blue;' id='%s'></div>" % id))
    display(Javascript(js)) 
Example #18
Source File: javascript_magic.py    From metakernel with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def line_javascript(self, code):
        """
        %javascript CODE - send code as JavaScript

        This line magic will execute the CODE on the line as
        JavaScript in the browser.

        Example:
            %javascript console.log("Print in the browser console")

        """
        jscode = Javascript(code)
        self.kernel.Display(jscode) 
Example #19
Source File: backend_nbagg.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def display_js(self):
        # XXX How to do this just once? It has to deal with multiple
        # browser instances using the same kernel (require.js - but the
        # file isn't static?).
        display(Javascript(FigureManagerNbAgg.get_javascript())) 
Example #20
Source File: backend_nbagg.py    From CogAlg with MIT License 5 votes vote down vote up
def display_js(self):
        # XXX How to do this just once? It has to deal with multiple
        # browser instances using the same kernel (require.js - but the
        # file isn't static?).
        display(Javascript(FigureManagerNbAgg.get_javascript())) 
Example #21
Source File: notebook.py    From ok-client with Apache License 2.0 5 votes vote down vote up
def save_notebook(self):
        """ Saves the current notebook by
        injecting JavaScript to save to .ipynb file.
        """
        try:
            from IPython.display import display, Javascript
        except ImportError:
            log.warning("Could not import IPython Display Function")
            print("Make sure to save your notebook before sending it to OK!")
            return

        if self.mode == "jupyter":
            display(Javascript('IPython.notebook.save_checkpoint();'))
            display(Javascript('IPython.notebook.save_notebook();'))
        elif self.mode == "jupyterlab":
            display(Javascript('document.querySelector(\'[data-command="docmanager:save"]\').click();'))   
                       
        print('Saving notebook...', end=' ')

        ipynbs = [path for path in self.assignment.src
                  if os.path.splitext(path)[1] == '.ipynb']
        # Wait for first .ipynb to save
        if ipynbs:
            if wait_for_save(ipynbs[0]):
                print("Saved '{}'.".format(ipynbs[0]))
            else:
                log.warning("Timed out waiting for IPython save")
                print("Could not automatically save \'{}\'".format(ipynbs[0]))
                print("Make sure your notebook"
                      " is correctly named and saved before submitting to OK!".format(ipynbs[0]))
                return False                
        else:
            print("No valid file sources found")
        return True 
Example #22
Source File: backend_nbagg.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def display_js(self):
        # XXX How to do this just once? It has to deal with multiple
        # browser instances using the same kernel (require.js - but the
        # file isn't static?).
        display(Javascript(FigureManagerNbAgg.get_javascript())) 
Example #23
Source File: backend_nbagg.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def display_js(self):
        # XXX How to do this just once? It has to deal with multiple
        # browser instances using the same kernel (require.js - but the
        # file isn't static?).
        display(Javascript(FigureManagerNbAgg.get_javascript())) 
Example #24
Source File: display_graph.py    From gated-graph-transformer-network with MIT License 5 votes vote down vote up
def noninteractive_next():
    return Javascript("window.nonint_next()") 
Example #25
Source File: display_graph.py    From gated-graph-transformer-network with MIT License 5 votes vote down vote up
def setup_graph_display():
    with open(os.path.join(os.path.dirname(__file__), "display_graph.js"), 'r') as f:
        JS_SETUP_STRING = f.read()
    return Javascript(JS_SETUP_STRING) 
Example #26
Source File: labeled_trees.py    From pytreebank with MIT License 5 votes vote down vote up
def to_dict(self, index=0):
        """
        Dict format for use in Javascript / Jason Chuang's display technology.
        """
        index += 1
        rep = {}
        rep["index"] = index
        rep["leaf"] = len(self.children) == 0
        rep["depth"] = self.udepth
        rep["scoreDistr"] = [0.0] * len(LabeledTree.SCORE_MAPPING)
        # dirac distribution at correct label
        if self.label is not None:
            rep["scoreDistr"][self.label] = 1.0
            mapping = LabeledTree.SCORE_MAPPING[:]
            rep["rating"] = mapping[self.label] - min(mapping)
        # if you are using this method for printing predictions
        # from a model, the the dot product with the model's output
        # distribution should be taken with this list:
        rep["numChildren"] = len(self.children)
        text = self.text if self.text != None else ""
        seen_tokens = 0
        witnessed_pixels = 0
        for i, child in enumerate(self.children):
            if i > 0:
                text += " "
            child_key = "child%d" % (i)
            (rep[child_key], index) = child.to_dict(index)
            text += rep[child_key]["text"]
            seen_tokens += rep[child_key]["tokens"]
            witnessed_pixels += rep[child_key]["pixels"]

        rep["text"] = text
        rep["tokens"] = 1 if (self.text != None and len(self.text) > 0) else seen_tokens
        rep["pixels"] = witnessed_pixels + 3 if len(self.children) > 0 else text_size(self.text)
        return (rep, index) 
Example #27
Source File: labeled_trees.py    From pytreebank with MIT License 5 votes vote down vote up
def display(self):
        from IPython.display import Javascript, display

        display(Javascript("createTrees(["+self.to_json()+"])"))
        display(Javascript("updateTrees()")) 
Example #28
Source File: labeled_trees.py    From pytreebank with MIT License 5 votes vote down vote up
def inject_visualization_javascript(tree_width=1200, tree_height=400, tree_node_radius=10):
        """
        In an Ipython notebook, show SST trees using the same Javascript
        code as used by Jason Chuang's visualisations.
        """
        from .javascript import insert_sentiment_markup
        insert_sentiment_markup(tree_width=tree_width, tree_height=tree_height, tree_node_radius=tree_node_radius) 
Example #29
Source File: inline.py    From pybel with MIT License 5 votes vote down vote up
def to_jupyter(
    graph: BELGraph,
    width: int = DEFAULT_WIDTH,
    height: int = DEFAULT_HEIGHT,
    color_map: Optional[Mapping[str, str]] = None,
):
    """Display a BEL graph inline in a Jupyter notebook.

    To use successfully, make run as the last statement in a cell inside a Jupyter notebook.

    :param graph: A BEL graph
    :param width: The width of the visualization window to render
    :param height: The height of the visualization window to render
    :param color_map: A dictionary from PyBEL internal node functions to CSS color strings like #FFEE00. Defaults
                    to :data:`default_color_map`
    :return: An IPython notebook Javascript object
    :rtype: :class:`IPython.display.Javascript`
    """
    from IPython.display import Javascript

    return Javascript(to_jupyter_str(
        graph,
        width=width,
        height=height,
        color_map=color_map,
    )) 
Example #30
Source File: inline.py    From pybel with MIT License 5 votes vote down vote up
def to_jupyter_str(
    graph: BELGraph,
    width: int = DEFAULT_WIDTH,
    height: int = DEFAULT_HEIGHT,
    color_map: Optional[Mapping[str, str]] = None,
) -> str:
    """Return the string to be javascript-ified by the Jupyter notebook function :class:`IPython.display.Javascript`.

    :param graph: A BEL graph
    :param width: The width of the visualization window to render
    :param height: The height of the visualization window to render
    :param color_map: A dictionary from PyBEL internal node functions to CSS color strings like #FFEE00. Defaults
                    to :data:`default_color_map`
    :return: The javascript string to turn into magic
    """
    gjson = to_nodelink_jsons(graph)
    chart_id = _generate_id()

    #: Renders templates from pybel.io.jupyter.templates folder
    render_template = build_template_renderer(__file__)

    return render_template(
        'pybel_jupyter.js',
        graph=gjson,
        chart=chart_id,
        width=width,
        height=height,
        color_map=(color_map or DEFAULT_COLOR_MAP),
    )