from cStringIO import StringIO
from IPython.display import Image
def figure2Image(fig):
buffer = StringIO()
fig.savefig(buffer, format='png')
buffer.reset()
data = buffer.read()
return Image(data)
class Slider(object):
def __init__(self, python_var, callback, min=1, max=100, step=1):
self._min = min
self._max = max
self._step = step
self._value_init = (min+max)/2
self._id = "slider" + str(id(self))
self._python_var = python_var
self._callback = callback
def update(self, value):
return self._callback(value)
def _repr_html_(self):
javascript = """ \
<script type="text/Javascript">
var %(id)s_computing = false;
function %(id)s_updated(value, final) {
//get the element
var display = document.getElementById("chosen");
//show the amount
display.innerHTML="%(python_var)s = " + value;
var command = "s.update(" + value + ")";
//console.log("Executing Command: " + command);
var kernel = IPython.notebook.kernel;
if (%(id)s_computing == false || final == true) {
kernel.execute(command, {'output' : %(id)s_handle_output}, {silent:false});
%(id)s_computing = true;
}
}
function %(id)s_handle_output(out_type, out) {
%(id)s_computing = false;
//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"];
img = out.data["image/png"];
if (img != null) {
document.getElementById("%(id)s_result_img").src = "data:image/png;base64," + img;
}
}
// 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("%(id)s_result_text").innerHTML = res;
}
</script>
""" % {"id": self._id, "python_var": self._python_var}
html = """ \
%(min)s <input id="%(id)s" type="range" min="%(min)s" max="%(max)s" step="%(step)s" value="%(value_init)s"
onchange="%(id)s_updated(this.value, false)" onmouseup="%(id)s_updated(this.value, true)" /> %(max)s</div>
<div id="chosen">%(python_var)s = %(value_init)s</div>
Out: <div id="%(id)s_result_text"></div>
<img id="%(id)s_result_img" src=""><br>
""" % {"id": self._id, "min": self._min, "max": self._max, "step": self._step, "value_init": self._value_init,
"python_var": self._python_var}
return javascript + html