# Buggy code
def __init__(self, db_filename, channels_dir, my_key, disable_sync=False):
    self.db_filename = db_filename
    self.channels_dir = channels_dir
    self.my_key = my_key
    self._logger = logging.getLogger(self.__class__.__name__)

    self._shutting_down = False
    self.batch_size = 10  # reasonable number, a little bit more than typically fits in a single UDP packet
    self.reference_timedelta = timedelta(milliseconds=100)
    self.sleep_on_external_thread = (
        0.05  # sleep this amount of seconds between batches executed on external thread
    )

    create_db = db_filename == ":memory:" or not os.path.isfile(self.db_filename)

    # We have to dynamically define/init ORM-managed entities here to be able to support
    # multiple sessions in Tribler. ORM-managed classes are bound to the database instance
    # at definition.
    self._db = orm.Database()

    # Possibly disable disk sync.
    # !!! ACHTUNG !!! This should be used only for special cases (e.g. DB upgrades), because
    # losing power during a write will corrupt the database.
    if disable_sync:
        # This attribute is internally called by Pony on startup, though pylint cannot detect it
        # with the static analysis.
        # pylint: disable=unused-variable
        @self._db.on_connect(provider="sqlite")
        def sqlite_disable_sync(_, connection):
            cursor = connection.cursor()
            cursor.execute("PRAGMA synchronous = 0")
            cursor.execute("PRAGMA temp_store = 2")

        # pylint: enable=unused-variable

    self.MiscData = misc.define_binding(self._db)

    self.TrackerState = tracker_state.define_binding(self._db)
    self.TorrentState = torrent_state.define_binding(self._db)

    self.clock = DiscreteClock(None if db_filename == ":memory:" else self.MiscData)

    self.ChannelNode = channel_node.define_binding(
        self._db, logger=self._logger, key=my_key, clock=self.clock
    )
    self.TorrentMetadata = torrent_metadata.define_binding(self._db)
    self.ChannelMetadata = channel_metadata.define_binding(self._db)
    self.ChannelVote = channel_vote.define_binding(self._db)
    self.ChannelPeer = channel_peer.define_binding(self._db)
    self.Vsids = vsids.define_binding(self._db)

    self.ChannelMetadata._channels_dir = channels_dir

    self._db.bind(provider="sqlite", filename=db_filename, create_db=create_db)
    if create_db:
        with db_session:
            self._db.execute(sql_create_fts_table)
    self._db.generate_mapping(
        create_tables=create_db
    )  # Must be run out of session scope
    if create_db:
        with db_session:
            self._db.execute(sql_add_fts_trigger_insert)
            self._db.execute(sql_add_fts_trigger_delete)
            self._db.execute(sql_add_fts_trigger_update)
            self._db.execute(sql_add_signature_index)
            self._db.execute(sql_add_public_key_index)
            self._db.execute(sql_add_infohash_index)

    if create_db:
        with db_session:
            self.MiscData(name="db_version", value=str(CURRENT_DB_VERSION))

    self.clock.init_clock()

    with db_session:
        default_vsids = self.Vsids.get(rowid=0)
        if not default_vsids:
            default_vsids = self.Vsids.create_default_vsids()
        self.ChannelMetadata.votes_scaling = default_vsids.max_val
        # Decay only happens while Tribler is running
        default_vsids.last_bump = datetime.utcnow()


# Traceback (RuntimeError)
ERROR:Executor:********** TRIBLER CRASHED **********
ERROR:Executor:Tribler crashed after uptime of 3195.03555894 sec! Stack trace: Traceback (most recent call last):
File "/usr/share/tribler/TriblerGUI/event_request_manager.py", line 114, in on_read_data
raise RuntimeError(json_dict["event"]["text"])
RuntimeError: [Failure instance: Traceback: <class 'pony.orm.dbapiprovider.OperationalError'>: database is locked
/usr/local/lib/python2.7/dist-packages/twisted/internet/base.py:1267:run
/usr/local/lib/python2.7/dist-packages/twisted/internet/base.py:1276:mainLoop
/usr/local/lib/python2.7/dist-packages/twisted/internet/base.py:902:runUntilCurrent
/usr/local/lib/python2.7/dist-packages/twisted/internet/task.py:239:__call__
--- <exception caught here> ---
/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py:151:maybeDeferred
/usr/share/tribler/Tribler/Core/TorrentChecker/torrent_checker.py:111:check_random_tracker
/usr/share/tribler/Tribler/Core/TorrentChecker/torrent_checker.py:187:get_valid_next_tracker_for_auto_check
/usr/share/tribler/Tribler/Core/TorrentChecker/torrent_checker.py:194:get_next_tracker_for_auto_check
<auto generated wrapper of get_next_tracker_for_auto_check() function>:2:get_next_tracker_for_auto_check
/home/tribler/.local/lib/python2.7/site-packages/pony/orm/core.py:528:new_func
/usr/share/tribler/Tribler/Core/Modules/tracker_manager.py:137:get_next_tracker_for_auto_check
/home/tribler/.local/lib/python2.7/site-packages/pony/orm/core.py:6279:__len__
/home/tribler/.local/lib/python2.7/site-packages/pony/orm/core.py:5778:_actual_fetch
/home/tribler/.local/lib/python2.7/site-packages/pony/orm/core.py:945:_exec_sql
/home/tribler/.local/lib/python2.7/site-packages/pony/orm/core.py:1776:reconnect
/home/tribler/.local/lib/python2.7/site-packages/pony/orm/core.py:943:_exec_sql
<auto generated wrapper of execute() function>:2:execute
/home/tribler/.local/lib/python2.7/site-packages/pony/orm/dbapiprovider.py:61:wrap_dbapi_exceptions
]

# Fixed code
def __init__(self, db_filename, channels_dir, my_key, disable_sync=False):
    self.db_filename = db_filename
    self.channels_dir = channels_dir
    self.my_key = my_key
    self._logger = logging.getLogger(self.__class__.__name__)

    self._shutting_down = False
    self.batch_size = 10  # reasonable number, a little bit more than typically fits in a single UDP packet
    self.reference_timedelta = timedelta(milliseconds=100)
    self.sleep_on_external_thread = (
        0.05  # sleep this amount of seconds between batches executed on external thread
    )

    create_db = db_filename == ":memory:" or not os.path.isfile(self.db_filename)

    # We have to dynamically define/init ORM-managed entities here to be able to support
    # multiple sessions in Tribler. ORM-managed classes are bound to the database instance
    # at definition.
    self._db = orm.Database()

    # Possibly disable disk sync.
    # !!! ACHTUNG !!! This should be used only for special cases (e.g. DB upgrades), because
    # losing power during a write will corrupt the database.
    if disable_sync:
        # This attribute is internally called by Pony on startup, though pylint cannot detect it
        # with the static analysis.
        # pylint: disable=unused-variable
        @self._db.on_connect(provider="sqlite")
        def sqlite_disable_sync(_, connection):
            cursor = connection.cursor()
            cursor.execute("PRAGMA synchronous = 0")
            cursor.execute("PRAGMA temp_store = 2")

        # pylint: enable=unused-variable

    self.MiscData = misc.define_binding(self._db)

    self.TrackerState = tracker_state.define_binding(self._db)
    self.TorrentState = torrent_state.define_binding(self._db)

    self.clock = DiscreteClock(None if db_filename == ":memory:" else self.MiscData)

    self.ChannelNode = channel_node.define_binding(
        self._db, logger=self._logger, key=my_key, clock=self.clock
    )
    self.TorrentMetadata = torrent_metadata.define_binding(self._db)
    self.ChannelMetadata = channel_metadata.define_binding(self._db)
    self.ChannelVote = channel_vote.define_binding(self._db)
    self.ChannelPeer = channel_peer.define_binding(self._db)
    self.Vsids = vsids.define_binding(self._db)

    self.ChannelMetadata._channels_dir = channels_dir

    self._db.bind(
        provider="sqlite", filename=db_filename, create_db=create_db, timeout=120.0
    )
    if create_db:
        with db_session:
            self._db.execute(sql_create_fts_table)
    self._db.generate_mapping(
        create_tables=create_db
    )  # Must be run out of session scope
    if create_db:
        with db_session:
            self._db.execute(sql_add_fts_trigger_insert)
            self._db.execute(sql_add_fts_trigger_delete)
            self._db.execute(sql_add_fts_trigger_update)
            self._db.execute(sql_add_signature_index)
            self._db.execute(sql_add_public_key_index)
            self._db.execute(sql_add_infohash_index)

    if create_db:
        with db_session:
            self.MiscData(name="db_version", value=str(CURRENT_DB_VERSION))

    self.clock.init_clock()

    with db_session:
        default_vsids = self.Vsids.get(rowid=0)
        if not default_vsids:
            default_vsids = self.Vsids.create_default_vsids()
        self.ChannelMetadata.votes_scaling = default_vsids.max_val
        # Decay only happens while Tribler is running
        default_vsids.last_bump = datetime.utcnow()