URL data analyzer and extractor. Detect malicious signs and other useful data associated with URLs.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4093 lines
345 KiB

  1. {
  2. "cells": [
  3. {
  4. "cell_type": "code",
  5. "execution_count": 3,
  6. "metadata": {},
  7. "outputs": [
  8. {
  9. "name": "stdout",
  10. "output_type": "stream",
  11. "text": [
  12. "Generating statistics: https://hoxhunt.com/\n"
  13. ]
  14. },
  15. {
  16. "data": {
  17. "application/javascript": [
  18. "/* Put everything inside the global mpl namespace */\n",
  19. "window.mpl = {};\n",
  20. "\n",
  21. "\n",
  22. "mpl.get_websocket_type = function() {\n",
  23. " if (typeof(WebSocket) !== 'undefined') {\n",
  24. " return WebSocket;\n",
  25. " } else if (typeof(MozWebSocket) !== 'undefined') {\n",
  26. " return MozWebSocket;\n",
  27. " } else {\n",
  28. " alert('Your browser does not have WebSocket support. ' +\n",
  29. " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n",
  30. " 'Firefox 4 and 5 are also supported but you ' +\n",
  31. " 'have to enable WebSockets in about:config.');\n",
  32. " };\n",
  33. "}\n",
  34. "\n",
  35. "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n",
  36. " this.id = figure_id;\n",
  37. "\n",
  38. " this.ws = websocket;\n",
  39. "\n",
  40. " this.supports_binary = (this.ws.binaryType != undefined);\n",
  41. "\n",
  42. " if (!this.supports_binary) {\n",
  43. " var warnings = document.getElementById(\"mpl-warnings\");\n",
  44. " if (warnings) {\n",
  45. " warnings.style.display = 'block';\n",
  46. " warnings.textContent = (\n",
  47. " \"This browser does not support binary websocket messages. \" +\n",
  48. " \"Performance may be slow.\");\n",
  49. " }\n",
  50. " }\n",
  51. "\n",
  52. " this.imageObj = new Image();\n",
  53. "\n",
  54. " this.context = undefined;\n",
  55. " this.message = undefined;\n",
  56. " this.canvas = undefined;\n",
  57. " this.rubberband_canvas = undefined;\n",
  58. " this.rubberband_context = undefined;\n",
  59. " this.format_dropdown = undefined;\n",
  60. "\n",
  61. " this.image_mode = 'full';\n",
  62. "\n",
  63. " this.root = $('<div/>');\n",
  64. " this._root_extra_style(this.root)\n",
  65. " this.root.attr('style', 'display: inline-block');\n",
  66. "\n",
  67. " $(parent_element).append(this.root);\n",
  68. "\n",
  69. " this._init_header(this);\n",
  70. " this._init_canvas(this);\n",
  71. " this._init_toolbar(this);\n",
  72. "\n",
  73. " var fig = this;\n",
  74. "\n",
  75. " this.waiting = false;\n",
  76. "\n",
  77. " this.ws.onopen = function () {\n",
  78. " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n",
  79. " fig.send_message(\"send_image_mode\", {});\n",
  80. " if (mpl.ratio != 1) {\n",
  81. " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n",
  82. " }\n",
  83. " fig.send_message(\"refresh\", {});\n",
  84. " }\n",
  85. "\n",
  86. " this.imageObj.onload = function() {\n",
  87. " if (fig.image_mode == 'full') {\n",
  88. " // Full images could contain transparency (where diff images\n",
  89. " // almost always do), so we need to clear the canvas so that\n",
  90. " // there is no ghosting.\n",
  91. " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n",
  92. " }\n",
  93. " fig.context.drawImage(fig.imageObj, 0, 0);\n",
  94. " };\n",
  95. "\n",
  96. " this.imageObj.onunload = function() {\n",
  97. " fig.ws.close();\n",
  98. " }\n",
  99. "\n",
  100. " this.ws.onmessage = this._make_on_message_function(this);\n",
  101. "\n",
  102. " this.ondownload = ondownload;\n",
  103. "}\n",
  104. "\n",
  105. "mpl.figure.prototype._init_header = function() {\n",
  106. " var titlebar = $(\n",
  107. " '<div class=\"ui-dialog-titlebar ui-widget-header ui-corner-all ' +\n",
  108. " 'ui-helper-clearfix\"/>');\n",
  109. " var titletext = $(\n",
  110. " '<div class=\"ui-dialog-title\" style=\"width: 100%; ' +\n",
  111. " 'text-align: center; padding: 3px;\"/>');\n",
  112. " titlebar.append(titletext)\n",
  113. " this.root.append(titlebar);\n",
  114. " this.header = titletext[0];\n",
  115. "}\n",
  116. "\n",
  117. "\n",
  118. "\n",
  119. "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n",
  120. "\n",
  121. "}\n",
  122. "\n",
  123. "\n",
  124. "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n",
  125. "\n",
  126. "}\n",
  127. "\n",
  128. "mpl.figure.prototype._init_canvas = function() {\n",
  129. " var fig = this;\n",
  130. "\n",
  131. " var canvas_div = $('<div/>');\n",
  132. "\n",
  133. " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n",
  134. "\n",
  135. " function canvas_keyboard_event(event) {\n",
  136. " return fig.key_event(event, event['data']);\n",
  137. " }\n",
  138. "\n",
  139. " canvas_div.keydown('key_press', canvas_keyboard_event);\n",
  140. " canvas_div.keyup('key_release', canvas_keyboard_event);\n",
  141. " this.canvas_div = canvas_div\n",
  142. " this._canvas_extra_style(canvas_div)\n",
  143. " this.root.append(canvas_div);\n",
  144. "\n",
  145. " var canvas = $('<canvas/>');\n",
  146. " canvas.addClass('mpl-canvas');\n",
  147. " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n",
  148. "\n",
  149. " this.canvas = canvas[0];\n",
  150. " this.context = canvas[0].getContext(\"2d\");\n",
  151. "\n",
  152. " var backingStore = this.context.backingStorePixelRatio ||\n",
  153. "\tthis.context.webkitBackingStorePixelRatio ||\n",
  154. "\tthis.context.mozBackingStorePixelRatio ||\n",
  155. "\tthis.context.msBackingStorePixelRatio ||\n",
  156. "\tthis.context.oBackingStorePixelRatio ||\n",
  157. "\tthis.context.backingStorePixelRatio || 1;\n",
  158. "\n",
  159. " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n",
  160. "\n",
  161. " var rubberband = $('<canvas/>');\n",
  162. " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n",
  163. "\n",
  164. " var pass_mouse_events = true;\n",
  165. "\n",
  166. " canvas_div.resizable({\n",
  167. " start: function(event, ui) {\n",
  168. " pass_mouse_events = false;\n",
  169. " },\n",
  170. " resize: function(event, ui) {\n",
  171. " fig.request_resize(ui.size.width, ui.size.height);\n",
  172. " },\n",
  173. " stop: function(event, ui) {\n",
  174. " pass_mouse_events = true;\n",
  175. " fig.request_resize(ui.size.width, ui.size.height);\n",
  176. " },\n",
  177. " });\n",
  178. "\n",
  179. " function mouse_event_fn(event) {\n",
  180. " if (pass_mouse_events)\n",
  181. " return fig.mouse_event(event, event['data']);\n",
  182. " }\n",
  183. "\n",
  184. " rubberband.mousedown('button_press', mouse_event_fn);\n",
  185. " rubberband.mouseup('button_release', mouse_event_fn);\n",
  186. " // Throttle sequential mouse events to 1 every 20ms.\n",
  187. " rubberband.mousemove('motion_notify', mouse_event_fn);\n",
  188. "\n",
  189. " rubberband.mouseenter('figure_enter', mouse_event_fn);\n",
  190. " rubberband.mouseleave('figure_leave', mouse_event_fn);\n",
  191. "\n",
  192. " canvas_div.on(\"wheel\", function (event) {\n",
  193. " event = event.originalEvent;\n",
  194. " event['data'] = 'scroll'\n",
  195. " if (event.deltaY < 0) {\n",
  196. " event.step = 1;\n",
  197. " } else {\n",
  198. " event.step = -1;\n",
  199. " }\n",
  200. " mouse_event_fn(event);\n",
  201. " });\n",
  202. "\n",
  203. " canvas_div.append(canvas);\n",
  204. " canvas_div.append(rubberband);\n",
  205. "\n",
  206. " this.rubberband = rubberband;\n",
  207. " this.rubberband_canvas = rubberband[0];\n",
  208. " this.rubberband_context = rubberband[0].getContext(\"2d\");\n",
  209. " this.rubberband_context.strokeStyle = \"#000000\";\n",
  210. "\n",
  211. " this._resize_canvas = function(width, height) {\n",
  212. " // Keep the size of the canvas, canvas container, and rubber band\n",
  213. " // canvas in synch.\n",
  214. " canvas_div.css('width', width)\n",
  215. " canvas_div.css('height', height)\n",
  216. "\n",
  217. " canvas.attr('width', width * mpl.ratio);\n",
  218. " canvas.attr('height', height * mpl.ratio);\n",
  219. " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n",
  220. "\n",
  221. " rubberband.attr('width', width);\n",
  222. " rubberband.attr('height', height);\n",
  223. " }\n",
  224. "\n",
  225. " // Set the figure to an initial 600x600px, this will subsequently be updated\n",
  226. " // upon first draw.\n",
  227. " this._resize_canvas(600, 600);\n",
  228. "\n",
  229. " // Disable right mouse context menu.\n",
  230. " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n",
  231. " return false;\n",
  232. " });\n",
  233. "\n",
  234. " function set_focus () {\n",
  235. " canvas.focus();\n",
  236. " canvas_div.focus();\n",
  237. " }\n",
  238. "\n",
  239. " window.setTimeout(set_focus, 100);\n",
  240. "}\n",
  241. "\n",
  242. "mpl.figure.prototype._init_toolbar = function() {\n",
  243. " var fig = this;\n",
  244. "\n",
  245. " var nav_element = $('<div/>');\n",
  246. " nav_element.attr('style', 'width: 100%');\n",
  247. " this.root.append(nav_element);\n",
  248. "\n",
  249. " // Define a callback function for later on.\n",
  250. " function toolbar_event(event) {\n",
  251. " return fig.toolbar_button_onclick(event['data']);\n",
  252. " }\n",
  253. " function toolbar_mouse_event(event) {\n",
  254. " return fig.toolbar_button_onmouseover(event['data']);\n",
  255. " }\n",
  256. "\n",
  257. " for(var toolbar_ind in mpl.toolbar_items) {\n",
  258. " var name = mpl.toolbar_items[toolbar_ind][0];\n",
  259. " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n",
  260. " var image = mpl.toolbar_items[toolbar_ind][2];\n",
  261. " var method_name = mpl.toolbar_items[toolbar_ind][3];\n",
  262. "\n",
  263. " if (!name) {\n",
  264. " // put a spacer in here.\n",
  265. " continue;\n",
  266. " }\n",
  267. " var button = $('<button/>');\n",
  268. " button.addClass('ui-button ui-widget ui-state-default ui-corner-all ' +\n",
  269. " 'ui-button-icon-only');\n",
  270. " button.attr('role', 'button');\n",
  271. " button.attr('aria-disabled', 'false');\n",
  272. " button.click(method_name, toolbar_event);\n",
  273. " button.mouseover(tooltip, toolbar_mouse_event);\n",
  274. "\n",
  275. " var icon_img = $('<span/>');\n",
  276. " icon_img.addClass('ui-button-icon-primary ui-icon');\n",
  277. " icon_img.addClass(image);\n",
  278. " icon_img.addClass('ui-corner-all');\n",
  279. "\n",
  280. " var tooltip_span = $('<span/>');\n",
  281. " tooltip_span.addClass('ui-button-text');\n",
  282. " tooltip_span.html(tooltip);\n",
  283. "\n",
  284. " button.append(icon_img);\n",
  285. " button.append(tooltip_span);\n",
  286. "\n",
  287. " nav_element.append(button);\n",
  288. " }\n",
  289. "\n",
  290. " var fmt_picker_span = $('<span/>');\n",
  291. "\n",
  292. " var fmt_picker = $('<select/>');\n",
  293. " fmt_picker.addClass('mpl-toolbar-option ui-widget ui-widget-content');\n",
  294. " fmt_picker_span.append(fmt_picker);\n",
  295. " nav_element.append(fmt_picker_span);\n",
  296. " this.format_dropdown = fmt_picker[0];\n",
  297. "\n",
  298. " for (var ind in mpl.extensions) {\n",
  299. " var fmt = mpl.extensions[ind];\n",
  300. " var option = $(\n",
  301. " '<option/>', {selected: fmt === mpl.default_extension}).html(fmt);\n",
  302. " fmt_picker.append(option);\n",
  303. " }\n",
  304. "\n",
  305. " // Add hover states to the ui-buttons\n",
  306. " $( \".ui-button\" ).hover(\n",
  307. " function() { $(this).addClass(\"ui-state-hover\");},\n",
  308. " function() { $(this).removeClass(\"ui-state-hover\");}\n",
  309. " );\n",
  310. "\n",
  311. " var status_bar = $('<span class=\"mpl-message\"/>');\n",
  312. " nav_element.append(status_bar);\n",
  313. " this.message = status_bar[0];\n",
  314. "}\n",
  315. "\n",
  316. "mpl.figure.prototype.request_resize = function(x_pixels, y_pixels) {\n",
  317. " // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n",
  318. " // which will in turn request a refresh of the image.\n",
  319. " this.send_message('resize', {'width': x_pixels, 'height': y_pixels});\n",
  320. "}\n",
  321. "\n",
  322. "mpl.figure.prototype.send_message = function(type, properties) {\n",
  323. " properties['type'] = type;\n",
  324. " properties['figure_id'] = this.id;\n",
  325. " this.ws.send(JSON.stringify(properties));\n",
  326. "}\n",
  327. "\n",
  328. "mpl.figure.prototype.send_draw_message = function() {\n",
  329. " if (!this.waiting) {\n",
  330. " this.waiting = true;\n",
  331. " this.ws.send(JSON.stringify({type: \"draw\", figure_id: this.id}));\n",
  332. " }\n",
  333. "}\n",
  334. "\n",
  335. "\n",
  336. "mpl.figure.prototype.handle_save = function(fig, msg) {\n",
  337. " var format_dropdown = fig.format_dropdown;\n",
  338. " var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n",
  339. " fig.ondownload(fig, format);\n",
  340. "}\n",
  341. "\n",
  342. "\n",
  343. "mpl.figure.prototype.handle_resize = function(fig, msg) {\n",
  344. " var size = msg['size'];\n",
  345. " if (size[0] != fig.canvas.width || size[1] != fig.canvas.height) {\n",
  346. " fig._resize_canvas(size[0], size[1]);\n",
  347. " fig.send_message(\"refresh\", {});\n",
  348. " };\n",
  349. "}\n",
  350. "\n",
  351. "mpl.figure.prototype.handle_rubberband = function(fig, msg) {\n",
  352. " var x0 = msg['x0'] / mpl.ratio;\n",
  353. " var y0 = (fig.canvas.height - msg['y0']) / mpl.ratio;\n",
  354. " var x1 = msg['x1'] / mpl.ratio;\n",
  355. " var y1 = (fig.canvas.height - msg['y1']) / mpl.ratio;\n",
  356. " x0 = Math.floor(x0) + 0.5;\n",
  357. " y0 = Math.floor(y0) + 0.5;\n",
  358. " x1 = Math.floor(x1) + 0.5;\n",
  359. " y1 = Math.floor(y1) + 0.5;\n",
  360. " var min_x = Math.min(x0, x1);\n",
  361. " var min_y = Math.min(y0, y1);\n",
  362. " var width = Math.abs(x1 - x0);\n",
  363. " var height = Math.abs(y1 - y0);\n",
  364. "\n",
  365. " fig.rubberband_context.clearRect(\n",
  366. " 0, 0, fig.canvas.width / mpl.ratio, fig.canvas.height / mpl.ratio);\n",
  367. "\n",
  368. " fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n",
  369. "}\n",
  370. "\n",
  371. "mpl.figure.prototype.handle_figure_label = function(fig, msg) {\n",
  372. " // Updates the figure title.\n",
  373. " fig.header.textContent = msg['label'];\n",
  374. "}\n",
  375. "\n",
  376. "mpl.figure.prototype.handle_cursor = function(fig, msg) {\n",
  377. " var cursor = msg['cursor'];\n",
  378. " switch(cursor)\n",
  379. " {\n",
  380. " case 0:\n",
  381. " cursor = 'pointer';\n",
  382. " break;\n",
  383. " case 1:\n",
  384. " cursor = 'default';\n",
  385. " break;\n",
  386. " case 2:\n",
  387. " cursor = 'crosshair';\n",
  388. " break;\n",
  389. " case 3:\n",
  390. " cursor = 'move';\n",
  391. " break;\n",
  392. " }\n",
  393. " fig.rubberband_canvas.style.cursor = cursor;\n",
  394. "}\n",
  395. "\n",
  396. "mpl.figure.prototype.handle_message = function(fig, msg) {\n",
  397. " fig.message.textContent = msg['message'];\n",
  398. "}\n",
  399. "\n",
  400. "mpl.figure.prototype.handle_draw = function(fig, msg) {\n",
  401. " // Request the server to send over a new figure.\n",
  402. " fig.send_draw_message();\n",
  403. "}\n",
  404. "\n",
  405. "mpl.figure.prototype.handle_image_mode = function(fig, msg) {\n",
  406. " fig.image_mode = msg['mode'];\n",
  407. "}\n",
  408. "\n",
  409. "mpl.figure.prototype.updated_canvas_event = function() {\n",
  410. " // Called whenever the canvas gets updated.\n",
  411. " this.send_message(\"ack\", {});\n",
  412. "}\n",
  413. "\n",
  414. "// A function to construct a web socket function for onmessage handling.\n",
  415. "// Called in the figure constructor.\n",
  416. "mpl.figure.prototype._make_on_message_function = function(fig) {\n",
  417. " return function socket_on_message(evt) {\n",
  418. " if (evt.data instanceof Blob) {\n",
  419. " /* FIXME: We get \"Resource interpreted as Image but\n",
  420. " * transferred with MIME type text/plain:\" errors on\n",
  421. " * Chrome. But how to set the MIME type? It doesn't seem\n",
  422. " * to be part of the websocket stream */\n",
  423. " evt.data.type = \"image/png\";\n",
  424. "\n",
  425. " /* Free the memory for the previous frames */\n",
  426. " if (fig.imageObj.src) {\n",
  427. " (window.URL || window.webkitURL).revokeObjectURL(\n",
  428. " fig.imageObj.src);\n",
  429. " }\n",
  430. "\n",
  431. " fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n",
  432. " evt.data);\n",
  433. " fig.updated_canvas_event();\n",
  434. " fig.waiting = false;\n",
  435. " return;\n",
  436. " }\n",
  437. " else if (typeof evt.data === 'string' && evt.data.slice(0, 21) == \"data:image/png;base64\") {\n",
  438. " fig.imageObj.src = evt.data;\n",
  439. " fig.updated_canvas_event();\n",
  440. " fig.waiting = false;\n",
  441. " return;\n",
  442. " }\n",
  443. "\n",
  444. " var msg = JSON.parse(evt.data);\n",
  445. " var msg_type = msg['type'];\n",
  446. "\n",
  447. " // Call the \"handle_{type}\" callback, which takes\n",
  448. " // the figure and JSON message as its only arguments.\n",
  449. " try {\n",
  450. " var callback = fig[\"handle_\" + msg_type];\n",
  451. " } catch (e) {\n",
  452. " console.log(\"No handler for the '\" + msg_type + \"' message type: \", msg);\n",
  453. " return;\n",
  454. " }\n",
  455. "\n",
  456. " if (callback) {\n",
  457. " try {\n",
  458. " // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n",
  459. " callback(fig, msg);\n",
  460. " } catch (e) {\n",
  461. " console.log(\"Exception inside the 'handler_\" + msg_type + \"' callback:\", e, e.stack, msg);\n",
  462. " }\n",
  463. " }\n",
  464. " };\n",
  465. "}\n",
  466. "\n",
  467. "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n",
  468. "mpl.findpos = function(e) {\n",
  469. " //this section is from http://www.quirksmode.org/js/events_properties.html\n",
  470. " var targ;\n",
  471. " if (!e)\n",
  472. " e = window.event;\n",
  473. " if (e.target)\n",
  474. " targ = e.target;\n",
  475. " else if (e.srcElement)\n",
  476. " targ = e.srcElement;\n",
  477. " if (targ.nodeType == 3) // defeat Safari bug\n",
  478. " targ = targ.parentNode;\n",
  479. "\n",
  480. " // jQuery normalizes the pageX and pageY\n",
  481. " // pageX,Y are the mouse positions relative to the document\n",
  482. " // offset() returns the position of the element relative to the document\n",
  483. " var x = e.pageX - $(targ).offset().left;\n",
  484. " var y = e.pageY - $(targ).offset().top;\n",
  485. "\n",
  486. " return {\"x\": x, \"y\": y};\n",
  487. "};\n",
  488. "\n",
  489. "/*\n",
  490. " * return a copy of an object with only non-object keys\n",
  491. " * we need this to avoid circular references\n",
  492. " * http://stackoverflow.com/a/24161582/3208463\n",
  493. " */\n",
  494. "function simpleKeys (original) {\n",
  495. " return Object.keys(original).reduce(function (obj, key) {\n",
  496. " if (typeof original[key] !== 'object')\n",
  497. " obj[key] = original[key]\n",
  498. " return obj;\n",
  499. " }, {});\n",
  500. "}\n",
  501. "\n",
  502. "mpl.figure.prototype.mouse_event = function(event, name) {\n",
  503. " var canvas_pos = mpl.findpos(event)\n",
  504. "\n",
  505. " if (name === 'button_press')\n",
  506. " {\n",
  507. " this.canvas.focus();\n",
  508. " this.canvas_div.focus();\n",
  509. " }\n",
  510. "\n",
  511. " var x = canvas_pos.x * mpl.ratio;\n",
  512. " var y = canvas_pos.y * mpl.ratio;\n",
  513. "\n",
  514. " this.send_message(name, {x: x, y: y, button: event.button,\n",
  515. " step: event.step,\n",
  516. " guiEvent: simpleKeys(event)});\n",
  517. "\n",
  518. " /* This prevents the web browser from automatically changing to\n",
  519. " * the text insertion cursor when the button is pressed. We want\n",
  520. " * to control all of the cursor setting manually through the\n",
  521. " * 'cursor' event from matplotlib */\n",
  522. " event.preventDefault();\n",
  523. " return false;\n",
  524. "}\n",
  525. "\n",
  526. "mpl.figure.prototype._key_event_extra = function(event, name) {\n",
  527. " // Handle any extra behaviour associated with a key event\n",
  528. "}\n",
  529. "\n",
  530. "mpl.figure.prototype.key_event = function(event, name) {\n",
  531. "\n",
  532. " // Prevent repeat events\n",
  533. " if (name == 'key_press')\n",
  534. " {\n",
  535. " if (event.which === this._key)\n",
  536. " return;\n",
  537. " else\n",
  538. " this._key = event.which;\n",
  539. " }\n",
  540. " if (name == 'key_release')\n",
  541. " this._key = null;\n",
  542. "\n",
  543. " var value = '';\n",
  544. " if (event.ctrlKey && event.which != 17)\n",
  545. " value += \"ctrl+\";\n",
  546. " if (event.altKey && event.which != 18)\n",
  547. " value += \"alt+\";\n",
  548. " if (event.shiftKey && event.which != 16)\n",
  549. " value += \"shift+\";\n",
  550. "\n",
  551. " value += 'k';\n",
  552. " value += event.which.toString();\n",
  553. "\n",
  554. " this._key_event_extra(event, name);\n",
  555. "\n",
  556. " this.send_message(name, {key: value,\n",
  557. " guiEvent: simpleKeys(event)});\n",
  558. " return false;\n",
  559. "}\n",
  560. "\n",
  561. "mpl.figure.prototype.toolbar_button_onclick = function(name) {\n",
  562. " if (name == 'download') {\n",
  563. " this.handle_save(this, null);\n",
  564. " } else {\n",
  565. " this.send_message(\"toolbar_button\", {name: name});\n",
  566. " }\n",
  567. "};\n",
  568. "\n",
  569. "mpl.figure.prototype.toolbar_button_onmouseover = function(tooltip) {\n",
  570. " this.message.textContent = tooltip;\n",
  571. "};\n",
  572. "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Pan axes with left mouse, zoom with right\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n",
  573. "\n",
  574. "mpl.extensions = [\"eps\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\"];\n",
  575. "\n",
  576. "mpl.default_extension = \"png\";var comm_websocket_adapter = function(comm) {\n",
  577. " // Create a \"websocket\"-like object which calls the given IPython comm\n",
  578. " // object with the appropriate methods. Currently this is a non binary\n",
  579. " // socket, so there is still some room for performance tuning.\n",
  580. " var ws = {};\n",
  581. "\n",
  582. " ws.close = function() {\n",
  583. " comm.close()\n",
  584. " };\n",
  585. " ws.send = function(m) {\n",
  586. " //console.log('sending', m);\n",
  587. " comm.send(m);\n",
  588. " };\n",
  589. " // Register the callback with on_msg.\n",
  590. " comm.on_msg(function(msg) {\n",
  591. " //console.log('receiving', msg['content']['data'], msg);\n",
  592. " // Pass the mpl event to the overridden (by mpl) onmessage function.\n",
  593. " ws.onmessage(msg['content']['data'])\n",
  594. " });\n",
  595. " return ws;\n",
  596. "}\n",
  597. "\n",
  598. "mpl.mpl_figure_comm = function(comm, msg) {\n",
  599. " // This is the function which gets called when the mpl process\n",
  600. " // starts-up an IPython Comm through the \"matplotlib\" channel.\n",
  601. "\n",
  602. " var id = msg.content.data.id;\n",
  603. " // Get hold of the div created by the display call when the Comm\n",
  604. " // socket was opened in Python.\n",
  605. " var element = $(\"#\" + id);\n",
  606. " var ws_proxy = comm_websocket_adapter(comm)\n",
  607. "\n",
  608. " function ondownload(figure, format) {\n",
  609. " window.open(figure.imageObj.src);\n",
  610. " }\n",
  611. "\n",
  612. " var fig = new mpl.figure(id, ws_proxy,\n",
  613. " ondownload,\n",
  614. " element.get(0));\n",
  615. "\n",
  616. " // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n",
  617. " // web socket which is closed, not our websocket->open comm proxy.\n",
  618. " ws_proxy.onopen();\n",
  619. "\n",
  620. " fig.parent_element = element.get(0);\n",
  621. " fig.cell_info = mpl.find_output_cell(\"<div id='\" + id + \"'></div>\");\n",
  622. " if (!fig.cell_info) {\n",
  623. " console.error(\"Failed to find cell for figure\", id, fig);\n",
  624. " return;\n",
  625. " }\n",
  626. "\n",
  627. " var output_index = fig.cell_info[2]\n",
  628. " var cell = fig.cell_info[0];\n",
  629. "\n",
  630. "};\n",
  631. "\n",
  632. "mpl.figure.prototype.handle_close = function(fig, msg) {\n",
  633. " var width = fig.canvas.width/mpl.ratio\n",
  634. " fig.root.unbind('remove')\n",
  635. "\n",
  636. " // Update the output cell to use the data from the current canvas.\n",
  637. " fig.push_to_output();\n",
  638. " var dataURL = fig.canvas.toDataURL();\n",
  639. " // Re-enable the keyboard manager in IPython - without this line, in FF,\n",
  640. " // the notebook keyboard shortcuts fail.\n",
  641. " IPython.keyboard_manager.enable()\n",
  642. " $(fig.parent_element).html('<img src=\"' + dataURL + '\" width=\"' + width + '\">');\n",
  643. " fig.close_ws(fig, msg);\n",
  644. "}\n",
  645. "\n",
  646. "mpl.figure.prototype.close_ws = function(fig, msg){\n",
  647. " fig.send_message('closing', msg);\n",
  648. " // fig.ws.close()\n",
  649. "}\n",
  650. "\n",
  651. "mpl.figure.prototype.push_to_output = function(remove_interactive) {\n",
  652. " // Turn the data on the canvas into data in the output cell.\n",
  653. " var width = this.canvas.width/mpl.ratio\n",
  654. " var dataURL = this.canvas.toDataURL();\n",
  655. " this.cell_info[1]['text/html'] = '<img src=\"' + dataURL + '\" width=\"' + width + '\">';\n",
  656. "}\n",
  657. "\n",
  658. "mpl.figure.prototype.updated_canvas_event = function() {\n",
  659. " // Tell IPython that the notebook contents must change.\n",
  660. " IPython.notebook.set_dirty(true);\n",
  661. " this.send_message(\"ack\", {});\n",
  662. " var fig = this;\n",
  663. " // Wait a second, then push the new image to the DOM so\n",
  664. " // that it is saved nicely (might be nice to debounce this).\n",
  665. " setTimeout(function () { fig.push_to_output() }, 1000);\n",
  666. "}\n",
  667. "\n",
  668. "mpl.figure.prototype._init_toolbar = function() {\n",
  669. " var fig = this;\n",
  670. "\n",
  671. " var nav_element = $('<div/>');\n",
  672. " nav_element.attr('style', 'width: 100%');\n",
  673. " this.root.append(nav_element);\n",
  674. "\n",
  675. " // Define a callback function for later on.\n",
  676. " function toolbar_event(event) {\n",
  677. " return fig.toolbar_button_onclick(event['data']);\n",
  678. " }\n",
  679. " function toolbar_mouse_event(event) {\n",
  680. " return fig.toolbar_button_onmouseover(event['data']);\n",
  681. " }\n",
  682. "\n",
  683. " for(var toolbar_ind in mpl.toolbar_items){\n",
  684. " var name = mpl.toolbar_items[toolbar_ind][0];\n",
  685. " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n",
  686. " var image = mpl.toolbar_items[toolbar_ind][2];\n",
  687. " var method_name = mpl.toolbar_items[toolbar_ind][3];\n",
  688. "\n",
  689. " if (!name) { continue; };\n",
  690. "\n",
  691. " var button = $('<button class=\"btn btn-default\" href=\"#\" title=\"' + name + '\"><i class=\"fa ' + image + ' fa-lg\"></i></button>');\n",
  692. " button.click(method_name, toolbar_event);\n",
  693. " button.mouseover(tooltip, toolbar_mouse_event);\n",
  694. " nav_element.append(button);\n",
  695. " }\n",
  696. "\n",
  697. " // Add the status bar.\n",
  698. " var status_bar = $('<span class=\"mpl-message\" style=\"text-align:right; float: right;\"/>');\n",
  699. " nav_element.append(status_bar);\n",
  700. " this.message = status_bar[0];\n",
  701. "\n",
  702. " // Add the close button to the window.\n",
  703. " var buttongrp = $('<div class=\"btn-group inline pull-right\"></div>');\n",
  704. " var button = $('<button class=\"btn btn-mini btn-primary\" href=\"#\" title=\"Stop Interaction\"><i class=\"fa fa-power-off icon-remove icon-large\"></i></button>');\n",
  705. " button.click(function (evt) { fig.handle_close(fig, {}); } );\n",
  706. " button.mouseover('Stop Interaction', toolbar_mouse_event);\n",
  707. " buttongrp.append(button);\n",
  708. " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n",
  709. " titlebar.prepend(buttongrp);\n",
  710. "}\n",
  711. "\n",
  712. "mpl.figure.prototype._root_extra_style = function(el){\n",
  713. " var fig = this\n",
  714. " el.on(\"remove\", function(){\n",
  715. "\tfig.close_ws(fig, {});\n",
  716. " });\n",
  717. "}\n",
  718. "\n",
  719. "mpl.figure.prototype._canvas_extra_style = function(el){\n",
  720. " // this is important to make the div 'focusable\n",
  721. " el.attr('tabindex', 0)\n",
  722. " // reach out to IPython and tell the keyboard manager to turn it's self\n",
  723. " // off when our div gets focus\n",
  724. "\n",
  725. " // location in version 3\n",
  726. " if (IPython.notebook.keyboard_manager) {\n",
  727. " IPython.notebook.keyboard_manager.register_events(el);\n",
  728. " }\n",
  729. " else {\n",
  730. " // location in version 2\n",
  731. " IPython.keyboard_manager.register_events(el);\n",
  732. " }\n",
  733. "\n",
  734. "}\n",
  735. "\n",
  736. "mpl.figure.prototype._key_event_extra = function(event, name) {\n",
  737. " var manager = IPython.notebook.keyboard_manager;\n",
  738. " if (!manager)\n",
  739. " manager = IPython.keyboard_manager;\n",
  740. "\n",
  741. " // Check for shift+enter\n",
  742. " if (event.shiftKey && event.which == 13) {\n",
  743. " this.canvas_div.blur();\n",
  744. " // select the cell after this one\n",
  745. " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n",
  746. " IPython.notebook.select(index + 1);\n",
  747. " }\n",
  748. "}\n",
  749. "\n",
  750. "mpl.figure.prototype.handle_save = function(fig, msg) {\n",
  751. " fig.ondownload(fig, null);\n",
  752. "}\n",
  753. "\n",
  754. "\n",
  755. "mpl.find_output_cell = function(html_output) {\n",
  756. " // Return the cell and output element which can be found *uniquely* in the notebook.\n",
  757. " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n",
  758. " // IPython event is triggered only after the cells have been serialised, which for\n",
  759. " // our purposes (turning an active figure into a static one), is too late.\n",
  760. " var cells = IPython.notebook.get_cells();\n",
  761. " var ncells = cells.length;\n",
  762. " for (var i=0; i<ncells; i++) {\n",
  763. " var cell = cells[i];\n",
  764. " if (cell.cell_type === 'code'){\n",
  765. " for (var j=0; j<cell.output_area.outputs.length; j++) {\n",
  766. " var data = cell.output_area.outputs[j];\n",
  767. " if (data.data) {\n",
  768. " // IPython >= 3 moved mimebundle to data attribute of output\n",
  769. " data = data.data;\n",
  770. " }\n",
  771. " if (data['text/html'] == html_output) {\n",
  772. " return [cell, data, j];\n",
  773. " }\n",
  774. " }\n",
  775. " }\n",
  776. " }\n",
  777. "}\n",
  778. "\n",
  779. "// Register the function which deals with the matplotlib target/channel.\n",
  780. "// The kernel may be null if the page has been refreshed.\n",
  781. "if (IPython.notebook.kernel != null) {\n",
  782. " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n",
  783. "}\n"
  784. ],
  785. "text/plain": [
  786. "<IPython.core.display.Javascript object>"
  787. ]
  788. },
  789. "metadata": {},
  790. "output_type": "display_data"
  791. },
  792. {
  793. "data": {
  794. "text/html": [
  795. "<img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA4QAAAMgCAYAAAB7w6zDAAAgAElEQVR4nOzdeXSU5d3G8SeBbCQRghJAokE5KFoUUFRUKAgibriVKtbygsqrglakVsprq8BBaKlbpa1YUcGtrixiQQoWwQ2VihYVEC0aU0Vxgwqy53r/0JkyTBLyBLjD/bu/n3N+5+hkMnnCM/dc95WZTCIBAAAAAIIU1fUBAAAAAADqBoUQAAAAAAJFIQQAAACAQFEIAQAAACBQFEIAAAAACBSFEAAAAAACRSEEAAAAgEBRCAEAAAAgUBRCAAAAAAgUhRAAAAAAAkUhBAAAAIBAUQgBAAAAIFAUQgAAAAAIFIUQAAAAAAJFIQQAAACAQFEIAQAAACBQFEIAAAAACBSFEAAAAAACRSEEAAAAgEBRCAF4oWfPnjriiCPUrl07de7cWW+88UZdHxIAALVCpmFvQiEE4IWvv/46+d/Tpk1Thw4d6vBoAACoPTINexMKIQDvTJ48WUcffXRdHwYAALuMTENdoxAC8Ea/fv1UUlKikpISvf3223V9OAAA1BqZhr0FhRCAdyZPnqzTTjutrg8DAIBdRqahrlEIAXgpNzdXX3zxRV0fBgAAu4xMQ12iEALY661du1Yff/xx8v+nTp2qFi1aqKKiog6PCgCA+Mg07G0ohAD2eh999JGOOeYYtW3bVkceeaR69OjBW3QDALxEpmFvQyEEAAAAgEBRCAEAAAAgUBRCAAAAAAgUhRAAAAAAAkUhBAAAAIBAUQgBAAAAIFAUQgAAAAAIFIUQAAAAAAJFIQQAAACAQFEIAQAAACBQFEIAAAAACBSFEAAAAAACRSEEAAAAgEBRCAEAAAAgUBRCAAAAAAgUhRAAAAAAAkUhBAAAAIBAUQgBAAAAIFAUQgAAAAAIFIUQAAAAAAJFIQQAAACAQFEIAQAAACBQFEIAAAAACBSFEAAAAAACRSEEAAAAgEBRCAEAAAAgUBRCAAAAAAgUhRAAAAAAAkUhBAAAAIBAUQgBAAAAIFAUQgAAAAAIFIUQAAAAAAJFIQQAAACAQFEIAQAAACBQFEIAAAAACBSFEAAAAAACRSEEAAAAgEBRCAEAAAAgUBRCAAAAAAgUhRAAAAAAAkUhBAAAAIBAUQgBAAAAIFAUQgAAAAAIFIUQAAAAAAJFIQQAAACAQFEIAQAAACBQFEIAAAAACBSFEAAAAAACRSEEvjdp0iRFUZScnJwcNW3aVN26ddPYsWP12Wef1fUh1khpaan69+9f14fhjf79+6u0tLRWn/vwww/r9ttv370H9L09eR4T9/UPPvggeVlV38sHH3ygKIp088031+prPffcc4qiSE888USlH7/yyisVRVHKce1sEudrxIgRiqJIGRkZ+te//pV22+vWrVNhYaGiKEr5t9yV76lr1676wQ9+UOnHPv/8c0VRpBEjRiQv2/F7qlevnpo1a6YLLrhAK1asiHX7tVHZua6pmTNnpnwvu9uoUaN02GGHadu2bZLinZfqjm3MmDGaNm3a7jzUWjn33HN11llnpVz25Zdfqn79+po6daokKYoiXXnllc6PLbF2Pv/8c+dfW9p7ztGu2P5cbt68WQcffPAeywNgT6MQAt9LbJwmTZqkhQsX6vnnn9eTTz6pa665Rg0bNlTjxo01d+7cuj7MnVq8eLHef//9uj4Mb7z//vtavHhxrT73jDPOqHWZ3Jk9WQhXr16thQsXauPGjcnLqvpeXBbCxHFtP1EUqU+fPimXJc5XYlNbWFioX//612m3PWnSJOXm5iorK6vOC2HiceW5557TTTfdpLy8PBUXF+urr76q8e3Xxq4Uwu3Pze728ccfKz8/P+V+Eee8VHds+fn5df5DsXXr1ikvL0/3339/yuX33XefGjRooG+//VZSuIVwbzhHu2rHczl58mQVFRXpiy++qOMjA+KjEALfS2ycFi1alPaxsrIyHXDAASosLNSnn35aB0eHvZGvhbAye0MhrEx1G+bEpnbgwIE64IADks80JXTu3FkXXnhh2uazLgrhjo8ro0aNUhRFuu+++2p8+7WxtxbCYcOGqUWLFinnzFIhfPzxx5WVlZVW+E8//XT16dMn+f8UQn/teC43bdqkxo0ba8yYMXV4VEDtUAiB71VXCKXvAj6KIo0aNSrl8qeeekqdOnVSXl6eCgoKdPLJJ+vll19OuU4ifP/5z3+qT58+2meffVRUVKShQ4dqy5YtWr58uXr16qWCggKVlpZq3LhxKZ+/YcMG/fznP1e7du2Sn9upUydNnz497Th3LBKJDflf/vIXXX/99WrevLkKCwvVo0cPLV++POVzFy9erDPOOENNmjRRdna2mjdvrtNPP13l5eXV/tvNmTNHZ511llq0aKGcnBy1atVKl112WdpmY/Xq1frf//1flZSUKDs7W/vtt59OOOGElGdea3IMGzZs0PDhw9WyZUtlZWVp//331+DBg/X111+nHdvDDz+sTp06KT8/X/n5+WrXrp3uueee5Mcre8noH//4R3Xp0kVNmjRRgwYN1LZtW40bN06bN29OXqdr166VvpwxYdOmTRo9erQOPfTQ5Pc6YMAArV69OuVrbd68Wdddd52aNm2qvLw8nXjiiXr11VdrVAg7duyo008/PeWytm3bKooivfbaa8nLpkyZoiiKtGTJEknpJaG672X7Tfqtt96qli1bKj8/X506ddLChQurPT7JTSF8+eWXFUWRZs+enfzYu+++qyiKNHfu3L2yEM6cOVNRFOk3v/lNjW9/ZxYuXKgTTjhBOTk5at68uYYPH6677747rRA++uij6tmzp5o1a6bc3Fy1adNGv/zlL7Vu3brkdfr371/pfSJxOzVZI1XZtGmT9t13X1133XUpl9f0vlbdsVV2edeuXSX991zMmTNHAwYMUFFRkRo0aKAzzzwz7SXHtX0sTLjgggvUq1evlMvWrl2r7OxsPfLII8nLEvfvBx54QG3atFFeXp6OPPJIPf3002m3+cILL6h79+4qKChQXl6ejj/+eP31r39NfryiokKnnXaaGjdurLKysuTl69ev1+GHH642bdokz3Fi7bz99tvq27ev9tlnHxUXF+viiy/WmjVr0s7JpEmT0o5nx/t6TW+zunNUlY0bN2rUqFFq06aNcnJy1LhxY3Xr1k0vvfRS8jo1zYXS0lKdccYZevrpp9W+ffvkGkj8m0+aNElt2rRRgwYNdMwxx1S6J6jsXErSoEGDVFpaqoqKimq/H2BvQyEEvrezQrhu3TrVq1dPPXr0SF728MMPK4oinXLKKZo+fboee+wxHX300crOztYLL7yQvF4iKA899FCNHj1ac+fO1bBhwxRFka666iq1adNG48eP19y5c3XxxRcriiJNmTIl+flr1qzRgAED9OCDD2revHmaPXu2fvGLXygzMzPtJUlVFcKWLVvqoosu0syZM/XII4/owAMPVOvWrbV169bk97fvvvuqY8eOevzxx7VgwQI99thjuuKKK7R06dJq/+0mTJig3/zmN5oxY4YWLFig+++/X+3atdOhhx6askHs1auXmjRporvvvlvz58/X9OnTdeONN+rRRx+t8TFUVFSoV69eql+/vm644QbNmTNHt9xyi/Lz89WhQ4eUl0HecMMNiqJI5513np544gnNmTNHt912m2644YbkdSorhEOHDtWECRM0e/ZszZs3T7fffrv2228/XXzxxcnrvPPOOzrxxBPVrFmzlJczStK2bdt06qmnKj8/X6NGjdLcuXN1zz33qEWLFjr88MOTLzFKfP2MjAxdd911yeNr0aKF9tlnn50WwuHDh6ugoCD5b/zpp58qiiLl5eWl/JR60KBBatq0afL/dyyE1X0viQ1hy5Ytdeqpp2r69OmaPn26jjjiCBUVFaVs9CqTuP899thj2rJlS9oMHjx4lwvh559/ri5duuj8889PfuyXv/ylWrZsqYqKir2yEP7xj39MW+c7u/3qvPPOO2rQoIEOP/xwPfLII3rqqafUq1cvHXjggWmFcPTo0br99ts1c+ZMzZ8/X3fddZcOOu
  796. ],
  797. "text/plain": [
  798. "<IPython.core.display.HTML object>"
  799. ]
  800. },
  801. "metadata": {},
  802. "output_type": "display_data"
  803. },
  804. {
  805. "name": "stdout",
  806. "output_type": "stream",
  807. "text": [
  808. "Generating statistics: https://hs.fi\n"
  809. ]
  810. },
  811. {
  812. "data": {
  813. "application/javascript": [
  814. "/* Put everything inside the global mpl namespace */\n",
  815. "window.mpl = {};\n",
  816. "\n",
  817. "\n",
  818. "mpl.get_websocket_type = function() {\n",
  819. " if (typeof(WebSocket) !== 'undefined') {\n",
  820. " return WebSocket;\n",
  821. " } else if (typeof(MozWebSocket) !== 'undefined') {\n",
  822. " return MozWebSocket;\n",
  823. " } else {\n",
  824. " alert('Your browser does not have WebSocket support. ' +\n",
  825. " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n",
  826. " 'Firefox 4 and 5 are also supported but you ' +\n",
  827. " 'have to enable WebSockets in about:config.');\n",
  828. " };\n",
  829. "}\n",
  830. "\n",
  831. "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n",
  832. " this.id = figure_id;\n",
  833. "\n",
  834. " this.ws = websocket;\n",
  835. "\n",
  836. " this.supports_binary = (this.ws.binaryType != undefined);\n",
  837. "\n",
  838. " if (!this.supports_binary) {\n",
  839. " var warnings = document.getElementById(\"mpl-warnings\");\n",
  840. " if (warnings) {\n",
  841. " warnings.style.display = 'block';\n",
  842. " warnings.textContent = (\n",
  843. " \"This browser does not support binary websocket messages. \" +\n",
  844. " \"Performance may be slow.\");\n",
  845. " }\n",
  846. " }\n",
  847. "\n",
  848. " this.imageObj = new Image();\n",
  849. "\n",
  850. " this.context = undefined;\n",
  851. " this.message = undefined;\n",
  852. " this.canvas = undefined;\n",
  853. " this.rubberband_canvas = undefined;\n",
  854. " this.rubberband_context = undefined;\n",
  855. " this.format_dropdown = undefined;\n",
  856. "\n",
  857. " this.image_mode = 'full';\n",
  858. "\n",
  859. " this.root = $('<div/>');\n",
  860. " this._root_extra_style(this.root)\n",
  861. " this.root.attr('style', 'display: inline-block');\n",
  862. "\n",
  863. " $(parent_element).append(this.root);\n",
  864. "\n",
  865. " this._init_header(this);\n",
  866. " this._init_canvas(this);\n",
  867. " this._init_toolbar(this);\n",
  868. "\n",
  869. " var fig = this;\n",
  870. "\n",
  871. " this.waiting = false;\n",
  872. "\n",
  873. " this.ws.onopen = function () {\n",
  874. " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n",
  875. " fig.send_message(\"send_image_mode\", {});\n",
  876. " if (mpl.ratio != 1) {\n",
  877. " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n",
  878. " }\n",
  879. " fig.send_message(\"refresh\", {});\n",
  880. " }\n",
  881. "\n",
  882. " this.imageObj.onload = function() {\n",
  883. " if (fig.image_mode == 'full') {\n",
  884. " // Full images could contain transparency (where diff images\n",
  885. " // almost always do), so we need to clear the canvas so that\n",
  886. " // there is no ghosting.\n",
  887. " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n",
  888. " }\n",
  889. " fig.context.drawImage(fig.imageObj, 0, 0);\n",
  890. " };\n",
  891. "\n",
  892. " this.imageObj.onunload = function() {\n",
  893. " fig.ws.close();\n",
  894. " }\n",
  895. "\n",
  896. " this.ws.onmessage = this._make_on_message_function(this);\n",
  897. "\n",
  898. " this.ondownload = ondownload;\n",
  899. "}\n",
  900. "\n",
  901. "mpl.figure.prototype._init_header = function() {\n",
  902. " var titlebar = $(\n",
  903. " '<div class=\"ui-dialog-titlebar ui-widget-header ui-corner-all ' +\n",
  904. " 'ui-helper-clearfix\"/>');\n",
  905. " var titletext = $(\n",
  906. " '<div class=\"ui-dialog-title\" style=\"width: 100%; ' +\n",
  907. " 'text-align: center; padding: 3px;\"/>');\n",
  908. " titlebar.append(titletext)\n",
  909. " this.root.append(titlebar);\n",
  910. " this.header = titletext[0];\n",
  911. "}\n",
  912. "\n",
  913. "\n",
  914. "\n",
  915. "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n",
  916. "\n",
  917. "}\n",
  918. "\n",
  919. "\n",
  920. "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n",
  921. "\n",
  922. "}\n",
  923. "\n",
  924. "mpl.figure.prototype._init_canvas = function() {\n",
  925. " var fig = this;\n",
  926. "\n",
  927. " var canvas_div = $('<div/>');\n",
  928. "\n",
  929. " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n",
  930. "\n",
  931. " function canvas_keyboard_event(event) {\n",
  932. " return fig.key_event(event, event['data']);\n",
  933. " }\n",
  934. "\n",
  935. " canvas_div.keydown('key_press', canvas_keyboard_event);\n",
  936. " canvas_div.keyup('key_release', canvas_keyboard_event);\n",
  937. " this.canvas_div = canvas_div\n",
  938. " this._canvas_extra_style(canvas_div)\n",
  939. " this.root.append(canvas_div);\n",
  940. "\n",
  941. " var canvas = $('<canvas/>');\n",
  942. " canvas.addClass('mpl-canvas');\n",
  943. " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n",
  944. "\n",
  945. " this.canvas = canvas[0];\n",
  946. " this.context = canvas[0].getContext(\"2d\");\n",
  947. "\n",
  948. " var backingStore = this.context.backingStorePixelRatio ||\n",
  949. "\tthis.context.webkitBackingStorePixelRatio ||\n",
  950. "\tthis.context.mozBackingStorePixelRatio ||\n",
  951. "\tthis.context.msBackingStorePixelRatio ||\n",
  952. "\tthis.context.oBackingStorePixelRatio ||\n",
  953. "\tthis.context.backingStorePixelRatio || 1;\n",
  954. "\n",
  955. " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n",
  956. "\n",
  957. " var rubberband = $('<canvas/>');\n",
  958. " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n",
  959. "\n",
  960. " var pass_mouse_events = true;\n",
  961. "\n",
  962. " canvas_div.resizable({\n",
  963. " start: function(event, ui) {\n",
  964. " pass_mouse_events = false;\n",
  965. " },\n",
  966. " resize: function(event, ui) {\n",
  967. " fig.request_resize(ui.size.width, ui.size.height);\n",
  968. " },\n",
  969. " stop: function(event, ui) {\n",
  970. " pass_mouse_events = true;\n",
  971. " fig.request_resize(ui.size.width, ui.size.height);\n",
  972. " },\n",
  973. " });\n",
  974. "\n",
  975. " function mouse_event_fn(event) {\n",
  976. " if (pass_mouse_events)\n",
  977. " return fig.mouse_event(event, event['data']);\n",
  978. " }\n",
  979. "\n",
  980. " rubberband.mousedown('button_press', mouse_event_fn);\n",
  981. " rubberband.mouseup('button_release', mouse_event_fn);\n",
  982. " // Throttle sequential mouse events to 1 every 20ms.\n",
  983. " rubberband.mousemove('motion_notify', mouse_event_fn);\n",
  984. "\n",
  985. " rubberband.mouseenter('figure_enter', mouse_event_fn);\n",
  986. " rubberband.mouseleave('figure_leave', mouse_event_fn);\n",
  987. "\n",
  988. " canvas_div.on(\"wheel\", function (event) {\n",
  989. " event = event.originalEvent;\n",
  990. " event['data'] = 'scroll'\n",
  991. " if (event.deltaY < 0) {\n",
  992. " event.step = 1;\n",
  993. " } else {\n",
  994. " event.step = -1;\n",
  995. " }\n",
  996. " mouse_event_fn(event);\n",
  997. " });\n",
  998. "\n",
  999. " canvas_div.append(canvas);\n",
  1000. " canvas_div.append(rubberband);\n",
  1001. "\n",
  1002. " this.rubberband = rubberband;\n",
  1003. " this.rubberband_canvas = rubberband[0];\n",
  1004. " this.rubberband_context = rubberband[0].getContext(\"2d\");\n",
  1005. " this.rubberband_context.strokeStyle = \"#000000\";\n",
  1006. "\n",
  1007. " this._resize_canvas = function(width, height) {\n",
  1008. " // Keep the size of the canvas, canvas container, and rubber band\n",
  1009. " // canvas in synch.\n",
  1010. " canvas_div.css('width', width)\n",
  1011. " canvas_div.css('height', height)\n",
  1012. "\n",
  1013. " canvas.attr('width', width * mpl.ratio);\n",
  1014. " canvas.attr('height', height * mpl.ratio);\n",
  1015. " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n",
  1016. "\n",
  1017. " rubberband.attr('width', width);\n",
  1018. " rubberband.attr('height', height);\n",
  1019. " }\n",
  1020. "\n",
  1021. " // Set the figure to an initial 600x600px, this will subsequently be updated\n",
  1022. " // upon first draw.\n",
  1023. " this._resize_canvas(600, 600);\n",
  1024. "\n",
  1025. " // Disable right mouse context menu.\n",
  1026. " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n",
  1027. " return false;\n",
  1028. " });\n",
  1029. "\n",
  1030. " function set_focus () {\n",
  1031. " canvas.focus();\n",
  1032. " canvas_div.focus();\n",
  1033. " }\n",
  1034. "\n",
  1035. " window.setTimeout(set_focus, 100);\n",
  1036. "}\n",
  1037. "\n",
  1038. "mpl.figure.prototype._init_toolbar = function() {\n",
  1039. " var fig = this;\n",
  1040. "\n",
  1041. " var nav_element = $('<div/>');\n",
  1042. " nav_element.attr('style', 'width: 100%');\n",
  1043. " this.root.append(nav_element);\n",
  1044. "\n",
  1045. " // Define a callback function for later on.\n",
  1046. " function toolbar_event(event) {\n",
  1047. " return fig.toolbar_button_onclick(event['data']);\n",
  1048. " }\n",
  1049. " function toolbar_mouse_event(event) {\n",
  1050. " return fig.toolbar_button_onmouseover(event['data']);\n",
  1051. " }\n",
  1052. "\n",
  1053. " for(var toolbar_ind in mpl.toolbar_items) {\n",
  1054. " var name = mpl.toolbar_items[toolbar_ind][0];\n",
  1055. " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n",
  1056. " var image = mpl.toolbar_items[toolbar_ind][2];\n",
  1057. " var method_name = mpl.toolbar_items[toolbar_ind][3];\n",
  1058. "\n",
  1059. " if (!name) {\n",
  1060. " // put a spacer in here.\n",
  1061. " continue;\n",
  1062. " }\n",
  1063. " var button = $('<button/>');\n",
  1064. " button.addClass('ui-button ui-widget ui-state-default ui-corner-all ' +\n",
  1065. " 'ui-button-icon-only');\n",
  1066. " button.attr('role', 'button');\n",
  1067. " button.attr('aria-disabled', 'false');\n",
  1068. " button.click(method_name, toolbar_event);\n",
  1069. " button.mouseover(tooltip, toolbar_mouse_event);\n",
  1070. "\n",
  1071. " var icon_img = $('<span/>');\n",
  1072. " icon_img.addClass('ui-button-icon-primary ui-icon');\n",
  1073. " icon_img.addClass(image);\n",
  1074. " icon_img.addClass('ui-corner-all');\n",
  1075. "\n",
  1076. " var tooltip_span = $('<span/>');\n",
  1077. " tooltip_span.addClass('ui-button-text');\n",
  1078. " tooltip_span.html(tooltip);\n",
  1079. "\n",
  1080. " button.append(icon_img);\n",
  1081. " button.append(tooltip_span);\n",
  1082. "\n",
  1083. " nav_element.append(button);\n",
  1084. " }\n",
  1085. "\n",
  1086. " var fmt_picker_span = $('<span/>');\n",
  1087. "\n",
  1088. " var fmt_picker = $('<select/>');\n",
  1089. " fmt_picker.addClass('mpl-toolbar-option ui-widget ui-widget-content');\n",
  1090. " fmt_picker_span.append(fmt_picker);\n",
  1091. " nav_element.append(fmt_picker_span);\n",
  1092. " this.format_dropdown = fmt_picker[0];\n",
  1093. "\n",
  1094. " for (var ind in mpl.extensions) {\n",
  1095. " var fmt = mpl.extensions[ind];\n",
  1096. " var option = $(\n",
  1097. " '<option/>', {selected: fmt === mpl.default_extension}).html(fmt);\n",
  1098. " fmt_picker.append(option);\n",
  1099. " }\n",
  1100. "\n",
  1101. " // Add hover states to the ui-buttons\n",
  1102. " $( \".ui-button\" ).hover(\n",
  1103. " function() { $(this).addClass(\"ui-state-hover\");},\n",
  1104. " function() { $(this).removeClass(\"ui-state-hover\");}\n",
  1105. " );\n",
  1106. "\n",
  1107. " var status_bar = $('<span class=\"mpl-message\"/>');\n",
  1108. " nav_element.append(status_bar);\n",
  1109. " this.message = status_bar[0];\n",
  1110. "}\n",
  1111. "\n",
  1112. "mpl.figure.prototype.request_resize = function(x_pixels, y_pixels) {\n",
  1113. " // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n",
  1114. " // which will in turn request a refresh of the image.\n",
  1115. " this.send_message('resize', {'width': x_pixels, 'height': y_pixels});\n",
  1116. "}\n",
  1117. "\n",
  1118. "mpl.figure.prototype.send_message = function(type, properties) {\n",
  1119. " properties['type'] = type;\n",
  1120. " properties['figure_id'] = this.id;\n",
  1121. " this.ws.send(JSON.stringify(properties));\n",
  1122. "}\n",
  1123. "\n",
  1124. "mpl.figure.prototype.send_draw_message = function() {\n",
  1125. " if (!this.waiting) {\n",
  1126. " this.waiting = true;\n",
  1127. " this.ws.send(JSON.stringify({type: \"draw\", figure_id: this.id}));\n",
  1128. " }\n",
  1129. "}\n",
  1130. "\n",
  1131. "\n",
  1132. "mpl.figure.prototype.handle_save = function(fig, msg) {\n",
  1133. " var format_dropdown = fig.format_dropdown;\n",
  1134. " var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n",
  1135. " fig.ondownload(fig, format);\n",
  1136. "}\n",
  1137. "\n",
  1138. "\n",
  1139. "mpl.figure.prototype.handle_resize = function(fig, msg) {\n",
  1140. " var size = msg['size'];\n",
  1141. " if (size[0] != fig.canvas.width || size[1] != fig.canvas.height) {\n",
  1142. " fig._resize_canvas(size[0], size[1]);\n",
  1143. " fig.send_message(\"refresh\", {});\n",
  1144. " };\n",
  1145. "}\n",
  1146. "\n",
  1147. "mpl.figure.prototype.handle_rubberband = function(fig, msg) {\n",
  1148. " var x0 = msg['x0'] / mpl.ratio;\n",
  1149. " var y0 = (fig.canvas.height - msg['y0']) / mpl.ratio;\n",
  1150. " var x1 = msg['x1'] / mpl.ratio;\n",
  1151. " var y1 = (fig.canvas.height - msg['y1']) / mpl.ratio;\n",
  1152. " x0 = Math.floor(x0) + 0.5;\n",
  1153. " y0 = Math.floor(y0) + 0.5;\n",
  1154. " x1 = Math.floor(x1) + 0.5;\n",
  1155. " y1 = Math.floor(y1) + 0.5;\n",
  1156. " var min_x = Math.min(x0, x1);\n",
  1157. " var min_y = Math.min(y0, y1);\n",
  1158. " var width = Math.abs(x1 - x0);\n",
  1159. " var height = Math.abs(y1 - y0);\n",
  1160. "\n",
  1161. " fig.rubberband_context.clearRect(\n",
  1162. " 0, 0, fig.canvas.width / mpl.ratio, fig.canvas.height / mpl.ratio);\n",
  1163. "\n",
  1164. " fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n",
  1165. "}\n",
  1166. "\n",
  1167. "mpl.figure.prototype.handle_figure_label = function(fig, msg) {\n",
  1168. " // Updates the figure title.\n",
  1169. " fig.header.textContent = msg['label'];\n",
  1170. "}\n",
  1171. "\n",
  1172. "mpl.figure.prototype.handle_cursor = function(fig, msg) {\n",
  1173. " var cursor = msg['cursor'];\n",
  1174. " switch(cursor)\n",
  1175. " {\n",
  1176. " case 0:\n",
  1177. " cursor = 'pointer';\n",
  1178. " break;\n",
  1179. " case 1:\n",
  1180. " cursor = 'default';\n",
  1181. " break;\n",
  1182. " case 2:\n",
  1183. " cursor = 'crosshair';\n",
  1184. " break;\n",
  1185. " case 3:\n",
  1186. " cursor = 'move';\n",
  1187. " break;\n",
  1188. " }\n",
  1189. " fig.rubberband_canvas.style.cursor = cursor;\n",
  1190. "}\n",
  1191. "\n",
  1192. "mpl.figure.prototype.handle_message = function(fig, msg) {\n",
  1193. " fig.message.textContent = msg['message'];\n",
  1194. "}\n",
  1195. "\n",
  1196. "mpl.figure.prototype.handle_draw = function(fig, msg) {\n",
  1197. " // Request the server to send over a new figure.\n",
  1198. " fig.send_draw_message();\n",
  1199. "}\n",
  1200. "\n",
  1201. "mpl.figure.prototype.handle_image_mode = function(fig, msg) {\n",
  1202. " fig.image_mode = msg['mode'];\n",
  1203. "}\n",
  1204. "\n",
  1205. "mpl.figure.prototype.updated_canvas_event = function() {\n",
  1206. " // Called whenever the canvas gets updated.\n",
  1207. " this.send_message(\"ack\", {});\n",
  1208. "}\n",
  1209. "\n",
  1210. "// A function to construct a web socket function for onmessage handling.\n",
  1211. "// Called in the figure constructor.\n",
  1212. "mpl.figure.prototype._make_on_message_function = function(fig) {\n",
  1213. " return function socket_on_message(evt) {\n",
  1214. " if (evt.data instanceof Blob) {\n",
  1215. " /* FIXME: We get \"Resource interpreted as Image but\n",
  1216. " * transferred with MIME type text/plain:\" errors on\n",
  1217. " * Chrome. But how to set the MIME type? It doesn't seem\n",
  1218. " * to be part of the websocket stream */\n",
  1219. " evt.data.type = \"image/png\";\n",
  1220. "\n",
  1221. " /* Free the memory for the previous frames */\n",
  1222. " if (fig.imageObj.src) {\n",
  1223. " (window.URL || window.webkitURL).revokeObjectURL(\n",
  1224. " fig.imageObj.src);\n",
  1225. " }\n",
  1226. "\n",
  1227. " fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n",
  1228. " evt.data);\n",
  1229. " fig.updated_canvas_event();\n",
  1230. " fig.waiting = false;\n",
  1231. " return;\n",
  1232. " }\n",
  1233. " else if (typeof evt.data === 'string' && evt.data.slice(0, 21) == \"data:image/png;base64\") {\n",
  1234. " fig.imageObj.src = evt.data;\n",
  1235. " fig.updated_canvas_event();\n",
  1236. " fig.waiting = false;\n",
  1237. " return;\n",
  1238. " }\n",
  1239. "\n",
  1240. " var msg = JSON.parse(evt.data);\n",
  1241. " var msg_type = msg['type'];\n",
  1242. "\n",
  1243. " // Call the \"handle_{type}\" callback, which takes\n",
  1244. " // the figure and JSON message as its only arguments.\n",
  1245. " try {\n",
  1246. " var callback = fig[\"handle_\" + msg_type];\n",
  1247. " } catch (e) {\n",
  1248. " console.log(\"No handler for the '\" + msg_type + \"' message type: \", msg);\n",
  1249. " return;\n",
  1250. " }\n",
  1251. "\n",
  1252. " if (callback) {\n",
  1253. " try {\n",
  1254. " // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n",
  1255. " callback(fig, msg);\n",
  1256. " } catch (e) {\n",
  1257. " console.log(\"Exception inside the 'handler_\" + msg_type + \"' callback:\", e, e.stack, msg);\n",
  1258. " }\n",
  1259. " }\n",
  1260. " };\n",
  1261. "}\n",
  1262. "\n",
  1263. "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n",
  1264. "mpl.findpos = function(e) {\n",
  1265. " //this section is from http://www.quirksmode.org/js/events_properties.html\n",
  1266. " var targ;\n",
  1267. " if (!e)\n",
  1268. " e = window.event;\n",
  1269. " if (e.target)\n",
  1270. " targ = e.target;\n",
  1271. " else if (e.srcElement)\n",
  1272. " targ = e.srcElement;\n",
  1273. " if (targ.nodeType == 3) // defeat Safari bug\n",
  1274. " targ = targ.parentNode;\n",
  1275. "\n",
  1276. " // jQuery normalizes the pageX and pageY\n",
  1277. " // pageX,Y are the mouse positions relative to the document\n",
  1278. " // offset() returns the position of the element relative to the document\n",
  1279. " var x = e.pageX - $(targ).offset().left;\n",
  1280. " var y = e.pageY - $(targ).offset().top;\n",
  1281. "\n",
  1282. " return {\"x\": x, \"y\": y};\n",
  1283. "};\n",
  1284. "\n",
  1285. "/*\n",
  1286. " * return a copy of an object with only non-object keys\n",
  1287. " * we need this to avoid circular references\n",
  1288. " * http://stackoverflow.com/a/24161582/3208463\n",
  1289. " */\n",
  1290. "function simpleKeys (original) {\n",
  1291. " return Object.keys(original).reduce(function (obj, key) {\n",
  1292. " if (typeof original[key] !== 'object')\n",
  1293. " obj[key] = original[key]\n",
  1294. " return obj;\n",
  1295. " }, {});\n",
  1296. "}\n",
  1297. "\n",
  1298. "mpl.figure.prototype.mouse_event = function(event, name) {\n",
  1299. " var canvas_pos = mpl.findpos(event)\n",
  1300. "\n",
  1301. " if (name === 'button_press')\n",
  1302. " {\n",
  1303. " this.canvas.focus();\n",
  1304. " this.canvas_div.focus();\n",
  1305. " }\n",
  1306. "\n",
  1307. " var x = canvas_pos.x * mpl.ratio;\n",
  1308. " var y = canvas_pos.y * mpl.ratio;\n",
  1309. "\n",
  1310. " this.send_message(name, {x: x, y: y, button: event.button,\n",
  1311. " step: event.step,\n",
  1312. " guiEvent: simpleKeys(event)});\n",
  1313. "\n",
  1314. " /* This prevents the web browser from automatically changing to\n",
  1315. " * the text insertion cursor when the button is pressed. We want\n",
  1316. " * to control all of the cursor setting manually through the\n",
  1317. " * 'cursor' event from matplotlib */\n",
  1318. " event.preventDefault();\n",
  1319. " return false;\n",
  1320. "}\n",
  1321. "\n",
  1322. "mpl.figure.prototype._key_event_extra = function(event, name) {\n",
  1323. " // Handle any extra behaviour associated with a key event\n",
  1324. "}\n",
  1325. "\n",
  1326. "mpl.figure.prototype.key_event = function(event, name) {\n",
  1327. "\n",
  1328. " // Prevent repeat events\n",
  1329. " if (name == 'key_press')\n",
  1330. " {\n",
  1331. " if (event.which === this._key)\n",
  1332. " return;\n",
  1333. " else\n",
  1334. " this._key = event.which;\n",
  1335. " }\n",
  1336. " if (name == 'key_release')\n",
  1337. " this._key = null;\n",
  1338. "\n",
  1339. " var value = '';\n",
  1340. " if (event.ctrlKey && event.which != 17)\n",
  1341. " value += \"ctrl+\";\n",
  1342. " if (event.altKey && event.which != 18)\n",
  1343. " value += \"alt+\";\n",
  1344. " if (event.shiftKey && event.which != 16)\n",
  1345. " value += \"shift+\";\n",
  1346. "\n",
  1347. " value += 'k';\n",
  1348. " value += event.which.toString();\n",
  1349. "\n",
  1350. " this._key_event_extra(event, name);\n",
  1351. "\n",
  1352. " this.send_message(name, {key: value,\n",
  1353. " guiEvent: simpleKeys(event)});\n",
  1354. " return false;\n",
  1355. "}\n",
  1356. "\n",
  1357. "mpl.figure.prototype.toolbar_button_onclick = function(name) {\n",
  1358. " if (name == 'download') {\n",
  1359. " this.handle_save(this, null);\n",
  1360. " } else {\n",
  1361. " this.send_message(\"toolbar_button\", {name: name});\n",
  1362. " }\n",
  1363. "};\n",
  1364. "\n",
  1365. "mpl.figure.prototype.toolbar_button_onmouseover = function(tooltip) {\n",
  1366. " this.message.textContent = tooltip;\n",
  1367. "};\n",
  1368. "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Pan axes with left mouse, zoom with right\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n",
  1369. "\n",
  1370. "mpl.extensions = [\"eps\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\"];\n",
  1371. "\n",
  1372. "mpl.default_extension = \"png\";var comm_websocket_adapter = function(comm) {\n",
  1373. " // Create a \"websocket\"-like object which calls the given IPython comm\n",
  1374. " // object with the appropriate methods. Currently this is a non binary\n",
  1375. " // socket, so there is still some room for performance tuning.\n",
  1376. " var ws = {};\n",
  1377. "\n",
  1378. " ws.close = function() {\n",
  1379. " comm.close()\n",
  1380. " };\n",
  1381. " ws.send = function(m) {\n",
  1382. " //console.log('sending', m);\n",
  1383. " comm.send(m);\n",
  1384. " };\n",
  1385. " // Register the callback with on_msg.\n",
  1386. " comm.on_msg(function(msg) {\n",
  1387. " //console.log('receiving', msg['content']['data'], msg);\n",
  1388. " // Pass the mpl event to the overridden (by mpl) onmessage function.\n",
  1389. " ws.onmessage(msg['content']['data'])\n",
  1390. " });\n",
  1391. " return ws;\n",
  1392. "}\n",
  1393. "\n",
  1394. "mpl.mpl_figure_comm = function(comm, msg) {\n",
  1395. " // This is the function which gets called when the mpl process\n",
  1396. " // starts-up an IPython Comm through the \"matplotlib\" channel.\n",
  1397. "\n",
  1398. " var id = msg.content.data.id;\n",
  1399. " // Get hold of the div created by the display call when the Comm\n",
  1400. " // socket was opened in Python.\n",
  1401. " var element = $(\"#\" + id);\n",
  1402. " var ws_proxy = comm_websocket_adapter(comm)\n",
  1403. "\n",
  1404. " function ondownload(figure, format) {\n",
  1405. " window.open(figure.imageObj.src);\n",
  1406. " }\n",
  1407. "\n",
  1408. " var fig = new mpl.figure(id, ws_proxy,\n",
  1409. " ondownload,\n",
  1410. " element.get(0));\n",
  1411. "\n",
  1412. " // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n",
  1413. " // web socket which is closed, not our websocket->open comm proxy.\n",
  1414. " ws_proxy.onopen();\n",
  1415. "\n",
  1416. " fig.parent_element = element.get(0);\n",
  1417. " fig.cell_info = mpl.find_output_cell(\"<div id='\" + id + \"'></div>\");\n",
  1418. " if (!fig.cell_info) {\n",
  1419. " console.error(\"Failed to find cell for figure\", id, fig);\n",
  1420. " return;\n",
  1421. " }\n",
  1422. "\n",
  1423. " var output_index = fig.cell_info[2]\n",
  1424. " var cell = fig.cell_info[0];\n",
  1425. "\n",
  1426. "};\n",
  1427. "\n",
  1428. "mpl.figure.prototype.handle_close = function(fig, msg) {\n",
  1429. " var width = fig.canvas.width/mpl.ratio\n",
  1430. " fig.root.unbind('remove')\n",
  1431. "\n",
  1432. " // Update the output cell to use the data from the current canvas.\n",
  1433. " fig.push_to_output();\n",
  1434. " var dataURL = fig.canvas.toDataURL();\n",
  1435. " // Re-enable the keyboard manager in IPython - without this line, in FF,\n",
  1436. " // the notebook keyboard shortcuts fail.\n",
  1437. " IPython.keyboard_manager.enable()\n",
  1438. " $(fig.parent_element).html('<img src=\"' + dataURL + '\" width=\"' + width + '\">');\n",
  1439. " fig.close_ws(fig, msg);\n",
  1440. "}\n",
  1441. "\n",
  1442. "mpl.figure.prototype.close_ws = function(fig, msg){\n",
  1443. " fig.send_message('closing', msg);\n",
  1444. " // fig.ws.close()\n",
  1445. "}\n",
  1446. "\n",
  1447. "mpl.figure.prototype.push_to_output = function(remove_interactive) {\n",
  1448. " // Turn the data on the canvas into data in the output cell.\n",
  1449. " var width = this.canvas.width/mpl.ratio\n",
  1450. " var dataURL = this.canvas.toDataURL();\n",
  1451. " this.cell_info[1]['text/html'] = '<img src=\"' + dataURL + '\" width=\"' + width + '\">';\n",
  1452. "}\n",
  1453. "\n",
  1454. "mpl.figure.prototype.updated_canvas_event = function() {\n",
  1455. " // Tell IPython that the notebook contents must change.\n",
  1456. " IPython.notebook.set_dirty(true);\n",
  1457. " this.send_message(\"ack\", {});\n",
  1458. " var fig = this;\n",
  1459. " // Wait a second, then push the new image to the DOM so\n",
  1460. " // that it is saved nicely (might be nice to debounce this).\n",
  1461. " setTimeout(function () { fig.push_to_output() }, 1000);\n",
  1462. "}\n",
  1463. "\n",
  1464. "mpl.figure.prototype._init_toolbar = function() {\n",
  1465. " var fig = this;\n",
  1466. "\n",
  1467. " var nav_element = $('<div/>');\n",
  1468. " nav_element.attr('style', 'width: 100%');\n",
  1469. " this.root.append(nav_element);\n",
  1470. "\n",
  1471. " // Define a callback function for later on.\n",
  1472. " function toolbar_event(event) {\n",
  1473. " return fig.toolbar_button_onclick(event['data']);\n",
  1474. " }\n",
  1475. " function toolbar_mouse_event(event) {\n",
  1476. " return fig.toolbar_button_onmouseover(event['data']);\n",
  1477. " }\n",
  1478. "\n",
  1479. " for(var toolbar_ind in mpl.toolbar_items){\n",
  1480. " var name = mpl.toolbar_items[toolbar_ind][0];\n",
  1481. " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n",
  1482. " var image = mpl.toolbar_items[toolbar_ind][2];\n",
  1483. " var method_name = mpl.toolbar_items[toolbar_ind][3];\n",
  1484. "\n",
  1485. " if (!name) { continue; };\n",
  1486. "\n",
  1487. " var button = $('<button class=\"btn btn-default\" href=\"#\" title=\"' + name + '\"><i class=\"fa ' + image + ' fa-lg\"></i></button>');\n",
  1488. " button.click(method_name, toolbar_event);\n",
  1489. " button.mouseover(tooltip, toolbar_mouse_event);\n",
  1490. " nav_element.append(button);\n",
  1491. " }\n",
  1492. "\n",
  1493. " // Add the status bar.\n",
  1494. " var status_bar = $('<span class=\"mpl-message\" style=\"text-align:right; float: right;\"/>');\n",
  1495. " nav_element.append(status_bar);\n",
  1496. " this.message = status_bar[0];\n",
  1497. "\n",
  1498. " // Add the close button to the window.\n",
  1499. " var buttongrp = $('<div class=\"btn-group inline pull-right\"></div>');\n",
  1500. " var button = $('<button class=\"btn btn-mini btn-primary\" href=\"#\" title=\"Stop Interaction\"><i class=\"fa fa-power-off icon-remove icon-large\"></i></button>');\n",
  1501. " button.click(function (evt) { fig.handle_close(fig, {}); } );\n",
  1502. " button.mouseover('Stop Interaction', toolbar_mouse_event);\n",
  1503. " buttongrp.append(button);\n",
  1504. " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n",
  1505. " titlebar.prepend(buttongrp);\n",
  1506. "}\n",
  1507. "\n",
  1508. "mpl.figure.prototype._root_extra_style = function(el){\n",
  1509. " var fig = this\n",
  1510. " el.on(\"remove\", function(){\n",
  1511. "\tfig.close_ws(fig, {});\n",
  1512. " });\n",
  1513. "}\n",
  1514. "\n",
  1515. "mpl.figure.prototype._canvas_extra_style = function(el){\n",
  1516. " // this is important to make the div 'focusable\n",
  1517. " el.attr('tabindex', 0)\n",
  1518. " // reach out to IPython and tell the keyboard manager to turn it's self\n",
  1519. " // off when our div gets focus\n",
  1520. "\n",
  1521. " // location in version 3\n",
  1522. " if (IPython.notebook.keyboard_manager) {\n",
  1523. " IPython.notebook.keyboard_manager.register_events(el);\n",
  1524. " }\n",
  1525. " else {\n",
  1526. " // location in version 2\n",
  1527. " IPython.keyboard_manager.register_events(el);\n",
  1528. " }\n",
  1529. "\n",
  1530. "}\n",
  1531. "\n",
  1532. "mpl.figure.prototype._key_event_extra = function(event, name) {\n",
  1533. " var manager = IPython.notebook.keyboard_manager;\n",
  1534. " if (!manager)\n",
  1535. " manager = IPython.keyboard_manager;\n",
  1536. "\n",
  1537. " // Check for shift+enter\n",
  1538. " if (event.shiftKey && event.which == 13) {\n",
  1539. " this.canvas_div.blur();\n",
  1540. " // select the cell after this one\n",
  1541. " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n",
  1542. " IPython.notebook.select(index + 1);\n",
  1543. " }\n",
  1544. "}\n",
  1545. "\n",
  1546. "mpl.figure.prototype.handle_save = function(fig, msg) {\n",
  1547. " fig.ondownload(fig, null);\n",
  1548. "}\n",
  1549. "\n",
  1550. "\n",
  1551. "mpl.find_output_cell = function(html_output) {\n",
  1552. " // Return the cell and output element which can be found *uniquely* in the notebook.\n",
  1553. " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n",
  1554. " // IPython event is triggered only after the cells have been serialised, which for\n",
  1555. " // our purposes (turning an active figure into a static one), is too late.\n",
  1556. " var cells = IPython.notebook.get_cells();\n",
  1557. " var ncells = cells.length;\n",
  1558. " for (var i=0; i<ncells; i++) {\n",
  1559. " var cell = cells[i];\n",
  1560. " if (cell.cell_type === 'code'){\n",
  1561. " for (var j=0; j<cell.output_area.outputs.length; j++) {\n",
  1562. " var data = cell.output_area.outputs[j];\n",
  1563. " if (data.data) {\n",
  1564. " // IPython >= 3 moved mimebundle to data attribute of output\n",
  1565. " data = data.data;\n",
  1566. " }\n",
  1567. " if (data['text/html'] == html_output) {\n",
  1568. " return [cell, data, j];\n",
  1569. " }\n",
  1570. " }\n",
  1571. " }\n",
  1572. " }\n",
  1573. "}\n",
  1574. "\n",
  1575. "// Register the function which deals with the matplotlib target/channel.\n",
  1576. "// The kernel may be null if the page has been refreshed.\n",
  1577. "if (IPython.notebook.kernel != null) {\n",
  1578. " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n",
  1579. "}\n"
  1580. ],
  1581. "text/plain": [
  1582. "<IPython.core.display.Javascript object>"
  1583. ]
  1584. },
  1585. "metadata": {},
  1586. "output_type": "display_data"
  1587. },
  1588. {
  1589. "data": {
  1590. "text/html": [
  1591. "<img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA4QAAAMgCAYAAAB7w6zDAAAgAElEQVR4nOzde5hVdb348TWDwMAMAhY3QbHIvIemJy9pWCZ4Nz3mpTKsSBM7qcej9XQq8PESdNG0c9KyxEseb6GIaSQdwfKSUWCSl6OmIamJaaAgIDKf3x/+ZjebmYEZhO+wvvN6Pc/3eWTtNWt/Z/Ze2/WevWbtIgAAAOiSis6eAAAAAJ1DEAIAAHRRghAAAKCLEoQAAABdlCAEAADoogQhAABAFyUIAQAAuihBCAAA0EUJQgAAgC5KEAIAAHRRghAAAKCLEoQAAABdlCAEAADoogQhAABAFyUIAQAAuihBCAAA0EUJQgAAgC5KEAIAAHRRghAAAKCLEoQAAABdlCAEAADoogQhAABAFyUIAQAAuihBCAAA0EUJQgAAgC5KEAIAAHRRghAAAKCLEoQAAABdlCAEAADoogQhAABAFyUIAQAAuihBCAAA0EUJQgAAgC5KEAIAAHRRghAAAKCLEoQAAABdlCAEAADoogQhAABAFyUIAQAAuihBCAAA0EUJQgAAgC5KEAIAAHRRghAAAKCLEoQAAABdlCAEAADoogQhAABAFyUIAQAAuihBCAAA0EUJQgAAgC5KEAIAAHRRghAAAKCLEoQAAABdlCAEAADoogQhAABAFyUIAQAAuihBCAAA0EUJQgAAgC5KEAIAAHRRghAAAKCLEoQAAABdlCAEAADoogQhAABAFyUIAQAAuihBCAAA0EUJQgAAgC5KEAIAAHRRghAAAKCLEoQAAABdlCAEAADoogQhAABAFyUIAQAAuihBCAAA0EUJQgAAgC5KEAIAAHRRghAAAKCLEoRQElOmTImiKCqjZ8+eMWjQoNh///3jwgsvjBdffLGzp9guw4cPj7Fjx3b2NEpj7NixMXz48PX62uuuuy4uvvjiDTuh/29jPo5Nz/Vnnnmmsqyt7+WZZ56Joiji29/+9nrd16xZs6Ioirj55ptbvf20006Loiiq5rWu0fR4TZgwIYqiiJqamvjzn//cYttLly6NPn36RFEUVT/Lt/M9jRo1KnbaaadWb3vppZeiKIqYMGFCZdma31O3bt1i8ODBcdxxx8UTTzzRoe2vj9Ye6/a64447qr6XDe3cc8+NHXbYIVavXh0RHXtc1ja3Cy64IG699dYNOdX1ctRRR8URRxxRtezll1+OzTbbLG655ZaIiCiKIk477bSNOo8bbrghdtxxx6irq4uiKGLevHmVfae5/fbbL04//fSNOhfoqgQhlETTgdOUKVPigQceiF//+tfxs5/9LM4444zo27dvbLHFFjFz5szOnuY6zZ07N5566qnOnkZpPPXUUzF37tz1+tpDDz10vWNyXTZmEC5atCgeeOCBWLFiRWVZW99LyiBsmlfzURRFHHPMMVXLmh6vpoPaPn36xNe+9rUW254yZUrU1dVF9+7dOz0Im15XZs2aFeeff3706tUrBg4cGK+88kq7t78+3k4QNn9sNrTnnnsu6uvrq54XHXlc1ja3+vr6Tv+l2NKlS6NXr15x9dVXVy2/8soro3fv3vH6669HxMYPwkWLFkX37t3j8MMPj9mzZ8cDDzwQy5Yti4ULF8YDDzxQte7s2bOje/fu8fjjj2+0+UBXJQihJJoOnObMmdPitgULFsRWW20Vffr0ib/97W+dMDs2RWUNwtZsCkHYmrUdMDcF4bhx42KrrbaqvNPUZN99940TTjihRSB0RhCu+bpy7rnnRlEUceWVV7Z7++tjUw3Cc845J4YOHVr1mOUUhDfddFN07969RfAfcsghccwxx1T+vbGD8N57742iKOLGG29s1/o777xzfP7zn99o84GuShBCSawtCCPe+h98URRx7rnnVi2/7bbbYq+99opevXpFQ0NDfPSjH43777+/ap2mA9c//vGPccwxx8Tmm28e/fv3jzPPPDNWrVoVjz/+eIwZMyYaGhpi+PDhMXny5KqvX758efz7v/97jBw5svK1e+21V0ybNq3FPNcMiaYD8v/5n/+Jr371qzFkyJDo06dPHHDAAS1+Ezx37tw49NBDY8CAAdGjR48YMmRIHHLIIbFw4cK1/uzuuuuuOOKII2Lo0KHRs2fPGDFiRJx88snx0ksvVa23aNGi+PznPx/Dhg2LHj16xDvf+c7YZ599qt55bc8cli9fHl/5yldim222ie7du8eWW24Z48ePj3/84x8t5nbdddfFXnvtFfX19VFfXx8jR46MH//4x5XbWztl9L/+679iv/32iwEDBkTv3r1j5513jsmTJ8cbb7xRWWfUqFGtns7YZOXKlXHeeefFdtttV/leTzrppFi0aFHVfb3xxhtx9tlnx6BBg6JXr17xwQ9+MB588MF2BeEee+wRhxxySNWynXfeOYqiiN/97neVZVOnTo2iKOLhhx+OiJaRsLbvpflB+ne/+93YZpttor6+Pvbaa68W7zC0JkUQ3n///VEURcyYMaNy2//93/9FURQxc+bMTTII77jjjiiKIr75zW+2e/vr8sADD8Q+++wTPXv2jCFDhsRXvvKV+NGPftQiCG+44YY48MADY/DgwVFXVxfbb799fPnLX46lS5dW1hk7dmyrz4mm7bRnH2nLypUr4x3veEecffbZVcvb+1xb29xaWz5q1KiI+Odjcdddd8VJJ50U/fv3j969e8dhhx3W4pTj9X0tbHLcccfFmDFjqpYtWbIkevToEddff31lWdPz+5prrontt98+evXqFe973/vi9ttvr/ra9rx2rqm1n1PTz6K1U0YjIiZPnhz19fXx6quvtuv7BNpHEEJJrCsIly5dGt26dYsDDjigsuy6666Loihi9OjRMW3atLjxxhtj9913jx49esRvfvObynpN//Pdbrvt4rzzzouZM2fGOeecE0VRxBe/+MXYfvvt49JLL42ZM2fGZz7zmSiKIqZOnVr5+sWLF8dJJ50U1157bdx9990xY8aM+I//+I+ora1tcUpSW0G4zTbbxCc/+cm444474vrrr4+tt946tt1223jzzTcr39873vGO2GOPPeKmm26Ke+65J2688cb4whe+EI8++uhaf3aXXXZZfPOb34zp06fHPffcE1dffXWMHDkytttuu6oDxDFjxsSAAQPiRz/6UcyePTumTZsW3/jGN+KGG25o9xwaGxtjzJgxsdlmm8XXv/71uOuuu+I73/lO1NfXx2677VZ1GuTXv/71KIoijj766Lj55pvjrrvuiosuuii+/vWvV9ZpLQjPPPPMuOyyy2LGjBlx9913x8UXXxzvfOc74zOf+UxlnUceeSQ++MEPxuDBg6tOZ4yIWL16dRx00EFRX18f5557bsycOTN+/OMfx9ChQ2PHHXesnC7WdP81NTVx9tlnV+Y3dOjQ2HzzzdcZhF/5yleioaGh8jP+29/+FkVRRK9eveKCCy6orHfqqafGoEGDKv9eMwjX9r00HWRvs802cdBBB8W0adNi2rRpscsuu0T//v1j8eLFa51j0/PvxhtvjFWrVrUY48ePf9tB+NJLL8V+++0Xxx57bOW2L3/5y7HNNttEY2PjJhmE//Vf/9ViP1/X9tfmkUceid69e8eOO+4Y119/fdx2220xZsyY2HrrrVsE4XnnnRcXX3xx3HHHHTF79uy4/PLL413veld8+MMfrqzz1FNPxTHHHBNFUVQ9J5r2r/bsI2359a9/HUVRxJ133lm1vL3PtbXN7YEHHohevXrFIYccUln+yCOPRMQ/H4utttoqPvvZz8YvfvGL+NGPfhQDBw6MrbbaqvILpfa+FjY9/2bNmlX1fSxfvjwaGhriRz/6UdXyn/70p9GzZ8+q2Gr6fj/wgQ/ETTfdFHfeeWfsv//+sdlmm1VF6rpeO1vz1FNPxX//939HURRx4YUXVv0s2grCBx98MIqiiOnTp7e5XaDjBCGUxLqCMCJi0KBBscMOO0TEWwf9W265Zeyyyy5Vpz299tprMXDgwNhnn30qy5r+5/vd7363anu77rprFEVRucBARMSqVatiwIABcfTRR7c5jzfffD
  1592. ],
  1593. "text/plain": [
  1594. "<IPython.core.display.HTML object>"
  1595. ]
  1596. },
  1597. "metadata": {},
  1598. "output_type": "display_data"
  1599. },
  1600. {
  1601. "name": "stdout",
  1602. "output_type": "stream",
  1603. "text": [
  1604. "Generating statistics: https://ts.fi\n"
  1605. ]
  1606. },
  1607. {
  1608. "data": {
  1609. "application/javascript": [
  1610. "/* Put everything inside the global mpl namespace */\n",
  1611. "window.mpl = {};\n",
  1612. "\n",
  1613. "\n",
  1614. "mpl.get_websocket_type = function() {\n",
  1615. " if (typeof(WebSocket) !== 'undefined') {\n",
  1616. " return WebSocket;\n",
  1617. " } else if (typeof(MozWebSocket) !== 'undefined') {\n",
  1618. " return MozWebSocket;\n",
  1619. " } else {\n",
  1620. " alert('Your browser does not have WebSocket support. ' +\n",
  1621. " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n",
  1622. " 'Firefox 4 and 5 are also supported but you ' +\n",
  1623. " 'have to enable WebSockets in about:config.');\n",
  1624. " };\n",
  1625. "}\n",
  1626. "\n",
  1627. "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n",
  1628. " this.id = figure_id;\n",
  1629. "\n",
  1630. " this.ws = websocket;\n",
  1631. "\n",
  1632. " this.supports_binary = (this.ws.binaryType != undefined);\n",
  1633. "\n",
  1634. " if (!this.supports_binary) {\n",
  1635. " var warnings = document.getElementById(\"mpl-warnings\");\n",
  1636. " if (warnings) {\n",
  1637. " warnings.style.display = 'block';\n",
  1638. " warnings.textContent = (\n",
  1639. " \"This browser does not support binary websocket messages. \" +\n",
  1640. " \"Performance may be slow.\");\n",
  1641. " }\n",
  1642. " }\n",
  1643. "\n",
  1644. " this.imageObj = new Image();\n",
  1645. "\n",
  1646. " this.context = undefined;\n",
  1647. " this.message = undefined;\n",
  1648. " this.canvas = undefined;\n",
  1649. " this.rubberband_canvas = undefined;\n",
  1650. " this.rubberband_context = undefined;\n",
  1651. " this.format_dropdown = undefined;\n",
  1652. "\n",
  1653. " this.image_mode = 'full';\n",
  1654. "\n",
  1655. " this.root = $('<div/>');\n",
  1656. " this._root_extra_style(this.root)\n",
  1657. " this.root.attr('style', 'display: inline-block');\n",
  1658. "\n",
  1659. " $(parent_element).append(this.root);\n",
  1660. "\n",
  1661. " this._init_header(this);\n",
  1662. " this._init_canvas(this);\n",
  1663. " this._init_toolbar(this);\n",
  1664. "\n",
  1665. " var fig = this;\n",
  1666. "\n",
  1667. " this.waiting = false;\n",
  1668. "\n",
  1669. " this.ws.onopen = function () {\n",
  1670. " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n",
  1671. " fig.send_message(\"send_image_mode\", {});\n",
  1672. " if (mpl.ratio != 1) {\n",
  1673. " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n",
  1674. " }\n",
  1675. " fig.send_message(\"refresh\", {});\n",
  1676. " }\n",
  1677. "\n",
  1678. " this.imageObj.onload = function() {\n",
  1679. " if (fig.image_mode == 'full') {\n",
  1680. " // Full images could contain transparency (where diff images\n",
  1681. " // almost always do), so we need to clear the canvas so that\n",
  1682. " // there is no ghosting.\n",
  1683. " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n",
  1684. " }\n",
  1685. " fig.context.drawImage(fig.imageObj, 0, 0);\n",
  1686. " };\n",
  1687. "\n",
  1688. " this.imageObj.onunload = function() {\n",
  1689. " fig.ws.close();\n",
  1690. " }\n",
  1691. "\n",
  1692. " this.ws.onmessage = this._make_on_message_function(this);\n",
  1693. "\n",
  1694. " this.ondownload = ondownload;\n",
  1695. "}\n",
  1696. "\n",
  1697. "mpl.figure.prototype._init_header = function() {\n",
  1698. " var titlebar = $(\n",
  1699. " '<div class=\"ui-dialog-titlebar ui-widget-header ui-corner-all ' +\n",
  1700. " 'ui-helper-clearfix\"/>');\n",
  1701. " var titletext = $(\n",
  1702. " '<div class=\"ui-dialog-title\" style=\"width: 100%; ' +\n",
  1703. " 'text-align: center; padding: 3px;\"/>');\n",
  1704. " titlebar.append(titletext)\n",
  1705. " this.root.append(titlebar);\n",
  1706. " this.header = titletext[0];\n",
  1707. "}\n",
  1708. "\n",
  1709. "\n",
  1710. "\n",
  1711. "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n",
  1712. "\n",
  1713. "}\n",
  1714. "\n",
  1715. "\n",
  1716. "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n",
  1717. "\n",
  1718. "}\n",
  1719. "\n",
  1720. "mpl.figure.prototype._init_canvas = function() {\n",
  1721. " var fig = this;\n",
  1722. "\n",
  1723. " var canvas_div = $('<div/>');\n",
  1724. "\n",
  1725. " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n",
  1726. "\n",
  1727. " function canvas_keyboard_event(event) {\n",
  1728. " return fig.key_event(event, event['data']);\n",
  1729. " }\n",
  1730. "\n",
  1731. " canvas_div.keydown('key_press', canvas_keyboard_event);\n",
  1732. " canvas_div.keyup('key_release', canvas_keyboard_event);\n",
  1733. " this.canvas_div = canvas_div\n",
  1734. " this._canvas_extra_style(canvas_div)\n",
  1735. " this.root.append(canvas_div);\n",
  1736. "\n",
  1737. " var canvas = $('<canvas/>');\n",
  1738. " canvas.addClass('mpl-canvas');\n",
  1739. " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n",
  1740. "\n",
  1741. " this.canvas = canvas[0];\n",
  1742. " this.context = canvas[0].getContext(\"2d\");\n",
  1743. "\n",
  1744. " var backingStore = this.context.backingStorePixelRatio ||\n",
  1745. "\tthis.context.webkitBackingStorePixelRatio ||\n",
  1746. "\tthis.context.mozBackingStorePixelRatio ||\n",
  1747. "\tthis.context.msBackingStorePixelRatio ||\n",
  1748. "\tthis.context.oBackingStorePixelRatio ||\n",
  1749. "\tthis.context.backingStorePixelRatio || 1;\n",
  1750. "\n",
  1751. " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n",
  1752. "\n",
  1753. " var rubberband = $('<canvas/>');\n",
  1754. " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n",
  1755. "\n",
  1756. " var pass_mouse_events = true;\n",
  1757. "\n",
  1758. " canvas_div.resizable({\n",
  1759. " start: function(event, ui) {\n",
  1760. " pass_mouse_events = false;\n",
  1761. " },\n",
  1762. " resize: function(event, ui) {\n",
  1763. " fig.request_resize(ui.size.width, ui.size.height);\n",
  1764. " },\n",
  1765. " stop: function(event, ui) {\n",
  1766. " pass_mouse_events = true;\n",
  1767. " fig.request_resize(ui.size.width, ui.size.height);\n",
  1768. " },\n",
  1769. " });\n",
  1770. "\n",
  1771. " function mouse_event_fn(event) {\n",
  1772. " if (pass_mouse_events)\n",
  1773. " return fig.mouse_event(event, event['data']);\n",
  1774. " }\n",
  1775. "\n",
  1776. " rubberband.mousedown('button_press', mouse_event_fn);\n",
  1777. " rubberband.mouseup('button_release', mouse_event_fn);\n",
  1778. " // Throttle sequential mouse events to 1 every 20ms.\n",
  1779. " rubberband.mousemove('motion_notify', mouse_event_fn);\n",
  1780. "\n",
  1781. " rubberband.mouseenter('figure_enter', mouse_event_fn);\n",
  1782. " rubberband.mouseleave('figure_leave', mouse_event_fn);\n",
  1783. "\n",
  1784. " canvas_div.on(\"wheel\", function (event) {\n",
  1785. " event = event.originalEvent;\n",
  1786. " event['data'] = 'scroll'\n",
  1787. " if (event.deltaY < 0) {\n",
  1788. " event.step = 1;\n",
  1789. " } else {\n",
  1790. " event.step = -1;\n",
  1791. " }\n",
  1792. " mouse_event_fn(event);\n",
  1793. " });\n",
  1794. "\n",
  1795. " canvas_div.append(canvas);\n",
  1796. " canvas_div.append(rubberband);\n",
  1797. "\n",
  1798. " this.rubberband = rubberband;\n",
  1799. " this.rubberband_canvas = rubberband[0];\n",
  1800. " this.rubberband_context = rubberband[0].getContext(\"2d\");\n",
  1801. " this.rubberband_context.strokeStyle = \"#000000\";\n",
  1802. "\n",
  1803. " this._resize_canvas = function(width, height) {\n",
  1804. " // Keep the size of the canvas, canvas container, and rubber band\n",
  1805. " // canvas in synch.\n",
  1806. " canvas_div.css('width', width)\n",
  1807. " canvas_div.css('height', height)\n",
  1808. "\n",
  1809. " canvas.attr('width', width * mpl.ratio);\n",
  1810. " canvas.attr('height', height * mpl.ratio);\n",
  1811. " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n",
  1812. "\n",
  1813. " rubberband.attr('width', width);\n",
  1814. " rubberband.attr('height', height);\n",
  1815. " }\n",
  1816. "\n",
  1817. " // Set the figure to an initial 600x600px, this will subsequently be updated\n",
  1818. " // upon first draw.\n",
  1819. " this._resize_canvas(600, 600);\n",
  1820. "\n",
  1821. " // Disable right mouse context menu.\n",
  1822. " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n",
  1823. " return false;\n",
  1824. " });\n",
  1825. "\n",
  1826. " function set_focus () {\n",
  1827. " canvas.focus();\n",
  1828. " canvas_div.focus();\n",
  1829. " }\n",
  1830. "\n",
  1831. " window.setTimeout(set_focus, 100);\n",
  1832. "}\n",
  1833. "\n",
  1834. "mpl.figure.prototype._init_toolbar = function() {\n",
  1835. " var fig = this;\n",
  1836. "\n",
  1837. " var nav_element = $('<div/>');\n",
  1838. " nav_element.attr('style', 'width: 100%');\n",
  1839. " this.root.append(nav_element);\n",
  1840. "\n",
  1841. " // Define a callback function for later on.\n",
  1842. " function toolbar_event(event) {\n",
  1843. " return fig.toolbar_button_onclick(event['data']);\n",
  1844. " }\n",
  1845. " function toolbar_mouse_event(event) {\n",
  1846. " return fig.toolbar_button_onmouseover(event['data']);\n",
  1847. " }\n",
  1848. "\n",
  1849. " for(var toolbar_ind in mpl.toolbar_items) {\n",
  1850. " var name = mpl.toolbar_items[toolbar_ind][0];\n",
  1851. " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n",
  1852. " var image = mpl.toolbar_items[toolbar_ind][2];\n",
  1853. " var method_name = mpl.toolbar_items[toolbar_ind][3];\n",
  1854. "\n",
  1855. " if (!name) {\n",
  1856. " // put a spacer in here.\n",
  1857. " continue;\n",
  1858. " }\n",
  1859. " var button = $('<button/>');\n",
  1860. " button.addClass('ui-button ui-widget ui-state-default ui-corner-all ' +\n",
  1861. " 'ui-button-icon-only');\n",
  1862. " button.attr('role', 'button');\n",
  1863. " button.attr('aria-disabled', 'false');\n",
  1864. " button.click(method_name, toolbar_event);\n",
  1865. " button.mouseover(tooltip, toolbar_mouse_event);\n",
  1866. "\n",
  1867. " var icon_img = $('<span/>');\n",
  1868. " icon_img.addClass('ui-button-icon-primary ui-icon');\n",
  1869. " icon_img.addClass(image);\n",
  1870. " icon_img.addClass('ui-corner-all');\n",
  1871. "\n",
  1872. " var tooltip_span = $('<span/>');\n",
  1873. " tooltip_span.addClass('ui-button-text');\n",
  1874. " tooltip_span.html(tooltip);\n",
  1875. "\n",
  1876. " button.append(icon_img);\n",
  1877. " button.append(tooltip_span);\n",
  1878. "\n",
  1879. " nav_element.append(button);\n",
  1880. " }\n",
  1881. "\n",
  1882. " var fmt_picker_span = $('<span/>');\n",
  1883. "\n",
  1884. " var fmt_picker = $('<select/>');\n",
  1885. " fmt_picker.addClass('mpl-toolbar-option ui-widget ui-widget-content');\n",
  1886. " fmt_picker_span.append(fmt_picker);\n",
  1887. " nav_element.append(fmt_picker_span);\n",
  1888. " this.format_dropdown = fmt_picker[0];\n",
  1889. "\n",
  1890. " for (var ind in mpl.extensions) {\n",
  1891. " var fmt = mpl.extensions[ind];\n",
  1892. " var option = $(\n",
  1893. " '<option/>', {selected: fmt === mpl.default_extension}).html(fmt);\n",
  1894. " fmt_picker.append(option);\n",
  1895. " }\n",
  1896. "\n",
  1897. " // Add hover states to the ui-buttons\n",
  1898. " $( \".ui-button\" ).hover(\n",
  1899. " function() { $(this).addClass(\"ui-state-hover\");},\n",
  1900. " function() { $(this).removeClass(\"ui-state-hover\");}\n",
  1901. " );\n",
  1902. "\n",
  1903. " var status_bar = $('<span class=\"mpl-message\"/>');\n",
  1904. " nav_element.append(status_bar);\n",
  1905. " this.message = status_bar[0];\n",
  1906. "}\n",
  1907. "\n",
  1908. "mpl.figure.prototype.request_resize = function(x_pixels, y_pixels) {\n",
  1909. " // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n",
  1910. " // which will in turn request a refresh of the image.\n",
  1911. " this.send_message('resize', {'width': x_pixels, 'height': y_pixels});\n",
  1912. "}\n",
  1913. "\n",
  1914. "mpl.figure.prototype.send_message = function(type, properties) {\n",
  1915. " properties['type'] = type;\n",
  1916. " properties['figure_id'] = this.id;\n",
  1917. " this.ws.send(JSON.stringify(properties));\n",
  1918. "}\n",
  1919. "\n",
  1920. "mpl.figure.prototype.send_draw_message = function() {\n",
  1921. " if (!this.waiting) {\n",
  1922. " this.waiting = true;\n",
  1923. " this.ws.send(JSON.stringify({type: \"draw\", figure_id: this.id}));\n",
  1924. " }\n",
  1925. "}\n",
  1926. "\n",
  1927. "\n",
  1928. "mpl.figure.prototype.handle_save = function(fig, msg) {\n",
  1929. " var format_dropdown = fig.format_dropdown;\n",
  1930. " var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n",
  1931. " fig.ondownload(fig, format);\n",
  1932. "}\n",
  1933. "\n",
  1934. "\n",
  1935. "mpl.figure.prototype.handle_resize = function(fig, msg) {\n",
  1936. " var size = msg['size'];\n",
  1937. " if (size[0] != fig.canvas.width || size[1] != fig.canvas.height) {\n",
  1938. " fig._resize_canvas(size[0], size[1]);\n",
  1939. " fig.send_message(\"refresh\", {});\n",
  1940. " };\n",
  1941. "}\n",
  1942. "\n",
  1943. "mpl.figure.prototype.handle_rubberband = function(fig, msg) {\n",
  1944. " var x0 = msg['x0'] / mpl.ratio;\n",
  1945. " var y0 = (fig.canvas.height - msg['y0']) / mpl.ratio;\n",
  1946. " var x1 = msg['x1'] / mpl.ratio;\n",
  1947. " var y1 = (fig.canvas.height - msg['y1']) / mpl.ratio;\n",
  1948. " x0 = Math.floor(x0) + 0.5;\n",
  1949. " y0 = Math.floor(y0) + 0.5;\n",
  1950. " x1 = Math.floor(x1) + 0.5;\n",
  1951. " y1 = Math.floor(y1) + 0.5;\n",
  1952. " var min_x = Math.min(x0, x1);\n",
  1953. " var min_y = Math.min(y0, y1);\n",
  1954. " var width = Math.abs(x1 - x0);\n",
  1955. " var height = Math.abs(y1 - y0);\n",
  1956. "\n",
  1957. " fig.rubberband_context.clearRect(\n",
  1958. " 0, 0, fig.canvas.width / mpl.ratio, fig.canvas.height / mpl.ratio);\n",
  1959. "\n",
  1960. " fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n",
  1961. "}\n",
  1962. "\n",
  1963. "mpl.figure.prototype.handle_figure_label = function(fig, msg) {\n",
  1964. " // Updates the figure title.\n",
  1965. " fig.header.textContent = msg['label'];\n",
  1966. "}\n",
  1967. "\n",
  1968. "mpl.figure.prototype.handle_cursor = function(fig, msg) {\n",
  1969. " var cursor = msg['cursor'];\n",
  1970. " switch(cursor)\n",
  1971. " {\n",
  1972. " case 0:\n",
  1973. " cursor = 'pointer';\n",
  1974. " break;\n",
  1975. " case 1:\n",
  1976. " cursor = 'default';\n",
  1977. " break;\n",
  1978. " case 2:\n",
  1979. " cursor = 'crosshair';\n",
  1980. " break;\n",
  1981. " case 3:\n",
  1982. " cursor = 'move';\n",
  1983. " break;\n",
  1984. " }\n",
  1985. " fig.rubberband_canvas.style.cursor = cursor;\n",
  1986. "}\n",
  1987. "\n",
  1988. "mpl.figure.prototype.handle_message = function(fig, msg) {\n",
  1989. " fig.message.textContent = msg['message'];\n",
  1990. "}\n",
  1991. "\n",
  1992. "mpl.figure.prototype.handle_draw = function(fig, msg) {\n",
  1993. " // Request the server to send over a new figure.\n",
  1994. " fig.send_draw_message();\n",
  1995. "}\n",
  1996. "\n",
  1997. "mpl.figure.prototype.handle_image_mode = function(fig, msg) {\n",
  1998. " fig.image_mode = msg['mode'];\n",
  1999. "}\n",
  2000. "\n",
  2001. "mpl.figure.prototype.updated_canvas_event = function() {\n",
  2002. " // Called whenever the canvas gets updated.\n",
  2003. " this.send_message(\"ack\", {});\n",
  2004. "}\n",
  2005. "\n",
  2006. "// A function to construct a web socket function for onmessage handling.\n",
  2007. "// Called in the figure constructor.\n",
  2008. "mpl.figure.prototype._make_on_message_function = function(fig) {\n",
  2009. " return function socket_on_message(evt) {\n",
  2010. " if (evt.data instanceof Blob) {\n",
  2011. " /* FIXME: We get \"Resource interpreted as Image but\n",
  2012. " * transferred with MIME type text/plain:\" errors on\n",
  2013. " * Chrome. But how to set the MIME type? It doesn't seem\n",
  2014. " * to be part of the websocket stream */\n",
  2015. " evt.data.type = \"image/png\";\n",
  2016. "\n",
  2017. " /* Free the memory for the previous frames */\n",
  2018. " if (fig.imageObj.src) {\n",
  2019. " (window.URL || window.webkitURL).revokeObjectURL(\n",
  2020. " fig.imageObj.src);\n",
  2021. " }\n",
  2022. "\n",
  2023. " fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n",
  2024. " evt.data);\n",
  2025. " fig.updated_canvas_event();\n",
  2026. " fig.waiting = false;\n",
  2027. " return;\n",
  2028. " }\n",
  2029. " else if (typeof evt.data === 'string' && evt.data.slice(0, 21) == \"data:image/png;base64\") {\n",
  2030. " fig.imageObj.src = evt.data;\n",
  2031. " fig.updated_canvas_event();\n",
  2032. " fig.waiting = false;\n",
  2033. " return;\n",
  2034. " }\n",
  2035. "\n",
  2036. " var msg = JSON.parse(evt.data);\n",
  2037. " var msg_type = msg['type'];\n",
  2038. "\n",
  2039. " // Call the \"handle_{type}\" callback, which takes\n",
  2040. " // the figure and JSON message as its only arguments.\n",
  2041. " try {\n",
  2042. " var callback = fig[\"handle_\" + msg_type];\n",
  2043. " } catch (e) {\n",
  2044. " console.log(\"No handler for the '\" + msg_type + \"' message type: \", msg);\n",
  2045. " return;\n",
  2046. " }\n",
  2047. "\n",
  2048. " if (callback) {\n",
  2049. " try {\n",
  2050. " // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n",
  2051. " callback(fig, msg);\n",
  2052. " } catch (e) {\n",
  2053. " console.log(\"Exception inside the 'handler_\" + msg_type + \"' callback:\", e, e.stack, msg);\n",
  2054. " }\n",
  2055. " }\n",
  2056. " };\n",
  2057. "}\n",
  2058. "\n",
  2059. "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n",
  2060. "mpl.findpos = function(e) {\n",
  2061. " //this section is from http://www.quirksmode.org/js/events_properties.html\n",
  2062. " var targ;\n",
  2063. " if (!e)\n",
  2064. " e = window.event;\n",
  2065. " if (e.target)\n",
  2066. " targ = e.target;\n",
  2067. " else if (e.srcElement)\n",
  2068. " targ = e.srcElement;\n",
  2069. " if (targ.nodeType == 3) // defeat Safari bug\n",
  2070. " targ = targ.parentNode;\n",
  2071. "\n",
  2072. " // jQuery normalizes the pageX and pageY\n",
  2073. " // pageX,Y are the mouse positions relative to the document\n",
  2074. " // offset() returns the position of the element relative to the document\n",
  2075. " var x = e.pageX - $(targ).offset().left;\n",
  2076. " var y = e.pageY - $(targ).offset().top;\n",
  2077. "\n",
  2078. " return {\"x\": x, \"y\": y};\n",
  2079. "};\n",
  2080. "\n",
  2081. "/*\n",
  2082. " * return a copy of an object with only non-object keys\n",
  2083. " * we need this to avoid circular references\n",
  2084. " * http://stackoverflow.com/a/24161582/3208463\n",
  2085. " */\n",
  2086. "function simpleKeys (original) {\n",
  2087. " return Object.keys(original).reduce(function (obj, key) {\n",
  2088. " if (typeof original[key] !== 'object')\n",
  2089. " obj[key] = original[key]\n",
  2090. " return obj;\n",
  2091. " }, {});\n",
  2092. "}\n",
  2093. "\n",
  2094. "mpl.figure.prototype.mouse_event = function(event, name) {\n",
  2095. " var canvas_pos = mpl.findpos(event)\n",
  2096. "\n",
  2097. " if (name === 'button_press')\n",
  2098. " {\n",
  2099. " this.canvas.focus();\n",
  2100. " this.canvas_div.focus();\n",
  2101. " }\n",
  2102. "\n",
  2103. " var x = canvas_pos.x * mpl.ratio;\n",
  2104. " var y = canvas_pos.y * mpl.ratio;\n",
  2105. "\n",
  2106. " this.send_message(name, {x: x, y: y, button: event.button,\n",
  2107. " step: event.step,\n",
  2108. " guiEvent: simpleKeys(event)});\n",
  2109. "\n",
  2110. " /* This prevents the web browser from automatically changing to\n",
  2111. " * the text insertion cursor when the button is pressed. We want\n",
  2112. " * to control all of the cursor setting manually through the\n",
  2113. " * 'cursor' event from matplotlib */\n",
  2114. " event.preventDefault();\n",
  2115. " return false;\n",
  2116. "}\n",
  2117. "\n",
  2118. "mpl.figure.prototype._key_event_extra = function(event, name) {\n",
  2119. " // Handle any extra behaviour associated with a key event\n",
  2120. "}\n",
  2121. "\n",
  2122. "mpl.figure.prototype.key_event = function(event, name) {\n",
  2123. "\n",
  2124. " // Prevent repeat events\n",
  2125. " if (name == 'key_press')\n",
  2126. " {\n",
  2127. " if (event.which === this._key)\n",
  2128. " return;\n",
  2129. " else\n",
  2130. " this._key = event.which;\n",
  2131. " }\n",
  2132. " if (name == 'key_release')\n",
  2133. " this._key = null;\n",
  2134. "\n",
  2135. " var value = '';\n",
  2136. " if (event.ctrlKey && event.which != 17)\n",
  2137. " value += \"ctrl+\";\n",
  2138. " if (event.altKey && event.which != 18)\n",
  2139. " value += \"alt+\";\n",
  2140. " if (event.shiftKey && event.which != 16)\n",
  2141. " value += \"shift+\";\n",
  2142. "\n",
  2143. " value += 'k';\n",
  2144. " value += event.which.toString();\n",
  2145. "\n",
  2146. " this._key_event_extra(event, name);\n",
  2147. "\n",
  2148. " this.send_message(name, {key: value,\n",
  2149. " guiEvent: simpleKeys(event)});\n",
  2150. " return false;\n",
  2151. "}\n",
  2152. "\n",
  2153. "mpl.figure.prototype.toolbar_button_onclick = function(name) {\n",
  2154. " if (name == 'download') {\n",
  2155. " this.handle_save(this, null);\n",
  2156. " } else {\n",
  2157. " this.send_message(\"toolbar_button\", {name: name});\n",
  2158. " }\n",
  2159. "};\n",
  2160. "\n",
  2161. "mpl.figure.prototype.toolbar_button_onmouseover = function(tooltip) {\n",
  2162. " this.message.textContent = tooltip;\n",
  2163. "};\n",
  2164. "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Pan axes with left mouse, zoom with right\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n",
  2165. "\n",
  2166. "mpl.extensions = [\"eps\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\"];\n",
  2167. "\n",
  2168. "mpl.default_extension = \"png\";var comm_websocket_adapter = function(comm) {\n",
  2169. " // Create a \"websocket\"-like object which calls the given IPython comm\n",
  2170. " // object with the appropriate methods. Currently this is a non binary\n",
  2171. " // socket, so there is still some room for performance tuning.\n",
  2172. " var ws = {};\n",
  2173. "\n",
  2174. " ws.close = function() {\n",
  2175. " comm.close()\n",
  2176. " };\n",
  2177. " ws.send = function(m) {\n",
  2178. " //console.log('sending', m);\n",
  2179. " comm.send(m);\n",
  2180. " };\n",
  2181. " // Register the callback with on_msg.\n",
  2182. " comm.on_msg(function(msg) {\n",
  2183. " //console.log('receiving', msg['content']['data'], msg);\n",
  2184. " // Pass the mpl event to the overridden (by mpl) onmessage function.\n",
  2185. " ws.onmessage(msg['content']['data'])\n",
  2186. " });\n",
  2187. " return ws;\n",
  2188. "}\n",
  2189. "\n",
  2190. "mpl.mpl_figure_comm = function(comm, msg) {\n",
  2191. " // This is the function which gets called when the mpl process\n",
  2192. " // starts-up an IPython Comm through the \"matplotlib\" channel.\n",
  2193. "\n",
  2194. " var id = msg.content.data.id;\n",
  2195. " // Get hold of the div created by the display call when the Comm\n",
  2196. " // socket was opened in Python.\n",
  2197. " var element = $(\"#\" + id);\n",
  2198. " var ws_proxy = comm_websocket_adapter(comm)\n",
  2199. "\n",
  2200. " function ondownload(figure, format) {\n",
  2201. " window.open(figure.imageObj.src);\n",
  2202. " }\n",
  2203. "\n",
  2204. " var fig = new mpl.figure(id, ws_proxy,\n",
  2205. " ondownload,\n",
  2206. " element.get(0));\n",
  2207. "\n",
  2208. " // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n",
  2209. " // web socket which is closed, not our websocket->open comm proxy.\n",
  2210. " ws_proxy.onopen();\n",
  2211. "\n",
  2212. " fig.parent_element = element.get(0);\n",
  2213. " fig.cell_info = mpl.find_output_cell(\"<div id='\" + id + \"'></div>\");\n",
  2214. " if (!fig.cell_info) {\n",
  2215. " console.error(\"Failed to find cell for figure\", id, fig);\n",
  2216. " return;\n",
  2217. " }\n",
  2218. "\n",
  2219. " var output_index = fig.cell_info[2]\n",
  2220. " var cell = fig.cell_info[0];\n",
  2221. "\n",
  2222. "};\n",
  2223. "\n",
  2224. "mpl.figure.prototype.handle_close = function(fig, msg) {\n",
  2225. " var width = fig.canvas.width/mpl.ratio\n",
  2226. " fig.root.unbind('remove')\n",
  2227. "\n",
  2228. " // Update the output cell to use the data from the current canvas.\n",
  2229. " fig.push_to_output();\n",
  2230. " var dataURL = fig.canvas.toDataURL();\n",
  2231. " // Re-enable the keyboard manager in IPython - without this line, in FF,\n",
  2232. " // the notebook keyboard shortcuts fail.\n",
  2233. " IPython.keyboard_manager.enable()\n",
  2234. " $(fig.parent_element).html('<img src=\"' + dataURL + '\" width=\"' + width + '\">');\n",
  2235. " fig.close_ws(fig, msg);\n",
  2236. "}\n",
  2237. "\n",
  2238. "mpl.figure.prototype.close_ws = function(fig, msg){\n",
  2239. " fig.send_message('closing', msg);\n",
  2240. " // fig.ws.close()\n",
  2241. "}\n",
  2242. "\n",
  2243. "mpl.figure.prototype.push_to_output = function(remove_interactive) {\n",
  2244. " // Turn the data on the canvas into data in the output cell.\n",
  2245. " var width = this.canvas.width/mpl.ratio\n",
  2246. " var dataURL = this.canvas.toDataURL();\n",
  2247. " this.cell_info[1]['text/html'] = '<img src=\"' + dataURL + '\" width=\"' + width + '\">';\n",
  2248. "}\n",
  2249. "\n",
  2250. "mpl.figure.prototype.updated_canvas_event = function() {\n",
  2251. " // Tell IPython that the notebook contents must change.\n",
  2252. " IPython.notebook.set_dirty(true);\n",
  2253. " this.send_message(\"ack\", {});\n",
  2254. " var fig = this;\n",
  2255. " // Wait a second, then push the new image to the DOM so\n",
  2256. " // that it is saved nicely (might be nice to debounce this).\n",
  2257. " setTimeout(function () { fig.push_to_output() }, 1000);\n",
  2258. "}\n",
  2259. "\n",
  2260. "mpl.figure.prototype._init_toolbar = function() {\n",
  2261. " var fig = this;\n",
  2262. "\n",
  2263. " var nav_element = $('<div/>');\n",
  2264. " nav_element.attr('style', 'width: 100%');\n",
  2265. " this.root.append(nav_element);\n",
  2266. "\n",
  2267. " // Define a callback function for later on.\n",
  2268. " function toolbar_event(event) {\n",
  2269. " return fig.toolbar_button_onclick(event['data']);\n",
  2270. " }\n",
  2271. " function toolbar_mouse_event(event) {\n",
  2272. " return fig.toolbar_button_onmouseover(event['data']);\n",
  2273. " }\n",
  2274. "\n",
  2275. " for(var toolbar_ind in mpl.toolbar_items){\n",
  2276. " var name = mpl.toolbar_items[toolbar_ind][0];\n",
  2277. " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n",
  2278. " var image = mpl.toolbar_items[toolbar_ind][2];\n",
  2279. " var method_name = mpl.toolbar_items[toolbar_ind][3];\n",
  2280. "\n",
  2281. " if (!name) { continue; };\n",
  2282. "\n",
  2283. " var button = $('<button class=\"btn btn-default\" href=\"#\" title=\"' + name + '\"><i class=\"fa ' + image + ' fa-lg\"></i></button>');\n",
  2284. " button.click(method_name, toolbar_event);\n",
  2285. " button.mouseover(tooltip, toolbar_mouse_event);\n",
  2286. " nav_element.append(button);\n",
  2287. " }\n",
  2288. "\n",
  2289. " // Add the status bar.\n",
  2290. " var status_bar = $('<span class=\"mpl-message\" style=\"text-align:right; float: right;\"/>');\n",
  2291. " nav_element.append(status_bar);\n",
  2292. " this.message = status_bar[0];\n",
  2293. "\n",
  2294. " // Add the close button to the window.\n",
  2295. " var buttongrp = $('<div class=\"btn-group inline pull-right\"></div>');\n",
  2296. " var button = $('<button class=\"btn btn-mini btn-primary\" href=\"#\" title=\"Stop Interaction\"><i class=\"fa fa-power-off icon-remove icon-large\"></i></button>');\n",
  2297. " button.click(function (evt) { fig.handle_close(fig, {}); } );\n",
  2298. " button.mouseover('Stop Interaction', toolbar_mouse_event);\n",
  2299. " buttongrp.append(button);\n",
  2300. " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n",
  2301. " titlebar.prepend(buttongrp);\n",
  2302. "}\n",
  2303. "\n",
  2304. "mpl.figure.prototype._root_extra_style = function(el){\n",
  2305. " var fig = this\n",
  2306. " el.on(\"remove\", function(){\n",
  2307. "\tfig.close_ws(fig, {});\n",
  2308. " });\n",
  2309. "}\n",
  2310. "\n",
  2311. "mpl.figure.prototype._canvas_extra_style = function(el){\n",
  2312. " // this is important to make the div 'focusable\n",
  2313. " el.attr('tabindex', 0)\n",
  2314. " // reach out to IPython and tell the keyboard manager to turn it's self\n",
  2315. " // off when our div gets focus\n",
  2316. "\n",
  2317. " // location in version 3\n",
  2318. " if (IPython.notebook.keyboard_manager) {\n",
  2319. " IPython.notebook.keyboard_manager.register_events(el);\n",
  2320. " }\n",
  2321. " else {\n",
  2322. " // location in version 2\n",
  2323. " IPython.keyboard_manager.register_events(el);\n",
  2324. " }\n",
  2325. "\n",
  2326. "}\n",
  2327. "\n",
  2328. "mpl.figure.prototype._key_event_extra = function(event, name) {\n",
  2329. " var manager = IPython.notebook.keyboard_manager;\n",
  2330. " if (!manager)\n",
  2331. " manager = IPython.keyboard_manager;\n",
  2332. "\n",
  2333. " // Check for shift+enter\n",
  2334. " if (event.shiftKey && event.which == 13) {\n",
  2335. " this.canvas_div.blur();\n",
  2336. " // select the cell after this one\n",
  2337. " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n",
  2338. " IPython.notebook.select(index + 1);\n",
  2339. " }\n",
  2340. "}\n",
  2341. "\n",
  2342. "mpl.figure.prototype.handle_save = function(fig, msg) {\n",
  2343. " fig.ondownload(fig, null);\n",
  2344. "}\n",
  2345. "\n",
  2346. "\n",
  2347. "mpl.find_output_cell = function(html_output) {\n",
  2348. " // Return the cell and output element which can be found *uniquely* in the notebook.\n",
  2349. " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n",
  2350. " // IPython event is triggered only after the cells have been serialised, which for\n",
  2351. " // our purposes (turning an active figure into a static one), is too late.\n",
  2352. " var cells = IPython.notebook.get_cells();\n",
  2353. " var ncells = cells.length;\n",
  2354. " for (var i=0; i<ncells; i++) {\n",
  2355. " var cell = cells[i];\n",
  2356. " if (cell.cell_type === 'code'){\n",
  2357. " for (var j=0; j<cell.output_area.outputs.length; j++) {\n",
  2358. " var data = cell.output_area.outputs[j];\n",
  2359. " if (data.data) {\n",
  2360. " // IPython >= 3 moved mimebundle to data attribute of output\n",
  2361. " data = data.data;\n",
  2362. " }\n",
  2363. " if (data['text/html'] == html_output) {\n",
  2364. " return [cell, data, j];\n",
  2365. " }\n",
  2366. " }\n",
  2367. " }\n",
  2368. " }\n",
  2369. "}\n",
  2370. "\n",
  2371. "// Register the function which deals with the matplotlib target/channel.\n",
  2372. "// The kernel may be null if the page has been refreshed.\n",
  2373. "if (IPython.notebook.kernel != null) {\n",
  2374. " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n",
  2375. "}\n"
  2376. ],
  2377. "text/plain": [
  2378. "<IPython.core.display.Javascript object>"
  2379. ]
  2380. },
  2381. "metadata": {},
  2382. "output_type": "display_data"
  2383. },
  2384. {
  2385. "data": {
  2386. "text/html": [
  2387. "<img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA4QAAAMgCAYAAAB7w6zDAAAgAElEQVR4nOzde5Td873/8e9M5J6QIIkIkspSl9JQThvKiVZd6lKXoy5Vh5ZD0RbHcTlWNfyU1lG02oPSI65VVRUcGqJubd1SjnLcFZH2pyhN2mgSIe/fH36zmzEzyUxsn8nn83081nqt1e7MbN9kz853P2fv2akCAACAWqp6+wAAAADoHYIQAACgpgQhAABATQlCAACAmhKEAAAANSUIAQAAakoQAgAA1JQgBAAAqClBCAAAUFOCEAAAoKYEIQAAQE0JQgAAgJoShAAAADUlCAEAAGpKEAIAANSUIAQAAKgpQQgAAFBTghAAAKCmBCEAAEBNCUIAAICaEoQAAAA1JQgBAABqShACAADUlCAEAACoKUEIAABQU4IQAACgpgQhAABATQlCAACAmhKEAAAANSUIAQAAakoQAgAA1JQgBAAAqClBCAAAUFOCEAAAoKYEIQAAQE0JQgAAgJoShAAAADUlCAEAAGpKEAIAANSUIAQAAKgpQQgAAFBTghAAAKCmBCEAAEBNCUIAAICaEoQAAAA1JQgBAABqShACAADUlCAEAACoKUEIAABQU4IQAACgpgQhAABATQlCAACAmhKEAAAANSUIAQAAakoQAgAA1JQgBAAAqClBCAAAUFOCEAAAoKYEIQAAQE0JQgAAgJoShAAAADUlCAEAAGpKEAIAANSUIAQAAKgpQQgAAFBTghAAAKCmBCEAAEBNCUIAAICaEoQAAAA1JQgBAABqShACAADUlCAEAACoKUEIAABQU4IQAACgpgQhtfPnP/85JkyY0Ng666wTffr0iddee623Dw0AAJIShNTemWeeGTvvvHNvH0a3TZkyJaqqaqx///4xatSo2HrrreP000+Pl19+ubcPsVvGjh0bBxxwQG8fRjYOOOCAGDt27DJ97pVXXhnnnHNOcw/o/3s/b8e2r/Xnn3++cVlXv5fnn38+qqqKM888c5n+W3fccUdUVRXXXHNNp79+xBFHRFVV7Y5raWu7vSZPnhxVVUVLS0v87ne/63Ddc+fOjaFDh0ZVVe3+LN/L72nSpEnxoQ99qNNfe/XVV6Oqqpg8eXLjsnf/nvr06ROrrbZa7L333vH000/36PqXRWe3dXfddNNN7X4vzXbKKafE+uuvH2+//XZE9Ox2WdKxnXbaaXHdddc181CXye677x6f+cxn2l322muvxQorrBA/+9nPIuL9OdbbbrstNt100xg0aFBUVRXXXXddp18Hn//852PXXXdt6n8baE8QUnsbbLDBcnFS7q62E+aUKVPi3nvvjbvvvjt++tOfxlFHHRUrrbRSrLzyyjF9+vTePsyleuihh+LZZ5/t7cPIxrPPPhsPPfTQMn3uTjvttMwxuTTvZxC+8sorce+998b8+fMbl3X1e0kZhG3Htfiqqoo999yz3WVtt1dbEA4dOjS+9rWvdbjuKVOmxIABA6Jv3769HoRtf6/ccccd8Y1vfCMGDhwYI0eOjNdff73b178s3ksQLn7bNNsf/vCHGDx4cLuvi57cLks6tsGDB/f6N8Xmzp0bAwcOjEsvvbTd5RdffHEMGjQo/va3v0VE84910aJFsfLKK8fEiRPjtttui3vvvTdef/31Tu/zzz77bKywwgrxi1/8omn/faA9QUit3XPPPTFq1KhYuHBhbx9Kt7U9cJoxY0aHX5s5c2asueaaMXTo0PjjH//YC0fH8ijXIOzM8hCEnamqKo444ohOf60tCA8++OBYc801G880tdlyyy1j33337fCguzeC8N1/r5xyyilRVVVcfPHF3b7+ZbG8BuFxxx0XY8aMaXeblRSEP/nJT6Jv374dgn/HHXeMPffcs/H/m32sv//976OqqjjjjDO69fE777xzbLvttk377wPtCUJq7eCDD45jjz22tw+jR5YUhBHvnOCrqopTTjml3eXXX399TJw4MQYOHBhDhgyJT33qU3HPPfe0+5i2B66//e1vY88994wVV1wxhg8fHkcffXQsXLgwnnzyydh+++1jyJAhMXbs2A4n83nz5sW//uu/xoQJExqfO3HixJg6dWqH43x3SLQ9IP/Rj34UJ554YowePTqGDh0a22yzTTz55JPtPvehhx6KnXbaKUaMGBH9+vWL0aNHx4477hizZs1a4p/drbfeGp/5zGdizJgx0b9//xg/fnwccsgh8eqrr7b7uFdeeSX+5V/+JdZYY43o169frLrqqrHFFlu0e+a1O8cwb968OOGEE2LcuHHRt2/fWH311ePwww+PP//5zx2O7corr4yJEyfG4MGDY/DgwTFhwoT44Q9/2Pj1zl4y+v3vfz+22mqrGDFiRAwaNCg23HDDOOOMM+LNN99sfMykSZM6fTljmwULFsSpp54a6667buP3euCBB8Yrr7zS7r/15ptvxrHHHhujRo2KgQMHxsc//vG4//77uxWEm222Wey4447tLttwww2jqqp44IEHGpdde+21UVVVPPLIIxHRMRKW9HtZ/EH6WWedFePGjYvBgwfHxIkT4957713i8UWkCcJ77rknqqqKadOmNX7tqaeeiqqqYvr06ctlEN50001RVVV885vf7Pb1L829994bW2yxRfTv3z9Gjx4dJ5xwQlx44YUdgvDHP/5xbLvttrHaaqvFgAEDYr311ovjjz8+5s6d2/iYAw44oNOvibbr6c59pCsLFiyIVVZZpcM5ortfa0s6ts4unzRpUkT8/ba49dZb48ADD4zhw4fHoEGDYuedd+7wkuNl/buwzd577x3bb799u8vmzJkT/fr1i6uuuioiYonH+sYbb8QxxxwT48aNi/79+8fw4cNj0003jR/96Edd/jfb7g+dvby6q28MXH311dHS0uJVJfA+EYTUVtvP7TzxxBO9fSg9srQgnDt3bvTp0ye22WabxmVXXnllVFUV2223XUydOjWuvvrq2HTTTaNfv37xy1/+svFxbSfqddddN0499dSYPn16HHfccVFVVXz5y1+O9dZbL84999yYPn16fOELX4iqquLaa69tfP7s2bPjwAMPjMsvvzxuv/32mDZtWvzbv/1btLa2dnhJUldBOG7cuNhvv/3ipptuiquuuirWWmutWGeddeKtt95q/P5WWWWV2GyzzeInP/lJ3HXXXXH11VfHl770pXj88ceX+Gd3/vnnxze/+c244YYb4q677opLL700JkyYEOuuu267B4jbb799jBgxIi688MK48847Y+rUqfH1r389fvzjH3f7GBYtWhTbb799rLDCCnHSSSfFrbfeGt/+9rdj8ODBsckmm7R7SdRJJ50UVVXFHnvsEddcc03ceuutcfbZZ8dJJ53U+JjOgvDoo4+O888/P6ZNmxa33357nHPOObHqqqvGF77whcbHPPbYY/Hxj388VltttXYvZ4yIePvtt2OHHXaIwYMHxymnnBLTp0+PH/7whzFmzJjYYIMNGi8Xa/vvt7S0xLHHHts4vjFjxsSKK6641CA84YQTYsiQIY0/4z/+8Y9RVVUMHDgwTjvttMbHHXbYYTFq1KjG/3/3g8Ml/V7aHmSPGzcudthhh5g6dWpMnTo1Ntpooxg+fHjMnj17icfY9vV39dVXx8KFCzvs8MMPf89B+Oqrr8ZWW20Ve+21V+PXjj/++Bg3blwsWrRouQzC73//+x3u50u7/iV57LHHYtCgQbHBBhvEVVddFddff31sv/32sdZaa3UIgVNPPTXOOeecuOmmm+LOO++MCy64ID7wgQ/EJz7xicbHPPvss7HnnntGVVXtviba7l/duY905e67746qquLmm29ud3l3v9aWdGz33ntvDBw4MHbcccfG5Y899lhE/P22WHPNNeOLX/xi/PznP48LL7wwRo4cGWuuuWbjG0rd/buw7evvjjvuaPf7mDdvXgwZMiQuvPDCdpdfccUV0b9///jLX/4SEbHEYz300ENj0KBBcfbZZ8cdd9wR//3f/x3f+ta34nvf+16Xf66zZs2Kn/3sZ1FVVXzlK19p9/LqroLw5Zdfjqqq4t
  2388. ],
  2389. "text/plain": [
  2390. "<IPython.core.display.HTML object>"
  2391. ]
  2392. },
  2393. "metadata": {},
  2394. "output_type": "display_data"
  2395. },
  2396. {
  2397. "name": "stdout",
  2398. "output_type": "stream",
  2399. "text": [
  2400. "Generating statistics: https://facebook.com\n"
  2401. ]
  2402. },
  2403. {
  2404. "data": {
  2405. "application/javascript": [
  2406. "/* Put everything inside the global mpl namespace */\n",
  2407. "window.mpl = {};\n",
  2408. "\n",
  2409. "\n",
  2410. "mpl.get_websocket_type = function() {\n",
  2411. " if (typeof(WebSocket) !== 'undefined') {\n",
  2412. " return WebSocket;\n",
  2413. " } else if (typeof(MozWebSocket) !== 'undefined') {\n",
  2414. " return MozWebSocket;\n",
  2415. " } else {\n",
  2416. " alert('Your browser does not have WebSocket support. ' +\n",
  2417. " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n",
  2418. " 'Firefox 4 and 5 are also supported but you ' +\n",
  2419. " 'have to enable WebSockets in about:config.');\n",
  2420. " };\n",
  2421. "}\n",
  2422. "\n",
  2423. "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n",
  2424. " this.id = figure_id;\n",
  2425. "\n",
  2426. " this.ws = websocket;\n",
  2427. "\n",
  2428. " this.supports_binary = (this.ws.binaryType != undefined);\n",
  2429. "\n",
  2430. " if (!this.supports_binary) {\n",
  2431. " var warnings = document.getElementById(\"mpl-warnings\");\n",
  2432. " if (warnings) {\n",
  2433. " warnings.style.display = 'block';\n",
  2434. " warnings.textContent = (\n",
  2435. " \"This browser does not support binary websocket messages. \" +\n",
  2436. " \"Performance may be slow.\");\n",
  2437. " }\n",
  2438. " }\n",
  2439. "\n",
  2440. " this.imageObj = new Image();\n",
  2441. "\n",
  2442. " this.context = undefined;\n",
  2443. " this.message = undefined;\n",
  2444. " this.canvas = undefined;\n",
  2445. " this.rubberband_canvas = undefined;\n",
  2446. " this.rubberband_context = undefined;\n",
  2447. " this.format_dropdown = undefined;\n",
  2448. "\n",
  2449. " this.image_mode = 'full';\n",
  2450. "\n",
  2451. " this.root = $('<div/>');\n",
  2452. " this._root_extra_style(this.root)\n",
  2453. " this.root.attr('style', 'display: inline-block');\n",
  2454. "\n",
  2455. " $(parent_element).append(this.root);\n",
  2456. "\n",
  2457. " this._init_header(this);\n",
  2458. " this._init_canvas(this);\n",
  2459. " this._init_toolbar(this);\n",
  2460. "\n",
  2461. " var fig = this;\n",
  2462. "\n",
  2463. " this.waiting = false;\n",
  2464. "\n",
  2465. " this.ws.onopen = function () {\n",
  2466. " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n",
  2467. " fig.send_message(\"send_image_mode\", {});\n",
  2468. " if (mpl.ratio != 1) {\n",
  2469. " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n",
  2470. " }\n",
  2471. " fig.send_message(\"refresh\", {});\n",
  2472. " }\n",
  2473. "\n",
  2474. " this.imageObj.onload = function() {\n",
  2475. " if (fig.image_mode == 'full') {\n",
  2476. " // Full images could contain transparency (where diff images\n",
  2477. " // almost always do), so we need to clear the canvas so that\n",
  2478. " // there is no ghosting.\n",
  2479. " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n",
  2480. " }\n",
  2481. " fig.context.drawImage(fig.imageObj, 0, 0);\n",
  2482. " };\n",
  2483. "\n",
  2484. " this.imageObj.onunload = function() {\n",
  2485. " fig.ws.close();\n",
  2486. " }\n",
  2487. "\n",
  2488. " this.ws.onmessage = this._make_on_message_function(this);\n",
  2489. "\n",
  2490. " this.ondownload = ondownload;\n",
  2491. "}\n",
  2492. "\n",
  2493. "mpl.figure.prototype._init_header = function() {\n",
  2494. " var titlebar = $(\n",
  2495. " '<div class=\"ui-dialog-titlebar ui-widget-header ui-corner-all ' +\n",
  2496. " 'ui-helper-clearfix\"/>');\n",
  2497. " var titletext = $(\n",
  2498. " '<div class=\"ui-dialog-title\" style=\"width: 100%; ' +\n",
  2499. " 'text-align: center; padding: 3px;\"/>');\n",
  2500. " titlebar.append(titletext)\n",
  2501. " this.root.append(titlebar);\n",
  2502. " this.header = titletext[0];\n",
  2503. "}\n",
  2504. "\n",
  2505. "\n",
  2506. "\n",
  2507. "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n",
  2508. "\n",
  2509. "}\n",
  2510. "\n",
  2511. "\n",
  2512. "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n",
  2513. "\n",
  2514. "}\n",
  2515. "\n",
  2516. "mpl.figure.prototype._init_canvas = function() {\n",
  2517. " var fig = this;\n",
  2518. "\n",
  2519. " var canvas_div = $('<div/>');\n",
  2520. "\n",
  2521. " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n",
  2522. "\n",
  2523. " function canvas_keyboard_event(event) {\n",
  2524. " return fig.key_event(event, event['data']);\n",
  2525. " }\n",
  2526. "\n",
  2527. " canvas_div.keydown('key_press', canvas_keyboard_event);\n",
  2528. " canvas_div.keyup('key_release', canvas_keyboard_event);\n",
  2529. " this.canvas_div = canvas_div\n",
  2530. " this._canvas_extra_style(canvas_div)\n",
  2531. " this.root.append(canvas_div);\n",
  2532. "\n",
  2533. " var canvas = $('<canvas/>');\n",
  2534. " canvas.addClass('mpl-canvas');\n",
  2535. " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n",
  2536. "\n",
  2537. " this.canvas = canvas[0];\n",
  2538. " this.context = canvas[0].getContext(\"2d\");\n",
  2539. "\n",
  2540. " var backingStore = this.context.backingStorePixelRatio ||\n",
  2541. "\tthis.context.webkitBackingStorePixelRatio ||\n",
  2542. "\tthis.context.mozBackingStorePixelRatio ||\n",
  2543. "\tthis.context.msBackingStorePixelRatio ||\n",
  2544. "\tthis.context.oBackingStorePixelRatio ||\n",
  2545. "\tthis.context.backingStorePixelRatio || 1;\n",
  2546. "\n",
  2547. " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n",
  2548. "\n",
  2549. " var rubberband = $('<canvas/>');\n",
  2550. " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n",
  2551. "\n",
  2552. " var pass_mouse_events = true;\n",
  2553. "\n",
  2554. " canvas_div.resizable({\n",
  2555. " start: function(event, ui) {\n",
  2556. " pass_mouse_events = false;\n",
  2557. " },\n",
  2558. " resize: function(event, ui) {\n",
  2559. " fig.request_resize(ui.size.width, ui.size.height);\n",
  2560. " },\n",
  2561. " stop: function(event, ui) {\n",
  2562. " pass_mouse_events = true;\n",
  2563. " fig.request_resize(ui.size.width, ui.size.height);\n",
  2564. " },\n",
  2565. " });\n",
  2566. "\n",
  2567. " function mouse_event_fn(event) {\n",
  2568. " if (pass_mouse_events)\n",
  2569. " return fig.mouse_event(event, event['data']);\n",
  2570. " }\n",
  2571. "\n",
  2572. " rubberband.mousedown('button_press', mouse_event_fn);\n",
  2573. " rubberband.mouseup('button_release', mouse_event_fn);\n",
  2574. " // Throttle sequential mouse events to 1 every 20ms.\n",
  2575. " rubberband.mousemove('motion_notify', mouse_event_fn);\n",
  2576. "\n",
  2577. " rubberband.mouseenter('figure_enter', mouse_event_fn);\n",
  2578. " rubberband.mouseleave('figure_leave', mouse_event_fn);\n",
  2579. "\n",
  2580. " canvas_div.on(\"wheel\", function (event) {\n",
  2581. " event = event.originalEvent;\n",
  2582. " event['data'] = 'scroll'\n",
  2583. " if (event.deltaY < 0) {\n",
  2584. " event.step = 1;\n",
  2585. " } else {\n",
  2586. " event.step = -1;\n",
  2587. " }\n",
  2588. " mouse_event_fn(event);\n",
  2589. " });\n",
  2590. "\n",
  2591. " canvas_div.append(canvas);\n",
  2592. " canvas_div.append(rubberband);\n",
  2593. "\n",
  2594. " this.rubberband = rubberband;\n",
  2595. " this.rubberband_canvas = rubberband[0];\n",
  2596. " this.rubberband_context = rubberband[0].getContext(\"2d\");\n",
  2597. " this.rubberband_context.strokeStyle = \"#000000\";\n",
  2598. "\n",
  2599. " this._resize_canvas = function(width, height) {\n",
  2600. " // Keep the size of the canvas, canvas container, and rubber band\n",
  2601. " // canvas in synch.\n",
  2602. " canvas_div.css('width', width)\n",
  2603. " canvas_div.css('height', height)\n",
  2604. "\n",
  2605. " canvas.attr('width', width * mpl.ratio);\n",
  2606. " canvas.attr('height', height * mpl.ratio);\n",
  2607. " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n",
  2608. "\n",
  2609. " rubberband.attr('width', width);\n",
  2610. " rubberband.attr('height', height);\n",
  2611. " }\n",
  2612. "\n",
  2613. " // Set the figure to an initial 600x600px, this will subsequently be updated\n",
  2614. " // upon first draw.\n",
  2615. " this._resize_canvas(600, 600);\n",
  2616. "\n",
  2617. " // Disable right mouse context menu.\n",
  2618. " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n",
  2619. " return false;\n",
  2620. " });\n",
  2621. "\n",
  2622. " function set_focus () {\n",
  2623. " canvas.focus();\n",
  2624. " canvas_div.focus();\n",
  2625. " }\n",
  2626. "\n",
  2627. " window.setTimeout(set_focus, 100);\n",
  2628. "}\n",
  2629. "\n",
  2630. "mpl.figure.prototype._init_toolbar = function() {\n",
  2631. " var fig = this;\n",
  2632. "\n",
  2633. " var nav_element = $('<div/>');\n",
  2634. " nav_element.attr('style', 'width: 100%');\n",
  2635. " this.root.append(nav_element);\n",
  2636. "\n",
  2637. " // Define a callback function for later on.\n",
  2638. " function toolbar_event(event) {\n",
  2639. " return fig.toolbar_button_onclick(event['data']);\n",
  2640. " }\n",
  2641. " function toolbar_mouse_event(event) {\n",
  2642. " return fig.toolbar_button_onmouseover(event['data']);\n",
  2643. " }\n",
  2644. "\n",
  2645. " for(var toolbar_ind in mpl.toolbar_items) {\n",
  2646. " var name = mpl.toolbar_items[toolbar_ind][0];\n",
  2647. " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n",
  2648. " var image = mpl.toolbar_items[toolbar_ind][2];\n",
  2649. " var method_name = mpl.toolbar_items[toolbar_ind][3];\n",
  2650. "\n",
  2651. " if (!name) {\n",
  2652. " // put a spacer in here.\n",
  2653. " continue;\n",
  2654. " }\n",
  2655. " var button = $('<button/>');\n",
  2656. " button.addClass('ui-button ui-widget ui-state-default ui-corner-all ' +\n",
  2657. " 'ui-button-icon-only');\n",
  2658. " button.attr('role', 'button');\n",
  2659. " button.attr('aria-disabled', 'false');\n",
  2660. " button.click(method_name, toolbar_event);\n",
  2661. " button.mouseover(tooltip, toolbar_mouse_event);\n",
  2662. "\n",
  2663. " var icon_img = $('<span/>');\n",
  2664. " icon_img.addClass('ui-button-icon-primary ui-icon');\n",
  2665. " icon_img.addClass(image);\n",
  2666. " icon_img.addClass('ui-corner-all');\n",
  2667. "\n",
  2668. " var tooltip_span = $('<span/>');\n",
  2669. " tooltip_span.addClass('ui-button-text');\n",
  2670. " tooltip_span.html(tooltip);\n",
  2671. "\n",
  2672. " button.append(icon_img);\n",
  2673. " button.append(tooltip_span);\n",
  2674. "\n",
  2675. " nav_element.append(button);\n",
  2676. " }\n",
  2677. "\n",
  2678. " var fmt_picker_span = $('<span/>');\n",
  2679. "\n",
  2680. " var fmt_picker = $('<select/>');\n",
  2681. " fmt_picker.addClass('mpl-toolbar-option ui-widget ui-widget-content');\n",
  2682. " fmt_picker_span.append(fmt_picker);\n",
  2683. " nav_element.append(fmt_picker_span);\n",
  2684. " this.format_dropdown = fmt_picker[0];\n",
  2685. "\n",
  2686. " for (var ind in mpl.extensions) {\n",
  2687. " var fmt = mpl.extensions[ind];\n",
  2688. " var option = $(\n",
  2689. " '<option/>', {selected: fmt === mpl.default_extension}).html(fmt);\n",
  2690. " fmt_picker.append(option);\n",
  2691. " }\n",
  2692. "\n",
  2693. " // Add hover states to the ui-buttons\n",
  2694. " $( \".ui-button\" ).hover(\n",
  2695. " function() { $(this).addClass(\"ui-state-hover\");},\n",
  2696. " function() { $(this).removeClass(\"ui-state-hover\");}\n",
  2697. " );\n",
  2698. "\n",
  2699. " var status_bar = $('<span class=\"mpl-message\"/>');\n",
  2700. " nav_element.append(status_bar);\n",
  2701. " this.message = status_bar[0];\n",
  2702. "}\n",
  2703. "\n",
  2704. "mpl.figure.prototype.request_resize = function(x_pixels, y_pixels) {\n",
  2705. " // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n",
  2706. " // which will in turn request a refresh of the image.\n",
  2707. " this.send_message('resize', {'width': x_pixels, 'height': y_pixels});\n",
  2708. "}\n",
  2709. "\n",
  2710. "mpl.figure.prototype.send_message = function(type, properties) {\n",
  2711. " properties['type'] = type;\n",
  2712. " properties['figure_id'] = this.id;\n",
  2713. " this.ws.send(JSON.stringify(properties));\n",
  2714. "}\n",
  2715. "\n",
  2716. "mpl.figure.prototype.send_draw_message = function() {\n",
  2717. " if (!this.waiting) {\n",
  2718. " this.waiting = true;\n",
  2719. " this.ws.send(JSON.stringify({type: \"draw\", figure_id: this.id}));\n",
  2720. " }\n",
  2721. "}\n",
  2722. "\n",
  2723. "\n",
  2724. "mpl.figure.prototype.handle_save = function(fig, msg) {\n",
  2725. " var format_dropdown = fig.format_dropdown;\n",
  2726. " var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n",
  2727. " fig.ondownload(fig, format);\n",
  2728. "}\n",
  2729. "\n",
  2730. "\n",
  2731. "mpl.figure.prototype.handle_resize = function(fig, msg) {\n",
  2732. " var size = msg['size'];\n",
  2733. " if (size[0] != fig.canvas.width || size[1] != fig.canvas.height) {\n",
  2734. " fig._resize_canvas(size[0], size[1]);\n",
  2735. " fig.send_message(\"refresh\", {});\n",
  2736. " };\n",
  2737. "}\n",
  2738. "\n",
  2739. "mpl.figure.prototype.handle_rubberband = function(fig, msg) {\n",
  2740. " var x0 = msg['x0'] / mpl.ratio;\n",
  2741. " var y0 = (fig.canvas.height - msg['y0']) / mpl.ratio;\n",
  2742. " var x1 = msg['x1'] / mpl.ratio;\n",
  2743. " var y1 = (fig.canvas.height - msg['y1']) / mpl.ratio;\n",
  2744. " x0 = Math.floor(x0) + 0.5;\n",
  2745. " y0 = Math.floor(y0) + 0.5;\n",
  2746. " x1 = Math.floor(x1) + 0.5;\n",
  2747. " y1 = Math.floor(y1) + 0.5;\n",
  2748. " var min_x = Math.min(x0, x1);\n",
  2749. " var min_y = Math.min(y0, y1);\n",
  2750. " var width = Math.abs(x1 - x0);\n",
  2751. " var height = Math.abs(y1 - y0);\n",
  2752. "\n",
  2753. " fig.rubberband_context.clearRect(\n",
  2754. " 0, 0, fig.canvas.width / mpl.ratio, fig.canvas.height / mpl.ratio);\n",
  2755. "\n",
  2756. " fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n",
  2757. "}\n",
  2758. "\n",
  2759. "mpl.figure.prototype.handle_figure_label = function(fig, msg) {\n",
  2760. " // Updates the figure title.\n",
  2761. " fig.header.textContent = msg['label'];\n",
  2762. "}\n",
  2763. "\n",
  2764. "mpl.figure.prototype.handle_cursor = function(fig, msg) {\n",
  2765. " var cursor = msg['cursor'];\n",
  2766. " switch(cursor)\n",
  2767. " {\n",
  2768. " case 0:\n",
  2769. " cursor = 'pointer';\n",
  2770. " break;\n",
  2771. " case 1:\n",
  2772. " cursor = 'default';\n",
  2773. " break;\n",
  2774. " case 2:\n",
  2775. " cursor = 'crosshair';\n",
  2776. " break;\n",
  2777. " case 3:\n",
  2778. " cursor = 'move';\n",
  2779. " break;\n",
  2780. " }\n",
  2781. " fig.rubberband_canvas.style.cursor = cursor;\n",
  2782. "}\n",
  2783. "\n",
  2784. "mpl.figure.prototype.handle_message = function(fig, msg) {\n",
  2785. " fig.message.textContent = msg['message'];\n",
  2786. "}\n",
  2787. "\n",
  2788. "mpl.figure.prototype.handle_draw = function(fig, msg) {\n",
  2789. " // Request the server to send over a new figure.\n",
  2790. " fig.send_draw_message();\n",
  2791. "}\n",
  2792. "\n",
  2793. "mpl.figure.prototype.handle_image_mode = function(fig, msg) {\n",
  2794. " fig.image_mode = msg['mode'];\n",
  2795. "}\n",
  2796. "\n",
  2797. "mpl.figure.prototype.updated_canvas_event = function() {\n",
  2798. " // Called whenever the canvas gets updated.\n",
  2799. " this.send_message(\"ack\", {});\n",
  2800. "}\n",
  2801. "\n",
  2802. "// A function to construct a web socket function for onmessage handling.\n",
  2803. "// Called in the figure constructor.\n",
  2804. "mpl.figure.prototype._make_on_message_function = function(fig) {\n",
  2805. " return function socket_on_message(evt) {\n",
  2806. " if (evt.data instanceof Blob) {\n",
  2807. " /* FIXME: We get \"Resource interpreted as Image but\n",
  2808. " * transferred with MIME type text/plain:\" errors on\n",
  2809. " * Chrome. But how to set the MIME type? It doesn't seem\n",
  2810. " * to be part of the websocket stream */\n",
  2811. " evt.data.type = \"image/png\";\n",
  2812. "\n",
  2813. " /* Free the memory for the previous frames */\n",
  2814. " if (fig.imageObj.src) {\n",
  2815. " (window.URL || window.webkitURL).revokeObjectURL(\n",
  2816. " fig.imageObj.src);\n",
  2817. " }\n",
  2818. "\n",
  2819. " fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n",
  2820. " evt.data);\n",
  2821. " fig.updated_canvas_event();\n",
  2822. " fig.waiting = false;\n",
  2823. " return;\n",
  2824. " }\n",
  2825. " else if (typeof evt.data === 'string' && evt.data.slice(0, 21) == \"data:image/png;base64\") {\n",
  2826. " fig.imageObj.src = evt.data;\n",
  2827. " fig.updated_canvas_event();\n",
  2828. " fig.waiting = false;\n",
  2829. " return;\n",
  2830. " }\n",
  2831. "\n",
  2832. " var msg = JSON.parse(evt.data);\n",
  2833. " var msg_type = msg['type'];\n",
  2834. "\n",
  2835. " // Call the \"handle_{type}\" callback, which takes\n",
  2836. " // the figure and JSON message as its only arguments.\n",
  2837. " try {\n",
  2838. " var callback = fig[\"handle_\" + msg_type];\n",
  2839. " } catch (e) {\n",
  2840. " console.log(\"No handler for the '\" + msg_type + \"' message type: \", msg);\n",
  2841. " return;\n",
  2842. " }\n",
  2843. "\n",
  2844. " if (callback) {\n",
  2845. " try {\n",
  2846. " // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n",
  2847. " callback(fig, msg);\n",
  2848. " } catch (e) {\n",
  2849. " console.log(\"Exception inside the 'handler_\" + msg_type + \"' callback:\", e, e.stack, msg);\n",
  2850. " }\n",
  2851. " }\n",
  2852. " };\n",
  2853. "}\n",
  2854. "\n",
  2855. "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n",
  2856. "mpl.findpos = function(e) {\n",
  2857. " //this section is from http://www.quirksmode.org/js/events_properties.html\n",
  2858. " var targ;\n",
  2859. " if (!e)\n",
  2860. " e = window.event;\n",
  2861. " if (e.target)\n",
  2862. " targ = e.target;\n",
  2863. " else if (e.srcElement)\n",
  2864. " targ = e.srcElement;\n",
  2865. " if (targ.nodeType == 3) // defeat Safari bug\n",
  2866. " targ = targ.parentNode;\n",
  2867. "\n",
  2868. " // jQuery normalizes the pageX and pageY\n",
  2869. " // pageX,Y are the mouse positions relative to the document\n",
  2870. " // offset() returns the position of the element relative to the document\n",
  2871. " var x = e.pageX - $(targ).offset().left;\n",
  2872. " var y = e.pageY - $(targ).offset().top;\n",
  2873. "\n",
  2874. " return {\"x\": x, \"y\": y};\n",
  2875. "};\n",
  2876. "\n",
  2877. "/*\n",
  2878. " * return a copy of an object with only non-object keys\n",
  2879. " * we need this to avoid circular references\n",
  2880. " * http://stackoverflow.com/a/24161582/3208463\n",
  2881. " */\n",
  2882. "function simpleKeys (original) {\n",
  2883. " return Object.keys(original).reduce(function (obj, key) {\n",
  2884. " if (typeof original[key] !== 'object')\n",
  2885. " obj[key] = original[key]\n",
  2886. " return obj;\n",
  2887. " }, {});\n",
  2888. "}\n",
  2889. "\n",
  2890. "mpl.figure.prototype.mouse_event = function(event, name) {\n",
  2891. " var canvas_pos = mpl.findpos(event)\n",
  2892. "\n",
  2893. " if (name === 'button_press')\n",
  2894. " {\n",
  2895. " this.canvas.focus();\n",
  2896. " this.canvas_div.focus();\n",
  2897. " }\n",
  2898. "\n",
  2899. " var x = canvas_pos.x * mpl.ratio;\n",
  2900. " var y = canvas_pos.y * mpl.ratio;\n",
  2901. "\n",
  2902. " this.send_message(name, {x: x, y: y, button: event.button,\n",
  2903. " step: event.step,\n",
  2904. " guiEvent: simpleKeys(event)});\n",
  2905. "\n",
  2906. " /* This prevents the web browser from automatically changing to\n",
  2907. " * the text insertion cursor when the button is pressed. We want\n",
  2908. " * to control all of the cursor setting manually through the\n",
  2909. " * 'cursor' event from matplotlib */\n",
  2910. " event.preventDefault();\n",
  2911. " return false;\n",
  2912. "}\n",
  2913. "\n",
  2914. "mpl.figure.prototype._key_event_extra = function(event, name) {\n",
  2915. " // Handle any extra behaviour associated with a key event\n",
  2916. "}\n",
  2917. "\n",
  2918. "mpl.figure.prototype.key_event = function(event, name) {\n",
  2919. "\n",
  2920. " // Prevent repeat events\n",
  2921. " if (name == 'key_press')\n",
  2922. " {\n",
  2923. " if (event.which === this._key)\n",
  2924. " return;\n",
  2925. " else\n",
  2926. " this._key = event.which;\n",
  2927. " }\n",
  2928. " if (name == 'key_release')\n",
  2929. " this._key = null;\n",
  2930. "\n",
  2931. " var value = '';\n",
  2932. " if (event.ctrlKey && event.which != 17)\n",
  2933. " value += \"ctrl+\";\n",
  2934. " if (event.altKey && event.which != 18)\n",
  2935. " value += \"alt+\";\n",
  2936. " if (event.shiftKey && event.which != 16)\n",
  2937. " value += \"shift+\";\n",
  2938. "\n",
  2939. " value += 'k';\n",
  2940. " value += event.which.toString();\n",
  2941. "\n",
  2942. " this._key_event_extra(event, name);\n",
  2943. "\n",
  2944. " this.send_message(name, {key: value,\n",
  2945. " guiEvent: simpleKeys(event)});\n",
  2946. " return false;\n",
  2947. "}\n",
  2948. "\n",
  2949. "mpl.figure.prototype.toolbar_button_onclick = function(name) {\n",
  2950. " if (name == 'download') {\n",
  2951. " this.handle_save(this, null);\n",
  2952. " } else {\n",
  2953. " this.send_message(\"toolbar_button\", {name: name});\n",
  2954. " }\n",
  2955. "};\n",
  2956. "\n",
  2957. "mpl.figure.prototype.toolbar_button_onmouseover = function(tooltip) {\n",
  2958. " this.message.textContent = tooltip;\n",
  2959. "};\n",
  2960. "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Pan axes with left mouse, zoom with right\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n",
  2961. "\n",
  2962. "mpl.extensions = [\"eps\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\"];\n",
  2963. "\n",
  2964. "mpl.default_extension = \"png\";var comm_websocket_adapter = function(comm) {\n",
  2965. " // Create a \"websocket\"-like object which calls the given IPython comm\n",
  2966. " // object with the appropriate methods. Currently this is a non binary\n",
  2967. " // socket, so there is still some room for performance tuning.\n",
  2968. " var ws = {};\n",
  2969. "\n",
  2970. " ws.close = function() {\n",
  2971. " comm.close()\n",
  2972. " };\n",
  2973. " ws.send = function(m) {\n",
  2974. " //console.log('sending', m);\n",
  2975. " comm.send(m);\n",
  2976. " };\n",
  2977. " // Register the callback with on_msg.\n",
  2978. " comm.on_msg(function(msg) {\n",
  2979. " //console.log('receiving', msg['content']['data'], msg);\n",
  2980. " // Pass the mpl event to the overridden (by mpl) onmessage function.\n",
  2981. " ws.onmessage(msg['content']['data'])\n",
  2982. " });\n",
  2983. " return ws;\n",
  2984. "}\n",
  2985. "\n",
  2986. "mpl.mpl_figure_comm = function(comm, msg) {\n",
  2987. " // This is the function which gets called when the mpl process\n",
  2988. " // starts-up an IPython Comm through the \"matplotlib\" channel.\n",
  2989. "\n",
  2990. " var id = msg.content.data.id;\n",
  2991. " // Get hold of the div created by the display call when the Comm\n",
  2992. " // socket was opened in Python.\n",
  2993. " var element = $(\"#\" + id);\n",
  2994. " var ws_proxy = comm_websocket_adapter(comm)\n",
  2995. "\n",
  2996. " function ondownload(figure, format) {\n",
  2997. " window.open(figure.imageObj.src);\n",
  2998. " }\n",
  2999. "\n",
  3000. " var fig = new mpl.figure(id, ws_proxy,\n",
  3001. " ondownload,\n",
  3002. " element.get(0));\n",
  3003. "\n",
  3004. " // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n",
  3005. " // web socket which is closed, not our websocket->open comm proxy.\n",
  3006. " ws_proxy.onopen();\n",
  3007. "\n",
  3008. " fig.parent_element = element.get(0);\n",
  3009. " fig.cell_info = mpl.find_output_cell(\"<div id='\" + id + \"'></div>\");\n",
  3010. " if (!fig.cell_info) {\n",
  3011. " console.error(\"Failed to find cell for figure\", id, fig);\n",
  3012. " return;\n",
  3013. " }\n",
  3014. "\n",
  3015. " var output_index = fig.cell_info[2]\n",
  3016. " var cell = fig.cell_info[0];\n",
  3017. "\n",
  3018. "};\n",
  3019. "\n",
  3020. "mpl.figure.prototype.handle_close = function(fig, msg) {\n",
  3021. " var width = fig.canvas.width/mpl.ratio\n",
  3022. " fig.root.unbind('remove')\n",
  3023. "\n",
  3024. " // Update the output cell to use the data from the current canvas.\n",
  3025. " fig.push_to_output();\n",
  3026. " var dataURL = fig.canvas.toDataURL();\n",
  3027. " // Re-enable the keyboard manager in IPython - without this line, in FF,\n",
  3028. " // the notebook keyboard shortcuts fail.\n",
  3029. " IPython.keyboard_manager.enable()\n",
  3030. " $(fig.parent_element).html('<img src=\"' + dataURL + '\" width=\"' + width + '\">');\n",
  3031. " fig.close_ws(fig, msg);\n",
  3032. "}\n",
  3033. "\n",
  3034. "mpl.figure.prototype.close_ws = function(fig, msg){\n",
  3035. " fig.send_message('closing', msg);\n",
  3036. " // fig.ws.close()\n",
  3037. "}\n",
  3038. "\n",
  3039. "mpl.figure.prototype.push_to_output = function(remove_interactive) {\n",
  3040. " // Turn the data on the canvas into data in the output cell.\n",
  3041. " var width = this.canvas.width/mpl.ratio\n",
  3042. " var dataURL = this.canvas.toDataURL();\n",
  3043. " this.cell_info[1]['text/html'] = '<img src=\"' + dataURL + '\" width=\"' + width + '\">';\n",
  3044. "}\n",
  3045. "\n",
  3046. "mpl.figure.prototype.updated_canvas_event = function() {\n",
  3047. " // Tell IPython that the notebook contents must change.\n",
  3048. " IPython.notebook.set_dirty(true);\n",
  3049. " this.send_message(\"ack\", {});\n",
  3050. " var fig = this;\n",
  3051. " // Wait a second, then push the new image to the DOM so\n",
  3052. " // that it is saved nicely (might be nice to debounce this).\n",
  3053. " setTimeout(function () { fig.push_to_output() }, 1000);\n",
  3054. "}\n",
  3055. "\n",
  3056. "mpl.figure.prototype._init_toolbar = function() {\n",
  3057. " var fig = this;\n",
  3058. "\n",
  3059. " var nav_element = $('<div/>');\n",
  3060. " nav_element.attr('style', 'width: 100%');\n",
  3061. " this.root.append(nav_element);\n",
  3062. "\n",
  3063. " // Define a callback function for later on.\n",
  3064. " function toolbar_event(event) {\n",
  3065. " return fig.toolbar_button_onclick(event['data']);\n",
  3066. " }\n",
  3067. " function toolbar_mouse_event(event) {\n",
  3068. " return fig.toolbar_button_onmouseover(event['data']);\n",
  3069. " }\n",
  3070. "\n",
  3071. " for(var toolbar_ind in mpl.toolbar_items){\n",
  3072. " var name = mpl.toolbar_items[toolbar_ind][0];\n",
  3073. " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n",
  3074. " var image = mpl.toolbar_items[toolbar_ind][2];\n",
  3075. " var method_name = mpl.toolbar_items[toolbar_ind][3];\n",
  3076. "\n",
  3077. " if (!name) { continue; };\n",
  3078. "\n",
  3079. " var button = $('<button class=\"btn btn-default\" href=\"#\" title=\"' + name + '\"><i class=\"fa ' + image + ' fa-lg\"></i></button>');\n",
  3080. " button.click(method_name, toolbar_event);\n",
  3081. " button.mouseover(tooltip, toolbar_mouse_event);\n",
  3082. " nav_element.append(button);\n",
  3083. " }\n",
  3084. "\n",
  3085. " // Add the status bar.\n",
  3086. " var status_bar = $('<span class=\"mpl-message\" style=\"text-align:right; float: right;\"/>');\n",
  3087. " nav_element.append(status_bar);\n",
  3088. " this.message = status_bar[0];\n",
  3089. "\n",
  3090. " // Add the close button to the window.\n",
  3091. " var buttongrp = $('<div class=\"btn-group inline pull-right\"></div>');\n",
  3092. " var button = $('<button class=\"btn btn-mini btn-primary\" href=\"#\" title=\"Stop Interaction\"><i class=\"fa fa-power-off icon-remove icon-large\"></i></button>');\n",
  3093. " button.click(function (evt) { fig.handle_close(fig, {}); } );\n",
  3094. " button.mouseover('Stop Interaction', toolbar_mouse_event);\n",
  3095. " buttongrp.append(button);\n",
  3096. " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n",
  3097. " titlebar.prepend(buttongrp);\n",
  3098. "}\n",
  3099. "\n",
  3100. "mpl.figure.prototype._root_extra_style = function(el){\n",
  3101. " var fig = this\n",
  3102. " el.on(\"remove\", function(){\n",
  3103. "\tfig.close_ws(fig, {});\n",
  3104. " });\n",
  3105. "}\n",
  3106. "\n",
  3107. "mpl.figure.prototype._canvas_extra_style = function(el){\n",
  3108. " // this is important to make the div 'focusable\n",
  3109. " el.attr('tabindex', 0)\n",
  3110. " // reach out to IPython and tell the keyboard manager to turn it's self\n",
  3111. " // off when our div gets focus\n",
  3112. "\n",
  3113. " // location in version 3\n",
  3114. " if (IPython.notebook.keyboard_manager) {\n",
  3115. " IPython.notebook.keyboard_manager.register_events(el);\n",
  3116. " }\n",
  3117. " else {\n",
  3118. " // location in version 2\n",
  3119. " IPython.keyboard_manager.register_events(el);\n",
  3120. " }\n",
  3121. "\n",
  3122. "}\n",
  3123. "\n",
  3124. "mpl.figure.prototype._key_event_extra = function(event, name) {\n",
  3125. " var manager = IPython.notebook.keyboard_manager;\n",
  3126. " if (!manager)\n",
  3127. " manager = IPython.keyboard_manager;\n",
  3128. "\n",
  3129. " // Check for shift+enter\n",
  3130. " if (event.shiftKey && event.which == 13) {\n",
  3131. " this.canvas_div.blur();\n",
  3132. " // select the cell after this one\n",
  3133. " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n",
  3134. " IPython.notebook.select(index + 1);\n",
  3135. " }\n",
  3136. "}\n",
  3137. "\n",
  3138. "mpl.figure.prototype.handle_save = function(fig, msg) {\n",
  3139. " fig.ondownload(fig, null);\n",
  3140. "}\n",
  3141. "\n",
  3142. "\n",
  3143. "mpl.find_output_cell = function(html_output) {\n",
  3144. " // Return the cell and output element which can be found *uniquely* in the notebook.\n",
  3145. " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n",
  3146. " // IPython event is triggered only after the cells have been serialised, which for\n",
  3147. " // our purposes (turning an active figure into a static one), is too late.\n",
  3148. " var cells = IPython.notebook.get_cells();\n",
  3149. " var ncells = cells.length;\n",
  3150. " for (var i=0; i<ncells; i++) {\n",
  3151. " var cell = cells[i];\n",
  3152. " if (cell.cell_type === 'code'){\n",
  3153. " for (var j=0; j<cell.output_area.outputs.length; j++) {\n",
  3154. " var data = cell.output_area.outputs[j];\n",
  3155. " if (data.data) {\n",
  3156. " // IPython >= 3 moved mimebundle to data attribute of output\n",
  3157. " data = data.data;\n",
  3158. " }\n",
  3159. " if (data['text/html'] == html_output) {\n",
  3160. " return [cell, data, j];\n",
  3161. " }\n",
  3162. " }\n",
  3163. " }\n",
  3164. " }\n",
  3165. "}\n",
  3166. "\n",
  3167. "// Register the function which deals with the matplotlib target/channel.\n",
  3168. "// The kernel may be null if the page has been refreshed.\n",
  3169. "if (IPython.notebook.kernel != null) {\n",
  3170. " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n",
  3171. "}\n"
  3172. ],
  3173. "text/plain": [
  3174. "<IPython.core.display.Javascript object>"
  3175. ]
  3176. },
  3177. "metadata": {},
  3178. "output_type": "display_data"
  3179. },
  3180. {
  3181. "data": {
  3182. "text/html": [
  3183. "<img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA4QAAAMgCAYAAAB7w6zDAAAgAElEQVR4nOzdeXTV9Z3/8W/CEpZEFgVBUFBKxY4KqFW0MlipO661LrUMVv2paKtSR2RsLToqHaattnamtm64jnVHHRXBBRS3UtFaxa21RdpStSpUVJTl/fvDuVcuSSDBL8Qvn8fznMc5enOTfENyb+4r9+YmC0mSJElSkmUtfQCSJEmSpJbJIJQkSZKkRDMIJUmSJCnRDEJJkiRJSjSDUJIkSZISzSCUJEmSpEQzCCVJkiQp0QxCSZIkSUo0g1CSJEmSEs0glCRJkqREMwglSZIkKdEMQkmSJElKNINQkiRJkhLNIJQkSZKkRDMIJUmSJCnRDEJJkiRJSjSDUJIkSZISzSCUJEmSpEQzCCVJkiQp0QxCSZKa2R577BHbbLNNDBw4MHbdddd4+umnW/qQJElaowxCSZKa2TvvvFP+79tvvz0GDx7cgkcjSdKaZxBKkvQpuuqqq2L77bdv6cOQJGmNMgglSVqDRo4cGb17947evXvHc88919KHI0nSGmUQSpL0Kbrqqqtin332aenDkCRpjTIIJUn6lLVr1y7+/ve/t/RhSJLU7AxCSZKa0cKFC+Mvf/lL+f9vu+226NWrVyxfvrwFj0qSpDXLIJQkqRm99tpr8cUvfjG23nrr2HbbbWP48OH+7IQkqbAZhJIkSZKUaAahJEmSJCWaQShJkiRJiWYQSpIkSVKiGYSSJEmSlGgGoSRJkiQlmkEoSZIkSYlmEEqSJElSohmEkiRJkpRoBqEkSZIkJZpBKEmSJEmJZhBKkiRJUqIZhJIkSZKUaAahJEmSJCWaQShJkiRJiWYQSpIkSVKiGYSSJEmSlGgGoSRJkiQlmkEoSZIkSYlmEEqSJElSohmEkiRJkpRoBqEkSZIkJZpBKEmSJEmJZhBKkiRJUqIZhJIkSZKUaAahJEmSJCWaQShJkiRJiWYQSpIkSVKiGYSSJEmSlGgGoSRJkiQlmkEoSZIkSYlmEEqSJElSohmEkiRJkpRoBqEkSZIkJZpBKEmSJEmJZhBKkiRJUqIZhJIkSZKUaAahJEmSJCWaQShJkiRJiWYQSpIkSVKiGYSSJEmSlGgGoSRJkiQlmkEoSZIkSYlmEEqSJElSohmEkiRJkpRoBqEkSZIkJZpBKEmSJEmJZhBKkiRJUqIZhFJETJo0KbIsK6upqYmNN944dtttt5gwYUK8/vrrLX2ITapPnz4xatSolj6MwjRq1Kjo06fPGr3u9ddfHxdddFG+B/R/rc3PY+lr/Y9//GP5tMY+lj/+8Y+RZVn88Ic/XKP39dBDD0WWZXHzzTc3+PKTTz45siyrOK7VKX2+xo8fH1mWRVVVVfzhD3+o97YXLVoUdXV1kWVZxb/lp/mYhg0bFv/0T//U4MvefPPNyLIsxo8fXz5t5Y+pVatW0aNHjzj88MPj5ZdfbtbbX5Ma+lw3tbvvvrviY8m7c889N7baaqtYtmxZRDTv87KqY7vgggvi9ttvz/NQ16iDDz44DjjggIrT3nrrrWjdunXcdttt5f8//PDDo1u3bpFlWRx44IEtcagR8cnl6c0331zn73vUqFHRsWPHdf5+8+7tt9+OTp06fSa+/qTmZhBK8ckNp0mTJsXjjz8eDz/8cNxyyy1x2mmnRadOnaJr164xbdq0lj7M1TZ79uz4/e9/39KHUZh+//vfx+zZs9fodffbb781HpOra20OwjfeeCMef/zxWLx4cfm0xj6WdTkIS8e1oizL4tBDD604rfT5Kt2Arauri+9973v13vakSZOiXbt20aZNmxYfhKXrlYceeijOP//8aN++fXTv3j3efvvtJr/9NenTDMIVPzd595e//CU6duxY8XXRnM/Lqo6tY8eOLf5DsUWLFkX79u3j6quvrjj9yiuvjA4dOsT7778fERGnnXZatG3bNq677rp4/PHH46WXXmqJw40IgzCvzjnnnPjc5z4XH374YUsfitSsDEIpPrnhNGvWrHovmzt3bmy66aZRV1cXf/vb31rg6PRZrKiDsKE+C4OwobIsi5NPPrnBl5VuwB533HGx6aablu9pKrXrrrvGkUceWW8gtMQgXPl65dxzz40sy+LKK69s8ttfkz6rg3Ds2LHRq1evis/Z+jQIb7rppmjTpk29wb/vvvvGoYceWv7/r3zlK7HVVlut68NrMIMwn/72t79F69at4/rrr2/pQ5GalUEoxaoHYcTH3+CzLItzzz234vQ77rgjhgwZEu3bt4/a2tr4yle+Eo899ljFeUrfaH/729/GoYceGhtssEF06dIlxowZE0uWLIkXX3wx9tprr6itrY0+ffrExIkTK17/gw8+iO985zsxcODA8usOGTIkJk+eXO84Vx4SpRvk//M//xNnnXVW9OzZM+rq6mL48OHx4osvVrzu7NmzY7/99otu3bpF27Zto2fPnrHvvvvGvHnzVvlvN3Xq1DjggAOiV69eUVNTE/369Yvjjz++3g2LN954I/7f//t/0bt372jbtm1stNFGscsuu1Tc89qUY/jggw9i3Lhx0bdv32jTpk1ssskmcdJJJ8U777xT79iuv/76GDJkSHTs2DE6duwYAwcOjMsvv7z88oYeMvpf//VfMXTo0OjWrVt06NAhtt5665g4cWJ89NFH5fMMGzaswYczlvrwww/jvPPOiy233LL8sR599NHxxhtvVLyvjz76KM4444zYeOONo3379vGlL30pnnzyySYNwh122CH23XffitO23nrryLIsfv3rX5dPu/XWWyPLsnj22Wcjov5IWNXHsuKN9B//+MfRt2/f6NixYwwZMiQef/zxVR5fxLoZhI899lhkWRZTpkwpv+yll16KLMti2rRpn8lBePfdd0eWZfGDH/ygyW9/dT3++OOxyy67RE1NTfTs2TPGjRsXl156ab1B+Ktf/Sr22GOP6NGjR7Rr1y4GDBgQZ555ZixatKh8nlGjRjX4NVF6O025jDTWhx9+GBtuuGGcccYZFac39WttVcfW0OnDhg2LiE8+F1OnTo2jjz46unTpEh06dIgRI0bUe8jxml4Xljr88MNjr732qjht4cKF0bZt27jhhhsaPdaHHnooIj6+l2nHHXeMLl26RF1dXQwePDguv/zyWL58eb33tbrruIiIadOmxe677x51dXXRvn372GWXXeL++++vOE/p8jR79uw4+OCDo66uLjbYYIM46qij6l1vLVu2LCZOnFi+fuvWrVuMHDmywX+fK664IrbddtuoqamJLl26xEEHHRRz5sypOE9Dg3DmzJmx4YYbxn777VfxtdlQTzzxRIwYMSK6du0aNTU1scUWW8Spp55acZ5HHnkkdt9996itrY327dvHzjvvHP/7v/9bcZ7S18gDDzwQxx13XHTt2jXq6upi5MiRsWjRopg/f3587Wtfi06dOkWPHj3i9NNPb/Brfp999omhQ4eu8pilz1oGoRSrH4SLFi2KVq1axfDhw8unXX/99ZFlWey5554xefLkuPHGG2P77bePtm3bxiOPPFI+X+kb7ZZbbhnnnXdeTJs2LcaOHRtZlsW3vvWtGDBgQFx88cUxbdq0+OY3vxlZlsWtt95afv0FCxbE0UcfHddee208+OCDMWXKlPjXf/3XqK6urveQpMYGYd++feOoo46Ku+++O2644YbYbLPNon///rF06dLyx7fhhhvGDjvsEDfddFPMmDEjbrzxxjjxxBPrffNeuUsuuSR+8IMfxJ133hkzZsyIq6++OgYOHBhbbrllxTfLvfbaK7p16xaXXnppTJ8+PSZPnhzf//7341e/+lWTj2H58uWx1157RevWrePss8+OqVOnxo9+9KPo2LFjDB48uOJhkGeffXZkWRaHHHJI3HzzzTF16tS48MIL4+yzzy6fp6FBOGbMmLjkkktiypQp8eCDD8ZFF10UG220UXzzm98sn+f555+PL33pS9GjR4+KhzNGfHxjae+9946OHTvGueeeG9OmTYvLL788evXqFV/4whfKDxcrvf+qqqo444wzysfXq1
  3184. ],
  3185. "text/plain": [
  3186. "<IPython.core.display.HTML object>"
  3187. ]
  3188. },
  3189. "metadata": {},
  3190. "output_type": "display_data"
  3191. }
  3192. ],
  3193. "source": [
  3194. "#!/bin/env python\n",
  3195. "\n",
  3196. "\"\"\"\n",
  3197. "URL data extractor\n",
  3198. "\n",
  3199. "Pekka Helenius <pekka [dot] helenius [at] fjordtek [dot] com>\n",
  3200. "\n",
  3201. "Requirements:\n",
  3202. "\n",
  3203. "Python 3\n",
  3204. "Python 3 BeautifulSoup4 (python-beautifulsoup4)\n",
  3205. "Python 3 whois (python-whois; PyPI)\n",
  3206. "Python 3 JSON Schema (python-jsonschema)\n",
  3207. "Python 3 Numpy (python-numpy)\n",
  3208. "Python 3 matplotlib (python-matplotlib)\n",
  3209. "\n",
  3210. "TODO: URL domain part length comparison analysis\n",
  3211. "TODO: URL non-TLD part length comparison analysis\n",
  3212. " - in phishing webpages, URL tends to be much longer than legitimate webpages\n",
  3213. " however, domains themselves tend to be much shorter (without TLD)\n",
  3214. " - phishing URLs often contain more number of dots and subdomains than legitimate URLs\n",
  3215. " - legitimate: robots.txt redirects bots to a legitimate domain rather than to the original phishing domain\n",
  3216. "\n",
  3217. "TODO: Website visual similarity analysis\n",
  3218. "TODO: consistency of RDN usage in HTML data\n",
  3219. "\"\"\"\n",
  3220. "\n",
  3221. "######################################\n",
  3222. "\n",
  3223. "%matplotlib notebook\n",
  3224. "import matplotlib.pyplot as plt\n",
  3225. "\n",
  3226. "from bs4 import BeautifulSoup as bs\n",
  3227. "from collections import Counter\n",
  3228. "from datetime import date, datetime\n",
  3229. "import json\n",
  3230. "import os\n",
  3231. "import re\n",
  3232. "import requests\n",
  3233. "from time import sleep\n",
  3234. "import urllib\n",
  3235. "from whois import whois\n",
  3236. "\n",
  3237. "# Target URLs\n",
  3238. "urls = [\n",
  3239. " \"https://hoxhunt.com/\",\n",
  3240. " \"https://hs.fi\",\n",
  3241. " \"https://ts.fi\",\n",
  3242. " \"https://facebook.com\"\n",
  3243. "]\n",
  3244. "\n",
  3245. "# Some web servers may block our request unless we set a widely used, well-known user agent string\n",
  3246. "request_headers = {\n",
  3247. " 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36'\n",
  3248. "}\n",
  3249. "\n",
  3250. "# Date format for domain timestamps\n",
  3251. "dateformat = \"%Y/%m/%d\"\n",
  3252. "\n",
  3253. "# All webpages may not like fetching data too fast\n",
  3254. "# Sleep time in seconds\n",
  3255. "sleep_interval_between_requests = 0.5\n",
  3256. "\n",
  3257. "# Write JSON results to a file?\n",
  3258. "use_file = True\n",
  3259. "# Full file path + name\n",
  3260. "filename = os.getcwd() + \"/\" + \"url_info.json\"\n",
  3261. "\n",
  3262. "# Generate plot from existing JSON data?\n",
  3263. "plot_only = False\n",
  3264. "\n",
  3265. "# Save generated plot images?\n",
  3266. "save_plot_images = True\n",
  3267. "\n",
  3268. "# DPI of plot images\n",
  3269. "plot_images_dpi = 150\n",
  3270. "\n",
  3271. "# Common link attribute references in various HTML elements\n",
  3272. "link_refs = {\n",
  3273. " 'a': 'href',\n",
  3274. " 'img': 'src',\n",
  3275. " 'script': 'src'\n",
  3276. "}\n",
  3277. "\n",
  3278. "############################################################################\n",
  3279. "############################################################################\n",
  3280. "\n",
  3281. "class json_url_data(object):\n",
  3282. "\n",
  3283. "# def __init__(self):\n",
  3284. "\n",
  3285. "######################################\n",
  3286. " \"\"\"\n",
  3287. " Set a new HTTP session and get response.\n",
  3288. "\n",
  3289. " Returns a requests.models.Response object.\n",
  3290. " \"\"\"\n",
  3291. " def set_session(self, url, method='get', redirects=True):\n",
  3292. " \n",
  3293. " # HTTP response status codes 1XX, 2XX and 3XX are OK\n",
  3294. " # Treat other codes as errors\n",
  3295. " sc = re.compile(r\"^[123]{1}[0-9]{2}\")\n",
  3296. " \n",
  3297. " sleep(sleep_interval_between_requests)\n",
  3298. " \n",
  3299. " try:\n",
  3300. " session = requests.Session()\n",
  3301. " response = session.request(method, url, headers=request_headers, allow_redirects=redirects)\n",
  3302. " \n",
  3303. " if not sc.match(str(response.status_code)):\n",
  3304. " raise Exception(\"Error: got invalid response status from the web server\")\n",
  3305. " return response\n",
  3306. " \n",
  3307. " except:\n",
  3308. " raise Exception(\"Error: HTTP session could not be established. URL: '\" + url + \"' (method: \" + method + \")\") from None\n",
  3309. "\n",
  3310. "######################################\n",
  3311. " \"\"\"\n",
  3312. " Fetch HTML data.\n",
  3313. "\n",
  3314. " Returns a bs4.BeautifulSoup object.\n",
  3315. " \"\"\"\n",
  3316. " def get_html_data(self, url):\n",
  3317. " \n",
  3318. " try:\n",
  3319. " data = bs(self.set_session(url).content, 'html.parser')\n",
  3320. " return data\n",
  3321. " except:\n",
  3322. " raise Exception(\"Error: HTML data could not be retrieved\")\n",
  3323. "\n",
  3324. "######################################\n",
  3325. " \"\"\"\n",
  3326. " Get URL redirects and related HTTP status codes.\n",
  3327. "\n",
  3328. " Returns a list object.\n",
  3329. " \"\"\"\n",
  3330. " def get_url_redirects(self, url):\n",
  3331. " \n",
  3332. " response = self.set_session(url)\n",
  3333. " list_data = []\n",
  3334. " \n",
  3335. " if response.history:\n",
  3336. " \n",
  3337. " for r in response.history:\n",
  3338. " list_data.append({'redirect_url': r.url, 'status': r.status_code})\n",
  3339. " \n",
  3340. " return list_data\n",
  3341. "\n",
  3342. "######################################\n",
  3343. " \"\"\"\n",
  3344. " Extract title HTML element contents from given HTML data.\n",
  3345. "\n",
  3346. " Returns a string object.\n",
  3347. " \"\"\"\n",
  3348. " def get_webpage_title(self, url):\n",
  3349. " \n",
  3350. " html_data = self.get_html_data(url)\n",
  3351. " \n",
  3352. " title = html_data.title.string\n",
  3353. " return title\n",
  3354. "\n",
  3355. "######################################\n",
  3356. " \"\"\"\n",
  3357. " Get WHOIS domain data.\n",
  3358. "\n",
  3359. " Returns a dict object.\n",
  3360. " \"\"\"\n",
  3361. " def get_whois_data(self, url):\n",
  3362. " dict_data = whois(url)\n",
  3363. " return dict_data\n",
  3364. "\n",
  3365. "######################################\n",
  3366. " \"\"\"\n",
  3367. " Get domain name based on WHOIS domain data.\n",
  3368. " \"\"\"\n",
  3369. " def get_domain_name(self, url):\n",
  3370. " domain_name = self.get_whois_data(url).domain_name\n",
  3371. " \n",
  3372. " if type(domain_name) is list:\n",
  3373. " return domain_name[0].lower()\n",
  3374. " else:\n",
  3375. " return domain_name.lower()\n",
  3376. "\n",
  3377. "######################################\n",
  3378. " \"\"\"\n",
  3379. " Get initial and final URLs\n",
  3380. " \n",
  3381. " Compare whether the final (destination) URL\n",
  3382. " matches with the initial URL in a request.\n",
  3383. " \n",
  3384. " Returns a dict object.\n",
  3385. " \"\"\"\n",
  3386. " def get_startfinal_urls(self, url):\n",
  3387. " \n",
  3388. " response = self.set_session(url)\n",
  3389. " end_url = response.url\n",
  3390. " \n",
  3391. " start_match = False\n",
  3392. " final_match = False\n",
  3393. " \n",
  3394. " # dr = re.compile(r\"^([a-z]+://)?([^/]+)\")\n",
  3395. " # dr_group_lastindex = dr.match(url).lastindex\n",
  3396. " # domain_name = dr.match(url).group(dr_group_lastindex)\n",
  3397. " \n",
  3398. " domain_name = self.get_domain_name(url)\n",
  3399. " \n",
  3400. " if re.search(domain_name, end_url):\n",
  3401. " final_match = True\n",
  3402. " \n",
  3403. " dict_data = {\n",
  3404. " 'startfinal_urls': {\n",
  3405. " 'start_url': {\n",
  3406. " 'url': url\n",
  3407. " },\n",
  3408. " 'final_url': {\n",
  3409. " 'url': end_url, 'domain_match': final_match\n",
  3410. " }\n",
  3411. " }\n",
  3412. " }\n",
  3413. " \n",
  3414. " return dict_data\n",
  3415. "\n",
  3416. "######################################\n",
  3417. " \"\"\"\n",
  3418. " Get domain registrar\n",
  3419. " \n",
  3420. " Returns a dict object.\n",
  3421. " \"\"\"\n",
  3422. " def get_domain_registrar(self, url):\n",
  3423. " dict_data = {'domain_registrar': self.get_whois_data(url).registrar }\n",
  3424. " return dict_data\n",
  3425. "\n",
  3426. "######################################\n",
  3427. " \"\"\"\n",
  3428. " Do comparison between the domain name, extracted\n",
  3429. " from WHOIS domain data and contents of a title HTML\n",
  3430. " element, extracted from HTML data based on a given URL.\n",
  3431. " \n",
  3432. " Returns a dict object.\n",
  3433. " \"\"\"\n",
  3434. " def get_domain_title_match(self, url):\n",
  3435. " \n",
  3436. " domain_name = self.get_domain_name(url)\n",
  3437. " title = self.get_webpage_title(url)\n",
  3438. " \n",
  3439. " # If is string:\n",
  3440. " if type(domain_name) is str:\n",
  3441. " if re.search(domain_name, title, re.IGNORECASE):\n",
  3442. " match = True\n",
  3443. " else:\n",
  3444. " match = False\n",
  3445. " \n",
  3446. " # If is list:\n",
  3447. " elif type(domain_name) is list:\n",
  3448. " for d in domain_name:\n",
  3449. " if re.search(d, title, re.IGNORECASE):\n",
  3450. " match = True\n",
  3451. " break\n",
  3452. " else:\n",
  3453. " match = False\n",
  3454. " else:\n",
  3455. " match = False\n",
  3456. " \n",
  3457. " dict_data = {\n",
  3458. " 'webpage_title': title,\n",
  3459. " 'domain_in_webpage_title': match\n",
  3460. " }\n",
  3461. " \n",
  3462. " return dict_data\n",
  3463. "\n",
  3464. "######################################\n",
  3465. " \"\"\"\n",
  3466. " Get a single timestamp from given data\n",
  3467. " \n",
  3468. " Two scenarios are considered: dates argument is either\n",
  3469. " a list or a string. If it is a list, then we need\n",
  3470. " to decide which date value to extract.\n",
  3471. " \n",
  3472. " Returns a date object.\n",
  3473. " \"\"\"\n",
  3474. " def get_single_date(self, dates, newest=False):\n",
  3475. " \n",
  3476. " dates_epoch = []\n",
  3477. " \n",
  3478. " if type(dates) is list:\n",
  3479. " for d in dates:\n",
  3480. " dates_epoch.append(d.timestamp())\n",
  3481. " else:\n",
  3482. " dates_epoch.append(dates.timestamp())\n",
  3483. " \n",
  3484. " return datetime.fromtimestamp(sorted(dates_epoch, reverse=newest)[0])\n",
  3485. "\n",
  3486. "######################################\n",
  3487. " \"\"\"\n",
  3488. " Get domain time information based on WHOIS domain data.\n",
  3489. " \n",
  3490. " Returns a dict object.\n",
  3491. " \"\"\"\n",
  3492. " def get_domain_timeinfo(self, url):\n",
  3493. " \n",
  3494. " whois_data = self.get_whois_data(url)\n",
  3495. " domain_creation_date = self.get_single_date(whois_data.creation_date, newest = False)\n",
  3496. " domain_updated_date = self.get_single_date(whois_data.updated_date, newest = False)\n",
  3497. " domain_expiration_date = self.get_single_date(whois_data.expiration_date, newest = False)\n",
  3498. " \n",
  3499. " dict_data = {\n",
  3500. " 'domain_timestamps':\n",
  3501. " {\n",
  3502. " 'created': domain_creation_date.strftime(dateformat),\n",
  3503. " 'updated': domain_updated_date.strftime(dateformat),\n",
  3504. " 'expires': domain_expiration_date.strftime(dateformat)\n",
  3505. " }\n",
  3506. " }\n",
  3507. " \n",
  3508. " return dict_data\n",
  3509. "\n",
  3510. "######################################\n",
  3511. " \"\"\"\n",
  3512. " Get domain time information based on WHOIS domain data,\n",
  3513. " relative to the current date (UTC time).\n",
  3514. " \n",
  3515. " Returns a dict object.\n",
  3516. " \"\"\"\n",
  3517. " def get_domain_timeinfo_relative(self, url):\n",
  3518. " \n",
  3519. " date_now = datetime.utcnow()\n",
  3520. " \n",
  3521. " whois_data = self.get_whois_data(url)\n",
  3522. " domain_creation_date = self.get_single_date(whois_data.creation_date, newest = False)\n",
  3523. " domain_updated_date = self.get_single_date(whois_data.updated_date, newest = False)\n",
  3524. " domain_expiration_date = self.get_single_date(whois_data.expiration_date, newest = False)\n",
  3525. " \n",
  3526. " dict_data = {\n",
  3527. " 'domain_timestamps_relative':\n",
  3528. " {\n",
  3529. " 'current_date': (date_now.strftime(dateformat)),\n",
  3530. " 'created_days_ago': (date_now - domain_creation_date).days,\n",
  3531. " 'updated_days_ago': (date_now - domain_updated_date).days,\n",
  3532. " 'expires_days_left': (domain_expiration_date - date_now).days\n",
  3533. " }\n",
  3534. " }\n",
  3535. " \n",
  3536. " return dict_data\n",
  3537. "\n",
  3538. "######################################\n",
  3539. " \"\"\"\n",
  3540. " Determine whether URL matches syntaxes such as\n",
  3541. " '../foo/bar/'\n",
  3542. " '/foo/../../bar/,\n",
  3543. " 'https://foo.bar/foo/../'\n",
  3544. " \n",
  3545. " etc.\n",
  3546. " \n",
  3547. " Returns a boolean object.\n",
  3548. " \"\"\"\n",
  3549. " def is_multidot_url(self, url):\n",
  3550. " \n",
  3551. " multidot = re.compile(r\".*[.]{2}/.*\")\n",
  3552. " \n",
  3553. " if multidot.match(url):\n",
  3554. " return True\n",
  3555. " return False\n",
  3556. "\n",
  3557. "######################################\n",
  3558. " \"\"\"\n",
  3559. " Get HTML element data from HTML data contents.\n",
  3560. " \n",
  3561. " Two fetching methods are supported:\n",
  3562. " - A) use only HTML element/tag name and extract raw contents of\n",
  3563. " these tags\n",
  3564. " - B) use both HTML element/tag name and more fine-grained\n",
  3565. " inner attribute name to determine which HTML elements are extracted\n",
  3566. " \n",
  3567. " Special case - URL link references:\n",
  3568. " - attributes 'href' or 'src' are considered as link referrals and \n",
  3569. " they are handled in a special way\n",
  3570. " - A) link referrals to directly to domain are placed in 'self_refs' list\n",
  3571. " (patterns: '/', '#', '../' and '/<anything>')\n",
  3572. " - B) link referrals to external domains are placed in 'ext_refs' list\n",
  3573. " (patterns such as 'https://foo.bar.dot/fancysite' etc.)\n",
  3574. " \n",
  3575. " - Both A) and B) link categories have 'normal' and 'multidot' subcategories\n",
  3576. " - normal links do not contain pattern '../'\n",
  3577. " - multidot links contain '../' pattern\n",
  3578. " \n",
  3579. " Returns a dict object.\n",
  3580. " \"\"\"\n",
  3581. " \n",
  3582. " def get_tag_data(self, url, tag, attribute=None):\n",
  3583. " \n",
  3584. " html_data = self.get_html_data(url)\n",
  3585. " domain_name = self.get_domain_name(url)\n",
  3586. " data = []\n",
  3587. " \n",
  3588. " if attribute != None:\n",
  3589. " \n",
  3590. " for d in html_data.find_all(tag):\n",
  3591. " \n",
  3592. " # Ignore the HTML tag if it does not contain our attribute\n",
  3593. " if d.get(attribute) != None:\n",
  3594. " data.append(d.get(attribute))\n",
  3595. " \n",
  3596. " if attribute == 'href' or attribute == 'src':\n",
  3597. " \n",
  3598. " self_refs = { 'normal': [], 'multidot': []}\n",
  3599. " ext_refs = { 'normal': [], 'multidot': []}\n",
  3600. " \n",
  3601. " # Syntax: '#<anything>', '/<anything>', '../<anything>'\n",
  3602. " rs = re.compile(r\"^[/#]|^[.]{2}/.*\")\n",
  3603. " \n",
  3604. " # Syntax: '<text>:<text>/'\n",
  3605. " rd = re.compile(r\"^[a-z]+:[a-z]+/\")\n",
  3606. " \n",
  3607. " # Syntax examples:\n",
  3608. " # 'http://foo.bar/', 'https://foo.bar/, 'foo.bar/', 'https://virus.foo.bar/'\n",
  3609. " rl = re.compile(r\"^([a-z]+://)?([^/]*\" + domain_name + \"/)\")\n",
  3610. " \n",
  3611. " for s in data:\n",
  3612. " \n",
  3613. " # Ignore mailto links\n",
  3614. " if re.match(\"^mailto:\", s): continue\n",
  3615. " \n",
  3616. " if rs.match(s) or rl.match(s) or rd.match(s):\n",
  3617. " if self.is_multidot_url(s):\n",
  3618. " self_refs['multidot'].append(s)\n",
  3619. " else:\n",
  3620. " self_refs['normal'].append(s)\n",
  3621. " else:\n",
  3622. " \n",
  3623. " if self.is_multidot_url(s):\n",
  3624. " try:\n",
  3625. " ext_refs['multidot'].append({'url': s, 'registrar': self.get_whois_data(s).registrar })\n",
  3626. " except:\n",
  3627. " # Fallback if WHOIS query fails\n",
  3628. " ext_refs['normal'].append({'url': s, 'registrar': None })\n",
  3629. " pass\n",
  3630. " else:\n",
  3631. " try:\n",
  3632. " ext_refs['normal'].append({'url': s, 'registrar': self.get_whois_data(s).registrar })\n",
  3633. " except:\n",
  3634. " ext_refs['normal'].append({'url': s, 'registrar': None })\n",
  3635. " pass\n",
  3636. " \n",
  3637. " data = None\n",
  3638. " \n",
  3639. " dict_data = {\n",
  3640. " tag: {\n",
  3641. " attribute + '_ext': (ext_refs),\n",
  3642. " attribute + '_self': (self_refs)\n",
  3643. " }\n",
  3644. " }\n",
  3645. " \n",
  3646. " else:\n",
  3647. " dict_data = {\n",
  3648. " tag: {\n",
  3649. " attribute: (data)\n",
  3650. " }\n",
  3651. " }\n",
  3652. " \n",
  3653. " else:\n",
  3654. " for d in html_data.find_all(tag):\n",
  3655. " data.append(d.prettify())\n",
  3656. " \n",
  3657. " dict_data = {\n",
  3658. " tag: (data)\n",
  3659. " }\n",
  3660. " \n",
  3661. " return dict_data\n",
  3662. "\n",
  3663. "######################################\n",
  3664. " \"\"\"\n",
  3665. " How many external URL links have same registrar than\n",
  3666. " the webpage itself?\n",
  3667. " \"\"\"\n",
  3668. " def get_registrar_count(self, registrar, urls):\n",
  3669. " \n",
  3670. " i = 0\n",
  3671. " \n",
  3672. " for u in urls:\n",
  3673. " for k,v in u.items():\n",
  3674. " if k == 'registrar' and v == registrar:\n",
  3675. " i += 1\n",
  3676. " \n",
  3677. " o = len(urls) - i\n",
  3678. " \n",
  3679. " dict_data = {\n",
  3680. " 'same_registrar_count': i,\n",
  3681. " 'other_registrar_count': o\n",
  3682. " }\n",
  3683. " \n",
  3684. " return dict_data\n",
  3685. "\n",
  3686. "######################################\n",
  3687. "\n",
  3688. " \"\"\"\n",
  3689. " Get values existing in a dict object,\n",
  3690. " based on a known key string.\n",
  3691. " \n",
  3692. " Returns a list object.\n",
  3693. " \n",
  3694. " TODO: Major re-work for the fetch function\n",
  3695. "\n",
  3696. " TODO: Support for more sophisticated JSON key string filtering\n",
  3697. " (possibility to use multiple keys for filtering)\n",
  3698. " \"\"\"\n",
  3699. " class json_fetcher(object):\n",
  3700. "\n",
  3701. " def __init__(self, dict_data, json_key):\n",
  3702. " self.json_dict = json.loads(json.dumps(dict_data))\n",
  3703. " self.json_key = json_key\n",
  3704. "\n",
  3705. " ##########\n",
  3706. " # Ref: https://www.codespeedy.com/how-to-loop-through-json-with-subkeys-in-python/\n",
  3707. " def fetch(self, jdata):\n",
  3708. "\n",
  3709. " if isinstance(jdata, dict):\n",
  3710. "\n",
  3711. " for k,v in jdata.items():\n",
  3712. " if k == self.json_key:\n",
  3713. " yield v\n",
  3714. " elif isinstance(v, dict):\n",
  3715. " for val in self.fetch(v):\n",
  3716. " yield val\n",
  3717. " elif isinstance(v, list):\n",
  3718. " for l in v:\n",
  3719. " if isinstance(l, dict):\n",
  3720. " for ka,va in l.items():\n",
  3721. " if ka == self.json_key:\n",
  3722. " yield va\n",
  3723. "\n",
  3724. " elif isinstance(jdata, list):\n",
  3725. " for l in jdata:\n",
  3726. " if isinstance(l, dict):\n",
  3727. " for k,v in l.items():\n",
  3728. " if k == self.json_key:\n",
  3729. " yield v\n",
  3730. " elif isinstance(l, list):\n",
  3731. " for lb in v:\n",
  3732. " for ka,va in lb.items():\n",
  3733. " if ka == self.json_key:\n",
  3734. " yield va\n",
  3735. "\n",
  3736. " ##########\n",
  3737. " def get_data(self, flatten=True):\n",
  3738. "\n",
  3739. " data_extract = []\n",
  3740. " flat_data = []\n",
  3741. "\n",
  3742. " for i in self.fetch(self.json_dict):\n",
  3743. " data_extract.append(i)\n",
  3744. "\n",
  3745. " # Flatten possible nested lists\n",
  3746. " # (i.e. JSON data contains multiple keys in\n",
  3747. " # different nested sections)\n",
  3748. " def get_data_extract(ld):\n",
  3749. " for l in ld:\n",
  3750. " if isinstance(l, list):\n",
  3751. " for la in get_data_extract(l):\n",
  3752. " yield la\n",
  3753. " else:\n",
  3754. " yield l\n",
  3755. "\n",
  3756. " if flatten == True:\n",
  3757. " for u in get_data_extract(data_extract):\n",
  3758. " flat_data.append(u)\n",
  3759. " \n",
  3760. " return flat_data\n",
  3761. " else:\n",
  3762. " return data_extract\n",
  3763. "\n",
  3764. "######################################\n",
  3765. " \"\"\"\n",
  3766. " Compile URL related data.\n",
  3767. " \"\"\"\n",
  3768. " def get_url_data(self, url):\n",
  3769. " \n",
  3770. " # Dict object for simple, non-nested data\n",
  3771. " data_simple = {}\n",
  3772. "\n",
  3773. " # Pre-defined dict object for specific data sets\n",
  3774. " webpage_data = {}\n",
  3775. " \n",
  3776. " startfinal_url = self.get_startfinal_urls(url)\n",
  3777. " redirect_url = self.get_url_redirects(url)\n",
  3778. " domain_registrar = self.get_domain_registrar(url)\n",
  3779. " domaintitle_match = self.get_domain_title_match(url)\n",
  3780. " \n",
  3781. " domain_time_relative = self.get_domain_timeinfo_relative(url)\n",
  3782. " domain_time = self.get_domain_timeinfo(url)\n",
  3783. " \n",
  3784. " html_element_iframe = self.get_tag_data(url, 'iframe')\n",
  3785. " html_element_a_href = self.get_tag_data(url, 'a', link_refs['a'])\n",
  3786. " html_element_img_src = self.get_tag_data(url, 'img', link_refs['img'])\n",
  3787. " html_element_script_src = self.get_tag_data(url, 'script', link_refs['script'])\n",
  3788. "\n",
  3789. " iframes_count = {\n",
  3790. " 'iframes_count':\n",
  3791. " len(self.json_fetcher(html_element_iframe, 'iframe').get_data())\n",
  3792. " }\n",
  3793. " \n",
  3794. " multidot_urls_count = {\n",
  3795. " 'multidot_url_count':\n",
  3796. " len(self.json_fetcher(html_element_a_href, 'multidot').get_data()) + len(self.json_fetcher(html_element_img_src, 'multidot').get_data()) + len(self.json_fetcher(html_element_script_src, 'multidot').get_data())\n",
  3797. " }\n",
  3798. " \n",
  3799. " ###################\n",
  3800. " def get_total_registrars():\n",
  3801. "\n",
  3802. " same_registrar_counts = 0\n",
  3803. " other_registrar_counts = 0\n",
  3804. " for k,v in link_refs.items():\n",
  3805. " \n",
  3806. " html_element = self.get_tag_data(url, k, v)\n",
  3807. " \n",
  3808. " same_registrar_counts += self.get_registrar_count(\n",
  3809. " domain_registrar['domain_registrar'],\n",
  3810. " html_element[k][v + '_ext']['normal']\n",
  3811. " )['same_registrar_count']\n",
  3812. " \n",
  3813. " other_registrar_counts += self.get_registrar_count(\n",
  3814. " domain_registrar['domain_registrar'],\n",
  3815. " html_element[k][v + '_ext']['normal']\n",
  3816. " )['other_registrar_count']\n",
  3817. " \n",
  3818. " registrar_counts = {\n",
  3819. " 'same_registrar_count': same_registrar_counts,\n",
  3820. " 'other_registrar_count': other_registrar_counts\n",
  3821. " }\n",
  3822. " return registrar_counts\n",
  3823. " \n",
  3824. " # Avoid unnecessary nesting of the following data\n",
  3825. " data_simple.update(domain_registrar)\n",
  3826. " data_simple.update(domaintitle_match)\n",
  3827. " data_simple.update(iframes_count)\n",
  3828. " data_simple.update(multidot_urls_count)\n",
  3829. " data_simple.update(get_total_registrars())\n",
  3830. " \n",
  3831. " url_data = dict({\n",
  3832. " url: [\n",
  3833. " data_simple,\n",
  3834. " startfinal_url,\n",
  3835. " {'redirects': redirect_url},\n",
  3836. " \n",
  3837. " domain_time_relative,\n",
  3838. " domain_time,\n",
  3839. " \n",
  3840. " {'webpage_data': [\n",
  3841. " html_element_iframe,\n",
  3842. " html_element_a_href,\n",
  3843. " html_element_img_src,\n",
  3844. " html_element_script_src\n",
  3845. " ]\n",
  3846. " }\n",
  3847. " ]\n",
  3848. " })\n",
  3849. " \n",
  3850. " return url_data\n",
  3851. "\n",
  3852. "\n",
  3853. "\n",
  3854. "class write_operations(object):\n",
  3855. "\n",
  3856. " def __init__(self):\n",
  3857. " self.filename = filename\n",
  3858. "\n",
  3859. "######################################\n",
  3860. " \"\"\"\n",
  3861. " Set JSON file name, append number suffix\n",
  3862. " # if file exists already.\n",
  3863. " \n",
  3864. " Returns file name path.\n",
  3865. " \"\"\"\n",
  3866. " def set_filename(self):\n",
  3867. " \n",
  3868. " c = 0\n",
  3869. " while True:\n",
  3870. " if os.path.exists(self.filename):\n",
  3871. " if c == 0:\n",
  3872. " self.filename = self.filename + \".\" + str(c)\n",
  3873. " else:\n",
  3874. " self.filename = re.sub(\"[0-9]+$\", str(c), self.filename)\n",
  3875. " else:\n",
  3876. " break\n",
  3877. " c += 1\n",
  3878. " return self.filename\n",
  3879. "\n",
  3880. "######################################\n",
  3881. " \"\"\"\n",
  3882. " Append to a JSON file.\n",
  3883. " \"\"\"\n",
  3884. " def write_to_file(self, data):\n",
  3885. " \n",
  3886. " try:\n",
  3887. " json_file = open(self.filename, \"a\")\n",
  3888. " json_file.write(data)\n",
  3889. " json_file.close()\n",
  3890. " return 0\n",
  3891. " except:\n",
  3892. " return 1\n",
  3893. "\n",
  3894. "######################################\n",
  3895. " \"\"\"\n",
  3896. " Fetch all pre-defined URLs.\n",
  3897. " \"\"\"\n",
  3898. " def fetch_and_store_url_data(self, urls, use_file):\n",
  3899. "\n",
  3900. " data_parts = {}\n",
  3901. " fetch_json_data = json_url_data()\n",
  3902. "\n",
  3903. " for u in urls:\n",
  3904. " print(\"Fetching URL data: %s\" % u)\n",
  3905. " try:\n",
  3906. " data_parts.update(fetch_json_data.get_url_data(u))\n",
  3907. " except:\n",
  3908. " print(\"Failed: %s\" % u)\n",
  3909. " pass\n",
  3910. "\n",
  3911. " json_data = json.dumps(data_parts)\n",
  3912. "\n",
  3913. " if use_file == True:\n",
  3914. " self.write_to_file(json_data)\n",
  3915. "\n",
  3916. " return json_data\n",
  3917. "\n",
  3918. "######################################\n",
  3919. "\"\"\"\n",
  3920. "Visualize & summarize data.\n",
  3921. "\"\"\"\n",
  3922. "\n",
  3923. "class data_visualization(object):\n",
  3924. "\n",
  3925. " def __init__(self, url, json_data):\n",
  3926. " self.url = url\n",
  3927. " self.json_data = json_data\n",
  3928. "\n",
  3929. " self.data = json.loads(json.dumps(self.json_data)).get(self.url)\n",
  3930. " self.json_url_obj = json_url_data()\n",
  3931. " self.domain_registrar = self.json_url_obj.get_domain_registrar(self.url)['domain_registrar']\n",
  3932. " self.webpage_data = self.json_url_obj.json_fetcher(self.data, 'webpage_data').get_data()\n",
  3933. "\n",
  3934. " def get_urls_count_summary(self):\n",
  3935. "\n",
  3936. " unique_refs = []\n",
  3937. "\n",
  3938. " for k,v in link_refs.items():\n",
  3939. " if v in unique_refs: continue\n",
  3940. " unique_refs.append(v)\n",
  3941. "\n",
  3942. " def link_count(refs, suffix):\n",
  3943. "\n",
  3944. " urls_cnt = 0\n",
  3945. "\n",
  3946. " for u in self.webpage_data:\n",
  3947. " for l in refs:\n",
  3948. " urls = self.json_url_obj.json_fetcher(u, l + suffix).get_data()\n",
  3949. " for n in urls:\n",
  3950. " urls_cnt += len(n['normal'])\n",
  3951. " urls_cnt += len(n['multidot'])\n",
  3952. " return urls_cnt\n",
  3953. "\n",
  3954. " data = {\n",
  3955. " 'local_urls': link_count(unique_refs, '_self'),\n",
  3956. " 'external_urls': link_count(unique_refs, '_ext')\n",
  3957. " }\n",
  3958. " \n",
  3959. " return data\n",
  3960. "\n",
  3961. " def get_registrars(self):\n",
  3962. "\n",
  3963. " registrars = []\n",
  3964. " #registrars.append(self.domain_registrar)\n",
  3965. "\n",
  3966. " for w in self.webpage_data:\n",
  3967. " webpage_registrars = self.json_url_obj.json_fetcher(w, 'registrar').get_data()\n",
  3968. " for wa in webpage_registrars:\n",
  3969. " if wa != None:\n",
  3970. " registrars.append(wa)\n",
  3971. " return registrars\n",
  3972. "\n",
  3973. " def get_registrar_count_summary(self):\n",
  3974. " \n",
  3975. " domain_counter = dict(Counter(self.get_registrars()))\n",
  3976. " data = {'fetched_domains': domain_counter, 'url_domain_registrar': self.domain_registrar }\n",
  3977. " return data\n",
  3978. "\n",
  3979. "######################################\n",
  3980. "\"\"\"\n",
  3981. "Execute the main program code.\n",
  3982. "\n",
  3983. "TODO: this code must figure out the correct JSON file\n",
  3984. "if multiple generated files are present.\n",
  3985. "\"\"\"\n",
  3986. "if __name__ == '__main__':\n",
  3987. "\n",
  3988. " if plot_only == False:\n",
  3989. " write_obj = write_operations()\n",
  3990. " write_obj.set_filename()\n",
  3991. " data = write_obj.fetch_and_store_url_data(urls, use_file)\n",
  3992. "\n",
  3993. " url_str_pattern = re.compile(r\"(^[a-z]+://)?([^/]*)\")\n",
  3994. "\n",
  3995. " if os.path.exists(filename):\n",
  3996. " with open(filename, \"r\") as json_file:\n",
  3997. " json_data = json.load(json_file)\n",
  3998. " else:\n",
  3999. " json_data = data\n",
  4000. "\n",
  4001. " # Get URLs from an available JSON data\n",
  4002. " for key_url in json_data.keys():\n",
  4003. " \n",
  4004. " print(\"Generating statistics: %s\" % key_url)\n",
  4005. "\n",
  4006. " fig = plt.figure()\n",
  4007. " fig_params = {\n",
  4008. " 'xtick.labelsize': 8,\n",
  4009. " 'figure.figsize': [9,8]\n",
  4010. " # 'figure.constrained_layout.use': True\n",
  4011. " }\n",
  4012. " plt.rcParams.update(fig_params)\n",
  4013. " \n",
  4014. " domain_string = url_str_pattern.split(key_url)[2].replace('.','')\n",
  4015. " summary = data_visualization(key_url, json_data)\n",
  4016. " \n",
  4017. " summary_registrars = summary.get_registrar_count_summary()['fetched_domains']\n",
  4018. "\n",
  4019. " x_r = list(summary_registrars.keys())\n",
  4020. " y_r = list(summary_registrars.values())\n",
  4021. " \n",
  4022. " # Show bar values\n",
  4023. " for index,data in enumerate(y_r):\n",
  4024. " plt.text(x=index, y=data+0.5, s=data, fontdict=dict(fontsize=8))\n",
  4025. " \n",
  4026. " title_r = \"Domains associated with HTML URL data (\" + key_url + \")\"\n",
  4027. " xlabel_r = \"Fetched domains\"\n",
  4028. " ylabel_r = \"Domain count\"\n",
  4029. "\n",
  4030. " plt.bar(x_r, y_r, color=\"green\", edgecolor=\"black\")\n",
  4031. " plt.title(title_r)\n",
  4032. " plt.xlabel(xlabel_r)\n",
  4033. " plt.ylabel(ylabel_r)\n",
  4034. " plt.xticks(rotation=45, horizontalalignment=\"right\")\n",
  4035. "\n",
  4036. " if save_plot_images == True:\n",
  4037. " plt.savefig(os.getcwd() + \"/\" + \"domain_figure_\" + domain_string + \".png\", dpi=plot_images_dpi)\n",
  4038. " plt.show()\n",
  4039. "\n",
  4040. " #fig_u = plt.figure()\n",
  4041. " \n",
  4042. " #summary_urls = summary.get_urls_count_summary()\n",
  4043. " \n",
  4044. " #x_u = list(summary_urls.keys())\n",
  4045. " #y_u = list(summary_urls.values())\n",
  4046. " #title_u = \"Local and external URL references (\" + key_url + \")\"\n",
  4047. " #xlabel_u = \"Fetched URLs\"\n",
  4048. " #ylabel_u = \"URL count\"\n",
  4049. " \n",
  4050. " #plt.bar(x_u, y_u, color=\"blue\", edgecolor='black')\n",
  4051. " #plt.title(title_u)\n",
  4052. " #plt.xlabel(xlabel_u)\n",
  4053. " #plt.ylabel(ylabel_u)\n",
  4054. " #plt.show()\n"
  4055. ]
  4056. },
  4057. {
  4058. "cell_type": "code",
  4059. "execution_count": null,
  4060. "metadata": {},
  4061. "outputs": [],
  4062. "source": []
  4063. },
  4064. {
  4065. "cell_type": "code",
  4066. "execution_count": null,
  4067. "metadata": {},
  4068. "outputs": [],
  4069. "source": []
  4070. }
  4071. ],
  4072. "metadata": {
  4073. "kernelspec": {
  4074. "display_name": "Python 3",
  4075. "language": "python",
  4076. "name": "python3"
  4077. },
  4078. "language_info": {
  4079. "codemirror_mode": {
  4080. "name": "ipython",
  4081. "version": 3
  4082. },
  4083. "file_extension": ".py",
  4084. "mimetype": "text/x-python",
  4085. "name": "python",
  4086. "nbconvert_exporter": "python",
  4087. "pygments_lexer": "ipython3",
  4088. "version": "3.8.5"
  4089. }
  4090. },
  4091. "nbformat": 4,
  4092. "nbformat_minor": 4
  4093. }