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

Issue:
Unable to set alpha with parameter extracted using data.importConditions
Running standalone v2022.1.2 for MacOS 11.6.5, I was trying to run an experiment built with ExperimentBuilder version 3.2.3. The experiment fails with the following error:

    TypeError: Could not set alpha as value `0` of type `int64`
    
Tracing this back through the code, it appears that the alpha value is being set from a CSV file imported using `data.importConditions`. v2022.1.2's colors.py alpha setter looks like this:

    @alpha.setter
    def alpha(self, value):
        # Treat 1x1 arrays as a float
        if isinstance(value, np.ndarray):
            if value.size == 1:
                value = float(value)
        # Clip value(s) to within range
        if isinstance(value, np.ndarray):
            value = np.clip(value, 0, 1)
        elif isinstance(value, (int, float)):
            value = min(value,1)
            value = max(value,0)
        else:
            raise TypeError(
                "Could not set alpha as value `{}` of type `{}`".format(
                    value, type(value).__name__))
        self._alpha = value
        
But it appears that pandas is importing the integer value as a `pandas.Int64Dtype`. But as can be seen, it raises a type error because it isn't an instances of a np.ndarray, int, or float. Perhaps we could expand these checks to include some of the Extension Dtypes from pandas?


Discussion:

Resolving patch:
diff --git a/psychopy/colors.py b/psychopy/colors.py
--- a/psychopy/colors.py
+++ b/psychopy/colors.py
@@ -504,13 +504,17 @@ def alpha(self, value):
         # Clip value(s) to within range
         if isinstance(value, np.ndarray):
             value = np.clip(value, 0, 1)
-        elif isinstance(value, (int, float)):
-            value = min(value,1)
-            value = max(value,0)
         else:
-            raise TypeError(
-                "Could not set alpha as value `{}` of type `{}`".format(
-                    value, type(value).__name__))
+            # If coercible to float, do so
+            try:
+                value = float(value)
+            except (TypeError, ValueError) as err:
+                raise TypeError(
+                    "Could not set alpha as value `{}` of type `{}`".format(value, type(value).__name__)
+                )
+            value = min(value, 1)
+            value = max(value, 0)
+        # Set value
         self._alpha = value
 
     @property


Test patch:
Repository: psychopy/psychopy

Issue:
[bug] error with upgrade dialog by open it twice
If I open the upgrade dialog and then close the dialog, when trying to open the dialog again, it throws the following error info:

```
Traceback (most recent call last):
  File "D:\Program Files\Psychopy\lib\site-packages\psychopy\app\_psychopyApp.py", line 670, in openUpdater
    dlg = connections.InstallUpdateDialog(parent=None, ID=-1, app=self)
  File "D:\Program Files\Psychopy\lib\site-packages\psychopy\app\connections\updates.py", line 325, in __init__
    self.updateStatus()
  File "D:\Program Files\Psychopy\lib\site-packages\psychopy\app\connections\updates.py", line 341, in updateStatus
    elif (parse_version(self.latest['version'])
TypeError: 'NoneType' object is not subscriptable
```



Discussion:

Resolving patch:
diff --git a/psychopy/app/connections/updates.py b/psychopy/app/connections/updates.py
--- a/psychopy/app/connections/updates.py
+++ b/psychopy/app/connections/updates.py
@@ -82,7 +82,7 @@ def __init__(self, app=None, runningVersion=None):
             self.runningVersion = runningVersion
 
         # self.headers = {'User-Agent': psychopy.constants.PSYCHOPY_USERAGENT}
-        self.latest = None
+        self.latest = getLatestVersionInfo()
         if web.proxies is None:
             web.setupProxy()
 


Test patch:
Repository: psychopy/psychopy

Issue:
ExpInfo array not closed properly when no properties set in builder
In 2022.1.3 (Windows 64-bit), if you remove all start up properties in experiment settings (participant, session etc) so there is nothing at all, the python generated will not close the expInfo array correctly, leaving you with something like so:

expInfo = }

I've attached an example script for information.  It is rare that anyone would not want start up parameters, but there could well be instances (like we have had).

[expinfo-eg.zip](https://github.com/psychopy/psychopy/files/8583103/expinfo-eg.zip)




Discussion:
This is one of those that sits in between user error and bug - as there is a safe method to not show a dialog at all (deselecting "show info dialog"), but also PsychoPy should be able to handle blank values for that control. I'll look into making the code construction more robust to handle it.
Ah, I didn't notice the show info dialog option - thanks for flagging that up.

Resolving patch:
diff --git a/psychopy/experiment/components/settings/__init__.py b/psychopy/experiment/components/settings/__init__.py
--- a/psychopy/experiment/components/settings/__init__.py
+++ b/psychopy/experiment/components/settings/__init__.py
@@ -911,12 +911,28 @@ def writeStartCode(self, buff, version):
                     " this script\n")
             buff.writeIndented(code % self.params['expName'])
 
-        sorting = "False"  # in Py3 dicts are chrono-sorted so default no sort
-        expInfoStr = "{"
+        # Construct exp info string
+        expInfoDict = self.getInfo()
+        code = (
+            "expInfo = {"
+        )
+        if len(expInfoDict):
+            # Only make the dict multiline if it actually has contents
+            code += "\n"
+        buff.writeIndented(code)
+        buff.setIndentLevel(1, relative=True)
         for key, value in self.getInfo().items():
-            expInfoStr += f"'{key}': {value}, "
-        expInfoStr = expInfoStr[:-2] + "}"
-        buff.writeIndented("expInfo = %s\n" % expInfoStr)
+            code = (
+                f"'{key}': {value},\n"
+            )
+            buff.writeIndented(code)
+        buff.setIndentLevel(-1, relative=True)
+        code = (
+            "}\n"
+        )
+        buff.writeIndented(code)
+
+        sorting = "False"  # in Py3 dicts are chrono-sorted so default no sort
         if self.params['Show info dlg'].val:
             buff.writeIndentedLines(
                 f"dlg = gui.DlgFromDict(dictionary=expInfo, "


Test patch:
Repository: psychopy/psychopy

Issue:
Instantiating MoveStim3 object before SoundPyo object causes SoundPyo sampleRate argument to be silently ignored. 
I am using an [external USB audio interface](https://focusrite.com/en/usb-audio-interface/scarlett/scarlett-2i2)  to deliver ultrasonic vocalizations at 192kHz to mice, while also playing them silent natural-scene movies. I have discovered that unless the `noAudio` option is set to True when creatuing a `MovieStim3`  object, even if the video file has no audio track, the `sampleRate` argument to subsequently created `SoundPyo` objects is silently ignored, and auditory stimuli are instead downsampled to 44.1kHz. If the `SoundPyo` object is created before the `MoveStim3` object, this does not happen. 

Perhaps there is a way for `SoundPyo` to check if it has actually succeeded at setting the requested `sampleRate`, and having it raise an error or a warning if it has not? 

I discovered this issue by recording playback during an experiment with an ultrasonic microphone, and was puzzled when there was no frequency content above 22kHz when running my experiment, while there had been ultrasonic content while testing. 

Thanks for all the wonderful work you do with PsychoPy!


Discussion:
Thank you for your post. Looking at the code, the SoundPyo backend spawns a server to interface with the audio driver that is configured only on the first use. Sample rate cannot be changed in successive instances of `Sound` object. I'll add a warning for now since allowing multiple sample rates requires substantial changes right now. 

Resolving patch:
diff --git a/psychopy/sound/backend_pyo.py b/psychopy/sound/backend_pyo.py
--- a/psychopy/sound/backend_pyo.py
+++ b/psychopy/sound/backend_pyo.py
@@ -325,7 +325,16 @@ def __init__(self, value="C", secs=0.5, octave=4, stereo=True,
         if pyoSndServer is None or pyoSndServer.getIsBooted() == 0:
             init(rate=sampleRate)
 
-        self.sampleRate = pyoSndServer.getSamplingRate()
+        # Check if the user tried to change the sample rate. Since this isn't
+        # possible presently, just warn the user for now.
+        actualSampleRate = pyoSndServer.getSamplingRate()
+        if actualSampleRate != sampleRate:
+            logging.warning(
+                "Cannot change sample rate to {} since audio server has "
+                "already started, using {} instead.".format(
+                    sampleRate, actualSampleRate))
+
+        self.sampleRate = actualSampleRate
         self.format = bits
         self.isStereo = stereo
         self.channels = 1 + int(stereo)


Test patch:
Repository: psychopy/psychopy

Issue:
Timezones should be stored in the date by default
## Problem description

Currently, the experiment info contains the date of the experiment without a timezone. This would create problems when labs use the the same script across different timezones.

## Suggested solution

`utils.getDateStr()` should store the [local timezone](https://dateutil.readthedocs.io/en/stable/examples.html#tzlocal-examples) (or even better UTC - but this would require some awareness in the users). 


Discussion:

Resolving patch:
diff --git a/psychopy/data/utils.py b/psychopy/data/utils.py
--- a/psychopy/data/utils.py
+++ b/psychopy/data/utils.py
@@ -647,6 +647,9 @@ def getDateStr(format="%Y-%m-%d_%Hh%M.%S.%f", fractionalSecondDigits=3):
     Parameters
     ----------
     format : str
+        See the documentation for `datetime.datetime.strftime` for more
+        information on format syntax:
+        https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
         default="%Y-%m-%d_%Hh%M.%S.%f"
     fractionalSecondDigits : int
         An integer value 1-6 indicating the number of digits of fractional
@@ -655,7 +658,7 @@ def getDateStr(format="%Y-%m-%d_%Hh%M.%S.%f", fractionalSecondDigits=3):
         milliseconds you can set fractionalSecondDigits=3
 
     """
-    now = datetime.datetime.now()
+    now = datetime.datetime.now().astimezone()
     microsecs = now.strftime("%f")
     nowStr = now.strftime(format)
     if "%f" in format and (


Test patch:
Repository: psychopy/psychopy

Issue:
psychopy.visual compares numpy.array against string (FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison)
When passing a mat (numpy matrix) to e.g. ImageStim, we get the following warning:

```
/home/riveale/.local/lib/python3.10/site-packages/psychopy/visual/basevisual.py:952: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
  if tex in ["none", "None", "color"]:
```

The implementation in in psychopy.visual.basevisual.py:
```

if tex in ["none", "None", "color"]:
            tex = None
```

Does not check the type of tex first (which may be a numpy array, etc.). So, in the future, this may e.g. compare every element of the passed memory against the strings.

It should be changed to check the type of tex dynamically, e.g. lower down:
`
if type(tex) == numpy.ndarray:`


Discussion:

Resolving patch:
diff --git a/psychopy/visual/basevisual.py b/psychopy/visual/basevisual.py
--- a/psychopy/visual/basevisual.py
+++ b/psychopy/visual/basevisual.py
@@ -949,7 +949,7 @@ def _createTexture(self, tex, id, pixFormat, stim, res=128, maskParams=None,
         """
 
         # transform all variants of `None` to that, simplifies conditions below
-        if tex in ["none", "None", "color"]:
+        if isinstance(tex, str) and tex in ["none", "None", "color"]:
             tex = None
 
         # Create an intensity texture, ranging -1:1.0


Test patch:
Repository: psychopy/psychopy

Issue:
Joystick `Device is already open` exception with pyglet backend
With the pyglet backend, creating a second Joystick object results in an exception:

```python
>>> from psychopy.hardware import joystick
pygame 2.1.2 (SDL 2.0.16, Python 3.9.15)
Hello from the pygame community. https://www.pygame.org/contribute.html
>>> j = joystick.Joystick(0)
>>> j = joystick.Joystick(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/lkeegan/.pyenv/versions/3.9.15/lib/python3.9/site-packages/psychopy/hardware/joystick/__init__.py", line 109, in __init__
    self._device.open()
  File "/home/lkeegan/.pyenv/versions/3.9.15/lib/python3.9/site-packages/pyglet/input/base.py", line 466, in open
    self.device.open(window, exclusive)
  File "/home/lkeegan/.pyenv/versions/3.9.15/lib/python3.9/site-packages/pyglet/input/evdev.py", line 297, in open
    super(EvdevDevice, self).open(window, exclusive)
  File "/home/lkeegan/.pyenv/versions/3.9.15/lib/python3.9/site-packages/pyglet/input/base.py", line 102, in open
    raise DeviceOpenException('Device is already open.')
pyglet.input.base.DeviceOpenException: Device is already open.
```


Discussion:

Resolving patch:
diff --git a/psychopy/hardware/joystick/__init__.py b/psychopy/hardware/joystick/__init__.py
--- a/psychopy/hardware/joystick/__init__.py
+++ b/psychopy/hardware/joystick/__init__.py
@@ -105,7 +105,10 @@ def __init__(self, id):
                               "etc...)")
             else:
                 self._device = joys[id]
-                self._device.open()
+                try:
+                    self._device.open()
+                except pyglet_input.DeviceOpenException as e:
+                    pass
                 self.name = self._device.device.name
             if len(visual.openWindows) == 0:
                 logging.error(


Test patch:
Repository: psychopy/psychopy

Issue:
Can't log on to Pavlovia from Builder on first go
Description of the problem:
On the Builder, when I click "Pavlovia.org -> User -> Log in to Pavlovia...", I get the following error message.

Traceback (most recent call last):
  File "/home/johnmcbride/.local/lib/python3.8/site-packages/psychopy/app/pavlovia_ui/menu.py", line 121, in onLogInPavlovia
    logInPavlovia(parent=self.parent)
  File "/home/johnmcbride/.local/lib/python3.8/site-packages/psychopy/app/pavlovia_ui/functions.py", line 93, in logInPavlovia
    dlg = PavloviaMiniBrowser(parent=parent, loginOnly=True)
  File "/home/johnmcbride/.local/lib/python3.8/site-packages/psychopy/app/pavlovia_ui/_base.py", line 79, in __init__
    self.user = pavlovia.getCurrentSession().user
  File "/home/johnmcbride/.local/lib/python3.8/site-packages/psychopy/projects/pavlovia.py", line 442, in user
    if not hasattr(self.gitlab, "user") or self.gitlab.user.username is None:
AttributeError: 'NoneType' object has no attribute 'username'


I am new to using the Builder, so, this is my first time trying to log in to Pavlovia through the Builder. This problem occurred first while I was using psychopy version 2022.2; the problem persists after installing the latest (2023.1) version.

Upon inspection of "./psychopy/projects/pavlovia.py", it looks like line 442 might have a bug. When a PavloviaSession class is initialized without a token, self.gitlab.user is initialized as "None" (I checked that this is the case). Hence, line 442 "if not hasattr(self.gitlab, "user") or self.gitlab.user.username is None" will throw an error in this case.

In my case, the problem is solved by replacing lines 442-444 with the following:
` try:
    self._user = User(self.gitlab.user.username)
except:
    return None 
`


Discussion:
Thanks for catching this and for doing the legwork to track it down! Your solution seems reasonable - only thing is that we try to avoid using `except` without catching a specific exception type, so I think `except AttributeError` is better in this case. I'll apply your fix and put in a PR now :)

Resolving patch:
diff --git a/psychopy/projects/pavlovia.py b/psychopy/projects/pavlovia.py
--- a/psychopy/projects/pavlovia.py
+++ b/psychopy/projects/pavlovia.py
@@ -439,9 +439,10 @@ def startSession(self, token):
     @property
     def user(self):
         if not hasattr(self, "_user") or self._user is None:
-            if not hasattr(self.gitlab, "user") or self.gitlab.user.username is None:
+            try:
+                self._user = User(self.gitlab.user.username)
+            except AttributeError:
                 return None
-            self._user = User(self.gitlab.user.username)
         return self._user
 
     @user.setter


Test patch:
Repository: psychopy/psychopy

Issue:
viewport is None when checkTiming=False (2022.2.5)
```
from psychopy import visual, core

win = visual.Window(checkTiming=False) # works on 2022.2.4
# win = visual.Window(checkTiming=True) # works

txt = visual.TextStim(win)
txt.draw()  
win.flip()  

core.wait(2)  
win.close()

# Pyglet 1.5.27 vs. 1.4.11, Ubuntu 22.10, python 3.9.13
```



Discussion:
Ah, I see the problem here - if checkTiming is False then the initial frame rate test is skipped, and this is the only thing in Window.__init__ which calls Window.flip. Without that initial flip, the viewport remains as None as it hasn't been initialised yet. 

This has cropped up in this release due to a change in how viewport is set - previously it was set manually on init, now it's set by flip or by calling Window.resetViewport. Easy fix I believe, just need to add a call to that function to init if checkTiming is False. Thanks for catching this!

Resolving patch:
diff --git a/psychopy/visual/window.py b/psychopy/visual/window.py
--- a/psychopy/visual/window.py
+++ b/psychopy/visual/window.py
@@ -598,6 +598,9 @@ def __init__(self,
         self.monitorFramePeriod = 0.0
         if checkTiming:
             self._monitorFrameRate = self.getActualFrameRate()
+        else:
+            # if not checking timing, window still needs to initialise viewport
+            self.resetViewport()
         if self._monitorFrameRate is not None:
             self.monitorFramePeriod = 1.0 / self._monitorFrameRate
         else:


Test patch:
Repository: psychopy/psychopy

Issue:
error while doing semi automatic gamma correction
I've installed the latest version of psychopy standalone (2023.01) on windows 
while running the semi automatic gamma calibration,
After inserting the parameters in the luminance values table an clicking ok, this error appears

```
wx._core.wxAssertionError: C++ assertion "GetEventHandler() == this" failed at ..\..\src\common\wincmn.cpp(470) in wxWindowBase::~wxWindowBase(): any pushed event handlers must have been removed

The above exception was the direct cause of the following exception:

SystemError: <class 'wx._core.IdleEvent'> returned a result with an error set

```
I did change this line in MonitorCenter.py to make the table appear
butBox = wx.BoxSizer(wx.VERTICAL)

would really appreciate a fix or workaround to make the gamma correction work


Discussion:

Resolving patch:
diff --git a/psychopy/monitors/MonitorCenter.py b/psychopy/monitors/MonitorCenter.py
--- a/psychopy/monitors/MonitorCenter.py
+++ b/psychopy/monitors/MonitorCenter.py
@@ -1122,8 +1122,9 @@ def __init__(self, parent, levels):
         btnOK.SetDefault()
         btnCANC = wx.Button(panel, wx.ID_CANCEL, _translate(" Cancel "))
 
-        butBox.Add(btnOK, 1, wx.BOTTOM | wx.ALIGN_RIGHT, pad)
-        butBox.Add(btnCANC, 1, wx.BOTTOM | wx.RIGHT | wx.ALIGN_RIGHT, pad)
+        butBox.AddStretchSpacer(1)
+        butBox.Add(btnOK, 1, wx.BOTTOM, pad)
+        butBox.Add(btnCANC, 1, wx.BOTTOM | wx.RIGHT, pad)
         mainSizer.Add(butBox, flag=wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM,
                       border=10)
 


Test patch:
Repository: psychopy/psychopy

Issue:
AttributeError: 'SoundPTB' object has no attribute 'isFinished'
In the latest release: v2023.1.2 , the default sound library is PTB, and when using the builder sound component to run a WAV file, you get the following error message:

`AttributeError: 'SoundPTB' object has no attribute 'isFinished'`

This is tested on Windows 10, and after uninstalling and re-installing to double check.

Doesn't complain about ".status" or ".isPlaying" attributes that is also generated upon running the builder script.   I've not yet tested in v2023 versions prior. I can confirm that it is working fine in v2022.1.3 (which is the version we're fixed on for this academic year).

**EDIT:** Just tested in v2023.1.1 and no errors.



Discussion:

Resolving patch:
diff --git a/psychopy/sound/backend_ptb.py b/psychopy/sound/backend_ptb.py
--- a/psychopy/sound/backend_ptb.py
+++ b/psychopy/sound/backend_ptb.py
@@ -332,6 +332,7 @@ def __init__(self, value="C", secs=0.5, octave=4, stereo=-1,
         self.setSound(value, secs=self.secs, octave=self.octave,
                       hamming=self.hamming)
         self._isPlaying = False  # set `True` after `play()` is called
+        self._isFinished = False
         self.status = NOT_STARTED
 
     @property
@@ -339,6 +340,11 @@ def isPlaying(self):
         """`True` if the audio playback is ongoing."""
         return self._isPlaying
 
+    @property
+    def isFinsihed(self):
+        """`True` if the audio playback has completed."""
+        return self._isFinished
+
     def _getDefaultSampleRate(self):
         """Check what streams are open and use one of these"""
         if len(streams):
@@ -542,6 +548,7 @@ def play(self, loops=None, when=None, log=True):
             logTime = None
         self.track.start(repetitions=loops, when=when)
         self._isPlaying = True
+        self._isFinished = False
         # time.sleep(0.)
         if log and self.autoLog:
             logging.exp(u"Sound %s started" % (self.name), obj=self, t=logTime)
@@ -582,10 +589,11 @@ def _EOS(self, reset=True, log=True):
         self._loopsFinished += 1
         if self.loops == 0:
             self.stop(reset=reset, log=False)
+            self._isFinished = True
         elif 0 < self.loops <= self._loopsFinished:
             self.stop(reset=reset, log=False)
+            self._isFinished = True
 
-        self._isPlaying = False
         if log and self.autoLog:
             logging.exp(u"Sound %s reached end of file" % self.name, obj=self)
 


Test patch:
Repository: psychopy/psychopy

Issue:
Radio does not work in Slider component in 2023 versions (2023 ~ 2023.1.2)
When using the Slider componenet in 2023~ versions the the ‘radio’ does not work.

It does not show the ticks according to the presetted values, and when I click the radio button the experiment shuts down.

I think this is a bug as when I down grade to 2022.2.5 version, it works perfectly.




Discussion:

Resolving patch:
diff --git a/psychopy/visual/slider.py b/psychopy/visual/slider.py
--- a/psychopy/visual/slider.py
+++ b/psychopy/visual/slider.py
@@ -180,7 +180,6 @@ def __init__(self,
         self.ori = ori
         self.flip = flip
 
-        self.startValue = self.markerPos = startValue
         self.rt = None
         self.history = []
         self.marker = None
@@ -204,6 +203,8 @@ def __init__(self,
         # some things must wait until elements created
         self.contrast = 1.0
 
+        self.startValue = self.markerPos = startValue
+
         # set autoLog (now that params have been initialised)
         self.autoLog = autoLog
         if autoLog:


Test patch: