# Buggy code
def create_valid_metainfo(metainfo):
    """
    Creates a valid metainfo dictionary by validating the elements and correcting when possible.

    :param metainfo: the metainfo that has to be validated
    :return: the original metainfo with corrected elements if possible
    :raise ValueError: if there is a faulty element which cannot be corrected.
    """
    metainfo_result = metainfo

    if not isinstance(metainfo, DictType):
        raise ValueError("metainfo not dict")

    # some .torrent files have a dht:// url in the announce field.
    if ("announce" in metainfo) and (
        not (
            is_valid_url(metainfo["announce"])
            or metainfo["announce"].startswith("dht:")
        )
    ):
        raise ValueError("announce URL bad")

    # common additional fields
    if "announce-list" in metainfo:
        al = metainfo["announce-list"]
        if not isinstance(al, ListType):
            raise ValueError("announce-list is not list, but " + repr(type(al)))
        if not all(isinstance(tier, ListType) for tier in al):
            raise ValueError("announce-list tier is not list")

    metainfo_result["nodes"] = validate_torrent_nodes(metainfo_result)
    metainfo_result["initial peers"] = validate_init_peers(metainfo)
    metainfo_result["url-list"] = validate_url_list(metainfo)
    metainfo_result["httpseeds"] = validate_http_seeds(metainfo)
    metainfo_result["info"] = validate_torrent_info(metainfo)

    # remove elements if None i.e. not valid.
    for key in {"httpseeds", "url-list", "nodes", "initial peers"}:
        if not metainfo[key]:
            del metainfo[key]

    if not ("announce" in metainfo or "nodes" in metainfo):
        # disabling this check, modifying metainfo to allow for ill-formatted torrents
        metainfo_result["nodes"] = []

    return dict(
        (key, val)
        for key, val in metainfo_result.iteritems()
        if val or (metainfo[key] and metainfo[key] == val)
    )


# Traceback (ValueError)
/home/tribler/tribler/Tribler/Core/Modules/restapi/downloads_endpoint.py:295:render_PUT
/home/tribler/tribler/Tribler/Core/Session.py:313:start_download_from_uri
/home/tribler/tribler/Tribler/Core/Libtorrent/LibtorrentMgr.py:571:start_download_from_uri
/home/tribler/tribler/Tribler/Core/Libtorrent/LibtorrentMgr.py:618:start_download
/home/tribler/tribler/Tribler/Core/TorrentDef.py:105:load_from_memory
/home/tribler/tribler/Tribler/Core/TorrentDef.py:119:_create
/home/tribler/tribler/Tribler/Core/Utilities/utilities.py:44:validTorrentFile
]
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/twisted/web/server.py", line 190, in process
self.render(resrc)
File "/usr/lib/python2.7/dist-packages/twisted/web/server.py", line 241, in render
body = resrc.render(self)
File "/usr/lib/python2.7/dist-packages/twisted/web/resource.py", line 250, in render
return m(request)
File "/home/tribler/tribler/Tribler/Core/Modules/restapi/downloads_endpoint.py", line 295, in render_PUT
unquote_plus(unicode(parameters['uri'][0], 'utf-8')), download_config)
File "/home/tribler/tribler/Tribler/Core/Session.py", line 313, in start_download_from_uri
return self.lm.ltmgr.start_download_from_uri(uri, dconfig=dconfig)
File "/home/tribler/tribler/Tribler/Core/Libtorrent/LibtorrentMgr.py", line 571, in start_download_from_uri
return succeed(self.start_download(torrentfilename=argument, dconfig=dconfig))
File "/home/tribler/tribler/Tribler/Core/Libtorrent/LibtorrentMgr.py", line 618, in start_download
tdef = TorrentDef.load_from_memory(torrent_data)
File "/home/tribler/tribler/Tribler/Core/TorrentDef.py", line 105, in load_from_memory
return TorrentDef._create(data)
File "/home/tribler/tribler/Tribler/Core/TorrentDef.py", line 119, in _create
validTorrentFile(metainfo)
File "/home/tribler/tribler/Tribler/Core/Utilities/utilities.py", line 44, in validTorrentFile
raise ValueError('announce URL bad')
ValueError: announce URL bad

# Fixed code
def create_valid_metainfo(metainfo):
    """
    Creates a valid metainfo dictionary by validating the elements and correcting when possible.

    :param metainfo: the metainfo that has to be validated
    :return: the original metainfo with corrected elements if possible
    :raise ValueError: if there is a faulty element which cannot be corrected.
    """
    metainfo_result = metainfo

    if not isinstance(metainfo, DictType):
        raise ValueError("metainfo not dict")

    # some .torrent files have a dht:// url in the announce field.
    if ("announce" in metainfo and metainfo["announce"]) and (
        not (
            is_valid_url(metainfo["announce"])
            or metainfo["announce"].startswith("dht:")
        )
    ):
        raise ValueError("announce URL bad")

    # common additional fields
    if "announce-list" in metainfo:
        al = metainfo["announce-list"]
        if not isinstance(al, ListType):
            raise ValueError("announce-list is not list, but " + repr(type(al)))
        if not all(isinstance(tier, ListType) for tier in al):
            raise ValueError("announce-list tier is not list")

    metainfo_result["nodes"] = validate_torrent_nodes(metainfo_result)
    metainfo_result["initial peers"] = validate_init_peers(metainfo)
    metainfo_result["url-list"] = validate_url_list(metainfo)
    metainfo_result["httpseeds"] = validate_http_seeds(metainfo)
    metainfo_result["info"] = validate_torrent_info(metainfo)

    # remove elements if None i.e. not valid.
    for key in {"httpseeds", "url-list", "nodes", "initial peers"}:
        if not metainfo[key]:
            del metainfo[key]

    if not ("announce" in metainfo or "nodes" in metainfo):
        # disabling this check, modifying metainfo to allow for ill-formatted torrents
        metainfo_result["nodes"] = []

    return dict(
        (key, val)
        for key, val in metainfo_result.iteritems()
        if val or (metainfo[key] and metainfo[key] == val)
    )