gurudesh/pytracebugs huggingface dataset:
# Buggy code
def validate_configuration(config, schema):
    """Validate data from configuration.yaml.

    We use voluptuous to validate the data obtained from the
    configuration file with the schema declared above. Voluptuous
    will raise a 'voluptuous.MultipleInvalid' exception if the data
    passed doesn't match the schema.

    This is a helper function so we don't need to do much with it other than
    initialize voluptuous.Schema and attempt to validate the data. The function
    'load_config_file' located on 'opsdroid.configuration.__init__' will handle
    the case when the exception is raised.

    Args:
        config: a yaml stream obtained from opening configuration.yaml
        schema (dict): the rules used to validate against data

    """
    validate = Schema(schema, extra=ALLOW_EXTRA)
    try:
        validate(config)
    except MultipleInvalid as error:
        _LOGGER.critical(
            _("Configuration for %s failed validation! %s - '%s'."),
            config.get("name", "basic opsdroid rules"),
            error.msg.capitalize(),
            error.path[0],
        )
        sys.exit(1)


# Traceback (AttributeError)
hemmo_1  | DEBUG opsdroid.parsers.crontab: Running crontab skills at Thu Jan 30 08:29:00 2020.
hemmo_1  | ERROR opsdroid.core: Exception when running skill 'cve'.
hemmo_1  | Traceback (most recent call last):
hemmo_1  |   File "/usr/local/lib/python3.7/site-packages/opsdroid/core.py", line 397, in run_skill
hemmo_1  |     return await skill(event)
hemmo_1  |   File "/root/.local/share/opsdroid/opsdroid-modules/skill/cve/__init__.py", line 142, in schedule
hemmo_1  |     await message.respond(f"Searching CVEs with queries: {', '.join(queries)}")
hemmo_1  |   File "/usr/local/lib/python3.7/site-packages/opsdroid/events.py", line 263, in respond
hemmo_1  |     "thinking-delay" in self.connector.configuration
hemmo_1  | AttributeError: 'NoneType' object has no attribute 'configuration'

# Fixed code
def validate_configuration(config, schema):
    """Validate data from configuration.yaml.

    We use voluptuous to validate the data obtained from the
    configuration file with the schema declared above. Voluptuous
    will raise a 'voluptuous.MultipleInvalid' exception if the data
    passed doesn't match the schema.

    This is a helper function so we don't need to do much with it other than
    initialize voluptuous.Schema and attempt to validate the data. The function
    'load_config_file' located on 'opsdroid.configuration.__init__' will handle
    the case when the exception is raised.

    Args:
        config: a yaml stream obtained from opening configuration.yaml
        schema (dict): the rules used to validate against data

    """
    validate = Schema(schema, extra=ALLOW_EXTRA)
    try:
        return validate(config)
    except MultipleInvalid as error:
        _LOGGER.critical(
            _("Configuration for %s failed validation! %s - '%s'."),
            config.get("name", "basic opsdroid rules"),
            error.msg.capitalize(),
            error.path[0],
        )
        sys.exit(1)
# Buggy code
def _load_intents(config):
    intent_file = os.path.join(config["install_path"], "intents.md")
    if os.path.isfile(intent_file):
        with open(intent_file, "r") as intent_file_handle:
            intents = intent_file_handle.read()
            return intents
    else:
        return None


# Traceback (AttributeError)
INFO opsdroid.parsers.rasanlu: Starting Rasa NLU training.
DEBUG asyncio: Using selector: KqueueSelector
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/Users/IOBreaker/Developments/Bots/opsdroid/opsdroid/__main__.py", line 206, in <module>
init()
File "/Users/IOBreaker/Developments/Bots/opsdroid/opsdroid/__main__.py", line 203, in init
main()
File "/Users/IOBreaker/Developments/Bots/opsdroid/venv/lib/python3.7/site-packages/click/core.py", line 764, in __call__
return self.main(*args, **kwargs)
File "/Users/IOBreaker/Developments/Bots/opsdroid/venv/lib/python3.7/site-packages/click/core.py", line 717, in main
rv = self.invoke(ctx)
File "/Users/IOBreaker/Developments/Bots/opsdroid/venv/lib/python3.7/site-packages/click/core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/IOBreaker/Developments/Bots/opsdroid/venv/lib/python3.7/site-packages/click/core.py", line 555, in invoke
return callback(*args, **kwargs)
File "/Users/IOBreaker/Developments/Bots/opsdroid/opsdroid/__main__.py", line 196, in main
opsdroid.load()
File "/Users/IOBreaker/Developments/Bots/opsdroid/opsdroid/core.py", line 152, in load
self.train_parsers(self.modules["skills"])
File "/Users/IOBreaker/Developments/Bots/opsdroid/opsdroid/core.py", line 270, in train_parsers
asyncio.gather(*tasks, loop=self.eventloop))
File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 568, in run_until_complete
return future.result()
File "/Users/IOBreaker/Developments/Bots/opsdroid/opsdroid/parsers/rasanlu.py", line 87, in train_rasanlu
intents = await _get_all_intents(skills)
File "/Users/IOBreaker/Developments/Bots/opsdroid/opsdroid/parsers/rasanlu.py", line 19, in _get_all_intents
matchers = [matcher for skill in skills for matcher in skill.matchers]
File "/Users/IOBreaker/Developments/Bots/opsdroid/opsdroid/parsers/rasanlu.py", line 19, in <listcomp>
matchers = [matcher for skill in skills for matcher in skill.matchers]
AttributeError: 'dict' object has no attribute 'matchers'

# Fixed code
def _load_intents(config):
    intent_file = os.path.join(config["install_path"], "intents.yml")
    if os.path.isfile(intent_file):
        with open(intent_file, "r") as intent_file_handle:
            intents = intent_file_handle.read()
            return intents
    else:
        return None
# Buggy code
async def parse(self, message):
    """Parse a string against all skills."""
    self.stats["messages_parsed"] = self.stats["messages_parsed"] + 1
    tasks = []
    if message is not None and message.text.strip() != "":
        _LOGGER.debug(_("Parsing input: %s"), message.text)

        tasks.append(self.eventloop.create_task(parse_always(self, message)))

        unconstrained_skills = await self._constrain_skills(self.skills, message)
        ranked_skills = await self.get_ranked_skills(unconstrained_skills, message)
        if ranked_skills:
            tasks.append(
                self.eventloop.create_task(
                    self.run_skill(
                        ranked_skills[0]["skill"], ranked_skills[0]["config"], message
                    )
                )
            )

    return tasks


# Traceback (AttributeError)
DEBUG opsdroid.connector.websocket: Starting Websocket connector
INFO opsdroid.core: Opsdroid is now running, press ctrl+c to exit.
INFO opsdroid.web: Started web server on http://127.0.0.1:8080
INFO aiohttp.access: 127.0.0.1 [07/Mar/2019:14:35:22 +0000] "POST /connector/websocket HTTP/1.1" 200 220 "-" "-"
DEBUG opsdroid.connector.websocket: User connected to 3d406d62-40e6-11e9-bd4a-4865ee166460
ERROR aiohttp.server: Error handling request
Traceback (most recent call last):
File "/usr/lib/python3.7/site-packages/aiohttp/web_protocol.py", line 418, in start
resp = await task
File "/usr/lib/python3.7/site-packages/aiohttp/web_app.py", line 458, in _handle
resp = await handler(request)
File "/home/hicham/Developments/Bots/opsdroid/opsdroid-master/opsdroid/connector/websocket/__init__.py", line 89, in websocket_handler
await self.opsdroid.parse(message)
File "/home/hicham/Developments/Bots/opsdroid/opsdroid-master/opsdroid/core.py", line 435, in parse
if message is not None and message.text.strip() != "":
AttributeError: 'NoneType' object has no attribute 'strip'
ERROR aiohttp.server: Unhandled exception

# Fixed code
async def parse(self, message):
    """Parse a string against all skills."""
    self.stats["messages_parsed"] = self.stats["messages_parsed"] + 1
    tasks = []
    if message is not None:
        if str(message.text).strip():
            _LOGGER.debug(_("Parsing input: %s"), message.text)

            tasks.append(self.eventloop.create_task(parse_always(self, message)))

            unconstrained_skills = await self._constrain_skills(self.skills, message)
            ranked_skills = await self.get_ranked_skills(unconstrained_skills, message)
            if ranked_skills:
                tasks.append(
                    self.eventloop.create_task(
                        self.run_skill(
                            ranked_skills[0]["skill"],
                            ranked_skills[0]["config"],
                            message,
                        )
                    )
                )

    return tasks
# Buggy code
async def listen(self):
    """Listen for and parse new messages.

    The bot will always listen to all opened chat windows,
    as long as opsdroid is running. Since anyone can start
    a new chat with the bot is recommended that a list of
    users to be whitelisted be provided in config.yaml.

    The method will sleep asynchronously at the end of
    every loop. The time can either be specified in the
    config.yaml with the param update-interval - this
    defaults to 1 second.

    Args:
        opsdroid (OpsDroid): An instance of opsdroid core.

    """
    while self.listening:
        await self._get_messages()

        await asyncio.sleep(self.update_interval)


# Traceback (KeyError)
DEBUG opsdroid.connector.telegram: {'update_id': 539000683, 'channel_post': {'message_id': 15, 'chat': {'id': -1002528219498, 'title': 'vLab', 'type': 'channel'}, 'date': 1550000742, 'text': 'hi'}}
DEBUG opsdroid.connector.telegram: {'update_id': 539026984, 'message': {'message_id': 53, 'from': {'id': 452280388, 'is_bot': False, 'first_name': 'IOBreaker', 'language_code': 'en'}, 'chat': {'id': 452266388, 'first_name': 'IOBreaker', 'type': 'private'}, 'date': 1550000813, 'text': '/start', 'entities': [{'offset': 0, 'length': 6, 'type': 'bot_command'}]}}
DEBUG asyncio: Using selector: EpollSelector
Traceback (most recent call last):
File "/usr/bin/opsdroid", line 11, in <module>
load_entry_point('opsdroid==0.14.1', 'console_scripts', 'opsdroid')()
File "/usr/lib64/python3.6/site-packages/click/core.py", line 764, in __call__
return self.main(*args, **kwargs)
File "/usr/lib64/python3.6/site-packages/click/core.py", line 717, in main
rv = self.invoke(ctx)
File "/usr/lib64/python3.6/site-packages/click/core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/lib64/python3.6/site-packages/click/core.py", line 555, in invoke
return callback(*args, **kwargs)
File "/usr/lib/python3.6/site-packages/opsdroid/__main__.py", line 197, in main
opsdroid.run()
File "/usr/lib/python3.6/site-packages/opsdroid/core.py", line 135, in run
self.eventloop.run_until_complete(asyncio.gather(*pending))
File "/usr/lib64/python3.6/asyncio/base_events.py", line 473, in run_until_complete
return future.result()
File "/usr/lib/python3.6/site-packages/opsdroid/connector/telegram/__init__.py", line 163, in listen
await self._get_messages()
File "/usr/lib/python3.6/site-packages/opsdroid/connector/telegram/__init__.py", line 143, in _get_messages
await self._parse_message(json)
File "/usr/lib/python3.6/site-packages/opsdroid/connector/telegram/__init__.py", line 99, in _parse_message
user = result["message"]["from"]["username"]
KeyError: 'username'

# Fixed code
async def listen(self):
    """Listen method of the connector.

    Every connector has to implement the listen method. When an
    infinite loop is running, it becomes hard to cancel this task.
    So we are creating a task and set it on a variable so we can
    cancel the task.

    """
    message_getter = self.loop.create_task(self.get_messages_loop())
    await self._closing.wait()
    message_getter.cancel()
# Buggy code
def import_module(config):
    """Import module namespace as variable and return it."""
    try:
        module = importlib.import_module(config["module_path"] + "." + config["name"])
        _LOGGER.debug("Loaded %s: %s", config["type"], config["module_path"])
        return module

    except ImportError as error:
        _LOGGER.debug(
            "Failed to load %s.%s.  ERROR: %s",
            config["module_path"],
            config["name"],
            error,
        )

    try:
        module = importlib.import_module(config["module_path"])
        _LOGGER.debug("Loaded %s: %s", config["type"], config["module_path"])
        return module

    except ImportError as error:
        _LOGGER.error("Failed to load %s: %s", config["type"], config["module_path"])
        _LOGGER.debug(error)

    return None


# Traceback (ImportError)
Traceback (most recent call last):
File "/Users/jacob/.pyenv/versions/3.5.1/lib/python3.5/runpy.py", line 170, in _run_module_as_main
"__main__", mod_spec)
File "/Users/jacob/.pyenv/versions/3.5.1/lib/python3.5/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/__main__.py", line 134, in <module>
main()
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/__main__.py", line 129, in main
opsdroid.start_loop()
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/core.py", line 123, in start_loop
self.loader.load_modules_from_config(self.config)
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/loader.py", line 206, in load_modules_from_config
self._reload_modules(skills)
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/loader.py", line 128, in _reload_modules
importlib.reload(module["module"])
File "/Users/jacob/.pyenv/versions/3.5.1/lib/python3.5/importlib/__init__.py", line 147, in reload
raise ImportError(msg.format(name), name=name)
ImportError: module opsdroid-modules.skill.hello not in sys.modules

# Fixed code
def import_module(config):
    """Import module namespace as variable and return it."""
    # Check if the module can be imported and proceed with import

    # Proceed only if config.name is specified
    # and parent module can be imported
    if config["name"] and importlib.util.find_spec(config["module_path"]):
        module_spec = importlib.util.find_spec(
            config["module_path"] + "." + config["name"]
        )
        if module_spec:
            module = Loader.import_module_from_spec(module_spec)
            _LOGGER.debug("Loaded %s: %s", config["type"], config["module_path"])
            return module

    module_spec = importlib.util.find_spec(config["module_path"])
    if module_spec:
        module = Loader.import_module_from_spec(module_spec)
        _LOGGER.debug("Loaded %s: %s", config["type"], config["module_path"])
        return module

    _LOGGER.error("Failed to load %s: %s", config["type"], config["module_path"])

    return None
# Buggy code
def _reload_modules(self, modules):
    for module in modules:
        self.current_import_config = module["config"]
        importlib.reload(module["module"])


# Traceback (ImportError)
Traceback (most recent call last):
File "/Users/jacob/.pyenv/versions/3.5.1/lib/python3.5/runpy.py", line 170, in _run_module_as_main
"__main__", mod_spec)
File "/Users/jacob/.pyenv/versions/3.5.1/lib/python3.5/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/__main__.py", line 134, in <module>
main()
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/__main__.py", line 129, in main
opsdroid.start_loop()
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/core.py", line 123, in start_loop
self.loader.load_modules_from_config(self.config)
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/loader.py", line 206, in load_modules_from_config
self._reload_modules(skills)
File "/Users/jacob/Projects/opsdroid/opsdroid/opsdroid/loader.py", line 128, in _reload_modules
importlib.reload(module["module"])
File "/Users/jacob/.pyenv/versions/3.5.1/lib/python3.5/importlib/__init__.py", line 147, in reload
raise ImportError(msg.format(name), name=name)
ImportError: module opsdroid-modules.skill.hello not in sys.modules

# Fixed code
def _reload_modules(self, modules):
    """Reload modules in namespace. Queries sys.modules."""
    for module in modules:
        self.current_import_config = module["config"]
        if isinstance(module["module"], ModuleType):
            module_name = module["module"].__name__
            if sys.modules.get(module_name):
                _LOGGER.debug("Reloading module %s", module_name)
                importlib.reload(sys.modules[module_name])
# Buggy code
def _createDetachedPanel(self, *args, **kwargs):
    panel = _DetachedPanel(self, *args, **kwargs)
    panel.__removeOnCloseConnection = panel.closedSignal().connect(
        lambda w: w.parent()._removeDetachedPanel(w)
    )

    scriptWindow = self.ancestor(GafferUI.ScriptWindow)
    if scriptWindow:
        panel.setTitle(scriptWindow.getTitle())
        weakSetTitle = Gaffer.WeakMethod(panel.setTitle)
        scriptWindow.titleChangedSignal().connect(
            lambda w, t: weakSetTitle(t), scoped=False
        )

    self.__detachedPanels.append(panel)
    return panel


# Traceback (ReferenceError)
Traceback (most recent call last):
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/Gaffer/WeakMethod.py", line 67, in __call__
return m( *args, **kwArgs )
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/ScriptWindow.py", line 226, in __scriptPlugChanged
self.__updateTitle()
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/ScriptWindow.py", line 221, in __updateTitle
w._setTitle( "Gaffer : %s%s%s%s" % ( f, ro, u, d ) )
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/ScriptWindow.py", line 101, in _setTitle
self.__titleChangedSignal( self, title )
IECore.Exception: Traceback (most recent call last):
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/CompoundEditor.py", line 130, in <lambda>
scriptWindow.titleChangedSignal().connect( lambda w, t : weakSetTitle( t ), scoped = False )
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/Gaffer/WeakMethod.py", line 64, in __call__
raise ReferenceError( "Instance referenced by WeakMethod %s.%s() no longer exists" % ( self.__method.__module__, self.__method.__name__ ) )
ReferenceError: Instance referenced by WeakMethod GafferUI.Window.setTitle() no longer exists

# Fixed code
def _createDetachedPanel(self, *args, **kwargs):
    panel = _DetachedPanel(self, *args, **kwargs)
    panel.__removeOnCloseConnection = panel.closedSignal().connect(
        lambda w: w.parent()._removeDetachedPanel(w)
    )

    scriptWindow = self.ancestor(GafferUI.ScriptWindow)
    if scriptWindow:
        panel.setTitle(scriptWindow.getTitle())
        weakSetTitle = Gaffer.WeakMethod(panel.setTitle)
        panel.__titleChangedConnection = scriptWindow.titleChangedSignal().connect(
            lambda w, t: weakSetTitle(t)
        )

    self.__detachedPanels.append(panel)
    return panel
# Buggy code
def _removeDetachedPanel(self, panel):
    self.__detachedPanels.remove(panel)
    panel.__removeOnCloseConnection = None
    panel._applyVisibility()


# Traceback (ReferenceError)
Traceback (most recent call last):
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/Gaffer/WeakMethod.py", line 67, in __call__
return m( *args, **kwArgs )
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/ScriptWindow.py", line 226, in __scriptPlugChanged
self.__updateTitle()
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/ScriptWindow.py", line 221, in __updateTitle
w._setTitle( "Gaffer : %s%s%s%s" % ( f, ro, u, d ) )
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/ScriptWindow.py", line 101, in _setTitle
self.__titleChangedSignal( self, title )
IECore.Exception: Traceback (most recent call last):
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/CompoundEditor.py", line 130, in <lambda>
scriptWindow.titleChangedSignal().connect( lambda w, t : weakSetTitle( t ), scoped = False )
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/Gaffer/WeakMethod.py", line 64, in __call__
raise ReferenceError( "Instance referenced by WeakMethod %s.%s() no longer exists" % ( self.__method.__module__, self.__method.__name__ ) )
ReferenceError: Instance referenced by WeakMethod GafferUI.Window.setTitle() no longer exists

# Fixed code
def _removeDetachedPanel(self, panel):
    self.__detachedPanels.remove(panel)
    panel.__removeOnCloseConnection = None
    panel.__titleChangedConnection = None
    panel._applyVisibility()
# Buggy code
def __setTabDragConstraints(self, qTabBar, event):
    # We need to work out some min/max X coordinates (in the tab bars local
    # space) such that when the user drags left/rigth the left/right edges
    # of the tab never leave the TabBar.
    tabRect = qTabBar.tabRect(qTabBar.currentIndex())
    self.__dragMinX = event.pos().x() - tabRect.x()  # cursorToTabLeftEdge
    cursorToTabRightEdge = tabRect.x() + tabRect.width() - event.pos().x()
    self.__dragMaxX = qTabBar.width() - cursorToTabRightEdge


# Traceback (ReferenceError)
Traceback (most recent call last):
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/Gaffer/WeakMethod.py", line 67, in __call__
return m( *args, **kwArgs )
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/ScriptWindow.py", line 226, in __scriptPlugChanged
self.__updateTitle()
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/ScriptWindow.py", line 221, in __updateTitle
w._setTitle( "Gaffer : %s%s%s%s" % ( f, ro, u, d ) )
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/ScriptWindow.py", line 101, in _setTitle
self.__titleChangedSignal( self, title )
IECore.Exception: Traceback (most recent call last):
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/GafferUI/CompoundEditor.py", line 130, in <lambda>
scriptWindow.titleChangedSignal().connect( lambda w, t : weakSetTitle( t ), scoped = False )
File "/software/apps/gaffer/0.54.0.0-preview/cent7.x86_64/cortex/10/gaffer/python/Gaffer/WeakMethod.py", line 64, in __call__
raise ReferenceError( "Instance referenced by WeakMethod %s.%s() no longer exists" % ( self.__method.__module__, self.__method.__name__ ) )
ReferenceError: Instance referenced by WeakMethod GafferUI.Window.setTitle() no longer exists

# Fixed code
def __setTabDragConstraints(self, qTabBar, event):
    # We need to work out some min/max X coordinates (in the tab bars local
    # space) such that when the user drags left/right the left/right edges
    # of the tab never leave the TabBar.
    barRect = qTabBar.rect()
    tabRect = qTabBar.tabRect(qTabBar.tabAt(event.pos()))
    mouseX = event.pos().x()

    self.__dragMinX = mouseX - tabRect.x()  # cursorToTabLeftEdge

    tabRightEdge = tabRect.x() + tabRect.width()
    if tabRightEdge > barRect.width():
        # Already as far right as it can go
        self.__dragMaxX = mouseX
    else:
        cursorToTabRightEdge = tabRightEdge - mouseX
        self.__dragMaxX = barRect.width() - cursorToTabRightEdge
# Buggy code
def acquire(jobPool):
    assert isinstance(jobPool, Gaffer.LocalDispatcher.JobPool)

    window = getattr(jobPool, "_window", None)
    if window:
        return window

    window = _LocalJobsWindow(jobPool)
    jobPool._window = window

    return window


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/Gaffer/WeakMethod.py", line 67, in __call__
return m( *args, **kwArgs )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/Button.py", line 138, in __clicked
self.clickedSignal()( self )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/Gaffer/WeakMethod.py", line 67, in __call__
return m( *args, **kwArgs )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/DispatcherUI.py", line 239, in __executeClicked
_showDispatcherWindow( [ self.getPlug().node() ] )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/DispatcherUI.py", line 450, in _showDispatcherWindow
window = __dispatcherWindow( nodes[0].scriptNode() )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/DispatcherUI.py", line 444, in __dispatcherWindow
scriptWindow.addChildWindow( window )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/Window.py", line 171, in addChildWindow
oldParent = childWindow.parent()
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/Widget.py", line 290, in parent
parentWidget = q.parentWidget()
RuntimeError: underlying C/C++ object has been deleted

# Fixed code
def acquire(jobPool):
    assert isinstance(jobPool, Gaffer.LocalDispatcher.JobPool)

    window = getattr(jobPool, "_window", None)
    if window is not None and window():
        return window()

    window = _LocalJobsWindow(jobPool)
    jobPool._window = weakref.ref(window)

    return window
# Buggy code
def __showLocalDispatcherWindow(menu):
    window = _LocalJobsWindow.acquire(Gaffer.LocalDispatcher.defaultJobPool())
    window.setVisible(True)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/Gaffer/WeakMethod.py", line 67, in __call__
return m( *args, **kwArgs )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/Button.py", line 138, in __clicked
self.clickedSignal()( self )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/Gaffer/WeakMethod.py", line 67, in __call__
return m( *args, **kwArgs )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/DispatcherUI.py", line 239, in __executeClicked
_showDispatcherWindow( [ self.getPlug().node() ] )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/DispatcherUI.py", line 450, in _showDispatcherWindow
window = __dispatcherWindow( nodes[0].scriptNode() )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/DispatcherUI.py", line 444, in __dispatcherWindow
scriptWindow.addChildWindow( window )
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/Window.py", line 171, in addChildWindow
oldParent = childWindow.parent()
File "/home/andrewk/apps/gaffer/0.3.0.0dev/cent6.x86_64/cortex/9/gaffer/python/GafferUI/Widget.py", line 290, in parent
parentWidget = q.parentWidget()
RuntimeError: underlying C/C++ object has been deleted

# Fixed code
def __showLocalDispatcherWindow(menu):
    window = _LocalJobsWindow.acquire(Gaffer.LocalDispatcher.defaultJobPool())
    scriptWindow = menu.ancestor(GafferUI.ScriptWindow)
    scriptWindow.addChildWindow(window)
    window.setVisible(True)
# Buggy code
def __init__(self, plug, **kw):
    GafferUI.CompoundNumericPlugValueWidget.__init__(self, plug, **kw)

    self.__swatch = GafferUI.ColorSwatch()
    ## \todo How do set maximum height with a public API?
    self.__swatch._qtWidget().setMaximumHeight(20)

    self._row().append(self.__swatch, expand=True)

    self.__buttonPressConnection = self.__swatch.buttonPressSignal().connect(
        Gaffer.WeakMethod(self.__buttonPress)
    )

    self.__colorChooserDialogue = None

    self._updateFromPlug()


# Traceback (RuntimeError)
# Traceback (most recent call last):
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/Widget.py", line 1458, in eventFilter
# return self.__mouseMove( qObject, qEvent )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/Widget.py", line 1603, in __mouseMove
# return widget._mouseMoveSignal( widget, event )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/Gaffer/WeakMethod.py", line 57, in __call__
# return m( *args, **kwArgs )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/Slider.py", line 146, in __mouseMove
# self.setPosition( float( event.line.p0.x ) / self.size().x )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/NumericSlider.py", line 73, in setPosition
# self.setValue( self.__min + position * ( self.__max - self.__min ) )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/NumericSlider.py", line 90, in setValue
# signal( self )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/Gaffer/WeakMethod.py", line 57, in __call__
# return m( *args, **kwArgs )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/ColorChooser.py", line 203, in __sliderChanged
# self.setColor( newColor )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/ColorChooser.py", line 174, in setColor
# self.__colorChangedSignal( self )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/Gaffer/WeakMethod.py", line 57, in __call__
# return m( *args, **kwArgs )
# File "/software/apps/gaffer/0.58.0/cent5.x86_64/cortex/8/maya/2012/python/GafferUI/ColorPlugValueWidget.py", line 131, in __colorChanged
# self.__plug.setValue( self.colorChooser().getColor() )
# RuntimeError: Exception : Cannot set value for plug "ShaderGraphApp.scripts.ScriptNode.PublicParameters.ieSimpleSurface.parameters.diffuseTint.r" except during computation.

# Fixed code
def __init__(self, plug, **kw):
    GafferUI.CompoundNumericPlugValueWidget.__init__(self, plug, **kw)

    self.__swatch = GafferUI.ColorSwatch()
    ## \todo How do set maximum height with a public API?
    self.__swatch._qtWidget().setMaximumHeight(20)

    self._row().append(self.__swatch, expand=True)

    self.__buttonPressConnection = self.__swatch.buttonPressSignal().connect(
        Gaffer.WeakMethod(self.__buttonPress)
    )

    self.__colorChooserDialogue = None
    self.__blinkBehaviour = None

    self._updateFromPlug()
# Buggy code
def uninstall_repo(self, name):
    repo_path = path.join(self.plugin_dir, name)
    shutil.rmtree(repo_path)
    repos = self.get_installed_plugin_repos().pop(name)
    self.set_plugin_repos(repos)


# Traceback (AttributeError)
20:25:29 DEBUG    errbot.errBot             Initializing backend storage
20:25:29 DEBUG    errbot.storage            Opening storage telegram_backend
20:25:29 DEBUG    errbot.storage.shelf      Open shelf storage /tmp/errbot-data/telegram_backend.db
Traceback (most recent call last):
File "/home/zoni/.virtualenvs/err/bin/errbot", line 9, in <module>
load_entry_point('errbot', 'console_scripts', 'errbot')()
File "/home/zoni/Workspace/Projects/err/errbot/err.py", line 261, in main
main(backend, logger, config, restore)
File "/home/zoni/Workspace/Projects/err/errbot/main.py", line 134, in main
bot = setup_bot(bot_class, logger, config, restore)
File "/home/zoni/Workspace/Projects/err/errbot/main.py", line 108, in setup_bot
errors = bot.plugin_manager.update_dynamic_plugins()
File "/home/zoni/Workspace/Projects/err/errbot/plugin_manager.py", line 423, in update_dynamic_plugins
return self.update_plugin_places(self.repo_manager.get_all_repos_paths(), self.extra, self.autoinstall_deps)
File "/home/zoni/Workspace/Projects/err/errbot/repo_manager.py", line 170, in get_all_repos_paths
return [os.path.join(self.plugin_dir, d) for d in self.get(INSTALLED_REPOS, {}).keys()]
AttributeError: 'str' object has no attribute 'keys'

# Fixed code
def uninstall_repo(self, name):
    repo_path = path.join(self.plugin_dir, name)
    shutil.rmtree(
        repo_path, ignore_errors=True
    )  # ignore errors because the DB can be desync'ed from the file tree.
    repos = self.get_installed_plugin_repos()
    del repos[name]
    self.set_plugin_repos(repos)
# Buggy code
def _warn_if_text_is_missing(endpoint: str, kwargs: Dict[str, Any]) -> None:
    attachments = kwargs.get("attachments")
    if attachments:
        if all(
            [
                attachment.get("fallback")
                and len(attachment.get("fallback").strip()) != 0
                for attachment in attachments
            ]
        ):
            return
        missing = "fallback"
    else:
        text = kwargs.get("text")
        if text and len(text.strip()) != 0:
            return
        missing = "text"
    message = (
        f"The `{missing}` argument is missing in the request payload for a {endpoint} call - "
        f"It's a best practice to always provide a `{missing}` argument when posting a message. "
        f"The `{missing}` argument is used in places where content cannot be rendered such as: "
        "system push notifications, assistive technology such as screen readers, etc."
    )
    # for unit tests etc.
    skip_deprecation = os.environ.get("SKIP_SLACK_SDK_WARNING")
    if skip_deprecation:
        return
    warnings.warn(message, UserWarning)


# Traceback (AttributeError)
Traceback (most recent call last):
...SNIP...
File "/usr/local/lib/python3.9/site-packages/slack_sdk/web/client.py", line 1185, in chat_update
"Developer": ":large_blue_square:  Developer",
_warn_if_text_is_missing("chat.update", kwargs)
File "/usr/local/lib/python3.9/site-packages/slack_sdk/web/internal_utils.py", line 237, in _warn_if_text_is_missing
[
File "/usr/local/lib/python3.9/site-packages/slack_sdk/web/internal_utils.py", line 238, in <listcomp>
attachment.get("fallback")
AttributeError: 'str' object has no attribute 'get'

# Fixed code
def _warn_if_text_is_missing(endpoint: str, kwargs: Dict[str, Any]) -> None:
    attachments = kwargs.get("attachments")
    if attachments and isinstance(attachments, list):
        if all(
            [
                attachment.get("fallback")
                and len(attachment.get("fallback").strip()) != 0
                for attachment in attachments
            ]
        ):
            return
        missing = "fallback"
    else:
        text = kwargs.get("text")
        if text and len(text.strip()) != 0:
            return
        missing = "text"
    message = (
        f"The `{missing}` argument is missing in the request payload for a {endpoint} call - "
        f"It's a best practice to always provide a `{missing}` argument when posting a message. "
        f"The `{missing}` argument is used in places where content cannot be rendered such as: "
        "system push notifications, assistive technology such as screen readers, etc."
    )
    # for unit tests etc.
    skip_deprecation = os.environ.get("SKIP_SLACK_SDK_WARNING")
    if skip_deprecation:
        return
    warnings.warn(message, UserWarning)
# Buggy code
async def files_upload(
    self, *, file: Union[str, IOBase] = None, content: str = None, **kwargs
) -> AsyncSlackResponse:
    """Uploads or creates a file.

    Args:
        file (str): Supply a file path.
            when you'd like to upload a specific file. e.g. 'dramacat.gif'
        content (str): Supply content when you'd like to create an
            editable text file containing the specified text. e.g. 'launch plan'
    Raises:
        SlackRequestError: If niether or both the `file` and `content` args are specified.
    """
    if file is None and content is None:
        raise e.SlackRequestError("The file or content argument must be specified.")
    if file is not None and content is not None:
        raise e.SlackRequestError(
            "You cannot specify both the file and the content argument."
        )

    if file:
        if "filename" not in kwargs:
            # use the local filename if filename is missing
            kwargs["filename"] = file.split(os.path.sep)[-1]
        return await self.api_call("files.upload", files={"file": file}, data=kwargs)
    data = kwargs.copy()
    data.update({"content": content})
    return await self.api_call("files.upload", data=data)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/afs/ThisCell/data/vlsi/eclipz/ct6/verif/p10d2/pscripts/user_modules/change_stats.py", line 456, in <module>
rc = main()
File "/afs/ThisCell/data/vlsi/eclipz/ct6/verif/p10d2/pscripts/user_modules/change_stats.py", line 356, in main
plotter(df)
File "/afs/ThisCell/data/vlsi/eclipz/ct6/verif/p10d2/pscripts/user_modules/change_stats.py", line 286, in plotter
initial_comment='')
File "/afs/ThisCell/func/vlsi/eclipz/ct6/verif/p10d1/.pscripts/pong/user_modules/site-packages/slack/web/client.py", line 1305, in files_upload
kwargs["filename"] = file.split(os.path.sep)[-1]
AttributeError: '_io.BufferedReader' object has no attribute 'split'

# Fixed code
async def files_upload(
    self, *, file: Union[str, IOBase] = None, content: str = None, **kwargs
) -> AsyncSlackResponse:
    """Uploads or creates a file.

    Args:
        file (str): Supply a file path.
            when you'd like to upload a specific file. e.g. 'dramacat.gif'
        content (str): Supply content when you'd like to create an
            editable text file containing the specified text. e.g. 'launch plan'
    Raises:
        SlackRequestError: If niether or both the `file` and `content` args are specified.
    """
    if file is None and content is None:
        raise e.SlackRequestError("The file or content argument must be specified.")
    if file is not None and content is not None:
        raise e.SlackRequestError(
            "You cannot specify both the file and the content argument."
        )

    if file:
        if "filename" not in kwargs and isinstance(file, str):
            # use the local filename if filename is missing
            kwargs["filename"] = file.split(os.path.sep)[-1]
        return await self.api_call("files.upload", files={"file": file}, data=kwargs)
    data = kwargs.copy()
    data.update({"content": content})
    return await self.api_call("files.upload", data=data)
# Buggy code
def files_upload(
    self, *, file: Union[str, IOBase] = None, content: str = None, **kwargs
) -> Union[Future, SlackResponse]:
    """Uploads or creates a file.

    Args:
        file (str): Supply a file path.
            when you'd like to upload a specific file. e.g. 'dramacat.gif'
        content (str): Supply content when you'd like to create an
            editable text file containing the specified text. e.g. 'launch plan'
    Raises:
        SlackRequestError: If niether or both the `file` and `content` args are specified.
    """
    if file is None and content is None:
        raise e.SlackRequestError("The file or content argument must be specified.")
    if file is not None and content is not None:
        raise e.SlackRequestError(
            "You cannot specify both the file and the content argument."
        )

    if file:
        if "filename" not in kwargs:
            # use the local filename if filename is missing
            kwargs["filename"] = file.split(os.path.sep)[-1]
        return self.api_call("files.upload", files={"file": file}, data=kwargs)
    data = kwargs.copy()
    data.update({"content": content})
    return self.api_call("files.upload", data=data)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/afs/ThisCell/data/vlsi/eclipz/ct6/verif/p10d2/pscripts/user_modules/change_stats.py", line 456, in <module>
rc = main()
File "/afs/ThisCell/data/vlsi/eclipz/ct6/verif/p10d2/pscripts/user_modules/change_stats.py", line 356, in main
plotter(df)
File "/afs/ThisCell/data/vlsi/eclipz/ct6/verif/p10d2/pscripts/user_modules/change_stats.py", line 286, in plotter
initial_comment='')
File "/afs/ThisCell/func/vlsi/eclipz/ct6/verif/p10d1/.pscripts/pong/user_modules/site-packages/slack/web/client.py", line 1305, in files_upload
kwargs["filename"] = file.split(os.path.sep)[-1]
AttributeError: '_io.BufferedReader' object has no attribute 'split'

# Fixed code
def files_upload(
    self, *, file: Union[str, IOBase] = None, content: str = None, **kwargs
) -> Union[Future, SlackResponse]:
    """Uploads or creates a file.

    Args:
        file (str): Supply a file path.
            when you'd like to upload a specific file. e.g. 'dramacat.gif'
        content (str): Supply content when you'd like to create an
            editable text file containing the specified text. e.g. 'launch plan'
    Raises:
        SlackRequestError: If niether or both the `file` and `content` args are specified.
    """
    if file is None and content is None:
        raise e.SlackRequestError("The file or content argument must be specified.")
    if file is not None and content is not None:
        raise e.SlackRequestError(
            "You cannot specify both the file and the content argument."
        )

    if file:
        if "filename" not in kwargs and isinstance(file, str):
            # use the local filename if filename is missing
            kwargs["filename"] = file.split(os.path.sep)[-1]
        return self.api_call("files.upload", files={"file": file}, data=kwargs)
    data = kwargs.copy()
    data.update({"content": content})
    return self.api_call("files.upload", data=data)
# Buggy code
async def _request(self, *, http_verb, api_url, req_args):
    """Submit the HTTP request with the running session or a new session.
    Returns:
        A dictionary of the response data.
    """
    if self.session and not self.session.closed:
        async with self.session.request(http_verb, api_url, **req_args) as res:
            return {
                "data": await res.json(),
                "headers": res.headers,
                "status_code": res.status,
            }
    async with aiohttp.ClientSession(
        loop=self._event_loop,
        timeout=aiohttp.ClientTimeout(total=self.timeout),
        auth=req_args.pop("auth"),
    ) as session:
        async with session.request(http_verb, api_url, **req_args) as res:
            return {
                "data": await res.json(),
                "headers": res.headers,
                "status_code": res.status,
            }


# Traceback (KeyError)
slackbot
Traceback (most recent call last):
File "foo.py", line 4, in <module>
for page in client.users_list(limit=1):
File "/home/foo/.pyenv/versions/3.7.2/lib/python3.7/site-packages/slack/web/slack_response.py", line 139, in __next__
req_args=self.req_args,
File "/home/foo/.pyenv/versions/3.7.2/lib/python3.7/asyncio/base_events.py", line 584, in run_until_complete
return future.result()
File "/home/foo/.pyenv/versions/3.7.2/lib/python3.7/site-packages/slack/web/base_client.py", line 258, in _request
auth=req_args.pop("auth"),
KeyError: 'auth'

# Fixed code
async def _request(self, *, http_verb, api_url, req_args):
    """Submit the HTTP request with the running session or a new session.
    Returns:
        A dictionary of the response data.
    """
    session = None
    if self.session and not self.session.closed:
        session = self.session
    else:
        session = aiohttp.ClientSession(
            timeout=aiohttp.ClientTimeout(total=self.timeout),
            auth=req_args.pop("auth", None),
        )

    response = None
    async with session.request(http_verb, api_url, **req_args) as res:
        data = {}
        try:
            data = await res.json()
        except aiohttp.ContentTypeError:
            self._logger.debug(
                f"No response data returned from the following API call: {api_url}."
            )
        response = {"data": data, "headers": res.headers, "status_code": res.status}

    await session.close()
    return response
# Buggy code
def run_on(*, event: str):
    """A decorator to store and link a callback to an event."""

    def decorator(callback):
        RTMClient.on(event=event, callback=callback)

    return decorator


# Traceback (TypeError)
Traceback (most recent call last):
File "a.py", line 7, in <module>
foo()
TypeError: 'NoneType' object is not callable

# Fixed code
def run_on(*, event: str):
    """A decorator to store and link a callback to an event."""

    def decorator(callback):
        RTMClient.on(event=event, callback=callback)
        return callback

    return decorator
# Buggy code
def decorator(callback):
    RTMClient.on(event=event, callback=callback)


# Traceback (TypeError)
Traceback (most recent call last):
File "a.py", line 7, in <module>
foo()
TypeError: 'NoneType' object is not callable

# Fixed code
def decorator(callback):
    RTMClient.on(event=event, callback=callback)
    return callback
# Buggy code
def __str__(self) -> str:
    if self == AdexEventType.BOND:
        return "deposit"
    if self == AdexEventType.UNBOND:
        return "withdraw"
    if self == AdexEventType.UNBOND_REQUEST:
        return "withdraw request"
    if self == AdexEventType.CHANNEL_WITHDRAW:
        return "claim"
    raise AttributeError(f"Corrupt value {self} for EventType -- Should never happen")


# Traceback (ValueError)
2021-01-17T09:45:53.929Z: Starting packaged python subprocess: /tmp/lefteris/.mount_rotki-bd0Awo/resources/rotkehlchen_py_dist/rotkehlchen-1.12.1-linux --api-port 4242 --loglevel debug --api-cors app://* --logfile /home/lefteris/.config/rotki/logs/rotkehlchen.log
2021-01-17T09:45:53.935Z: The Python sub-process started on port: 4242 (PID: 19124)
^C2021-01-17T09:54:44.510Z: Exiting the application
2021-01-17T09:54:44.675Z: Traceback (most recent call last):
File "rotkehlchen/chain/substrate/manager.py", line 408, in _get_node_interface
File "site-packages/substrateinterface/base.py", line 450, in __init__
ValueError: Type registry preset 'kusama' not found

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "src/gevent/greenlet.py", line 818, in gevent._greenlet.Greenlet.run
File "rotkehlchen/chain/substrate/manager.py", line 240, in _connect_node
File "rotkehlchen/chain/substrate/manager.py", line 418, in _get_node_interface
AttributeError: Invalid SubstrateInterface instantiation
2021-01-17T09:47:30Z <Greenlet at 0x7fcc0ff06cb0: <bound method SubstrateManager._connect_node of <rotkehlchen.chain.substrate.manager.SubstrateManager object at 0x7fcc167b5f90>>(node=<KusamaNodeName.OWN: 0>, endpoint='http://localhost:9933')> failed with AttributeError

Traceback (most recent call last):
File "rotkehlchen/chain/substrate/manager.py", line 408, in _get_node_interface
File "site-packages/substrateinterface/base.py", line 450, in __init__
ValueError: Type registry preset 'kusama' not found

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "src/gevent/greenlet.py", line 818, in gevent._greenlet.Greenlet.run
File "rotkehlchen/chain/substrate/manager.py", line 240, in _connect_node
File "rotkehlchen/chain/substrate/manager.py", line 418, in _get_node_interface
AttributeError: Invalid SubstrateInterface instantiation
2021-01-17T09:47:30Z <Greenlet at 0x7fcc0fe8d5f0: <bound method SubstrateManager._connect_node of <rotkehlchen.chain.substrate.manager.SubstrateManager object at 0x7fcc167b5f90>>(node=<KusamaNodeName.PARITY: 1>, endpoint='https://kusama-rpc.polkadot.io/')> failed with AttributeError

# Fixed code
def __str__(self) -> str:
    if self == AdexEventType.BOND:
        return "deposit"
    if self == AdexEventType.UNBOND:
        return "withdraw"
    if self == AdexEventType.UNBOND_REQUEST:
        return "withdraw request"
    if self == AdexEventType.CHANNEL_WITHDRAW:
        return "claim"
    raise AssertionError(f"Corrupt value {self} for EventType -- Should never happen")