gurudesh/pytracebugs huggingface dataset:
# Buggy code
def get_added_date_string(self):
    if self.added_date:
        return self.added_date.strftime("%Y-%m-%dT%H:%M:%S")
    else:
        return Date.now()


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/jeff/gtg/GTG/gtk/browser/modify_tags.py", line 94, in on_confirm
task.add_tag(tag)
File "/home/jeff/gtg/GTG/core/task.py", line 707, in add_tag
cgi.escape(tagname), sep, c)
AttributeError: module 'cgi' has no attribute 'escape'
Exception in thread Thread-2:

Traceback (most recent call last):
File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/lib/python3.8/threading.py", line 1254, in run
self.function(*self.args, **self.kwargs)
File "/home/jeff/gtg/GTG/backends/generic_backend.py", line 649, in launch_setting_thread
self.set_task(task)
File "/home/jeff/gtg/GTG/backends/backend_localfile.py", line 166, in set_task
t_xml = taskxml.task_to_xml(self.doc, task)
File "/home/jeff/gtg/GTG/core/taskxml.py", line 129, in task_to_xml
cleanxml.addTextNode(doc, t_xml, "addeddate", task.get_added_date_string())
File "/home/jeff/gtg/GTG/core/cleanxml.py", line 80, in addTextNode
element.appendChild(doc.createTextNode(content))
File "/usr/lib/python3.8/xml/dom/minidom.py", line 1659, in createTextNode
raise TypeError("node contents must be a string")
TypeError: node contents must be a string

# Fixed code
def get_added_date_string(self):
    FORMAT = "%Y-%m-%dT%H:%M:%S"

    if self.added_date:
        return self.added_date.strftime(FORMAT)
    else:
        return datetime.now().strftime(FORMAT)
# Buggy code
def set_title(self, title, transaction_ids=[]):
    """Sets the task title"""
    title = cgi.escape(title)
    result = self.rtm.tasks.setName(
        timeline=self.timeline,
        list_id=self.rtm_list.id,
        taskseries_id=self.rtm_taskseries.id,
        task_id=self.rtm_task.id,
        name=title,
    )
    transaction_ids.append(result.transaction.id)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/jeff/gtg/GTG/gtk/editor/taskview.py", line 550, in modified
self._detect_tag(buff, local_start, local_end)
File "/home/jeff/gtg/GTG/gtk/editor/taskview.py", line 740, in _detect_tag
self.add_tag_callback(my_word)
File "/home/jeff/gtg/GTG/core/task.py", line 707, in add_tag
cgi.escape(tagname), sep, c)
AttributeError: module 'cgi' has no attribute 'escape'

# Fixed code
def set_title(self, title, transaction_ids=[]):
    """Sets the task title"""
    title = html.escape(title)
    result = self.rtm.tasks.setName(
        timeline=self.timeline,
        list_id=self.rtm_list.id,
        taskseries_id=self.rtm_taskseries.id,
        task_id=self.rtm_task.id,
        name=title,
    )
    transaction_ids.append(result.transaction.id)
# Buggy code
def set_text(self, texte):
    self.can_be_deleted = False
    if texte != "<content/>":
        # defensive programmation to filter bad formatted tasks
        if not texte.startswith("<content>"):
            texte = cgi.escape(texte, quote=True)
            texte = f"<content>{texte}"
        if not texte.endswith("</content>"):
            texte = f"{texte}</content>"
        self.content = str(texte)
    else:
        self.content = ""


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/jeff/gtg/GTG/gtk/editor/taskview.py", line 550, in modified
self._detect_tag(buff, local_start, local_end)
File "/home/jeff/gtg/GTG/gtk/editor/taskview.py", line 740, in _detect_tag
self.add_tag_callback(my_word)
File "/home/jeff/gtg/GTG/core/task.py", line 707, in add_tag
cgi.escape(tagname), sep, c)
AttributeError: module 'cgi' has no attribute 'escape'

# Fixed code
def set_text(self, texte):
    self.can_be_deleted = False
    if texte != "<content/>":
        # defensive programmation to filter bad formatted tasks
        if not texte.startswith("<content>"):
            texte = html.escape(texte, quote=True)
            texte = f"<content>{texte}"
        if not texte.endswith("</content>"):
            texte = f"{texte}</content>"
        self.content = str(texte)
    else:
        self.content = ""
# Buggy code
def add_tag(self, tagname):
    "Add a tag to the task and insert '@tag' into the task's content"
    if self.tag_added(tagname):
        c = self.content

        # strip <content>...</content> tags
        if c.startswith("<content>"):
            c = c[len("<content>") :]
        if c.endswith("</content>"):
            c = c[: -len("</content>")]

        if not c:
            # don't need a separator if it's the only text
            sep = ""
        elif c.startswith("<tag>"):
            # if content starts with a tag, make a comma-separated list
            sep = ", "
        else:
            # other text at the beginning, so put the tag on its own line
            sep = "\n\n"

        self.content = "<content><tag>%s</tag>%s%s</content>" % (
            cgi.escape(tagname),
            sep,
            c,
        )
        # we modify the task internal state, thus we have to call for a
        # sync
        self.sync()


# Traceback (AttributeError)
Traceback (most recent call last):
File "/home/jeff/gtg/GTG/gtk/editor/taskview.py", line 550, in modified
self._detect_tag(buff, local_start, local_end)
File "/home/jeff/gtg/GTG/gtk/editor/taskview.py", line 740, in _detect_tag
self.add_tag_callback(my_word)
File "/home/jeff/gtg/GTG/core/task.py", line 707, in add_tag
cgi.escape(tagname), sep, c)
AttributeError: module 'cgi' has no attribute 'escape'

# Fixed code
def add_tag(self, tagname):
    "Add a tag to the task and insert '@tag' into the task's content"
    if self.tag_added(tagname):
        c = self.content

        # strip <content>...</content> tags
        if c.startswith("<content>"):
            c = c[len("<content>") :]
        if c.endswith("</content>"):
            c = c[: -len("</content>")]

        if not c:
            # don't need a separator if it's the only text
            sep = ""
        elif c.startswith("<tag>"):
            # if content starts with a tag, make a comma-separated list
            sep = ", "
        else:
            # other text at the beginning, so put the tag on its own line
            sep = "\n\n"

        self.content = "<content><tag>%s</tag>%s%s</content>" % (
            html.escape(tagname),
            sep,
            c,
        )
        # we modify the task internal state, thus we have to call for a
        # sync
        self.sync()
# Buggy code
def _get_tasks_from_blocks(task_blocks: Sequence) -> Generator:
    """Get list of tasks from list made of tasks and nested tasks."""
    NESTED_TASK_KEYS = [
        "block",
        "always",
        "rescue",
    ]

    def get_nested_tasks(task: Any) -> Generator[Any, None, None]:
        return (
            subtask
            for k in NESTED_TASK_KEYS
            if task and k in task
            for subtask in task[k]
        )

    for task in task_blocks:
        for sub_task in get_nested_tasks(task):
            yield sub_task
        yield task


# Traceback (TypeError)
Traceback (most recent call last):
File "/Users/ssbarnea/.pyenv/versions/3.8.2/bin/ansible-lint", line 11, in <module>
load_entry_point('ansible-lint', 'console_scripts', 'ansible-lint')()
File "/Users/ssbarnea/c/os/ansible-lint/lib/ansiblelint/__main__.py", line 94, in main
matches.extend(runner.run())
File "/Users/ssbarnea/c/os/ansible-lint/lib/ansiblelint/__init__.py", line 159, in run
for child in ansiblelint.utils.find_children(arg, self.playbook_dir):
File "/Users/ssbarnea/c/os/ansible-lint/lib/ansiblelint/utils.py", line 195, in find_children
for child in _rebind_match_filename(playbook[0], play_children)(
File "/Users/ssbarnea/c/os/ansible-lint/lib/ansiblelint/utils.py", line 174, in func_wrapper
return func(*args, **kwargs)
File "/Users/ssbarnea/c/os/ansible-lint/lib/ansiblelint/utils.py", line 248, in play_children
return delegate_map[k](basedir, k, v, parent_type)
File "/Users/ssbarnea/c/os/ansible-lint/lib/ansiblelint/utils.py", line 287, in _taskshandlers_children
results.extend(_taskshandlers_children(basedir, k, th['block'], parent_type))
File "/Users/ssbarnea/c/os/ansible-lint/lib/ansiblelint/utils.py", line 264, in _taskshandlers_children
for th in v:
TypeError: 'NoneType' object is not iterable

# Fixed code
def _get_tasks_from_blocks(task_blocks: Sequence) -> Generator:
    """Get list of tasks from list made of tasks and nested tasks."""
    NESTED_TASK_KEYS = [
        "block",
        "always",
        "rescue",
    ]

    def get_nested_tasks(task: Any) -> Generator[Any, None, None]:
        for k in NESTED_TASK_KEYS:
            if task and k in task and task[k]:
                for subtask in task[k]:
                    yield subtask

    for task in task_blocks:
        for sub_task in get_nested_tasks(task):
            yield sub_task
        yield task
# Buggy code
def get_nested_tasks(task: Any) -> Generator[Any, None, None]:
    return (
        subtask for k in NESTED_TASK_KEYS if task and k in task for subtask in task[k]
    )


# Traceback (TypeError)
Traceback (most recent call last):
File "/Users/ssbarnea/.pyenv/versions/3.8.2/bin/ansible-lint", line 11, in <module>
load_entry_point('ansible-lint', 'console_scripts', 'ansible-lint')()
File "/Users/ssbarnea/c/os/ansible-lint/lib/ansiblelint/__main__.py", line 94, in main
matches.extend(runner.run())
File "/Users/ssbarnea/c/os/ansible-lint/lib/ansiblelint/__init__.py", line 159, in run
for child in ansiblelint.utils.find_children(arg, self.playbook_dir):
File "/Users/ssbarnea/c/os/ansible-lint/lib/ansiblelint/utils.py", line 195, in find_children
for child in _rebind_match_filename(playbook[0], play_children)(
File "/Users/ssbarnea/c/os/ansible-lint/lib/ansiblelint/utils.py", line 174, in func_wrapper
return func(*args, **kwargs)
File "/Users/ssbarnea/c/os/ansible-lint/lib/ansiblelint/utils.py", line 248, in play_children
return delegate_map[k](basedir, k, v, parent_type)
File "/Users/ssbarnea/c/os/ansible-lint/lib/ansiblelint/utils.py", line 287, in _taskshandlers_children
results.extend(_taskshandlers_children(basedir, k, th['block'], parent_type))
File "/Users/ssbarnea/c/os/ansible-lint/lib/ansiblelint/utils.py", line 264, in _taskshandlers_children
for th in v:
TypeError: 'NoneType' object is not iterable

# Fixed code
def get_nested_tasks(task: Any) -> Generator[Any, None, None]:
    for k in NESTED_TASK_KEYS:
        if task and k in task and task[k]:
            for subtask in task[k]:
                yield subtask
# Buggy code
def _playbook_items(pb_data: dict) -> ItemsView:
    if isinstance(pb_data, dict):
        return pb_data.items()
    elif not pb_data:
        return []
    else:
        return [item for play in pb_data for item in play.items()]


# Traceback (AttributeError)
(venv) user@test:~/ansible$ cat test.yml
- #debug:
#  msg: Hello!

(venv) user@test:~/ansible$ ansible-lint test.yml -vvv
DEBUG    Logging initialized to level 10
DEBUG    Options: Namespace(colored=True, config_file=None, display_relative_path=True, exclude_paths=[], format='plain', listrules=False, listtags=False, parseable=False, parseable_severity=False, playbook=['test.yml'], quiet=False, rulesdir=[], skip_list=[], tags=[], use_default_rules=False, verbosity=3)
DEBUG    Loading rules from /home/user/ansible/venv/lib/python3.8/site-packages/ansiblelint/rules
Traceback (most recent call last):
File "/home/user/ansible/venv/bin/ansible-lint", line 8, in <module>
sys.exit(main())
File "/home/user/ansible/venv/lib/python3.8/site-packages/ansiblelint/__main__.py", line 116, in main
matches.extend(runner.run())
File "/home/user/ansible/venv/lib/python3.8/site-packages/ansiblelint/runner.py", line 73, in run
for child in ansiblelint.utils.find_children(arg, self.playbook_dir):
File "/home/user/ansible/venv/lib/python3.8/site-packages/ansiblelint/utils.py", line 159, in find_children
items = _playbook_items(playbook_ds)
File "/home/user/ansible/venv/lib/python3.8/site-packages/ansiblelint/utils.py", line 134, in _playbook_items
return [item for play in pb_data for item in play.items()]
File "/home/user/ansible/venv/lib/python3.8/site-packages/ansiblelint/utils.py", line 134, in <listcomp>
return [item for play in pb_data for item in play.items()]
AttributeError: 'NoneType' object has no attribute 'items'

# Fixed code
def _playbook_items(pb_data: dict) -> ItemsView:
    if isinstance(pb_data, dict):
        return pb_data.items()
    elif not pb_data:
        return []
    else:
        # "if play" prevents failure if the play sequence containes None,
        # which is weird but currently allowed by Ansible
        # https://github.com/ansible-community/ansible-lint/issues/849
        return [item for play in pb_data if play for item in play.items()]
# Buggy code
def expand_path_vars(path: str) -> str:
    """Expand the environment or ~ variables in a path string."""
    path = path.strip()
    path = os.path.expanduser(path)
    path = os.path.expandvars(path)
    return path


# Traceback (AttributeError)
DEBUG    Logging initialized to level 10
DEBUG    Options: Namespace(colored=True, config_file=None, display_relative_path=True, exclude_paths=[], format='plain', listrules=False, listtags=False, parseable=False, parseable_severity=False, playbook=['playbook.yml'], quiet=False, rulesdir=[PosixPath('/lint-rules')], skip_list=[], tags=[], use_default_rules=True, verbosity=3)
Traceback (most recent call last):
File "/usr/local/bin/ansible-lint", line 8, in <module>
sys.exit(main())
File "/usr/local/lib/python3.8/site-packages/ansiblelint/__main__.py", line 93, in main
rules = RulesCollection(rulesdirs)
File "/usr/local/lib/python3.8/site-packages/ansiblelint/rules/__init__.py", line 186, in __init__
self.rulesdirs = ansiblelint.utils.expand_paths_vars(rulesdirs)
File "/usr/local/lib/python3.8/site-packages/ansiblelint/utils.py", line 783, in expand_paths_vars
paths = [expand_path_vars(p) for p in paths]
File "/usr/local/lib/python3.8/site-packages/ansiblelint/utils.py", line 783, in <listcomp>
paths = [expand_path_vars(p) for p in paths]
File "/usr/local/lib/python3.8/site-packages/ansiblelint/utils.py", line 775, in expand_path_vars
path = path.strip()
AttributeError: 'PosixPath' object has no attribute 'strip'

# Fixed code
def expand_path_vars(path: str) -> str:
    """Expand the environment or ~ variables in a path string."""
    # It may be possible for function to be called with a Path object
    path = str(path).strip()
    path = os.path.expanduser(path)
    path = os.path.expandvars(path)
    return path
# Buggy code
def focus_event(self):
    return self.focus.original_widget


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/khal/ui/__init__.py", line 1348, in start_pane
loop.run()
File "/usr/lib/python3.8/site-packages/urwid/main_loop.py", line 287, in run
self._run()
File "/usr/lib/python3.8/site-packages/urwid/main_loop.py", line 385, in _run
self.event_loop.run()
File "/usr/lib/python3.8/site-packages/urwid/main_loop.py", line 790, in run
self._loop()
File "/usr/lib/python3.8/site-packages/urwid/main_loop.py", line 827, in _loop
self._watch_files[fd]()
File "/usr/lib/python3.8/site-packages/urwid/raw_display.py", line 416, in <lambda>
wrapper = lambda: self.parse_input(
File "/usr/lib/python3.8/site-packages/urwid/raw_display.py", line 515, in parse_input
callback(processed, processed_codes)
File "/usr/lib/python3.8/site-packages/urwid/main_loop.py", line 412, in _update
self.process_input(keys)
File "/usr/lib/python3.8/site-packages/urwid/main_loop.py", line 513, in process_input
k = self._topmost_widget.keypress(self.screen_size, k)
File "/usr/lib/python3.8/site-packages/urwid/wimp.py", line 651, in keypress
return self._current_widget.keypress(size, key)
File "/usr/lib/python3.8/site-packages/urwid/container.py", line 1135, in keypress
return self.body.keypress( (maxcol, remaining), key )
File "/usr/lib/python3.8/site-packages/khal/ui/base.py", line 114, in keypress
return super().keypress(size, key)
File "/usr/lib/python3.8/site-packages/khal/ui/widgets.py", line 308, in keypress
key = super(NextMixin, self).keypress(size, key)
File "/usr/lib/python3.8/site-packages/urwid/container.py", line 2316, in keypress
key = w.keypress((mc,) + size[1:], key)
File "/usr/lib/python3.8/site-packages/khal/ui/__init__.py", line 903, in keypress
if self.focus_event:
File "/usr/lib/python3.8/site-packages/khal/ui/__init__.py", line 636, in focus_event
return self.dlistbox.focus_event
File "/usr/lib/python3.8/site-packages/khal/ui/__init__.py", line 258, in focus_event
return self.focus.original_widget
AttributeError: 'NoneType' object has no attribute 'original_widget'

# Fixed code
def focus_event(self):
    if self.focus is None:
        return None
    else:
        return self.focus.original_widget
# Buggy code
def get_event(self, href, calendar):
    return self._cover_event(self._backend.get(href, calendar))


# Traceback (AssertionError)
Traceback (most recent call last):
File "/usr/lib/python3.5/site-packages/khal/ui/__init__.py", line 891, in start_pane
loop.run()
File "/usr/lib/python3.5/site-packages/urwid/main_loop.py", line 278, in run
self._run()
File "/usr/lib/python3.5/site-packages/urwid/main_loop.py", line 376, in _run
self.event_loop.run()
File "/usr/lib/python3.5/site-packages/urwid/main_loop.py", line 682, in run
self._loop()
File "/usr/lib/python3.5/site-packages/urwid/main_loop.py", line 719, in _loop
self._watch_files[fd]()
File "/usr/lib/python3.5/site-packages/urwid/raw_display.py", line 393, in <lambda>
event_loop, callback, self.get_available_raw_input())
File "/usr/lib/python3.5/site-packages/urwid/raw_display.py", line 493, in parse_input
callback(processed, processed_codes)
File "/usr/lib/python3.5/site-packages/urwid/main_loop.py", line 403, in _update
self.process_input(keys)
File "/usr/lib/python3.5/site-packages/urwid/main_loop.py", line 509, in process_input
something_handled |= bool(self.unhandled_input(k))
File "/usr/lib/python3.5/site-packages/urwid/main_loop.py", line 555, in unhandled_input
return self._unhandled_input(input)
File "/usr/lib/python3.5/site-packages/khal/ui/base.py", line 149, in on_key_press
self.backtrack()
File "/usr/lib/python3.5/site-packages/khal/ui/base.py", line 139, in backtrack
cb(data)
File "/usr/lib/python3.5/site-packages/khal/ui/__init__.py", line 775, in cleanup
event = self.collection.get_event(href, account)
File "/usr/lib/python3.5/site-packages/khal/khalendar/khalendar.py", line 234, in get_event
return self._cover_event(self._backend.get(href, calendar))
File "/usr/lib/python3.5/site-packages/khal/khalendar/backend.py", line 544, in get
assert calendar is not None
AssertionError

# Fixed code
def get_event(self, href, calendar):
    return self._cover_event(self._backend.get(href, calendar=calendar))
# Buggy code
def __init__(self, eventcolumn):
    self.eventcolumn = eventcolumn
    self.list_walker = None
    pile = urwid.Filler(urwid.Pile([]))
    urwid.WidgetWrap.__init__(self, pile)
    self.update_by_date()


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/bin/ikhal", line 9, in <module>
load_entry_point('khal==0.7.1.dev128+ng619ddd6.d20160219', 'console_scripts', 'ikhal')()
File "/usr/lib/python3.5/site-packages/click/core.py", line 716, in __call__
return self.main(*args, **kwargs)
File "/usr/lib/python3.5/site-packages/click/core.py", line 696, in main
rv = self.invoke(ctx)
File "/usr/lib/python3.5/site-packages/click/core.py", line 889, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/lib/python3.5/site-packages/click/core.py", line 534, in invoke
return callback(*args, **kwargs)
File "/usr/lib/python3.5/site-packages/click/decorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "/usr/lib/python3.5/site-packages/khal/cli.py", line 361, in interactive_cli
controllers.interactive(build_collection(ctx), ctx.obj['conf'])
File "/usr/lib/python3.5/site-packages/khal/controllers.py", line 209, in interactive
description='do something')
File "/usr/lib/python3.5/site-packages/khal/ui/__init__.py", line 715, in __init__
get_styles=collection.get_styles
File "/usr/lib/python3.5/site-packages/khal/ui/calendarwidget.py", line 591, in __init__
self.set_focus_date(initial)
File "/usr/lib/python3.5/site-packages/khal/ui/calendarwidget.py", line 605, in set_focus_date
self.box.set_focus_date(a_day)
File "/usr/lib/python3.5/site-packages/khal/ui/calendarwidget.py", line 295, in set_focus_date
self.body.set_focus_date(a_day)
File "/usr/lib/python3.5/site-packages/khal/ui/calendarwidget.py", line 370, in set_focus_date
self[self.focus]._set_focus_position(column)
File "/usr/lib/python3.5/site-packages/khal/ui/calendarwidget.py", line 139, in _set_focus_position
self.on_date_change(self.contents[position][0].date)
File "/usr/lib/python3.5/site-packages/khal/ui/__init__.py", line 764, in show_date
self.eventscolumn.original_widget.current_date = date
File "/usr/lib/python3.5/site-packages/khal/ui/__init__.py", line 312, in current_date
if len(self.events.events) > 0:
AttributeError: 'EventList' object has no attribute 'events'

# Fixed code
def __init__(self, eventcolumn):
    self.eventcolumn = eventcolumn
    self.events = None
    self.list_walker = None
    pile = urwid.Filler(urwid.Pile([]))
    urwid.WidgetWrap.__init__(self, pile)
    self.update_by_date()
# Buggy code
def global_options(f):
    config = click.option(
        "--config", "-c", default=None, metavar="PATH", help="The config file to use."
    )
    verbose = click.option(
        "--verbose", "-v", is_flag=True, help="Output debugging information."
    )
    version = click.version_option(version=__version__)

    return config(verbose(version(f)))


# Traceback (TypeError)
(vdir)gour@atmarama ~/p/vdir> ikhal -a gour
Traceback (most recent call last):
File "/home/gour/prj/vdir/bin/ikhal", line 9, in <module>
load_entry_point('khal==0.6.1.dev83+nge9717c8', 'console_scripts', 'ikhal')()
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 700, in __call__
return self.main(*args, **kwargs)
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 679, in main
with self.make_context(prog_name, args, **extra) as ctx:
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 594, in make_context
self.parse_args(ctx, args)
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 858, in parse_args
value, args = param.handle_parse_result(ctx, opts, args)
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 1362, in handle_parse_result
self.callback, ctx, self, value)
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 56, in invoke_param_callback
return callback(ctx, param, value)
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/khal/cli.py", line 58, in _multi_calendar_select_callback
if 'calendar_selection' in ctx.obj:
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def global_options(f):
    def config_callback(ctx, option, config):
        prepare_context(ctx, config)

    def verbosity_callback(ctx, option, verbose):
        if verbose:
            logger.setLevel(logging.DEBUG)
        else:
            logger.setLevel(logging.INFO)

    config = click.option(
        "--config",
        "-c",
        default=None,
        metavar="PATH",
        help="The config file to use.",
        is_eager=True,
        expose_value=False,
        callback=config_callback,
    )
    verbose = click.option(
        "--verbose",
        "-v",
        is_flag=True,
        help="Output debugging information.",
        expose_value=False,
        callback=verbosity_callback,
    )
    version = click.version_option(version=__version__)

    return config(verbose(version(f)))
# Buggy code
def prepare_context(ctx, config, verbose):
    if ctx.obj is not None:
        return

    if verbose:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)

    ctx.obj = {}
    try:
        ctx.obj["conf"] = conf = get_config(config)
    except InvalidSettingsError:
        sys.exit(1)

    logger.debug("khal %s" % __version__)
    logger.debug("Using config:")
    logger.debug(to_unicode(stringify_conf(conf), "utf-8"))

    if conf is None:
        raise click.UsageError("Invalid config file, exiting.")


# Traceback (TypeError)
(vdir)gour@atmarama ~/p/vdir> ikhal -a gour
Traceback (most recent call last):
File "/home/gour/prj/vdir/bin/ikhal", line 9, in <module>
load_entry_point('khal==0.6.1.dev83+nge9717c8', 'console_scripts', 'ikhal')()
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 700, in __call__
return self.main(*args, **kwargs)
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 679, in main
with self.make_context(prog_name, args, **extra) as ctx:
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 594, in make_context
self.parse_args(ctx, args)
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 858, in parse_args
value, args = param.handle_parse_result(ctx, opts, args)
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 1362, in handle_parse_result
self.callback, ctx, self, value)
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 56, in invoke_param_callback
return callback(ctx, param, value)
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/khal/cli.py", line 58, in _multi_calendar_select_callback
if 'calendar_selection' in ctx.obj:
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def prepare_context(ctx, config):
    assert ctx.obj is None

    ctx.obj = {}
    try:
        ctx.obj["conf"] = conf = get_config(config)
    except InvalidSettingsError:
        sys.exit(1)

    logger.debug("khal %s" % __version__)
    logger.debug("Using config:")
    logger.debug(to_unicode(stringify_conf(conf), "utf-8"))

    if conf is None:
        raise click.UsageError("Invalid config file, exiting.")
# Buggy code
def cli(ctx, config, verbose):
    # setting the process title so it looks nicer in ps
    # shows up as 'khal' under linux and as 'python: khal (python2.7)'
    # under FreeBSD, which is still nicer than the default
    setproctitle("khal")
    prepare_context(ctx, config, verbose)

    if not ctx.invoked_subcommand:
        command = ctx.obj["conf"]["default"]["default_command"]
        if command:
            ctx.invoke(cli.commands[command])
        else:
            click.echo(ctx.get_help())
            ctx.exit(1)


# Traceback (TypeError)
(vdir)gour@atmarama ~/p/vdir> ikhal -a gour
Traceback (most recent call last):
File "/home/gour/prj/vdir/bin/ikhal", line 9, in <module>
load_entry_point('khal==0.6.1.dev83+nge9717c8', 'console_scripts', 'ikhal')()
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 700, in __call__
return self.main(*args, **kwargs)
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 679, in main
with self.make_context(prog_name, args, **extra) as ctx:
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 594, in make_context
self.parse_args(ctx, args)
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 858, in parse_args
value, args = param.handle_parse_result(ctx, opts, args)
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 1362, in handle_parse_result
self.callback, ctx, self, value)
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 56, in invoke_param_callback
return callback(ctx, param, value)
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/khal/cli.py", line 58, in _multi_calendar_select_callback
if 'calendar_selection' in ctx.obj:
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def cli(ctx):
    # setting the process title so it looks nicer in ps
    # shows up as 'khal' under linux and as 'python: khal (python2.7)'
    # under FreeBSD, which is still nicer than the default
    setproctitle("khal")

    if not ctx.invoked_subcommand:
        command = ctx.obj["conf"]["default"]["default_command"]
        if command:
            ctx.invoke(cli.commands[command])
        else:
            click.echo(ctx.get_help())
            ctx.exit(1)
# Buggy code
def interactive_cli(ctx, config, verbose):
    """Interactive UI. Also launchable via `khal interactive`."""
    prepare_context(ctx, config, verbose)
    controllers.interactive(build_collection(ctx), ctx.obj["conf"])


# Traceback (TypeError)
(vdir)gour@atmarama ~/p/vdir> ikhal -a gour
Traceback (most recent call last):
File "/home/gour/prj/vdir/bin/ikhal", line 9, in <module>
load_entry_point('khal==0.6.1.dev83+nge9717c8', 'console_scripts', 'ikhal')()
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 700, in __call__
return self.main(*args, **kwargs)
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 679, in main
with self.make_context(prog_name, args, **extra) as ctx:
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 594, in make_context
self.parse_args(ctx, args)
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 858, in parse_args
value, args = param.handle_parse_result(ctx, opts, args)
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 1362, in handle_parse_result
self.callback, ctx, self, value)
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/click/core.py", line 56, in invoke_param_callback
return callback(ctx, param, value)
File "/home/gour/prj/vdir/local/lib/python2.7/site-packages/khal/cli.py", line 58, in _multi_calendar_select_callback
if 'calendar_selection' in ctx.obj:
TypeError: argument of type 'NoneType' is not iterable

# Fixed code
def interactive_cli(ctx):
    """Interactive UI. Also launchable via `khal interactive`."""
    controllers.interactive(build_collection(ctx), ctx.obj["conf"])
# Buggy code
def prepare_context(ctx, config, verbose):
    if ctx.obj is not None:
        return

    if verbose:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)

    ctx.obj = {}
    ctx.obj["conf"] = conf = get_config(config)

    out = StringIO()
    conf.write(out)
    logger.debug("Using config:")
    logger.debug(out.getvalue())

    if conf is None:
        raise click.UsageError("Invalid config file, exiting.")


# Traceback (KeyError)
Traceback (most recent call last):
File "/usr/local/bin/khal", line 9, in <module>
load_entry_point('khal==0.3.1', 'console_scripts', 'khal')()
File "/usr/local/lib/python2.7/dist-packages/khal-0.3.1-py2.7.egg/khal/cli.py", line 104, in main_khal
color=cal['color'],
File "/usr/local/lib/python2.7/dist-packages/configobj-4.7.2-py2.7.egg/configobj.py", line 567, in __getitem__
val = dict.__getitem__(self, key)
KeyError: 'color'

# Fixed code
def prepare_context(ctx, config, verbose):
    if ctx.obj is not None:
        return

    if verbose:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)

    ctx.obj = {}
    try:
        ctx.obj["conf"] = conf = get_config(config)
    except InvalidSettingsError:
        sys.exit(1)

    out = StringIO()
    conf.write(out)
    logger.debug("Using config:")
    logger.debug(out.getvalue())

    if conf is None:
        raise click.UsageError("Invalid config file, exiting.")
# Buggy code
def config_checks(config):
    """do some tests on the config we cannot do with configobj's validator"""
    if len(config["calendars"].keys()) < 1:
        raise ValueError("Found no calendar in the config file")
    test_default_calendar(config)
    config["sqlite"]["path"] = expand_db_path(config["sqlite"]["path"])
    if not config["locale"]["default_timezone"]:
        config["locale"]["default_timezone"] = is_timezone(
            config["locale"]["default_timezone"]
        )
    if not config["locale"]["local_timezone"]:
        config["locale"]["local_timezone"] = is_timezone(
            config["locale"]["local_timezone"]
        )


# Traceback (KeyError)
Traceback (most recent call last):
File "/usr/local/bin/khal", line 9, in <module>
load_entry_point('khal==0.3.1', 'console_scripts', 'khal')()
File "/usr/local/lib/python2.7/dist-packages/khal-0.3.1-py2.7.egg/khal/cli.py", line 104, in main_khal
color=cal['color'],
File "/usr/local/lib/python2.7/dist-packages/configobj-4.7.2-py2.7.egg/configobj.py", line 567, in __getitem__
val = dict.__getitem__(self, key)
KeyError: 'color'

# Fixed code
def config_checks(config):
    """do some tests on the config we cannot do with configobj's validator"""
    if len(config["calendars"].keys()) < 1:
        logger.fatal("Found no calendar section in the config file")
        raise InvalidSettingsError()
    test_default_calendar(config)
    config["sqlite"]["path"] = expand_db_path(config["sqlite"]["path"])
    if not config["locale"]["default_timezone"]:
        config["locale"]["default_timezone"] = is_timezone(
            config["locale"]["default_timezone"]
        )
    if not config["locale"]["local_timezone"]:
        config["locale"]["local_timezone"] = is_timezone(
            config["locale"]["local_timezone"]
        )
# Buggy code
def __init__(self, conf):
    db_path = conf.sqlite.path
    if db_path is None:
        db_path = xdg.BaseDirectory.save_data_path("khal") + "/khal.db"
    self.db_path = path.expanduser(db_path)
    self.conn = sqlite3.connect(self.db_path)
    self.cursor = self.conn.cursor()
    self.debug = conf.debug
    self._create_default_tables()
    self._check_table_version()
    self.conf = conf


# Traceback (sqlite3.OperationalError)
Traceback (most recent call last):
File "/home/catern/src/khal/virt/bin/khal", line 5, in <module>
pkg_resources.run_script('khal==0.1.0.dev', 'khal')
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 540, in run_script
self.require(requires)[0].run_script(script_name, ns)
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 1462, in run_script
exec_(script_code, namespace, namespace)
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 41, in exec_
exec("""exec code in globs, locs""")
File "<string>", line 1, in <module>
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/khal-0.1.0.dev-py2.7.egg/EGG-INFO/scripts/khal", line 72, in <module>

File "build/bdist.linux-x86_64/egg/khal/controllers.py", line 178, in __init__
File "build/bdist.linux-x86_64/egg/khal/backend.py", line 440, in get_allday_range
File "build/bdist.linux-x86_64/egg/khal/backend.py", line 164, in sql_ex
sqlite3.OperationalError: no such table: simple_d

# Fixed code
def __init__(self, conf):
    db_path = conf.sqlite.path
    if db_path is None:
        db_path = xdg.BaseDirectory.save_data_path("khal") + "/khal.db"
    self.db_path = path.expanduser(db_path)
    self.conn = sqlite3.connect(self.db_path)
    self.cursor = self.conn.cursor()
    self.debug = conf.debug
    self._create_default_tables()
    self._check_table_version()
    self.conf = conf
    self._accounts = []
# Buggy code
def needs_update(self, account, href_etag_list):
    """checks if we need to update this vcard
    :param account: account
    :param account: string
    :param href_etag_list: list of tuples of (hrefs and etags)
    :return: list of hrefs that need an update
    """
    needs_update = list()
    for href, etag in href_etag_list:
        stuple = (href,)
        sql_s = "SELECT etag FROM {0} WHERE href = ?".format(account + "_m")
        result = self.sql_ex(sql_s, stuple)
        if not result or etag != result[0][0]:
            needs_update.append(href)
    return needs_update


# Traceback (sqlite3.OperationalError)
Traceback (most recent call last):
File "/home/catern/src/khal/virt/bin/khal", line 5, in <module>
pkg_resources.run_script('khal==0.1.0.dev', 'khal')
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 540, in run_script
self.require(requires)[0].run_script(script_name, ns)
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 1462, in run_script
exec_(script_code, namespace, namespace)
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 41, in exec_
exec("""exec code in globs, locs""")
File "<string>", line 1, in <module>
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/khal-0.1.0.dev-py2.7.egg/EGG-INFO/scripts/khal", line 72, in <module>

File "build/bdist.linux-x86_64/egg/khal/controllers.py", line 178, in __init__
File "build/bdist.linux-x86_64/egg/khal/backend.py", line 440, in get_allday_range
File "build/bdist.linux-x86_64/egg/khal/backend.py", line 164, in sql_ex
sqlite3.OperationalError: no such table: simple_d

# Fixed code
def needs_update(self, account, href_etag_list):
    """checks if we need to update this vcard
    :param account: account
    :param account: string
    :param href_etag_list: list of tuples of (hrefs and etags)
    :return: list of hrefs that need an update
    """
    self._check_account(account)
    needs_update = list()
    for href, etag in href_etag_list:
        stuple = (href,)
        sql_s = "SELECT etag FROM {0} WHERE href = ?".format(account + "_m")
        result = self.sql_ex(sql_s, stuple)
        if not result or etag != result[0][0]:
            needs_update.append(href)
    return needs_update
# Buggy code
def update_href(self, oldhref, newhref, account, etag="", status=OK):
    """updates old_href to new_href, can also alter etag and status,
    see update() for an explanation of these parameters"""
    stuple = (newhref, etag, status, oldhref)
    sql_s = "UPDATE {0} SET href = ?, etag = ?, status = ? \
             WHERE href = ?;".format(account + "_m")
    self.sql_ex(sql_s, stuple)
    for dbname in [account + "_d", account + "_dt"]:
        sql_s = "UPDATE {0} SET href = ? WHERE href = ?;".format(dbname)
        self.sql_ex(sql_s, (newhref, oldhref))


# Traceback (sqlite3.OperationalError)
Traceback (most recent call last):
File "/home/catern/src/khal/virt/bin/khal", line 5, in <module>
pkg_resources.run_script('khal==0.1.0.dev', 'khal')
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 540, in run_script
self.require(requires)[0].run_script(script_name, ns)
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 1462, in run_script
exec_(script_code, namespace, namespace)
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 41, in exec_
exec("""exec code in globs, locs""")
File "<string>", line 1, in <module>
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/khal-0.1.0.dev-py2.7.egg/EGG-INFO/scripts/khal", line 72, in <module>

File "build/bdist.linux-x86_64/egg/khal/controllers.py", line 178, in __init__
File "build/bdist.linux-x86_64/egg/khal/backend.py", line 440, in get_allday_range
File "build/bdist.linux-x86_64/egg/khal/backend.py", line 164, in sql_ex
sqlite3.OperationalError: no such table: simple_d

# Fixed code
def update_href(self, oldhref, newhref, account, etag="", status=OK):
    """updates old_href to new_href, can also alter etag and status,
    see update() for an explanation of these parameters"""
    self._check_account(account)
    stuple = (newhref, etag, status, oldhref)
    sql_s = "UPDATE {0} SET href = ?, etag = ?, status = ? \
             WHERE href = ?;".format(account + "_m")
    self.sql_ex(sql_s, stuple)
    for dbname in [account + "_d", account + "_dt"]:
        sql_s = "UPDATE {0} SET href = ? WHERE href = ?;".format(dbname)
        self.sql_ex(sql_s, (newhref, oldhref))
# Buggy code
def href_exists(self, href, account):
    """returns True if href already exists in db

    :param href: href
    :type href: str()
    :returns: True or False
    """
    sql_s = "SELECT href FROM {0} WHERE href = ?;".format(account)
    if len(self.sql_ex(sql_s, (href,))) == 0:
        return False
    else:
        return True


# Traceback (sqlite3.OperationalError)
Traceback (most recent call last):
File "/home/catern/src/khal/virt/bin/khal", line 5, in <module>
pkg_resources.run_script('khal==0.1.0.dev', 'khal')
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 540, in run_script
self.require(requires)[0].run_script(script_name, ns)
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 1462, in run_script
exec_(script_code, namespace, namespace)
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 41, in exec_
exec("""exec code in globs, locs""")
File "<string>", line 1, in <module>
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/khal-0.1.0.dev-py2.7.egg/EGG-INFO/scripts/khal", line 72, in <module>

File "build/bdist.linux-x86_64/egg/khal/controllers.py", line 178, in __init__
File "build/bdist.linux-x86_64/egg/khal/backend.py", line 440, in get_allday_range
File "build/bdist.linux-x86_64/egg/khal/backend.py", line 164, in sql_ex
sqlite3.OperationalError: no such table: simple_d

# Fixed code
def href_exists(self, href, account):
    """returns True if href already exists in db

    :param href: href
    :type href: str()
    :returns: True or False
    """
    self._check_account(account)
    sql_s = "SELECT href FROM {0} WHERE href = ?;".format(account)
    if len(self.sql_ex(sql_s, (href,))) == 0:
        return False
    else:
        return True
# Buggy code
def get_etag(self, href, account):
    """get etag for href

    type href: str()
    return: etag
    rtype: str()
    """
    sql_s = "SELECT etag FROM {0} WHERE href=(?);".format(account + "_m")
    etag = self.sql_ex(sql_s, (href,))[0][0]
    return etag


# Traceback (sqlite3.OperationalError)
Traceback (most recent call last):
File "/home/catern/src/khal/virt/bin/khal", line 5, in <module>
pkg_resources.run_script('khal==0.1.0.dev', 'khal')
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 540, in run_script
self.require(requires)[0].run_script(script_name, ns)
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 1462, in run_script
exec_(script_code, namespace, namespace)
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 41, in exec_
exec("""exec code in globs, locs""")
File "<string>", line 1, in <module>
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/khal-0.1.0.dev-py2.7.egg/EGG-INFO/scripts/khal", line 72, in <module>

File "build/bdist.linux-x86_64/egg/khal/controllers.py", line 178, in __init__
File "build/bdist.linux-x86_64/egg/khal/backend.py", line 440, in get_allday_range
File "build/bdist.linux-x86_64/egg/khal/backend.py", line 164, in sql_ex
sqlite3.OperationalError: no such table: simple_d

# Fixed code
def get_etag(self, href, account):
    """get etag for href

    type href: str()
    return: etag
    rtype: str()
    """
    self._check_account(account)
    sql_s = "SELECT etag FROM {0} WHERE href=(?);".format(account + "_m")
    etag = self.sql_ex(sql_s, (href,))[0][0]
    return etag
# Buggy code
def delete(self, href, account):
    """
    removes the event from the db,
    returns nothing
    """
    logging.debug("locally deleting " + str(href))
    for dbname in [account + "_d", account + "_dt", account + "_m"]:
        sql_s = "DELETE FROM {0} WHERE href = ? ;".format(dbname)
        self.sql_ex(sql_s, (href,))


# Traceback (sqlite3.OperationalError)
Traceback (most recent call last):
File "/home/catern/src/khal/virt/bin/khal", line 5, in <module>
pkg_resources.run_script('khal==0.1.0.dev', 'khal')
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 540, in run_script
self.require(requires)[0].run_script(script_name, ns)
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 1462, in run_script
exec_(script_code, namespace, namespace)
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 41, in exec_
exec("""exec code in globs, locs""")
File "<string>", line 1, in <module>
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/khal-0.1.0.dev-py2.7.egg/EGG-INFO/scripts/khal", line 72, in <module>

File "build/bdist.linux-x86_64/egg/khal/controllers.py", line 178, in __init__
File "build/bdist.linux-x86_64/egg/khal/backend.py", line 440, in get_allday_range
File "build/bdist.linux-x86_64/egg/khal/backend.py", line 164, in sql_ex
sqlite3.OperationalError: no such table: simple_d

# Fixed code
def delete(self, href, account):
    """
    removes the event from the db,
    returns nothing
    """
    self._check_account(account)
    logging.debug("locally deleting " + str(href))
    for dbname in [account + "_d", account + "_dt", account + "_m"]:
        sql_s = "DELETE FROM {0} WHERE href = ? ;".format(dbname)
        self.sql_ex(sql_s, (href,))
# Buggy code
def get_all_href_from_db(self, accounts):
    """returns a list with all hrefs"""
    result = list()
    for account in accounts:
        hrefs = self.sql_ex("SELECT href FROM {0}".format(account + "_m"))
        result = result + [(href[0], account) for href in hrefs]
    return result


# Traceback (sqlite3.OperationalError)
Traceback (most recent call last):
File "/home/catern/src/khal/virt/bin/khal", line 5, in <module>
pkg_resources.run_script('khal==0.1.0.dev', 'khal')
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 540, in run_script
self.require(requires)[0].run_script(script_name, ns)
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 1462, in run_script
exec_(script_code, namespace, namespace)
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 41, in exec_
exec("""exec code in globs, locs""")
File "<string>", line 1, in <module>
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/khal-0.1.0.dev-py2.7.egg/EGG-INFO/scripts/khal", line 72, in <module>

File "build/bdist.linux-x86_64/egg/khal/controllers.py", line 178, in __init__
File "build/bdist.linux-x86_64/egg/khal/backend.py", line 440, in get_allday_range
File "build/bdist.linux-x86_64/egg/khal/backend.py", line 164, in sql_ex
sqlite3.OperationalError: no such table: simple_d

# Fixed code
def get_all_href_from_db(self, accounts):
    """returns a list with all hrefs"""
    result = list()
    for account in accounts:
        self._check_account(account)
        hrefs = self.sql_ex("SELECT href FROM {0}".format(account + "_m"))
        result = result + [(href[0], account) for href in hrefs]
    return result
# Buggy code
def get_all_href_from_db_not_new(self, accounts):
    """returns list of all not new hrefs"""
    result = list()
    for account in accounts:
        sql_s = "SELECT href FROM {0} WHERE status != (?)".format(account + "_m")
        stuple = (NEW,)
        hrefs = self.sql_ex(sql_s, stuple)
        result = result + [(href[0], account) for href in hrefs]
    return result


# Traceback (sqlite3.OperationalError)
Traceback (most recent call last):
File "/home/catern/src/khal/virt/bin/khal", line 5, in <module>
pkg_resources.run_script('khal==0.1.0.dev', 'khal')
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 540, in run_script
self.require(requires)[0].run_script(script_name, ns)
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 1462, in run_script
exec_(script_code, namespace, namespace)
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/pkg_resources.py", line 41, in exec_
exec("""exec code in globs, locs""")
File "<string>", line 1, in <module>
File "/home/catern/src/khal/virt/lib/python2.7/site-packages/khal-0.1.0.dev-py2.7.egg/EGG-INFO/scripts/khal", line 72, in <module>

File "build/bdist.linux-x86_64/egg/khal/controllers.py", line 178, in __init__
File "build/bdist.linux-x86_64/egg/khal/backend.py", line 440, in get_allday_range
File "build/bdist.linux-x86_64/egg/khal/backend.py", line 164, in sql_ex
sqlite3.OperationalError: no such table: simple_d

# Fixed code
def get_all_href_from_db_not_new(self, accounts):
    """returns list of all not new hrefs"""
    result = list()
    for account in accounts:
        self._check_account(account)
        sql_s = "SELECT href FROM {0} WHERE status != (?)".format(account + "_m")
        stuple = (NEW,)
        hrefs = self.sql_ex(sql_s, stuple)
        result = result + [(href[0], account) for href in hrefs]
    return result