gurudesh/pytracebugs huggingface dataset:
# Buggy code
def murder_keepalived(self):
    now = time.time()
    while True:
        with self._lock:
            try:
                # remove the connection from the queue
                conn = self._keep.popleft()
            except IndexError:
                break

        delta = conn.timeout - now
        if delta > 0:
            # add the connection back to the queue
            with self._lock:
                self._keep.appendleft(conn)
            break
        else:
            self.nr_conns -= 1
            # remove the socket from the poller
            with self._lock:
                try:
                    self.poller.unregister(conn.sock)
                except socket.error as e:
                    if e.args[0] != errno.EBADF:
                        raise

            # close the socket
            conn.close()


# Traceback (BrokenPipeError)
[2014-11-17 04:18:49 -0500] [13520] [ERROR] Error handling request
Traceback (most recent call last):
File "/usr/local/lib/python3.4/site-packages/gunicorn/workers/async.py", line 108, in handle_request
resp.write(item)
File "/usr/local/lib/python3.4/site-packages/gunicorn/http/wsgi.py", line 344, in write
util.write(self.sock, arg, self.chunked)
File "/usr/local/lib/python3.4/site-packages/gunicorn/util.py", line 301, in write
sock.sendall(data)
File "/usr/local/lib/python3.4/site-packages/eventlet/greenio.py", line 375, in sendall
tail = self.send(data, flags)
File "/usr/local/lib/python3.4/site-packages/eventlet/greenio.py", line 358, in send
total_sent += fd.send(data[total_sent:], flags)
File "/usr/local/lib/python3.4/site-packages/eventlet/greenio.py", line 351, in send
return fd.send(data, flags)
BrokenPipeError: [Errno 32] Broken pipe

# Fixed code
def murder_keepalived(self):
    now = time.time()
    while True:
        with self._lock:
            try:
                # remove the connection from the queue
                conn = self._keep.popleft()
            except IndexError:
                break

        delta = conn.timeout - now
        if delta > 0:
            # add the connection back to the queue
            with self._lock:
                self._keep.appendleft(conn)
            break
        else:
            self.nr_conns -= 1
            # remove the socket from the poller
            with self._lock:
                try:
                    self.poller.unregister(conn.sock)
                except EnvironmentError as e:
                    if e.errno != errno.EBADF:
                        raise

            # close the socket
            conn.close()
# Buggy code
def run_for_one(self, timeout):
    listener = self.sockets[0]
    while self.alive:
        self.notify()

        # Accept a connection. If we get an error telling us
        # that no connection is waiting we fall down to the
        # select which is where we'll wait for a bit for new
        # workers to come give us some love.
        try:
            self.accept(listener)
            # Keep processing clients until no one is waiting. This
            # prevents the need to select() for every client that we
            # process.
            continue

        except socket.error as e:
            if e.args[0] not in (errno.EAGAIN, errno.ECONNABORTED, errno.EWOULDBLOCK):
                raise

        if not self.is_parent_alive():
            return

        try:
            self.wait(timeout)
        except StopWaiting:
            return


# Traceback (BrokenPipeError)
[2014-11-17 04:18:49 -0500] [13520] [ERROR] Error handling request
Traceback (most recent call last):
File "/usr/local/lib/python3.4/site-packages/gunicorn/workers/async.py", line 108, in handle_request
resp.write(item)
File "/usr/local/lib/python3.4/site-packages/gunicorn/http/wsgi.py", line 344, in write
util.write(self.sock, arg, self.chunked)
File "/usr/local/lib/python3.4/site-packages/gunicorn/util.py", line 301, in write
sock.sendall(data)
File "/usr/local/lib/python3.4/site-packages/eventlet/greenio.py", line 375, in sendall
tail = self.send(data, flags)
File "/usr/local/lib/python3.4/site-packages/eventlet/greenio.py", line 358, in send
total_sent += fd.send(data[total_sent:], flags)
File "/usr/local/lib/python3.4/site-packages/eventlet/greenio.py", line 351, in send
return fd.send(data, flags)
BrokenPipeError: [Errno 32] Broken pipe

# Fixed code
def run_for_one(self, timeout):
    listener = self.sockets[0]
    while self.alive:
        self.notify()

        # Accept a connection. If we get an error telling us
        # that no connection is waiting we fall down to the
        # select which is where we'll wait for a bit for new
        # workers to come give us some love.
        try:
            self.accept(listener)
            # Keep processing clients until no one is waiting. This
            # prevents the need to select() for every client that we
            # process.
            continue

        except EnvironmentError as e:
            if e.errno not in (errno.EAGAIN, errno.ECONNABORTED, errno.EWOULDBLOCK):
                raise

        if not self.is_parent_alive():
            return

        try:
            self.wait(timeout)
        except StopWaiting:
            return
# Buggy code
def run_for_multiple(self, timeout):
    while self.alive:
        self.notify()

        try:
            ready = self.wait(timeout)
        except StopWaiting:
            return

        if ready is not None:
            for listener in ready:
                try:
                    self.accept(listener)
                except socket.error as e:
                    if e.args[0] not in (
                        errno.EAGAIN,
                        errno.ECONNABORTED,
                        errno.EWOULDBLOCK,
                    ):
                        raise

        if not self.is_parent_alive():
            return


# Traceback (BrokenPipeError)
[2014-11-17 04:18:49 -0500] [13520] [ERROR] Error handling request
Traceback (most recent call last):
File "/usr/local/lib/python3.4/site-packages/gunicorn/workers/async.py", line 108, in handle_request
resp.write(item)
File "/usr/local/lib/python3.4/site-packages/gunicorn/http/wsgi.py", line 344, in write
util.write(self.sock, arg, self.chunked)
File "/usr/local/lib/python3.4/site-packages/gunicorn/util.py", line 301, in write
sock.sendall(data)
File "/usr/local/lib/python3.4/site-packages/eventlet/greenio.py", line 375, in sendall
tail = self.send(data, flags)
File "/usr/local/lib/python3.4/site-packages/eventlet/greenio.py", line 358, in send
total_sent += fd.send(data[total_sent:], flags)
File "/usr/local/lib/python3.4/site-packages/eventlet/greenio.py", line 351, in send
return fd.send(data, flags)
BrokenPipeError: [Errno 32] Broken pipe

# Fixed code
def run_for_multiple(self, timeout):
    while self.alive:
        self.notify()

        try:
            ready = self.wait(timeout)
        except StopWaiting:
            return

        if ready is not None:
            for listener in ready:
                try:
                    self.accept(listener)
                except EnvironmentError as e:
                    if e.errno not in (
                        errno.EAGAIN,
                        errno.ECONNABORTED,
                        errno.EWOULDBLOCK,
                    ):
                        raise

        if not self.is_parent_alive():
            return
# Buggy code
def _set_handler(self, log, output, fmt):
    # remove previous gunicorn log handler
    h = self._get_gunicorn_handler(log)
    if h:
        log.handlers.remove(h)

    if output is not None:
        if output == "-":
            h = logging.StreamHandler()
        else:
            util.check_is_writeable(output)
            h = logging.FileHandler(output)
            # make sure the user can reopen the file
            os.chown(h.baseFilename, self.cfg.user, self.cfg.group)

        h.setFormatter(fmt)
        h._gunicorn = True
        log.addHandler(h)


# Traceback (OSError)
Traceback (most recent call last):
File "/env/bin/gunicorn", line 11, in <module>
sys.exit(run())
File "/env/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 74, in run
WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run()
File "/env/lib/python2.7/site-packages/gunicorn/app/base.py", line 192, in run
super(Application, self).run()
File "/env/lib/python2.7/site-packages/gunicorn/app/base.py", line 72, in run
Arbiter(self).run()
File "/env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 61, in __init__
self.setup(app)
File "/env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 94, in setup
self.log = self.cfg.logger_class(app.cfg)
File "/env/lib/python2.7/site-packages/gunicorn/glogging.py", line 178, in __init__
self.setup(cfg)
File "/env/lib/python2.7/site-packages/gunicorn/glogging.py", line 192, in setup
fmt=logging.Formatter(self.access_fmt))
File "/env/lib/python2.7/site-packages/gunicorn/glogging.py", line 341, in _set_handler
os.chown(h.baseFilename, self.cfg.user, self.cfg.group)
OSError: [Errno 1] Operation not permitted: '/dev/null'

# Fixed code
def _set_handler(self, log, output, fmt):
    # remove previous gunicorn log handler
    h = self._get_gunicorn_handler(log)
    if h:
        log.handlers.remove(h)

    if output is not None:
        if output == "-":
            h = logging.StreamHandler()
        else:
            util.check_is_writeable(output)
            h = logging.FileHandler(output)
            # make sure the user can reopen the file
            if not util.is_writable(h.baseFilename, self.cfg.user, self.cfg.group):
                os.chown(h.baseFilename, self.cfg.user, self.cfg.group)
        h.setFormatter(fmt)
        h._gunicorn = True
        log.addHandler(h)
# Buggy code
def _get_user(self, environ):
    user = None
    http_auth = environ.get("HTTP_AUTHORIZATION")
    if http_auth:
        auth = http_auth.split(" ", 1)
        if len(auth) == 2:
            try:
                # b64decode doesn't accept unicode in Python < 3.3
                # so we need to convert it to a byte string
                auth = base64.b64decode(auth[1].strip().encode("utf-8"))
                if PY3:  # b64decode returns a byte string in Python 3
                    auth = auth.decode("utf-8")
                auth = auth.split(":", 1)
            except TypeError as exc:
                self.debug("Couldn't get username: %s", exc)
                return user
            if len(auth) == 2:
                user = auth[0]
    return user


# Traceback (UnicodeDecodeError)
Traceback (most recent call last):
File "/usr/src/deps/gunicorn/gunicorn/workers/async.py", line 116, in handle_request
self.log.access(resp, req, environ, request_time)
File "/usr/src/deps/gunicorn/gunicorn/glogging.py", line 287, in access
request_time))
File "/usr/src/deps/gunicorn/gunicorn/glogging.py", line 243, in atoms
'u': self._get_user(environ) or '-',
File "/usr/src/deps/gunicorn/gunicorn/glogging.py", line 392, in _get_user
auth = auth.decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc2 in position 0: invalid continuation byte

# Fixed code
def _get_user(self, environ):
    user = None
    http_auth = environ.get("HTTP_AUTHORIZATION")
    if http_auth and http_auth.startswith("Basic"):
        auth = http_auth.split(" ", 1)
        if len(auth) == 2:
            try:
                # b64decode doesn't accept unicode in Python < 3.3
                # so we need to convert it to a byte string
                auth = base64.b64decode(auth[1].strip().encode("utf-8"))
                if PY3:  # b64decode returns a byte string in Python 3
                    auth = auth.decode("utf-8")
                auth = auth.split(":", 1)
            except TypeError as exc:
                self.debug("Couldn't get username: %s", exc)
                return user
            if len(auth) == 2:
                user = auth[0]
    return user
# Buggy code
def scan(i, token, column):
    for x in self.ignore:
        m = x.match(stream, i)
        if m:
            return column

    to_scan = column.to_scan.get_news()

    for item in to_scan:
        m = item.expect.match(stream, i)
        if m:
            t = Token(item.expect.name, m.group(0), i, text_line, text_column)
            delayed_matches[m.end()].append(item.advance(t))

            s = m.group(0)
            for j in range(1, len(s)):
                m = item.expect.match(s[:-j])
                if m:
                    delayed_matches[m.end()].append(item.advance(m.group(0)))

    next_set = Column(i + 1)
    next_set.add(delayed_matches[i + 1])
    del delayed_matches[i + 1]  # No longer needed, so unburden memory

    return next_set


# Traceback (lark.common.ParseError)
Traceback (most recent call last):
File "lark_earley_bug.py", line 18, in <module>
tree = parser.parse("int 1 ! This is a comment\n")
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lark/lark.py", line 193, in parse
return self.parser.parse(text)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lark/parser_frontends.py", line 144, in parse
return self.parser.parse(text)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/lark/parsers/xearley.py", line 128, in parse
raise ParseError('Incomplete parse: Could not find a solution to input')
lark.common.ParseError: Incomplete parse: Could not find a solution to input

# Fixed code
def scan(i, token, column):
    to_scan = column.to_scan.get_news()

    for x in self.ignore:
        m = x.match(stream, i)
        if m:
            # TODO add partial matches for ignore too?
            delayed_matches[m.end()] += to_scan

    for item in to_scan:
        m = item.expect.match(stream, i)
        if m:
            t = Token(item.expect.name, m.group(0), i, text_line, text_column)
            delayed_matches[m.end()].append(item.advance(t))

            s = m.group(0)
            for j in range(1, len(s)):
                m = item.expect.match(s[:-j])
                if m:
                    delayed_matches[m.end()].append(item.advance(m.group(0)))

    next_set = Column(i + 1)
    next_set.add(delayed_matches[i + 1])
    del delayed_matches[i + 1]  # No longer needed, so unburden memory

    return next_set
# Buggy code
def _identify_local_rank(self):
    if "SLURM_JOBID" in os.environ:
        os.environ["LOCAL_RANK"] = os.environ["SLURM_LOCALID"]

    if "LOCAL_RANK" in os.environ:
        self._local_rank = int(os.environ["LOCAL_RANK"])
    elif self._ext_local_rank is not None:
        self._local_rank = self._ext_local_rank
    else:
        warnings.warn(
            "Local rank information for native distributed setting will be initialized using heuristic approach "
            "based on hostname which can be different of real setup. Please, either set `os.environ['LOCAL_RANK']` "
            "ro use `idist.set_local_rank(local_rank)` with correct local rank index."
        )
        # use socket gethostname heuristic to determine number of nodes => local rank
        self._local_rank = self._compute_local_rank_via_hostname()


# Traceback (AttributeError)
import ignite
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\__init__.py", line 2, in <module>
import ignite.distributed
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\distributed\__init__.py", line 1, in <module>
from ignite.distributed.utils import *
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\distributed\utils.py", line 9, in <module>
from ignite.distributed.comp_models import _SerialModel, has_xla_support, registered_computation_models
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\distributed\comp_models\__init__.py", line 2, in <module>
from ignite.distributed.comp_models.native import _NativeDistModel
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\distributed\comp_models\native.py", line 13, in <module>
class _NativeDistModel(ComputationModel):
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\distributed\comp_models\native.py", line 33, in _NativeDistModel
for name in [dist.Backend.NCCL, dist.Backend.GLOO, dist.Backend.MPI]
AttributeError: module 'torch.distributed' has no attribute 'Backend'

# Fixed code
def _identify_local_rank(self):
    if "SLURM_JOBID" in os.environ:
        os.environ["LOCAL_RANK"] = os.environ["SLURM_LOCALID"]

    if "LOCAL_RANK" in os.environ:
        self._local_rank = int(os.environ["LOCAL_RANK"])
    elif self._ext_local_rank is not None:
        self._local_rank = self._ext_local_rank
    else:
        warnings.warn(
            "Local rank information for native distributed setting will be initialized using "
            "heuristic approach based on hostname which can be different of real setup. Please, "
            "either set `os.environ['LOCAL_RANK']` "
            "or use `idist.set_local_rank(local_rank)` with correct local rank index."
        )
        # use socket gethostname heuristic to determine number of nodes => local rank
        self._local_rank = self._compute_local_rank_via_hostname()
# Buggy code
def create_from_context() -> Optional["_XlaDistModel"]:
    if not has_xla_support:
        return None
    return _XlaDistModel()


# Traceback (AttributeError)
import ignite
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\__init__.py", line 2, in <module>
import ignite.distributed
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\distributed\__init__.py", line 1, in <module>
from ignite.distributed.utils import *
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\distributed\utils.py", line 9, in <module>
from ignite.distributed.comp_models import _SerialModel, has_xla_support, registered_computation_models
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\distributed\comp_models\__init__.py", line 2, in <module>
from ignite.distributed.comp_models.native import _NativeDistModel
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\distributed\comp_models\native.py", line 13, in <module>
class _NativeDistModel(ComputationModel):
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\distributed\comp_models\native.py", line 33, in _NativeDistModel
for name in [dist.Backend.NCCL, dist.Backend.GLOO, dist.Backend.MPI]
AttributeError: module 'torch.distributed' has no attribute 'Backend'

# Fixed code
def create_from_context() -> Optional["_XlaDistModel"]:
    return _XlaDistModel()
# Buggy code
def create_from_backend(backend: str = "xla-tpu", **kwargs) -> "_XlaDistModel":
    if not has_xla_support:
        raise RuntimeError("Torch xla package is not installed.")
    return _XlaDistModel(backend=backend, **kwargs)


# Traceback (AttributeError)
import ignite
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\__init__.py", line 2, in <module>
import ignite.distributed
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\distributed\__init__.py", line 1, in <module>
from ignite.distributed.utils import *
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\distributed\utils.py", line 9, in <module>
from ignite.distributed.comp_models import _SerialModel, has_xla_support, registered_computation_models
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\distributed\comp_models\__init__.py", line 2, in <module>
from ignite.distributed.comp_models.native import _NativeDistModel
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\distributed\comp_models\native.py", line 13, in <module>
class _NativeDistModel(ComputationModel):
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\distributed\comp_models\native.py", line 33, in _NativeDistModel
for name in [dist.Backend.NCCL, dist.Backend.GLOO, dist.Backend.MPI]
AttributeError: module 'torch.distributed' has no attribute 'Backend'

# Fixed code
def create_from_backend(backend: str = "xla-tpu", **kwargs) -> "_XlaDistModel":
    return _XlaDistModel(backend=backend, **kwargs)
# Buggy code
def spawn(
    fn: Callable,
    args: Tuple,
    kwargs_dict: Optional[Mapping] = None,
    num_procs_per_node: int = 1,
    num_nodes: int = 1,
    node_rank: int = 0,
    backend: str = "xla-tpu",
    **kwargs,
):
    if not has_xla_support:
        raise RuntimeError("Torch xla package is not installed.")

    import os

    if "COLAB_TPU_ADDR" in os.environ:
        kwargs["start_method"] = "fork"

    xmp.spawn(
        _XlaDistModel._dist_worker_task_fn,
        args=(backend, fn, args, kwargs_dict),
        nprocs=num_procs_per_node,
        **kwargs,
    )


# Traceback (AttributeError)
import ignite
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\__init__.py", line 2, in <module>
import ignite.distributed
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\distributed\__init__.py", line 1, in <module>
from ignite.distributed.utils import *
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\distributed\utils.py", line 9, in <module>
from ignite.distributed.comp_models import _SerialModel, has_xla_support, registered_computation_models
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\distributed\comp_models\__init__.py", line 2, in <module>
from ignite.distributed.comp_models.native import _NativeDistModel
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\distributed\comp_models\native.py", line 13, in <module>
class _NativeDistModel(ComputationModel):
File "C:\Users\Foo\anaconda3\envs\ignite\lib\site-packages\ignite\distributed\comp_models\native.py", line 33, in _NativeDistModel
for name in [dist.Backend.NCCL, dist.Backend.GLOO, dist.Backend.MPI]
AttributeError: module 'torch.distributed' has no attribute 'Backend'

# Fixed code
def spawn(
    fn: Callable,
    args: Tuple,
    kwargs_dict: Optional[Mapping] = None,
    num_procs_per_node: int = 1,
    num_nodes: int = 1,
    node_rank: int = 0,
    backend: str = "xla-tpu",
    **kwargs,
):
    import os

    if "COLAB_TPU_ADDR" in os.environ:
        kwargs["start_method"] = "fork"

    xmp.spawn(
        _XlaDistModel._dist_worker_task_fn,
        args=(backend, fn, args, kwargs_dict),
        nprocs=num_procs_per_node,
        **kwargs,
    )
# Buggy code
def __init__(self, lr_scheduler, save_history=False, **kwds):
    if not isinstance(lr_scheduler, _LRScheduler):
        raise TypeError(
            "Argument lr_scheduler should be a subclass of torch.optim.lr_scheduler._LRScheduler, "
            "but given {}".format(type(lr_scheduler))
        )

    self.lr_scheduler = lr_scheduler
    super(LRScheduler, self).__init__(
        optimizer=self.lr_scheduler.optimizer,
        param_name="lr",
        save_history=save_history,
    )
    self._state_attrs += [
        "lr_scheduler",
    ]


# Traceback (TypeError)
Traceback (most recent call last):
File "tutorials/misc/lr_schedulers.py", line 56, in <module>
lr_values = LRScheduler.simulate_values(num_events=50, lr_scheduler=lr_scheduler)
File "/work/desrozis/Softwares/conda/envs/focus-light/lib/python3.7/site-packages/ignite/contrib/handlers/param_scheduler.py", line 606, in simulate_values
copy_lr_scheduler = LRScheduler._replicate_lr_scheduler(lr_scheduler)
File "/work/desrozis/Softwares/conda/envs/focus-light/lib/python3.7/site-packages/ignite/contrib/handlers/param_scheduler.py", line 627, in _replicate_lr_scheduler
copy_lr_scheduler = lr_scheduler_cls(optimizer=dummy_optimizer, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'T_i'

# Fixed code
def __init__(self, lr_scheduler, save_history=False, **kwargs):
    if not isinstance(lr_scheduler, _LRScheduler):
        raise TypeError(
            "Argument lr_scheduler should be a subclass of torch.optim.lr_scheduler._LRScheduler, "
            "but given {}".format(type(lr_scheduler))
        )

    self.lr_scheduler = lr_scheduler
    super(LRScheduler, self).__init__(
        optimizer=self.lr_scheduler.optimizer,
        param_name="lr",
        save_history=save_history,
    )
    self._state_attrs += [
        "lr_scheduler",
    ]
# Buggy code
def simulate_values(cls, num_events, schedulers, **kwargs):
    """Method to simulate scheduled values during num_events events.

    Args:
        num_events (int): number of events during the simulation.
        lr_schedulers (subclass of `torch.optim.lr_scheduler._LRScheduler`): lr_scheduler object to wrap.

    Returns:
        list of pairs: [event_index, value]

    """
    copy_lr_schedulers = [_replicate_scheduler(s) for s in schedulers]
    values = []
    scheduler = cls(schedulers=copy_lr_schedulers)
    for i in range(num_events):
        scheduler(engine=None)
        params = scheduler.get_param()
        values.append([i] + params)
    return values


# Traceback (TypeError)
Traceback (most recent call last):
File "tutorials/misc/lr_schedulers.py", line 56, in <module>
lr_values = LRScheduler.simulate_values(num_events=50, lr_scheduler=lr_scheduler)
File "/work/desrozis/Softwares/conda/envs/focus-light/lib/python3.7/site-packages/ignite/contrib/handlers/param_scheduler.py", line 606, in simulate_values
copy_lr_scheduler = LRScheduler._replicate_lr_scheduler(lr_scheduler)
File "/work/desrozis/Softwares/conda/envs/focus-light/lib/python3.7/site-packages/ignite/contrib/handlers/param_scheduler.py", line 627, in _replicate_lr_scheduler
copy_lr_scheduler = lr_scheduler_cls(optimizer=dummy_optimizer, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'T_i'

# Fixed code
def simulate_values(cls, num_events, schedulers, **kwargs):
    """Method to simulate scheduled values during num_events events.

    Args:
        num_events (int): number of events during the simulation.
        lr_schedulers (subclass of `torch.optim.lr_scheduler._LRScheduler`): lr_scheduler object to wrap.

    Returns:
        list of pairs: [event_index, value]

    """

    # This scheduler uses `torch.optim.lr_scheduler._LRScheduler` which
    # should be replicated in order to simulate LR values and
    # not perturb original scheduler.
    with tempfile.TemporaryDirectory() as tmpdirname:
        cache_filepath = Path(tmpdirname) / "ignite_lr_scheduler_cache.pt"
        objs = {
            "lr_scheduler_{}".format(i): s.state_dict()
            for i, s in enumerate(schedulers)
        }
        # all schedulers should be related to the same optimizer
        objs["optimizer"] = schedulers[0].optimizer.state_dict()

        torch.save(objs, cache_filepath.as_posix())

        values = []
        scheduler = cls(schedulers=schedulers, **kwargs)
        for i in range(num_events):
            params = scheduler.get_param()
            values.append([i] + params)
            scheduler(engine=None)

        objs = torch.load(cache_filepath.as_posix())
        for i, s in enumerate(schedulers):
            s.load_state_dict(objs["lr_scheduler_{}".format(i)])
            s.optimizer.load_state_dict(objs["optimizer"])

        return values
# Buggy code
def _handler_wrapper(
    handler: Callable, event_name: Any, event_filter: Callable
) -> Callable:
    def wrapper(engine: Engine, *args, **kwargs) -> Any:
        event = engine.state.get_event_attrib_value(event_name)
        if event_filter(engine, event):
            return handler(engine, *args, **kwargs)

    # setup input handler as parent to make has_event_handler work
    wrapper._parent = weakref.ref(handler)
    return wrapper


# Traceback (TypeError)
TypeErrorTraceback (most recent call last)
<ipython-input-13-832efed482dd> in <module>
14
15 e.add_event_handler(Events.ITERATION_COMPLETED(every=2), f4)
---> 16 e.fire_event(Events.ITERATION_COMPLETED)
17 e.fire_event(Events.ITERATION_COMPLETED)

/opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in fire_event(self, event_name)
414
415         """
--> 416         return self._fire_event(event_name)
417
418     def terminate(self) -> None:

/opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in _fire_event(self, event_name, *event_args, **event_kwargs)
391                 kwargs.update(event_kwargs)
392                 first, others = ((args[0],), args[1:]) if (args and args[0] == self) else ((), args)
--> 393                 func(*first, *(event_args + others), **kwargs)
394
395     def fire_event(self, event_name: Any) -> None:

/opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in wrapper(engine, *args, **kwargs)
203             event = engine.state.get_event_attrib_value(event_name)
204             if event_filter(engine, event):
--> 205                 return handler(engine, *args, **kwargs)
206
207         # setup input handler as parent to make has_event_handler work

TypeError: f4() takes 0 positional arguments but 1 was given

# Fixed code
def _handler_wrapper(
    self, handler: Callable, event_name: Any, event_filter: Callable
) -> Callable:
    # signature of the following wrapper will be inspected during registering to check if engine is necessary
    # we have to build a wrapper with relevant signature : solution is functools.wrapsgit s
    @functools.wraps(handler)
    def wrapper(*args, **kwargs) -> Any:
        event = self.state.get_event_attrib_value(event_name)
        if event_filter(self, event):
            return handler(*args, **kwargs)

    # setup input handler as parent to make has_event_handler work
    wrapper._parent = weakref.ref(handler)
    return wrapper
# Buggy code
def wrapper(engine: Engine, *args, **kwargs) -> Any:
    event = engine.state.get_event_attrib_value(event_name)
    if event_filter(engine, event):
        return handler(engine, *args, **kwargs)


# Traceback (TypeError)
TypeErrorTraceback (most recent call last)
<ipython-input-13-832efed482dd> in <module>
14
15 e.add_event_handler(Events.ITERATION_COMPLETED(every=2), f4)
---> 16 e.fire_event(Events.ITERATION_COMPLETED)
17 e.fire_event(Events.ITERATION_COMPLETED)

/opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in fire_event(self, event_name)
414
415         """
--> 416         return self._fire_event(event_name)
417
418     def terminate(self) -> None:

/opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in _fire_event(self, event_name, *event_args, **event_kwargs)
391                 kwargs.update(event_kwargs)
392                 first, others = ((args[0],), args[1:]) if (args and args[0] == self) else ((), args)
--> 393                 func(*first, *(event_args + others), **kwargs)
394
395     def fire_event(self, event_name: Any) -> None:

/opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in wrapper(engine, *args, **kwargs)
203             event = engine.state.get_event_attrib_value(event_name)
204             if event_filter(engine, event):
--> 205                 return handler(engine, *args, **kwargs)
206
207         # setup input handler as parent to make has_event_handler work

TypeError: f4() takes 0 positional arguments but 1 was given

# Fixed code
def wrapper(*args, **kwargs) -> Any:
    event = self.state.get_event_attrib_value(event_name)
    if event_filter(self, event):
        return handler(*args, **kwargs)
# Buggy code
def __init__(self, event: CallableEvents, filter: Callable):
    if not callable(filter):
        raise TypeError("Argument filter should be callable")
    self.event = event
    self.filter = filter


# Traceback (SyntaxError)
root@user:/# pip install --pre pytorch-ignite
Successfully installed pytorch-ignite-0.4.0.dev20200129
root@user:/#
root@user:/# python -c "import ignite"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module>
import ignite.engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module>
from ignite.engine.engine import Engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1
from __future__ import annotations
^
SyntaxError: future feature annotations is not defined
root@user:/# python --version
Python 3.5.6 :: Anaconda, Inc.

# Fixed code
def __init__(self, event: Any, filter: Callable):
    if not callable(filter):
        raise TypeError("Argument filter should be callable")
    self.event = event
    self.filter = filter
# Buggy code
def __call__(
    self,
    event_filter: Optional[Callable] = None,
    every: Optional[int] = None,
    once: Optional[int] = None,
) -> Union[CallableEvents, EventWithFilter]:
    if not ((event_filter is not None) ^ (every is not None) ^ (once is not None)):
        raise ValueError("Only one of the input arguments should be specified")

    if (event_filter is not None) and not callable(event_filter):
        raise TypeError("Argument event_filter should be a callable")

    if (every is not None) and not (isinstance(every, numbers.Integral) and every > 0):
        raise ValueError("Argument every should be integer and greater than zero")

    if (once is not None) and not (isinstance(once, numbers.Integral) and once > 0):
        raise ValueError("Argument every should be integer and positive")

    if every is not None:
        if every == 1:
            # Just return the event itself
            return self
        event_filter = CallableEvents.every_event_filter(every)

    if once is not None:
        event_filter = CallableEvents.once_event_filter(once)

    # check signature:
    _check_signature("engine", event_filter, "event_filter", "event")

    return EventWithFilter(self, event_filter)


# Traceback (SyntaxError)
root@user:/# pip install --pre pytorch-ignite
Successfully installed pytorch-ignite-0.4.0.dev20200129
root@user:/#
root@user:/# python -c "import ignite"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module>
import ignite.engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module>
from ignite.engine.engine import Engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1
from __future__ import annotations
^
SyntaxError: future feature annotations is not defined
root@user:/# python --version
Python 3.5.6 :: Anaconda, Inc.

# Fixed code
def __call__(
    self,
    event_filter: Optional[Callable] = None,
    every: Optional[int] = None,
    once: Optional[int] = None,
):
    if not ((event_filter is not None) ^ (every is not None) ^ (once is not None)):
        raise ValueError("Only one of the input arguments should be specified")

    if (event_filter is not None) and not callable(event_filter):
        raise TypeError("Argument event_filter should be a callable")

    if (every is not None) and not (isinstance(every, numbers.Integral) and every > 0):
        raise ValueError("Argument every should be integer and greater than zero")

    if (once is not None) and not (isinstance(once, numbers.Integral) and once > 0):
        raise ValueError("Argument every should be integer and positive")

    if every is not None:
        if every == 1:
            # Just return the event itself
            return self
        event_filter = CallableEvents.every_event_filter(every)

    if once is not None:
        event_filter = CallableEvents.once_event_filter(once)

    # check signature:
    _check_signature("engine", event_filter, "event_filter", "event")

    return EventWithFilter(self, event_filter)
# Buggy code
def __enter__(self) -> RemovableEventHandle:
    return self


# Traceback (SyntaxError)
root@user:/# pip install --pre pytorch-ignite
Successfully installed pytorch-ignite-0.4.0.dev20200129
root@user:/#
root@user:/# python -c "import ignite"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module>
import ignite.engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module>
from ignite.engine.engine import Engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1
from __future__ import annotations
^
SyntaxError: future feature annotations is not defined
root@user:/# python --version
Python 3.5.6 :: Anaconda, Inc.

# Fixed code
def __enter__(self):
    return self
# Buggy code
def attach(
    self,
    engine: Engine,
    start: str = Events.STARTED,
    pause: str = Events.COMPLETED,
    resume: Optional[str] = None,
    step: Optional[str] = None,
) -> Timer:
    """Register callbacks to control the timer.

    Args:
        engine (Engine):
            Engine that this timer will be attached to.
        start (Events):
            Event which should start (reset) the timer.
        pause (Events):
            Event which should pause the timer.
        resume (Events, optional):
            Event which should resume the timer.
        step (Events, optional):
            Event which should call the `step` method of the counter.

    Returns:
        self (Timer)

    """

    engine.add_event_handler(start, self.reset)
    engine.add_event_handler(pause, self.pause)

    if resume is not None:
        engine.add_event_handler(resume, self.resume)

    if step is not None:
        engine.add_event_handler(step, self.step)

    return self


# Traceback (SyntaxError)
root@user:/# pip install --pre pytorch-ignite
Successfully installed pytorch-ignite-0.4.0.dev20200129
root@user:/#
root@user:/# python -c "import ignite"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module>
import ignite.engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module>
from ignite.engine.engine import Engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1
from __future__ import annotations
^
SyntaxError: future feature annotations is not defined
root@user:/# python --version
Python 3.5.6 :: Anaconda, Inc.

# Fixed code
def attach(
    self,
    engine: Engine,
    start: str = Events.STARTED,
    pause: str = Events.COMPLETED,
    resume: Optional[str] = None,
    step: Optional[str] = None,
):
    """Register callbacks to control the timer.

    Args:
        engine (Engine):
            Engine that this timer will be attached to.
        start (Events):
            Event which should start (reset) the timer.
        pause (Events):
            Event which should pause the timer.
        resume (Events, optional):
            Event which should resume the timer.
        step (Events, optional):
            Event which should call the `step` method of the counter.

    Returns:
        self (Timer)

    """

    engine.add_event_handler(start, self.reset)
    engine.add_event_handler(pause, self.pause)

    if resume is not None:
        engine.add_event_handler(resume, self.resume)

    if step is not None:
        engine.add_event_handler(step, self.step)

    return self
# Buggy code
def reset(self, *args) -> Timer:
    self.__init__(self._average)
    return self


# Traceback (SyntaxError)
root@user:/# pip install --pre pytorch-ignite
Successfully installed pytorch-ignite-0.4.0.dev20200129
root@user:/#
root@user:/# python -c "import ignite"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module>
import ignite.engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module>
from ignite.engine.engine import Engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1
from __future__ import annotations
^
SyntaxError: future feature annotations is not defined
root@user:/# python --version
Python 3.5.6 :: Anaconda, Inc.

# Fixed code
def reset(self, *args):
    self.__init__(self._average)
    return self
# Buggy code
def __add__(self, other: Metric) -> Metric:
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x + y, self, other)


# Traceback (SyntaxError)
root@user:/# pip install --pre pytorch-ignite
Successfully installed pytorch-ignite-0.4.0.dev20200129
root@user:/#
root@user:/# python -c "import ignite"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module>
import ignite.engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module>
from ignite.engine.engine import Engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1
from __future__ import annotations
^
SyntaxError: future feature annotations is not defined
root@user:/# python --version
Python 3.5.6 :: Anaconda, Inc.

# Fixed code
def __add__(self, other):
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x + y, self, other)
# Buggy code
def __radd__(self, other: Metric) -> Metric:
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x + y, other, self)


# Traceback (SyntaxError)
root@user:/# pip install --pre pytorch-ignite
Successfully installed pytorch-ignite-0.4.0.dev20200129
root@user:/#
root@user:/# python -c "import ignite"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module>
import ignite.engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module>
from ignite.engine.engine import Engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1
from __future__ import annotations
^
SyntaxError: future feature annotations is not defined
root@user:/# python --version
Python 3.5.6 :: Anaconda, Inc.

# Fixed code
def __radd__(self, other):
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x + y, other, self)
# Buggy code
def __sub__(self, other: Metric) -> Metric:
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x - y, self, other)


# Traceback (SyntaxError)
root@user:/# pip install --pre pytorch-ignite
Successfully installed pytorch-ignite-0.4.0.dev20200129
root@user:/#
root@user:/# python -c "import ignite"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module>
import ignite.engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module>
from ignite.engine.engine import Engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1
from __future__ import annotations
^
SyntaxError: future feature annotations is not defined
root@user:/# python --version
Python 3.5.6 :: Anaconda, Inc.

# Fixed code
def __sub__(self, other):
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x - y, self, other)
# Buggy code
def __rsub__(self, other: Metric) -> Metric:
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x - y, other, self)


# Traceback (SyntaxError)
root@user:/# pip install --pre pytorch-ignite
Successfully installed pytorch-ignite-0.4.0.dev20200129
root@user:/#
root@user:/# python -c "import ignite"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module>
import ignite.engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module>
from ignite.engine.engine import Engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1
from __future__ import annotations
^
SyntaxError: future feature annotations is not defined
root@user:/# python --version
Python 3.5.6 :: Anaconda, Inc.

# Fixed code
def __rsub__(self, other):
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x - y, other, self)
# Buggy code
def __mul__(self, other: Metric) -> Metric:
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x * y, self, other)


# Traceback (SyntaxError)
root@user:/# pip install --pre pytorch-ignite
Successfully installed pytorch-ignite-0.4.0.dev20200129
root@user:/#
root@user:/# python -c "import ignite"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module>
import ignite.engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module>
from ignite.engine.engine import Engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1
from __future__ import annotations
^
SyntaxError: future feature annotations is not defined
root@user:/# python --version
Python 3.5.6 :: Anaconda, Inc.

# Fixed code
def __mul__(self, other):
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x * y, self, other)
# Buggy code
def __rmul__(self, other: Metric) -> Metric:
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x * y, other, self)


# Traceback (SyntaxError)
root@user:/# pip install --pre pytorch-ignite
Successfully installed pytorch-ignite-0.4.0.dev20200129
root@user:/#
root@user:/# python -c "import ignite"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module>
import ignite.engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module>
from ignite.engine.engine import Engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1
from __future__ import annotations
^
SyntaxError: future feature annotations is not defined
root@user:/# python --version
Python 3.5.6 :: Anaconda, Inc.

# Fixed code
def __rmul__(self, other):
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x * y, other, self)
# Buggy code
def __pow__(self, other: Metric) -> Metric:
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x**y, self, other)


# Traceback (SyntaxError)
root@user:/# pip install --pre pytorch-ignite
Successfully installed pytorch-ignite-0.4.0.dev20200129
root@user:/#
root@user:/# python -c "import ignite"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module>
import ignite.engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module>
from ignite.engine.engine import Engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1
from __future__ import annotations
^
SyntaxError: future feature annotations is not defined
root@user:/# python --version
Python 3.5.6 :: Anaconda, Inc.

# Fixed code
def __pow__(self, other):
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x**y, self, other)
# Buggy code
def __rpow__(self, other: Metric) -> Metric:
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x**y, other, self)


# Traceback (SyntaxError)
root@user:/# pip install --pre pytorch-ignite
Successfully installed pytorch-ignite-0.4.0.dev20200129
root@user:/#
root@user:/# python -c "import ignite"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module>
import ignite.engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module>
from ignite.engine.engine import Engine
File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1
from __future__ import annotations
^
SyntaxError: future feature annotations is not defined
root@user:/# python --version
Python 3.5.6 :: Anaconda, Inc.

# Fixed code
def __rpow__(self, other):
    from ignite.metrics import MetricsLambda

    return MetricsLambda(lambda x, y: x**y, other, self)