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

Issue:
Update the contributors section of the docs
As requested by @imphil in https://github.com/cocotb/cocotb/pull/1482, which I requested we revert in order to handle as a separate PR.

> Please remove the whole contributors section for now, it's outdated. You can replace it with something like:
> 
> ```rst
> cocotb is developed and maintained by an active community under the umbrella of the `Free and Open Source Silicon Foundation <https://www.fossi-foundation.org>`_. 
> 
> Our GitHub repository contains a list of all `contributors <https://github.com/cocotb/cocotb/graphs/contributors>`_. 
> ```
> 

In my opinion we should keep the old attributions too, in case they are historically interesting - although I don't think they need to be as visible as they are today.


Discussion:
Yes, they have to stay somewhere discoverable, but not on the quickstart page. 

Resolving patch:
diff --git a/documentation/source/conf.py b/documentation/source/conf.py
--- a/documentation/source/conf.py
+++ b/documentation/source/conf.py
@@ -69,7 +69,7 @@
 
 # General information about the project.
 project = 'cocotb'
-copyright = '2014-{0}, PotentialVentures'.format(datetime.datetime.now().year)
+copyright = '2014-{0}, cocotb contributors'.format(datetime.datetime.now().year)
 
 # The version info for the project you're documenting, acts as replacement for
 # |version| and |release|, also used in various other places throughout the
@@ -242,7 +242,7 @@
 # (source start file, target name, title, author, documentclass [howto/manual]).
 latex_documents = [
   ('index', 'cocotb.tex', 'cocotb Documentation',
-   'PotentialVentures', 'manual'),
+   'cocotb contributors', 'manual'),
 ]
 
 # The name of an image file (relative to this directory) to place at the top of
@@ -272,7 +272,7 @@
 # (source start file, name, description, authors, manual section).
 man_pages = [
     ('index', 'cocotb', 'cocotb Documentation',
-     ['PotentialVentures'], 1)
+     ['cocotb contributors'], 1)
 ]
 
 # If true, show URL addresses after external links.
@@ -286,7 +286,7 @@
 #  dir menu entry, description, category)
 texinfo_documents = [
   ('index', 'cocotb', 'cocotb Documentation',
-   'PotentialVentures', 'cocotb', 'Coroutine Cosimulation TestBench \
+   'cocotb contributors', 'cocotb', 'Coroutine Cosimulation TestBench \
      environment for efficient verification of RTL using Python.',
    'Miscellaneous'),
 ]


Test patch:
Repository: cocotb/cocotb

Issue:
Move utility scripts out of the cocotb package
We should introduce another namespace to put python libraries/scripts that don't depend on the cocotb runtime. For example, the build script.




Discussion:
In the case of the `build_ext` it probably should be merged into setup.py, as it is done in the [main python distribution](https://github.com/python/cpython/blob/master/setup.py).
But note that that setup.py imports `distutils`, so its still the case that not all the code is in one place. In my opinion the split aids clarity for now, so we should keep it as long as we do so in a way that doesn't cause other issues.
I tried just moving build libs into the top level, but the import fails when using tox. Perhaps there is some option to get tox to recognize it as a build dependency? CPython puts their `build_ext` overload in setup.py; it's a big file, I feel if they knew how to split it up, they would.
Did you remember to add it to `MANIFEST.in`?

https://github.com/cocotb/cocotb/pull/1568/files#diff-97c91a104c431d0c365565d3ac03ac13

Resolving patch:
diff --git a/cocotb/_build_libs.py b/cocotb_build_libs.py
similarity index 99%
rename from cocotb/_build_libs.py
rename to cocotb_build_libs.py
--- a/cocotb/_build_libs.py
+++ b/cocotb_build_libs.py
@@ -16,7 +16,7 @@
 
 
 logger = logging.getLogger(__name__)
-cocotb_share_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "share"))
+cocotb_share_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "cocotb", "share"))
 
 
 def _get_lib_ext_name():
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -53,10 +53,9 @@
 from os import path, walk
 from io import StringIO
 
-# note: cocotb is not installed properly yet, but we can import it anyway
-# because it's in the current directory. We'll need to change this if we
-# add `install_requires` to the `setup()` call.
-from cocotb._build_libs import get_ext, build_ext
+# Note: cocotb is not installed properly yet and is missing dependencies and binaries
+# We can still import other files next to setup.py, as long as they're in MANIFEST.in
+from cocotb_build_libs import get_ext, build_ext
 
 def read_file(fname):
     with open(path.join(path.dirname(__file__), fname), encoding='utf8') as f:


Test patch:
Repository: cocotb/cocotb

Issue:
Document how to get a rotating logger
In #1224 we had the request to support a "rotating" logger in cocotb. 
Now that #1266 has gone in there is a reasonably comfortable way to do that without modifying cocotb itself.

```python
root_logger = logging.getLogger()

# undo the setup cocotb did
for handler in root_logger.handlers:
    root_logger.remove_handler(handler)
    handler.close()

# do whatever configuration you want instead
file_handler = RotatingFileHandler(logfile, maxBytes=(1048576*5), backupCount=4)
file_handler.setFormatter(cocotb.log.SimLogFormatter())
root_logger.addHandler(file_handler)
```
at which point this seems like something that doesn't need to be in cocotb itself.

_Originally posted by @eric-wieser in https://github.com/cocotb/cocotb/pull/1224#issuecomment-581368001_


This issue is to document this as a useful snippet somewhere in the docs, as the general problem seems to be something other users might stumble across.


Discussion:

Resolving patch:
diff --git a/cocotb/log.py b/cocotb/log.py
--- a/cocotb/log.py
+++ b/cocotb/log.py
@@ -67,8 +67,10 @@ def default_config():
 
     If desired, this logging configuration can be overwritten by calling
     ``logging.basicConfig(..., force=True)`` (in Python 3.8 onwards), or by
-    manually resetting the root logger instance, for which examples can be
-    found online.
+    manually resetting the root logger instance.
+    An example of this can be found in the section on :ref:`rotating-logger`.
+
+    .. versionadded:: 1.4
     """
     # construct an appropriate handler
     hdlr = logging.StreamHandler(sys.stdout)
@@ -135,11 +137,13 @@ class SimTimeContextFilter(logging.Filter):
     This uses the approach described in the :ref:`Python logging cookbook <python:filters-contextual>`.
 
     This adds the :attr:`~logging.LogRecord.created_sim_time` attribute.
+
+    .. versionadded:: 1.4
     """
 
     # needed to make our docs render well
     def __init__(self):
-        """ Takes no arguments """
+        """"""
         super().__init__()
 
     def filter(self, record):


Test patch:
Repository: cocotb/cocotb

Issue:
AvalonSTPkts hexdump needs a minor fix now that the transaction is of type bytes rather than string
When DEBUG logging level is enabled, the `hexdump` call in `_monitor_recv` function of AvalonSTPkts calls hexdump after converting the `pkt` in to `str` which is no longer needed


Discussion:
Mind giving a filename and line number?
line 220 in `cocotb/cocotb/monitors/avalon.py`

https://github.com/cocotb/cocotb/blob/c7da01ce2d09aec7f76da9f1b802a3bd679942fc/cocotb/monitors/avalon.py#L220

Thanks, good find. Want to make a PR to fix that?
Sure, will do soon.

Resolving patch:
diff --git a/cocotb/monitors/avalon.py b/cocotb/monitors/avalon.py
--- a/cocotb/monitors/avalon.py
+++ b/cocotb/monitors/avalon.py
@@ -217,7 +217,7 @@ def valid():
 
                 if self.bus.endofpacket.value:
                     self.log.info("Received a packet of %d bytes", len(pkt))
-                    self.log.debug(hexdump(str((pkt))))
+                    self.log.debug(hexdump(pkt))
                     self.channel = channel
                     if self.report_channel:
                         self._recv({"data": pkt, "channel": channel})


Test patch:
Repository: cocotb/cocotb

Issue:
setup.py uses https://cocotb.org which doesn't work (yet)
We have 
https://github.com/cocotb/cocotb/blob/e74d508e30027c16778b95ef0985b6bcbc5207c2/setup.py#L90
which doesn't work (yet). Do we also want to use https://docs.cocotb.org temporarily like in GitHub?



Discussion:
Yes, let's do that.

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -87,7 +87,7 @@ def package_files(directory):
     cmdclass={'build_ext': build_ext},
     version=__version__,  # noqa: F821
     description='cocotb is a coroutine based cosimulation library for writing VHDL and Verilog testbenches in Python.',
-    url='https://cocotb.org',
+    url='https://docs.cocotb.org',
     license='BSD',
     long_description=read_file('README.md'),
     long_description_content_type='text/markdown',


Test patch:
Repository: cocotb/cocotb

Issue:
Change how we detect tests in test modules
On the gitter a user asked for help with an error that occured once he instantiated the MATLAB engine at the module level. When the regression manager was gathering tests, logs showed `Found test matlab.engine.matlabengine.<matlab.engine.matlabengine.MatlabFunc object at 0x00000000095873C8>` which implies the regression manager detected the MATLAB engine object as a cocotb test.

Requirements for a module-level object to be detected as a cocotb test are quite low. It just needs to pass a `hasattr(obj, "im_test")` check:
https://github.com/cocotb/cocotb/blob/ed2c954e9f0ad55eafc368432887dc58003227f3/cocotb/regression.py#L204-L206

We should make that requirement stricter with an `isinstance(obj, cocotb.test)` check. The regression manager already levies a number of other interface requirements on cocotb tests, so supporting duck typed tests is improbable; and if done by design can be achieve by inheriting from `cocotb.test`.


Discussion:

Resolving patch:
diff --git a/cocotb/regression.py b/cocotb/regression.py
--- a/cocotb/regression.py
+++ b/cocotb/regression.py
@@ -191,7 +191,7 @@ def _discover_tests() -> Iterable[Test]:
                         err = AttributeError("Test %s doesn't exist in %s" % (test_name, module_name))
                         raise err from None  # discard nested traceback
 
-                    if not hasattr(test, "im_test"):
+                    if not isinstance(test, Test):
                         _logger.error("Requested %s from module %s isn't a cocotb.test decorated coroutine",
                                       test_name, module_name)
                         raise ImportError("Failed to find requested test %s" % test_name)
@@ -202,7 +202,7 @@ def _discover_tests() -> Iterable[Test]:
 
             # auto-discover
             for thing in vars(module).values():
-                if hasattr(thing, "im_test"):
+                if isinstance(thing, Test):
                     yield thing
 
     @staticmethod


Test patch:
Repository: cocotb/cocotb

Issue:
SimFailure causes test results to be printed multiple times
There's a loop in `RegressionManager` on tests with `SimFailure` result that goes:

`_record_result` -> `tear_down` -> `_record_result` -> ...

And prints out the results multiple times.

See: https://travis-ci.org/github/cocotb/cocotb/jobs/686173872#L704

Found while reviewing #1793.


Discussion:

Resolving patch:
diff --git a/cocotb/regression.py b/cocotb/regression.py
--- a/cocotb/regression.py
+++ b/cocotb/regression.py
@@ -95,6 +95,7 @@ def __init__(self, dut: SimHandle, tests: Iterable[Test], hooks: Iterable[Hook])
         self.count = 0
         self.skipped = 0
         self.failures = 0
+        self._tearing_down = False
 
         # Setup XUnit
         ###################
@@ -229,6 +230,12 @@ def _init_hook(self, hook: Hook) -> Optional[RunningTask]:
             return cocotb.scheduler.add(test)
 
     def tear_down(self) -> None:
+        # prevent re-entering the tear down procedure
+        if not self._tearing_down:
+            self._tearing_down = True
+        else:
+            return
+
         # fail remaining tests
         while True:
             test = self.next_test()


Test patch:
Repository: cocotb/cocotb

Issue:
Document cocotb module variables
The `cocotb` module has some important variables which aren't documented:

- [ ] SIM_NAME
- [ ] SIM_VERSION
- [ ] RANDOM_SEED
- [ ] log
- [X] scheduler
- [ ] regression_manager
- [X] plusargs
- [ ] argv/argc
- [ ] LANGUAGE


Discussion:
Some related notes:

https://docs.cocotb.org/en/latest/library_reference.html?highlight=plusargs#cocotb.plusargs should get a backreference to https://docs.cocotb.org/en/latest/building.html?highlight=plusargs#var-PLUSARGS

Same for ``RANDOM_SEED`` once we add a docstring (https://docs.cocotb.org/en/latest/building.html#envvar-RANDOM_SEED).

Also, ``plusargs`` should be moved out of the "Utilities" section.

What's up with the different cases? Should they all be lowercased, or ``plusargs`` uppercased since it also comes from an envvar? (But then, ``SIM_*``  do not come from envvars.)
Yeah, it's not very apparent that they are there, so I guess people forget about them. We could provide aliases with a consistent casing? Not sure that's worth it though. I wonder if there is some better way to make that information available.

Resolving patch:
diff --git a/cocotb/__init__.py b/cocotb/__init__.py
--- a/cocotb/__init__.py
+++ b/cocotb/__init__.py
@@ -37,6 +37,7 @@
 import random
 import time
 import warnings
+from typing import Dict, List, Union
 
 import cocotb._os_compat  # must appear first, before the first import of cocotb.simulator
 import cocotb.handle
@@ -95,13 +96,35 @@ def _reopen_stream_with_buffering(stream_name):
 # so that cocotb.scheduler gives you the singleton instance and not the
 # scheduler package
 
-scheduler = None
+scheduler = None  # type: cocotb.scheduler.Scheduler
 """The global scheduler instance."""
 
-regression_manager = None
+regression_manager = None  # type: cocotb.regression.RegressionManager
+"""The global regression manager instance."""
 
-plusargs = {}
-"""A dictionary of "plusargs" handed to the simulation."""
+argv = None  # type: List[str]
+"""The argument list as seen by the simulator"""
+
+argc = None  # type: int
+"""The length of :data:`cocotb.argv`"""
+
+plusargs = None  # type: Dict[str, Union[bool, str]]
+"""A dictionary of "plusargs" handed to the simulation. See :make:var:`PLUSARGS` for details."""
+
+LANGUAGE = os.getenv("TOPLEVEL_LANG")  # type: str
+"""The value of :make:var:`TOPLEVEL_LANG`"""
+
+SIM_NAME = None  # type: str
+"""The running simulator product information. ``None`` if :mod:`cocotb` was not loaded from a simulator"""
+
+SIM_VERSION = None  # type: str
+"""The version of the running simulator. ``None`` if :mod:`cocotb` was not loaded from a simulator"""
+
+RANDOM_SEED = None  # type: int
+"""
+The value passed to the Python default random number generator.
+See :envvar:`RANDOM_SEED` for details on how the value is computed.
+"""
 
 
 def fork(coro):
@@ -112,8 +135,6 @@ def fork(coro):
 # FIXME is this really required?
 _rlock = threading.RLock()
 
-LANGUAGE = os.getenv("TOPLEVEL_LANG")
-
 
 def mem_debug(port):
     import cocotb.memdebug


Test patch:
Repository: cocotb/cocotb

Issue:
XGMII monitor crashes with AttributeError
`self._pkt` is initialized to `b""` (immutable), but we are using `.append()` to add payload data to it. This won't work. Maybe instead use a `bytearray()`?

_Originally posted by @LeChuck42 in https://github.com/cocotb/cocotb/pull/1545#issuecomment-635394899_

These lines exemplify the issue:

https://github.com/cocotb/cocotb/blob/924f35a3b7d39543118b7bfaed77dd4808e6612b/cocotb/monitors/xgmii.py#L107-L121


Discussion:

Resolving patch:
diff --git a/cocotb/monitors/xgmii.py b/cocotb/monitors/xgmii.py
--- a/cocotb/monitors/xgmii.py
+++ b/cocotb/monitors/xgmii.py
@@ -114,7 +114,7 @@ def _add_payload(self, ctrl, bytes):
                                   " ".join(["%02X" % b for b in bytes]))
                     self.log.info("ctrl = :" +
                                   " ".join(["%s" % str(c) for c in ctrl]))
-                    self._pkt = b""
+                    self._pkt = bytearray()
                 return False
 
             self._pkt.append(byte)
@@ -123,7 +123,7 @@ def _add_payload(self, ctrl, bytes):
     @cocotb.coroutine
     def _monitor_recv(self):
         clk = RisingEdge(self.clock)
-        self._pkt = b""
+        self._pkt = bytearray()
 
         while True:
             yield clk
@@ -154,7 +154,7 @@ def _monitor_recv(self):
                     self.log.error("Received a runt frame!")
                 if len(self._pkt) < 12:
                     self.log.error("No data to extract")
-                    self._pkt = b""
+                    self._pkt = bytearray()
                     continue
 
                 preamble_sfd = self._pkt[0:7]
@@ -164,7 +164,7 @@ def _monitor_recv(self):
                 if preamble_sfd != _PREAMBLE_SFD:
                     self.log.error("Got a frame with unknown preamble/SFD")
                     self.log.error(hexdump(preamble_sfd))
-                    self._pkt = b""
+                    self._pkt = bytearray()
                     continue
 
                 expected_crc = struct.pack("<I",
@@ -183,4 +183,4 @@ def _monitor_recv(self):
                     p = payload
 
                 self._recv(p)
-                self._pkt = b""
+                self._pkt = bytearray()


Test patch:
Repository: cocotb/cocotb

Issue:
Warn if attempting to schedule timers shorter than smallest simulation granularity
Just hit an issue where I was using `Timer(1)` on VHPI, which doesn't schedule callbacks in simulation units but absolute, it would seem.  It's therefore possible to schedule a timer smaller than the minimum simulation resolution.

See also #115.



Discussion:

Resolving patch:
diff --git a/cocotb/triggers.py b/cocotb/triggers.py
--- a/cocotb/triggers.py
+++ b/cocotb/triggers.py
@@ -33,7 +33,7 @@
 from cocotb import simulator
 from cocotb.log import SimLog
 from cocotb.utils import (
-    get_sim_steps, ParametrizedSingleton,
+    get_sim_steps, get_time_from_sim_steps, ParametrizedSingleton,
     lazy_property, remove_traceback_frames,
 )
 from cocotb import outcomes
@@ -196,13 +196,7 @@ def __init__(self, time_ps, units=None):
             :func:`~cocotb.utils.get_sim_steps`
         """
         GPITrigger.__init__(self)
-        self._time_ps = time_ps
-        self._units = units
-
-    @lazy_property
-    def sim_steps(self):
-        # lazy so we don't call into the simulator until we need to
-        return get_sim_steps(self._time_ps, self._units)
+        self.sim_steps = get_sim_steps(time_ps, units)
 
     def prime(self, callback):
         """Register for a timed callback."""
@@ -214,10 +208,9 @@ def prime(self, callback):
         GPITrigger.prime(self, callback)
 
     def __repr__(self):
-        return "<{} of {:1.2f}{} at {}>".format(
+        return "<{} of {:1.2f}ps at {}>".format(
             type(self).__qualname__,
-            self._time_ps,
-            self._units,
+            get_time_from_sim_steps(self.sim_steps, units='ps'),
             _pointer_str(self)
         )
 


Test patch:
Repository: cocotb/cocotb

Issue:
Start testing in Python 3.9
Python 3.9.0b1 is release already, and soon there'll be a full release. We should start running CI against it, to catch things like #1910


Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -112,6 +112,7 @@ def package_files(directory):
         "Programming Language :: Python :: 3.6",
         "Programming Language :: Python :: 3.7",
         "Programming Language :: Python :: 3.8",
+        "Programming Language :: Python :: 3.9",
         "License :: OSI Approved :: BSD License",
         "Topic :: Scientific/Engineering :: Electronic Design Automation (EDA)",
     ],


Test patch:
Repository: cocotb/cocotb

Issue:
GHDL waveform documentation
I could not find how to make a cocotb+ghdl sim produce a vcd waveform. I eventually tracked it down by looking at makefile.ghdl.  All that's needed is: make SIM=ghdl SIM_ARGS=--vcd=anyname.vcd.  I tried it on the dff example and it seems to work fine.
 
If you're interested, I added a waveform sub-section to the ghdl section of https://github.com/jwrr/cocotb/blob/readme/documentation/source/simulator_support.rst.  I used the Verilator waveform section as a template.



Discussion:
Some references:

- https://ghdl.readthedocs.io/en/latest/using/Simulation.html#export-waveforms
- ghdl/ghdl#1365
- https://github.com/umarcor/pulseview/tree/ghdl/ghdl

Resolving patch:
diff --git a/documentation/source/conf.py b/documentation/source/conf.py
--- a/documentation/source/conf.py
+++ b/documentation/source/conf.py
@@ -46,7 +46,10 @@
     'sphinx_tabs.tabs',
     ]
 
-intersphinx_mapping = {'python': ('https://docs.python.org/3', None)}
+intersphinx_mapping = {
+    'python': ('https://docs.python.org/3', None),
+    'ghdl': ('https://ghdl.readthedocs.io/en/latest', None)
+}
 
 # Github repo
 issues_github_path = "cocotb/cocotb"


Test patch:
Repository: cocotb/cocotb

Issue:
_def_name and _def_file mostly empty
I added ``_def_name`` and ``_def_file`` to ``test_discovery`` to see what it actually contains, and I found that only for the ``HierarchyArrayObject`` and one of the ``HierarchyObject``s the strings are not both empty: 
```
[...]
     0.00ns INFO     cocotb.sample_module                  test_discovery.py:44   in _discover                       Found name=test_and_gate def_name=and def_file= type=(<class 'cocotb.handle.HierarchyObject'>)
[...]
     0.00ns INFO     cocotb.sample_module                  test_discovery.py:44   in _discover                       Found name=stream_in_string def_name= def_file= type=(<class 'cocotb.handle.HierarchyObject'>)
     0.00ns INFO     cocotb.sample_module                  test_discovery.py:44   in _discover                       Found name=genblk1 def_name=sample_module def_file=/home/colin/tools/cocotb/tests/designs/sample_module/sample_module.sv type=(<class 'cocotb.handle.HierarchyArrayObject'>)
     0.00ns INFO     cocotb.sample_module                  test_discovery.py:44   in _discover                       Found name=genblk1[0] def_name= def_file= type=(<class 'cocotb.handle.HierarchyObject'>)
[...]
```
I'm not sure if this is intended or a regression.


Discussion:
For VPI, this is because the "definition name" `vpiDefName` property is defined for:
- instance objects (package, interface, program, module)
- ref object (see 37.15 of IEEE 1800-2012 SystemVerilog LRM)
- interface typespec
- primitives (gate, swithc, udp)
- udp definition

It shows up for `HierarchyArrayObject`s because they use the parent module handle.

"definition location" `vpiDefFile` is defined for instance objects and attributes.
Thanks for digging this up, something to put in the docstring. 
For VHPI, cocotb is using ``vhpiNameP`` (https://github.com/cocotb/cocotb/blob/master/cocotb/share/lib/vhpi/VhpiCbHdl.cpp#L244) which is the "name of the designated object in unspecified case for basic identifiers (VHDL is case insensitive) or case preserved for extended identifiers.", and ``vhpiFileNameP``.

Resolving patch:
diff --git a/cocotb/handle.py b/cocotb/handle.py
--- a/cocotb/handle.py
+++ b/cocotb/handle.py
@@ -96,10 +96,18 @@ def __init__(self, handle, path):
         self._def_name = self._handle.get_definition_name()  # type: str
         """The name of a GPI object's definition.
 
+        This is the value of ``vpiDefName`` for VPI, ``vhpiNameP`` for VHPI,
+        and ``mti_GetPrimaryName`` for FLI.
+        Support for this depends on the specific object type and simulator used.
+
         :meta public:
         """
         self._def_file = self._handle.get_definition_file()  # type: str
-        """The file that sources the object's definition.
+        """The name of the file that sources the object's definition.
+
+        This is the value of ``vpiDefFile`` for VPI, ``vhpiFileNameP`` for VHPI,
+        and ``mti_GetRegionSourceName`` for FLI.
+        Support for this depends on the specific object type and simulator used.
 
         :meta public:
         """


Test patch: