开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
捐赠
捐赠前请先登录
扫描微信二维码支付
取消
支付完成
支付提示
将跳转至支付宝完成支付
确定
取消
1 Star 0 Fork 0

小春/OnlinePythonTutor

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
master
分支 (8)
标签 (1)
master
independent-visualizer
opt-ipy
cumulative_mode
play-with-transitions
d3ify-stack
modularize
experiment-with-d3
v-Aug8-for-DeNero
master
分支 (8)
标签 (1)
master
independent-visualizer
opt-ipy
cumulative_mode
play-with-transitions
d3ify-stack
modularize
experiment-with-d3
v-Aug8-for-DeNero
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
master
分支 (8)
标签 (1)
master
independent-visualizer
opt-ipy
cumulative_mode
play-with-transitions
d3ify-stack
modularize
experiment-with-d3
v-Aug8-for-DeNero
OnlinePythonTutor
/
v3
/
make_visualizations.py
OnlinePythonTutor
/
v3
/
make_visualizations.py
make_visualizations.py 15.32 KB
一键复制 编辑 原始数据 按行查看 历史
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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
# 'Make' support for Online Python Tutor
#
# Copyright (C) 2013 Peter Robinson (pjr@itee.uq.edu.au)
#
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
This program is a 'make' program for embedding traces in web pages.
The process is driven by a .json file (the 'Makefile')
Assuming the file viz_makefile.json is in the cwd which will typically
be where the web pages and python code to be visualized reside,
and $OPT is the path to the installation of OPT
(including make_visualizations.py) then
python $OPT/make_visualizations.py viz_makefile.json
will generate all the .js traces and update the web pages as specified
in viz_makefile.json.
python $OPT/make_visualizations.py viz_makefile.json eg1.html
will do the same thing but only for the given page(s).
Here is an example of the 'Makefile' viz_makefile.json
----------------------------
{
"visualizer_url":
"http://path_to_local_visualizer/visualize.html",
"default_viz_config":
{
"embeddedMode": true,
"verticalStack": true
},
"eg1.html":
[
# hash to end of line is a comment
"js/t1.js",
{
"python_scripts/t1a.py": {}
"python_scripts/t1b.py": {"embeddedMode": false}
}
]
"eg2.html":
[
"js/t2.js",
{
# verticalStack is removed from the params below
"python_scripts/t2.py": {"verticalStack": ""}
}
]
}
----------------------------
For each .html file the first argument is the .js file where the traces will go
and the second argument is a dictionary whose keys are the python scripts
to be used to generate the traces.
If "visualizer_url" is not supplied it defaults to
"http://pythontutor.com/visualize.html"
If "default_viz_config" is not supplied it defaults to
{'heightChangeCallback': 'redrawAllVisualizerArrows',
'editCodeBaseURL': viz_url}
where viz_url is the value associated with the "visualizer_url" key.
Note: for this version heightChangeCallback is hard-wired to be
redrawAllVisualizerArrows.
The dictionary associated with a python script overrides the
"default_viz_config" dictionary.
In other words, if all visualizations behave the same way then the dictionary
associated with a python script can be set to {} and so will end up being the
(supplied) default.
"""
import subprocess
import os
import re
import json
from optparse import OptionParser
# The OPT program for generating traces
GEN_JSON = "generate_json_trace.py"
# The command used to generate traces {0} will be the full path to GEN_JSON
# !! WARNING !! python below might need to be modified to point at the
# correct version
COMMAND = "python {0} --create_jsvar={1}Trace {2}"
# The possible keys for configuring the visualization and their types
# At the moment changing callbacks are not supported -
# 'heightChangeCallback' is hard-wired in
VIZ_CONFIG_TYPES = {#'heightChangeCallback': unicode,
#'updateOutputCallback': unicode,
#'executeCodeWithRawInputFunc': unicode,
'embeddedMode': bool,
'startingInstruction': int,
'verticalStack': bool,
'jumpToEnd': bool,
'codeDivWidth': int,
'codeDivHeight': int,
'hideOutput' : bool,
'editCodeBaseURL' : unicode,
'allowEditAnnotations' : bool,
'disableHeapNesting' : bool,
'drawParentPointer' : bool,
'textualMemoryLabels' : bool,
'showOnlyOutputs' : bool,
}
CALLBACK_PATTERN_REPL = [
(r'"heightChangeCallback"\s*:\s*"([^"]*)"', r'"heightChangeCallback":1円'),
(r'"dateOutputCallback"\s*:\s*"([^"]*)"', r'"OutputCallback":1円'),
(r'"executeCodeWithRawInputFunc"\s*:\s*"([^"]*)"',
r'"executeCodeWithRawInputFunc":1円')
]
# visualize.html in OPT home
DEFALUT_VIZ_URL = 'http://pythontutor.com/visualize.html'
# The global default visualization configuration
# Note: heightChangeCallback is hard-wired to be redrawAllVisualizerArrows
DEFAULT_VIZ_CONFIG = {'heightChangeCallback': 'redrawAllVisualizerArrows'}
# The string used to generate js code for ExecutionVisualizer
VIZ_VAR = \
"""var {0}Visualizer =
new ExecutionVisualizer('{0}Div', {0}Trace,
{1});"""
# The following is used to inject the dependencies and other info
# into the web pages. If this info is already there then it will be replaced.
# If your file already has this info in but does not have the
# PY_TUTOR_END footer then manually remove this info.
# This information is based on the example from 'http://pythontutor.com'
PY_TUTOR_START = '<!-- dependencies for pytutor.js -->'
PY_TUTOR_END = '<!-- end of dependencies for pytutor.js -->'
PY_TUTOR_DEPEND = PY_TUTOR_START + \
"""
<script type="text/javascript" src="js/d3.v2.min.js"></script>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/jquery.simplemodal.js"></script> <!-- for questions -->
<script type="text/javascript" src="js/jquery.ba-bbq.min.js"></script> <!-- for handling back button and URL hashes -->
<script type="text/javascript" src="js/jquery.jsPlumb-1.3.10-all-min.js "></script> <!-- for rendering SVG connectors
DO NOT UPGRADE ABOVE 1.3.10 OR ELSE BREAKAGE WILL OCCUR -->
<script type="text/javascript" src="js/jquery-ui-1.8.24.custom.min.js"></script> <!-- for sliders and other UI elements -->
<link type="text/css" href="css/ui-lightness/jquery-ui-1.8.24.custom.css" rel="stylesheet" />
<link type="text/css" href="css/basic.css" rel="stylesheet" />
<!-- Python Tutor frontend code and styles -->
<script type="text/javascript" src="js/pytutor.js"></script>
<link rel="stylesheet" href="css/pytutor.css"/>
<!-- Visualize Script -->
<script type="text/javascript" src="{0}"></script>
<!-- Cut and paste the following lines to the place where the visualizations are to be inserted
{1}
-->
""" + PY_TUTOR_END
# A regular expression used to remove the old info
PY_TUTOR_RE = PY_TUTOR_START + '.*' + PY_TUTOR_END
# Used to inject a comment along with the dependency information so that
# you can cut and paste into the appropriate place in to the page body
DIV_TEXT = '<div id="{0}Div"></div>'
# The ready function to go at the end ot the generated .js file
DOCUMENT_READY_TEXT = \
"""
$(document).ready(function() {{
{0}
function redrawAllVisualizerArrows() {{
{1}
}}
$(window).resize(redrawAllVisualizerArrows);
}});
"""
REDRAW_CONNECTORS_TEXT = "if ({0}Visualizer) {0}Visualizer.redrawConnectors();"
COMMENT_RE = r'#.*$'
def check_viz_config(parent, config):
"""Check that config is a valid visualization configuration"""
isOK = True
if type(config) != dict:
print "In {0}, {1} is not a dictionary".format(parent,config)
return False
for key, value in config.iteritems():
config_field_type = VIZ_CONFIG_TYPES.get(key)
if config_field_type is None:
print "Unknown visualizer key:", key
isOK = False
elif value != '' and type(value) != config_field_type:
print "The visualizer configure entry {0}:{1} has the wrong type".format(key,value)
isOK = False
return isOK
def check_html_build(html, html_build_info):
"""Check that the build information for this html file is valid."""
if len(html_build_info) != 2:
print "The build list for {0} should have 2 entries".format(html)
return False
if type(html_build_info[0]) != unicode or \
not html_build_info[0].endswith('.js'):
print "The first argument of build list for {0} should be a .js file".format(html)
if type(html_build_info[1]) != dict:
print "The html build information must be a dictionary"
return False
isOK = True
for key, value in html_build_info[1].iteritems():
if type(key) != unicode or not key.endswith('.py'):
print "The key {0} is not a .py file".format(key)
isOK = False
isOK = check_viz_config(html_build_info[1], value) and isOK
return isOK
def check_build_info(build_info):
"""Check that the json info is a valid 'Makefile'"""
isOK = True
if type(build_info) != dict:
print "The build information must be a dictionary"
return False
for key, value in build_info.iteritems():
if key == 'default_viz_config':
isOK = check_viz_config(build_info, value) and isOK
elif key == 'visualizer_url':
if type(value) != unicode:
print 'The visualizer url must be a string'
isOK = False
elif key.endswith('.html'):
isOK = check_html_build(key, value) and isOK
else:
print 'Unknown key:', key
isOK = False
return isOK
def update_dict(d, defaultd):
"""Update d with key,value pairs in defaultd if the key is not in d.
If the value is the empty string then that entry is removed from
the dictionary"""
for key, value in defaultd.iteritems():
if key not in d:
d[key] = value
elif value == '':
d.pop(key)
def get_build_info(json_file):
"""Return the build information in json_file.
Check if file is valid.
"""
try:
fp = open(json_file, 'rU')
text = fp.read()
fp.close()
text = re.sub(COMMENT_RE, '', text, flags=re.M)
build_info = json.loads(text)
except Exception as e:
print "Error in {0}:\n{1}".format(json_file, str(e))
return None
if not check_build_info(build_info):
return None
# if necessary add a value for "visualizer_url"
if "visualizer_url" not in build_info:
build_info["visualizer_url"] = DEFALUT_VIZ_URL
# merge DEFAULT_VIZ_CONFIG with the supplied "default_viz_config"
config = DEFAULT_VIZ_CONFIG
config["editCodeBaseURL"] = build_info["visualizer_url"]
config.update(build_info.get("default_viz_config", {}))
build_info["default_viz_config"] = config
# update all the
for key, value in build_info.iteritems():
if key.endswith('.html'):
for py_key, py_dict in value[1].iteritems():
update_dict(py_dict, build_info.get("default_viz_config", {}))
return build_info
def get_vizname_root(py_file):
"""Return the name to be used as the prefix for Trace, Visualizer etc"""
return os.path.basename(py_file).replace('.', '_')
def run_command(gen_trace, py_file):
""" Return the output of generate_json_trace.py on py_file"""
command = COMMAND.format(gen_trace, get_vizname_root(py_file), py_file)
return subprocess.check_output(command,bufsize=1,
close_fds=True,
shell=True)
def make_viz(build_info, html_files):
"""Build the visualizations specified in build_info and html_files"""
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
prog = os.path.join(dname, GEN_JSON)
# if no html files are supplied 'make' all of them
if not html_files:
html_files = [h for h in build_info if h.endswith('.html')]
for html in html_files:
if html in build_info:
make_html_viz(prog, html, build_info[html])
else:
print "{0} is not in the json file".format(html)
def get_viz_config(conf):
"""Get the configuration params for visualization."""
text = json.dumps(conf)
# The callbacks are strings in conf and need to be turned into
# function relreences by removing the quotes
for patt, repl in CALLBACK_PATTERN_REPL:
text = re.sub(patt, repl, text)
return text
def make_html_viz(prog, html_file, html_info):
"""'Make' the visualizations for html_file"""
js_out, py_dict = html_info
# all_traces is a string containing all the js trace datastructures
# for all the supplied .py files for html_file
try:
all_traces = '\n'.join(run_command(prog, py) for py in py_dict)
except Exception as e:
print str(e)
return
# all_viz is the string containing the js code for creating the
# required instances of ExecutionVisualizer for all the .py files
# the root of the .py file is used as the root names in ExecutionVisualizer
all_viz = '\n'.join(VIZ_VAR.format(get_vizname_root(py),
get_viz_config(pyd)) \
for py,pyd in py_dict.iteritems())
all_redraws = ' \n'.join(REDRAW_CONNECTORS_TEXT.format(get_vizname_root(py)) for py, pyd in py_dict.iteritems() if 'redrawAllVisualizerArrows' in pyd.values())
ready_function = DOCUMENT_READY_TEXT.format(all_viz, all_redraws)
# all_js is the string of all the require js code
all_js = all_traces + '\n' + ready_function + '\n'
fd = open(js_out, 'w')
fd.write(all_js)
fd.close()
# Update html_file
try:
fd = open(html_file, 'rU')
html_text = fd.read()
fd.close()
except Exception as e:
print str(e)
return
# strip out the old OPT dependency info
html_text = re.sub(PY_TUTOR_RE, '', html_text, flags=re.M | re.S)
end_head_pos = html_text.find('\n</head>')
if end_head_pos == -1:
print "Could not find '\n</head>' in {0}".format(html_file)
return
# all_divs is the string of all div entries to embed in the html
# this is added to the header comments for easy cut and pasting
# to the correct location in the document.
all_divs = '\n'.join(DIV_TEXT.format(get_vizname_root(py)) for py in py_dict)
# add the updated dependency info just before </head>
html_text = html_text[:end_head_pos] +\
PY_TUTOR_DEPEND.format(js_out, all_divs) + \
html_text[end_head_pos:]
fd = open(html_file, 'w')
fd.write(html_text)
fd.close()
def main(args):
build_info = get_build_info(args[0])
if build_info is None:
print "Make aborted"
else:
make_viz(build_info, args[1:])
if __name__ == '__main__':
usage = "usage: %prog json_file [py_files]"
parser = OptionParser(usage = usage)
options,args = parser.parse_args()
if len(args) == 0:
print "Missing arguments - try python make_visualizations.py -h"
else:
main(args)
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/wython/OnlinePythonTutor.git
git@gitee.com:wython/OnlinePythonTutor.git
wython
OnlinePythonTutor
OnlinePythonTutor
master
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /