/
sage_util.py
90 lines (74 loc) · 2.44 KB
/
sage_util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# Python2.7でsageを使用するためのユーティリティ
# -*- coding: utf-8 -*-
# taichinoさんのprettyprint.pyから引用
# https://github.com/taichino/prettyprint/blob/master/prettyprint/prettyprint.py
import json
class MyEncoder (json.JSONEncoder):
def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
try:
return json.JSONEncoder.default(self, o)
except TypeError:
return str(o)
def pp(obj):
print pp_str(obj)
def pp_str(obj):
orig = json.dumps(obj,
indent=4,
sort_keys=True,
skipkeys=True,
cls=MyEncoder)
return eval("u'''%s'''" % orig).encode('utf-8')
# SageのGraphicsをHTMLとして表示するためのユーティリティ(by Hiroshi TAKEMOTO)
import urllib, base64
from IPython.display import Image
def _to_png(graphics):
filename = os.path.join(SAGE_TMP, 'junk.png')
graphics.save_image(filename)
_img = Image(filename)
os.remove(filename)
return "<img src='data:image/png;base64," + base64.b64encode(_img.data) + "'/>"
class Graphics2Html:
def __init__(self, graphics):
self._html = _to_png(graphics)
def _repr_html_(self):
return self._html
# Sageのhtml.tableでは日本語が化けて表示されないので、HTML版を作成(by Hiroshi TAKEMOTO)
class Table2Html:
def __init__(self, tbl, header=[]):
self.tbl = tbl
self.hdr = header
def _repr_html_(self):
html = ["<table class='table_form'><tbody>"]
if len(self.hdr) > 0:
html.append("<tr>")
for item in self.hdr:
html.append("<th>%s</th>" % item)
html.append("</tr>")
line = 0
for raw in self.tbl:
if line % 2 == 0:
html.append("<tr class='row-a'>")
else:
html.append("<tr class='row-b'>")
line += 1
for item in raw:
html.append("<td>%s</td>" % item)
html.append("</tr>")
html.append("</tbody></table>")
return ''.join(html)
# 以下のURLから引用
# http://stackoverflow.com/questions/19470099/view-pdf-image-in-an-ipython-notebook/19470377
class PDF2html(object):
def __init__(self, pdf, size=(200,200)):
self.pdf = pdf
self.size = size
def _repr_html_(self):
return'<iframe src={0} width={1[0]} height={1[1]}></iframe>'.format(self.pdf, self.size)
def _repr_latex_(self):
return r'\includegraphics[width=1.0\textwidth]{{{0}}}'.format(self.pdf)