nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: dask/dask
Pull request #4387 (2019-01-15 14:53:25)

Calling np.dtype on a delayed object works
Calling `np.dtype(dask.delayed(...))` used to result in a segfault, as
numpy recursively tries to get `dtype` from the object. This is likely a
bug in numpy. For now, we can do a dumb check for if `x.dtype.dtype` is
called (which shouldn't ever show up in real code).

See https://github.com/dask/dask/pull/4374#issuecomment-454381465.



Patch:
diff --git a/dask/delayed.py b/dask/delayed.py
index 836493a4d..8ea647869 100644
--- a/dask/delayed.py
+++ b/dask/delayed.py
@@ -606,6 +606,16 @@ class DelayedAttr(Delayed):
         self._attr = attr
         self._key = 'getattr-%s' % tokenize(obj, attr, pure=True)
 
+    def __getattr__(self, attr):
+        # Calling np.dtype(dask.delayed(...)) used to result in a segfault, as
+        # numpy recursively tries to get `dtype` from the object. This is
+        # likely a bug in numpy. For now, we can do a dumb for if
+        # `x.dtype().dtype()` is called (which shouldn't ever show up in real
+        # code). See https://github.com/dask/dask/pull/4374#issuecomment-454381465
+        if attr == 'dtype' and self._attr == 'dtype':
+            raise AttributeError("Attribute %s not found" % attr)
+        super(DelayedAttr, self).__getattr__(attr)
+
     @property
     def dask(self):
         layer = {self._key: (getattr, self._obj._key, self._attr)}


Test patch:
diff --git a/dask/tests/test_delayed.py b/dask/tests/test_delayed.py
index 66516846a..5a378f0e4 100644
--- a/dask/tests/test_delayed.py
+++ b/dask/tests/test_delayed.py
@@ -161,6 +161,16 @@ def test_method_getattr_call_same_task():
     assert getattr not in set(v[0] for v in o.__dask_graph__().values())
 
 
+def test_np_dtype_of_delayed():
+    # This used to result in a segfault due to recursion, see
+    # https://github.com/dask/dask/pull/4374#issuecomment-454381465
+    np = pytest.importorskip('numpy')
+    x = delayed(1)
+    with pytest.raises(TypeError):
+        np.dtype(x)
+    assert delayed(np.array([1], dtype='f8')).dtype.compute() == np.dtype('f8')
+
+
 def test_delayed_errors():
     a = delayed([1, 2, 3])
     # Immutable
Repository: dask/dask
Pull request #4502 (2019-02-19 02:31:41)

implement out_type for bag.fold
Fixes https://github.com/dask/dask/issues/4433

- [ ] Tests added / passed
- [ ] Passes `flake8 dask`


jcrist: LGTM. Thanks.

Patch:
diff --git a/dask/bag/core.py b/dask/bag/core.py
index a4983b96a..141ade7e2 100644
--- a/dask/bag/core.py
+++ b/dask/bag/core.py
@@ -727,7 +727,8 @@ class Bag(DaskMethodsMixin):
         return to_avro(self, filename, schema, name_function, storage_options,
                        codec, sync_interval, metadata, compute, **kwargs)
 
-    def fold(self, binop, combine=None, initial=no_default, split_every=None):
+    def fold(self, binop, combine=None, initial=no_default, split_every=None,
+             out_type=Item):
         """ Parallelizable reduction
 
         Fold is like the builtin function ``reduce`` except that it works in
@@ -777,11 +778,11 @@ class Bag(DaskMethodsMixin):
         if initial is not no_default:
             return self.reduction(curry(_reduce, binop, initial=initial),
                                   curry(_reduce, combine),
-                                  split_every=split_every)
+                                  split_every=split_every, out_type=out_type)
         else:
             from toolz.curried import reduce
             return self.reduction(reduce(binop), reduce(combine),
-                                  split_every=split_every)
+                                  split_every=split_every, out_type=out_type)
 
     def frequencies(self, split_every=None, sort=False):
         """ Count number of occurrences of each distinct element.


Test patch:
diff --git a/dask/bag/tests/test_bag.py b/dask/bag/tests/test_bag.py
index 022f0733d..116b41b99 100644
--- a/dask/bag/tests/test_bag.py
+++ b/dask/bag/tests/test_bag.py
@@ -218,6 +218,15 @@ def test_fold():
     assert set(e.fold(add, initial=[]).compute(scheduler='sync')) == set([1, 2, 3])
 
 
+def test_fold_bag():
+    def binop(tot, x):
+        tot.add(x)
+        return tot
+    c = b.fold(binop, combine=set.union, initial=set(), out_type=Bag)
+    assert isinstance(c, Bag)
+    assert_eq(c, list(set(range(5))))
+
+
 def test_distinct():
     assert sorted(b.distinct()) == [0, 1, 2, 3, 4]
     assert b.distinct().name == b.distinct().name
Repository: bluesky/bluesky
Pull request #1507 (2022-02-28 18:40:48)

ENH: don't call stage unless stageable
Some of the device objects we are passing into bluesky happen to have an attribute `stage` that has nothing to do with Bluesky's concept of `Stageable`. Since we already have protocols, we can use them to make the run engine smart enough to not attempt calling `stage` on our objects.

There are other places in the run engine where protocols could be used, but I'm going to ignore those in favor of solving the problem in front of us now.

As always, feel free to reject or propose alternative solutions. If the answer is "please don't ever pass anything with attribute `stage` this is expected behavior" we can work with that.

## Description

Replace `hasattr(obj, 'stage')` with `isinstance(obj, bs_protocols.Stageable)`.

## Motivation and Context

See https://gitlab.com/yaq/yaqd-attune/-/issues/6

## How Has This Been Tested?

Tests written.


Patch:
diff --git a/bluesky/run_engine.py b/bluesky/run_engine.py
index c9ddf9d8..a58ff869 100644
--- a/bluesky/run_engine.py
+++ b/bluesky/run_engine.py
@@ -14,6 +14,7 @@ import weakref
 from dataclasses import dataclass
 import typing
 from .bundlers import RunBundler
+from . import protocols as bs_protocols
 
 import concurrent
 
@@ -2316,7 +2317,7 @@ class RunEngine:
         """
         _, obj, args, kwargs, _ = msg
         # If an object has no 'stage' method, assume there is nothing to do.
-        if not hasattr(obj, 'stage'):
+        if not isinstance(obj, bs_protocols.Stageable):
             return []
         result = obj.stage()
         self._staged.add(obj)  # add first in case of failure below
@@ -2332,7 +2333,7 @@ class RunEngine:
         """
         _, obj, args, kwargs, _ = msg
         # If an object has no 'unstage' method, assume there is nothing to do.
-        if not hasattr(obj, 'unstage'):
+        if not isinstance(obj, bs_protocols.Stageable):
             return []
         result = obj.unstage()
         # use `discard()` to ignore objects that are not in the staged set.


Test patch:
diff --git a/bluesky/tests/test_run_engine.py b/bluesky/tests/test_run_engine.py
index a9762a77..43952b3c 100644
--- a/bluesky/tests/test_run_engine.py
+++ b/bluesky/tests/test_run_engine.py
@@ -339,6 +339,26 @@ def test_stage_and_unstage_are_optional_methods(RE):
     RE([Msg('stage', dummy), Msg('unstage', dummy)])
 
 
+def test_need_both_stage_and_unstage_for_stagable(RE):
+    class StageOnly(object):
+
+        def stage(self):
+            raise Exception
+
+    class UnstageOnly(object):
+
+        def unstage(self):
+            raise Exception
+
+    stage_only = StageOnly()
+    unstage_only = UnstageOnly()
+    RE([Msg("stage", stage_only),
+        Msg("stage", unstage_only),
+        Msg("unstage", stage_only),
+        Msg("unstage", unstage_only)]
+       )
+
+
 def test_pause_resume_devices(RE):
     paused = {}
     resumed = {}
Repository: bluesky/bluesky
Pull request #1699 (2024-04-15 18:57:19)

[ENH] Add __main__.py and entrypoint for checking version info.
<!--- Provide a general summary of your changes in the Title above -->

## Description
Adding `__main__.py` with simple main entrypoint that prints version, update `pyproject.toml`.

## Motivation and Context

Solves #1667

## How Has This Been Tested?

```
(venv) [jwlodek@vdi-10-65-15-187 bluesky]$ which python
~/Workspace/bluesky/venv/bin/python
(venv) [jwlodek@vdi-10-65-15-187 bluesky]$ python --version
Python 3.11.5
(venv) [jwlodek@vdi-10-65-15-187 bluesky]$ python -m bluesky --version
1.13.0a4.dev31+g6168e9d0.d20240415
```

<!--
## Screenshots (if appropriate):
-->



Patch:
diff --git a/src/bluesky/__main__.py b/src/bluesky/__main__.py
new file mode 100644
index 00000000..79a4266c
--- /dev/null
+++ b/src/bluesky/__main__.py
@@ -0,0 +1,16 @@
+from argparse import ArgumentParser
+
+from . import __version__
+
+__all__ = ["main"]
+
+
+def main(args=None):
+    parser = ArgumentParser()
+    parser.add_argument("-v", "--version", action="version", version=__version__)
+    args = parser.parse_args(args)
+
+
+# test with: python -m bluesky
+if __name__ == "__main__":
+    main()


Test patch:
diff --git a/src/bluesky/tests/test_cli.py b/src/bluesky/tests/test_cli.py
new file mode 100644
index 00000000..6dc25faa
--- /dev/null
+++ b/src/bluesky/tests/test_cli.py
@@ -0,0 +1,9 @@
+import subprocess
+import sys
+
+from bluesky import __version__
+
+
+def test_cli_version():
+    cmd = [sys.executable, "-m", "bluesky", "--version"]
+    assert subprocess.check_output(cmd).decode().strip() == __version__
Repository: bluesky/bluesky
Pull request #1787 (2024-08-06 08:52:56)

re-apply the livescatter axes fix from PR 1523
<!--- Provide a general summary of your changes in the Title above -->

## Description
<!--- Describe your changes in detail -->

re-applied changed from https://github.com/bluesky/bluesky/pull/1523


Patch:
diff --git a/src/bluesky/callbacks/mpl_plotting.py b/src/bluesky/callbacks/mpl_plotting.py
index 27641e9b..a0dc03f1 100644
--- a/src/bluesky/callbacks/mpl_plotting.py
+++ b/src/bluesky/callbacks/mpl_plotting.py
@@ -378,12 +378,12 @@ class LiveScatter(QtAwareCallback):
         self.sc.set_array(np.asarray(self._Idata))
 
         if self.xlim is None:
-            minx, maxx = np.minimum(x, self._minx), np.maximum(x, self._maxx)
-            self.ax.set_xlim(minx, maxx)
+            self.minx, self.maxx = np.minimum(x, self._minx), np.maximum(x, self._maxx)
+            self.ax.set_xlim(self.minx, self.maxx)
 
         if self.ylim is None:
-            miny, maxy = np.minimum(y, self._miny), np.maximum(y, self._maxy)
-            self.ax.set_ylim(miny, maxy)
+            self.miny, self.maxy = np.minimum(y, self._miny), np.maximum(y, self._maxy)
+            self.ax.set_ylim(self.miny, self.maxy)
 
         if self.clim is None:
             clim = np.nanmin(self._Idata), np.nanmax(self._Idata)


Test patch:
diff --git a/src/bluesky/tests/test_callbacks.py b/src/bluesky/tests/test_callbacks.py
index 734033a9..45abcb8e 100644
--- a/src/bluesky/tests/test_callbacks.py
+++ b/src/bluesky/tests/test_callbacks.py
@@ -14,14 +14,7 @@ import bluesky.preprocessors as bpp
 from bluesky.callbacks import CallbackBase, CallbackCounter, LiveFit, LiveTable
 from bluesky.callbacks.broker import BrokerCallbackBase
 from bluesky.callbacks.core import make_callback_safe, make_class_safe
-from bluesky.callbacks.mpl_plotting import (
-    LiveFitPlot,
-    LiveGrid,
-    LiveMesh,
-    LivePlot,
-    LiveRaster,
-    LiveScatter,
-)
+from bluesky.callbacks.mpl_plotting import LiveFitPlot, LiveGrid, LiveMesh, LivePlot, LiveRaster, LiveScatter
 from bluesky.plan_stubs import pause
 from bluesky.plans import count, grid_scan, inner_product_scan, scan
 from bluesky.preprocessors import run_wrapper, subs_wrapper
@@ -389,6 +382,19 @@ def test_live_scatter(RE, hw):
         )
 
 
+def test_live_scatter_auto_range(RE, hw):
+    cb = LiveScatter("motor1", "motor2", "det5")
+    RE(grid_scan([hw.det5], hw.motor1, -3, 3, 6, hw.motor2, -5, 5, 10, False), cb)
+    assert cb.minx is not None
+    assert cb.maxx is not None
+    assert cb.miny is not None
+    assert cb.maxy is not None
+    assert cb.ax.get_xlim()[0] == -3
+    assert cb.ax.get_xlim()[1] == 3
+    assert cb.ax.get_ylim()[0] == -5
+    assert cb.ax.get_ylim()[1] == 5
+
+
 @pytest.mark.xfail(
     raises=NotImplementedError, reason="This tests an API databroker has removed, and needs updating."
 )