gurudesh/pytracebugs huggingface dataset:
# Buggy code
def start(self):
    """
    Start the actual proxy minion.

    If sub-classed, don't **ever** forget to run:

        super(YourSubClass, self).start()

    NOTE: Run any required code before calling `super()`.
    """
    super(ProxyMinion, self).start()
    try:
        if check_user(self.config["user"]):
            log.info("The proxy minion is starting up")
            self.verify_hash_type()
            self.action_log_info("Starting up")
            self.minion.tune_in()
    except (KeyboardInterrupt, SaltSystemExit) as exc:
        self.action_log_info("Stopping")
        if isinstance(exc, KeyboardInterrupt):
            log.warning("Exiting on Ctrl-c")
            self.shutdown()
        else:
            log.error(str(exc))
            self.shutdown(exc.code)


# Traceback (KeyError)
salt p8000 test.ping
p8000:
The minion function caused an exception: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/minion.py", line 1378, in _thread_return
return_data = executor.execute()
File "/usr/lib/python2.7/site-packages/salt/executors/direct_call.py", line 28, in execute
return self.func(*self.args, **self.kwargs)
File "/usr/lib/python2.7/site-packages/salt/modules/test.py", line 117, in ping
ping_cmd = __opts__['proxy']['proxytype'] + '.ping'
KeyError: 'proxy'

# Fixed code
def start(self):
    """
    Start the actual proxy minion.

    If sub-classed, don't **ever** forget to run:

        super(YourSubClass, self).start()

    NOTE: Run any required code before calling `super()`.
    """
    super(ProxyMinion, self).start()
    try:
        if check_user(self.config["user"]):
            self.action_log_info("The Proxy Minion is starting up")
            self.verify_hash_type()
            self.minion.tune_in()
            if self.minion.restart:
                raise SaltClientError("Proxy Minion could not connect to Master")
    except (KeyboardInterrupt, SaltSystemExit) as exc:
        self.action_log_info("Proxy Minion Stopping")
        if isinstance(exc, KeyboardInterrupt):
            log.warning("Exiting on Ctrl-c")
            self.shutdown()
        else:
            log.error(str(exc))
            self.shutdown(exc.code)
# Buggy code
def _handle_signals(self, signum, sigframe):  # pylint: disable=unused-argument
    # escalate signal to the process manager processes
    self.minion.stop(signum)
    super(Minion, self)._handle_signals(signum, sigframe)


# Traceback (KeyError)
salt p8000 test.ping
p8000:
The minion function caused an exception: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/minion.py", line 1378, in _thread_return
return_data = executor.execute()
File "/usr/lib/python2.7/site-packages/salt/executors/direct_call.py", line 28, in execute
return self.func(*self.args, **self.kwargs)
File "/usr/lib/python2.7/site-packages/salt/modules/test.py", line 117, in ping
ping_cmd = __opts__['proxy']['proxytype'] + '.ping'
KeyError: 'proxy'

# Fixed code
def _handle_signals(self, signum, sigframe):  # pylint: disable=unused-argument
    # escalate signal to the process manager processes
    self.minion.stop(signum)
    super(ProxyMinion, self)._handle_signals(signum, sigframe)
# Buggy code
def list_nodes_select(conn=None, call=None):
    """
    Return a list of the VMs that are on the provider, with select fields
    """
    return salt.utils.cloud.list_nodes_select(
        list_nodes_full(),
        __opts__["query.selection"],
        call,
    )


# Traceback (NameError)
[ERROR   ] There was a query error: global name '__opts__' is not defined
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/cloud/cli.py", line 348, in run
ret = mapper.run_map(dmap)
File "/usr/lib/python2.7/site-packages/salt/cloud/__init__.py", line 2213, in run_map
profile, local_master=local_master
File "/usr/lib/python2.7/site-packages/salt/cloud/__init__.py", line 1281, in create
output = self.clouds[func](vm_)
File "/usr/lib/python2.7/site-packages/salt/cloud/clouds/vultrpy.py", line 224, in create
transport=__opts__['transport']
File "/usr/lib/python2.7/site-packages/salt/utils/cloud.py", line 1721, in fire_event
sock_dir = os.path.join(__opts__['sock_dir'], 'master')
NameError: global name '__opts__' is not defined

# Fixed code
def list_nodes_select(conn=None, call=None):
    """
    Return a list of the VMs that are on the provider, with select fields
    """
    return __utils__["cloud.list_nodes_select"](
        list_nodes_full(),
        __opts__["query.selection"],
        call,
    )
# Buggy code
def show_instance(name, call=None):
    """
    Show the details from the provider concerning an instance
    """
    if call != "action":
        raise SaltCloudSystemExit(
            "The show_instance action must be called with -a or --action."
        )

    nodes = list_nodes_full()
    # Find under which cloud service the name is listed, if any
    if name not in nodes:
        return {}
    salt.utils.cloud.cache_node(nodes[name], __active_provider_name__, __opts__)
    return nodes[name]


# Traceback (NameError)
[ERROR   ] There was a query error: global name '__opts__' is not defined
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/cloud/cli.py", line 348, in run
ret = mapper.run_map(dmap)
File "/usr/lib/python2.7/site-packages/salt/cloud/__init__.py", line 2213, in run_map
profile, local_master=local_master
File "/usr/lib/python2.7/site-packages/salt/cloud/__init__.py", line 1281, in create
output = self.clouds[func](vm_)
File "/usr/lib/python2.7/site-packages/salt/cloud/clouds/vultrpy.py", line 224, in create
transport=__opts__['transport']
File "/usr/lib/python2.7/site-packages/salt/utils/cloud.py", line 1721, in fire_event
sock_dir = os.path.join(__opts__['sock_dir'], 'master')
NameError: global name '__opts__' is not defined

# Fixed code
def show_instance(name, call=None):
    """
    Show the details from the provider concerning an instance
    """
    if call != "action":
        raise SaltCloudSystemExit(
            "The show_instance action must be called with -a or --action."
        )

    nodes = list_nodes_full()
    # Find under which cloud service the name is listed, if any
    if name not in nodes:
        return {}
    __utils__["cloud.cache_node"](nodes[name], __active_provider_name__, __opts__)
    return nodes[name]
# Buggy code
def _query(path, method="GET", data=None, params=None, header_dict=None, decode=True):
    """
    Perform a query directly against the Vultr REST API
    """
    api_key = config.get_cloud_config_value(
        "api_key",
        get_configured_provider(),
        __opts__,
        search_global=False,
    )
    management_host = config.get_cloud_config_value(
        "management_host",
        get_configured_provider(),
        __opts__,
        search_global=False,
        default="api.vultr.com",
    )
    url = "https://{management_host}/v1/{path}?api_key={api_key}".format(
        management_host=management_host,
        path=path,
        api_key=api_key,
    )

    if header_dict is None:
        header_dict = {}

    result = salt.utils.http.query(
        url,
        method=method,
        params=params,
        data=data,
        header_dict=header_dict,
        port=443,
        text=True,
        decode=decode,
        decode_type="json",
        hide_fields=["api_key"],
        opts=__opts__,
    )
    if "dict" in result:
        return result["dict"]

    return result


# Traceback (NameError)
[ERROR   ] There was a query error: global name '__opts__' is not defined
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/cloud/cli.py", line 348, in run
ret = mapper.run_map(dmap)
File "/usr/lib/python2.7/site-packages/salt/cloud/__init__.py", line 2213, in run_map
profile, local_master=local_master
File "/usr/lib/python2.7/site-packages/salt/cloud/__init__.py", line 1281, in create
output = self.clouds[func](vm_)
File "/usr/lib/python2.7/site-packages/salt/cloud/clouds/vultrpy.py", line 224, in create
transport=__opts__['transport']
File "/usr/lib/python2.7/site-packages/salt/utils/cloud.py", line 1721, in fire_event
sock_dir = os.path.join(__opts__['sock_dir'], 'master')
NameError: global name '__opts__' is not defined

# Fixed code
def _query(path, method="GET", data=None, params=None, header_dict=None, decode=True):
    """
    Perform a query directly against the Vultr REST API
    """
    api_key = config.get_cloud_config_value(
        "api_key",
        get_configured_provider(),
        __opts__,
        search_global=False,
    )
    management_host = config.get_cloud_config_value(
        "management_host",
        get_configured_provider(),
        __opts__,
        search_global=False,
        default="api.vultr.com",
    )
    url = "https://{management_host}/v1/{path}?api_key={api_key}".format(
        management_host=management_host,
        path=path,
        api_key=api_key,
    )

    if header_dict is None:
        header_dict = {}

    result = __utils__["http.query"](
        url,
        method=method,
        params=params,
        data=data,
        header_dict=header_dict,
        port=443,
        text=True,
        decode=decode,
        decode_type="json",
        hide_fields=["api_key"],
        opts=__opts__,
    )
    if "dict" in result:
        return result["dict"]

    return result
# Buggy code
def _psql_cmd(*args, **kwargs):
    """
    Return string with fully composed psql command.

    Accept optional keyword arguments: user, host and port as well as any
    number or positional arguments to be added to the end of command.
    """
    (user, host, port, maintenance_db, password) = _connection_defaults(
        kwargs.get("user"),
        kwargs.get("host"),
        kwargs.get("port"),
        kwargs.get("maintenance_db"),
        kwargs.get("password"),
    )

    cmd = [
        salt.utils.which("psql"),
        "--no-align",
        "--no-readline",
        "--no-password",
    ]  # It is never acceptable to issue a password prompt.
    if user:
        cmd += ["--username", user]
    if host:
        cmd += ["--host", host]
    if port:
        cmd += ["--port", str(port)]
    if not maintenance_db:
        maintenance_db = "postgres"
    cmd.extend(["--dbname", maintenance_db])
    cmd.extend(args)
    return cmd


# Traceback (KeyError)
# salt-call postgres.version

local:
Timing is on.

# salt-call postgres.db_list
[ERROR   ] An un-handled exception was caught by salt's global exception handler:
KeyError: 'Name'
Traceback (most recent call last):
File "/usr/bin/salt-call", line 11, in <module>
salt_call()
File "/usr/lib/python2.7/dist-packages/salt/scripts.py", line 352, in salt_call
client.run()
File "/usr/lib/python2.7/dist-packages/salt/cli/call.py", line 58, in run
caller.run()
File "/usr/lib/python2.7/dist-packages/salt/cli/caller.py", line 134, in run
ret = self.call()
File "/usr/lib/python2.7/dist-packages/salt/cli/caller.py", line 197, in call
ret['return'] = func(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/modules/postgres.py", line 435, in db_list
ret[row['Name']] = row

# Fixed code
def _psql_cmd(*args, **kwargs):
    """
    Return string with fully composed psql command.

    Accept optional keyword arguments: user, host and port as well as any
    number or positional arguments to be added to the end of command.
    """
    (user, host, port, maintenance_db, password) = _connection_defaults(
        kwargs.get("user"),
        kwargs.get("host"),
        kwargs.get("port"),
        kwargs.get("maintenance_db"),
        kwargs.get("password"),
    )

    cmd = [
        salt.utils.which("psql"),
        "--no-align",
        "--no-readline",
        "--no-psqlrc",
        "--no-password",
    ]  # It is never acceptable to issue a password prompt.
    if user:
        cmd += ["--username", user]
    if host:
        cmd += ["--host", host]
    if port:
        cmd += ["--port", str(port)]
    if not maintenance_db:
        maintenance_db = "postgres"
    cmd.extend(["--dbname", maintenance_db])
    cmd.extend(args)
    return cmd
# Buggy code
def __virtual__():
    """
    Virtual service only on systems using runit as init process (PID 1).
    Otherwise, use this module with the provider mechanism.
    """
    if __grains__["init"] == "runit":
        if __grains__["os"] == "Void":
            add_svc_avail_path("/etc/sv")
        return __virtualname__
    return False


# Traceback (KeyError)
[ERROR   ] Exception raised when processing __virtual__ function for runit. Module will not be loaded 'init'
Traceback (most recent call last):
File "/opt/local/lib/python2.7/site-packages/salt/loader.py", line 1583, in process_virtual
virtual = getattr(mod, virtual_func)()
File "/opt/local/lib/python2.7/site-packages/salt/modules/runit.py", line 91, in __virtual__
if __grains__['init'] == 'runit':
File "/opt/local/lib/python2.7/site-packages/salt/utils/context.py", line 194, in __getitem__
return self._dict()[key]
KeyError: 'init'
[WARNING ] salt.loaded.int.module.runit.__virtual__() is wrongly returning `None`. It should either return `True`, `False` or a new name. If you're the developer of the module 'runit', please fix this.

# Fixed code
def __virtual__():
    """
    Virtual service only on systems using runit as init process (PID 1).
    Otherwise, use this module with the provider mechanism.
    """
    if __grains__.get("init") == "runit":
        if __grains__["os"] == "Void":
            add_svc_avail_path("/etc/sv")
        return __virtualname__
    return False
# Buggy code
def verify_log(opts):
    """
    If an insecre logging configuration is found, show a warning
    """
    level = LOG_LEVELS.get(opts.get("log_level").lower(), logging.NOTSET)

    if level < logging.INFO:
        log.warn(
            "Insecure logging configuration detected! Sensitive data may be logged."
        )


# Traceback (AttributeError)
2016-09-21 11:39:14,969 [salt.log.setup   ][ERROR   ][596] An un-handled exception was caught by salt's global exception handler:
AttributeError: 'NoneType' object has no attribute 'lower'
Traceback (most recent call last):
File "/usr/bin/salt-api", line 8, in <module>
salt_api()
File "/usr/lib/python2.7/dist-packages/salt/scripts.py", line 464, in salt_api
sapi.start()
File "/usr/lib/python2.7/dist-packages/salt/cli/api.py", line 79, in start
super(SaltAPI, self).start()
File "/usr/lib/python2.7/dist-packages/salt/utils/parsers.py", line 941, in start
self.prepare()
File "/usr/lib/python2.7/dist-packages/salt/cli/api.py", line 53, in prepare
verify_log(self.config)
File "/usr/lib/python2.7/dist-packages/salt/utils/verify.py", line 523, in verify_log
level = LOG_LEVELS.get(opts.get('log_level').lower(), logging.NOTSET)
AttributeError: 'NoneType' object has no attribute 'lower'

# Fixed code
def verify_log(opts):
    """
    If an insecre logging configuration is found, show a warning
    """
    level = LOG_LEVELS.get(str(opts.get("log_level")).lower(), logging.NOTSET)

    if level < logging.INFO:
        log.warn(
            "Insecure logging configuration detected! Sensitive data may be logged."
        )
# Buggy code
def present(name, definition):
    """
    Ensure that the named index is present
    """

    ret = {"name": name, "changes": {}, "result": True, "comment": ""}

    index_exists = __salt__["elasticsearch.index_exists"](name=name)
    if not index_exists:
        if __opts__["test"]:
            ret["comment"] = "Index {0} will be created".format(name)
            ret["result"] = None
        else:
            ret["result"] = __salt__["elasticsearch.index_create"](
                index=name, body=definition
            )
            # TODO show pending changes (body)

            if ret["result"]:
                ret["comment"] = "Created index {0} successfully".format(name)
    elif index_exists:
        ret["comment"] = "Index {0} is already present".format(name)
    else:
        ret["comment"] = (
            "Failed to determine whether index {0} is present, see Minion log for more information".format(
                name
            )
        )
        ret["result"] = False

    return ret


# Traceback (TypeError)
----------
ID: elasticsearch_index_some_index_name
Function: elasticsearch_index.present
Name: appointment
Result: False
Comment: An exception occurred in this state: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/state.py", line 1723, in call
**cdata['kwargs'])
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1650, in wrapper
return f(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/salt/states/elasticsearch_index.py", line 53, in present
index_exists = __salt__['elasticsearch.index_exists'](name=name)
TypeError: index_exists() got an unexpected keyword argument 'name'
Started: 23:58:37.170851
Duration: 1.342 ms
Changes:

# Fixed code
def present(name, definition):
    """
    Ensure that the named index is present
    """

    ret = {"name": name, "changes": {}, "result": True, "comment": ""}

    index_exists = __salt__["elasticsearch.index_exists"](index=name)
    if not index_exists:
        if __opts__["test"]:
            ret["comment"] = "Index {0} will be created".format(name)
            ret["result"] = None
        else:
            ret["result"] = __salt__["elasticsearch.index_create"](
                index=name, body=definition
            )
            # TODO show pending changes (body)

            if ret["result"]:
                ret["comment"] = "Created index {0} successfully".format(name)
    elif index_exists:
        ret["comment"] = "Index {0} is already present".format(name)
    else:
        ret["comment"] = (
            "Failed to determine whether index {0} is present, see Minion log for more information".format(
                name
            )
        )
        ret["result"] = False

    return ret
# Buggy code
def output(data):
    """
    The HighState Outputter is only meant to be used with the state.highstate
    function, or a function that returns highstate return data.
    """
    # If additional information is passed through via the "data" dictionary to
    # the highstate outputter, such as "outputter" or "retcode", discard it.
    # We only want the state data that was passed through, if it is wrapped up
    # in the "data" key, as the orchestrate runner does. See Issue #31330,
    # pull request #27838, and pull request #27175 for more information.
    if "data" in data:
        data = data.pop("data")

    for host, hostdata in six.iteritems(data):
        if not isinstance(hostdata, dict):
            # Highstate return data must be a dict, if this is not the case
            # then this value is likely a retcode.
            continue
        return _format_host(host, hostdata)[0]
    log.error(
        "Data passed to highstate outputter is not a valid highstate return: %s", data
    )


# Traceback (AttributeError)
[ch3ll@thecakeisalie ~]$ sudo salt '*02*' state.sls doesnotexist -ldebug

...
[DEBUG   ] LazyLoaded highstate.output
[ERROR   ] Data passed to highstate outputter is not a valid highstate return: {'ch3ll-minion02': ["No matching sls found for 'doesnotexist' in env 'base'"]}
[DEBUG   ] Traceback (most recent call last):
File "/home/ch3ll/git/salt/salt/output/__init__.py", line 39, in try_printout
return get_printout(out, opts)(data).rstrip()
AttributeError: 'NoneType' object has no attribute 'rstrip'

[DEBUG   ] LazyLoaded nested.output
ch3ll-minion02:
- No matching sls found for 'doesnotexist' in env 'base'
[DEBUG   ] jid 20160812160340754435 found all minions set(['ch3ll-minion02'])
ERROR: Minions returned with non-zero exit code

# Fixed code
def output(data):
    """
    The HighState Outputter is only meant to be used with the state.highstate
    function, or a function that returns highstate return data.
    """
    # If additional information is passed through via the "data" dictionary to
    # the highstate outputter, such as "outputter" or "retcode", discard it.
    # We only want the state data that was passed through, if it is wrapped up
    # in the "data" key, as the orchestrate runner does. See Issue #31330,
    # pull request #27838, and pull request #27175 for more information.
    if "data" in data:
        data = data.pop("data")

    for host, hostdata in six.iteritems(data):
        if not isinstance(hostdata, dict):
            # Highstate return data must be a dict, if this is not the case
            # then this value is likely a retcode.
            continue
        return _format_host(host, hostdata)[0]
    log.error(
        "Data passed to highstate outputter is not a valid highstate return: %s", data
    )
    # We should not reach here, but if we do return empty string
    return ""
# Buggy code
def output(data):
    """
    The HighState Outputter is only meant to be used with the state.highstate
    function, or a function that returns highstate return data.
    """
    # If additional information is passed through via the "data" dictionary to
    # the highstate outputter, such as "outputter" or "retcode", discard it.
    # We only want the state data that was passed through, if it is wrapped up
    # in the "data" key, as the orchestrate runner does. See Issue #31330,
    # pull request #27838, and pull request #27175 for more information.
    if "data" in data:
        data = data.pop("data")

    ret = [
        _format_host(host, hostdata)[0]
        for host, hostdata in six.iteritems(data)
        # Highstate return data must be a dict, if this is not the case
        # then this value is likely a retcode.
        if isinstance(hostdata, dict)
    ]
    if ret:
        return "\n".join(ret)
    log.error(
        "Data passed to highstate outputter is not a valid highstate return: %s", data
    )
    # We should not reach here, but if we do return empty string
    return ""


# Traceback (AttributeError)
[ch3ll@thecakeisalie ~]$ sudo salt '*02*' state.sls doesnotexist -ldebug

...
[DEBUG   ] LazyLoaded highstate.output
[ERROR   ] Data passed to highstate outputter is not a valid highstate return: {'ch3ll-minion02': ["No matching sls found for 'doesnotexist' in env 'base'"]}
[DEBUG   ] Traceback (most recent call last):
File "/home/ch3ll/git/salt/salt/output/__init__.py", line 39, in try_printout
return get_printout(out, opts)(data).rstrip()
AttributeError: 'NoneType' object has no attribute 'rstrip'

[DEBUG   ] LazyLoaded nested.output
ch3ll-minion02:
- No matching sls found for 'doesnotexist' in env 'base'
[DEBUG   ] jid 20160812160340754435 found all minions set(['ch3ll-minion02'])
ERROR: Minions returned with non-zero exit code

# Fixed code
def output(data):
    """
    The HighState Outputter is only meant to be used with the state.highstate
    function, or a function that returns highstate return data.
    """
    # If additional information is passed through via the "data" dictionary to
    # the highstate outputter, such as "outputter" or "retcode", discard it.
    # We only want the state data that was passed through, if it is wrapped up
    # in the "data" key, as the orchestrate runner does. See Issue #31330,
    # pull request #27838, and pull request #27175 for more information.
    if "data" in data:
        data = data.pop("data")

    ret = [_format_host(host, hostdata)[0] for host, hostdata in six.iteritems(data)]
    if ret:
        return "\n".join(ret)
    log.error(
        "Data passed to highstate outputter is not a valid highstate return: %s", data
    )
    # We should not reach here, but if we do return empty string
    return ""
# Buggy code
def refresh_db():
    """
    Force a repository refresh by calling ``zypper refresh --force``, return a dict::

        {'<database name>': Bool}

    CLI Example:

    .. code-block:: bash

        salt '*' pkg.refresh_db
    """
    ret = {}
    out = __zypper__.refreshable.call("refresh", "--force")

    for line in out.splitlines():
        if not line:
            continue
        if line.strip().startswith("Repository") and "'" in line:
            key = line.split("'")[1].strip()
            if "is up to date" in line:
                ret[key] = False
        elif line.strip().startswith("Building") and "'" in line:
            key = line.split("'")[1].strip()
            if "done" in line:
                ret[key] = True
    return ret


# Traceback (IndexError)
The minion function caused an exception: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/minion.py", line 1071, in _thread_return
return_data = func(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/salt/modules/zypper.py", line 893, in upgrade
refresh_db()
File "/usr/lib/python2.7/site-packages/salt/modules/zypper.py", line 703, in refresh_db
key = line.split('\'')[1].strip()
IndexError: list index out of range

# Fixed code
def refresh_db():
    """
    Force a repository refresh by calling ``zypper refresh --force``, return a dict::

        {'<database name>': Bool}

    CLI Example:

    .. code-block:: bash

        salt '*' pkg.refresh_db
    """
    ret = {}
    out = __zypper__.refreshable.call("refresh", "--force")

    for line in out.splitlines():
        if not line:
            continue
        if line.strip().startswith("Repository") and "'" in line:
            try:
                key = line.split("'")[1].strip()
                if "is up to date" in line:
                    ret[key] = False
            except IndexError:
                continue
        elif line.strip().startswith("Building") and "'" in line:
            key = line.split("'")[1].strip()
            if "done" in line:
                ret[key] = True
    return ret
# Buggy code
def post_dns_record(dns_domain, name, record_type, record_data):
    """
    Creates or updates a DNS record for the given name if the domain is managed with DO.
    """
    domain = query(method="domains", droplet_id=dns_domain)

    if domain:
        result = query(
            method="domains",
            droplet_id=dns_domain,
            command="records",
            args={"type": record_type, "name": name, "data": record_data},
            http_method="post",
        )
        return result

    return False


# Traceback (TypeError)
...
[DEBUG   ] Trying to execute 'digital_ocean.post_dns_record' with the following kwargs: {'record_type': 'A', 'name': 'pup02cristian', 'dns_domain': 'hybris.rocks', 'record_data': '159.203.39.245'}
[ERROR   ] There was an error running the function: post_dns_record() got an unexpected keyword argument 'call'
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/cloud/cli.py", line 274, in run
self.function_provider, self.function_name, kwargs
File "/usr/lib/python2.7/site-packages/salt/cloud/__init__.py", line 1593, in do_function
call='function', kwargs=kwargs
TypeError: post_dns_record() got an unexpected keyword argument 'call'

# Fixed code
def post_dns_record(**kwargs):
    """
    Creates a DNS record for the given name if the domain is managed with DO.
    """
    if "kwargs" in kwargs:  # flatten kwargs if called via salt-cloud -f
        f_kwargs = kwargs["kwargs"]
        del kwargs["kwargs"]
        kwargs.update(f_kwargs)
    mandatory_kwargs = ("dns_domain", "name", "record_type", "record_data")
    for i in mandatory_kwargs:
        if kwargs[i]:
            pass
        else:
            error = '{0}="{1}" ## all mandatory args must be provided: {2}'.format(
                i, kwargs[i], str(mandatory_kwargs)
            )
            raise salt.exceptions.SaltInvocationError(error)

    domain = query(method="domains", droplet_id=kwargs["dns_domain"])

    if domain:
        result = query(
            method="domains",
            droplet_id=kwargs["dns_domain"],
            command="records",
            args={
                "type": kwargs["record_type"],
                "name": kwargs["name"],
                "data": kwargs["record_data"],
            },
            http_method="post",
        )
        return result

    return False
# Buggy code
def get(key, default=""):
    """
    Attempt to retrieve the named value from grains, if the named value is not
    available return the passed default. The default return is an empty string.

    The value can also represent a value in a nested dict using a ":" delimiter
    for the dict. This means that if a dict in grains looks like this::

        {'pkg': {'apache': 'httpd'}}

    To retrieve the value associated with the apache key in the pkg dict this
    key can be passed::

        pkg:apache

    CLI Example:

    .. code-block:: bash

        salt '*' grains.get pkg:apache
    """
    return salt.utils.traverse_dict_and_list(__grains__, key, default)


# Traceback (TypeError)
[ERROR   ] Rendering exception occurred: Jinja error: get() got an unexpected keyword argument 'delimiter'
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/utils/templates.py", line 366, in render_jinja_tmpl
output = template.render(**decoded_context)
File "/usr/lib/python2.7/site-packages/jinja2/environment.py", line 989, in render
return self.environment.handle_exception(exc_info, True)
File "/usr/lib/python2.7/site-packages/jinja2/environment.py", line 754, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 23, in top-level template code
TypeError: get() got an unexpected keyword argument 'delimiter'

# Fixed code
def get(key, default="", delimiter=DEFAULT_TARGET_DELIM, ordered=True):
    """
    Attempt to retrieve the named value from grains, if the named value is not
    available return the passed default. The default return is an empty string.

    The value can also represent a value in a nested dict using a ":" delimiter
    for the dict. This means that if a dict in grains looks like this::

        {'pkg': {'apache': 'httpd'}}

    To retrieve the value associated with the apache key in the pkg dict this
    key can be passed::

        pkg:apache

    CLI Example:

    .. code-block:: bash

        salt '*' grains.get pkg:apache
    """
    if ordered is True:
        grains = __grains__
    else:
        grains = json.loads(json.dumps(__grains__))
    return salt.utils.traverse_dict_and_list(__grains__, key, default, delimiter)
# Buggy code
def __init__(opts):
    salt.utils.compat.pack_dunder(__name__)
    if HAS_LIBCLOUD:
        __utils__["libcloud.assign_funcs"](__name__, "dns", pack=__salt__)


# Traceback (KeyError)
[DEBUG   ] Error loading module.libcloud_dns: __init__ failed
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1362, in _load_module
module_init(self.opts)
File "/usr/lib/python2.7/site-packages/salt/modules/libcloud_dns.py", line 67, in __init__
__utils__['libcloud.assign_funcs'](__name__, 'dns', pack=__salt__)
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1066, in __getitem__
func = super(LazyLoader, self).__getitem__(item)
File "/usr/lib/python2.7/site-packages/salt/utils/lazy.py", line 101, in __getitem__
raise KeyError(key)
KeyError: 'libcloud.assign_funcs'

# Fixed code
def __init__(opts):
    salt.utils.compat.pack_dunder(__name__)
# Buggy code
def _get_driver(profile):
    config = __salt__["config.option"]("libcloud_dns")[profile]
    cls = get_driver(config["driver"])
    key = config.get("key")
    secret = config.get("secret", None)
    secure = config.get("secure", True)
    host = config.get("jost", None)
    port = config.get("port", None)
    return cls(key, secret, secure, host, port)


# Traceback (KeyError)
[DEBUG   ] Error loading module.libcloud_dns: __init__ failed
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1362, in _load_module
module_init(self.opts)
File "/usr/lib/python2.7/site-packages/salt/modules/libcloud_dns.py", line 67, in __init__
__utils__['libcloud.assign_funcs'](__name__, 'dns', pack=__salt__)
File "/usr/lib/python2.7/site-packages/salt/loader.py", line 1066, in __getitem__
func = super(LazyLoader, self).__getitem__(item)
File "/usr/lib/python2.7/site-packages/salt/utils/lazy.py", line 101, in __getitem__
raise KeyError(key)
KeyError: 'libcloud.assign_funcs'

# Fixed code
def _get_driver(profile):
    config = __salt__["config.option"]("libcloud_dns")[profile]
    cls = get_driver(config["driver"])
    key = config.get("key")
    secret = config.get("secret", None)
    secure = config.get("secure", True)
    host = config.get("host", None)
    port = config.get("port", None)
    return cls(key, secret, secure, host, port)
# Buggy code
def clean_old_jobs():
    """
    Clean out minions's return data for old jobs.
    """
    serv = _get_serv(ret=None)
    living_jids = set(serv.keys("load:*"))
    to_remove = []
    for ret_key in serv.keys("ret:*"):
        load_key = ret_key.replace("ret:", "load:", 1)
        if load_key not in living_jids:
            to_remove.append(ret_key)
    serv.delete(**to_remove)  # pylint: disable=E1134


# Traceback (TypeError)
[ERROR   ] An un-handled exception from the multiprocessing process 'Maintenance-11' was caught:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/utils/process.py", line 613, in _run
return self._original_run()
File "/usr/lib/python2.7/dist-packages/salt/master.py", line 236, in run
salt.daemons.masterapi.clean_old_jobs(self.opts)
File "/usr/lib/python2.7/dist-packages/salt/daemons/masterapi.py", line 187, in clean_old_jobs
mminion.returners[fstr]()
File "/usr/lib/python2.7/dist-packages/salt/returners/redis_return.py", line 215, in clean_old_jobs
serv.delete(**to_remove)  # pylint: disable=E1134
TypeError: delete() argument after ** must be a mapping, not list

# Fixed code
def clean_old_jobs():
    """
    Clean out minions's return data for old jobs.

    Normally, hset 'ret:<jid>' are saved with a TTL, and will eventually
    get cleaned by redis.But for jobs with some very late minion return, the
    corresponding hset's TTL will be refreshed to a too late timestamp, we'll
    do manually cleaning here.
    """
    serv = _get_serv(ret=None)
    living_jids = set(serv.keys("load:*"))
    to_remove = []
    for ret_key in serv.keys("ret:*"):
        load_key = ret_key.replace("ret:", "load:", 1)
        if load_key not in living_jids:
            to_remove.append(ret_key)
    serv.delete(*to_remove)
# Buggy code
def active(extended=False):
    """
    List the active mounts.

    CLI Example:

    .. code-block:: bash

        salt '*' mount.active
    """
    ret = {}
    if __grains__["os"] == "FreeBSD":
        _active_mounts_freebsd(ret)
    elif __grains__["os"] == "Solaris":
        _active_mounts_solaris(ret)
    elif __grains__["os"] == "OpenBSD":
        _active_mounts_openbsd(ret)
    elif __grains__["os"] in ["MacOS", "Darwin"]:
        _active_mounts_darwin(ret)
    else:
        if extended:
            try:
                _active_mountinfo(ret)
            except CommandExecutionError:
                _active_mounts(ret)
        else:
            _active_mounts(ret)
    return ret


# Traceback (IndexError)
[ERROR   ] Command 'mount -l' failed with return code: 1
[ERROR   ] stderr: mount: illegal option -- l
Usage:
mount [-v | -p]
mount [-F FSType] [-V] [current_options] [-o specific_options]
{special | mount_point}
mount [-F FSType] [-V] [current_options] [-o specific_options]
special mount_point
mount -a [-F FSType ] [-V] [current_options] [-o specific_options]
[mount_point ...]
[ERROR   ] An exception occurred in this state: Traceback (most recent call last):
File "salt/state.py", line 1379, in call
File "salt/states/mount.py", line 87, in mounted
File "salt/modules/mount.py", line 108, in active
File "salt/modules/mount.py", line 30, in _active_mountinfo
File "salt/modules/mount.py", line 25, in _list_mounts
IndexError: list index out of rang

# Fixed code
def active(extended=False):
    """
    List the active mounts.

    CLI Example:

    .. code-block:: bash

        salt '*' mount.active
    """
    ret = {}
    if __grains__["os"] == "FreeBSD":
        _active_mounts_freebsd(ret)
    elif __grains__["kernel"] == "SunOS":
        _active_mounts_solaris(ret)
    elif __grains__["os"] == "OpenBSD":
        _active_mounts_openbsd(ret)
    elif __grains__["os"] in ["MacOS", "Darwin"]:
        _active_mounts_darwin(ret)
    else:
        if extended:
            try:
                _active_mountinfo(ret)
            except CommandExecutionError:
                _active_mounts(ret)
        else:
            _active_mounts(ret)
    return ret
# Buggy code
def swapon(name, priority=None):
    """
    Activate a swap disk

    CLI Example:

    .. code-block:: bash

        salt '*' mount.swapon /root/swapfile
    """
    ret = {}
    on_ = swaps()
    if name in on_:
        ret["stats"] = on_[name]
        ret["new"] = False
        return ret
    cmd = "swapon {0}".format(name)
    if priority:
        cmd += " -p {0}".format(priority)
    __salt__["cmd.run"](cmd, python_shell=False)
    on_ = swaps()
    if name in on_:
        ret["stats"] = on_[name]
        ret["new"] = True
        return ret
    return ret


# Traceback (IndexError)
[ERROR   ] Command 'mount -l' failed with return code: 1
[ERROR   ] stderr: mount: illegal option -- l
Usage:
mount [-v | -p]
mount [-F FSType] [-V] [current_options] [-o specific_options]
{special | mount_point}
mount [-F FSType] [-V] [current_options] [-o specific_options]
special mount_point
mount -a [-F FSType ] [-V] [current_options] [-o specific_options]
[mount_point ...]
[ERROR   ] An exception occurred in this state: Traceback (most recent call last):
File "salt/state.py", line 1379, in call
File "salt/states/mount.py", line 87, in mounted
File "salt/modules/mount.py", line 108, in active
File "salt/modules/mount.py", line 30, in _active_mountinfo
File "salt/modules/mount.py", line 25, in _list_mounts
IndexError: list index out of rang

# Fixed code
def swapon(name, priority=None):
    """
    Activate a swap disk

    .. versionchanged:: 2016.3.2

    CLI Example:

    .. code-block:: bash

        salt '*' mount.swapon /root/swapfile
    """
    ret = {}
    on_ = swaps()
    if name in on_:
        ret["stats"] = on_[name]
        ret["new"] = False
        return ret

    if __grains__["kernel"] == "SunOS":
        if __grains__["virtual"] != "zone":
            __salt__["cmd.run"]("swap -a {0}".format(name), python_shell=False)
        else:
            return False
    else:
        cmd = "swapon {0}".format(name)
        if priority:
            cmd += " -p {0}".format(priority)
        __salt__["cmd.run"](cmd, python_shell=False)

    on_ = swaps()
    if name in on_:
        ret["stats"] = on_[name]
        ret["new"] = True
        return ret

    return ret
# Buggy code
def swapoff(name):
    """
    Deactivate a named swap mount

    CLI Example:

    .. code-block:: bash

        salt '*' mount.swapoff /root/swapfile
    """
    on_ = swaps()
    if name in on_:
        if __grains__["os"] != "OpenBSD":
            __salt__["cmd.run"]("swapoff {0}".format(name), python_shell=False)
        else:
            __salt__["cmd.run"]("swapctl -d {0}".format(name), python_shell=False)
        on_ = swaps()
        if name in on_:
            return False
        return True
    return None


# Traceback (IndexError)
[ERROR   ] Command 'mount -l' failed with return code: 1
[ERROR   ] stderr: mount: illegal option -- l
Usage:
mount [-v | -p]
mount [-F FSType] [-V] [current_options] [-o specific_options]
{special | mount_point}
mount [-F FSType] [-V] [current_options] [-o specific_options]
special mount_point
mount -a [-F FSType ] [-V] [current_options] [-o specific_options]
[mount_point ...]
[ERROR   ] An exception occurred in this state: Traceback (most recent call last):
File "salt/state.py", line 1379, in call
File "salt/states/mount.py", line 87, in mounted
File "salt/modules/mount.py", line 108, in active
File "salt/modules/mount.py", line 30, in _active_mountinfo
File "salt/modules/mount.py", line 25, in _list_mounts
IndexError: list index out of rang

# Fixed code
def swapoff(name):
    """
    Deactivate a named swap mount

    .. versionchanged:: 2016.3.2

    CLI Example:

    .. code-block:: bash

        salt '*' mount.swapoff /root/swapfile
    """
    on_ = swaps()
    if name in on_:
        if __grains__["kernel"] == "SunOS":
            if __grains__["virtual"] != "zone":
                __salt__["cmd.run"]("swap -a {0}".format(name), python_shell=False)
            else:
                return False
        elif __grains__["os"] != "OpenBSD":
            __salt__["cmd.run"]("swapoff {0}".format(name), python_shell=False)
        else:
            __salt__["cmd.run"]("swapctl -d {0}".format(name), python_shell=False)
        on_ = swaps()
        if name in on_:
            return False
        return True
    return None
# Buggy code
def exec_code_all(lang, code, cwd=None):
    """
    Pass in two strings, the first naming the executable language, aka -
    python2, python3, ruby, perl, lua, etc. the second string containing
    the code you wish to execute. All cmd artifacts (stdout, stderr, retcode, pid)
    will be returned.

    CLI Example:

    .. code-block:: bash

        salt '*' cmd.exec_code_all ruby 'puts "cheese"'
    """
    codefile = salt.utils.mkstemp()
    with salt.utils.fopen(codefile, "w+t") as fp_:
        fp_.write(code)
    cmd = [lang, codefile]
    ret = run_all(cmd, cwd=cwd, python_shell=False)
    os.remove(codefile)
    return ret


# Traceback (ValueError)
The minion function caused an exception: Traceback (most recent call last):
File "c:\salt\bin\lib\site-packages\salt\minion.py", line 1318, in _thread_return
return_data = executor.execute()
File "c:\salt\bin\lib\site-packages\salt\executors\direct_call.py", line 28, in execute
return self.func(*self.args, **self.kwargs)
File "c:\salt\bin\lib\site-packages\salt\modules\cmdmod.py", line 2296, in exec_code_all
with salt.utils.fopen(codefile, 'w+t') as fp_:
File "c:\salt\bin\lib\site-packages\salt\utils\__init__.py", line 1209, in fopen
fhandle = open(*args, **kwargs)
ValueError: Invalid mode ('w+tb')

# Fixed code
def exec_code_all(lang, code, cwd=None):
    """
    Pass in two strings, the first naming the executable language, aka -
    python2, python3, ruby, perl, lua, etc. the second string containing
    the code you wish to execute. All cmd artifacts (stdout, stderr, retcode, pid)
    will be returned.

    CLI Example:

    .. code-block:: bash

        salt '*' cmd.exec_code_all ruby 'puts "cheese"'
    """
    codefile = salt.utils.mkstemp()
    with salt.utils.fopen(codefile, "w+t", binary=False) as fp_:
        fp_.write(code)
    cmd = [lang, codefile]
    ret = run_all(cmd, cwd=cwd, python_shell=False)
    os.remove(codefile)
    return ret
# Buggy code
def __virtual__():
    """
    This function determines whether or not
    to make this cloud module available upon execution.
    Most often, it uses get_configured_provider() to determine
     if the necessary configuration has been set up.
    It may also check for necessary imports decide whether to load the module.
    In most cases, it will return a True or False value.
    If the name of the driver used does not match the filename,
     then that name should be returned instead of True.

    @return True|False|str
    """

    if not HAS_LIBS:
        return False

    if get_configured_provider() is False:
        return False

    # If the name of the driver used does not match the filename,
    #  then that name should be returned instead of True.
    # return __virtualname__
    return True


# Traceback (ImportError)
root@rallytime:~# salt-cloud -d rally-u14-1
[INFO    ] salt-cloud starting
[ERROR   ] Couldn't import VirtualBox API
Traceback (most recent call last):
File "/root/SaltStack/salt/salt/utils/virtualbox.py", line 25, in <module>
import vboxapi
ImportError: No module named vboxapi

# Fixed code
def __virtual__():
    """
    This function determines whether or not
    to make this cloud module available upon execution.
    Most often, it uses get_configured_provider() to determine
     if the necessary configuration has been set up.
    It may also check for necessary imports decide whether to load the module.
    In most cases, it will return a True or False value.
    If the name of the driver used does not match the filename,
     then that name should be returned instead of True.

    @return True|False|str
    """
    if not HAS_VBOX:
        return (
            False,
            "The virtualbox driver cannot be loaded: 'vboxapi' is not installed.",
        )

    if get_configured_provider() is False:
        return (
            False,
            "The virtualbox driver cannot be loaded: 'virtualbox' provider is not configured.",
        )

    # If the name of the driver used does not match the filename,
    #  then that name should be returned instead of True.
    return __virtualname__
# Buggy code
def node_state(id_):
    """
    Libcloud supported node states
    """
    states = {
        0: "RUNNING",
        1: "REBOOTING",
        2: "TERMINATED",
        3: "PENDING",
        4: "UNKNOWN",
        5: "STOPPED",
        6: "SUSPENDED",
        7: "ERROR",
        8: "PAUSED",
    }
    return states[id_]


# Traceback (KeyError)
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/cloud/__init__.py", line 2352, in run_parallel_map_providers_query
cloud.clouds[data['fun']]()
File "/usr/lib/python2.7/dist-packages/salt/cloud/libcloudfuncs.py", line 443, in list_nodes
'state': node_state(node.state)
File "/usr/lib/python2.7/dist-packages/salt/cloud/libcloudfuncs.py", line 67, in node_state
return states[id_]
KeyError: 'running'

# Fixed code
def node_state(id_):
    """
    Libcloud supported node states
    """
    states_int = {
        0: "RUNNING",
        1: "REBOOTING",
        2: "TERMINATED",
        3: "PENDING",
        4: "UNKNOWN",
        5: "STOPPED",
        6: "SUSPENDED",
        7: "ERROR",
        8: "PAUSED",
    }
    states_str = {
        "running": "RUNNING",
        "rebooting": "REBOOTING",
        "starting": "STARTING",
        "terminated": "TERMINATED",
        "pending": "PENDING",
        "unknown": "UNKNOWN",
        "stopping": "STOPPING",
        "stopped": "STOPPED",
        "suspended": "SUSPENDED",
        "error": "ERROR",
        "paused": "PAUSED",
        "reconfiguring": "RECONFIGURING",
    }
    return states_str[id_] if isinstance(id_, string_types) else states_int[id_]