internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: vispy/vispy

Issue:
While dragging, event.button is 0 instead of the actual press button
One has to do `event.press_event.button` instead.



Discussion:

Resolving patch:
diff --git a/vispy/app/base.py b/vispy/app/base.py
--- a/vispy/app/base.py
+++ b/vispy/app/base.py
@@ -173,6 +173,8 @@ def _vispy_mouse_move(self, **kwds):
             last_event = self._vispy_mouse_data['last_event']
             if last_event is not None:
                 last_event._forget_last_event()
+        else:
+            kwds['button'] = self._vispy_mouse_data['press_event'].button
 
         ev = self._vispy_canvas.events.mouse_move(**kwds)
         self._vispy_mouse_data['last_event'] = ev
diff --git a/vispy/app/canvas.py b/vispy/app/canvas.py
--- a/vispy/app/canvas.py
+++ b/vispy/app/canvas.py
@@ -394,9 +394,11 @@ class MouseEvent(Event):
        String indicating the event type (e.g. mouse_press, key_release)
     pos : (int, int)
         The position of the mouse (in screen coordinates).
-    button : int
+    button : int | None
         The button that generated this event (can be None).
-        Left=1, right=2, middle=3.
+        Left=1, right=2, middle=3. During a mouse drag, this
+        will return the button that started the drag (same thing as
+        ``event.press_event.button``).
     buttons : [int, ...]
         The list of buttons depressed during this event.
     modifiers : tuple of Key instances
@@ -424,7 +426,7 @@ def __init__(self, type, pos=None, button=None, buttons=None,
                  **kwds):
         Event.__init__(self, type, **kwds)
         self._pos = (0, 0) if (pos is None) else (pos[0], pos[1])
-        self._button = int(button) if (button is not None) else 0
+        self._button = int(button) if (button is not None) else None
         self._buttons = [] if (buttons is None) else buttons
         self._modifiers = tuple(modifiers or ())
         self._delta = (0.0, 0.0) if (delta is None) else (delta[0], delta[1])


Test patch:
Repository: vispy/vispy

Issue:
The first emitted Timer event has `None` as `dt` property
``` python
def on_timer(self, event):
    print event.dt
```

displays `None` the first time, and the correct dt then (a float). The first dt should probably be `0.0`.



Discussion:
I actually think `None` makes more sense. If not `None`, then probably `np.inf` (or maybe even `np.nan`). If the idea is that `event.dt` gives you the time between the previous event and the current one, then it's undefined for the first event. However, I guess doing `np.inf` would functionally make the most sense since comparisons like `if dt > 1 / 60.:` would work. Is that what you want it for?

This is tough! `dt` is indeed undefined, so I lean towards None also. `inf` or `0.0` may make that calculations keep working (no `if dt is not None` required), but I guess dt will be often used in division, which would result in ZeroDivisionError. `inf` may also result in nasty behavior (we better not have someone do `time.sleep(dt)`. 

Another option is to set the start point when the user calls `Timer.start()`. That way the first dt measures the time since the timer started, which should be roughly the same interval as all subsequent timeouts..

> Another option is to set the start point when the user calls Timer.start(). That way the first dt measures the time since the timer started, which should be roughly the same interval as all subsequent timeouts..

+1

Doh! +1


Resolving patch:
diff --git a/vispy/app/timer.py b/vispy/app/timer.py
--- a/vispy/app/timer.py
+++ b/vispy/app/timer.py
@@ -103,7 +103,7 @@ def start(self, interval=None, iterations=None):
             self.max_iterations = iterations
         self._backend._vispy_start(self.interval)
         self._running = True
-        self._last_emit_time = None
+        self._last_emit_time = precision_time()
         self.events.start(type='timer_start')
 
     def stop(self):
@@ -139,10 +139,7 @@ def _timeout(self, *args):
 
         # compute dt since last event
         now = precision_time()
-        if self._last_emit_time is None:
-            dt = None
-        else:
-            dt = now - self._last_emit_time
+        dt = now - self._last_emit_time
         self._last_emit_time = now
 
         self.events.timeout(


Test patch:
Repository: vispy/vispy

Issue:
BUG: Mesh example doesn't rotate
I assume it's related to the `gloo` tweaks that were done recently, but `examples/visuals/mesh_visual.py` doesn't rotate. @lcampagn any idea?



Discussion:
I confirmed the `rotate` function is being called by adding a print statement, so it must be something else.

Yeah, at some point the system for simplifying transforms was changed, and this broke the connection between modifying the transform and updating the final program. Haven't gotten around to fixing it because we are currently working through an overhaul of the shader / program system anyway.

Cool, just wanted to make sure we were aware of it. It looks like the code used to have a TODO/Hack to get it to update by setting the `_program._need_build` property, looks like that's no longer a workaround.


Resolving patch:
diff --git a/examples/visuals/mesh_visual.py b/examples/visuals/mesh_visual.py
--- a/examples/visuals/mesh_visual.py
+++ b/examples/visuals/mesh_visual.py
@@ -92,9 +92,9 @@ def __init__(self):
         for i, mesh in enumerate(self.meshes):
             x = 2.0 * (i % grid[0]) / grid[0] + 4.0 / grid[0] - 2
             y = - 2.0 * (i // grid[1]) / grid[1] - 4.0 / grid[1] + 2
-            mesh.transform = ChainTransform([self.rotation,
-                                             STTransform(translate=(x, y),
-                                                         scale=(s, s, s))])
+            mesh.transform = ChainTransform([STTransform(translate=(x, y),
+                                                         scale=(s, s, s)),
+                                             self.rotation])
 
         vispy.app.Canvas.__init__(self, close_keys='escape')
         self.size = (800, 800)
diff --git a/vispy/scene/visuals/modular_visual.py b/vispy/scene/visuals/modular_visual.py
--- a/vispy/scene/visuals/modular_visual.py
+++ b/vispy/scene/visuals/modular_visual.py
@@ -9,7 +9,7 @@
 from ... import gloo
 from .visual import Visual
 from ..shaders import ModularProgram
-from ..transforms import ChainTransform
+#from ..transforms import ChainTransform
 from ..components import (VisualComponent, XYPosComponent, XYZPosComponent,
                           UniformColorComponent, VertexColorComponent)
 
@@ -358,7 +358,7 @@ def _activate_transform(self, event=None):
         # TODO: this must be optimized.
         # Allow using as plain visual or in a scenegraph
         t = self.transform if (event is None) else event.render_transform
-        if isinstance(t, ChainTransform):
-            t.simplify()  # Reduce number of transforms
+        #if isinstance(t, ChainTransform):
+        #    t.simplify()  # Reduce number of transforms
         #self._program['map_local_to_nd'] = self.transform.shader_map()
         self._program['map_local_to_nd'] = t.shader_map()


Test patch:
Repository: vispy/vispy

Issue:
Adding `elapsed` property to Timer event?
`event.elapsed` would be a shortcut to ~~`event.dt * event.iteration`~~. Actually it's a bit more complicated because `event.dt` is not constant, so it should rather be the sum of all `event.dt`s.



Discussion:
Would it be better to just return `ptime.time() - timer.start_time` ? Note that this would mean that calling `timer.elapsed` twice within an iteration would return different results (which I think would be the expected behavior).

Yes, probably, maybe using [default timer](https://docs.python.org/2/library/timeit.html#timeit.default_timer).

I was not aware of default_timer. We should test that on all platforms and see whether it can be used to replace `util.ptime`.

Oh, I didn't see there was a custom function here. I think it would be
better to use default_timer (I usually use this function), but it would
require some testing to be completely sure it's working fine. I'm going to
open a new issue.

> Yes, probably, maybe using default timer.

Or `time.perf_counter` on py33+ https://docs.python.org/dev/library/time.html#time.perf_counter


Resolving patch:
diff --git a/vispy/app/timer.py b/vispy/app/timer.py
--- a/vispy/app/timer.py
+++ b/vispy/app/timer.py
@@ -56,6 +56,7 @@ def __init__(self, interval=0.0, connect=None, iterations=-1, start=False,
 
         self._interval = interval
         self._running = False
+        self._first_emit_time = None
         self._last_emit_time = None
         self.iter_count = 0
         self.max_iterations = iterations
@@ -81,6 +82,10 @@ def interval(self, val):
             self.stop()
             self.start()
 
+    @property
+    def elapsed(self):
+        return precision_time() - self._first_emit_time
+
     @property
     def running(self):
         return self._running
@@ -103,6 +108,7 @@ def start(self, interval=None, iterations=None):
             self.max_iterations = iterations
         self._backend._vispy_start(self.interval)
         self._running = True
+        self._first_emit_time = precision_time()
         self._last_emit_time = precision_time()
         self.events.start(type='timer_start')
 
@@ -140,11 +146,13 @@ def _timeout(self, *args):
         # compute dt since last event
         now = precision_time()
         dt = now - self._last_emit_time
+        elapsed = now - self._first_emit_time
         self._last_emit_time = now
 
         self.events.timeout(
             type='timer_timeout',
             iteration=self.iter_count,
+            elapsed=elapsed,
             dt=dt)
         self.iter_count += 1
 


Test patch:
diff --git a/vispy/app/tests/test_app.py b/vispy/app/tests/test_app.py
--- a/vispy/app/tests/test_app.py
+++ b/vispy/app/tests/test_app.py
@@ -305,6 +305,8 @@ def fake(event):
         timer.interval = 0.002
         assert_equal(timer.interval, 0.002)
         assert_true(timer.running)
+        sleep(.003)
+        assert_true(timer.elapsed >= 0.002)
         timer.stop()
         assert_true(not timer.running)
         assert_true(timer.native)
Repository: vispy/vispy

Issue:
In ColorArray, implement __getitem__ and __setitem__
To access a single or a subset of colors.



Discussion:
PR welcome :)


Resolving patch:
diff --git a/vispy/color/_color.py b/vispy/color/_color.py
--- a/vispy/color/_color.py
+++ b/vispy/color/_color.py
@@ -303,6 +303,26 @@ def __eq__(self, other):
         return np.array_equal(self._rgba, other._rgba)
 
     ###########################################################################
+    def __getitem__(self, item):
+        if isinstance(item, tuple):
+            raise ValueError('ColorArray indexing is only allowed along '
+                             'the first dimension.')
+        subrgba = self._rgba[item]
+        if subrgba.ndim == 1:
+            assert len(subrgba) == 4
+        elif subrgba.ndim == 2:
+            assert subrgba.shape[1] in (3, 4)
+        return ColorArray(subrgba)
+        
+    def __setitem__(self, item, value):
+        if isinstance(item, tuple):
+            raise ValueError('ColorArray indexing is only allowed along '
+                             'the first dimension.')
+        # value should be a RGBA array, or a ColorArray instance
+        if isinstance(value, ColorArray):
+            value = value.rgba
+        self._rgba[item] = value
+    
     # RGB(A)
     @property
     def rgba(self):


Test patch:
diff --git a/vispy/color/tests/test_color.py b/vispy/color/tests/test_color.py
--- a/vispy/color/tests/test_color.py
+++ b/vispy/color/tests/test_color.py
@@ -23,6 +23,28 @@ def test_color():
     assert_array_equal(x.hsv, [240, 1, 1])
 
 
+def test_color_array():
+    """Basic tests for ColorArray class"""
+    x = ColorArray(['r', 'g', 'b'])
+    assert_array_equal(x.rgb, np.eye(3))
+    # Test ColorArray.__getitem__.
+    assert isinstance(x[0], ColorArray)
+    assert isinstance(x[:], ColorArray)
+    assert_array_equal(x.rgba[:], x[:].rgba)
+    assert_array_equal(x.rgba[0], x[0].rgba.squeeze())
+    assert_array_equal(x.rgba[1:3], x[1:3].rgba)
+    assert_raises(ValueError, x.__getitem__, (0, 1))
+    # Test ColorArray.__setitem__.
+    x[0] = 0
+    assert_array_equal(x.rgba[0, :], np.zeros(4))
+    assert_array_equal(x.rgba, x[:].rgba)
+    x[1] = 1
+    assert_array_equal(x[1].rgba, np.ones((1, 4)))
+    x[:] = .5
+    assert_array_equal(x.rgba, .5 * np.ones((3, 4)))
+    assert_raises(ValueError, x.__setitem__, (0, 1), 0)
+
+
 def test_color_interpretation():
     """Test basic color interpretation API"""
     # test useful ways of single color init
Repository: vispy/vispy

Issue:
Error "no module named widgets" when using ipynb examples
```
/home/luke/vispy/vispy/app/application.py in _use(self, backend_name)
    158                 if not try_others:
    159                     # Fail if user wanted to use a specific backend
--> 160                     raise RuntimeError(msg)
    161                 elif key in imported_toolkits:
    162                     # Warn if were unable to use an already imported toolkit

RuntimeError: Could not import backend "ipynb_vnc":
No module named widgets
```

Hints?



Discussion:
You have IPython 2.0+?

No. Perhaps this should be detected and provide a more helpful error..

(ubuntu currently has 1.2.1, so there are bound to be many users with the same issue)

+1, I thought it was already the case! I may do a PR later, unless @almarklein beats me to it...

I doubt that I won't :)

Euh.. I mean I doubt that I will


Resolving patch:
diff --git a/vispy/app/backends/_ipynb_vnc.py b/vispy/app/backends/_ipynb_vnc.py
--- a/vispy/app/backends/_ipynb_vnc.py
+++ b/vispy/app/backends/_ipynb_vnc.py
@@ -18,7 +18,7 @@
                     BaseTimerBackend)
 from .. import Application, Canvas
 from ...util import logger
-from ...util.event import Event  # For timer
+#from ...util.event import Event  # For timer
 
 # Imports for screenshot
 # Perhaps we should refactor these to have just one import
@@ -69,6 +69,9 @@ def _set_config(c):
 else:
     # Try importing IPython
     try:
+        import IPython
+        if IPython.version_info < (2,):
+            raise RuntimeError('ipynb_vnc backend need IPython version >= 2.0')
         from IPython.html.widgets import DOMWidget
         from IPython.utils.traitlets import Unicode, Int, Float, Bool
         from IPython.display import display, Javascript
@@ -219,7 +222,7 @@ def _on_draw(self, event=None):
         # Handle initialization
         if not self._initialized:
             self._initialized = True
-            self._vispy_canvas.events.add(timer=Event)
+            #self._vispy_canvas.events.add(timer=Event)
             self._vispy_canvas.events.initialize()
             self._on_resize()
 
@@ -305,7 +308,8 @@ def _gen_event(self, ev):
             if self._need_draw:
                 self._on_draw()
             # Generate a timer event on every poll from JS
-            self._vispy_canvas.events.timer(type="timer")
+            # AK: no, just use app.Timer as usual!
+            #self._vispy_canvas.events.timer(type="timer")
 
     def _prepare_js(self):
         pkgdir = op.dirname(__file__)


Test patch:
Repository: vispy/vispy

Issue:
Bug when running Vispy offline for the first time
There appears to be a bug when you run Vispy offline and you don't have the freetype thing already downloaded. Not completely sure about the exact conditions responsible for the crash, require some testing...



Discussion:
If you're offline then it shouldn't be able to download the library, and it should give an error saying it couldn't import it. Is this what you mean by "crash"? I guess we should raise a clearer `ImportError` and say people either need to have Freetype installed and available on their system, or be connected to the internet.

but what if I don't need to use freetype in my visualization? I may want to
be able to use Vispy offline without showing text

2014-08-26 17:45 GMT+01:00 Eric89GXL notifications@github.com:

> If you're offline then it shouldn't be able to download the library, and
> it should give an error saying it couldn't import it. Is this what you mean
> by "crash"? I guess we should raise a clearer ImportError and say people
> either need to have Freetype installed and available on their system, or be
> connected to the internet.
> 
> —
> Reply to this email directly or view it on GitHub
> https://github.com/vispy/vispy/issues/462#issuecomment-53451389.

Oh, right. Yes, in principle it should only give an error if you try to use `freetype` / fonts / text. I can open a PR for it. Do you have a suitable test setup?


Resolving patch:
diff --git a/vispy/util/fonts/_freetype.py b/vispy/util/fonts/_freetype.py
--- a/vispy/util/fonts/_freetype.py
+++ b/vispy/util/fonts/_freetype.py
@@ -9,9 +9,6 @@
 import sys
 import numpy as np
 
-from ...ext.freetype import (FT_LOAD_RENDER, FT_LOAD_NO_HINTING,
-                             FT_LOAD_NO_AUTOHINT, Face)
-
 
 # Convert face to filename
 from ._vispy_fonts import _vispy_fonts, _get_vispy_font_filename
@@ -25,7 +22,11 @@
 _font_dict = {}
 
 
+# Nest freetype imports in case someone doesn't have freetype on their system
+# and isn't using fonts (Windows)
+
 def _load_font(face, bold, italic):
+    from ...ext.freetype import Face
     key = '%s-%s-%s' % (face, bold, italic)
     if key in _font_dict:
         return _font_dict[key]
@@ -40,6 +41,8 @@ def _load_font(face, bold, italic):
 
 def _load_glyph(f, char, glyphs_dict):
     """Load glyph from font into dict"""
+    from ...ext.freetype import (FT_LOAD_RENDER, FT_LOAD_NO_HINTING,
+                                 FT_LOAD_NO_AUTOHINT)
     flags = FT_LOAD_RENDER | FT_LOAD_NO_HINTING | FT_LOAD_NO_AUTOHINT
     face = _load_font(f['face'], f['bold'], f['italic'])
     face.set_char_size(f['size'] * 64)


Test patch:
Repository: vispy/vispy

Issue:
Adding more documentation
Currently, we only have the API reference. There's no other documentation at the moment.

Here are a few references we could take inspiration from/copy.
- [@rougier's tutorial](http://www.loria.fr/~rougier/teaching/opengl/)
- Recipe from the IPython Cookbook (link coming soon)
- [Paper in Frontiers in Neuroinformatics](http://journal.frontiersin.org/Journal/10.3389/fninf.2013.00036/full)



Discussion:

Resolving patch:
diff --git a/vispy/__init__.py b/vispy/__init__.py
--- a/vispy/__init__.py
+++ b/vispy/__init__.py
@@ -8,25 +8,13 @@
 Vispy
 =====
 
-Vispy is a collaborative project that has the goal to allow more sharing
-of code between visualization projects based on OpenGL. It does this
-by providing powerful interfaces to OpenGL, at different levels of
-abstraction and generality.
-
-Vispy consists of the following modules:
-  * vispy.app: for creating windows, timers and mainloops for various backends
-  * vispy.gloo: Object oriented GL API
-  * vispy.gloo.gl: Low level OpenGL API
-  * vispy.util: various utilities
-  * vispy.scene: Higher level visualization objects (work in progress)
-  * vispy.mpl_plot: matplotlib interface (work in progress)
-  * ... more to come
-
-Vispy comes with a powerful event system and a simple application
-framework that works on multiple backends. This allows easy creation
-of figures, and enables integrating visualizations in a GUI application.
-
-For more information see http://vispy.org.
+Vispy is a **high-performance interactive 2D/3D data visualization
+library**. Vispy leverages the computational power of modern **Graphics
+Processing Units (GPUs)** through the **OpenGL** library to display very
+large datasets.
+
+For more information, see http://vispy.org.
+
 """
 
 from __future__ import division


Test patch:
Repository: vispy/vispy

Issue:
Add left/right arrows on the carousel



Discussion:
@Eric89GXL you want to do it? I'm not sure I'll have time to do it today. Hopefully we can make the release today...

@rossant @almarklein if you can give me a link to the example you built the current carousel off of, I can give it a shot, yeah

I found the relevant code. I'll see if I can figure it out.

For future reference it lives in `_website/_scripts.py`


Resolving patch:
diff --git a/make/make.py b/make/make.py
--- a/make/make.py
+++ b/make/make.py
@@ -209,7 +209,7 @@ def images(self, arg):
             return self.help('images')
 
         # Create subdirs if needed
-        for subdir in ['gallery', 'thumbs', 'test']:
+        for subdir in ['gallery', 'thumbs', 'carousel', 'test']:
             subdir = op.join(IMAGES_DIR, subdir)
             if not op.isdir(subdir):
                 os.mkdir(subdir)
@@ -307,7 +307,7 @@ def grabscreenshot(event):
             # Get canvas
             if hasattr(m, 'canvas'):
                 c = m.canvas  # scene examples
-            elif hasattr(m, 'Canvas'):  
+            elif hasattr(m, 'Canvas'):
                 c = m.Canvas()
             else:
                 print('Ignore: %s, no canvas' % name)
@@ -334,16 +334,25 @@ def _images_thumbnails(self):
         import numpy as np
         gallery_dir = op.join(IMAGES_DIR, 'gallery')
         thumbs_dir = op.join(IMAGES_DIR, 'thumbs')
+        carousel_dir = op.join(IMAGES_DIR, 'carousel')
         for fname in os.listdir(gallery_dir):
             filename1 = op.join(gallery_dir, fname)
             filename2 = op.join(thumbs_dir, fname)
+            filename3 = op.join(carousel_dir, fname)
             #
             im = imread(filename1)
+
             newx = 200
             newy = int(newx * im.shape[0] / im.shape[1])
             im = (resize(im, (newy, newx), 2) * 255).astype(np.uint8)
             imsave(filename2, im)
-            print('Created thumbnail %s' % fname)
+
+            newy = 160  # This should match the carousel size!
+            newx = int(newy * im.shape[1] / im.shape[0])
+            im = (resize(im, (newy, newx), 1) * 255).astype(np.uint8)
+            imsave(filename3, im)
+
+            print('Created thumbnail and carousel %s' % fname)
 
     def copyright(self, arg):
         """ Update all copyright notices to the current year.
@@ -421,12 +430,14 @@ def sphinx_clean(build_dir):
 
 def sphinx_build(src_dir, build_dir):
     import sphinx
-    sphinx.main(('sphinx-build',  # Dummy
-                 '-b', 'html',
-                 '-d', op.join(build_dir, 'doctrees'),
-                 src_dir,  # Source
-                 op.join(build_dir, 'html'),  # Dest
-                 ))
+    ret = sphinx.main(('sphinx-build',  # Dummy
+                       '-b', 'html',
+                       '-d', op.join(build_dir, 'doctrees'),
+                       src_dir,  # Source
+                       op.join(build_dir, 'html'),  # Dest
+                       ))
+    if ret != 0:
+        raise RuntimeError('Sphinx error: %s' % ret)
     print("Build finished. The HTML pages are in %s/html." % build_dir)
 
 


Test patch: