We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
interact doesn't work with instance methods
This code:

``` python
from IPython.html.widgets import interact

class Foo(object):
    def show(self, x):
        print x

f = Foo()

interact(f.show, x=(1,10))
```

produces this exception:

```
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-58-b03b8685dfc0> in <module>()
      7 f = Foo()
      8 
----> 9 interact(f.show, x=(1,10))

/home/fperez/usr/lib/python2.7/site-packages/IPython/html/widgets/interaction.pyc in interact(__interact_f, **kwargs)
    235         f = __interact_f
    236         w = interactive(f, **kwargs)
--> 237         f.widget = w
    238         display(w)
    239         return f

AttributeError: 'instancemethod' object has no attribute 'widget'
```


--- 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/html/widgets/interaction.py`
Content:
```
1 """Interact with functions using widgets."""
2 
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2013, the IPython Development Team.
5 #
6 # Distributed under the terms of the Modified BSD License.
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
10 
11 #-----------------------------------------------------------------------------
12 # Imports
13 #-----------------------------------------------------------------------------
14 
15 from __future__ import print_function
16 
17 try:  # Python >= 3.3
18     from inspect import signature, Parameter
19 except ImportError:
20     from IPython.utils.signatures import signature, Parameter
21 from inspect import getcallargs
22 
23 from IPython.core.getipython import get_ipython
24 from IPython.html.widgets import (Widget, Text,
25     FloatSlider, IntSlider, Checkbox, Dropdown,
26     Box, Button, DOMWidget)
27 from IPython.display import display, clear_output
28 from IPython.utils.py3compat import string_types, unicode_type
29 from IPython.utils.traitlets import HasTraits, Any, Unicode
30 
31 empty = Parameter.empty
32 
33 #-----------------------------------------------------------------------------
34 # Classes and Functions
35 #-----------------------------------------------------------------------------
36 
37 
38 def _matches(o, pattern):
39     """Match a pattern of types in a sequence."""
40     if not len(o) == len(pattern):
41         return False
42     comps = zip(o,pattern)
43     return all(isinstance(obj,kind) for obj,kind in comps)
44 
45 
46 def _get_min_max_value(min, max, value=None, step=None):
47     """Return min, max, value given input values with possible None."""
48     if value is None:
49         if not max > min:
50             raise ValueError('max must be greater than min: (min={0}, max={1})'.format(min, max))
51         value = min + abs(min-max)/2
52         value = type(min)(value)
53     elif min is None and max is None:
54         if value == 0.0:
55             min, max, value = 0.0, 1.0, 0.5
56         elif value == 0:
57             min, max, value = 0, 1, 0
58         elif isinstance(value, (int, float)):
59             min, max = (-value, 3*value) if value > 0 else (3*value, -value)
60         else:
61             raise TypeError('expected a number, got: %r' % value)
62     else:
63         raise ValueError('unable to infer range, value from: ({0}, {1}, {2})'.format(min, max, value))
64     if step is not None:
65         # ensure value is on a step
66         r = (value - min) % step
67         value = value - r
68     return min, max, value
69 
70 def _widget_abbrev_single_value(o):
71     """Make widgets from single values, which can be used as parameter defaults."""
72     if isinstance(o, string_types):
73         return Text(value=unicode_type(o))
74     elif isinstance(o, dict):
75         return Dropdown(values=o)
76     elif isinstance(o, bool):
77         return Checkbox(value=o)
78     elif isinstance(o, float):
79         min, max, value = _get_min_max_value(None, None, o)
80         return FloatSlider(value=o, min=min, max=max)
81     elif isinstance(o, int):
82         min, max, value = _get_min_max_value(None, None, o)
83         return IntSlider(value=o, min=min, max=max)
84     else:
85         return None
86 
87 def _widget_abbrev(o):
88     """Make widgets from abbreviations: single values, lists or tuples."""
89     float_or_int = (float, int)
90     if isinstance(o, (list, tuple)):
91         if o and all(isinstance(x, string_types) for x in o):
92             return Dropdown(values=[unicode_type(k) for k in o])
93         elif _matches(o, (float_or_int, float_or_int)):
94             min, max, value = _get_min_max_value(o[0], o[1])
95             if all(isinstance(_, int) for _ in o):
96                 cls = IntSlider
97             else:
98                 cls = FloatSlider
99             return cls(value=value, min=min, max=max)
100         elif _matches(o, (float_or_int, float_or_int, float_or_int)):
101             step = o[2]
102             if step <= 0:
103                 raise ValueError("step must be >= 0, not %r" % step)
104             min, max, value = _get_min_max_value(o[0], o[1], step=step)
105             if all(isinstance(_, int) for _ in o):
106                 cls = IntSlider
107             else:
108                 cls = FloatSlider
109             return cls(value=value, min=min, max=max, step=step)
110     else:
111         return _widget_abbrev_single_value(o)
112 
113 def _widget_from_abbrev(abbrev, default=empty):
114     """Build a Widget instance given an abbreviation or Widget."""
115     if isinstance(abbrev, Widget) or isinstance(abbrev, fixed):
116         return abbrev
117 
118     widget = _widget_abbrev(abbrev)
119     if default is not empty and isinstance(abbrev, (list, tuple, dict)):
120         # if it's not a single-value abbreviation,
121         # set the initial value from the default
122         try:
123             widget.value = default
124         except Exception:
125             # ignore failure to set default
126             pass
127     if widget is None:
128         raise ValueError("%r cannot be transformed to a Widget" % (abbrev,))
129     return widget
130 
131 def _yield_abbreviations_for_parameter(param, kwargs):
132     """Get an abbreviation for a function parameter."""
133     name = param.name
134     kind = param.kind
135     ann = param.annotation
136     default = param.default
137     not_found = (name, empty, empty)
138     if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY):
139         if name in kwargs:
140             value = kwargs.pop(name)
141         elif ann is not empty:
142             value = ann
143         elif default is not empty:
144             value = default
145         else:
146             yield not_found
147         yield (name, value, default)
148     elif kind == Parameter.VAR_KEYWORD:
149         # In this case name=kwargs and we yield the items in kwargs with their keys.
150         for k, v in kwargs.copy().items():
151             kwargs.pop(k)
152             yield k, v, empty
153 
154 def _find_abbreviations(f, kwargs):
155     """Find the abbreviations for a function and kwargs passed to interact."""
156     new_kwargs = []
157     for param in signature(f).parameters.values():
158         for name, value, default in _yield_abbreviations_for_parameter(param, kwargs):
159             if value is empty:
160                 raise ValueError('cannot find widget or abbreviation for argument: {!r}'.format(name))
161             new_kwargs.append((name, value, default))
162     return new_kwargs
163 
164 def _widgets_from_abbreviations(seq):
165     """Given a sequence of (name, abbrev) tuples, return a sequence of Widgets."""
166     result = []
167     for name, abbrev, default in seq:
168         widget = _widget_from_abbrev(abbrev, default)
169         if not widget.description:
170             widget.description = name
171         result.append(widget)
172     return result
173 
174 def interactive(__interact_f, **kwargs):
175     """Build a group of widgets to interact with a function."""
176     f = __interact_f
177     co = kwargs.pop('clear_output', True)
178     manual = kwargs.pop('__manual', False)
179     kwargs_widgets = []
180     container = Box()
181     container.result = None
182     container.args = []
183     container.kwargs = dict()
184     kwargs = kwargs.copy()
185 
186     new_kwargs = _find_abbreviations(f, kwargs)
187     # Before we proceed, let's make sure that the user has passed a set of args+kwargs
188     # that will lead to a valid call of the function. This protects against unspecified
189     # and doubly-specified arguments.
190     getcallargs(f, **{n:v for n,v,_ in new_kwargs})
191     # Now build the widgets from the abbreviations.
192     kwargs_widgets.extend(_widgets_from_abbreviations(new_kwargs))
193 
194     # This has to be done as an assignment, not using container.children.append,
195     # so that traitlets notices the update. We skip any objects (such as fixed) that
196     # are not DOMWidgets.
197     c = [w for w in kwargs_widgets if isinstance(w, DOMWidget)]
198 
199     # If we are only to run the function on demand, add a button to request this
200     if manual:
201         manual_button = Button(description="Run %s" % f.__name__)
202         c.append(manual_button)
203     container.children = c
204 
205     # Build the callback
206     def call_f(name=None, old=None, new=None):
207         container.kwargs = {}
208         for widget in kwargs_widgets:
209             value = widget.value
210             container.kwargs[widget.description] = value
211         if co:
212             clear_output(wait=True)
213         if manual:
214             manual_button.disabled = True
215         try:
216             container.result = f(**container.kwargs)
217         except Exception as e:
218             ip = get_ipython()
219             if ip is None:
220                 container.log.warn("Exception in interact callback: %s", e, exc_info=True)
221             else:
222                 ip.showtraceback()
223         finally:
224             if manual:
225                 manual_button.disabled = False
226 
227     # Wire up the widgets
228     # If we are doing manual running, the callback is only triggered by the button
229     # Otherwise, it is triggered for every trait change received
230     # On-demand running also suppresses running the fucntion with the initial parameters
231     if manual:
232         manual_button.on_click(call_f)
233     else:
234         for widget in kwargs_widgets:
235             widget.on_trait_change(call_f, 'value')
236 
237         container.on_displayed(lambda _: call_f(None, None, None))
238 
239     return container
240 
241 def interact(__interact_f=None, **kwargs):
242     """interact(f, **kwargs)
243 
244     Interact with a function using widgets."""
245     # positional arg support in: https://gist.github.com/8851331
246     if __interact_f is not None:
247         # This branch handles the cases:
248         # 1. interact(f, **kwargs)
249         # 2. @interact
250         #    def f(*args, **kwargs):
251         #        ...
252         f = __interact_f
253         w = interactive(f, **kwargs)
254         f.widget = w
255         display(w)
256         return f
257     else:
258         # This branch handles the case:
259         # @interact(a=30, b=40)
260         # def f(*args, **kwargs):
261         #     ...
262         def dec(f):
263             w = interactive(f, **kwargs)
264             f.widget = w
265             display(w)
266             return f
267         return dec
268 
269 def interact_manual(__interact_f=None, **kwargs):
270     """interact_manual(f, **kwargs)
271     
272     As `interact()`, generates widgets for each argument, but rather than running
273     the function after each widget change, adds a "Run" button and waits for it
274     to be clicked. Useful if the function is long-running and has several
275     parameters to change.
276     """
277     return interact(__interact_f, __manual=True, **kwargs)
278 
279 class fixed(HasTraits):
280     """A pseudo-widget whose value is fixed and never synced to the client."""
281     value = Any(help="Any Python object")
282     description = Unicode('', help="Any Python object")
283     def __init__(self, value, **kwargs):
284         super(fixed, self).__init__(value=value, **kwargs)
285
```
--- 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/html/widgets/interaction.py b/IPython/html/widgets/interaction.py
--- a/IPython/html/widgets/interaction.py
+++ b/IPython/html/widgets/interaction.py
@@ -1,16 +1,7 @@
 """Interact with functions using widgets."""
 
-#-----------------------------------------------------------------------------
-# Copyright (c) 2013, the IPython Development Team.
-#
+# Copyright (c) IPython Development Team.
 # Distributed under the terms of the Modified BSD License.
-#
-# The full license is in the file COPYING.txt, distributed with this software.
-#-----------------------------------------------------------------------------
-
-#-----------------------------------------------------------------------------
-# Imports
-#-----------------------------------------------------------------------------
 
 from __future__ import print_function
 
@@ -30,10 +21,6 @@
 
 empty = Parameter.empty
 
-#-----------------------------------------------------------------------------
-# Classes and Functions
-#-----------------------------------------------------------------------------
-
 
 def _matches(o, pattern):
     """Match a pattern of types in a sequence."""
@@ -251,7 +238,13 @@
         #        ...
         f = __interact_f
         w = interactive(f, **kwargs)
-        f.widget = w
+        try:
+            f.widget = w
+        except AttributeError:
+            # some things (instancemethods) can't have attributes attached,
+            # so wrap in a lambda
+            f = lambda *args, **kwargs: __interact_f(*args, **kwargs)
+            f.widget = w
         display(w)
         return f
     else:
@@ -260,10 +253,7 @@
         # def f(*args, **kwargs):
         #     ...
         def dec(f):
-            w = interactive(f, **kwargs)
-            f.widget = w
-            display(w)
-            return f
+            return interact(f, **kwargs)
         return dec
 
 def interact_manual(__interact_f=None, **kwargs):

{"golden_diff": "diff --git a/IPython/html/widgets/interaction.py b/IPython/html/widgets/interaction.py\n--- a/IPython/html/widgets/interaction.py\n+++ b/IPython/html/widgets/interaction.py\n@@ -1,16 +1,7 @@\n \"\"\"Interact with functions using widgets.\"\"\"\n \n-#-----------------------------------------------------------------------------\n-# Copyright (c) 2013, the IPython Development Team.\n-#\n+# Copyright (c) IPython Development Team.\n # Distributed under the terms of the Modified BSD License.\n-#\n-# The full license is in the file COPYING.txt, distributed with this software.\n-#-----------------------------------------------------------------------------\n-\n-#-----------------------------------------------------------------------------\n-# Imports\n-#-----------------------------------------------------------------------------\n \n from __future__ import print_function\n \n@@ -30,10 +21,6 @@\n \n empty = Parameter.empty\n \n-#-----------------------------------------------------------------------------\n-# Classes and Functions\n-#-----------------------------------------------------------------------------\n-\n \n def _matches(o, pattern):\n     \"\"\"Match a pattern of types in a sequence.\"\"\"\n@@ -251,7 +238,13 @@\n         #        ...\n         f = __interact_f\n         w = interactive(f, **kwargs)\n-        f.widget = w\n+        try:\n+            f.widget = w\n+        except AttributeError:\n+            # some things (instancemethods) can't have attributes attached,\n+            # so wrap in a lambda\n+            f = lambda *args, **kwargs: __interact_f(*args, **kwargs)\n+            f.widget = w\n         display(w)\n         return f\n     else:\n@@ -260,10 +253,7 @@\n         # def f(*args, **kwargs):\n         #     ...\n         def dec(f):\n-            w = interactive(f, **kwargs)\n-            f.widget = w\n-            display(w)\n-            return f\n+            return interact(f, **kwargs)\n         return dec\n \n def interact_manual(__interact_f=None, **kwargs):\n", "issue": "interact doesn't work with instance methods\nThis code:\n\n``` python\nfrom IPython.html.widgets import interact\n\nclass Foo(object):\n    def show(self, x):\n        print x\n\nf = Foo()\n\ninteract(f.show, x=(1,10))\n```\n\nproduces this exception:\n\n```\n---------------------------------------------------------------------------\nAttributeError                            Traceback (most recent call last)\n<ipython-input-58-b03b8685dfc0> in <module>()\n      7 f = Foo()\n      8 \n----> 9 interact(f.show, x=(1,10))\n\n/home/fperez/usr/lib/python2.7/site-packages/IPython/html/widgets/interaction.pyc in interact(__interact_f, **kwargs)\n    235         f = __interact_f\n    236         w = interactive(f, **kwargs)\n--> 237         f.widget = w\n    238         display(w)\n    239         return f\n\nAttributeError: 'instancemethod' object has no attribute 'widget'\n```\n\n", "before_files": [{"content": "\"\"\"Interact with functions using widgets.\"\"\"\n\n#-----------------------------------------------------------------------------\n# Copyright (c) 2013, the IPython Development Team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n#-----------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------\n# Imports\n#-----------------------------------------------------------------------------\n\nfrom __future__ import print_function\n\ntry:  # Python >= 3.3\n    from inspect import signature, Parameter\nexcept ImportError:\n    from IPython.utils.signatures import signature, Parameter\nfrom inspect import getcallargs\n\nfrom IPython.core.getipython import get_ipython\nfrom IPython.html.widgets import (Widget, Text,\n    FloatSlider, IntSlider, Checkbox, Dropdown,\n    Box, Button, DOMWidget)\nfrom IPython.display import display, clear_output\nfrom IPython.utils.py3compat import string_types, unicode_type\nfrom IPython.utils.traitlets import HasTraits, Any, Unicode\n\nempty = Parameter.empty\n\n#-----------------------------------------------------------------------------\n# Classes and Functions\n#-----------------------------------------------------------------------------\n\n\ndef _matches(o, pattern):\n    \"\"\"Match a pattern of types in a sequence.\"\"\"\n    if not len(o) == len(pattern):\n        return False\n    comps = zip(o,pattern)\n    return all(isinstance(obj,kind) for obj,kind in comps)\n\n\ndef _get_min_max_value(min, max, value=None, step=None):\n    \"\"\"Return min, max, value given input values with possible None.\"\"\"\n    if value is None:\n        if not max > min:\n            raise ValueError('max must be greater than min: (min={0}, max={1})'.format(min, max))\n        value = min + abs(min-max)/2\n        value = type(min)(value)\n    elif min is None and max is None:\n        if value == 0.0:\n            min, max, value = 0.0, 1.0, 0.5\n        elif value == 0:\n            min, max, value = 0, 1, 0\n        elif isinstance(value, (int, float)):\n            min, max = (-value, 3*value) if value > 0 else (3*value, -value)\n        else:\n            raise TypeError('expected a number, got: %r' % value)\n    else:\n        raise ValueError('unable to infer range, value from: ({0}, {1}, {2})'.format(min, max, value))\n    if step is not None:\n        # ensure value is on a step\n        r = (value - min) % step\n        value = value - r\n    return min, max, value\n\ndef _widget_abbrev_single_value(o):\n    \"\"\"Make widgets from single values, which can be used as parameter defaults.\"\"\"\n    if isinstance(o, string_types):\n        return Text(value=unicode_type(o))\n    elif isinstance(o, dict):\n        return Dropdown(values=o)\n    elif isinstance(o, bool):\n        return Checkbox(value=o)\n    elif isinstance(o, float):\n        min, max, value = _get_min_max_value(None, None, o)\n        return FloatSlider(value=o, min=min, max=max)\n    elif isinstance(o, int):\n        min, max, value = _get_min_max_value(None, None, o)\n        return IntSlider(value=o, min=min, max=max)\n    else:\n        return None\n\ndef _widget_abbrev(o):\n    \"\"\"Make widgets from abbreviations: single values, lists or tuples.\"\"\"\n    float_or_int = (float, int)\n    if isinstance(o, (list, tuple)):\n        if o and all(isinstance(x, string_types) for x in o):\n            return Dropdown(values=[unicode_type(k) for k in o])\n        elif _matches(o, (float_or_int, float_or_int)):\n            min, max, value = _get_min_max_value(o[0], o[1])\n            if all(isinstance(_, int) for _ in o):\n                cls = IntSlider\n            else:\n                cls = FloatSlider\n            return cls(value=value, min=min, max=max)\n        elif _matches(o, (float_or_int, float_or_int, float_or_int)):\n            step = o[2]\n            if step <= 0:\n                raise ValueError(\"step must be >= 0, not %r\" % step)\n            min, max, value = _get_min_max_value(o[0], o[1], step=step)\n            if all(isinstance(_, int) for _ in o):\n                cls = IntSlider\n            else:\n                cls = FloatSlider\n            return cls(value=value, min=min, max=max, step=step)\n    else:\n        return _widget_abbrev_single_value(o)\n\ndef _widget_from_abbrev(abbrev, default=empty):\n    \"\"\"Build a Widget instance given an abbreviation or Widget.\"\"\"\n    if isinstance(abbrev, Widget) or isinstance(abbrev, fixed):\n        return abbrev\n\n    widget = _widget_abbrev(abbrev)\n    if default is not empty and isinstance(abbrev, (list, tuple, dict)):\n        # if it's not a single-value abbreviation,\n        # set the initial value from the default\n        try:\n            widget.value = default\n        except Exception:\n            # ignore failure to set default\n            pass\n    if widget is None:\n        raise ValueError(\"%r cannot be transformed to a Widget\" % (abbrev,))\n    return widget\n\ndef _yield_abbreviations_for_parameter(param, kwargs):\n    \"\"\"Get an abbreviation for a function parameter.\"\"\"\n    name = param.name\n    kind = param.kind\n    ann = param.annotation\n    default = param.default\n    not_found = (name, empty, empty)\n    if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY):\n        if name in kwargs:\n            value = kwargs.pop(name)\n        elif ann is not empty:\n            value = ann\n        elif default is not empty:\n            value = default\n        else:\n            yield not_found\n        yield (name, value, default)\n    elif kind == Parameter.VAR_KEYWORD:\n        # In this case name=kwargs and we yield the items in kwargs with their keys.\n        for k, v in kwargs.copy().items():\n            kwargs.pop(k)\n            yield k, v, empty\n\ndef _find_abbreviations(f, kwargs):\n    \"\"\"Find the abbreviations for a function and kwargs passed to interact.\"\"\"\n    new_kwargs = []\n    for param in signature(f).parameters.values():\n        for name, value, default in _yield_abbreviations_for_parameter(param, kwargs):\n            if value is empty:\n                raise ValueError('cannot find widget or abbreviation for argument: {!r}'.format(name))\n            new_kwargs.append((name, value, default))\n    return new_kwargs\n\ndef _widgets_from_abbreviations(seq):\n    \"\"\"Given a sequence of (name, abbrev) tuples, return a sequence of Widgets.\"\"\"\n    result = []\n    for name, abbrev, default in seq:\n        widget = _widget_from_abbrev(abbrev, default)\n        if not widget.description:\n            widget.description = name\n        result.append(widget)\n    return result\n\ndef interactive(__interact_f, **kwargs):\n    \"\"\"Build a group of widgets to interact with a function.\"\"\"\n    f = __interact_f\n    co = kwargs.pop('clear_output', True)\n    manual = kwargs.pop('__manual', False)\n    kwargs_widgets = []\n    container = Box()\n    container.result = None\n    container.args = []\n    container.kwargs = dict()\n    kwargs = kwargs.copy()\n\n    new_kwargs = _find_abbreviations(f, kwargs)\n    # Before we proceed, let's make sure that the user has passed a set of args+kwargs\n    # that will lead to a valid call of the function. This protects against unspecified\n    # and doubly-specified arguments.\n    getcallargs(f, **{n:v for n,v,_ in new_kwargs})\n    # Now build the widgets from the abbreviations.\n    kwargs_widgets.extend(_widgets_from_abbreviations(new_kwargs))\n\n    # This has to be done as an assignment, not using container.children.append,\n    # so that traitlets notices the update. We skip any objects (such as fixed) that\n    # are not DOMWidgets.\n    c = [w for w in kwargs_widgets if isinstance(w, DOMWidget)]\n\n    # If we are only to run the function on demand, add a button to request this\n    if manual:\n        manual_button = Button(description=\"Run %s\" % f.__name__)\n        c.append(manual_button)\n    container.children = c\n\n    # Build the callback\n    def call_f(name=None, old=None, new=None):\n        container.kwargs = {}\n        for widget in kwargs_widgets:\n            value = widget.value\n            container.kwargs[widget.description] = value\n        if co:\n            clear_output(wait=True)\n        if manual:\n            manual_button.disabled = True\n        try:\n            container.result = f(**container.kwargs)\n        except Exception as e:\n            ip = get_ipython()\n            if ip is None:\n                container.log.warn(\"Exception in interact callback: %s\", e, exc_info=True)\n            else:\n                ip.showtraceback()\n        finally:\n            if manual:\n                manual_button.disabled = False\n\n    # Wire up the widgets\n    # If we are doing manual running, the callback is only triggered by the button\n    # Otherwise, it is triggered for every trait change received\n    # On-demand running also suppresses running the fucntion with the initial parameters\n    if manual:\n        manual_button.on_click(call_f)\n    else:\n        for widget in kwargs_widgets:\n            widget.on_trait_change(call_f, 'value')\n\n        container.on_displayed(lambda _: call_f(None, None, None))\n\n    return container\n\ndef interact(__interact_f=None, **kwargs):\n    \"\"\"interact(f, **kwargs)\n\n    Interact with a function using widgets.\"\"\"\n    # positional arg support in: https://gist.github.com/8851331\n    if __interact_f is not None:\n        # This branch handles the cases:\n        # 1. interact(f, **kwargs)\n        # 2. @interact\n        #    def f(*args, **kwargs):\n        #        ...\n        f = __interact_f\n        w = interactive(f, **kwargs)\n        f.widget = w\n        display(w)\n        return f\n    else:\n        # This branch handles the case:\n        # @interact(a=30, b=40)\n        # def f(*args, **kwargs):\n        #     ...\n        def dec(f):\n            w = interactive(f, **kwargs)\n            f.widget = w\n            display(w)\n            return f\n        return dec\n\ndef interact_manual(__interact_f=None, **kwargs):\n    \"\"\"interact_manual(f, **kwargs)\n    \n    As `interact()`, generates widgets for each argument, but rather than running\n    the function after each widget change, adds a \"Run\" button and waits for it\n    to be clicked. Useful if the function is long-running and has several\n    parameters to change.\n    \"\"\"\n    return interact(__interact_f, __manual=True, **kwargs)\n\nclass fixed(HasTraits):\n    \"\"\"A pseudo-widget whose value is fixed and never synced to the client.\"\"\"\n    value = Any(help=\"Any Python object\")\n    description = Unicode('', help=\"Any Python object\")\n    def __init__(self, value, **kwargs):\n        super(fixed, self).__init__(value=value, **kwargs)\n", "path": "IPython/html/widgets/interaction.py"}], "after_files": [{"content": "\"\"\"Interact with functions using widgets.\"\"\"\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom __future__ import print_function\n\ntry:  # Python >= 3.3\n    from inspect import signature, Parameter\nexcept ImportError:\n    from IPython.utils.signatures import signature, Parameter\nfrom inspect import getcallargs\n\nfrom IPython.core.getipython import get_ipython\nfrom IPython.html.widgets import (Widget, Text,\n    FloatSlider, IntSlider, Checkbox, Dropdown,\n    Box, Button, DOMWidget)\nfrom IPython.display import display, clear_output\nfrom IPython.utils.py3compat import string_types, unicode_type\nfrom IPython.utils.traitlets import HasTraits, Any, Unicode\n\nempty = Parameter.empty\n\n\ndef _matches(o, pattern):\n    \"\"\"Match a pattern of types in a sequence.\"\"\"\n    if not len(o) == len(pattern):\n        return False\n    comps = zip(o,pattern)\n    return all(isinstance(obj,kind) for obj,kind in comps)\n\n\ndef _get_min_max_value(min, max, value=None, step=None):\n    \"\"\"Return min, max, value given input values with possible None.\"\"\"\n    if value is None:\n        if not max > min:\n            raise ValueError('max must be greater than min: (min={0}, max={1})'.format(min, max))\n        value = min + abs(min-max)/2\n        value = type(min)(value)\n    elif min is None and max is None:\n        if value == 0.0:\n            min, max, value = 0.0, 1.0, 0.5\n        elif value == 0:\n            min, max, value = 0, 1, 0\n        elif isinstance(value, (int, float)):\n            min, max = (-value, 3*value) if value > 0 else (3*value, -value)\n        else:\n            raise TypeError('expected a number, got: %r' % value)\n    else:\n        raise ValueError('unable to infer range, value from: ({0}, {1}, {2})'.format(min, max, value))\n    if step is not None:\n        # ensure value is on a step\n        r = (value - min) % step\n        value = value - r\n    return min, max, value\n\ndef _widget_abbrev_single_value(o):\n    \"\"\"Make widgets from single values, which can be used as parameter defaults.\"\"\"\n    if isinstance(o, string_types):\n        return Text(value=unicode_type(o))\n    elif isinstance(o, dict):\n        return Dropdown(values=o)\n    elif isinstance(o, bool):\n        return Checkbox(value=o)\n    elif isinstance(o, float):\n        min, max, value = _get_min_max_value(None, None, o)\n        return FloatSlider(value=o, min=min, max=max)\n    elif isinstance(o, int):\n        min, max, value = _get_min_max_value(None, None, o)\n        return IntSlider(value=o, min=min, max=max)\n    else:\n        return None\n\ndef _widget_abbrev(o):\n    \"\"\"Make widgets from abbreviations: single values, lists or tuples.\"\"\"\n    float_or_int = (float, int)\n    if isinstance(o, (list, tuple)):\n        if o and all(isinstance(x, string_types) for x in o):\n            return Dropdown(values=[unicode_type(k) for k in o])\n        elif _matches(o, (float_or_int, float_or_int)):\n            min, max, value = _get_min_max_value(o[0], o[1])\n            if all(isinstance(_, int) for _ in o):\n                cls = IntSlider\n            else:\n                cls = FloatSlider\n            return cls(value=value, min=min, max=max)\n        elif _matches(o, (float_or_int, float_or_int, float_or_int)):\n            step = o[2]\n            if step <= 0:\n                raise ValueError(\"step must be >= 0, not %r\" % step)\n            min, max, value = _get_min_max_value(o[0], o[1], step=step)\n            if all(isinstance(_, int) for _ in o):\n                cls = IntSlider\n            else:\n                cls = FloatSlider\n            return cls(value=value, min=min, max=max, step=step)\n    else:\n        return _widget_abbrev_single_value(o)\n\ndef _widget_from_abbrev(abbrev, default=empty):\n    \"\"\"Build a Widget instance given an abbreviation or Widget.\"\"\"\n    if isinstance(abbrev, Widget) or isinstance(abbrev, fixed):\n        return abbrev\n\n    widget = _widget_abbrev(abbrev)\n    if default is not empty and isinstance(abbrev, (list, tuple, dict)):\n        # if it's not a single-value abbreviation,\n        # set the initial value from the default\n        try:\n            widget.value = default\n        except Exception:\n            # ignore failure to set default\n            pass\n    if widget is None:\n        raise ValueError(\"%r cannot be transformed to a Widget\" % (abbrev,))\n    return widget\n\ndef _yield_abbreviations_for_parameter(param, kwargs):\n    \"\"\"Get an abbreviation for a function parameter.\"\"\"\n    name = param.name\n    kind = param.kind\n    ann = param.annotation\n    default = param.default\n    not_found = (name, empty, empty)\n    if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY):\n        if name in kwargs:\n            value = kwargs.pop(name)\n        elif ann is not empty:\n            value = ann\n        elif default is not empty:\n            value = default\n        else:\n            yield not_found\n        yield (name, value, default)\n    elif kind == Parameter.VAR_KEYWORD:\n        # In this case name=kwargs and we yield the items in kwargs with their keys.\n        for k, v in kwargs.copy().items():\n            kwargs.pop(k)\n            yield k, v, empty\n\ndef _find_abbreviations(f, kwargs):\n    \"\"\"Find the abbreviations for a function and kwargs passed to interact.\"\"\"\n    new_kwargs = []\n    for param in signature(f).parameters.values():\n        for name, value, default in _yield_abbreviations_for_parameter(param, kwargs):\n            if value is empty:\n                raise ValueError('cannot find widget or abbreviation for argument: {!r}'.format(name))\n            new_kwargs.append((name, value, default))\n    return new_kwargs\n\ndef _widgets_from_abbreviations(seq):\n    \"\"\"Given a sequence of (name, abbrev) tuples, return a sequence of Widgets.\"\"\"\n    result = []\n    for name, abbrev, default in seq:\n        widget = _widget_from_abbrev(abbrev, default)\n        if not widget.description:\n            widget.description = name\n        result.append(widget)\n    return result\n\ndef interactive(__interact_f, **kwargs):\n    \"\"\"Build a group of widgets to interact with a function.\"\"\"\n    f = __interact_f\n    co = kwargs.pop('clear_output', True)\n    manual = kwargs.pop('__manual', False)\n    kwargs_widgets = []\n    container = Box()\n    container.result = None\n    container.args = []\n    container.kwargs = dict()\n    kwargs = kwargs.copy()\n\n    new_kwargs = _find_abbreviations(f, kwargs)\n    # Before we proceed, let's make sure that the user has passed a set of args+kwargs\n    # that will lead to a valid call of the function. This protects against unspecified\n    # and doubly-specified arguments.\n    getcallargs(f, **{n:v for n,v,_ in new_kwargs})\n    # Now build the widgets from the abbreviations.\n    kwargs_widgets.extend(_widgets_from_abbreviations(new_kwargs))\n\n    # This has to be done as an assignment, not using container.children.append,\n    # so that traitlets notices the update. We skip any objects (such as fixed) that\n    # are not DOMWidgets.\n    c = [w for w in kwargs_widgets if isinstance(w, DOMWidget)]\n\n    # If we are only to run the function on demand, add a button to request this\n    if manual:\n        manual_button = Button(description=\"Run %s\" % f.__name__)\n        c.append(manual_button)\n    container.children = c\n\n    # Build the callback\n    def call_f(name=None, old=None, new=None):\n        container.kwargs = {}\n        for widget in kwargs_widgets:\n            value = widget.value\n            container.kwargs[widget.description] = value\n        if co:\n            clear_output(wait=True)\n        if manual:\n            manual_button.disabled = True\n        try:\n            container.result = f(**container.kwargs)\n        except Exception as e:\n            ip = get_ipython()\n            if ip is None:\n                container.log.warn(\"Exception in interact callback: %s\", e, exc_info=True)\n            else:\n                ip.showtraceback()\n        finally:\n            if manual:\n                manual_button.disabled = False\n\n    # Wire up the widgets\n    # If we are doing manual running, the callback is only triggered by the button\n    # Otherwise, it is triggered for every trait change received\n    # On-demand running also suppresses running the fucntion with the initial parameters\n    if manual:\n        manual_button.on_click(call_f)\n    else:\n        for widget in kwargs_widgets:\n            widget.on_trait_change(call_f, 'value')\n\n        container.on_displayed(lambda _: call_f(None, None, None))\n\n    return container\n\ndef interact(__interact_f=None, **kwargs):\n    \"\"\"interact(f, **kwargs)\n\n    Interact with a function using widgets.\"\"\"\n    # positional arg support in: https://gist.github.com/8851331\n    if __interact_f is not None:\n        # This branch handles the cases:\n        # 1. interact(f, **kwargs)\n        # 2. @interact\n        #    def f(*args, **kwargs):\n        #        ...\n        f = __interact_f\n        w = interactive(f, **kwargs)\n        try:\n            f.widget = w\n        except AttributeError:\n            # some things (instancemethods) can't have attributes attached,\n            # so wrap in a lambda\n            f = lambda *args, **kwargs: __interact_f(*args, **kwargs)\n            f.widget = w\n        display(w)\n        return f\n    else:\n        # This branch handles the case:\n        # @interact(a=30, b=40)\n        # def f(*args, **kwargs):\n        #     ...\n        def dec(f):\n            return interact(f, **kwargs)\n        return dec\n\ndef interact_manual(__interact_f=None, **kwargs):\n    \"\"\"interact_manual(f, **kwargs)\n    \n    As `interact()`, generates widgets for each argument, but rather than running\n    the function after each widget change, adds a \"Run\" button and waits for it\n    to be clicked. Useful if the function is long-running and has several\n    parameters to change.\n    \"\"\"\n    return interact(__interact_f, __manual=True, **kwargs)\n\nclass fixed(HasTraits):\n    \"\"\"A pseudo-widget whose value is fixed and never synced to the client.\"\"\"\n    value = Any(help=\"Any Python object\")\n    description = Unicode('', help=\"Any Python object\")\n    def __init__(self, value, **kwargs):\n        super(fixed, self).__init__(value=value, **kwargs)\n", "path": "IPython/html/widgets/interaction.py"}]}