We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
oct2py v >= 0.3.1 doesn't need h5py anymore
The octave magic docs/examples should update this  information.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `IPython/extensions/octavemagic.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 """
3 ===========
4 octavemagic
5 ===========
6 
7 Magics for interacting with Octave via oct2py.
8 
9 .. note::
10 
11   The ``oct2py`` module needs to be installed separately, and in turn depends
12   on ``h5py``.  Both can be obtained using ``easy_install`` or ``pip``.
13 
14 Usage
15 =====
16 
17 ``%octave``
18 
19 {OCTAVE_DOC}
20 
21 ``%octave_push``
22 
23 {OCTAVE_PUSH_DOC}
24 
25 ``%octave_pull``
26 
27 {OCTAVE_PULL_DOC}
28 
29 """
30 
31 #-----------------------------------------------------------------------------
32 #  Copyright (C) 2012 The IPython Development Team
33 #
34 #  Distributed under the terms of the BSD License.  The full license is in
35 #  the file COPYING, distributed as part of this software.
36 #-----------------------------------------------------------------------------
37 
38 import tempfile
39 from glob import glob
40 from shutil import rmtree
41 
42 import numpy as np
43 import oct2py
44 from xml.dom import minidom
45 
46 from IPython.core.displaypub import publish_display_data
47 from IPython.core.magic import (Magics, magics_class, line_magic,
48                                 line_cell_magic)
49 from IPython.testing.skipdoctest import skip_doctest
50 from IPython.core.magic_arguments import (
51     argument, magic_arguments, parse_argstring
52 )
53 from IPython.utils.py3compat import unicode_to_str
54 
55 class OctaveMagicError(oct2py.Oct2PyError):
56     pass
57 
58 _mimetypes = {'png' : 'image/png',
59              'svg' : 'image/svg+xml',
60              'jpg' : 'image/jpeg',
61               'jpeg': 'image/jpeg'}
62 
63 @magics_class
64 class OctaveMagics(Magics):
65     """A set of magics useful for interactive work with Octave via oct2py.
66     """
67     def __init__(self, shell):
68         """
69         Parameters
70         ----------
71         shell : IPython shell
72 
73         """
74         super(OctaveMagics, self).__init__(shell)
75         self._oct = oct2py.Oct2Py()
76         self._plot_format = 'png'
77 
78         # Allow publish_display_data to be overridden for
79         # testing purposes.
80         self._publish_display_data = publish_display_data
81 
82 
83     def _fix_gnuplot_svg_size(self, image, size=None):
84         """
85         GnuPlot SVGs do not have height/width attributes.  Set
86         these to be the same as the viewBox, so that the browser
87         scales the image correctly.
88 
89         Parameters
90         ----------
91         image : str
92             SVG data.
93         size : tuple of int
94             Image width, height.
95 
96         """
97         (svg,) = minidom.parseString(image).getElementsByTagName('svg')
98         viewbox = svg.getAttribute('viewBox').split(' ')
99 
100         if size is not None:
101             width, height = size
102         else:
103             width, height = viewbox[2:]
104 
105         svg.setAttribute('width', '%dpx' % width)
106         svg.setAttribute('height', '%dpx' % height)
107         return svg.toxml()
108 
109 
110     @skip_doctest
111     @line_magic
112     def octave_push(self, line):
113         '''
114         Line-level magic that pushes a variable to Octave.
115 
116         `line` should be made up of whitespace separated variable names in the
117         IPython namespace::
118 
119             In [7]: import numpy as np
120 
121             In [8]: X = np.arange(5)
122 
123             In [9]: X.mean()
124             Out[9]: 2.0
125 
126             In [10]: %octave_push X
127 
128             In [11]: %octave mean(X)
129             Out[11]: 2.0
130 
131         '''
132         inputs = line.split(' ')
133         for input in inputs:
134             input = unicode_to_str(input)
135             self._oct.put(input, self.shell.user_ns[input])
136 
137 
138     @skip_doctest
139     @line_magic
140     def octave_pull(self, line):
141         '''
142         Line-level magic that pulls a variable from Octave.
143 
144             In [18]: _ = %octave x = [1 2; 3 4]; y = 'hello'
145 
146             In [19]: %octave_pull x y
147 
148             In [20]: x
149             Out[20]:
150             array([[ 1.,  2.],
151                    [ 3.,  4.]])
152 
153             In [21]: y
154             Out[21]: 'hello'
155 
156         '''
157         outputs = line.split(' ')
158         for output in outputs:
159             output = unicode_to_str(output)
160             self.shell.push({output: self._oct.get(output)})
161 
162 
163     @skip_doctest
164     @magic_arguments()
165     @argument(
166         '-i', '--input', action='append',
167         help='Names of input variables to be pushed to Octave. Multiple names '
168              'can be passed, separated by commas with no whitespace.'
169         )
170     @argument(
171         '-o', '--output', action='append',
172         help='Names of variables to be pulled from Octave after executing cell '
173              'body. Multiple names can be passed, separated by commas with no '
174              'whitespace.'
175         )
176     @argument(
177         '-s', '--size', action='store',
178         help='Pixel size of plots, "width,height". Default is "-s 400,250".'
179         )
180     @argument(
181         '-f', '--format', action='store',
182         help='Plot format (png, svg or jpg).'
183         )
184 
185     @argument(
186         'code',
187         nargs='*',
188         )
189     @line_cell_magic
190     def octave(self, line, cell=None):
191         '''
192         Execute code in Octave, and pull some of the results back into the
193         Python namespace.
194 
195             In [9]: %octave X = [1 2; 3 4]; mean(X)
196             Out[9]: array([[ 2., 3.]])
197 
198         As a cell, this will run a block of Octave code, without returning any
199         value::
200 
201             In [10]: %%octave
202                ....: p = [-2, -1, 0, 1, 2]
203                ....: polyout(p, 'x')
204 
205             -2*x^4 - 1*x^3 + 0*x^2 + 1*x^1 + 2
206 
207         In the notebook, plots are published as the output of the cell, e.g.
208 
209         %octave plot([1 2 3], [4 5 6])
210 
211         will create a line plot.
212 
213         Objects can be passed back and forth between Octave and IPython via the
214         -i and -o flags in line::
215 
216             In [14]: Z = np.array([1, 4, 5, 10])
217 
218             In [15]: %octave -i Z mean(Z)
219             Out[15]: array([ 5.])
220 
221 
222             In [16]: %octave -o W W = Z * mean(Z)
223             Out[16]: array([  5.,  20.,  25.,  50.])
224 
225             In [17]: W
226             Out[17]: array([  5.,  20.,  25.,  50.])
227 
228         The size and format of output plots can be specified::
229 
230             In [18]: %%octave -s 600,800 -f svg
231                 ...: plot([1, 2, 3]);
232 
233         '''
234         args = parse_argstring(self.octave, line)
235 
236         # arguments 'code' in line are prepended to the cell lines
237         if cell is None:
238             code = ''
239             return_output = True
240             line_mode = True
241         else:
242             code = cell
243             return_output = False
244             line_mode = False
245 
246         code = ' '.join(args.code) + code
247 
248         if args.input:
249             for input in ','.join(args.input).split(','):
250                 input = unicode_to_str(input)
251                 self._oct.put(input, self.shell.user_ns[input])
252 
253         # generate plots in a temporary directory
254         plot_dir = tempfile.mkdtemp()
255         if args.size is not None:
256             size = args.size
257         else:
258             size = '400,240'
259 
260         if args.format is not None:
261             plot_format = args.format
262         else:
263             plot_format = 'png'
264 
265         pre_call = '''
266         global __ipy_figures = [];
267         page_screen_output(0);
268 
269         function fig_create(src, event)
270           global __ipy_figures;
271           __ipy_figures(size(__ipy_figures) + 1) = src;
272           set(src, "visible", "off");
273         end
274 
275         set(0, 'DefaultFigureCreateFcn', @fig_create);
276 
277         close all;
278         clear ans;
279 
280         # ___<end_pre_call>___ #
281         '''
282 
283         post_call = '''
284         # ___<start_post_call>___ #
285 
286         # Save output of the last execution
287         if exist("ans") == 1
288           _ = ans;
289         else
290           _ = nan;
291         end
292 
293         for f = __ipy_figures
294           outfile = sprintf('%(plot_dir)s/__ipy_oct_fig_%%03d.png', f);
295           try
296             print(f, outfile, '-d%(plot_format)s', '-tight', '-S%(size)s');
297           end
298         end
299 
300         ''' % locals()
301 
302         code = ' '.join((pre_call, code, post_call))
303         try:
304             text_output = self._oct.run(code, verbose=False)
305         except (oct2py.Oct2PyError) as exception:
306             msg = exception.message
307             msg = msg.split('# ___<end_pre_call>___ #')[1]
308             msg = msg.split('# ___<start_post_call>___ #')[0]
309             raise OctaveMagicError('Octave could not complete execution.  '
310                                    'Traceback (currently broken in oct2py): %s'
311                                    % msg)
312 
313         key = 'OctaveMagic.Octave'
314         display_data = []
315 
316         # Publish text output
317         if text_output:
318             display_data.append((key, {'text/plain': text_output}))
319 
320         # Publish images
321         images = [open(imgfile, 'rb').read() for imgfile in \
322                   glob("%s/*" % plot_dir)]
323         rmtree(plot_dir)
324 
325         plot_mime_type = _mimetypes.get(plot_format, 'image/png')
326         width, height = [int(s) for s in size.split(',')]
327         for image in images:
328             if plot_format == 'svg':
329                 image = self._fix_gnuplot_svg_size(image, size=(width, height))
330             display_data.append((key, {plot_mime_type: image}))
331 
332         if args.output:
333             for output in ','.join(args.output).split(','):
334                 output = unicode_to_str(output)
335                 self.shell.push({output: self._oct.get(output)})
336 
337         for source, data in display_data:
338             self._publish_display_data(source, data)
339 
340         if return_output:
341             ans = self._oct.get('_')
342 
343             # Unfortunately, Octave doesn't have a "None" object,
344             # so we can't return any NaN outputs
345             if np.isscalar(ans) and np.isnan(ans):
346                 ans = None
347 
348             return ans
349 
350 
351 __doc__ = __doc__.format(
352     OCTAVE_DOC = ' '*8 + OctaveMagics.octave.__doc__,
353     OCTAVE_PUSH_DOC = ' '*8 + OctaveMagics.octave_push.__doc__,
354     OCTAVE_PULL_DOC = ' '*8 + OctaveMagics.octave_pull.__doc__
355     )
356 
357 
358 _loaded = False
359 def load_ipython_extension(ip):
360     """Load the extension in IPython."""
361     global _loaded
362     if not _loaded:
363         ip.register_magics(OctaveMagics)
364         _loaded = True
365
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/IPython/extensions/octavemagic.py b/IPython/extensions/octavemagic.py
--- a/IPython/extensions/octavemagic.py
+++ b/IPython/extensions/octavemagic.py
@@ -8,8 +8,8 @@
 
 .. note::
 
-  The ``oct2py`` module needs to be installed separately, and in turn depends
-  on ``h5py``.  Both can be obtained using ``easy_install`` or ``pip``.
+  The ``oct2py`` module needs to be installed separately and
+  can be obtained using ``easy_install`` or ``pip``.
 
 Usage
 =====

{"golden_diff": "diff --git a/IPython/extensions/octavemagic.py b/IPython/extensions/octavemagic.py\n--- a/IPython/extensions/octavemagic.py\n+++ b/IPython/extensions/octavemagic.py\n@@ -8,8 +8,8 @@\n \n .. note::\n \n-  The ``oct2py`` module needs to be installed separately, and in turn depends\n-  on ``h5py``.  Both can be obtained using ``easy_install`` or ``pip``.\n+  The ``oct2py`` module needs to be installed separately and\n+  can be obtained using ``easy_install`` or ``pip``.\n \n Usage\n =====\n", "issue": "oct2py v >= 0.3.1 doesn't need h5py anymore\nThe octave magic docs/examples should update this  information.\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"\n===========\noctavemagic\n===========\n\nMagics for interacting with Octave via oct2py.\n\n.. note::\n\n  The ``oct2py`` module needs to be installed separately, and in turn depends\n  on ``h5py``.  Both can be obtained using ``easy_install`` or ``pip``.\n\nUsage\n=====\n\n``%octave``\n\n{OCTAVE_DOC}\n\n``%octave_push``\n\n{OCTAVE_PUSH_DOC}\n\n``%octave_pull``\n\n{OCTAVE_PULL_DOC}\n\n\"\"\"\n\n#-----------------------------------------------------------------------------\n#  Copyright (C) 2012 The IPython Development Team\n#\n#  Distributed under the terms of the BSD License.  The full license is in\n#  the file COPYING, distributed as part of this software.\n#-----------------------------------------------------------------------------\n\nimport tempfile\nfrom glob import glob\nfrom shutil import rmtree\n\nimport numpy as np\nimport oct2py\nfrom xml.dom import minidom\n\nfrom IPython.core.displaypub import publish_display_data\nfrom IPython.core.magic import (Magics, magics_class, line_magic,\n                                line_cell_magic)\nfrom IPython.testing.skipdoctest import skip_doctest\nfrom IPython.core.magic_arguments import (\n    argument, magic_arguments, parse_argstring\n)\nfrom IPython.utils.py3compat import unicode_to_str\n\nclass OctaveMagicError(oct2py.Oct2PyError):\n    pass\n\n_mimetypes = {'png' : 'image/png',\n             'svg' : 'image/svg+xml',\n             'jpg' : 'image/jpeg',\n              'jpeg': 'image/jpeg'}\n\n@magics_class\nclass OctaveMagics(Magics):\n    \"\"\"A set of magics useful for interactive work with Octave via oct2py.\n    \"\"\"\n    def __init__(self, shell):\n        \"\"\"\n        Parameters\n        ----------\n        shell : IPython shell\n\n        \"\"\"\n        super(OctaveMagics, self).__init__(shell)\n        self._oct = oct2py.Oct2Py()\n        self._plot_format = 'png'\n\n        # Allow publish_display_data to be overridden for\n        # testing purposes.\n        self._publish_display_data = publish_display_data\n\n\n    def _fix_gnuplot_svg_size(self, image, size=None):\n        \"\"\"\n        GnuPlot SVGs do not have height/width attributes.  Set\n        these to be the same as the viewBox, so that the browser\n        scales the image correctly.\n\n        Parameters\n        ----------\n        image : str\n            SVG data.\n        size : tuple of int\n            Image width, height.\n\n        \"\"\"\n        (svg,) = minidom.parseString(image).getElementsByTagName('svg')\n        viewbox = svg.getAttribute('viewBox').split(' ')\n\n        if size is not None:\n            width, height = size\n        else:\n            width, height = viewbox[2:]\n\n        svg.setAttribute('width', '%dpx' % width)\n        svg.setAttribute('height', '%dpx' % height)\n        return svg.toxml()\n\n\n    @skip_doctest\n    @line_magic\n    def octave_push(self, line):\n        '''\n        Line-level magic that pushes a variable to Octave.\n\n        `line` should be made up of whitespace separated variable names in the\n        IPython namespace::\n\n            In [7]: import numpy as np\n\n            In [8]: X = np.arange(5)\n\n            In [9]: X.mean()\n            Out[9]: 2.0\n\n            In [10]: %octave_push X\n\n            In [11]: %octave mean(X)\n            Out[11]: 2.0\n\n        '''\n        inputs = line.split(' ')\n        for input in inputs:\n            input = unicode_to_str(input)\n            self._oct.put(input, self.shell.user_ns[input])\n\n\n    @skip_doctest\n    @line_magic\n    def octave_pull(self, line):\n        '''\n        Line-level magic that pulls a variable from Octave.\n\n            In [18]: _ = %octave x = [1 2; 3 4]; y = 'hello'\n\n            In [19]: %octave_pull x y\n\n            In [20]: x\n            Out[20]:\n            array([[ 1.,  2.],\n                   [ 3.,  4.]])\n\n            In [21]: y\n            Out[21]: 'hello'\n\n        '''\n        outputs = line.split(' ')\n        for output in outputs:\n            output = unicode_to_str(output)\n            self.shell.push({output: self._oct.get(output)})\n\n\n    @skip_doctest\n    @magic_arguments()\n    @argument(\n        '-i', '--input', action='append',\n        help='Names of input variables to be pushed to Octave. Multiple names '\n             'can be passed, separated by commas with no whitespace.'\n        )\n    @argument(\n        '-o', '--output', action='append',\n        help='Names of variables to be pulled from Octave after executing cell '\n             'body. Multiple names can be passed, separated by commas with no '\n             'whitespace.'\n        )\n    @argument(\n        '-s', '--size', action='store',\n        help='Pixel size of plots, \"width,height\". Default is \"-s 400,250\".'\n        )\n    @argument(\n        '-f', '--format', action='store',\n        help='Plot format (png, svg or jpg).'\n        )\n\n    @argument(\n        'code',\n        nargs='*',\n        )\n    @line_cell_magic\n    def octave(self, line, cell=None):\n        '''\n        Execute code in Octave, and pull some of the results back into the\n        Python namespace.\n\n            In [9]: %octave X = [1 2; 3 4]; mean(X)\n            Out[9]: array([[ 2., 3.]])\n\n        As a cell, this will run a block of Octave code, without returning any\n        value::\n\n            In [10]: %%octave\n               ....: p = [-2, -1, 0, 1, 2]\n               ....: polyout(p, 'x')\n\n            -2*x^4 - 1*x^3 + 0*x^2 + 1*x^1 + 2\n\n        In the notebook, plots are published as the output of the cell, e.g.\n\n        %octave plot([1 2 3], [4 5 6])\n\n        will create a line plot.\n\n        Objects can be passed back and forth between Octave and IPython via the\n        -i and -o flags in line::\n\n            In [14]: Z = np.array([1, 4, 5, 10])\n\n            In [15]: %octave -i Z mean(Z)\n            Out[15]: array([ 5.])\n\n\n            In [16]: %octave -o W W = Z * mean(Z)\n            Out[16]: array([  5.,  20.,  25.,  50.])\n\n            In [17]: W\n            Out[17]: array([  5.,  20.,  25.,  50.])\n\n        The size and format of output plots can be specified::\n\n            In [18]: %%octave -s 600,800 -f svg\n                ...: plot([1, 2, 3]);\n\n        '''\n        args = parse_argstring(self.octave, line)\n\n        # arguments 'code' in line are prepended to the cell lines\n        if cell is None:\n            code = ''\n            return_output = True\n            line_mode = True\n        else:\n            code = cell\n            return_output = False\n            line_mode = False\n\n        code = ' '.join(args.code) + code\n\n        if args.input:\n            for input in ','.join(args.input).split(','):\n                input = unicode_to_str(input)\n                self._oct.put(input, self.shell.user_ns[input])\n\n        # generate plots in a temporary directory\n        plot_dir = tempfile.mkdtemp()\n        if args.size is not None:\n            size = args.size\n        else:\n            size = '400,240'\n\n        if args.format is not None:\n            plot_format = args.format\n        else:\n            plot_format = 'png'\n\n        pre_call = '''\n        global __ipy_figures = [];\n        page_screen_output(0);\n\n        function fig_create(src, event)\n          global __ipy_figures;\n          __ipy_figures(size(__ipy_figures) + 1) = src;\n          set(src, \"visible\", \"off\");\n        end\n\n        set(0, 'DefaultFigureCreateFcn', @fig_create);\n\n        close all;\n        clear ans;\n\n        # ___<end_pre_call>___ #\n        '''\n\n        post_call = '''\n        # ___<start_post_call>___ #\n\n        # Save output of the last execution\n        if exist(\"ans\") == 1\n          _ = ans;\n        else\n          _ = nan;\n        end\n\n        for f = __ipy_figures\n          outfile = sprintf('%(plot_dir)s/__ipy_oct_fig_%%03d.png', f);\n          try\n            print(f, outfile, '-d%(plot_format)s', '-tight', '-S%(size)s');\n          end\n        end\n\n        ''' % locals()\n\n        code = ' '.join((pre_call, code, post_call))\n        try:\n            text_output = self._oct.run(code, verbose=False)\n        except (oct2py.Oct2PyError) as exception:\n            msg = exception.message\n            msg = msg.split('# ___<end_pre_call>___ #')[1]\n            msg = msg.split('# ___<start_post_call>___ #')[0]\n            raise OctaveMagicError('Octave could not complete execution.  '\n                                   'Traceback (currently broken in oct2py): %s'\n                                   % msg)\n\n        key = 'OctaveMagic.Octave'\n        display_data = []\n\n        # Publish text output\n        if text_output:\n            display_data.append((key, {'text/plain': text_output}))\n\n        # Publish images\n        images = [open(imgfile, 'rb').read() for imgfile in \\\n                  glob(\"%s/*\" % plot_dir)]\n        rmtree(plot_dir)\n\n        plot_mime_type = _mimetypes.get(plot_format, 'image/png')\n        width, height = [int(s) for s in size.split(',')]\n        for image in images:\n            if plot_format == 'svg':\n                image = self._fix_gnuplot_svg_size(image, size=(width, height))\n            display_data.append((key, {plot_mime_type: image}))\n\n        if args.output:\n            for output in ','.join(args.output).split(','):\n                output = unicode_to_str(output)\n                self.shell.push({output: self._oct.get(output)})\n\n        for source, data in display_data:\n            self._publish_display_data(source, data)\n\n        if return_output:\n            ans = self._oct.get('_')\n\n            # Unfortunately, Octave doesn't have a \"None\" object,\n            # so we can't return any NaN outputs\n            if np.isscalar(ans) and np.isnan(ans):\n                ans = None\n\n            return ans\n\n\n__doc__ = __doc__.format(\n    OCTAVE_DOC = ' '*8 + OctaveMagics.octave.__doc__,\n    OCTAVE_PUSH_DOC = ' '*8 + OctaveMagics.octave_push.__doc__,\n    OCTAVE_PULL_DOC = ' '*8 + OctaveMagics.octave_pull.__doc__\n    )\n\n\n_loaded = False\ndef load_ipython_extension(ip):\n    \"\"\"Load the extension in IPython.\"\"\"\n    global _loaded\n    if not _loaded:\n        ip.register_magics(OctaveMagics)\n        _loaded = True\n", "path": "IPython/extensions/octavemagic.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"\n===========\noctavemagic\n===========\n\nMagics for interacting with Octave via oct2py.\n\n.. note::\n\n  The ``oct2py`` module needs to be installed separately and\n  can be obtained using ``easy_install`` or ``pip``.\n\nUsage\n=====\n\n``%octave``\n\n{OCTAVE_DOC}\n\n``%octave_push``\n\n{OCTAVE_PUSH_DOC}\n\n``%octave_pull``\n\n{OCTAVE_PULL_DOC}\n\n\"\"\"\n\n#-----------------------------------------------------------------------------\n#  Copyright (C) 2012 The IPython Development Team\n#\n#  Distributed under the terms of the BSD License.  The full license is in\n#  the file COPYING, distributed as part of this software.\n#-----------------------------------------------------------------------------\n\nimport tempfile\nfrom glob import glob\nfrom shutil import rmtree\n\nimport numpy as np\nimport oct2py\nfrom xml.dom import minidom\n\nfrom IPython.core.displaypub import publish_display_data\nfrom IPython.core.magic import (Magics, magics_class, line_magic,\n                                line_cell_magic)\nfrom IPython.testing.skipdoctest import skip_doctest\nfrom IPython.core.magic_arguments import (\n    argument, magic_arguments, parse_argstring\n)\nfrom IPython.utils.py3compat import unicode_to_str\n\nclass OctaveMagicError(oct2py.Oct2PyError):\n    pass\n\n_mimetypes = {'png' : 'image/png',\n             'svg' : 'image/svg+xml',\n             'jpg' : 'image/jpeg',\n              'jpeg': 'image/jpeg'}\n\n@magics_class\nclass OctaveMagics(Magics):\n    \"\"\"A set of magics useful for interactive work with Octave via oct2py.\n    \"\"\"\n    def __init__(self, shell):\n        \"\"\"\n        Parameters\n        ----------\n        shell : IPython shell\n\n        \"\"\"\n        super(OctaveMagics, self).__init__(shell)\n        self._oct = oct2py.Oct2Py()\n        self._plot_format = 'png'\n\n        # Allow publish_display_data to be overridden for\n        # testing purposes.\n        self._publish_display_data = publish_display_data\n\n\n    def _fix_gnuplot_svg_size(self, image, size=None):\n        \"\"\"\n        GnuPlot SVGs do not have height/width attributes.  Set\n        these to be the same as the viewBox, so that the browser\n        scales the image correctly.\n\n        Parameters\n        ----------\n        image : str\n            SVG data.\n        size : tuple of int\n            Image width, height.\n\n        \"\"\"\n        (svg,) = minidom.parseString(image).getElementsByTagName('svg')\n        viewbox = svg.getAttribute('viewBox').split(' ')\n\n        if size is not None:\n            width, height = size\n        else:\n            width, height = viewbox[2:]\n\n        svg.setAttribute('width', '%dpx' % width)\n        svg.setAttribute('height', '%dpx' % height)\n        return svg.toxml()\n\n\n    @skip_doctest\n    @line_magic\n    def octave_push(self, line):\n        '''\n        Line-level magic that pushes a variable to Octave.\n\n        `line` should be made up of whitespace separated variable names in the\n        IPython namespace::\n\n            In [7]: import numpy as np\n\n            In [8]: X = np.arange(5)\n\n            In [9]: X.mean()\n            Out[9]: 2.0\n\n            In [10]: %octave_push X\n\n            In [11]: %octave mean(X)\n            Out[11]: 2.0\n\n        '''\n        inputs = line.split(' ')\n        for input in inputs:\n            input = unicode_to_str(input)\n            self._oct.put(input, self.shell.user_ns[input])\n\n\n    @skip_doctest\n    @line_magic\n    def octave_pull(self, line):\n        '''\n        Line-level magic that pulls a variable from Octave.\n\n            In [18]: _ = %octave x = [1 2; 3 4]; y = 'hello'\n\n            In [19]: %octave_pull x y\n\n            In [20]: x\n            Out[20]:\n            array([[ 1.,  2.],\n                   [ 3.,  4.]])\n\n            In [21]: y\n            Out[21]: 'hello'\n\n        '''\n        outputs = line.split(' ')\n        for output in outputs:\n            output = unicode_to_str(output)\n            self.shell.push({output: self._oct.get(output)})\n\n\n    @skip_doctest\n    @magic_arguments()\n    @argument(\n        '-i', '--input', action='append',\n        help='Names of input variables to be pushed to Octave. Multiple names '\n             'can be passed, separated by commas with no whitespace.'\n        )\n    @argument(\n        '-o', '--output', action='append',\n        help='Names of variables to be pulled from Octave after executing cell '\n             'body. Multiple names can be passed, separated by commas with no '\n             'whitespace.'\n        )\n    @argument(\n        '-s', '--size', action='store',\n        help='Pixel size of plots, \"width,height\". Default is \"-s 400,250\".'\n        )\n    @argument(\n        '-f', '--format', action='store',\n        help='Plot format (png, svg or jpg).'\n        )\n\n    @argument(\n        'code',\n        nargs='*',\n        )\n    @line_cell_magic\n    def octave(self, line, cell=None):\n        '''\n        Execute code in Octave, and pull some of the results back into the\n        Python namespace.\n\n            In [9]: %octave X = [1 2; 3 4]; mean(X)\n            Out[9]: array([[ 2., 3.]])\n\n        As a cell, this will run a block of Octave code, without returning any\n        value::\n\n            In [10]: %%octave\n               ....: p = [-2, -1, 0, 1, 2]\n               ....: polyout(p, 'x')\n\n            -2*x^4 - 1*x^3 + 0*x^2 + 1*x^1 + 2\n\n        In the notebook, plots are published as the output of the cell, e.g.\n\n        %octave plot([1 2 3], [4 5 6])\n\n        will create a line plot.\n\n        Objects can be passed back and forth between Octave and IPython via the\n        -i and -o flags in line::\n\n            In [14]: Z = np.array([1, 4, 5, 10])\n\n            In [15]: %octave -i Z mean(Z)\n            Out[15]: array([ 5.])\n\n\n            In [16]: %octave -o W W = Z * mean(Z)\n            Out[16]: array([  5.,  20.,  25.,  50.])\n\n            In [17]: W\n            Out[17]: array([  5.,  20.,  25.,  50.])\n\n        The size and format of output plots can be specified::\n\n            In [18]: %%octave -s 600,800 -f svg\n                ...: plot([1, 2, 3]);\n\n        '''\n        args = parse_argstring(self.octave, line)\n\n        # arguments 'code' in line are prepended to the cell lines\n        if cell is None:\n            code = ''\n            return_output = True\n            line_mode = True\n        else:\n            code = cell\n            return_output = False\n            line_mode = False\n\n        code = ' '.join(args.code) + code\n\n        if args.input:\n            for input in ','.join(args.input).split(','):\n                input = unicode_to_str(input)\n                self._oct.put(input, self.shell.user_ns[input])\n\n        # generate plots in a temporary directory\n        plot_dir = tempfile.mkdtemp()\n        if args.size is not None:\n            size = args.size\n        else:\n            size = '400,240'\n\n        if args.format is not None:\n            plot_format = args.format\n        else:\n            plot_format = 'png'\n\n        pre_call = '''\n        global __ipy_figures = [];\n        page_screen_output(0);\n\n        function fig_create(src, event)\n          global __ipy_figures;\n          __ipy_figures(size(__ipy_figures) + 1) = src;\n          set(src, \"visible\", \"off\");\n        end\n\n        set(0, 'DefaultFigureCreateFcn', @fig_create);\n\n        close all;\n        clear ans;\n\n        # ___<end_pre_call>___ #\n        '''\n\n        post_call = '''\n        # ___<start_post_call>___ #\n\n        # Save output of the last execution\n        if exist(\"ans\") == 1\n          _ = ans;\n        else\n          _ = nan;\n        end\n\n        for f = __ipy_figures\n          outfile = sprintf('%(plot_dir)s/__ipy_oct_fig_%%03d.png', f);\n          try\n            print(f, outfile, '-d%(plot_format)s', '-tight', '-S%(size)s');\n          end\n        end\n\n        ''' % locals()\n\n        code = ' '.join((pre_call, code, post_call))\n        try:\n            text_output = self._oct.run(code, verbose=False)\n        except (oct2py.Oct2PyError) as exception:\n            msg = exception.message\n            msg = msg.split('# ___<end_pre_call>___ #')[1]\n            msg = msg.split('# ___<start_post_call>___ #')[0]\n            raise OctaveMagicError('Octave could not complete execution.  '\n                                   'Traceback (currently broken in oct2py): %s'\n                                   % msg)\n\n        key = 'OctaveMagic.Octave'\n        display_data = []\n\n        # Publish text output\n        if text_output:\n            display_data.append((key, {'text/plain': text_output}))\n\n        # Publish images\n        images = [open(imgfile, 'rb').read() for imgfile in \\\n                  glob(\"%s/*\" % plot_dir)]\n        rmtree(plot_dir)\n\n        plot_mime_type = _mimetypes.get(plot_format, 'image/png')\n        width, height = [int(s) for s in size.split(',')]\n        for image in images:\n            if plot_format == 'svg':\n                image = self._fix_gnuplot_svg_size(image, size=(width, height))\n            display_data.append((key, {plot_mime_type: image}))\n\n        if args.output:\n            for output in ','.join(args.output).split(','):\n                output = unicode_to_str(output)\n                self.shell.push({output: self._oct.get(output)})\n\n        for source, data in display_data:\n            self._publish_display_data(source, data)\n\n        if return_output:\n            ans = self._oct.get('_')\n\n            # Unfortunately, Octave doesn't have a \"None\" object,\n            # so we can't return any NaN outputs\n            if np.isscalar(ans) and np.isnan(ans):\n                ans = None\n\n            return ans\n\n\n__doc__ = __doc__.format(\n    OCTAVE_DOC = ' '*8 + OctaveMagics.octave.__doc__,\n    OCTAVE_PUSH_DOC = ' '*8 + OctaveMagics.octave_push.__doc__,\n    OCTAVE_PULL_DOC = ' '*8 + OctaveMagics.octave_pull.__doc__\n    )\n\n\n_loaded = False\ndef load_ipython_extension(ip):\n    \"\"\"Load the extension in IPython.\"\"\"\n    global _loaded\n    if not _loaded:\n        ip.register_magics(OctaveMagics)\n        _loaded = True\n", "path": "IPython/extensions/octavemagic.py"}]}