Exemplo n.º 1
0
def build_context():
    """Builds a javascript context."""
    threejs_url = 'https://www.gstatic.com/external_hosted/threejs-r98/'
    _publish.javascript(url=threejs_url + 'three.min.js')
    _publish.javascript(url=threejs_url +
                        'examples/js/controls/OrbitControls.js')
    return _js_builder.Js(mode=_js_builder.PERSISTENT)
Exemplo n.º 2
0
    def _publish(self):
        """Publishes this tab bar in the given cell.

    Note: this function is idempotent.
    """
        if self._published:
            return
        content_height = 'initial',
        content_border = '0px',
        border_color = '#a7a7a7',
        self._content_div = self._id + '_content'
        super(TabBar, self)._publish()
        with self._output_in_widget():
            _publish.css(url=self.TAB_CSS)
            _publish.javascript(url=self.TABBAR_JS)
            _publish.html(self._html_repr())

            js.js_global.colab_lib.createTabBar({
                'location': self._location,
                'elementId': self._id,
                'tabNames': self.tab_names,
                'initialSelection': self._active,
                'contentBorder': content_border,
                'contentHeight': content_height,
                'borderColor': border_color,
            })
            # Note: publish() will only be called once, thus this will never change
            # already visible tab.
            js.js_global[self._id].setSelectedTabIndex(0)
Exemplo n.º 3
0
 def _get_javascript_runner(self, mode):
     """Returns an appropriate function that executes the given javascript."""
     if mode == PERSISTENT:
         # Note: want lazy binding, particularly for tests to be able
         # to inject custom handling.
         # pylint: disable=unnecessary-lambda
         return lambda x: _publish.javascript(x)
     elif mode == EVAL:
         # Note: we don't want javascript value on python side
         # unless user specifically requests it using .eval().
         # This allows us to properly chain function and javascript class
         # (since those are not serializable) and eliminates the need to wait
         # for frontend to return.
         return lambda x: _js.eval_js('(()=>{' + x + '})()',
                                      ignore_result=True)
     else:
         raise JsException('Invalid mode: %r.' % mode)
def custom_latex_printer(exp,**options):
    from google.colab.output._publish import javascript
    url = "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/latest.js?config=TeX-AMS_HTML"
    javascript(url=url)
    return sym.printing.latex(exp,**options)
def draw_tree(tree):
    """
    tree = {'a/0.5': {}, 'b/0.5': {'B/0.5': {}}, }
    """
    from uuid import uuid4
    tree_id = "tree_" + uuid4().hex

    drawcalls = []
    drawcalls.append('g.setNode("c", { label: "context" , shape: "circle" });')
    drawcalls.append('g.node("c").style = "fill: #7f7";')

    # Just do it recursively
    def _draw_subtree(subtree, prefix=''):
        for i, (label, subsubtree) in enumerate(subtree.items()):
            node_id = prefix + '_' + str(i)
            drawcalls.append('g.setNode("' + node_id +
                             '", { label: "" , shape: "circle" });')
            drawcalls.append('g.setEdge("' + prefix + '", "' + node_id +
                             '", { arrowhead: "vee", label: ' +
                             json.dumps(label) + '});')
            _draw_subtree(subsubtree, node_id)

    _draw_subtree(tree, 'c')

    if len(drawcalls) > 1200:
        return "Tree too large to draw!"

    try:
        from google.colab.output._publish import javascript
        javascript(
            url="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js")
        javascript(
            url=
            "https://cdnjs.cloudflare.com/ajax/libs/dagre-d3/0.6.1/dagre-d3.min.js"
        )
        non_colab = ""
    except:
        non_colab = '''
            <script>
                require.config({
                    paths: {
                        "d3": "https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3",
                        "dagreD3": "https://cdnjs.cloudflare.com/ajax/libs/dagre-d3/0.6.1/dagre-d3.min"
                    }
                });
                try {
                    requirejs(['d3', 'dagreD3'], function() {});
                } catch (e) {}
                try {
                    require(['d3', 'dagreD3'], function() {});
                } catch (e) {}
            </script>
            <!--script>
                (function() {if(typeof d3 == "undefined") {
                    var script = document.createElement("script");
                    script.type = "text/javascript";
                    script.src = "https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js";
                    document.body.appendChild(script);
                    var script = document.createElement("script");
                    script.type = "text/javascript";
                    script.src = "https://cdnjs.cloudflare.com/ajax/libs/dagre-d3/0.6.1/dagre-d3.min.js";
                    document.body.appendChild(script);
                }})();
            </script-->
        '''

    return non_colab + '''
    <style>
        .node rect, .node circle, .node ellipse {
            stroke: #333;
            fill: #fff;
            stroke-width: 1px;
        }
        .edgePath path {
            stroke: #333;
            fill: #333;
            stroke-width: 1.5px;
        }
    </style>
    ''' + f'<center><svg width="850" height="600" id="{tree_id}"><g/></svg></center>' + '''
    <script>
        (function render_d3() {
    ''' + ('''
            //var d3, dagreD3;
            try {
                d3 = require('d3');
                dagreD3 = require('dagreD3');
            } catch (e) { setTimeout(render_d3, 50); return; } // requirejs is broken on external domains
    ''' if non_colab != "" else "") + '''
            var g = new dagreD3.graphlib.Graph().setGraph({ 'rankdir': 'LR' });
    ''' + "\n".join(drawcalls) + f'var svg = d3.select("#{tree_id}");' + '''