gurudesh/pytracebugs huggingface dataset:
# Buggy code
def tree_view_rename_selected(self):
    view = self._namespace
    element = view.get_selected_element()
    if element is not None:
        path = view.get_model().path_from_element(element)
        column = view.get_column(0)
        cell = column.get_cells()[1]
        cell.set_property("editable", 1)
        cell.set_property("text", element.name)
        view.set_cursor(path, column, True)
        cell.set_property("editable", 0)


# Traceback (AttributeError)
gaphor.transaction ERROR Transaction terminated due to an exception, performing a rollback
Traceback (most recent call last):
File "/app/lib/python3.7/site-packages/gaphor/transaction.py", line 27, in _transactional
r = func(*args, **kwargs)
File "/app/lib/python3.7/site-packages/gaphor/ui/namespace.py", line 600, in tree_view_create_diagram
self.select_element(diagram)
File "/app/lib/python3.7/site-packages/gaphor/ui/namespace.py", line 552, in select_element
self._namespace.get_model().path_from_element(element)
AttributeError: 'TreeModelSort' object has no attribute 'path_from_element'
Traceback (most recent call last):
File "/app/lib/python3.7/site-packages/gaphor/action.py", line 179, in _action_activate
method()
File "/app/lib/python3.7/site-packages/gaphor/transaction.py", line 27, in _transactional
r = func(*args, **kwargs)
File "/app/lib/python3.7/site-packages/gaphor/ui/namespace.py", line 600, in tree_view_create_diagram
self.select_element(diagram)
File "/app/lib/python3.7/site-packages/gaphor/ui/namespace.py", line 552, in select_element
self._namespace.get_model().path_from_element(element)
AttributeError: 'TreeModelSort' object has no attribute 'path_from_element'
``

### System Information
OS:
- [X] Linux (Please put in notes the specific distro)
- [ ] MacOS
- [ ] Windows 10
- [ ] Windows 7

NOTES:

# Fixed code
def tree_view_rename_selected(self):
    view = self._namespace
    element = view.get_selected_element()
    if element is not None:
        selection = view.get_selection()
        model, iter = selection.get_selected()
        path = model.get_path(iter)
        column = view.get_column(0)
        cell = column.get_cells()[1]
        cell.set_property("editable", 1)
        cell.set_property("text", element.name)
        view.set_cursor(path, column, True)
        cell.set_property("editable", 0)
# Buggy code
def get_tcp_dstip(self, sock):
    pfile = self.firewall.pfile

    try:
        peer = sock.getpeername()
    except socket.error:
        _, e = sys.exc_info()[:2]
        if e.args[0] == errno.EINVAL:
            debug2(
                "get_tcp_dstip error: sock.getpeername() %s\nsocket is probably closed.\n"
                % e
            )
            return sock.getsockname()

    proxy = sock.getsockname()

    argv = (
        sock.family,
        socket.IPPROTO_TCP,
        peer[0].encode("ASCII"),
        peer[1],
        proxy[0].encode("ASCII"),
        proxy[1],
    )
    out_line = b"QUERY_PF_NAT %d,%d,%s,%d,%s,%d\n" % argv
    pfile.write(out_line)
    pfile.flush()
    in_line = pfile.readline()
    debug2(out_line.decode("ASCII") + " > " + in_line.decode("ASCII"))
    if in_line.startswith(b"QUERY_PF_NAT_SUCCESS "):
        (ip, port) = in_line[21:].split(b",")
        return (ip.decode("ASCII"), int(port))

    return sock.getsockname()


# Traceback (OSError)
Traceback (most recent call last):
File "/usr/local/bin/sshuttle", line 11, in <module>
load_entry_point('sshuttle==0.78.4', 'console_scripts', 'sshuttle')()
File "/usr/local/Cellar/sshuttle/0.78.4_1/libexec/lib/python3.7/site-packages/sshuttle/cmdline.py", line 79, in main
opt.user)
File "/usr/local/Cellar/sshuttle/0.78.4_1/libexec/lib/python3.7/site-packages/sshuttle/client.py", line 778, in main
seed_hosts, auto_hosts, auto_nets, daemon, to_nameserver)
File "/usr/local/Cellar/sshuttle/0.78.4_1/libexec/lib/python3.7/site-packages/sshuttle/client.py", line 538, in _main
ssnet.runonce(handlers, mux)
File "/usr/local/Cellar/sshuttle/0.78.4_1/libexec/lib/python3.7/site-packages/sshuttle/ssnet.py", line 596, in runonce
h.callback(s)
File "/usr/local/Cellar/sshuttle/0.78.4_1/libexec/lib/python3.7/site-packages/sshuttle/client.py", line 139, in <lambda>
lambda sock: callback(sock, method, mux, handlers)
File "/usr/local/Cellar/sshuttle/0.78.4_1/libexec/lib/python3.7/site-packages/sshuttle/client.py", line 355, in onaccept_tcp
dstip = method.get_tcp_dstip(sock)
File "/usr/local/Cellar/sshuttle/0.78.4_1/libexec/lib/python3.7/site-packages/sshuttle/methods/pf.py", line 423, in get_tcp_dstip
peer = sock.getpeername()
OSError: [Errno 22] Invalid argument

# Fixed code
def get_tcp_dstip(self, sock):
    pfile = self.firewall.pfile

    try:
        peer = sock.getpeername()
    except socket.error:
        _, e = sys.exc_info()[:2]
        if e.args[0] == errno.EINVAL:
            return sock.getsockname()

    proxy = sock.getsockname()

    argv = (
        sock.family,
        socket.IPPROTO_TCP,
        peer[0].encode("ASCII"),
        peer[1],
        proxy[0].encode("ASCII"),
        proxy[1],
    )
    out_line = b"QUERY_PF_NAT %d,%d,%s,%d,%s,%d\n" % argv
    pfile.write(out_line)
    pfile.flush()
    in_line = pfile.readline()
    debug2(out_line.decode("ASCII") + " > " + in_line.decode("ASCII"))
    if in_line.startswith(b"QUERY_PF_NAT_SUCCESS "):
        (ip, port) = in_line[21:].split(b",")
        return (ip.decode("ASCII"), int(port))

    return sock.getsockname()
# Buggy code
def _try_peername(sock):
    try:
        pn = sock.getpeername()
        if pn:
            return "%s:%s" % (pn[0], pn[1])
    except socket.error:
        _, e = sys.exc_info()[:2]
        if e.args[0] == errno.EINVAL:
            debug2(
                "_try_peername error: sock.getpeername() %s\nsocket is probably closed.\n"
                % e
            )
            pass
        elif e.args[0] not in (errno.ENOTCONN, errno.ENOTSOCK):
            raise
    except AttributeError:
        pass
    return "unknown"


# Traceback (OSError)
Traceback (most recent call last):
File "/usr/local/bin/sshuttle", line 11, in <module>
load_entry_point('sshuttle==0.78.4', 'console_scripts', 'sshuttle')()
File "/usr/local/Cellar/sshuttle/0.78.4_1/libexec/lib/python3.7/site-packages/sshuttle/cmdline.py", line 79, in main
opt.user)
File "/usr/local/Cellar/sshuttle/0.78.4_1/libexec/lib/python3.7/site-packages/sshuttle/client.py", line 778, in main
seed_hosts, auto_hosts, auto_nets, daemon, to_nameserver)
File "/usr/local/Cellar/sshuttle/0.78.4_1/libexec/lib/python3.7/site-packages/sshuttle/client.py", line 538, in _main
ssnet.runonce(handlers, mux)
File "/usr/local/Cellar/sshuttle/0.78.4_1/libexec/lib/python3.7/site-packages/sshuttle/ssnet.py", line 596, in runonce
h.callback(s)
File "/usr/local/Cellar/sshuttle/0.78.4_1/libexec/lib/python3.7/site-packages/sshuttle/client.py", line 139, in <lambda>
lambda sock: callback(sock, method, mux, handlers)
File "/usr/local/Cellar/sshuttle/0.78.4_1/libexec/lib/python3.7/site-packages/sshuttle/client.py", line 355, in onaccept_tcp
dstip = method.get_tcp_dstip(sock)
File "/usr/local/Cellar/sshuttle/0.78.4_1/libexec/lib/python3.7/site-packages/sshuttle/methods/pf.py", line 423, in get_tcp_dstip
peer = sock.getpeername()
OSError: [Errno 22] Invalid argument

# Fixed code
def _try_peername(sock):
    try:
        pn = sock.getpeername()
        if pn:
            return "%s:%s" % (pn[0], pn[1])
    except socket.error:
        _, e = sys.exc_info()[:2]
        if e.args[0] == errno.EINVAL:
            pass
        elif e.args[0] not in (errno.ENOTCONN, errno.ENOTSOCK):
            raise
    except AttributeError:
        pass
    return "unknown"
# Buggy code
def _pre_experiment_hook(self, experiment: Experiment):
    monitoring_params = experiment.monitoring_params
    monitoring_params["dir"] = str(Path(experiment.logdir).absolute())

    log_on_batch_end: bool = monitoring_params.pop("log_on_batch_end", False)
    log_on_epoch_end: bool = monitoring_params.pop("log_on_epoch_end", True)
    checkpoints_glob: List[str] = monitoring_params.pop("checkpoints_glob", None)
    self._init(
        log_on_batch_end=log_on_batch_end,
        log_on_epoch_end=log_on_epoch_end,
        checkpoints_glob=checkpoints_glob,
    )
    if isinstance(experiment, ConfigExperiment):
        exp_config = utils.flatten_dict(experiment.stages_config)
        wandb.init(**monitoring_params, config=exp_config)
    else:
        wandb.init(**monitoring_params)


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-279a2ce060b8> in <module>
24     monitoring_params={
25         'project': "yt",
---> 26         'group': "aa"
27     }
28 )

~/.local/lib/python3.6/site-packages/catalyst/dl/runner/supervised.py in train(self, model, criterion, optimizer, loaders, logdir, callbacks, scheduler, resume, num_epochs, valid_loader, main_metric, minimize_metric, verbose, state_kwargs, checkpoint_data, fp16, monitoring_params, check)
204             monitoring_params=monitoring_params
205         )
--> 206         self.run_experiment(experiment, check=check)
207
208     def infer(

~/.local/lib/python3.6/site-packages/catalyst/contrib/dl/runner/wandb.py in run_experiment(self, experiment, check)
141         self._pre_experiment_hook(experiment=experiment)
142         super().run_experiment(experiment=experiment, check=check)
--> 143         self._post_experiment_hook(experiment=experiment)
144
145

~/.local/lib/python3.6/site-packages/catalyst/contrib/dl/runner/wandb.py in _post_experiment_hook(self, experiment)
104
105         checkpoint_paths = []
--> 106         for glob in self.checkpoints_glob:
107             checkpoint_paths.extend(list(checkpoints_src.glob(glob)))
108         checkpoint_paths = list(set(checkpoint_paths))

TypeError: 'NoneType' object is not iterable

# Fixed code
def _pre_experiment_hook(self, experiment: Experiment):
    monitoring_params = experiment.monitoring_params
    monitoring_params["dir"] = str(Path(experiment.logdir).absolute())

    log_on_batch_end: bool = monitoring_params.pop("log_on_batch_end", False)
    log_on_epoch_end: bool = monitoring_params.pop("log_on_epoch_end", True)
    checkpoints_glob: List[str] = monitoring_params.pop("checkpoints_glob", [])
    self._init(
        log_on_batch_end=log_on_batch_end,
        log_on_epoch_end=log_on_epoch_end,
        checkpoints_glob=checkpoints_glob,
    )
    if isinstance(experiment, ConfigExperiment):
        exp_config = utils.flatten_dict(experiment.stages_config)
        wandb.init(**monitoring_params, config=exp_config)
    else:
        wandb.init(**monitoring_params)
# Buggy code
def _init(self, **kwargs):
    global WANDB_ENABLED
    assert len(kwargs) == 0
    if WANDB_ENABLED:
        if self.monitoring_params is not None:
            self.checkpoints_glob: List[str] = self.monitoring_params.pop(
                "checkpoints_glob", ["best.pth", "last.pth"]
            )

            wandb.init(**self.monitoring_params)
        else:
            WANDB_ENABLED = False
    self.wandb_mode = "sampler"


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-279a2ce060b8> in <module>
24     monitoring_params={
25         'project': "yt",
---> 26         'group': "aa"
27     }
28 )

~/.local/lib/python3.6/site-packages/catalyst/dl/runner/supervised.py in train(self, model, criterion, optimizer, loaders, logdir, callbacks, scheduler, resume, num_epochs, valid_loader, main_metric, minimize_metric, verbose, state_kwargs, checkpoint_data, fp16, monitoring_params, check)
204             monitoring_params=monitoring_params
205         )
--> 206         self.run_experiment(experiment, check=check)
207
208     def infer(

~/.local/lib/python3.6/site-packages/catalyst/contrib/dl/runner/wandb.py in run_experiment(self, experiment, check)
141         self._pre_experiment_hook(experiment=experiment)
142         super().run_experiment(experiment=experiment, check=check)
--> 143         self._post_experiment_hook(experiment=experiment)
144
145

~/.local/lib/python3.6/site-packages/catalyst/contrib/dl/runner/wandb.py in _post_experiment_hook(self, experiment)
104
105         checkpoint_paths = []
--> 106         for glob in self.checkpoints_glob:
107             checkpoint_paths.extend(list(checkpoints_src.glob(glob)))
108         checkpoint_paths = list(set(checkpoint_paths))

TypeError: 'NoneType' object is not iterable

# Fixed code
def _init(self, **kwargs):
    global WANDB_ENABLED
    assert len(kwargs) == 0
    if WANDB_ENABLED:
        if self.monitoring_params is not None:
            self.checkpoints_glob: List[str] = self.monitoring_params.pop(
                "checkpoints_glob", []
            )

            wandb.init(**self.monitoring_params)
        else:
            WANDB_ENABLED = False
    self.wandb_mode = "sampler"
# Buggy code
def load_checkpoint(*, filename, state: _State):
    if os.path.isfile(filename):
        print(f"=> loading checkpoint {filename}")
        checkpoint = utils.load_checkpoint(filename)

        state.epoch = checkpoint["epoch"]

        utils.unpack_checkpoint(
            checkpoint,
            model=state.model,
            criterion=state.criterion,
            optimizer=state.optimizer,
            scheduler=state.scheduler,
        )

        print(f"loaded checkpoint {filename} (epoch {checkpoint['epoch']})")
    else:
        raise Exception(f"No checkpoint found at {filename}")


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-279a2ce060b8> in <module>
24     monitoring_params={
25         'project': "yt",
---> 26         'group': "aa"
27     }
28 )

~/.local/lib/python3.6/site-packages/catalyst/dl/runner/supervised.py in train(self, model, criterion, optimizer, loaders, logdir, callbacks, scheduler, resume, num_epochs, valid_loader, main_metric, minimize_metric, verbose, state_kwargs, checkpoint_data, fp16, monitoring_params, check)
204             monitoring_params=monitoring_params
205         )
--> 206         self.run_experiment(experiment, check=check)
207
208     def infer(

~/.local/lib/python3.6/site-packages/catalyst/contrib/dl/runner/wandb.py in run_experiment(self, experiment, check)
141         self._pre_experiment_hook(experiment=experiment)
142         super().run_experiment(experiment=experiment, check=check)
--> 143         self._post_experiment_hook(experiment=experiment)
144
145

~/.local/lib/python3.6/site-packages/catalyst/contrib/dl/runner/wandb.py in _post_experiment_hook(self, experiment)
104
105         checkpoint_paths = []
--> 106         for glob in self.checkpoints_glob:
107             checkpoint_paths.extend(list(checkpoints_src.glob(glob)))
108         checkpoint_paths = list(set(checkpoint_paths))

TypeError: 'NoneType' object is not iterable

# Fixed code
def load_checkpoint(*, filename, state: _State):
    if os.path.isfile(filename):
        print(f"=> loading checkpoint {filename}")
        checkpoint = utils.load_checkpoint(filename)

        state.epoch = checkpoint["epoch"]
        state.stage_epoch = checkpoint["stage_epoch"]
        state.stage = checkpoint["stage"]

        utils.unpack_checkpoint(
            checkpoint,
            model=state.model,
            criterion=state.criterion,
            optimizer=state.optimizer,
            scheduler=state.scheduler,
        )

        print(
            f"loaded checkpoint {filename} "
            f"(epoch {checkpoint['epoch']}, "
            f"stage_epoch {checkpoint['stage_epoch']}, "
            f"stage {checkpoint['stage']})"
        )
    else:
        raise Exception(f"No checkpoint found at {filename}")
# Buggy code
def on_stage_start(self, state: _State):
    for key in self._keys_from_state:
        value = getattr(state, key, None)
        if value is not None:
            setattr(self, key, value)

    if self.resume_dir is not None:
        self.resume = str(self.resume_dir) + "/" + str(self.resume)

    if self.resume is not None:
        self.load_checkpoint(filename=self.resume, state=state)


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-279a2ce060b8> in <module>
24     monitoring_params={
25         'project': "yt",
---> 26         'group': "aa"
27     }
28 )

~/.local/lib/python3.6/site-packages/catalyst/dl/runner/supervised.py in train(self, model, criterion, optimizer, loaders, logdir, callbacks, scheduler, resume, num_epochs, valid_loader, main_metric, minimize_metric, verbose, state_kwargs, checkpoint_data, fp16, monitoring_params, check)
204             monitoring_params=monitoring_params
205         )
--> 206         self.run_experiment(experiment, check=check)
207
208     def infer(

~/.local/lib/python3.6/site-packages/catalyst/contrib/dl/runner/wandb.py in run_experiment(self, experiment, check)
141         self._pre_experiment_hook(experiment=experiment)
142         super().run_experiment(experiment=experiment, check=check)
--> 143         self._post_experiment_hook(experiment=experiment)
144
145

~/.local/lib/python3.6/site-packages/catalyst/contrib/dl/runner/wandb.py in _post_experiment_hook(self, experiment)
104
105         checkpoint_paths = []
--> 106         for glob in self.checkpoints_glob:
107             checkpoint_paths.extend(list(checkpoints_src.glob(glob)))
108         checkpoint_paths = list(set(checkpoint_paths))

TypeError: 'NoneType' object is not iterable

# Fixed code
def on_stage_start(self, state: _State):
    for key in self._keys_from_state:
        value = getattr(state, key, None)
        if value is not None:
            setattr(self, key, value)

    if self.resume_dir is not None:
        self.resume = str(self.resume_dir) + "/" + str(self.resume)

    if self.resume is not None:
        self.load_checkpoint(filename=self.resume, state=state)
        state.resume = None
# Buggy code
def _run_stage(self, stage: str):
    self._prepare_for_stage(stage)

    self._run_event("stage", moment="start")
    for epoch in range(self.state.num_epochs):
        self.state.stage_epoch = epoch

        self._run_event("epoch", moment="start")
        self._run_epoch(stage=stage, epoch=epoch)
        self._run_event("epoch", moment="end")

        if self._check_run and self.state.stage_epoch >= 2:
            break
        if self.state.early_stop:
            self.state.early_stop = False
            break

        self.state.epoch += 1
    self._run_event("stage", moment="end")


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-279a2ce060b8> in <module>
24     monitoring_params={
25         'project': "yt",
---> 26         'group': "aa"
27     }
28 )

~/.local/lib/python3.6/site-packages/catalyst/dl/runner/supervised.py in train(self, model, criterion, optimizer, loaders, logdir, callbacks, scheduler, resume, num_epochs, valid_loader, main_metric, minimize_metric, verbose, state_kwargs, checkpoint_data, fp16, monitoring_params, check)
204             monitoring_params=monitoring_params
205         )
--> 206         self.run_experiment(experiment, check=check)
207
208     def infer(

~/.local/lib/python3.6/site-packages/catalyst/contrib/dl/runner/wandb.py in run_experiment(self, experiment, check)
141         self._pre_experiment_hook(experiment=experiment)
142         super().run_experiment(experiment=experiment, check=check)
--> 143         self._post_experiment_hook(experiment=experiment)
144
145

~/.local/lib/python3.6/site-packages/catalyst/contrib/dl/runner/wandb.py in _post_experiment_hook(self, experiment)
104
105         checkpoint_paths = []
--> 106         for glob in self.checkpoints_glob:
107             checkpoint_paths.extend(list(checkpoints_src.glob(glob)))
108         checkpoint_paths = list(set(checkpoint_paths))

TypeError: 'NoneType' object is not iterable

# Fixed code
def _run_stage(self, stage: str):
    self._prepare_for_stage(stage)

    self._run_event("stage", moment="start")
    while self.state.stage_epoch < self.state.num_epochs:
        self._run_event("epoch", moment="start")
        utils.set_global_seed(self.experiment.initial_seed + self.state.epoch + 1)
        self._run_epoch(stage=stage, epoch=self.state.stage_epoch)
        self._run_event("epoch", moment="end")

        if self._check_run and self.state.stage_epoch >= 2:
            break
        if self.state.early_stop:
            self.state.early_stop = False
            break

        self.state.epoch += 1
        self.state.stage_epoch += 1
    self._run_event("stage", moment="end")
# Buggy code
def stages(self) -> List[str]:
    """Experiment's stage names"""
    stages_keys = list(self.stages_config.keys())
    return stages_keys


# Traceback (TypeError)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-279a2ce060b8> in <module>
24     monitoring_params={
25         'project': "yt",
---> 26         'group': "aa"
27     }
28 )

~/.local/lib/python3.6/site-packages/catalyst/dl/runner/supervised.py in train(self, model, criterion, optimizer, loaders, logdir, callbacks, scheduler, resume, num_epochs, valid_loader, main_metric, minimize_metric, verbose, state_kwargs, checkpoint_data, fp16, monitoring_params, check)
204             monitoring_params=monitoring_params
205         )
--> 206         self.run_experiment(experiment, check=check)
207
208     def infer(

~/.local/lib/python3.6/site-packages/catalyst/contrib/dl/runner/wandb.py in run_experiment(self, experiment, check)
141         self._pre_experiment_hook(experiment=experiment)
142         super().run_experiment(experiment=experiment, check=check)
--> 143         self._post_experiment_hook(experiment=experiment)
144
145

~/.local/lib/python3.6/site-packages/catalyst/contrib/dl/runner/wandb.py in _post_experiment_hook(self, experiment)
104
105         checkpoint_paths = []
--> 106         for glob in self.checkpoints_glob:
107             checkpoint_paths.extend(list(checkpoints_src.glob(glob)))
108         checkpoint_paths = list(set(checkpoint_paths))

TypeError: 'NoneType' object is not iterable

# Fixed code
def stages(self) -> List[str]:
    """Experiment's stage names"""
    stages_keys = list(self.stages_config.keys())

    # Change start `stages_keys` if resume data were founded
    state_params = self.get_state_params(stages_keys[0])
    resume, resume_dir = [
        state_params.get(key, None) for key in ["resume", "resume_dir"]
    ]

    if resume_dir is not None:
        resume = resume_dir / str(resume)

    if resume is not None and Path(resume).is_file():
        checkpoint = utils.load_checkpoint(resume)
        start_stage = checkpoint["stage"]
        start_idx = stages_keys.index(start_stage)
        stages_keys = stages_keys[start_idx:]

    return stages_keys
# Buggy code
def _add_from_tx(self, tx: TransactionReceiptType) -> None:
    tx._confirmed.wait()
    if tx.status:
        self.at(tx.contract_address, tx.sender, tx)


# Traceback (brownie.exceptions.ContractNotFound)
Running 'scripts.dev-deploy.main'...
Transaction sent: 0x36f1599c9b5b5ab9f243f5d0c64e8f2637a355818bc4cf5e1a67168e9e22713e
Gas price: 0.0 gwei   Gas limit: 6721975
ArgobytesOwnedVaultDeployer.constructor confirmed - Block: 1   Gas used: 3545980 (52.75%)
ArgobytesOwnedVaultDeployer deployed at: 0x04246fAA61004668E1C0a388A3bF60E67827A17E

Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/home/ski/code/argobytes-contracts-brownie/venv/lib/python3.8/site-packages/brownie/network/contract.py", line 190, in _add_from_tx
self.at(tx.contract_address, tx.sender, tx)
File "/home/ski/code/argobytes-contracts-brownie/venv/lib/python3.8/site-packages/brownie/network/contract.py", line 174, in at
contract = ProjectContract(self._project, build, address, owner, tx)
File "/home/ski/code/argobytes-contracts-brownie/venv/lib/python3.8/site-packages/brownie/network/contract.py", line 728, in __init__
_DeployedContractBase.__init__(self, address, owner, tx)
File "/home/ski/code/argobytes-contracts-brownie/venv/lib/python3.8/site-packages/brownie/network/contract.py", line 309, in __init__
raise ContractNotFound(f"No contract deployed at {address}")
brownie.exceptions.ContractNotFound: No contract deployed at 0x04246fAA61004668E1C0a388A3bF60E67827A17E

# Fixed code
def _add_from_tx(self, tx: TransactionReceiptType) -> None:
    tx._confirmed.wait()
    if tx.status:
        try:
            self.at(tx.contract_address, tx.sender, tx)
        except ContractNotFound:
            # if the contract self-destructed during deployment
            pass
# Buggy code
def get_str_dtype(cls, pandas_dtype_arg):
    """Get pandas-compatible string representation of dtype."""
    dtype_ = pandas_dtype_arg
    if dtype_ is None:
        return dtype_

    if is_extension_array_dtype(dtype_):
        if isinstance(dtype_, type):
            try:
                # Convert to str here because some pandas dtypes allow
                # an empty constructor for compatatibility but fail on
                # str(). e.g: PeriodDtype
                return str(dtype_())
            except (TypeError, AttributeError) as err:
                raise TypeError(
                    f"Pandas dtype {dtype_} cannot be instantiated: "
                    f"{err}\n Usage Tip: Use an instance or a string "
                    "representation."
                ) from err
        return str(dtype_)

    if dtype_ in NUMPY_TYPES:
        dtype_ = cls.from_numpy_type(dtype_)
    elif isinstance(dtype_, str):
        dtype_ = cls.from_str_alias(dtype_)
    elif isinstance(dtype_, type):
        dtype_ = cls.from_python_type(dtype_)

    if isinstance(dtype_, cls):
        return dtype_.str_alias
    raise TypeError(
        "type of `pandas_dtype` argument not recognized: "
        f"{type(pandas_dtype_arg)}. Please specify a pandera PandasDtype "
        "enum, legal pandas data type, pandas data type string alias, or "
        "numpy data type string alias"
    )


# Traceback (AttributeError)
Traceback (most recent call last):
File "foo.py", line 8, in <module>
yaml_schema = schema.to_yaml()
File "/Users/nielsbantilan/git/pandera/pandera/schemas.py", line 1197, in to_yaml
return pandera.io.to_yaml(self, fp)
File "/Users/nielsbantilan/git/pandera/pandera/io.py", line 223, in to_yaml
statistics = _serialize_schema(dataframe_schema)
File "/Users/nielsbantilan/git/pandera/pandera/io.py", line 93, in _serialize_schema
columns = {
File "/Users/nielsbantilan/git/pandera/pandera/io.py", line 94, in <dictcomp>
col_name: _serialize_component_stats(column_stats)
File "/Users/nielsbantilan/git/pandera/pandera/io.py", line 68, in _serialize_component_stats
"pandas_dtype": component_stats["pandas_dtype"].value,
AttributeError: type object 'int' has no attribute 'value'

# Fixed code
def get_str_dtype(cls, pandas_dtype_arg) -> Optional[str]:
    """Get pandas-compatible string representation of dtype."""
    pandas_dtype = cls.get_dtype(pandas_dtype_arg)
    if pandas_dtype is None:
        return pandas_dtype
    elif isinstance(pandas_dtype, PandasDtype):
        return pandas_dtype.str_alias
    return str(pandas_dtype)
# Buggy code
def __eq__(self, other):
    # pylint: disable=comparison-with-callable
    # see https://github.com/PyCQA/pylint/issues/2306
    if other is None:
        return False
    if isinstance(other, str):
        other = self.from_str_alias(other)
    if self.value == "string" and LEGACY_PANDAS:
        return PandasDtype.String.value == other.value
    elif self.value == "string":
        return self.value == other.value
    return self.str_alias == other.str_alias


# Traceback (AttributeError)
Traceback (most recent call last):
File "foo.py", line 8, in <module>
yaml_schema = schema.to_yaml()
File "/Users/nielsbantilan/git/pandera/pandera/schemas.py", line 1197, in to_yaml
return pandera.io.to_yaml(self, fp)
File "/Users/nielsbantilan/git/pandera/pandera/io.py", line 223, in to_yaml
statistics = _serialize_schema(dataframe_schema)
File "/Users/nielsbantilan/git/pandera/pandera/io.py", line 93, in _serialize_schema
columns = {
File "/Users/nielsbantilan/git/pandera/pandera/io.py", line 94, in <dictcomp>
col_name: _serialize_component_stats(column_stats)
File "/Users/nielsbantilan/git/pandera/pandera/io.py", line 68, in _serialize_component_stats
"pandas_dtype": component_stats["pandas_dtype"].value,
AttributeError: type object 'int' has no attribute 'value'

# Fixed code
def __eq__(self, other):
    # pylint: disable=comparison-with-callable
    # see https://github.com/PyCQA/pylint/issues/2306
    if other is None:
        return False
    other_dtype = PandasDtype.get_dtype(other)
    if self.value == "string" and LEGACY_PANDAS:
        return PandasDtype.String.value == other_dtype.value
    elif self.value == "string":
        return self.value == other_dtype.value
    return self.str_alias == other_dtype.str_alias
# Buggy code
def _deserialize_component_stats(serialized_component_stats):
    from pandera import Check  # pylint: disable=import-outside-toplevel

    pandas_dtype = PandasDtype.from_str_alias(
        serialized_component_stats["pandas_dtype"]
    )
    checks = None
    if serialized_component_stats["checks"] is not None:
        checks = [
            _deserialize_check_stats(
                getattr(Check, check_name), check_stats, pandas_dtype
            )
            for check_name, check_stats in serialized_component_stats["checks"].items()
        ]
    return {
        "pandas_dtype": pandas_dtype,
        "nullable": serialized_component_stats["nullable"],
        "checks": checks,
        **{
            key: serialized_component_stats.get(key)
            for key in [
                "name",
                "allow_duplicates",
                "coerce",
                "required",
                "regex",
            ]
            if key in serialized_component_stats
        },
    }


# Traceback (AttributeError)
Traceback (most recent call last):
File "foo.py", line 8, in <module>
yaml_schema = schema.to_yaml()
File "/Users/nielsbantilan/git/pandera/pandera/schemas.py", line 1197, in to_yaml
return pandera.io.to_yaml(self, fp)
File "/Users/nielsbantilan/git/pandera/pandera/io.py", line 223, in to_yaml
statistics = _serialize_schema(dataframe_schema)
File "/Users/nielsbantilan/git/pandera/pandera/io.py", line 93, in _serialize_schema
columns = {
File "/Users/nielsbantilan/git/pandera/pandera/io.py", line 94, in <dictcomp>
col_name: _serialize_component_stats(column_stats)
File "/Users/nielsbantilan/git/pandera/pandera/io.py", line 68, in _serialize_component_stats
"pandas_dtype": component_stats["pandas_dtype"].value,
AttributeError: type object 'int' has no attribute 'value'

# Fixed code
def _deserialize_component_stats(serialized_component_stats):
    from pandera import Check  # pylint: disable=import-outside-toplevel

    pandas_dtype = PandasDtype.from_str_alias(
        serialized_component_stats["pandas_dtype"]
    )
    checks = None
    if serialized_component_stats.get("checks") is not None:
        checks = [
            _deserialize_check_stats(
                getattr(Check, check_name), check_stats, pandas_dtype
            )
            for check_name, check_stats in serialized_component_stats["checks"].items()
        ]
    return {
        "pandas_dtype": pandas_dtype,
        "checks": checks,
        **{
            key: serialized_component_stats.get(key)
            for key in [
                "name",
                "nullable",
                "allow_duplicates",
                "coerce",
                "required",
                "regex",
            ]
            if key in serialized_component_stats
        },
    }
# Buggy code
def get_dataframe_schema_statistics(dataframe_schema):
    """Get statistical properties from dataframe schema."""
    statistics = {
        "columns": {
            col_name: {
                "pandas_dtype": column._pandas_dtype,
                "nullable": column.nullable,
                "allow_duplicates": column.allow_duplicates,
                "coerce": column.coerce,
                "required": column.required,
                "regex": column.regex,
                "checks": parse_checks(column.checks),
            }
            for col_name, column in dataframe_schema.columns.items()
        },
        "index": (
            None
            if dataframe_schema.index is None
            else get_index_schema_statistics(dataframe_schema.index)
        ),
        "coerce": dataframe_schema.coerce,
    }
    return statistics


# Traceback (AttributeError)
Traceback (most recent call last):
File "foo.py", line 8, in <module>
yaml_schema = schema.to_yaml()
File "/Users/nielsbantilan/git/pandera/pandera/schemas.py", line 1197, in to_yaml
return pandera.io.to_yaml(self, fp)
File "/Users/nielsbantilan/git/pandera/pandera/io.py", line 223, in to_yaml
statistics = _serialize_schema(dataframe_schema)
File "/Users/nielsbantilan/git/pandera/pandera/io.py", line 93, in _serialize_schema
columns = {
File "/Users/nielsbantilan/git/pandera/pandera/io.py", line 94, in <dictcomp>
col_name: _serialize_component_stats(column_stats)
File "/Users/nielsbantilan/git/pandera/pandera/io.py", line 68, in _serialize_component_stats
"pandas_dtype": component_stats["pandas_dtype"].value,
AttributeError: type object 'int' has no attribute 'value'

# Fixed code
def get_dataframe_schema_statistics(dataframe_schema):
    """Get statistical properties from dataframe schema."""
    statistics = {
        "columns": {
            col_name: {
                "pandas_dtype": column.pdtype,
                "nullable": column.nullable,
                "allow_duplicates": column.allow_duplicates,
                "coerce": column.coerce,
                "required": column.required,
                "regex": column.regex,
                "checks": parse_checks(column.checks),
            }
            for col_name, column in dataframe_schema.columns.items()
        },
        "index": (
            None
            if dataframe_schema.index is None
            else get_index_schema_statistics(dataframe_schema.index)
        ),
        "coerce": dataframe_schema.coerce,
    }
    return statistics
# Buggy code
def pdtype(self) -> Optional[PandasDtype]:
    """PandasDtype of the dataframe."""
    if self.pandas_dtype is None:
        return self.pandas_dtype
    return PandasDtype.from_str_alias(PandasDtype.get_str_dtype(self.pandas_dtype))


# Traceback (AttributeError)
Traceback (most recent call last):
File "foo.py", line 8, in <module>
yaml_schema = schema.to_yaml()
File "/Users/nielsbantilan/git/pandera/pandera/schemas.py", line 1197, in to_yaml
return pandera.io.to_yaml(self, fp)
File "/Users/nielsbantilan/git/pandera/pandera/io.py", line 223, in to_yaml
statistics = _serialize_schema(dataframe_schema)
File "/Users/nielsbantilan/git/pandera/pandera/io.py", line 93, in _serialize_schema
columns = {
File "/Users/nielsbantilan/git/pandera/pandera/io.py", line 94, in <dictcomp>
col_name: _serialize_component_stats(column_stats)
File "/Users/nielsbantilan/git/pandera/pandera/io.py", line 68, in _serialize_component_stats
"pandas_dtype": component_stats["pandas_dtype"].value,
AttributeError: type object 'int' has no attribute 'value'

# Fixed code
def pdtype(self) -> Optional[PandasDtype]:
    """PandasDtype of the dataframe."""
    pandas_dtype = PandasDtype.get_str_dtype(self.pandas_dtype)
    if pandas_dtype is None:
        return pandas_dtype
    return PandasDtype.from_str_alias(pandas_dtype)
# Buggy code
def _serialize_component_stats(component_stats):
    """
    Serialize column or index statistics into json/yaml-compatible format.
    """
    serialized_checks = None
    if component_stats["checks"] is not None:
        serialized_checks = {
            check_name: _serialize_check_stats(
                check_stats, component_stats["pandas_dtype"]
            )
            for check_name, check_stats in component_stats["checks"].items()
        }
    return {
        "pandas_dtype": component_stats["pandas_dtype"].value,
        "nullable": component_stats["nullable"],
        "checks": serialized_checks,
        **{
            key: component_stats.get(key)
            for key in ["name", "allow_duplicates", "coerce", "required", "regex"]
            if key in component_stats
        },
    }


# Traceback (AttributeError)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-7-6d1fa2fde789> in <module>
----> 1 pa.io.to_script(schema)

~/git/pandera/pandera/io.py in to_script(dataframe_schema, path_or_buf)
309                 properties['pandas_dtype'].name
310             ),
--> 311             checks=_format_checks(properties["checks"]),
312             nullable=properties["nullable"],
313         )

~/git/pandera/pandera/io.py in _format_checks(checks_dict)
248     for check_name, check_kwargs in checks_dict.items():
249         args = ", ".join(
--> 250             "{}={}".format(k, v.__repr__()) for k, v in check_kwargs.items()
251         )
252         checks.append("Check.{}({})".format(check_name, args))

AttributeError: 'NoneType' object has no attribute 'items'

# Fixed code
def _serialize_component_stats(component_stats):
    """
    Serialize column or index statistics into json/yaml-compatible format.
    """
    serialized_checks = None
    if component_stats["checks"] is not None:
        serialized_checks = {}
        for check_name, check_stats in component_stats["checks"].items():
            if check_stats is None:
                warnings.warn(
                    f"Check {check_name} cannot be serialized. This check will be "
                    f"ignored"
                )
            else:
                serialized_checks[check_name] = _serialize_check_stats(
                    check_stats, component_stats["pandas_dtype"]
                )
    return {
        "pandas_dtype": component_stats["pandas_dtype"].value,
        "nullable": component_stats["nullable"],
        "checks": serialized_checks,
        **{
            key: component_stats.get(key)
            for key in ["name", "allow_duplicates", "coerce", "required", "regex"]
            if key in component_stats
        },
    }
# Buggy code
def _format_checks(checks_dict):
    if checks_dict is None:
        return "None"

    checks = []
    for check_name, check_kwargs in checks_dict.items():
        args = ", ".join(
            "{}={}".format(k, v.__repr__()) for k, v in check_kwargs.items()
        )
        checks.append("Check.{}({})".format(check_name, args))
    return "[{}]".format(", ".join(checks))


# Traceback (AttributeError)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-7-6d1fa2fde789> in <module>
----> 1 pa.io.to_script(schema)

~/git/pandera/pandera/io.py in to_script(dataframe_schema, path_or_buf)
309                 properties['pandas_dtype'].name
310             ),
--> 311             checks=_format_checks(properties["checks"]),
312             nullable=properties["nullable"],
313         )

~/git/pandera/pandera/io.py in _format_checks(checks_dict)
248     for check_name, check_kwargs in checks_dict.items():
249         args = ", ".join(
--> 250             "{}={}".format(k, v.__repr__()) for k, v in check_kwargs.items()
251         )
252         checks.append("Check.{}({})".format(check_name, args))

AttributeError: 'NoneType' object has no attribute 'items'

# Fixed code
def _format_checks(checks_dict):
    if checks_dict is None:
        return "None"

    checks = []
    for check_name, check_kwargs in checks_dict.items():
        if check_kwargs is None:
            warnings.warn(
                f"Check {check_name} cannot be serialized. This check will be ignored"
            )
        else:
            args = ", ".join(
                "{}={}".format(k, v.__repr__()) for k, v in check_kwargs.items()
            )
            checks.append("Check.{}({})".format(check_name, args))
    return "[{}]".format(", ".join(checks))
# Buggy code
def _process_optional_args(self, optional_args):
    # Define locking method
    self.lock_disable = optional_args.get("lock_disable", False)

    self.enablepwd = optional_args.pop("enable_password", "")
    self.eos_autoComplete = optional_args.pop("eos_autoComplete", None)
    # eos_transport is there for backwards compatibility, transport is the preferred method
    transport = optional_args.get(
        "transport", optional_args.get("eos_transport", "https")
    )
    try:
        self.transport_class = pyeapi.client.TRANSPORTS[transport]
    except KeyError:
        raise ConnectionException("Unknown transport: {}".format(self.transport))
    init_args = inspect.getfullargspec(self.transport_class.__init__)[0]

    init_args.pop(0)  # Remove "self"
    init_args.append("enforce_verification")  # Not an arg for unknown reason

    filter_args = ["host", "username", "password", "timeout", "lock_disable"]

    self.eapi_kwargs = {
        k: v
        for k, v in optional_args.items()
        if k in init_args and k not in filter_args
    }


# Traceback (KeyError)
Traceback (most recent call last):
File "list-vlan2.py", line 19, in <module>
print(yaml.dump(device.get_interfaces_counters()))
File "/srv/home/adm-brin-f/Devel/pythonspace/test-napalm/.venv/lib/python3.6/site-packages/napalm/ios/ios.py", line 2133, in get_interfaces_counters
counters[interface]["rx_discards"] = int(match.group("IQD"))
KeyError: 'Management0'

# Fixed code
def _process_optional_args(self, optional_args):
    # Define locking method
    self.lock_disable = optional_args.get("lock_disable", False)

    self.enablepwd = optional_args.pop("enable_password", "")
    self.eos_autoComplete = optional_args.pop("eos_autoComplete", None)
    # eos_transport is there for backwards compatibility, transport is the preferred method
    transport = optional_args.get(
        "transport", optional_args.get("eos_transport", "https")
    )
    self.fn0039_config = optional_args.pop("eos_fn0039_config", False)
    try:
        self.transport_class = pyeapi.client.TRANSPORTS[transport]
    except KeyError:
        raise ConnectionException("Unknown transport: {}".format(self.transport))
    init_args = inspect.getfullargspec(self.transport_class.__init__)[0]

    init_args.pop(0)  # Remove "self"
    init_args.append("enforce_verification")  # Not an arg for unknown reason

    filter_args = ["host", "username", "password", "timeout", "lock_disable"]

    self.eapi_kwargs = {
        k: v
        for k, v in optional_args.items()
        if k in init_args and k not in filter_args
    }
# Buggy code
def run_commands(self, commands, **kwargs):
    """
    Run commands wrapper
    :param commands: list of commands
    :param kwargs: other args
    :return: list of outputs
    """
    if isinstance(commands, str):
        new_commands = [cli_convert(commands, self.cli_version)]
    else:
        new_commands = [cli_convert(cmd, self.cli_version) for cmd in commands]

    return super(Node, self).run_commands(new_commands, **kwargs)


# Traceback (KeyError)
Traceback (most recent call last):
File "list-vlan2.py", line 19, in <module>
print(yaml.dump(device.get_interfaces_counters()))
File "/srv/home/adm-brin-f/Devel/pythonspace/test-napalm/.venv/lib/python3.6/site-packages/napalm/ios/ios.py", line 2133, in get_interfaces_counters
counters[interface]["rx_discards"] = int(match.group("IQD"))
KeyError: 'Management0'

# Fixed code
def run_commands(self, commands, **kwargs):
    """
    Run commands wrapper
    :param commands: list of commands
    :param kwargs: other args
    :return: list of outputs
    """
    fn0039_transform = kwargs.pop("fn0039_transform", True)
    if fn0039_transform:
        if isinstance(commands, str):
            commands = [cli_convert(commands, self.cli_version)]
        else:
            commands = [cli_convert(cmd, self.cli_version) for cmd in commands]

    return super(Node, self).run_commands(commands, **kwargs)
# Buggy code
def commit_config(self, message=""):
    """Commit configuration."""
    commit_args = {"comment": message} if message else {}
    self.device.cu.commit(ignore_warning=self.ignore_warning, **commit_args)
    if not self.lock_disable and not self.session_config_lock:
        self._unlock()


# Traceback (KeyError)
Traceback (most recent call last):
File "list-vlan2.py", line 19, in <module>
print(yaml.dump(device.get_interfaces_counters()))
File "/srv/home/adm-brin-f/Devel/pythonspace/test-napalm/.venv/lib/python3.6/site-packages/napalm/ios/ios.py", line 2133, in get_interfaces_counters
counters[interface]["rx_discards"] = int(match.group("IQD"))
KeyError: 'Management0'

# Fixed code
def commit_config(self, message=""):
    """Commit configuration."""
    commit_args = {"comment": message} if message else {}
    self.device.cu.commit(ignore_warning=self.ignore_warning, **commit_args)
    if not self.lock_disable and not self.session_config_lock:
        self._unlock()
    if self.config_private:
        self.device.rpc.close_configuration()
# Buggy code
def discard_config(self):
    """Discard changes (rollback 0)."""
    self.device.cu.rollback(rb_id=0)
    if not self.lock_disable and not self.session_config_lock:
        self._unlock()


# Traceback (KeyError)
Traceback (most recent call last):
File "list-vlan2.py", line 19, in <module>
print(yaml.dump(device.get_interfaces_counters()))
File "/srv/home/adm-brin-f/Devel/pythonspace/test-napalm/.venv/lib/python3.6/site-packages/napalm/ios/ios.py", line 2133, in get_interfaces_counters
counters[interface]["rx_discards"] = int(match.group("IQD"))
KeyError: 'Management0'

# Fixed code
def discard_config(self):
    """Discard changes (rollback 0)."""
    self.device.cu.rollback(rb_id=0)
    if not self.lock_disable and not self.session_config_lock:
        self._unlock()
    if self.config_private:
        self.device.rpc.close_configuration()
# Buggy code
def _send_command(self, command, raw_text=False):
    """
    Wrapper for Netmiko's send_command method.

    raw_text argument is not used and is for code sharing with NX-API.
    """
    return self.device.send_command(command)


# Traceback (KeyError)
Traceback (most recent call last):
File "list-vlan2.py", line 19, in <module>
print(yaml.dump(device.get_interfaces_counters()))
File "/srv/home/adm-brin-f/Devel/pythonspace/test-napalm/.venv/lib/python3.6/site-packages/napalm/ios/ios.py", line 2133, in get_interfaces_counters
counters[interface]["rx_discards"] = int(match.group("IQD"))
KeyError: 'Management0'

# Fixed code
def _send_command(self, command, raw_text=False, cmd_verify=True):
    """
    Wrapper for Netmiko's send_command method.

    raw_text argument is not used and is for code sharing with NX-API.
    """
    return self.device.send_command(command, cmd_verify=cmd_verify)