We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Invalid magics in dask.imperitive.Value
``` python
__inv__
__concat__
__not__
```

You are setting these to `operator.inv`, `operator.concat` and `operator.not_`; however, `inv` is an alias for `invert` and the magic is already defined. `concat` is an alias for `add` that is more readable for lists and collections. Also, `not_` cannot be overridden with a function, `__not__` is not called.

If you are using these names internally then I apologize; however, I would urge you not to "invent" your own magic methods:

from pep8:

> `__double_leading_and_trailing_underscore__` : "magic" objects or attributes that live in user-controlled namespaces. E.g. `__init__`, `__import__` or `__file__` . Never invent such names; only use them as documented. 


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `dask/imperative.py`
Content:
```
1 import operator
2 from functools import partial, wraps
3 from itertools import chain, count
4 from collections import Iterator
5 
6 from toolz import merge, unique, curry
7 
8 from .optimize import cull, fuse
9 from .context import _globals
10 from .compatibility import apply
11 from . import threaded
12 
13 __all__ = ['do', 'value', 'Value']
14 
15 
16 def flat_unique(ls):
17     """Flatten ``ls``, filter by unique id, and return a list"""
18     return list(unique(chain.from_iterable(ls), key=id))
19 
20 
21 def unzip(ls, nout):
22     """Unzip a list of lists into ``nout`` outputs."""
23     out = list(zip(*ls))
24     if not out:
25         out = [()] * nout
26     return out
27 
28 
29 def to_task_dasks(expr):
30     """Normalize a python object and extract all sub-dasks.
31 
32     - Replace ``Values`` with their keys
33     - Convert literals to things the schedulers can handle
34     - Extract dasks from all enclosed values
35 
36     Parameters
37     ----------
38     expr : object
39         The object to be normalized. This function knows how to handle
40         ``Value``s, as well as most builtin python types.
41 
42     Returns
43     -------
44     task : normalized task to be run
45     dasks : list of dasks that form the dag for this task
46 
47     Examples
48     --------
49 
50     >>> a = value(1, 'a')
51     >>> b = value(2, 'b')
52     >>> task, dasks = to_task_dasks([a, b, 3])
53     >>> task # doctest: +SKIP
54     (list, ['a', 'b', 3])
55     >>> dasks # doctest: +SKIP
56     [{'a': 1}, {'b': 2}]
57 
58     >>> task, dasks = to_task_dasks({a: 1, b: 2})
59     >>> task # doctest: +SKIP
60     (dict, (list, [(list, ['a', 1]), (list, ['b', 2])]))
61     >>> dasks # doctest: +SKIP
62     [{'a': 1}, {'b': 2}]
63     """
64     if isinstance(expr, Value):
65         return expr.key, expr._dasks
66     elif isinstance(expr, (Iterator, list, tuple, set)):
67         args, dasks = unzip(map(to_task_dasks, expr), 2)
68         args = list(args)
69         dasks = flat_unique(dasks)
70         # Ensure output type matches input type
71         if isinstance(expr, (list, tuple, set)):
72             return (type(expr), args), dasks
73         else:
74             return args, dasks
75     elif isinstance(expr, dict):
76         args, dasks = to_task_dasks(list([k, v] for k, v in expr.items()))
77         return (dict, args), dasks
78     else:
79         return expr, []
80 
81 
82 tokens = ('_{0}'.format(i) for i in count(1))
83 
84 
85 def tokenize(v, pure=False):
86     """Mapping function from task -> consistent name.
87 
88     Parameters
89     ----------
90     v : object
91         Any python object (or tuple of objects) that summarize the task.
92     pure : boolean, optional
93         If True, a consistent hash function is tried on the input. If this
94         fails, then a unique identifier is used. If False (default), then a
95         unique identifier is always used.
96     """
97     # TODO: May have hash collisions...
98     if pure:
99         try:
100             return str(hash(v))
101         except TypeError:
102             pass
103     return next(tokens)
104 
105 
106 def applyfunc(func, args, kwargs, pure=False):
107     """Create a Value by applying a function to args.
108 
109     Given a function and arguments, return a Value that represents the result
110     of that computation."""
111 
112     args, dasks = unzip(map(to_task_dasks, args), 2)
113     dasks = flat_unique(dasks)
114     name = tokenize((func, args, frozenset(kwargs.items())), pure)
115     if kwargs:
116         func = partial(func, **kwargs)
117     dasks.append({name: (func,) + args})
118     return Value(name, dasks)
119 
120 
121 @curry
122 def do(func, pure=False):
123     """Wraps a function so that it outputs a ``Value``.
124 
125     Examples
126     --------
127     Can be used as a decorator:
128 
129     >>> @do
130     ... def add(a, b):
131     ...     return a + b
132     >>> res = add(1, 2)
133     >>> type(res) == Value
134     True
135     >>> res.compute()
136     3
137 
138     For other cases, it may be cleaner to call ``do`` on a function at call
139     time:
140 
141     >>> res2 = do(sum)([res, 2, 3])
142     >>> res2.compute()
143     8
144 
145     ``do`` also accepts an optional keyword ``pure``. If False (default), then
146     subsequent calls will always produce a different ``Value``. This is useful
147     for non-pure functions (such as ``time`` or ``random``).
148 
149     >>> from random import random
150     >>> out1 = do(random)()
151     >>> out2 = do(random)()
152     >>> out1.key == out2.key
153     False
154 
155     If you know a function is pure (output only depends on the input, with no
156     global state), then you can set ``pure=True``. This will attempt to apply a
157     consistent name to the output, but will fallback on the same behavior of
158     ``pure=False`` if this fails.
159 
160     >>> @do(pure=True)
161     ... def add(a, b):
162     ...     return a + b
163     >>> out1 = add(1, 2)
164     >>> out2 = add(1, 2)
165     >>> out1.key == out2.key
166     True
167     """
168     @wraps(func)
169     def _dfunc(*args, **kwargs):
170         return applyfunc(func, args, kwargs, pure=pure)
171     return _dfunc
172 
173 
174 def optimize(dsk, keys):
175     dsk2 = cull(dsk, keys)
176     return fuse(dsk2)
177 
178 
179 def get(dsk, keys, get=None, **kwargs):
180     """Specialized get function"""
181     get = get or _globals['get'] or threaded.get
182     dsk2 = optimize(dsk, keys)
183     return get(dsk2, keys, **kwargs)
184 
185 
186 def right(method):
187     """Wrapper to create 'right' version of operator given left version"""
188     def _inner(self, other):
189         return method(other, self)
190     return _inner
191 
192 
193 class Value(object):
194     """Represents a value to be computed by dask.
195 
196     Equivalent to the output from a single key in a dask graph.
197     """
198     __slots__ = ('_key', '_dasks')
199 
200     def __init__(self, name, dasks):
201         object.__setattr__(self, '_key', name)
202         object.__setattr__(self, '_dasks', dasks)
203 
204     def compute(self, **kwargs):
205         """Compute the result."""
206         dask1 = cull(self.dask, self.key)
207         return get(dask1, self.key, **kwargs)
208 
209     @property
210     def dask(self):
211         return merge(*self._dasks)
212 
213     @property
214     def key(self):
215         return self._key
216 
217     def visualize(self, optimize_graph=False, **kwargs):
218         """Visualize the dask as a graph"""
219         from dask.dot import dot_graph
220         if optimize_graph:
221             return dot_graph(optimize(self.dask, self.key), **kwargs)
222         else:
223             return dot_graph(self.dask, **kwargs)
224 
225     def __repr__(self):
226         return "Value({0})".format(repr(self.key))
227 
228     def __hash__(self):
229         return hash(self.key)
230 
231     def __dir__(self):
232         return list(self.__dict__.keys())
233 
234     def __getattr__(self, attr):
235         if not attr.startswith('_'):
236             return do(getattr, True)(self, attr)
237         else:
238             raise AttributeError("Attribute {0} not found".format(attr))
239 
240     def __setattr__(self, attr, val):
241         raise TypeError("Value objects are immutable")
242 
243     def __setitem__(self, index, val):
244         raise TypeError("Value objects are immutable")
245 
246     def __iter__(self):
247         raise TypeError("Value objects are not iterable")
248 
249     def __call__(self, *args, **kwargs):
250         return do(apply)(self, args, kwargs)
251 
252     def __bool__(self):
253         raise TypeError("Truth of Value objects is not supported")
254 
255     __nonzero__ = __bool__
256 
257     __abs__ = do(operator.abs, True)
258     __add__ = do(operator.add, True)
259     __and__ = do(operator.and_, True)
260     __concat__ = do(operator.concat, True)
261     __delitem__ = do(operator.delitem, True)
262     __div__ = do(operator.floordiv, True)
263     __eq__ = do(operator.eq, True)
264     __floordiv__ = do(operator.floordiv, True)
265     __ge__ = do(operator.ge, True)
266     __getitem__ = do(operator.getitem, True)
267     __gt__ = do(operator.gt, True)
268     __index__ = do(operator.index, True)
269     __inv__ = do(operator.inv, True)
270     __invert__ = do(operator.invert, True)
271     __le__ = do(operator.le, True)
272     __lshift__ = do(operator.lshift, True)
273     __lt__ = do(operator.lt, True)
274     __mod__ = do(operator.mod, True)
275     __mul__ = do(operator.mul, True)
276     __ne__ = do(operator.ne, True)
277     __neg__ = do(operator.neg, True)
278     __not__ = do(operator.not_, True)
279     __or__ = do(operator.or_, True)
280     __pos__ = do(operator.pos, True)
281     __pow__ = do(operator.pow, True)
282     __radd__ = do(right(operator.add), True)
283     __rand__ = do(right(operator.and_), True)
284     __rdiv__ = do(right(operator.floordiv), True)
285     __rfloordiv__ = do(right(operator.floordiv), True)
286     __rlshift__ = do(right(operator.lshift), True)
287     __rmod__ = do(right(operator.mod), True)
288     __rmul__ = do(right(operator.mul), True)
289     __ror__ = do(right(operator.or_), True)
290     __rpow__ = do(right(operator.pow), True)
291     __rrshift__ = do(right(operator.rshift), True)
292     __rshift__ = do(operator.rshift, True)
293     __rsub__ = do(right(operator.sub), True)
294     __rtruediv__ = do(right(operator.truediv), True)
295     __rxor__ = do(right(operator.xor), True)
296     __sub__ = do(operator.sub, True)
297     __truediv__ = do(operator.truediv, True)
298     __xor__ = do(operator.xor, True)
299 
300 
301 def value(val, name=None):
302     """Create a ``Value`` from a python object.
303 
304     Parameters
305     ----------
306     val : object
307         Object to be wrapped.
308     name : string, optional
309         Name to be used in the resulting dask.
310 
311     Examples
312     --------
313     >>> a = value([1, 2, 3])
314     >>> a.compute()
315     [1, 2, 3]
316 
317     Values can act as a proxy to the underlying object. Many operators are
318     supported:
319 
320     >>> (a + [1, 2]).compute()
321     [1, 2, 3, 1, 2]
322     >>> a[1].compute()
323     2
324 
325     Method and attribute access also works:
326 
327     >>> a.count(2).compute()
328     1
329 
330     Note that if a method doesn't exist, no error will be thrown until runtime:
331 
332     >>> res = a.not_a_real_method()
333     >>> res.compute()  # doctest: +SKIP
334     AttributeError("'list' object has no attribute 'not_a_real_method'")
335     """
336 
337     name = name or tokenize(val, True)
338     task, dasks = to_task_dasks(val)
339     dasks.append({name: task})
340     return Value(name, dasks)
341
```
--- 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/dask/imperative.py b/dask/imperative.py
--- a/dask/imperative.py
+++ b/dask/imperative.py
@@ -257,8 +257,6 @@
     __abs__ = do(operator.abs, True)
     __add__ = do(operator.add, True)
     __and__ = do(operator.and_, True)
-    __concat__ = do(operator.concat, True)
-    __delitem__ = do(operator.delitem, True)
     __div__ = do(operator.floordiv, True)
     __eq__ = do(operator.eq, True)
     __floordiv__ = do(operator.floordiv, True)
@@ -266,7 +264,6 @@
     __getitem__ = do(operator.getitem, True)
     __gt__ = do(operator.gt, True)
     __index__ = do(operator.index, True)
-    __inv__ = do(operator.inv, True)
     __invert__ = do(operator.invert, True)
     __le__ = do(operator.le, True)
     __lshift__ = do(operator.lshift, True)
@@ -275,7 +272,6 @@
     __mul__ = do(operator.mul, True)
     __ne__ = do(operator.ne, True)
     __neg__ = do(operator.neg, True)
-    __not__ = do(operator.not_, True)
     __or__ = do(operator.or_, True)
     __pos__ = do(operator.pos, True)
     __pow__ = do(operator.pow, True)

{"golden_diff": "diff --git a/dask/imperative.py b/dask/imperative.py\n--- a/dask/imperative.py\n+++ b/dask/imperative.py\n@@ -257,8 +257,6 @@\n     __abs__ = do(operator.abs, True)\n     __add__ = do(operator.add, True)\n     __and__ = do(operator.and_, True)\n-    __concat__ = do(operator.concat, True)\n-    __delitem__ = do(operator.delitem, True)\n     __div__ = do(operator.floordiv, True)\n     __eq__ = do(operator.eq, True)\n     __floordiv__ = do(operator.floordiv, True)\n@@ -266,7 +264,6 @@\n     __getitem__ = do(operator.getitem, True)\n     __gt__ = do(operator.gt, True)\n     __index__ = do(operator.index, True)\n-    __inv__ = do(operator.inv, True)\n     __invert__ = do(operator.invert, True)\n     __le__ = do(operator.le, True)\n     __lshift__ = do(operator.lshift, True)\n@@ -275,7 +272,6 @@\n     __mul__ = do(operator.mul, True)\n     __ne__ = do(operator.ne, True)\n     __neg__ = do(operator.neg, True)\n-    __not__ = do(operator.not_, True)\n     __or__ = do(operator.or_, True)\n     __pos__ = do(operator.pos, True)\n     __pow__ = do(operator.pow, True)\n", "issue": "Invalid magics in dask.imperitive.Value\n``` python\n__inv__\n__concat__\n__not__\n```\n\nYou are setting these to `operator.inv`, `operator.concat` and `operator.not_`; however, `inv` is an alias for `invert` and the magic is already defined. `concat` is an alias for `add` that is more readable for lists and collections. Also, `not_` cannot be overridden with a function, `__not__` is not called.\n\nIf you are using these names internally then I apologize; however, I would urge you not to \"invent\" your own magic methods:\n\nfrom pep8:\n\n> `__double_leading_and_trailing_underscore__` : \"magic\" objects or attributes that live in user-controlled namespaces. E.g. `__init__`, `__import__` or `__file__` . Never invent such names; only use them as documented. \n\n", "before_files": [{"content": "import operator\nfrom functools import partial, wraps\nfrom itertools import chain, count\nfrom collections import Iterator\n\nfrom toolz import merge, unique, curry\n\nfrom .optimize import cull, fuse\nfrom .context import _globals\nfrom .compatibility import apply\nfrom . import threaded\n\n__all__ = ['do', 'value', 'Value']\n\n\ndef flat_unique(ls):\n    \"\"\"Flatten ``ls``, filter by unique id, and return a list\"\"\"\n    return list(unique(chain.from_iterable(ls), key=id))\n\n\ndef unzip(ls, nout):\n    \"\"\"Unzip a list of lists into ``nout`` outputs.\"\"\"\n    out = list(zip(*ls))\n    if not out:\n        out = [()] * nout\n    return out\n\n\ndef to_task_dasks(expr):\n    \"\"\"Normalize a python object and extract all sub-dasks.\n\n    - Replace ``Values`` with their keys\n    - Convert literals to things the schedulers can handle\n    - Extract dasks from all enclosed values\n\n    Parameters\n    ----------\n    expr : object\n        The object to be normalized. This function knows how to handle\n        ``Value``s, as well as most builtin python types.\n\n    Returns\n    -------\n    task : normalized task to be run\n    dasks : list of dasks that form the dag for this task\n\n    Examples\n    --------\n\n    >>> a = value(1, 'a')\n    >>> b = value(2, 'b')\n    >>> task, dasks = to_task_dasks([a, b, 3])\n    >>> task # doctest: +SKIP\n    (list, ['a', 'b', 3])\n    >>> dasks # doctest: +SKIP\n    [{'a': 1}, {'b': 2}]\n\n    >>> task, dasks = to_task_dasks({a: 1, b: 2})\n    >>> task # doctest: +SKIP\n    (dict, (list, [(list, ['a', 1]), (list, ['b', 2])]))\n    >>> dasks # doctest: +SKIP\n    [{'a': 1}, {'b': 2}]\n    \"\"\"\n    if isinstance(expr, Value):\n        return expr.key, expr._dasks\n    elif isinstance(expr, (Iterator, list, tuple, set)):\n        args, dasks = unzip(map(to_task_dasks, expr), 2)\n        args = list(args)\n        dasks = flat_unique(dasks)\n        # Ensure output type matches input type\n        if isinstance(expr, (list, tuple, set)):\n            return (type(expr), args), dasks\n        else:\n            return args, dasks\n    elif isinstance(expr, dict):\n        args, dasks = to_task_dasks(list([k, v] for k, v in expr.items()))\n        return (dict, args), dasks\n    else:\n        return expr, []\n\n\ntokens = ('_{0}'.format(i) for i in count(1))\n\n\ndef tokenize(v, pure=False):\n    \"\"\"Mapping function from task -> consistent name.\n\n    Parameters\n    ----------\n    v : object\n        Any python object (or tuple of objects) that summarize the task.\n    pure : boolean, optional\n        If True, a consistent hash function is tried on the input. If this\n        fails, then a unique identifier is used. If False (default), then a\n        unique identifier is always used.\n    \"\"\"\n    # TODO: May have hash collisions...\n    if pure:\n        try:\n            return str(hash(v))\n        except TypeError:\n            pass\n    return next(tokens)\n\n\ndef applyfunc(func, args, kwargs, pure=False):\n    \"\"\"Create a Value by applying a function to args.\n\n    Given a function and arguments, return a Value that represents the result\n    of that computation.\"\"\"\n\n    args, dasks = unzip(map(to_task_dasks, args), 2)\n    dasks = flat_unique(dasks)\n    name = tokenize((func, args, frozenset(kwargs.items())), pure)\n    if kwargs:\n        func = partial(func, **kwargs)\n    dasks.append({name: (func,) + args})\n    return Value(name, dasks)\n\n\n@curry\ndef do(func, pure=False):\n    \"\"\"Wraps a function so that it outputs a ``Value``.\n\n    Examples\n    --------\n    Can be used as a decorator:\n\n    >>> @do\n    ... def add(a, b):\n    ...     return a + b\n    >>> res = add(1, 2)\n    >>> type(res) == Value\n    True\n    >>> res.compute()\n    3\n\n    For other cases, it may be cleaner to call ``do`` on a function at call\n    time:\n\n    >>> res2 = do(sum)([res, 2, 3])\n    >>> res2.compute()\n    8\n\n    ``do`` also accepts an optional keyword ``pure``. If False (default), then\n    subsequent calls will always produce a different ``Value``. This is useful\n    for non-pure functions (such as ``time`` or ``random``).\n\n    >>> from random import random\n    >>> out1 = do(random)()\n    >>> out2 = do(random)()\n    >>> out1.key == out2.key\n    False\n\n    If you know a function is pure (output only depends on the input, with no\n    global state), then you can set ``pure=True``. This will attempt to apply a\n    consistent name to the output, but will fallback on the same behavior of\n    ``pure=False`` if this fails.\n\n    >>> @do(pure=True)\n    ... def add(a, b):\n    ...     return a + b\n    >>> out1 = add(1, 2)\n    >>> out2 = add(1, 2)\n    >>> out1.key == out2.key\n    True\n    \"\"\"\n    @wraps(func)\n    def _dfunc(*args, **kwargs):\n        return applyfunc(func, args, kwargs, pure=pure)\n    return _dfunc\n\n\ndef optimize(dsk, keys):\n    dsk2 = cull(dsk, keys)\n    return fuse(dsk2)\n\n\ndef get(dsk, keys, get=None, **kwargs):\n    \"\"\"Specialized get function\"\"\"\n    get = get or _globals['get'] or threaded.get\n    dsk2 = optimize(dsk, keys)\n    return get(dsk2, keys, **kwargs)\n\n\ndef right(method):\n    \"\"\"Wrapper to create 'right' version of operator given left version\"\"\"\n    def _inner(self, other):\n        return method(other, self)\n    return _inner\n\n\nclass Value(object):\n    \"\"\"Represents a value to be computed by dask.\n\n    Equivalent to the output from a single key in a dask graph.\n    \"\"\"\n    __slots__ = ('_key', '_dasks')\n\n    def __init__(self, name, dasks):\n        object.__setattr__(self, '_key', name)\n        object.__setattr__(self, '_dasks', dasks)\n\n    def compute(self, **kwargs):\n        \"\"\"Compute the result.\"\"\"\n        dask1 = cull(self.dask, self.key)\n        return get(dask1, self.key, **kwargs)\n\n    @property\n    def dask(self):\n        return merge(*self._dasks)\n\n    @property\n    def key(self):\n        return self._key\n\n    def visualize(self, optimize_graph=False, **kwargs):\n        \"\"\"Visualize the dask as a graph\"\"\"\n        from dask.dot import dot_graph\n        if optimize_graph:\n            return dot_graph(optimize(self.dask, self.key), **kwargs)\n        else:\n            return dot_graph(self.dask, **kwargs)\n\n    def __repr__(self):\n        return \"Value({0})\".format(repr(self.key))\n\n    def __hash__(self):\n        return hash(self.key)\n\n    def __dir__(self):\n        return list(self.__dict__.keys())\n\n    def __getattr__(self, attr):\n        if not attr.startswith('_'):\n            return do(getattr, True)(self, attr)\n        else:\n            raise AttributeError(\"Attribute {0} not found\".format(attr))\n\n    def __setattr__(self, attr, val):\n        raise TypeError(\"Value objects are immutable\")\n\n    def __setitem__(self, index, val):\n        raise TypeError(\"Value objects are immutable\")\n\n    def __iter__(self):\n        raise TypeError(\"Value objects are not iterable\")\n\n    def __call__(self, *args, **kwargs):\n        return do(apply)(self, args, kwargs)\n\n    def __bool__(self):\n        raise TypeError(\"Truth of Value objects is not supported\")\n\n    __nonzero__ = __bool__\n\n    __abs__ = do(operator.abs, True)\n    __add__ = do(operator.add, True)\n    __and__ = do(operator.and_, True)\n    __concat__ = do(operator.concat, True)\n    __delitem__ = do(operator.delitem, True)\n    __div__ = do(operator.floordiv, True)\n    __eq__ = do(operator.eq, True)\n    __floordiv__ = do(operator.floordiv, True)\n    __ge__ = do(operator.ge, True)\n    __getitem__ = do(operator.getitem, True)\n    __gt__ = do(operator.gt, True)\n    __index__ = do(operator.index, True)\n    __inv__ = do(operator.inv, True)\n    __invert__ = do(operator.invert, True)\n    __le__ = do(operator.le, True)\n    __lshift__ = do(operator.lshift, True)\n    __lt__ = do(operator.lt, True)\n    __mod__ = do(operator.mod, True)\n    __mul__ = do(operator.mul, True)\n    __ne__ = do(operator.ne, True)\n    __neg__ = do(operator.neg, True)\n    __not__ = do(operator.not_, True)\n    __or__ = do(operator.or_, True)\n    __pos__ = do(operator.pos, True)\n    __pow__ = do(operator.pow, True)\n    __radd__ = do(right(operator.add), True)\n    __rand__ = do(right(operator.and_), True)\n    __rdiv__ = do(right(operator.floordiv), True)\n    __rfloordiv__ = do(right(operator.floordiv), True)\n    __rlshift__ = do(right(operator.lshift), True)\n    __rmod__ = do(right(operator.mod), True)\n    __rmul__ = do(right(operator.mul), True)\n    __ror__ = do(right(operator.or_), True)\n    __rpow__ = do(right(operator.pow), True)\n    __rrshift__ = do(right(operator.rshift), True)\n    __rshift__ = do(operator.rshift, True)\n    __rsub__ = do(right(operator.sub), True)\n    __rtruediv__ = do(right(operator.truediv), True)\n    __rxor__ = do(right(operator.xor), True)\n    __sub__ = do(operator.sub, True)\n    __truediv__ = do(operator.truediv, True)\n    __xor__ = do(operator.xor, True)\n\n\ndef value(val, name=None):\n    \"\"\"Create a ``Value`` from a python object.\n\n    Parameters\n    ----------\n    val : object\n        Object to be wrapped.\n    name : string, optional\n        Name to be used in the resulting dask.\n\n    Examples\n    --------\n    >>> a = value([1, 2, 3])\n    >>> a.compute()\n    [1, 2, 3]\n\n    Values can act as a proxy to the underlying object. Many operators are\n    supported:\n\n    >>> (a + [1, 2]).compute()\n    [1, 2, 3, 1, 2]\n    >>> a[1].compute()\n    2\n\n    Method and attribute access also works:\n\n    >>> a.count(2).compute()\n    1\n\n    Note that if a method doesn't exist, no error will be thrown until runtime:\n\n    >>> res = a.not_a_real_method()\n    >>> res.compute()  # doctest: +SKIP\n    AttributeError(\"'list' object has no attribute 'not_a_real_method'\")\n    \"\"\"\n\n    name = name or tokenize(val, True)\n    task, dasks = to_task_dasks(val)\n    dasks.append({name: task})\n    return Value(name, dasks)\n", "path": "dask/imperative.py"}], "after_files": [{"content": "import operator\nfrom functools import partial, wraps\nfrom itertools import chain, count\nfrom collections import Iterator\n\nfrom toolz import merge, unique, curry\n\nfrom .optimize import cull, fuse\nfrom .context import _globals\nfrom .compatibility import apply\nfrom . import threaded\n\n__all__ = ['do', 'value', 'Value']\n\n\ndef flat_unique(ls):\n    \"\"\"Flatten ``ls``, filter by unique id, and return a list\"\"\"\n    return list(unique(chain.from_iterable(ls), key=id))\n\n\ndef unzip(ls, nout):\n    \"\"\"Unzip a list of lists into ``nout`` outputs.\"\"\"\n    out = list(zip(*ls))\n    if not out:\n        out = [()] * nout\n    return out\n\n\ndef to_task_dasks(expr):\n    \"\"\"Normalize a python object and extract all sub-dasks.\n\n    - Replace ``Values`` with their keys\n    - Convert literals to things the schedulers can handle\n    - Extract dasks from all enclosed values\n\n    Parameters\n    ----------\n    expr : object\n        The object to be normalized. This function knows how to handle\n        ``Value``s, as well as most builtin python types.\n\n    Returns\n    -------\n    task : normalized task to be run\n    dasks : list of dasks that form the dag for this task\n\n    Examples\n    --------\n\n    >>> a = value(1, 'a')\n    >>> b = value(2, 'b')\n    >>> task, dasks = to_task_dasks([a, b, 3])\n    >>> task # doctest: +SKIP\n    (list, ['a', 'b', 3])\n    >>> dasks # doctest: +SKIP\n    [{'a': 1}, {'b': 2}]\n\n    >>> task, dasks = to_task_dasks({a: 1, b: 2})\n    >>> task # doctest: +SKIP\n    (dict, (list, [(list, ['a', 1]), (list, ['b', 2])]))\n    >>> dasks # doctest: +SKIP\n    [{'a': 1}, {'b': 2}]\n    \"\"\"\n    if isinstance(expr, Value):\n        return expr.key, expr._dasks\n    elif isinstance(expr, (Iterator, list, tuple, set)):\n        args, dasks = unzip(map(to_task_dasks, expr), 2)\n        args = list(args)\n        dasks = flat_unique(dasks)\n        # Ensure output type matches input type\n        if isinstance(expr, (list, tuple, set)):\n            return (type(expr), args), dasks\n        else:\n            return args, dasks\n    elif isinstance(expr, dict):\n        args, dasks = to_task_dasks(list([k, v] for k, v in expr.items()))\n        return (dict, args), dasks\n    else:\n        return expr, []\n\n\ntokens = ('_{0}'.format(i) for i in count(1))\n\n\ndef tokenize(v, pure=False):\n    \"\"\"Mapping function from task -> consistent name.\n\n    Parameters\n    ----------\n    v : object\n        Any python object (or tuple of objects) that summarize the task.\n    pure : boolean, optional\n        If True, a consistent hash function is tried on the input. If this\n        fails, then a unique identifier is used. If False (default), then a\n        unique identifier is always used.\n    \"\"\"\n    # TODO: May have hash collisions...\n    if pure:\n        try:\n            return str(hash(v))\n        except TypeError:\n            pass\n    return next(tokens)\n\n\ndef applyfunc(func, args, kwargs, pure=False):\n    \"\"\"Create a Value by applying a function to args.\n\n    Given a function and arguments, return a Value that represents the result\n    of that computation.\"\"\"\n\n    args, dasks = unzip(map(to_task_dasks, args), 2)\n    dasks = flat_unique(dasks)\n    name = tokenize((func, args, frozenset(kwargs.items())), pure)\n    if kwargs:\n        func = partial(func, **kwargs)\n    dasks.append({name: (func,) + args})\n    return Value(name, dasks)\n\n\n@curry\ndef do(func, pure=False):\n    \"\"\"Wraps a function so that it outputs a ``Value``.\n\n    Examples\n    --------\n    Can be used as a decorator:\n\n    >>> @do\n    ... def add(a, b):\n    ...     return a + b\n    >>> res = add(1, 2)\n    >>> type(res) == Value\n    True\n    >>> res.compute()\n    3\n\n    For other cases, it may be cleaner to call ``do`` on a function at call\n    time:\n\n    >>> res2 = do(sum)([res, 2, 3])\n    >>> res2.compute()\n    8\n\n    ``do`` also accepts an optional keyword ``pure``. If False (default), then\n    subsequent calls will always produce a different ``Value``. This is useful\n    for non-pure functions (such as ``time`` or ``random``).\n\n    >>> from random import random\n    >>> out1 = do(random)()\n    >>> out2 = do(random)()\n    >>> out1.key == out2.key\n    False\n\n    If you know a function is pure (output only depends on the input, with no\n    global state), then you can set ``pure=True``. This will attempt to apply a\n    consistent name to the output, but will fallback on the same behavior of\n    ``pure=False`` if this fails.\n\n    >>> @do(pure=True)\n    ... def add(a, b):\n    ...     return a + b\n    >>> out1 = add(1, 2)\n    >>> out2 = add(1, 2)\n    >>> out1.key == out2.key\n    True\n    \"\"\"\n    @wraps(func)\n    def _dfunc(*args, **kwargs):\n        return applyfunc(func, args, kwargs, pure=pure)\n    return _dfunc\n\n\ndef optimize(dsk, keys):\n    dsk2 = cull(dsk, keys)\n    return fuse(dsk2)\n\n\ndef get(dsk, keys, get=None, **kwargs):\n    \"\"\"Specialized get function\"\"\"\n    get = get or _globals['get'] or threaded.get\n    dsk2 = optimize(dsk, keys)\n    return get(dsk2, keys, **kwargs)\n\n\ndef right(method):\n    \"\"\"Wrapper to create 'right' version of operator given left version\"\"\"\n    def _inner(self, other):\n        return method(other, self)\n    return _inner\n\n\nclass Value(object):\n    \"\"\"Represents a value to be computed by dask.\n\n    Equivalent to the output from a single key in a dask graph.\n    \"\"\"\n    __slots__ = ('_key', '_dasks')\n\n    def __init__(self, name, dasks):\n        object.__setattr__(self, '_key', name)\n        object.__setattr__(self, '_dasks', dasks)\n\n    def compute(self, **kwargs):\n        \"\"\"Compute the result.\"\"\"\n        dask1 = cull(self.dask, self.key)\n        return get(dask1, self.key, **kwargs)\n\n    @property\n    def dask(self):\n        return merge(*self._dasks)\n\n    @property\n    def key(self):\n        return self._key\n\n    def visualize(self, optimize_graph=False, **kwargs):\n        \"\"\"Visualize the dask as a graph\"\"\"\n        from dask.dot import dot_graph\n        if optimize_graph:\n            return dot_graph(optimize(self.dask, self.key), **kwargs)\n        else:\n            return dot_graph(self.dask, **kwargs)\n\n    def __repr__(self):\n        return \"Value({0})\".format(repr(self.key))\n\n    def __hash__(self):\n        return hash(self.key)\n\n    def __dir__(self):\n        return list(self.__dict__.keys())\n\n    def __getattr__(self, attr):\n        if not attr.startswith('_'):\n            return do(getattr, True)(self, attr)\n        else:\n            raise AttributeError(\"Attribute {0} not found\".format(attr))\n\n    def __setattr__(self, attr, val):\n        raise TypeError(\"Value objects are immutable\")\n\n    def __setitem__(self, index, val):\n        raise TypeError(\"Value objects are immutable\")\n\n    def __iter__(self):\n        raise TypeError(\"Value objects are not iterable\")\n\n    def __call__(self, *args, **kwargs):\n        return do(apply)(self, args, kwargs)\n\n    def __bool__(self):\n        raise TypeError(\"Truth of Value objects is not supported\")\n\n    __nonzero__ = __bool__\n\n    __abs__ = do(operator.abs, True)\n    __add__ = do(operator.add, True)\n    __and__ = do(operator.and_, True)\n    __div__ = do(operator.floordiv, True)\n    __eq__ = do(operator.eq, True)\n    __floordiv__ = do(operator.floordiv, True)\n    __ge__ = do(operator.ge, True)\n    __getitem__ = do(operator.getitem, True)\n    __gt__ = do(operator.gt, True)\n    __index__ = do(operator.index, True)\n    __invert__ = do(operator.invert, True)\n    __le__ = do(operator.le, True)\n    __lshift__ = do(operator.lshift, True)\n    __lt__ = do(operator.lt, True)\n    __mod__ = do(operator.mod, True)\n    __mul__ = do(operator.mul, True)\n    __ne__ = do(operator.ne, True)\n    __neg__ = do(operator.neg, True)\n    __or__ = do(operator.or_, True)\n    __pos__ = do(operator.pos, True)\n    __pow__ = do(operator.pow, True)\n    __radd__ = do(right(operator.add), True)\n    __rand__ = do(right(operator.and_), True)\n    __rdiv__ = do(right(operator.floordiv), True)\n    __rfloordiv__ = do(right(operator.floordiv), True)\n    __rlshift__ = do(right(operator.lshift), True)\n    __rmod__ = do(right(operator.mod), True)\n    __rmul__ = do(right(operator.mul), True)\n    __ror__ = do(right(operator.or_), True)\n    __rpow__ = do(right(operator.pow), True)\n    __rrshift__ = do(right(operator.rshift), True)\n    __rshift__ = do(operator.rshift, True)\n    __rsub__ = do(right(operator.sub), True)\n    __rtruediv__ = do(right(operator.truediv), True)\n    __rxor__ = do(right(operator.xor), True)\n    __sub__ = do(operator.sub, True)\n    __truediv__ = do(operator.truediv, True)\n    __xor__ = do(operator.xor, True)\n\n\ndef value(val, name=None):\n    \"\"\"Create a ``Value`` from a python object.\n\n    Parameters\n    ----------\n    val : object\n        Object to be wrapped.\n    name : string, optional\n        Name to be used in the resulting dask.\n\n    Examples\n    --------\n    >>> a = value([1, 2, 3])\n    >>> a.compute()\n    [1, 2, 3]\n\n    Values can act as a proxy to the underlying object. Many operators are\n    supported:\n\n    >>> (a + [1, 2]).compute()\n    [1, 2, 3, 1, 2]\n    >>> a[1].compute()\n    2\n\n    Method and attribute access also works:\n\n    >>> a.count(2).compute()\n    1\n\n    Note that if a method doesn't exist, no error will be thrown until runtime:\n\n    >>> res = a.not_a_real_method()\n    >>> res.compute()  # doctest: +SKIP\n    AttributeError(\"'list' object has no attribute 'not_a_real_method'\")\n    \"\"\"\n\n    name = name or tokenize(val, True)\n    task, dasks = to_task_dasks(val)\n    dasks.append({name: task})\n    return Value(name, dasks)\n", "path": "dask/imperative.py"}]}