In [67]:
 import subprocess
def exe0(expr):
    global out
    out = subprocess.check_output(["./impdriver", expr])
    return out.decode("utf-8")
def exe():
    global mem
    expr = input('ImpCode$ ' + mem + "; ")
#     global out
    out = subprocess.check_output(["./impdriver", mem+"; "+expr]).decode("utf-8")
    print(out.split('\n')[0])
    mem = out.split('\n')[1]
mem = 'x:=0; y:=0; z:=0'
In [68]:
exe()
ImpCode$ x:=0; y:=0; z:=0;  x + y * 3x : 0, y : 0, z : 0
In [10]:
import readline
def rlinput(prompt, prefill=''):
   readline.set_startup_hook(lambda: readline.insert_text(prefill))
   try:
      return raw_input(prompt)
   finally:
      readline.set_startup_hook()
In [11]:
rlinput('a')
a a
Out[11]:
'a'
In [16]:
res = raw_input('Folder [default] : ')
res = res or 'default'
Folder [default] :  
In [4]:
res
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-4-41a0db25bac4> in <module>()
----> 1 res

NameError: name 'res' is not defined
In [5]:
from IPython.display import HTML
newvar = ""
htm = """
<input id="inptval" style="width:60%;" type="text" value="This is an editable default value.">
<button onclick="set_value()" style="width:20%;">OK</button>

<script type="text/Javascript">
    function set_value(){
        var input_value = document.getElementById('inptval').value;
        var command = "newvar = '" + input_value + "'";
        var kernel = IPython.notebook.kernel;
        kernel.execute(command);
    }
</script>
"""
HTML(htm)
Out[5]:
In [6]:
newvar
Out[6]:
'This is an editable default value.'
In [7]:
% env
Out[7]:
{'AR': 'ar',
 'AS': 'as',
 'CC': 'gcc',
 'CCACHE_BASEDIR': '/projects/sage/sage-7.5',
 'CHMOD': 'chmod',
 'CLICOLOR': '1',
 'CP': 'cp',
 'CPATH': '/projects/sage/sage-7.5/local/include:/usr/include/x86_64-linux-gnu',
 'CXX': 'g++',
 'CYSIGNALS_CRASH_DAYS': '7',
 'CYSIGNALS_CRASH_LOGS': '/projects/bc698cd5-4915-492b-8da7-6867325e53f0/.sage//crash_logs',
 'DOT_SAGE': '/projects/bc698cd5-4915-492b-8da7-6867325e53f0/.sage/',
 'ECLDIR': '/projects/sage/sage-7.5/local/lib/ecl/',
 'F77': 'gfortran',
 'F90': 'gfortran',
 'F95': 'gfortran',
 'FC': 'gfortran',
 'GIT_PAGER': 'cat',
 'GPDOCDIR': '/projects/sage/sage-7.5/local/share/pari/doc',
 'GPHELP': '/projects/sage/sage-7.5/local/bin/gphelp',
 'GP_DATA_DIR': '/projects/sage/sage-7.5/local/share/pari',
 'HOME': '/projects/bc698cd5-4915-492b-8da7-6867325e53f0',
 'IPYTHONDIR': '/projects/bc698cd5-4915-492b-8da7-6867325e53f0/.sage//ipython-5.0.0',
 'ISOCHRONES': '/projects/data/isochrones',
 'JPY_PARENT_PID': '23484',
 'JULIA_PKGDIR': '/usr/local/share/julia/site',
 'JUPYTER_CONFIG_DIR': '/projects/bc698cd5-4915-492b-8da7-6867325e53f0/.sage//jupyter-4.1',
 'LANG': 'en_US.UTF-8',
 'LD': 'ld',
 'LDFLAGS': '-L/projects/sage/sage-7.5/local/lib -Wl,-rpath,/projects/sage/sage-7.5/local/lib ',
 'LD_LIBRARY_PATH': '/usr/lib:/usr/local/lib',
 'LIBRARY_PATH': '/projects/sage/sage-7.5/local/lib:/usr/lib/x86_64-linux-gnu',
 'LN': 'ln',
 'LOGNAME': 'bc698cd54915492b8da76867325e53f0',
 'MAIL': '/var/mail/bc698cd54915492b8da76867325e53f0',
 'MAKE': 'make',
 'MAXIMA_PREFIX': '/projects/sage/sage-7.5/local',
 'MKDIR': 'mkdir',
 'MPLBACKEND': 'module://ipykernel.pylab.backend_inline',
 'MPLCONFIGDIR': '/projects/bc698cd5-4915-492b-8da7-6867325e53f0/.sage//matplotlib-1.5.1',
 'MV': 'mv',
 'NLTK_DATA': '/projects/data/nltk_data',
 'PAGER': 'cat',
 'PATH': '/projects/sage/sage-7.5/build/bin:/projects/sage/sage-7.5/src/bin:/projects/sage/sage-7.5/local/bin:/projects/bc698cd5-4915-492b-8da7-6867325e53f0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
 'PERL5LIB': '/projects/sage/sage-7.5/local/lib/perl5:',
 'PIP_INSTALL': 'sage-pip-install',
 'PWD': '/projects/bc698cd5-4915-492b-8da7-6867325e53f0',
 'PYTHONHOME': '/projects/sage/sage-7.5/local',
 'PYTHONPATH': '/projects/bc698cd5-4915-492b-8da7-6867325e53f0/.local/lib/python3.4/site-packages:/usr/lib/python3.4:/usr/lib/python3.4/plat-x86_64-linux-gnu:/usr/lib/python3.4/lib-dynload:/usr/local/lib/python3.4/dist-packages:/usr/lib/python3/dist-packages:/usr/local/lib/python3.4/site-packages',
 'PYTHON_EGG_CACHE': '/projects/bc698cd5-4915-492b-8da7-6867325e53f0/.sage//.python-eggs',
 'RANLIB': 'ranlib',
 'R_MAKEVARS_SITE': '/projects/sage/sage-7.5/local/lib/R/share/Makevars.site',
 'R_MAKEVARS_USER': '/projects/bc698cd5-4915-492b-8da7-6867325e53f0/.sage//R/Makevars.user',
 'SAGE64': 'no',
 'SAGE_DATA': '/projects/sage/sage-7.5/local/share',
 'SAGE_DISTFILES': '/projects/sage/sage-7.5/upstream',
 'SAGE_DOC': '/projects/sage/sage-7.5/local/share/doc/sage',
 'SAGE_DOC_MATHJAX': 'True',
 'SAGE_DOC_SRC': '/projects/sage/sage-7.5/src/doc',
 'SAGE_ENV_SOURCED': '4',
 'SAGE_ETC': '/projects/sage/sage-7.5/local/etc',
 'SAGE_EXTCODE': '/projects/sage/sage-7.5/local/share/sage/ext',
 'SAGE_LOCAL': '/projects/sage/sage-7.5/local',
 'SAGE_LOGS': '/projects/sage/sage-7.5/logs/pkgs',
 'SAGE_NUM_THREADS': '1',
 'SAGE_NUM_THREADS_PARALLEL': '8',
 'SAGE_ORIG_PATH': '/projects/bc698cd5-4915-492b-8da7-6867325e53f0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
 'SAGE_ORIG_PATH_SET': 'True',
 'SAGE_REPO_ANONYMOUS': 'git://trac.sagemath.org/sage.git',
 'SAGE_REPO_AUTHENTICATED': 'ssh://[email protected]:2222/sage.git',
 'SAGE_ROOT': '/projects/sage/sage-7.5',
 'SAGE_SCRIPTS_DIR': '/projects/sage/sage-7.5/src/bin',
 'SAGE_SHARE': '/projects/sage/sage-7.5/local/share',
 'SAGE_SPKG_INST': '/projects/sage/sage-7.5/local/var/lib/sage/installed',
 'SAGE_SRC': '/projects/sage/sage-7.5/src',
 'SAGE_STARTUP_FILE': '/projects/bc698cd5-4915-492b-8da7-6867325e53f0/.sage//init.sage',
 'SHELL': '/bin/bash',
 'SHLVL': '0',
 'SINGULARPATH': '/projects/sage/sage-7.5/local/share/singular',
 'SINGULAR_EXECUTABLE': '/projects/sage/sage-7.5/local/bin/Singular',
 'SMC': '/projects/bc698cd5-4915-492b-8da7-6867325e53f0/.smc',
 'SMC_BASE_URL': '',
 'TERM': 'xterm-color',
 'TERMINFO': '/projects/sage/sage-7.5/local/share/terminfo',
 'TOUCH': 'touch',
 'UNAME': 'Linux',
 'USER': 'bc698cd54915492b8da76867325e53f0',
 'USERNAME': 'bc698cd54915492b8da76867325e53f0',
 '_JAVA_OPTIONS': '-Xms64m',
 '__sage__': ''}
In [2]:
print foo

NameErrorTraceback (most recent call last)
<ipython-input-2-512cd49e65f5> in <module>()
----> 1 print foo

NameError: name 'foo' is not defined
In [4]:
from notebook import widgets
from IPython.utils.traitlets import Unicode

class HelloWidget(widgets.DOMWidget):
    _view_name = Unicode('HelloView', sync=True)
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-4-299d14095da0> in <module>()
----> 1 from notebook import widgets
      2 from IPython.utils.traitlets import Unicode
      3 
      4 class HelloWidget(widgets.DOMWidget):
      5     _view_name = Unicode('HelloView', sync=True)

ImportError: cannot import name 'widgets'
In [1]:
%%script python2
import sys
print 'hello from Python %s' % sys.version
hello from Python 2.7.10 (default, Oct 14 2015, 16:09:02) 
[GCC 5.2.1 20151010]
In [7]:
%%script ./impdriver
x:=
x := 0; y := 0; z := 0
In [9]:
%%script ocaml
let () = print_endline("a");;
        OCaml version 4.01.0

# a
# 
In [12]:
%%script ocaml
open Core.Std
let r file = In_channel.read_lines file;;
        OCaml version 4.01.0

#   # open Core.Std
  let r file = In_channel.read_lines file;;
Error: Unbound module Core
# 
In [3]:
def f(x):
    return x
In [1]:
from __future__ import print_function
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
In [4]:
interact(f, x=True);
Out[4]:
True
In [5]:
@interact(x=True, y=1.0)
def g(x, y):
    return (x, y)
Out[5]:
(True, 1.0)
In [7]:
interact(f, x=widgets.IntSlider(min=-10,max=30,step=1,value=10));
Out[7]:
10
In [9]:
from IPython.display import HTML

input_form = """
<div style="background-color:gainsboro; border:solid black; width:300px; padding:20px;">
Variable Name: <input type="text" id="var_name" value="foo"><br>
Variable Value: <input type="text" id="var_value" value="bar"><br>
<button onclick="set_value()">Set Value</button>
</div>
"""

javascript = """
<script type="text/Javascript">
    function set_value(){
        var var_name = document.getElementById('var_name').value;
        var var_value = document.getElementById('var_value').value;
        var command = var_name + " = '" + var_value + "'";
        console.log("Executing Command: " + command);
        
        var kernel = IPython.notebook.kernel;
        kernel.execute(command);
    }
</script>
"""

HTML(input_form + javascript)
Out[9]:
Variable Name:
Variable Value:
In [14]:
from math import pi, sin
# Add an input form similar to what we saw above
input_form = """
<div style="background-color:gainsboro; border:solid black; width:600px; padding:20px;">
Code: <input type="text" id="code_input" size="50" height="2" value="sin(pi / 2)"><br>
Result: <input type="text" id="result_output" size="50" value="1.0"><br>
<button onclick="exec_code()">Execute</button>
</div>
"""

# here the javascript has a function to execute the code
# within the input box, and a callback to handle the output.
javascript = """
<script type="text/Javascript">
    function handle_output(out_type, out){
        console.log(out_type);
        console.log(out);
        var res = null;
         // if output is a print statement
        if(out_type == "stream"){
            res = out.data;
        }
        // if output is a python object
        else if(out_type === "pyout"){
            res = out.data["text/plain"];
        }
        // if output is a python error
        else if(out_type == "pyerr"){
            res = out.ename + ": " + out.evalue;
        }
        // if output is something we haven't thought of
        else{
            res = "[out type not implemented]";   
        }
        document.getElementById("result_output").value = res;
    }
    
    function exec_code(){
        var code_input = document.getElementById('code_input').value;
        var kernel = IPython.notebook.kernel;
        var callbacks = {'output' : handle_output};
        document.getElementById("result_output").value = "";  // clear output box
        var msg_id = kernel.execute(code_input, callbacks, {silent:false});
        console.log("button pressed");
    }
</script>
"""

HTML(input_form + javascript)
Out[14]:
Code:
Result:
In [15]:
from IPython.display import HTML

javascript = '''
<script type="text/javascript">
    alert("HOGE")
</script>
'''

HTML(javascript) # ポップアップウィンドウを表示
Out[15]:
In [10]:
foo
Out[10]:
'bar'
In [1]:
from ipywidgets import *
In [2]:
IntSlider()
In [3]:
from IPython.display import display
w = IntSlider()
display(w)
In [16]:
import numpy as np
from IPython.display import HTML

javascript = '''
<script type="text/javascript">
var kernel = IPython.notebook.kernel;

var callback = function(output) {
  var res = output.content.data['text/plain'];
  alert(res);
};

var x = 2.0;
var command = 'np.sin(' + x + ')';
kernel.execute(command, {'iopub': {"output": callback}}, {silent:false});
</script>
'''

HTML(javascript)
Out[16]:
In [17]:
input_form = """
<div style="border:solid navy; padding:20px;">
<input type="file" id="file_selector" name="files[]"/>
<output id="list"></output>
</div>
"""

javascript = """
<script type="text/Javascript">
  function handleFileSelect(evt) {
    var kernel = IPython.notebook.kernel;
    var files = evt.target.files; // FileList object
    console.log('Executing orig')
    console.log(files)
    // files is a FileList of File objects. List some properties.
    var output = [];
    var f = files[0]
    output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
                  f.size, ' bytes, last modified: ',
                  f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
                  '</_Mli>');
    document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
    var command = 'fname = "' + f.name + '"'
    console.log(command)
    kernel.execute(command);
  }

  document.getElementById('file_selector').addEventListener('change', handleFileSelect, false);
</script>
"""

def file_selector():
    from IPython.display import HTML, display
    display(HTML(input_form + javascript))
In [18]:
file_selector()
In [23]:
%%javascript

var cell = IPython.notebook.get_cell(0);
var mt;
var i;
for (var i = 0 ; i < cell.code_mirror.doc.size; i++) {
    if (mt) {
        mt.clear();
    }
    mt = cell.code_mirror.markText({line: i, ch: 0 },
                                   {line: i + 1, ch: 0 },
                                   {className: "styled-background"});
    alert("Line " + i);
}

if (mt) {
    mt.clear();
}
In [21]:
%%javascript

var cell = IPython.notebook.get_cell(0);

for (var n = 0 ; n < cell.code_mirror.doc.size; n++) {
    var info = cell.code_mirror.lineInfo(n);
    if (info.gutterMarkers) {
        alert("breakpoint at line " + (n + 1));
    }
}
In [24]:
from IPython.display import HTML

# We'll use HTML to create a control panel

disp_html = """
<div class="animation" align="left" width="400">
<button onclick="pause()">Pause</button>
<button onclick="play()">Play</button>
<input type="range" name="points" min="0" max="10"/>
<button onclick="step()">Step</button><br/>
<div id="result_output"/>
</div>
"""

javascript = """
<script type="text/Javascript">
var count = 0;  // a counter
var running = 0;  // is it running?
var timer = null;
var kernel = IPython.notebook.kernel;

function handle_output(out){
        //console.log(out);
        var res = null;
         // if output is a print statement
        if (out.msg_type == "stream") {
            res = out.content.data;
        } else if (out.msg_type === "pyout") {
            // if output is a python object
            res = out.content.data["text/plain"];
        } else if (out.msg_type == "pyerr") {
            // if output is a python error
            res = out.content.data["text/plain"];
        } else if (out.msg_type == "execute_result") {
            res = "execute_reply: " + out.content.data["text/plain"];
        }
        // if output is something we haven't thought of
        else{
            res = out.ToString();   
        }
        document.getElementById("result_output").innerText += res;

    if(animating > 0){
        timer = setTimeout(step, 100);
    }
}

var callbacks = { 'iopub' : {'output' : handle_output}};

function pause() {
    animating = 0;
    if (timer) {
        clearInterval(timer);
        timer = null;
    }
}

function play() {
    pause();
    animating = +1;
    step();
}

function step() {
    count += 1;
    var msg_id = kernel.execute("print " + count, callbacks, {silent: false});
}

</script>
"""

HTML(disp_html + javascript)
Out[24]: