gurudesh/pytracebugs huggingface dataset:
# Buggy code
def advanced_settings():
    """Track the existence of <cleanonupdate>true</cleanonupdate>
    It is incompatible with plugin paths.
    """
    if settings("useDirectPaths") != "0":
        return

    path = xbmc.translatePath("special://profile/")
    file = os.path.join(path, "advancedsettings.xml")

    try:
        xml = etree.parse(file).getroot()
    except Exception:
        return

    video = xml.find("videolibrary")

    if video is not None:
        cleanonupdate = video.find("cleanonupdate")

        if cleanonupdate is not None and cleanonupdate.text == "true":
            LOG.warning("cleanonupdate disabled")
            video.remove(cleanonupdate)

            tree = etree.ElementTree(xml)
            tree.write(path)

            dialog("ok", "{jellyfin}", translate(33097))
            xbmc.executebuiltin("RestartApp")

            return True


# Traceback (IOError)
2021-02-14 03:15:59.646 T:1455395040  NOTICE: JELLYFIN.library -> ERROR::jellyfin_kodi/library.py:319 [Errno 21] Is a directory: u'/home/osmc/.kodi/userdata/'
Traceback (most recent call last):
File "jellyfin_kodi/library.py", line 315, in startup
sync.libraries()
File "jellyfin_kodi/full_sync.py", line 100, in libraries
if not xmls.advanced_settings() and self.sync['Libraries']:
File "jellyfin_kodi/helper/xmls.py", line 130, in advanced_settings
tree.write(path)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 802, in write
file = open(file_or_filename, "wb")
IOError: [Errno 21] Is a directory: u'/home/osmc/.kodi/userdata/'

# Fixed code
def advanced_settings():
    """Track the existence of <cleanonupdate>true</cleanonupdate>
    It is incompatible with plugin paths.
    """
    if settings("useDirectPaths") != "0":
        return

    path = xbmc.translatePath("special://profile/")
    file = os.path.join(path, "advancedsettings.xml")

    try:
        xml = etree.parse(file).getroot()
    except Exception:
        return

    video = xml.find("videolibrary")

    if video is not None:
        cleanonupdate = video.find("cleanonupdate")

        if cleanonupdate is not None and cleanonupdate.text == "true":
            LOG.warning("cleanonupdate disabled")
            video.remove(cleanonupdate)

            tree = etree.ElementTree(xml)
            tree.write(file)

            dialog("ok", "{jellyfin}", translate(33097))
            xbmc.executebuiltin("RestartApp")

            return True
# Buggy code
def run(self):
    with Database("jellyfin") as jellyfindb:
        database = jellyfin_db.JellyfinDatabase(jellyfindb.cursor)

        while True:
            try:
                item_id = self.queue.get(timeout=1)
            except Queue.Empty:
                break

            try:
                media = database.get_media_by_id(item_id)
                self.output[media].put({"Id": item_id, "Type": media})
            except Exception as error:
                LOG.exception(error)

                items = database.get_media_by_parent_id(item_id)

                if not items:
                    LOG.info(
                        "Could not find media %s in the jellyfin database.", item_id
                    )
                else:
                    for item in items:
                        self.output[item[1]].put({"Id": item[0], "Type": item[1]})

            self.queue.task_done()

            if window("jellyfin_should_stop.bool"):
                break

    LOG.info("--<[ q:sort/%s ]", id(self))
    self.is_done = True


# Traceback (TypeError)
2020-04-08 20:06:13.443 T:140039749101312  NOTICE: JELLYFIN.objects.music -> ERROR::jellyfin_kodi/objects/music.py:392 'NoneType' object has no attribute '__getitem__'
Traceback (most recent call last):
File "jellyfin_kodi/objects/music.py", line 390, in song_artist_link
temp_obj['ArtistId'] = self.jellyfin_db.get_item_by_id(*values(temp_obj, QUEM.get_item_obj))[0]
TypeError: 'NoneType' object has no attribute '__getitem__'

# Fixed code
def run(self):
    with Database("jellyfin") as jellyfindb:
        database = jellyfin_db.JellyfinDatabase(jellyfindb.cursor)

        while True:
            try:
                item_id = self.queue.get(timeout=1)
            except Queue.Empty:
                break

            try:
                media = database.get_media_by_id(item_id)
                if media:
                    self.output[media].put({"Id": item_id, "Type": media})
                else:
                    items = database.get_media_by_parent_id(item_id)

                    if not items:
                        LOG.info(
                            "Could not find media %s in the jellyfin database.", item_id
                        )
                    else:
                        for item in items:
                            self.output[item[1]].put({"Id": item[0], "Type": item[1]})
            except Exception as error:
                LOG.exception(error)

            self.queue.task_done()

            if window("jellyfin_should_stop.bool"):
                break

    LOG.info("--<[ q:sort/%s ]", id(self))
    self.is_done = True
# Buggy code
def format(self, record):
    if record.pathname:
        record.pathname = ensure_text(record.pathname, sys.getfilesystemencoding())

    self._gen_rel_path(record)

    # Call the original formatter class to do the grunt work
    result = logging.Formatter.format(self, record)

    return result


# Traceback (TypeError)
ERROR: EXCEPTION Thrown (PythonToCppException) : -->Python callback/script returned the following error<--
- NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!
Error Type: <type 'exceptions.TypeError'>
Error Contents: decode() argument 1 must be string, not None
Traceback (most recent call last):
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/service.py", line 21, in <module>
from entrypoint import Service  # noqa: F402
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/entrypoint/__init__.py", line 13, in <module>
from .default import Events
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/entrypoint/default.py", line 14, in <module>
from database import reset, get_sync, Database, jellyfin_db, get_credentials
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/database/__init__.py", line 16, in <module>
from objects import obj
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/objects/__init__.py", line 13, in <module>
Objects().mapping()
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/objects/obj.py", line 37, in mapping
file_dir = os.path.dirname(ensure_text(__file__, sys.getfilesystemencoding()))
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/script.module.six/lib/six.py", line 915, in ensure_text
return s.decode(encoding, errors)
TypeError: decode() argument 1 must be string, not None
-->End of Python script error report<--

# Fixed code
def format(self, record):
    if record.pathname:
        record.pathname = ensure_text(record.pathname, get_filesystem_encoding())

    self._gen_rel_path(record)

    # Call the original formatter class to do the grunt work
    result = logging.Formatter.format(self, record)

    return result
# Buggy code
def formatException(self, exc_info):
    _pluginpath_real = os.path.realpath(__pluginpath__)
    res = []

    for o in traceback.format_exception(*exc_info):
        o = ensure_text(o, sys.getfilesystemencoding())

        if o.startswith('  File "'):
            # If this split can't handle your file names, you should seriously consider renaming your files.
            fn = o.split('  File "', 2)[1].split('", line ', 1)[0]
            rfn = os.path.realpath(fn)
            if rfn.startswith(_pluginpath_real):
                o = o.replace(fn, os.path.relpath(rfn, _pluginpath_real))

        res.append(o)

    return "".join(res)


# Traceback (TypeError)
ERROR: EXCEPTION Thrown (PythonToCppException) : -->Python callback/script returned the following error<--
- NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!
Error Type: <type 'exceptions.TypeError'>
Error Contents: decode() argument 1 must be string, not None
Traceback (most recent call last):
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/service.py", line 21, in <module>
from entrypoint import Service  # noqa: F402
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/entrypoint/__init__.py", line 13, in <module>
from .default import Events
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/entrypoint/default.py", line 14, in <module>
from database import reset, get_sync, Database, jellyfin_db, get_credentials
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/database/__init__.py", line 16, in <module>
from objects import obj
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/objects/__init__.py", line 13, in <module>
Objects().mapping()
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/objects/obj.py", line 37, in mapping
file_dir = os.path.dirname(ensure_text(__file__, sys.getfilesystemencoding()))
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/script.module.six/lib/six.py", line 915, in ensure_text
return s.decode(encoding, errors)
TypeError: decode() argument 1 must be string, not None
-->End of Python script error report<--

# Fixed code
def formatException(self, exc_info):
    _pluginpath_real = os.path.realpath(__pluginpath__)
    res = []

    for o in traceback.format_exception(*exc_info):
        o = ensure_text(o, get_filesystem_encoding())

        if o.startswith('  File "'):
            # If this split can't handle your file names, you should seriously consider renaming your files.
            fn = o.split('  File "', 2)[1].split('", line ', 1)[0]
            rfn = os.path.realpath(fn)
            if rfn.startswith(_pluginpath_real):
                o = o.replace(fn, os.path.relpath(rfn, _pluginpath_real))

        res.append(o)

    return "".join(res)
# Buggy code
def mapping(self):
    """Load objects mapping."""
    file_dir = os.path.dirname(ensure_text(__file__, sys.getfilesystemencoding()))

    with open(os.path.join(file_dir, "obj_map.json")) as infile:
        self.objects = json.load(infile)


# Traceback (TypeError)
ERROR: EXCEPTION Thrown (PythonToCppException) : -->Python callback/script returned the following error<--
- NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!
Error Type: <type 'exceptions.TypeError'>
Error Contents: decode() argument 1 must be string, not None
Traceback (most recent call last):
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/service.py", line 21, in <module>
from entrypoint import Service  # noqa: F402
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/entrypoint/__init__.py", line 13, in <module>
from .default import Events
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/entrypoint/default.py", line 14, in <module>
from database import reset, get_sync, Database, jellyfin_db, get_credentials
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/database/__init__.py", line 16, in <module>
from objects import obj
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/objects/__init__.py", line 13, in <module>
Objects().mapping()
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/plugin.video.jellyfin/jellyfin_kodi/objects/obj.py", line 37, in mapping
file_dir = os.path.dirname(ensure_text(__file__, sys.getfilesystemencoding()))
File "/storage/emulated/0/Android/data/org.xbmc.kodi/files/.kodi/addons/script.module.six/lib/six.py", line 915, in ensure_text
return s.decode(encoding, errors)
TypeError: decode() argument 1 must be string, not None
-->End of Python script error report<--

# Fixed code
def mapping(self):
    """Load objects mapping."""
    file_dir = os.path.dirname(ensure_text(__file__, get_filesystem_encoding()))

    with open(os.path.join(file_dir, "obj_map.json")) as infile:
        self.objects = json.load(infile)
# Buggy code
def format(self, record):
    self._gen_rel_path(record)

    # Call the original formatter class to do the grunt work
    result = logging.Formatter.format(self, record)

    return result


# Traceback (UnicodeDecodeError)
- NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!
Error Type: <type 'exceptions.UnicodeDecodeError'>
Error Contents: 'ascii' codec can't decode byte 0xcc in position 7: ordinal not in range(128)
Traceback (most recent call last):
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\service.py", line 22, in <module>
from entrypoint import Service  # noqa: F402
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\entrypoint\__init__.py", line 10, in <module>
from helper import loghandler
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\helper\loghandler.py", line 14, in <module>
import database
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\database\__init__.py", line 16, in <module>
from objects import obj
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\objects\__init__.py", line 13, in <module>
Objects().mapping()
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\objects\obj.py", line 35, in mapping
with open(os.path.join(os.path.dirname(__file__), 'obj_map.json')) as infile:
File "C:\Program Files\Kodi\system\python\Lib\ntpath.py", line 85, in join
result_path = result_path + p_path
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcc in position 7: ordinal not in range(128)
-->End of Python script error report<-- -->

# Fixed code
def format(self, record):
    if record.pathname:
        record.pathname = ensure_text(record.pathname, sys.getfilesystemencoding())

    self._gen_rel_path(record)

    # Call the original formatter class to do the grunt work
    result = logging.Formatter.format(self, record)

    return result
# Buggy code
def formatException(self, exc_info):
    _pluginpath_real = os.path.realpath(__pluginpath__)
    res = []

    for o in traceback.format_exception(*exc_info):
        if o.startswith('  File "'):
            # If this split can't handle your file names, you should seriously consider renaming your files.
            fn = o.split('  File "', 2)[1].split('", line ', 1)[0]
            rfn = os.path.realpath(fn)
            if rfn.startswith(_pluginpath_real):
                o = o.replace(fn, os.path.relpath(rfn, _pluginpath_real))

        res.append(o)

    return "".join(res)


# Traceback (UnicodeDecodeError)
- NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!
Error Type: <type 'exceptions.UnicodeDecodeError'>
Error Contents: 'ascii' codec can't decode byte 0xcc in position 7: ordinal not in range(128)
Traceback (most recent call last):
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\service.py", line 22, in <module>
from entrypoint import Service  # noqa: F402
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\entrypoint\__init__.py", line 10, in <module>
from helper import loghandler
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\helper\loghandler.py", line 14, in <module>
import database
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\database\__init__.py", line 16, in <module>
from objects import obj
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\objects\__init__.py", line 13, in <module>
Objects().mapping()
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\objects\obj.py", line 35, in mapping
with open(os.path.join(os.path.dirname(__file__), 'obj_map.json')) as infile:
File "C:\Program Files\Kodi\system\python\Lib\ntpath.py", line 85, in join
result_path = result_path + p_path
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcc in position 7: ordinal not in range(128)
-->End of Python script error report<-- -->

# Fixed code
def formatException(self, exc_info):
    _pluginpath_real = os.path.realpath(__pluginpath__)
    res = []

    for o in traceback.format_exception(*exc_info):
        o = ensure_text(o, sys.getfilesystemencoding())

        if o.startswith('  File "'):
            # If this split can't handle your file names, you should seriously consider renaming your files.
            fn = o.split('  File "', 2)[1].split('", line ', 1)[0]
            rfn = os.path.realpath(fn)
            if rfn.startswith(_pluginpath_real):
                o = o.replace(fn, os.path.relpath(rfn, _pluginpath_real))

        res.append(o)

    return "".join(res)
# Buggy code
def mapping(self):
    """Load objects mapping."""
    with open(os.path.join(os.path.dirname(__file__), "obj_map.json")) as infile:
        self.objects = json.load(infile)


# Traceback (UnicodeDecodeError)
- NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!
Error Type: <type 'exceptions.UnicodeDecodeError'>
Error Contents: 'ascii' codec can't decode byte 0xcc in position 7: ordinal not in range(128)
Traceback (most recent call last):
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\service.py", line 22, in <module>
from entrypoint import Service  # noqa: F402
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\entrypoint\__init__.py", line 10, in <module>
from helper import loghandler
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\helper\loghandler.py", line 14, in <module>
import database
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\database\__init__.py", line 16, in <module>
from objects import obj
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\objects\__init__.py", line 13, in <module>
Objects().mapping()
File "C:\Users\��\AppData\Roaming\Kodi\addons\plugin.video.jellyfin\jellyfin_kodi\objects\obj.py", line 35, in mapping
with open(os.path.join(os.path.dirname(__file__), 'obj_map.json')) as infile:
File "C:\Program Files\Kodi\system\python\Lib\ntpath.py", line 85, in join
result_path = result_path + p_path
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcc in position 7: ordinal not in range(128)
-->End of Python script error report<-- -->

# Fixed code
def mapping(self):
    """Load objects mapping."""
    file_dir = os.path.dirname(ensure_text(__file__, sys.getfilesystemencoding()))

    with open(os.path.join(file_dir, "obj_map.json")) as infile:
        self.objects = json.load(infile)
# Buggy code
def get_root(app, request=None):
    """Return a tuple composed of ``(root, closer)`` when provided a
    :term:`router` instance as the ``app`` argument.  The ``root``
    returned is the application root object.  The ``closer`` returned
    is a callable (accepting no arguments) that should be called when
    your scripting application is finished using the root.

    ``request`` is passed to the :app:`Pyramid` application root
    factory to compute the root. If ``request`` is None, a default
    will be constructed using the registry's :term:`Request Factory`
    via the :meth:`pyramid.interfaces.IRequestFactory.blank` method.
    """
    registry = app.registry
    if request is None:
        request = _make_request("/", registry)
    threadlocals = {"registry": registry, "request": request}
    app.threadlocal_manager.push(threadlocals)

    def closer(request=request):  # keep request alive via this function default
        app.threadlocal_manager.pop()

    root = app.root_factory(request)
    return root, closer


# Traceback (AttributeError)
# bin/pshell mything/development.ini
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help" for more information.

Environment:
app          The WSGI application.
registry     Active Pyramid registry.
request      Active request object.
root         Root of the default resource tree.
root_factory Default root factory used to create `root`.

from pyramid.scripting import get_root
x = get_root(app)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/shane/src/pyramidtest/eggs/pyramid-1.9.1-py3.5.egg/pyramid/scripting.py", line 30, in get_root
app.threadlocal_manager.push(threadlocals)
AttributeError: 'Router' object has no attribute 'threadlocal_manager'


# Fixed code
def get_root(app, request=None):
    """Return a tuple composed of ``(root, closer)`` when provided a
    :term:`router` instance as the ``app`` argument.  The ``root``
    returned is the application root object.  The ``closer`` returned
    is a callable (accepting no arguments) that should be called when
    your scripting application is finished using the root.

    ``request`` is passed to the :app:`Pyramid` application root
    factory to compute the root. If ``request`` is None, a default
    will be constructed using the registry's :term:`Request Factory`
    via the :meth:`pyramid.interfaces.IRequestFactory.blank` method.
    """
    registry = app.registry
    if request is None:
        request = _make_request("/", registry)
    request.registry = registry
    ctx = RequestContext(request)
    ctx.begin()

    def closer():
        ctx.end()

    root = app.root_factory(request)
    return root, closer
# Buggy code
def closer(request=request):  # keep request alive via this function default
    app.threadlocal_manager.pop()


# Traceback (AttributeError)
# bin/pshell mything/development.ini
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help" for more information.

Environment:
app          The WSGI application.
registry     Active Pyramid registry.
request      Active request object.
root         Root of the default resource tree.
root_factory Default root factory used to create `root`.

from pyramid.scripting import get_root
x = get_root(app)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/shane/src/pyramidtest/eggs/pyramid-1.9.1-py3.5.egg/pyramid/scripting.py", line 30, in get_root
app.threadlocal_manager.push(threadlocals)
AttributeError: 'Router' object has no attribute 'threadlocal_manager'


# Fixed code
def closer():
    ctx.end()
# Buggy code
def closer():
    threadlocal_manager.pop()


# Traceback (AttributeError)
# bin/pshell mything/development.ini
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help" for more information.

Environment:
app          The WSGI application.
registry     Active Pyramid registry.
request      Active request object.
root         Root of the default resource tree.
root_factory Default root factory used to create `root`.

from pyramid.scripting import get_root
x = get_root(app)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/shane/src/pyramidtest/eggs/pyramid-1.9.1-py3.5.egg/pyramid/scripting.py", line 30, in get_root
app.threadlocal_manager.push(threadlocals)
AttributeError: 'Router' object has no attribute 'threadlocal_manager'


# Fixed code
def closer():
    ctx.end()
# Buggy code
def __init__(
    self,
    secret,
    cookie_name="auth_tkt",
    secure=False,
    include_ip=False,
    timeout=None,
    reissue_time=None,
    max_age=None,
    http_only=False,
    path="/",
    wild_domain=True,
    hashalg="md5",
    parent_domain=False,
    domain=None,
):
    serializer = _SimpleSerializer()

    self.cookie_profile = CookieProfile(
        cookie_name=cookie_name,
        secure=secure,
        max_age=max_age,
        httponly=http_only,
        path=path,
        serializer=serializer,
    )

    self.secret = secret
    self.cookie_name = cookie_name
    self.secure = secure
    self.include_ip = include_ip
    self.timeout = timeout if timeout is None else int(timeout)
    self.reissue_time = reissue_time if reissue_time is None else int(reissue_time)
    self.max_age = max_age if max_age is None else int(max_age)
    self.wild_domain = wild_domain
    self.parent_domain = parent_domain
    self.domain = domain
    self.hashalg = hashalg


# Traceback (ImportError)
import pyramid.viewderivers
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../lib/python2.7/site-packages/pyramid/viewderivers.py", line 31, in <module>
from pyramid.config.util import (
File ".../lib/python2.7/site-packages/pyramid/config/__init__.py", line 78, in <module>
from pyramid.config.views import ViewsConfiguratorMixin
File ".../lib/python2.7/site-packages/pyramid/config/views.py", line 80, in <module>
from pyramid.viewderivers import (
ImportError: cannot import name INGRESS

# Fixed code
def __init__(
    self,
    secret,
    cookie_name="auth_tkt",
    secure=False,
    include_ip=False,
    timeout=None,
    reissue_time=None,
    max_age=None,
    http_only=False,
    path="/",
    wild_domain=True,
    hashalg="md5",
    parent_domain=False,
    domain=None,
):
    serializer = SimpleSerializer()

    self.cookie_profile = CookieProfile(
        cookie_name=cookie_name,
        secure=secure,
        max_age=max_age,
        httponly=http_only,
        path=path,
        serializer=serializer,
    )

    self.secret = secret
    self.cookie_name = cookie_name
    self.secure = secure
    self.include_ip = include_ip
    self.timeout = timeout if timeout is None else int(timeout)
    self.reissue_time = reissue_time if reissue_time is None else int(reissue_time)
    self.max_age = max_age if max_age is None else int(max_age)
    self.wild_domain = wild_domain
    self.parent_domain = parent_domain
    self.domain = domain
    self.hashalg = hashalg
# Buggy code
def _apply_view_derivers(self, info):
    d = pyramid.viewderivers

    # These derivers are not really derivers and so have fixed order
    outer_derivers = [
        ("attr_wrapped_view", d.attr_wrapped_view),
        ("predicated_view", d.predicated_view),
    ]

    view = info.original_view
    derivers = self.registry.getUtility(IViewDerivers)
    for name, deriver in reversed(outer_derivers + derivers.sorted()):
        view = wraps_view(deriver)(view, info)
    return view


# Traceback (ImportError)
import pyramid.viewderivers
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../lib/python2.7/site-packages/pyramid/viewderivers.py", line 31, in <module>
from pyramid.config.util import (
File ".../lib/python2.7/site-packages/pyramid/config/__init__.py", line 78, in <module>
from pyramid.config.views import ViewsConfiguratorMixin
File ".../lib/python2.7/site-packages/pyramid/config/views.py", line 80, in <module>
from pyramid.viewderivers import (
ImportError: cannot import name INGRESS

# Fixed code
def _apply_view_derivers(self, info):
    # These derivers are not really derivers and so have fixed order
    outer_derivers = [
        ("attr_wrapped_view", attr_wrapped_view),
        ("predicated_view", predicated_view),
    ]

    view = info.original_view
    derivers = self.registry.getUtility(IViewDerivers)
    for name, deriver in reversed(outer_derivers + derivers.sorted()):
        view = wraps_view(deriver)(view, info)
    return view
# Buggy code
def __init__(
    self,
    cookie_name="csrf_token",
    secure=False,
    httponly=False,
    domain=None,
    max_age=None,
    path="/",
):
    serializer = _SimpleSerializer()
    self.cookie_profile = CookieProfile(
        cookie_name=cookie_name,
        secure=secure,
        max_age=max_age,
        httponly=httponly,
        path=path,
        domains=[domain],
        serializer=serializer,
    )
    self.cookie_name = cookie_name


# Traceback (ImportError)
import pyramid.viewderivers
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../lib/python2.7/site-packages/pyramid/viewderivers.py", line 31, in <module>
from pyramid.config.util import (
File ".../lib/python2.7/site-packages/pyramid/config/__init__.py", line 78, in <module>
from pyramid.config.views import ViewsConfiguratorMixin
File ".../lib/python2.7/site-packages/pyramid/config/views.py", line 80, in <module>
from pyramid.viewderivers import (
ImportError: cannot import name INGRESS

# Fixed code
def __init__(
    self,
    cookie_name="csrf_token",
    secure=False,
    httponly=False,
    domain=None,
    max_age=None,
    path="/",
):
    serializer = SimpleSerializer()
    self.cookie_profile = CookieProfile(
        cookie_name=cookie_name,
        secure=secure,
        max_age=max_age,
        httponly=httponly,
        path=path,
        domains=[domain],
        serializer=serializer,
    )
    self.cookie_name = cookie_name
# Buggy code
def __init__(self, val, config):
    if is_nonstr_iter(val):
        self.val = set(val)
    else:
        self.val = set((val,))


# Traceback (ImportError)
import pyramid.viewderivers
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../lib/python2.7/site-packages/pyramid/viewderivers.py", line 31, in <module>
from pyramid.config.util import (
File ".../lib/python2.7/site-packages/pyramid/config/__init__.py", line 78, in <module>
from pyramid.config.views import ViewsConfiguratorMixin
File ".../lib/python2.7/site-packages/pyramid/config/views.py", line 80, in <module>
from pyramid.viewderivers import (
ImportError: cannot import name INGRESS

# Fixed code
def __init__(self, predicate):
    self.predicate = predicate
# Buggy code
def text(self):
    return "effective_principals = %s" % sorted(list(self.val))


# Traceback (ImportError)
import pyramid.viewderivers
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../lib/python2.7/site-packages/pyramid/viewderivers.py", line 31, in <module>
from pyramid.config.util import (
File ".../lib/python2.7/site-packages/pyramid/config/__init__.py", line 78, in <module>
from pyramid.config.views import ViewsConfiguratorMixin
File ".../lib/python2.7/site-packages/pyramid/config/views.py", line 80, in <module>
from pyramid.viewderivers import (
ImportError: cannot import name INGRESS

# Fixed code
def text(self):
    return self._notted_text(self.predicate.text())
# Buggy code
def __call__(self, context, request):
    req_principals = request.effective_principals
    if is_nonstr_iter(req_principals):
        rpset = set(req_principals)
        if self.val.issubset(rpset):
            return True
    return False


# Traceback (ImportError)
import pyramid.viewderivers
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../lib/python2.7/site-packages/pyramid/viewderivers.py", line 31, in <module>
from pyramid.config.util import (
File ".../lib/python2.7/site-packages/pyramid/config/__init__.py", line 78, in <module>
from pyramid.config.views import ViewsConfiguratorMixin
File ".../lib/python2.7/site-packages/pyramid/config/views.py", line 80, in <module>
from pyramid.viewderivers import (
ImportError: cannot import name INGRESS

# Fixed code
def __call__(self, context, request):
    result = self.predicate(context, request)
    phash = self.phash()
    if phash:
        result = not result
    return result
# Buggy code
def phash(self):
    # This isn't actually a predicate, it's just a infodict modifier that
    # injects ``traverse`` into the matchdict.  As a result, we don't
    # need to update the hash.
    return ""


# Traceback (ImportError)
import pyramid.viewderivers
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../lib/python2.7/site-packages/pyramid/viewderivers.py", line 31, in <module>
from pyramid.config.util import (
File ".../lib/python2.7/site-packages/pyramid/config/__init__.py", line 78, in <module>
from pyramid.config.views import ViewsConfiguratorMixin
File ".../lib/python2.7/site-packages/pyramid/config/views.py", line 80, in <module>
from pyramid.viewderivers import (
ImportError: cannot import name INGRESS

# Fixed code
def phash(self):
    return self._notted_text(self.predicate.phash())
# Buggy code
def __init__(self, file, line, function, src):
    self.file = file
    self.line = line
    self.function = function
    self.src = src


# Traceback (ImportError)
import pyramid.viewderivers
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".../lib/python2.7/site-packages/pyramid/viewderivers.py", line 31, in <module>
from pyramid.config.util import (
File ".../lib/python2.7/site-packages/pyramid/config/__init__.py", line 78, in <module>
from pyramid.config.views import ViewsConfiguratorMixin
File ".../lib/python2.7/site-packages/pyramid/config/views.py", line 80, in <module>
from pyramid.viewderivers import (
ImportError: cannot import name INGRESS

# Fixed code
def __init__(
    self,
    default_before=LAST,
    default_after=None,
    first=FIRST,
    last=LAST,
):
    self.names = []
    self.req_before = set()
    self.req_after = set()
    self.name2before = {}
    self.name2after = {}
    self.name2val = {}
    self.order = []
    self.default_before = default_before
    self.default_after = default_after
    self.first = first
    self.last = last
# Buggy code
def orderandpos(v):
    n, v = v
    if not isinstance(v, dict):
        # old-style tuple action
        v = expand_action(*v)
    return (v["order"] or 0, n)


# Traceback (pyramid.exceptions.ConfigurationError)
Traceback (most recent call last):
File "demo2.py", line 27, in <module>
config.commit()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 654, in commit
self.action_state.execute_actions(introspector=self.introspector)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1158, in execute_actions
list(pending_actions) +
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1121, in resume
for a, b in zip_longest(actions, executed_actions):
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1255, in resolveConflicts
discriminator = undefer(action['discriminator'])
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 271, in undefer
v = v.resolve()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 263, in resolve
return self.value
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/decorator.py", line 45, in __get__
val = self.wrapped(inst)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 260, in value
return self.func()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/views.py", line 810, in discrim_func
self._check_view_options(**dvals)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/views.py", line 1070, in _check_view_options
raise ConfigurationError('Unknown view options: %s' % (kw,))
pyramid.exceptions.ConfigurationError: Unknown view options: {'noop': True}

# Fixed code
def orderandpos(v):
    n, v = v
    return (v["order"] or 0, n)
# Buggy code
def orderonly(v):
    n, v = v
    if not isinstance(v, dict):
        # old-style tuple action
        v = expand_action(*v)
    return v["order"] or 0


# Traceback (pyramid.exceptions.ConfigurationError)
Traceback (most recent call last):
File "demo2.py", line 27, in <module>
config.commit()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 654, in commit
self.action_state.execute_actions(introspector=self.introspector)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1158, in execute_actions
list(pending_actions) +
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1121, in resume
for a, b in zip_longest(actions, executed_actions):
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1255, in resolveConflicts
discriminator = undefer(action['discriminator'])
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 271, in undefer
v = v.resolve()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 263, in resolve
return self.value
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/decorator.py", line 45, in __get__
val = self.wrapped(inst)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 260, in value
return self.func()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/views.py", line 810, in discrim_func
self._check_view_options(**dvals)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/views.py", line 1070, in _check_view_options
raise ConfigurationError('Unknown view options: %s' % (kw,))
pyramid.exceptions.ConfigurationError: Unknown view options: {'noop': True}

# Fixed code
def orderonly(v):
    n, v = v
    return v["order"] or 0
# Buggy code
def bypath(ainfo):
    path, order, i = ainfo[2]["includepath"], ainfo[0], ainfo[1]
    return path, order, i


# Traceback (pyramid.exceptions.ConfigurationError)
Traceback (most recent call last):
File "demo2.py", line 27, in <module>
config.commit()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 654, in commit
self.action_state.execute_actions(introspector=self.introspector)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1158, in execute_actions
list(pending_actions) +
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1121, in resume
for a, b in zip_longest(actions, executed_actions):
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1255, in resolveConflicts
discriminator = undefer(action['discriminator'])
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 271, in undefer
v = v.resolve()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 263, in resolve
return self.value
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/decorator.py", line 45, in __get__
val = self.wrapped(inst)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 260, in value
return self.func()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/views.py", line 810, in discrim_func
self._check_view_options(**dvals)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/views.py", line 1070, in _check_view_options
raise ConfigurationError('Unknown view options: %s' % (kw,))
pyramid.exceptions.ConfigurationError: Unknown view options: {'noop': True}

# Fixed code
def bypath(ainfo):
    path, i = ainfo[1]["includepath"], ainfo[0]
    return path, order, i
# Buggy code
def __init__(self):
    # NB "actions" is an API, dep'd upon by pyramid_zcml's load_zcml func
    self.actions = []
    self._seen_files = set()


# Traceback (pyramid.exceptions.ConfigurationError)
Traceback (most recent call last):
File "demo2.py", line 27, in <module>
config.commit()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 654, in commit
self.action_state.execute_actions(introspector=self.introspector)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1158, in execute_actions
list(pending_actions) +
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1121, in resume
for a, b in zip_longest(actions, executed_actions):
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/__init__.py", line 1255, in resolveConflicts
discriminator = undefer(action['discriminator'])
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 271, in undefer
v = v.resolve()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 263, in resolve
return self.value
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/decorator.py", line 45, in __get__
val = self.wrapped(inst)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/registry.py", line 260, in value
return self.func()
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/views.py", line 810, in discrim_func
self._check_view_options(**dvals)
File "/Users/dstufft/.virtualenvs/tmp-afd03b5a92f8d7f/lib/python3.5/site-packages/pyramid/config/views.py", line 1070, in _check_view_options
raise ConfigurationError('Unknown view options: %s' % (kw,))
pyramid.exceptions.ConfigurationError: Unknown view options: {'noop': True}

# Fixed code
def __init__(self):
    # keep a set of resolved discriminators to test against to ensure
    # that a new action does not conflict with something already executed
    self.resolved_ainfos = {}

    # actions left over from a previous iteration
    self.remaining_actions = []

    # after executing an action we memoize its order to avoid any new
    # actions sending us backward
    self.min_order = None

    # unique tracks the index of the action so we need it to increase
    # monotonically across invocations to resolveConflicts
    self.start = 0
# Buggy code
def __init__(self, backend, rsa_cdata, evp_pkey):
    self._backend = backend
    self._rsa_cdata = rsa_cdata
    self._evp_pkey = evp_pkey

    n = self._backend._ffi.new("BIGNUM **")
    self._backend._lib.RSA_get0_key(
        self._rsa_cdata,
        n,
        self._backend._ffi.NULL,
        self._backend._ffi.NULL,
    )
    self._backend.openssl_assert(n[0] != self._backend._ffi.NULL)
    self._key_size = self._backend._lib.BN_num_bits(n[0])


# Traceback (AssertionError)
Traceback (most recent call last):
File "bad_crypto.py", line 5, in <module>
jwt.encode({}, my_key, algorithm='RS256')
File "/Users/matt/.pyenv/versions/apidev/lib/python3.5/site-packages/jwt/api_jwt.py", line 65, in encode
json_payload, key, algorithm, headers, json_encoder
File "/Users/matt/.pyenv/versions/apidev/lib/python3.5/site-packages/jwt/api_jws.py", line 114, in encode
signature = alg_obj.sign(signing_input, key)
File "/Users/matt/.pyenv/versions/apidev/lib/python3.5/site-packages/jwt/algorithms.py", line 313, in sign
return key.sign(msg, padding.PKCS1v15(), self.hash_alg())
File "/Users/matt/.pyenv/versions/apidev/lib/python3.5/site-packages/cryptography/hazmat/backends/openssl/rsa.py", line 415, in sign
return _rsa_sig_sign(self._backend, padding, algorithm, self, data)
File "/Users/matt/.pyenv/versions/apidev/lib/python3.5/site-packages/cryptography/hazmat/backends/openssl/rsa.py", line 239, in _rsa_sig_sign
assert errors[0].lib == backend._lib.ERR_LIB_RSA
AssertionError

# Fixed code
def __init__(self, backend, rsa_cdata, evp_pkey):
    res = backend._lib.RSA_check_key(rsa_cdata)
    if res != 1:
        errors = backend._consume_errors_with_text()
        raise ValueError("Invalid private key", errors)

    self._backend = backend
    self._rsa_cdata = rsa_cdata
    self._evp_pkey = evp_pkey

    n = self._backend._ffi.new("BIGNUM **")
    self._backend._lib.RSA_get0_key(
        self._rsa_cdata,
        n,
        self._backend._ffi.NULL,
        self._backend._ffi.NULL,
    )
    self._backend.openssl_assert(n[0] != self._backend._ffi.NULL)
    self._key_size = self._backend._lib.BN_num_bits(n[0])
# Buggy code
def __init__(self, oid, value):
    if not isinstance(oid, ObjectIdentifier):
        raise TypeError("oid argument must be an ObjectIdentifier instance.")

    if not isinstance(value, six.text_type):
        raise TypeError("value argument must be a text type.")

    if oid == NameOID.COUNTRY_NAME and len(value.encode("utf8")) != 2:
        raise ValueError("Country name must be a 2 character country code")

    self._oid = oid
    self._value = value


# Traceback (cryptography.exceptions.InternalError)
Traceback (most recent call last):
File "openssl_error.py", line 19, in <module>
cert = builder.sign(private_key, hashes.SHA256(), default_backend())
File "/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/x509/base.py", line 564, in sign
return backend.create_x509_certificate(self, private_key, algorithm)
File "/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 746, in create_x509_certificate
x509_cert, _encode_name_gc(self, builder._subject_name)
File "/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/encode_asn1.py", line 103, in _encode_name_gc
subject = _encode_name(backend, attributes)
File "/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/encode_asn1.py", line 97, in _encode_name
backend.openssl_assert(res == 1)
File "/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 107, in openssl_assert
return binding._openssl_assert(self._lib, ok)
File "/home/ubuntu/.local/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/binding.py", line 75, in _openssl_assert
errors_with_text
cryptography.exceptions.InternalError: Unknown OpenSSL error. This error is commonly encountered when another library is not cleaning up the OpenSSL error stack. If you are using cryptography with another library that uses OpenSSL try disabling it before reporting a bug. Otherwise please file an issue at https://github.com/pyca/cryptography/issues with information on how to reproduce this. ([_OpenSSLErrorWithText(code=218603672L, lib=13, func=122, reason=152, reason_text='error:0D07A098:asn1 encoding routines:ASN1_mbstring_ncopy:string too short')])

# Fixed code
def __init__(self, oid, value):
    if not isinstance(oid, ObjectIdentifier):
        raise TypeError("oid argument must be an ObjectIdentifier instance.")

    if not isinstance(value, six.text_type):
        raise TypeError("value argument must be a text type.")

    if oid == NameOID.COUNTRY_NAME and len(value.encode("utf8")) != 2:
        raise ValueError("Country name must be a 2 character country code")

    if len(value) == 0:
        raise ValueError("Value cannot be an empty string")

    self._oid = oid
    self._value = value