prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  visa_handle.clear on instantiation causes some instruments to freeze
  The use of visa_handle.clear on the instantiation of a VISA instrument causes some instruments to lock up. In particular I've noticed for SERIAL instruments, this command spews some garbage on the serial port that requires the instrument to be reset before it is possible to use it again.
  
  ### Steps to reproduce
  1. Plug in a buggy instrument and instantiate an instance of it.
  
  ### Actual behaviour
  The instrument freezes
  
  ### System
  Win 7
  Using the Harvard DecaDAC
  2b6d72b
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `qcodes/instrument/visa.py`
  Content:
  ```
  1 """Visa instrument driver based on pyvisa."""
  2 import visa
  3 
  4 from .base import Instrument
  5 import qcodes.utils.validators as vals
  6 
  7 
  8 class VisaInstrument(Instrument):
  9 
  10     """
  11     Base class for all instruments using visa connections.
  12 
  13     Args:
  14         name (str): What this instrument is called locally.
  15 
  16         address (str): The visa resource name to use to connect.
  17             Optionally includes '@<backend>' at the end. For example,
  18             'ASRL2' will open COM2 with the default NI backend, but
  19             'ASRL2@py' will open COM2 using pyvisa-py. Note that qcodes
  20             does not install (or even require) ANY backends, it is up to
  21             the user to do that. see eg:
  22             http://pyvisa.readthedocs.org/en/stable/names.html
  23 
  24         timeout (number): seconds to allow for responses. Default 5.
  25 
  26         terminator: Read termination character(s) to look for. Default ''.
  27 
  28         metadata (Optional[Dict]): additional static metadata to add to this
  29             instrument's JSON snapshot.
  30 
  31     See help for ``qcodes.Instrument`` for additional information on writing
  32     instrument subclasses.
  33 
  34     Attributes:
  35         visa_handle (pyvisa.resources.Resource): The communication channel.
  36     """
  37 
  38     def __init__(self, name, address=None, timeout=5, terminator='', **kwargs):
  39         super().__init__(name, **kwargs)
  40 
  41         self.add_parameter('timeout',
  42                            get_cmd=self._get_visa_timeout,
  43                            set_cmd=self._set_visa_timeout,
  44                            unit='s',
  45                            vals=vals.MultiType(vals.Numbers(min_value=0),
  46                                                vals.Enum(None)))
  47 
  48         self.set_address(address)
  49         self.set_terminator(terminator)
  50         self.timeout.set(timeout)
  51 
  52     def set_address(self, address):
  53         """
  54         Change the address for this instrument.
  55 
  56         Args:
  57             address: The visa resource name to use to connect.
  58                 Optionally includes '@<backend>' at the end. For example,
  59                 'ASRL2' will open COM2 with the default NI backend, but
  60                 'ASRL2@py' will open COM2 using pyvisa-py. Note that qcodes
  61                 does not install (or even require) ANY backends, it is up to
  62                 the user to do that.
  63                 see eg: http://pyvisa.readthedocs.org/en/stable/names.html
  64         """
  65         # in case we're changing the address - close the old handle first
  66         if getattr(self, 'visa_handle', None):
  67             self.visa_handle.close()
  68 
  69         if address and '@' in address:
  70             address, visa_library = address.split('@')
  71             resource_manager = visa.ResourceManager('@' + visa_library)
  72         else:
  73             resource_manager = visa.ResourceManager()
  74 
  75         self.visa_handle = resource_manager.open_resource(address)
  76 
  77         self.visa_handle.clear()
  78         self._address = address
  79 
  80     def set_terminator(self, terminator):
  81         r"""
  82         Change the read terminator to use.
  83 
  84         Args:
  85             terminator (str): Character(s) to look for at the end of a read.
  86                 eg. '\r\n'.
  87         """
  88         self.visa_handle.read_termination = terminator
  89         self._terminator = terminator
  90 
  91     def _set_visa_timeout(self, timeout):
  92         if timeout is None:
  93             self.visa_handle.timeout = None
  94         else:
  95             # pyvisa uses milliseconds but we use seconds
  96             self.visa_handle.timeout = timeout * 1000.0
  97 
  98     def _get_visa_timeout(self):
  99         timeout_ms = self.visa_handle.timeout
  100         if timeout_ms is None:
  101             return None
  102         else:
  103             # pyvisa uses milliseconds but we use seconds
  104             return timeout_ms / 1000
  105 
  106     def close(self):
  107         """Disconnect and irreversibly tear down the instrument."""
  108         if getattr(self, 'visa_handle', None):
  109             self.visa_handle.close()
  110         super().close()
  111 
  112     def check_error(self, ret_code):
  113         """
  114         Default error checking, raises an error if return code !=0.
  115 
  116         Does not differentiate between warnings or specific error messages.
  117         Override this function in your driver if you want to add specific
  118         error messages.
  119 
  120         Args:
  121             ret_code (int): A Visa error code. See eg:
  122                 https://github.com/hgrecco/pyvisa/blob/master/pyvisa/errors.py
  123 
  124         Raises:
  125             visa.VisaIOError: if ``ret_code`` indicates a communication
  126                 problem.
  127         """
  128         if ret_code != 0:
  129             raise visa.VisaIOError(ret_code)
  130 
  131     def write_raw(self, cmd):
  132         """
  133         Low-level interface to ``visa_handle.write``.
  134 
  135         Args:
  136             cmd (str): The command to send to the instrument.
  137         """
  138         nr_bytes_written, ret_code = self.visa_handle.write(cmd)
  139         self.check_error(ret_code)
  140 
  141     def ask_raw(self, cmd):
  142         """
  143         Low-level interface to ``visa_handle.ask``.
  144 
  145         Args:
  146             cmd (str): The command to send to the instrument.
  147 
  148         Returns:
  149             str: The instrument's response.
  150         """
  151         return self.visa_handle.ask(cmd)
  152 
  153     def snapshot_base(self, update=False):
  154         """
  155         State of the instrument as a JSON-compatible dict.
  156 
  157         Args:
  158             update (bool): If True, update the state by querying the
  159                 instrument. If False, just use the latest values in memory.
  160 
  161         Returns:
  162             dict: base snapshot
  163         """
  164         snap = super().snapshot_base(update=update)
  165 
  166         snap['address'] = self._address
  167         snap['terminator'] = self._terminator
  168         snap['timeout'] = self.timeout.get()
  169 
  170         return snap
  171
  ```
  --- 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()
  
  ```
  
golden_diff: diff --git a/qcodes/instrument/visa.py b/qcodes/instrument/visa.py
  --- a/qcodes/instrument/visa.py
  +++ b/qcodes/instrument/visa.py
  @@ -1,10 +1,11 @@
   """Visa instrument driver based on pyvisa."""
   import visa
  +import pyvisa.constants as vi_const
  +import pyvisa.resources
   
   from .base import Instrument
   import qcodes.utils.validators as vals
   
  -
   class VisaInstrument(Instrument):
   
       """
  @@ -74,7 +75,13 @@
   
           self.visa_handle = resource_manager.open_resource(address)
   
  -        self.visa_handle.clear()
  +        # Serial instruments have a separate flush method to clear their buffers
  +        # which behaves differently to clear. This is particularly important
  +        # for instruments which do not support SCPI commands.
  +        if isinstance(self.visa_handle, pyvisa.resources.SerialInstrument):
  +            self.visa_handle.flush(vi_const.VI_READ_BUF_DISCARD | vi_const.VI_WRITE_BUF_DISCARD)
  +        else:
  +            self.visa_handle.clear()
           self._address = address
   
       def set_terminator(self, terminator):
  
verification_info: {"golden_diff": "diff --git a/qcodes/instrument/visa.py b/qcodes/instrument/visa.py\n--- a/qcodes/instrument/visa.py\n+++ b/qcodes/instrument/visa.py\n@@ -1,10 +1,11 @@\n \"\"\"Visa instrument driver based on pyvisa.\"\"\"\n import visa\n+import pyvisa.constants as vi_const\n+import pyvisa.resources\n \n from .base import Instrument\n import qcodes.utils.validators as vals\n \n-\n class VisaInstrument(Instrument):\n \n     \"\"\"\n@@ -74,7 +75,13 @@\n \n         self.visa_handle = resource_manager.open_resource(address)\n \n-        self.visa_handle.clear()\n+        # Serial instruments have a separate flush method to clear their buffers\n+        # which behaves differently to clear. This is particularly important\n+        # for instruments which do not support SCPI commands.\n+        if isinstance(self.visa_handle, pyvisa.resources.SerialInstrument):\n+            self.visa_handle.flush(vi_const.VI_READ_BUF_DISCARD | vi_const.VI_WRITE_BUF_DISCARD)\n+        else:\n+            self.visa_handle.clear()\n         self._address = address\n \n     def set_terminator(self, terminator):\n", "issue": "visa_handle.clear on instantiation causes some instruments to freeze\nThe use of visa_handle.clear on the instantiation of a VISA instrument causes some instruments to lock up. In particular I've noticed for SERIAL instruments, this command spews some garbage on the serial port that requires the instrument to be reset before it is possible to use it again.\r\n\r\n### Steps to reproduce\r\n1. Plug in a buggy instrument and instantiate an instance of it.\r\n\r\n### Actual behaviour\r\nThe instrument freezes\r\n\r\n### System\r\nWin 7\r\nUsing the Harvard DecaDAC\r\n2b6d72b\n", "before_files": [{"content": "\"\"\"Visa instrument driver based on pyvisa.\"\"\"\nimport visa\n\nfrom .base import Instrument\nimport qcodes.utils.validators as vals\n\n\nclass VisaInstrument(Instrument):\n\n    \"\"\"\n    Base class for all instruments using visa connections.\n\n    Args:\n        name (str): What this instrument is called locally.\n\n        address (str): The visa resource name to use to connect.\n            Optionally includes '@<backend>' at the end. For example,\n            'ASRL2' will open COM2 with the default NI backend, but\n            'ASRL2@py' will open COM2 using pyvisa-py. Note that qcodes\n            does not install (or even require) ANY backends, it is up to\n            the user to do that. see eg:\n            http://pyvisa.readthedocs.org/en/stable/names.html\n\n        timeout (number): seconds to allow for responses. Default 5.\n\n        terminator: Read termination character(s) to look for. Default ''.\n\n        metadata (Optional[Dict]): additional static metadata to add to this\n            instrument's JSON snapshot.\n\n    See help for ``qcodes.Instrument`` for additional information on writing\n    instrument subclasses.\n\n    Attributes:\n        visa_handle (pyvisa.resources.Resource): The communication channel.\n    \"\"\"\n\n    def __init__(self, name, address=None, timeout=5, terminator='', **kwargs):\n        super().__init__(name, **kwargs)\n\n        self.add_parameter('timeout',\n                           get_cmd=self._get_visa_timeout,\n                           set_cmd=self._set_visa_timeout,\n                           unit='s',\n                           vals=vals.MultiType(vals.Numbers(min_value=0),\n                                               vals.Enum(None)))\n\n        self.set_address(address)\n        self.set_terminator(terminator)\n        self.timeout.set(timeout)\n\n    def set_address(self, address):\n        \"\"\"\n        Change the address for this instrument.\n\n        Args:\n            address: The visa resource name to use to connect.\n                Optionally includes '@<backend>' at the end. For example,\n                'ASRL2' will open COM2 with the default NI backend, but\n                'ASRL2@py' will open COM2 using pyvisa-py. Note that qcodes\n                does not install (or even require) ANY backends, it is up to\n                the user to do that.\n                see eg: http://pyvisa.readthedocs.org/en/stable/names.html\n        \"\"\"\n        # in case we're changing the address - close the old handle first\n        if getattr(self, 'visa_handle', None):\n            self.visa_handle.close()\n\n        if address and '@' in address:\n            address, visa_library = address.split('@')\n            resource_manager = visa.ResourceManager('@' + visa_library)\n        else:\n            resource_manager = visa.ResourceManager()\n\n        self.visa_handle = resource_manager.open_resource(address)\n\n        self.visa_handle.clear()\n        self._address = address\n\n    def set_terminator(self, terminator):\n        r\"\"\"\n        Change the read terminator to use.\n\n        Args:\n            terminator (str): Character(s) to look for at the end of a read.\n                eg. '\\r\\n'.\n        \"\"\"\n        self.visa_handle.read_termination = terminator\n        self._terminator = terminator\n\n    def _set_visa_timeout(self, timeout):\n        if timeout is None:\n            self.visa_handle.timeout = None\n        else:\n            # pyvisa uses milliseconds but we use seconds\n            self.visa_handle.timeout = timeout * 1000.0\n\n    def _get_visa_timeout(self):\n        timeout_ms = self.visa_handle.timeout\n        if timeout_ms is None:\n            return None\n        else:\n            # pyvisa uses milliseconds but we use seconds\n            return timeout_ms / 1000\n\n    def close(self):\n        \"\"\"Disconnect and irreversibly tear down the instrument.\"\"\"\n        if getattr(self, 'visa_handle', None):\n            self.visa_handle.close()\n        super().close()\n\n    def check_error(self, ret_code):\n        \"\"\"\n        Default error checking, raises an error if return code !=0.\n\n        Does not differentiate between warnings or specific error messages.\n        Override this function in your driver if you want to add specific\n        error messages.\n\n        Args:\n            ret_code (int): A Visa error code. See eg:\n                https://github.com/hgrecco/pyvisa/blob/master/pyvisa/errors.py\n\n        Raises:\n            visa.VisaIOError: if ``ret_code`` indicates a communication\n                problem.\n        \"\"\"\n        if ret_code != 0:\n            raise visa.VisaIOError(ret_code)\n\n    def write_raw(self, cmd):\n        \"\"\"\n        Low-level interface to ``visa_handle.write``.\n\n        Args:\n            cmd (str): The command to send to the instrument.\n        \"\"\"\n        nr_bytes_written, ret_code = self.visa_handle.write(cmd)\n        self.check_error(ret_code)\n\n    def ask_raw(self, cmd):\n        \"\"\"\n        Low-level interface to ``visa_handle.ask``.\n\n        Args:\n            cmd (str): The command to send to the instrument.\n\n        Returns:\n            str: The instrument's response.\n        \"\"\"\n        return self.visa_handle.ask(cmd)\n\n    def snapshot_base(self, update=False):\n        \"\"\"\n        State of the instrument as a JSON-compatible dict.\n\n        Args:\n            update (bool): If True, update the state by querying the\n                instrument. If False, just use the latest values in memory.\n\n        Returns:\n            dict: base snapshot\n        \"\"\"\n        snap = super().snapshot_base(update=update)\n\n        snap['address'] = self._address\n        snap['terminator'] = self._terminator\n        snap['timeout'] = self.timeout.get()\n\n        return snap\n", "path": "qcodes/instrument/visa.py"}], "after_files": [{"content": "\"\"\"Visa instrument driver based on pyvisa.\"\"\"\nimport visa\nimport pyvisa.constants as vi_const\nimport pyvisa.resources\n\nfrom .base import Instrument\nimport qcodes.utils.validators as vals\n\nclass VisaInstrument(Instrument):\n\n    \"\"\"\n    Base class for all instruments using visa connections.\n\n    Args:\n        name (str): What this instrument is called locally.\n\n        address (str): The visa resource name to use to connect.\n            Optionally includes '@<backend>' at the end. For example,\n            'ASRL2' will open COM2 with the default NI backend, but\n            'ASRL2@py' will open COM2 using pyvisa-py. Note that qcodes\n            does not install (or even require) ANY backends, it is up to\n            the user to do that. see eg:\n            http://pyvisa.readthedocs.org/en/stable/names.html\n\n        timeout (number): seconds to allow for responses. Default 5.\n\n        terminator: Read termination character(s) to look for. Default ''.\n\n        metadata (Optional[Dict]): additional static metadata to add to this\n            instrument's JSON snapshot.\n\n    See help for ``qcodes.Instrument`` for additional information on writing\n    instrument subclasses.\n\n    Attributes:\n        visa_handle (pyvisa.resources.Resource): The communication channel.\n    \"\"\"\n\n    def __init__(self, name, address=None, timeout=5, terminator='', **kwargs):\n        super().__init__(name, **kwargs)\n\n        self.add_parameter('timeout',\n                           get_cmd=self._get_visa_timeout,\n                           set_cmd=self._set_visa_timeout,\n                           unit='s',\n                           vals=vals.MultiType(vals.Numbers(min_value=0),\n                                               vals.Enum(None)))\n\n        self.set_address(address)\n        self.set_terminator(terminator)\n        self.timeout.set(timeout)\n\n    def set_address(self, address):\n        \"\"\"\n        Change the address for this instrument.\n\n        Args:\n            address: The visa resource name to use to connect.\n                Optionally includes '@<backend>' at the end. For example,\n                'ASRL2' will open COM2 with the default NI backend, but\n                'ASRL2@py' will open COM2 using pyvisa-py. Note that qcodes\n                does not install (or even require) ANY backends, it is up to\n                the user to do that.\n                see eg: http://pyvisa.readthedocs.org/en/stable/names.html\n        \"\"\"\n        # in case we're changing the address - close the old handle first\n        if getattr(self, 'visa_handle', None):\n            self.visa_handle.close()\n\n        if address and '@' in address:\n            address, visa_library = address.split('@')\n            resource_manager = visa.ResourceManager('@' + visa_library)\n        else:\n            resource_manager = visa.ResourceManager()\n\n        self.visa_handle = resource_manager.open_resource(address)\n\n        # Serial instruments have a separate flush method to clear their buffers\n        # which behaves differently to clear. This is particularly important\n        # for instruments which do not support SCPI commands.\n        if isinstance(self.visa_handle, pyvisa.resources.SerialInstrument):\n            self.visa_handle.flush(vi_const.VI_READ_BUF_DISCARD | vi_const.VI_WRITE_BUF_DISCARD)\n        else:\n            self.visa_handle.clear()\n        self._address = address\n\n    def set_terminator(self, terminator):\n        r\"\"\"\n        Change the read terminator to use.\n\n        Args:\n            terminator (str): Character(s) to look for at the end of a read.\n                eg. '\\r\\n'.\n        \"\"\"\n        self.visa_handle.read_termination = terminator\n        self._terminator = terminator\n\n    def _set_visa_timeout(self, timeout):\n        if timeout is None:\n            self.visa_handle.timeout = None\n        else:\n            # pyvisa uses milliseconds but we use seconds\n            self.visa_handle.timeout = timeout * 1000.0\n\n    def _get_visa_timeout(self):\n        timeout_ms = self.visa_handle.timeout\n        if timeout_ms is None:\n            return None\n        else:\n            # pyvisa uses milliseconds but we use seconds\n            return timeout_ms / 1000\n\n    def close(self):\n        \"\"\"Disconnect and irreversibly tear down the instrument.\"\"\"\n        if getattr(self, 'visa_handle', None):\n            self.visa_handle.close()\n        super().close()\n\n    def check_error(self, ret_code):\n        \"\"\"\n        Default error checking, raises an error if return code !=0.\n\n        Does not differentiate between warnings or specific error messages.\n        Override this function in your driver if you want to add specific\n        error messages.\n\n        Args:\n            ret_code (int): A Visa error code. See eg:\n                https://github.com/hgrecco/pyvisa/blob/master/pyvisa/errors.py\n\n        Raises:\n            visa.VisaIOError: if ``ret_code`` indicates a communication\n                problem.\n        \"\"\"\n        if ret_code != 0:\n            raise visa.VisaIOError(ret_code)\n\n    def write_raw(self, cmd):\n        \"\"\"\n        Low-level interface to ``visa_handle.write``.\n\n        Args:\n            cmd (str): The command to send to the instrument.\n        \"\"\"\n        nr_bytes_written, ret_code = self.visa_handle.write(cmd)\n        self.check_error(ret_code)\n\n    def ask_raw(self, cmd):\n        \"\"\"\n        Low-level interface to ``visa_handle.ask``.\n\n        Args:\n            cmd (str): The command to send to the instrument.\n\n        Returns:\n            str: The instrument's response.\n        \"\"\"\n        return self.visa_handle.ask(cmd)\n\n    def snapshot_base(self, update=False):\n        \"\"\"\n        State of the instrument as a JSON-compatible dict.\n\n        Args:\n            update (bool): If True, update the state by querying the\n                instrument. If False, just use the latest values in memory.\n\n        Returns:\n            dict: base snapshot\n        \"\"\"\n        snap = super().snapshot_base(update=update)\n\n        snap['address'] = self._address\n        snap['terminator'] = self._terminator\n        snap['timeout'] = self.timeout.get()\n\n        return snap\n", "path": "qcodes/instrument/visa.py"}]}