gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _get_series_info(self, task, config, series_name, series_url):
    log.info("Retrieving series info for %s", series_name)
    response = requests.get(series_url)
    page = get_soup(response.content)
    tvseries = page.find(
        "div", itemscope="itemscope", itemtype="https://schema.org/TVSeries"
    )
    series_info = (
        Entry()
    )  # create a stub to store the common values for all episodes of this series
    series_info["npo_url"] = tvseries.find("a", itemprop="url")["href"]
    series_info["npo_name"] = tvseries.find("span", itemprop="name").contents[0]
    series_info["npo_description"] = tvseries.find(
        "span", itemprop="description"
    ).contents[0]
    series_info["npo_language"] = tvseries.find("span", itemprop="inLanguage").contents[
        0
    ]

    return series_info


# Traceback (AttributeError)
2017-07-05 20:31 CRITICAL task tv-journaal BUG: Unhandled error in plugin npo_watchlist: 'NoneType' object has no attribute 'find'
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flexget/task.py", line 486, in __run_plugin
return method(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flexget/event.py", line 23, in call
return self.func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flexget/plugins/input/npo_watchlist.py", line 326, in on_task_input
entries += self._get_favorites_entries(task, config)
File "/usr/local/lib/python2.7/dist-packages/flexget/plugins/input/npo_watchlist.py", line 318, in _get_favorites_entries
series_info = self._get_series_info(task, config, series_name, url)
File "/usr/local/lib/python2.7/dist-packages/flexget/plugins/input/npo_watchlist.py", line 180, in _get_series_info
series_info['npo_url'] = tvseries.find('a', itemprop='url')['href']
AttributeError: 'NoneType' object has no attribute 'find'

# Fixed code
def _get_series_info(self, task, config, episode_name, episode_url):
    log.info("Retrieving series info for %s", episode_name)
    try:
        response = requests.get(episode_url)
        page = get_soup(response.content)

        series_url = page.find("a", class_="npo-episode-header-program-info")["href"]

        if series_url not in self._series_info:
            response = requests.get(series_url)
            page = get_soup(response.content)

            series_info = self._parse_series_info(task, config, page, series_url)
            self._series_info[series_url] = series_info

        return self._series_info[series_url]
    except RequestException as e:
        raise plugin.PluginError("Request error: %s" % e.args[0])
# Buggy code
def on_task_input(self, task, config):
    entries = self._get_watchlist_entries(task, config)
    entries += self._get_favorites_entries(task, config)

    return entries


# Traceback (AttributeError)
2017-07-05 20:31 CRITICAL task tv-journaal BUG: Unhandled error in plugin npo_watchlist: 'NoneType' object has no attribute 'find'
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flexget/task.py", line 486, in __run_plugin
return method(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flexget/event.py", line 23, in call
return self.func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flexget/plugins/input/npo_watchlist.py", line 326, in on_task_input
entries += self._get_favorites_entries(task, config)
File "/usr/local/lib/python2.7/dist-packages/flexget/plugins/input/npo_watchlist.py", line 318, in _get_favorites_entries
series_info = self._get_series_info(task, config, series_name, url)
File "/usr/local/lib/python2.7/dist-packages/flexget/plugins/input/npo_watchlist.py", line 180, in _get_series_info
series_info['npo_url'] = tvseries.find('a', itemprop='url')['href']
AttributeError: 'NoneType' object has no attribute 'find'

# Fixed code
def on_task_input(self, task, config):
    email = config.get("email")
    log.info("Retrieving npo.nl watchlist for %s", email)

    response = self._get_page(task, config, "https://www.npo.nl/mijn_npo")
    page = get_soup(response.content)

    entries = self._get_watchlist_entries(task, config, page)
    entries += self._get_favorites_entries(task, config, page)

    return entries
# Buggy code
def is_archive(path):
    """
    Attempts to open an entry as an archive; returns True on success, False on failure.
    """

    archive = None

    try:
        archive = open_archive(path)
        if archive:
            archive.close()
            return True
    except ArchiveError as error:
        error_message = "Failed to open file as archive: %s (%s)" % (path, error)
        log.debug(error_message)

    return False


# Traceback (IOError)
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/flexget/task.py", line 477, in __run_plugin
return method(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/flexget/event.py", line 23, in __call__
return self.func(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/flexget/plugins/filter/archives.py", line 65, in on_task_filter
if archive.is_archive(archive_path):
File "/usr/local/lib/python2.7/site-packages/flexget/utils/archive.py", line 207, in is_archive
archive = open_archive(path)
File "/usr/local/lib/python2.7/site-packages/flexget/utils/archive.py", line 189, in open_archive
elif rarfile and rarfile.is_rarfile(archive_path):
File "/usr/local/lib/python2.7/site-packages/rarfile.py", line 362, in is_rarfile
fd = XFile(xfile)
File "/usr/local/lib/python2.7/site-packages/rarfile.py", line 1755, in __init__
self._fd = open(xfile, 'rb', bufsize)
IOError: [Errno 21] Is a directory: u'/Volumes/Drobo/downloads/tv/

# Fixed code
def is_archive(path):
    """
    Attempts to open an entry as an archive; returns True on success, False on failure.
    """

    archive = None

    try:
        archive = open_archive(path)
        if archive:
            archive.close()
            return True
    except (IOError, ArchiveError) as error:
        log.debug("Failed to open file as archive: %s (%s)", path, error)

    return False
# Buggy code
def execute_cmd(self, cmd, allow_background, encoding):
    log.verbose("Executing: %s" % cmd)
    # if PY2: cmd = cmd.encode(encoding) ?
    p = subprocess.Popen(
        cmd,
        shell=True,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        close_fds=False,
    )
    if not allow_background:
        (r, w) = (p.stdout, p.stdin)
        response = native_str_to_text(r.read(), encoding=encoding, errors="replace")
        r.close()
        w.close()
        if response:
            log.info("Stdout: %s" % response)
    return p.wait()


# Traceback (UnicodeEncodeError)
2016-07-25 11:58 CRITICAL task          remove-folders  BUG: Unhandled error in plugin exec: 'ascii' codec can't encode character u'\xf1' in position 124: ordinal not in range(128)
Traceback (most recent call last):
File "c:\python27\lib\site-packages\flexget\task.py", line 444, in __run_plugin
return method(*args, **kwargs)
File "c:\python27\lib\site-packages\flexget\event.py", line 23, in __call__
return self.func(*args, **kwargs)
File "c:\python27\lib\site-packages\flexget\plugins\output\exec.py", line 192, in phase_handler
self.execute(task, 'on_' + phase, config)
File "c:\python27\lib\site-packages\flexget\plugins\output\exec.py", line 163, in execute
if (self.execute_cmd(cmd, allow_background, config['encoding']) != 0 and
File "c:\python27\lib\site-packages\flexget\plugins\output\exec.py", line 109, in execute_cmd
stderr=subprocess.STDOUT, close_fds=False)
File "c:\python27\lib\subprocess.py", line 711, in __init__
errread, errwrite)
File "c:\python27\lib\subprocess.py", line 929, in _execute_child
args = '{} /c "{}"'.format (comspec, args)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 124: ordinal not in range(128)

# Fixed code
def execute_cmd(self, cmd, allow_background, encoding):
    log.verbose("Executing: %s", cmd)
    p = subprocess.Popen(
        text_to_native_str(cmd, encoding=io_encoding),
        shell=True,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        close_fds=False,
    )
    if not allow_background:
        r, w = (p.stdout, p.stdin)
        response = r.read().decode(io_encoding)
        r.close()
        w.close()
        if response:
            log.info("Stdout: %s", response.rstrip())  # rstrip to get rid of newlines
    return p.wait()
# Buggy code
def url_rewrite(self, task, entry):
    series_url = entry["url"]
    search_title = re.sub("\[.*\] ", "", entry["title"])

    self.config = task.config.get("serienjunkies") or {}
    self.config.setdefault("hoster", DEFAULT_HOSTER)
    self.config.setdefault("language", DEFAULT_LANGUAGE)

    download_urls = self.parse_downloads(series_url, search_title)
    if not download_urls:
        entry.reject("No Episode found")
    else:
        entry["url"] = download_urls[-1]
        entry["description"] = ", ".join(download_urls)

    # Debug Information
    log.debug("TV Show URL: %s" % series_url)
    log.debug("Episode: %s" % search_title)
    log.debug("Download URL: %s" % download_urls)


# Traceback (ValueError)
2016-09-16 21:34 DEBUG    urlrewriter   serienjk_de_local Checking 2 entries
2016-09-16 21:34 DEBUG    urlrewriter   serienjk_de_local Url rewriting http://serienjunkies.org/gotham/gotham-staffel-2-blu-ray-sd720p1080p/
2016-09-16 21:34 DEBUG    utils.requests serienjk_de_local Fetching http://serienjunkies.org/gotham/gotham-staffel-2-blu-ray-sd720p1080p/
2016-09-16 21:34 DEBUG    serienjunkies serienjk_de_local Title seems to describe multiple episodes
2016-09-16 21:34 DEBUG    plugin        serienjk_de_local decorator caught ValueError. handled traceback:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flexget/plugin.py", line 118, in wrapped_func
return func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flexget/plugins/sites/serienjunkies.py", line 116, in parse_downloads
if not self.check_language(episode_lang):
File "/usr/local/lib/python2.7/dist-packages/flexget/plugins/sites/serienjunkies.py", line 169, in check_language
languages = languages[:languages.index("+")]
ValueError: substring not found
2016-09-16 21:34 WARNING  urlrewriter   serienjk_de_local URL rewriting serienjunkies failed: substring not found

# Fixed code
def url_rewrite(self, task, entry):
    series_url = entry["url"]
    search_title = re.sub("\[.*\] ", "", entry["title"])

    self.config = task.config.get("serienjunkies") or {}
    self.config.setdefault("hoster", DEFAULT_HOSTER)
    self.config.setdefault("language", DEFAULT_LANGUAGE)

    download_urls = self.parse_downloads(series_url, search_title)
    if not download_urls:
        entry.reject("No Episode found")
    else:
        entry["url"] = download_urls[-1]
        entry["description"] = ", ".join(download_urls)

    # Debug Information
    log.debug("TV Show URL: %s", series_url)
    log.debug("Episode: %s", search_title)
    log.debug("Download URL: %s", download_urls)
# Buggy code
def invalidate_cache(self):
    self._items = None


# Traceback (TypeError)
2016-04-11 20:53 DEBUG    manager       imdb            Traceback:
Traceback (most recent call last):
File "c:\python27\lib\site-packages\flexget\task.py", line 438, in __run_plugin
return method(*args, **kwargs)
File "c:\python27\lib\site-packages\flexget\event.py", line 22, in __call__
return self.func(*args, **kwargs)
File "c:\python27\lib\site-packages\flexget\plugins\output\list_remove.py", line 36, in on_task_output
thelist -= task.accepted
File "c:\python27\lib\_abcoll.py", line 356, in __isub__
self.discard(value)
File "c:\python27\lib\site-packages\flexget\plugins\list\imdb_list.py", line 173, in discard
self._items = [i for i in self._items if i['imdb_id'] != entry['imdb_id']]
TypeError: 'NoneType' object is not iterable

# Fixed code
def invalidate_cache(self):
    self._items = []
# Buggy code
def invalidate_cache(self):
    self._items = []


# Traceback (TypeError)
2016-04-11 20:53 DEBUG    manager       imdb            Traceback:
Traceback (most recent call last):
File "c:\python27\lib\site-packages\flexget\task.py", line 438, in __run_plugin
return method(*args, **kwargs)
File "c:\python27\lib\site-packages\flexget\event.py", line 22, in __call__
return self.func(*args, **kwargs)
File "c:\python27\lib\site-packages\flexget\plugins\output\list_remove.py", line 36, in on_task_output
thelist -= task.accepted
File "c:\python27\lib\_abcoll.py", line 356, in __isub__
self.discard(value)
File "c:\python27\lib\site-packages\flexget\plugins\list\imdb_list.py", line 173, in discard
self._items = [i for i in self._items if i['imdb_id'] != entry['imdb_id']]
TypeError: 'NoneType' object is not iterable

# Fixed code
def invalidate_cache(self):
    self._items = None
# Buggy code
def select(self, selection: Union[QModelIndex, QItemSelection], flags: int):
    """
    (De)Select given rows

    Args:
        selection (QModelIndex or QItemSelection):
            rows to select; indices refer to the proxy model, not the source
        flags (QItemSelectionModel.SelectionFlags):
            flags that tell whether to Clear, Select, Deselect or Toggle
    """
    if isinstance(selection, QModelIndex):
        rows = {selection.model().mapToSource(selection).row()}
    else:
        indices = selection.indexes()
        if indices:
            selection = indices[0].model().mapSelectionToSource(selection)
            rows = {index.row() for index in selection.indexes()}
        else:
            rows = set()
    self.select_rows(rows, flags)


# Traceback (AttributeError)
-------------------------- AttributeError Exception ---------------------------
Traceback (most recent call last):
File "/Users/ajda/orange/orange3/Orange/widgets/evaluate/owpredictions.py", line 1130, in select
self.store.select(selection, flags)
File "/Users/ajda/orange/orange3/Orange/widgets/evaluate/owpredictions.py", line 1057, in select
rows = {selection.model().mapToSource(selection).row()}
AttributeError: 'NoneType' object has no attribute 'mapToSource'
-------------------------------------------------------------------------------

# Fixed code
def select(self, selection: Union[QModelIndex, QItemSelection], flags: int):
    """
    (De)Select given rows

    Args:
        selection (QModelIndex or QItemSelection):
            rows to select; indices refer to the proxy model, not the source
        flags (QItemSelectionModel.SelectionFlags):
            flags that tell whether to Clear, Select, Deselect or Toggle
    """
    if isinstance(selection, QModelIndex):
        if selection.model() is not None:
            rows = {selection.model().mapToSource(selection).row()}
        else:
            rows = set()
    else:
        indices = selection.indexes()
        if indices:
            selection = indices[0].model().mapSelectionToSource(selection)
            rows = {index.row() for index in selection.indexes()}
        else:
            rows = set()
    self.select_rows(rows, flags)
# Buggy code
def _emit_changed(self):
    """
    A context manager that calls `emit_selection_rows_changed after
    changing a selection.
    """

    def map_from_source(rows):
        from_src = self.proxy.mapFromSource
        index = self.proxy.sourceModel().index
        return {from_src(index(row, 0)).row() for row in rows}

    old_rows = self._rows.copy()
    try:
        yield
    finally:
        deselected = map_from_source(old_rows - self._rows)
        selected = map_from_source(self._rows - old_rows)
        if selected or deselected:
            for model in self._selection_models:
                model.emit_selection_rows_changed(selected, deselected)


# Traceback (AttributeError)
-------------------------- AttributeError Exception ---------------------------
Traceback (most recent call last):
File "/Users/ajda/orange/orange3/Orange/widgets/evaluate/owpredictions.py", line 1130, in select
self.store.select(selection, flags)
File "/Users/ajda/orange/orange3/Orange/widgets/evaluate/owpredictions.py", line 1057, in select
rows = {selection.model().mapToSource(selection).row()}
AttributeError: 'NoneType' object has no attribute 'mapToSource'
-------------------------------------------------------------------------------

# Fixed code
def _emit_changed(self):
    """
    A context manager that calls `emit_selection_rows_changed after
    changing a selection.
    """

    def map_from_source(rows):
        from_src = self.proxy.mapFromSource
        index = self.proxy.sourceModel().index
        return {from_src(index(row, 0)).row() for row in rows}

    old_rows = self._rows.copy()
    try:
        yield
    finally:
        if self.proxy.sourceModel() is not None:
            deselected = map_from_source(old_rows - self._rows)
            selected = map_from_source(self._rows - old_rows)
            if selected or deselected:
                for model in self._selection_models:
                    model.emit_selection_rows_changed(selected, deselected)
# Buggy code
def settings_to_widget(self, widget, *_args):
    context = widget.current_context
    if context is None:
        return
    pairs = context.values.get("attr_pairs", [])
    widget.attr_pairs = [self.decode_pair(widget, pair) for pair in pairs]


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangecanvas/scheme/signalmanager.py", line 936, in __process_next
if self.__process_next_helper(use_max_active=True):
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangecanvas/scheme/signalmanager.py", line 974, in __process_next_helper
self.process_node(selected_node)
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangecanvas/scheme/signalmanager.py", line 605, in process_node
self.send_to_node(node, signals_in)
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/workflow/widgetsscheme.py", line 792, in send_to_node
self.process_signals_for_widget(node, widget, signals)
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/workflow/widgetsscheme.py", line 833, in process_signals_for_widget
widget.handleNewSignals()
File "/Users/ajda/orange/orange3/Orange/widgets/data/owmergedata.py", line 364, in handleNewSignals
self.openContext(self.data and self.data.domain,
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/widget.py", line 994, in openContext
self.settingsHandler.open_context(self, *a)
File "/Users/ajda/orange/orange3/Orange/widgets/data/owmergedata.py", line 190, in open_context
super().open_context(widget,
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/settings.py", line 816, in open_context
self.find_or_create_context(widget, *args)
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/settings.py", line 848, in find_or_create_context
best_context, best_score = self.find_context(self.global_contexts, args,
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/settings.py", line 868, in find_context
score = self.match(context, *args)
File "/Users/ajda/orange/orange3/Orange/widgets/data/owmergedata.py", line 235, in match
left, right = zip(*context.values["attr_pairs"])
KeyError: 'attr_pairs'

# Fixed code
def settings_to_widget(self, widget, *_args):
    context = widget.current_context
    if context is None:
        return
    pairs = context.values.get("attr_pairs")
    if pairs:
        # attr_pairs is schema only setting which means it is not always
        # present. When not present leave widgets default.
        widget.attr_pairs = [self.decode_pair(widget, pair) for pair in pairs]
# Buggy code
def match(self, context, variables1, variables2):
    def matches(part, variables):
        return all(
            var[1] == 100 and var[0] in variables or variables.get(var[0], -1) == var[1]
            for var in part
        )

    if (variables1, variables2) == (context.variables1, context.variables2):
        return self.PERFECT_MATCH

    left, right = zip(*context.values["attr_pairs"])
    if matches(left, variables1) and matches(right, variables2):
        return 0.5

    return self.NO_MATCH


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangecanvas/scheme/signalmanager.py", line 936, in __process_next
if self.__process_next_helper(use_max_active=True):
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangecanvas/scheme/signalmanager.py", line 974, in __process_next_helper
self.process_node(selected_node)
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangecanvas/scheme/signalmanager.py", line 605, in process_node
self.send_to_node(node, signals_in)
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/workflow/widgetsscheme.py", line 792, in send_to_node
self.process_signals_for_widget(node, widget, signals)
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/workflow/widgetsscheme.py", line 833, in process_signals_for_widget
widget.handleNewSignals()
File "/Users/ajda/orange/orange3/Orange/widgets/data/owmergedata.py", line 364, in handleNewSignals
self.openContext(self.data and self.data.domain,
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/widget.py", line 994, in openContext
self.settingsHandler.open_context(self, *a)
File "/Users/ajda/orange/orange3/Orange/widgets/data/owmergedata.py", line 190, in open_context
super().open_context(widget,
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/settings.py", line 816, in open_context
self.find_or_create_context(widget, *args)
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/settings.py", line 848, in find_or_create_context
best_context, best_score = self.find_context(self.global_contexts, args,
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/settings.py", line 868, in find_context
score = self.match(context, *args)
File "/Users/ajda/orange/orange3/Orange/widgets/data/owmergedata.py", line 235, in match
left, right = zip(*context.values["attr_pairs"])
KeyError: 'attr_pairs'

# Fixed code
def match(self, context, variables1, variables2):
    def matches(part, variables):
        return all(
            var[1] == 100 and var[0] in variables or variables.get(var[0], -1) == var[1]
            for var in part
        )

    if (variables1, variables2) == (context.variables1, context.variables2):
        return self.PERFECT_MATCH

    if "attr_pairs" in context.values:
        left, right = zip(*context.values["attr_pairs"])
        if matches(left, variables1) and matches(right, variables2):
            return 0.5

    return self.NO_MATCH
# Buggy code
def __eq__(self, other):
    if type(self) is not type(other):
        return False

    var1 = self._get_identical_source(self)
    var2 = self._get_identical_source(other)
    # pylint: disable=protected-access
    return var1.name == var2.name and var1._compute_value == var2._compute_value


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangecanvas/scheme/signalmanager.py", line 936, in __process_next
if self.__process_next_helper(use_max_active=True):
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangecanvas/scheme/signalmanager.py", line 974, in __process_next_helper
self.process_node(selected_node)
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangecanvas/scheme/signalmanager.py", line 605, in process_node
self.send_to_node(node, signals_in)
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/workflow/widgetsscheme.py", line 792, in send_to_node
self.process_signals_for_widget(node, widget, signals)
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/workflow/widgetsscheme.py", line 833, in process_signals_for_widget
widget.handleNewSignals()
File "/Users/ajda/orange/orange3/Orange/widgets/data/owmergedata.py", line 364, in handleNewSignals
self.openContext(self.data and self.data.domain,
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/widget.py", line 994, in openContext
self.settingsHandler.open_context(self, *a)
File "/Users/ajda/orange/orange3/Orange/widgets/data/owmergedata.py", line 190, in open_context
super().open_context(widget,
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/settings.py", line 816, in open_context
self.find_or_create_context(widget, *args)
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/settings.py", line 848, in find_or_create_context
best_context, best_score = self.find_context(self.global_contexts, args,
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/settings.py", line 868, in find_context
score = self.match(context, *args)
File "/Users/ajda/orange/orange3/Orange/widgets/data/owmergedata.py", line 235, in match
left, right = zip(*context.values["attr_pairs"])
KeyError: 'attr_pairs'

# Fixed code
def __eq__(self, other):
    if type(self) is not type(other):
        return False

    var1 = self._get_identical_source(self)
    var2 = self._get_identical_source(other)
    # pylint: disable=protected-access
    return (
        self.name == other.name
        and var1.name == var2.name
        and var1._compute_value == var2._compute_value
    )
# Buggy code
def __hash__(self):
    var = self._get_identical_source(self)
    return hash((var.name, type(self), var._compute_value))


# Traceback (KeyError)
Traceback (most recent call last):
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangecanvas/scheme/signalmanager.py", line 936, in __process_next
if self.__process_next_helper(use_max_active=True):
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangecanvas/scheme/signalmanager.py", line 974, in __process_next_helper
self.process_node(selected_node)
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangecanvas/scheme/signalmanager.py", line 605, in process_node
self.send_to_node(node, signals_in)
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/workflow/widgetsscheme.py", line 792, in send_to_node
self.process_signals_for_widget(node, widget, signals)
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/workflow/widgetsscheme.py", line 833, in process_signals_for_widget
widget.handleNewSignals()
File "/Users/ajda/orange/orange3/Orange/widgets/data/owmergedata.py", line 364, in handleNewSignals
self.openContext(self.data and self.data.domain,
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/widget.py", line 994, in openContext
self.settingsHandler.open_context(self, *a)
File "/Users/ajda/orange/orange3/Orange/widgets/data/owmergedata.py", line 190, in open_context
super().open_context(widget,
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/settings.py", line 816, in open_context
self.find_or_create_context(widget, *args)
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/settings.py", line 848, in find_or_create_context
best_context, best_score = self.find_context(self.global_contexts, args,
File "/Users/ajda/opt/miniconda3/envs/o3/lib/python3.8/site-packages/orangewidget/settings.py", line 868, in find_context
score = self.match(context, *args)
File "/Users/ajda/orange/orange3/Orange/widgets/data/owmergedata.py", line 235, in match
left, right = zip(*context.values["attr_pairs"])
KeyError: 'attr_pairs'

# Fixed code
def __hash__(self):
    var = self._get_identical_source(self)
    return hash((self.name, var.name, type(self), var._compute_value))
# Buggy code
def __init__(self, dist, group_val=None):
    self.dist = dist
    self.n = n = np.sum(dist[1])
    if n == 0:
        return
    self.a_min = float(dist[0, 0])
    self.a_max = float(dist[0, -1])
    self.mean = float(np.sum(dist[0] * dist[1]) / n)
    self.var = float(np.sum(dist[1] * (dist[0] - self.mean) ** 2) / n)
    self.dev = math.sqrt(self.var)
    a, freq = np.asarray(dist)
    q25, median, q75 = _quantiles(a, freq, [0.25, 0.5, 0.75])
    self.median = median
    # The code below omits the q25 or q75 in the plot when they are None
    self.q25 = None if q25 == median else q25
    self.q75 = None if q75 == median else q75
    self.data_range = ContDataRange(self.q25, self.q75, group_val)


# Traceback (TypeError)
Traceback (most recent call last):
File "/Users/ajda/orange/orange3/Orange/widgets/visualize/owboxplot.py", line 1119, in commit
selected = Values(self.conditions, conjunction=False)(self.dataset)
File "/Users/ajda/orange/orange3/Orange/data/filter.py", line 220, in __call__
return data._filter_values(self)
File "/Users/ajda/orange/orange3/Orange/data/table.py", line 1183, in _filter_values
selection = self._values_filter_to_indicator(filter)
File "/Users/ajda/orange/orange3/Orange/data/table.py", line 1213, in _values_filter_to_indicator
selection = self._filter_to_indicator(f)
File "/Users/ajda/orange/orange3/Orange/data/table.py", line 1240, in _filter_to_indicator
return self._values_filter_to_indicator(filter)
File "/Users/ajda/orange/orange3/Orange/data/table.py", line 1213, in _values_filter_to_indicator
selection = self._filter_to_indicator(f)
File "/Users/ajda/orange/orange3/Orange/data/table.py", line 1285, in _filter_to_indicator
return col_filter(col_indices[0])
File "/Users/ajda/orange/orange3/Orange/data/table.py", line 1269, in col_filter
return self._continuous_filter_to_indicator(filter, col)
File "/Users/ajda/orange/orange3/Orange/data/table.py", line 1331, in _continuous_filter_to_indicator
return self._range_filter_to_indicator(filter, col, filter.min, filter.max)
File "/Users/ajda/orange/orange3/Orange/data/table.py", line 1386, in _range_filter_to_indicator
return (col >= fmin) * (col <= fmax)
TypeError: '>=' not supported between instances of 'float' and 'NoneType'

# Fixed code
def __init__(self, dist, group_val=None):
    self.dist = dist
    self.n = n = np.sum(dist[1])
    if n == 0:
        return
    self.a_min = float(dist[0, 0])
    self.a_max = float(dist[0, -1])
    self.mean = float(np.sum(dist[0] * dist[1]) / n)
    self.var = float(np.sum(dist[1] * (dist[0] - self.mean) ** 2) / n)
    self.dev = math.sqrt(self.var)
    a, freq = np.asarray(dist)
    q25, median, q75 = _quantiles(a, freq, [0.25, 0.5, 0.75])
    self.median = median
    # The code below omits the q25 or q75 in the plot when they are None
    self.q25 = None if q25 == median else q25
    self.q75 = None if q75 == median else q75
    self.data_range = ContDataRange(q25, q75, group_val)
# Buggy code
def row_side_colors(self):
    var = self.annotation_color_var
    if var is None:
        return None
    column_data = column_data_from_table(self.input_data, var)
    span = (np.nanmin(column_data), np.nanmax(column_data))
    merges = self._merge_row_indices()
    if merges is not None:
        column_data = aggregate(var, column_data, merges)
    data, colormap = self._colorize(var, column_data)
    if var.is_continuous:
        colormap.span = span
    return data, colormap, var


# Traceback (AssertionError)
-------------------------- AssertionError Exception ---------------------------
Traceback (most recent call last):
File "/Users/ajda/orange/orange3/Orange/widgets/visualize/owheatmap.py", line 1112, in set_annotation_color_var
self.update_row_side_colors()
File "/Users/ajda/orange/orange3/Orange/widgets/visualize/owheatmap.py", line 1122, in update_row_side_colors
widget.setRowSideColorAnnotations(colors[0], colors[1], colors[2].name)
File "/Users/ajda/orange/orange3/Orange/widgets/visualize/utils/heatmap.py", line 731, in setRowSideColorAnnotations
self.__setColorAnnotationsHelper(
File "/Users/ajda/orange/orange3/Orange/widgets/visualize/utils/heatmap.py", line 823, in __setColorAnnotationsHelper
subset = colormap.apply(subset)
File "/Users/ajda/orange/orange3/Orange/widgets/visualize/utils/heatmap.py", line 114, in apply
low, high = self.adjust_levels(low, high)
File "/Users/ajda/orange/orange3/Orange/widgets/visualize/utils/heatmap.py", line 98, in adjust_levels
assert low <= high
AssertionError
-------------------------------------------------------------------------------

# Fixed code
def row_side_colors(self):
    var = self.annotation_color_var
    if var is None:
        return None
    column_data = column_data_from_table(self.input_data, var)
    merges = self._merge_row_indices()
    if merges is not None:
        column_data = aggregate(var, column_data, merges)
    data, colormap = self._colorize(var, column_data)
    if var.is_continuous:
        span = (np.nanmin(column_data), np.nanmax(column_data))
        if np.any(np.isnan(span)):
            span = 0.0, 1.0
        colormap.span = span
    return data, colormap, var
# Buggy code
def adjust_levels(self, low: float, high: float) -> Tuple[float, float]:
    """
    Adjust the data low, high levels by applying the thresholding and
    centering.
    """
    assert low <= high
    threshold_low, threshold_high = self.thresholds
    lt = low + (high - low) * threshold_low
    ht = low + (high - low) * threshold_high
    if self.center is not None:
        center = self.center
        maxoff = max(abs(center - lt), abs(center - ht))
        lt = center - maxoff
        ht = center + maxoff
    return lt, ht


# Traceback (AssertionError)
-------------------------- AssertionError Exception ---------------------------
Traceback (most recent call last):
File "/Users/ajda/orange/orange3/Orange/widgets/visualize/owheatmap.py", line 1112, in set_annotation_color_var
self.update_row_side_colors()
File "/Users/ajda/orange/orange3/Orange/widgets/visualize/owheatmap.py", line 1122, in update_row_side_colors
widget.setRowSideColorAnnotations(colors[0], colors[1], colors[2].name)
File "/Users/ajda/orange/orange3/Orange/widgets/visualize/utils/heatmap.py", line 731, in setRowSideColorAnnotations
self.__setColorAnnotationsHelper(
File "/Users/ajda/orange/orange3/Orange/widgets/visualize/utils/heatmap.py", line 823, in __setColorAnnotationsHelper
subset = colormap.apply(subset)
File "/Users/ajda/orange/orange3/Orange/widgets/visualize/utils/heatmap.py", line 114, in apply
low, high = self.adjust_levels(low, high)
File "/Users/ajda/orange/orange3/Orange/widgets/visualize/utils/heatmap.py", line 98, in adjust_levels
assert low <= high
AssertionError
-------------------------------------------------------------------------------

# Fixed code
def adjust_levels(self, low: float, high: float) -> Tuple[float, float]:
    """
    Adjust the data low, high levels by applying the thresholding and
    centering.
    """
    if np.any(np.isnan([low, high])):
        return np.nan, np.nan
    elif low > high:
        raise ValueError(f"low > high ({low} > {high})")
    threshold_low, threshold_high = self.thresholds
    lt = low + (high - low) * threshold_low
    ht = low + (high - low) * threshold_high
    if self.center is not None:
        center = self.center
        maxoff = max(abs(center - lt), abs(center - ht))
        lt = center - maxoff
        ht = center + maxoff
    return lt, ht
# Buggy code
def get_merge_attributes(self) -> List[str]:
    """
    Returns attributes that will be merged

    Returns
    -------
    List of attributes' to be merged names
    """
    counts = Counter(self.data)
    if self.selected_radio.isChecked():
        return self.selected_attributes
    elif self.n_values_radio.isChecked():
        keep_values = self.n_values_spin.value()
        values = counts.most_common()[keep_values:]
        indices = [i for i, _ in values]
    elif self.frequent_abs_radio.isChecked():
        indices = [
            v for v, c in counts.most_common() if c < self.frequent_abs_spin.value()
        ]
    else:  # self.frequent_rel_radio.isChecked():
        n_all = sum(counts.values())
        indices = [
            v
            for v, c in counts.most_common()
            if c / n_all * 100 < self.frequent_rel_spin.value()
        ]
    return np.array(self.variable.categories)[indices].tolist()


# Traceback (TypeError)
Traceback (most recent call last):
File "/Users/ajda/orange/orange3/Orange/widgets/data/oweditdomain.py", line 1451, in _merge_categories
dlg.get_merged_value_name(), dlg.get_merge_attributes()
File "/Users/ajda/orange/orange3/Orange/widgets/data/oweditdomain.py", line 817, in get_merge_attributes
counts = Counter(self.data)
File "/Users/ajda/miniconda3/envs/o3/lib/python3.7/collections/__init__.py", line 566, in __init__
self.update(*args, **kwds)
File "/Users/ajda/miniconda3/envs/o3/lib/python3.7/collections/__init__.py", line 653, in update
_count_elements(self, iterable)
TypeError: unhashable type: 'MaskedConstant'

# Fixed code
def get_merge_attributes(self) -> List[str]:
    """
    Returns attributes that will be merged

    Returns
    -------
    List of attributes' to be merged names
    """
    if self.selected_radio.isChecked():
        return self.selected_attributes

    if isinstance(self.data, MArray):
        non_nan = self.data[~self.data.mask]
    elif isinstance(self.data, np.ndarray):
        non_nan = self.data[~np.isnan(self.data)]
    else:  # list
        non_nan = [x for x in self.data if x is not None]

    counts = Counter(non_nan)
    if self.n_values_radio.isChecked():
        keep_values = self.n_values_spin.value()
        values = counts.most_common()[keep_values:]
        indices = [i for i, _ in values]
    elif self.frequent_abs_radio.isChecked():
        indices = [
            v for v, c in counts.most_common() if c < self.frequent_abs_spin.value()
        ]
    else:  # self.frequent_rel_radio.isChecked():
        n_all = sum(counts.values())
        indices = [
            v
            for v, c in counts.most_common()
            if c / n_all * 100 < self.frequent_rel_spin.value()
        ]

    indices = np.array(indices, dtype=int)  # indices must be ints
    return np.array(self.variable.categories)[indices].tolist()
# Buggy code
def on_selection_change(self, selection, action=SomView.SelectionSet):
    if self.selection is None:
        self.selection = np.zeros(self.grid_cells.T.shape, dtype=np.int16)
    if action == SomView.SelectionSet:
        self.selection[:] = 0
        self.selection[selection] = 1
    elif action == SomView.SelectionAddToGroup:
        self.selection[selection] = max(1, np.max(self.selection))
    elif action == SomView.SelectionNewGroup:
        self.selection[selection] = 1 + np.max(self.selection)
    elif action & SomView.SelectionRemove:
        self.selection[selection] = 0
    self.redraw_selection()
    self.update_output()


# Traceback (AttributeError)
-------------------------- AttributeError Exception ---------------------------
Traceback (most recent call last):
File "/home/matej/Documents/orange3/Orange/widgets/unsupervised/owsom.py", line 427, in on_selection_change
self.selection = np.zeros(self.grid_cells.T.shape, dtype=np.int16)
AttributeError: 'NoneType' object has no attribute 'T'
-------------------------------------------------------------------------------

# Fixed code
def on_selection_change(self, selection, action=SomView.SelectionSet):
    if self.data is None:  # clicks on empty canvas
        return
    if self.selection is None:
        self.selection = np.zeros(self.grid_cells.T.shape, dtype=np.int16)
    if action == SomView.SelectionSet:
        self.selection[:] = 0
        self.selection[selection] = 1
    elif action == SomView.SelectionAddToGroup:
        self.selection[selection] = max(1, np.max(self.selection))
    elif action == SomView.SelectionNewGroup:
        self.selection[selection] = 1 + np.max(self.selection)
    elif action & SomView.SelectionRemove:
        self.selection[selection] = 0
    self.redraw_selection()
    self.update_output()
# Buggy code
def __init__(self, column):
    super().__init__()
    self.column = column
    self.last_domain = None


# Traceback (TypeError)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "<string>", line 10, in <module>
File "C:\Users\reads\AppData\Local\Continuum\miniconda3\envs\orange-spectroscopy\lib\site-packages\Orange\data\filter.py", line 64, in __call__
return data._filter_is_defined(self.columns, self.negate)
File "C:\Users\reads\AppData\Local\Continuum\miniconda3\envs\orange-spectroscopy\lib\site-packages\Orange\data\table.py", line 1141, in _filter_is_defined
remove = np.logical_or(remove, bn.anynan([col], axis=0))
File "C:\Users\reads\AppData\Local\Continuum\miniconda3\envs\orange-spectroscopy\lib\site-packages\bottleneck\slow\reduce.py", line 86, in anynan
return np.isnan(a).any(axis)
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

# Fixed code
def __init__(self, column):
    super().__init__()
    self.column = column
# Buggy code
def __call__(self, inst):
    if inst.domain is not self.last_domain:
        self.cache_position(inst.domain)
    value = inst[self.pos_cache]
    if self.values is None:
        return not isnan(value)
    else:
        return value in self.values


# Traceback (TypeError)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "<string>", line 10, in <module>
File "C:\Users\reads\AppData\Local\Continuum\miniconda3\envs\orange-spectroscopy\lib\site-packages\Orange\data\filter.py", line 64, in __call__
return data._filter_is_defined(self.columns, self.negate)
File "C:\Users\reads\AppData\Local\Continuum\miniconda3\envs\orange-spectroscopy\lib\site-packages\Orange\data\table.py", line 1141, in _filter_is_defined
remove = np.logical_or(remove, bn.anynan([col], axis=0))
File "C:\Users\reads\AppData\Local\Continuum\miniconda3\envs\orange-spectroscopy\lib\site-packages\bottleneck\slow\reduce.py", line 86, in anynan
return np.isnan(a).any(axis)
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

# Fixed code
def __call__(self, inst):
    value = inst[inst.domain.index(self.column)]
    if self.values is None:
        return not isnan(value)
    else:
        return value in self.values
# Buggy code
def __call__(self, inst):
    if inst.domain is not self.last_domain:
        self.cache_position(inst.domain)
    value = inst[self.pos_cache]
    if isnan(value):
        return self.oper == self.Equal and isnan(self.ref)
    if self.oper == self.Equal:
        return value == self.ref
    if self.oper == self.NotEqual:
        return value != self.ref
    if self.oper == self.Less:
        return value < self.ref
    if self.oper == self.LessEqual:
        return value <= self.ref
    if self.oper == self.Greater:
        return value > self.ref
    if self.oper == self.GreaterEqual:
        return value >= self.ref
    if self.oper == self.Between:
        return self.ref <= value <= self.max
    if self.oper == self.Outside:
        return not self.ref <= value <= self.max
    if self.oper == self.IsDefined:
        return True
    raise ValueError("invalid operator")


# Traceback (TypeError)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "<string>", line 10, in <module>
File "C:\Users\reads\AppData\Local\Continuum\miniconda3\envs\orange-spectroscopy\lib\site-packages\Orange\data\filter.py", line 64, in __call__
return data._filter_is_defined(self.columns, self.negate)
File "C:\Users\reads\AppData\Local\Continuum\miniconda3\envs\orange-spectroscopy\lib\site-packages\Orange\data\table.py", line 1141, in _filter_is_defined
remove = np.logical_or(remove, bn.anynan([col], axis=0))
File "C:\Users\reads\AppData\Local\Continuum\miniconda3\envs\orange-spectroscopy\lib\site-packages\bottleneck\slow\reduce.py", line 86, in anynan
return np.isnan(a).any(axis)
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

# Fixed code
def __call__(self, inst):
    value = inst[inst.domain.index(self.column)]
    if isnan(value):
        return self.oper == self.Equal and isnan(self.ref)
    if self.oper == self.Equal:
        return value == self.ref
    if self.oper == self.NotEqual:
        return value != self.ref
    if self.oper == self.Less:
        return value < self.ref
    if self.oper == self.LessEqual:
        return value <= self.ref
    if self.oper == self.Greater:
        return value > self.ref
    if self.oper == self.GreaterEqual:
        return value >= self.ref
    if self.oper == self.Between:
        return self.ref <= value <= self.max
    if self.oper == self.Outside:
        return not self.ref <= value <= self.max
    if self.oper == self.IsDefined:
        return True
    raise ValueError("invalid operator")
# Buggy code
def __call__(self, inst):
    if inst.domain is not self.last_domain:
        self.cache_position(inst.domain)
    value = inst[self.pos_cache]
    if self.case_sensitive:
        return value in self._values
    else:
        return value.lower() in self.values_lower


# Traceback (TypeError)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "<string>", line 10, in <module>
File "C:\Users\reads\AppData\Local\Continuum\miniconda3\envs\orange-spectroscopy\lib\site-packages\Orange\data\filter.py", line 64, in __call__
return data._filter_is_defined(self.columns, self.negate)
File "C:\Users\reads\AppData\Local\Continuum\miniconda3\envs\orange-spectroscopy\lib\site-packages\Orange\data\table.py", line 1141, in _filter_is_defined
remove = np.logical_or(remove, bn.anynan([col], axis=0))
File "C:\Users\reads\AppData\Local\Continuum\miniconda3\envs\orange-spectroscopy\lib\site-packages\bottleneck\slow\reduce.py", line 86, in anynan
return np.isnan(a).any(axis)
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

# Fixed code
def __call__(self, inst):
    value = inst[inst.domain.index(self.column)]
    if self.case_sensitive:
        return value in self._values
    else:
        return value.lower() in self.values_lower