gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __init__(self, input_reader=None, output_writer=None):
    """Initializes the CLI tool object.

    Args:
      input_reader: optional input reader (instance of InputReader).
                    The default is None which indicates the use of the stdin
                    input reader.
      output_writer: optional output writer (instance of OutputWriter).
                     The default is None which indicates the use of the stdout
                     output writer.
    """
    super(PregTool, self).__init__(
        input_reader=input_reader, output_writer=output_writer
    )
    self._front_end = preg.PregFrontend()
    self._key_path = None
    self._knowledge_base_object = knowledge_base.KnowledgeBase()
    self._parse_restore_points = False
    self._path_resolvers = []
    self._verbose_output = False
    self._windows_directory = ""

    self.plugin_names = ""
    self.registry_file = ""
    self.run_mode = None
    self.source_type = None


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/local/bin/preg.py", line 5, in <module>
pkg_resources.run_script('plaso==1.3.0-20150715', u'preg.py')
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 492, in run_script
self.require(requires)[0].run_script(script_name, ns)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 1350, in run_script
execfile(script_filename, namespace, namespace)
File "/Library/Python/2.7/site-packages/plaso-1.3.0_20150715-py2.7.egg/EGG-INFO/scripts/preg.py", line 1711, in <module>
if not Main():
File "/Library/Python/2.7/site-packages/plaso-1.3.0_20150715-py2.7.egg/EGG-INFO/scripts/preg.py", line 1700, in Main
tool.RunModeRegistryPlugin()
File "/Library/Python/2.7/site-packages/plaso-1.3.0_20150715-py2.7.egg/EGG-INFO/scripts/preg.py", line 865, in RunModeRegistryPlugin
plugin_list = self.plugin_names.split(u',')
AttributeError: 'list' object has no attribute 'split'

# Fixed code
def __init__(self, input_reader=None, output_writer=None):
    """Initializes the CLI tool object.

    Args:
      input_reader: optional input reader (instance of InputReader).
                    The default is None which indicates the use of the stdin
                    input reader.
      output_writer: optional output writer (instance of OutputWriter).
                     The default is None which indicates the use of the stdout
                     output writer.
    """
    super(PregTool, self).__init__(
        input_reader=input_reader, output_writer=output_writer
    )
    self._front_end = preg.PregFrontend()
    self._key_path = None
    self._knowledge_base_object = knowledge_base.KnowledgeBase()
    self._parse_restore_points = False
    self._path_resolvers = []
    self._verbose_output = False
    self._windows_directory = ""

    self.plugin_names = []
    self.registry_file = ""
    self.run_mode = None
    self.source_type = None
# Buggy code
def VerifyRow(self, parser_mediator, row):
    """Verify that this is a McAfee AV Access Protection Log file.

    Args:
      parser_mediator: A parser mediator object (instance of ParserMediator).
      row: A single row from the CSV file.

    Returns:
      True if this is the correct parser, False otherwise.
    """
    if len(row) != 8:
        return False

    # This file can have a UTF-8 byte-order-marker at the beginning of
    # the first row.
    # TODO: Find out all the code pages this can have.  Asked McAfee 10/31.
    if row["date"][0:3] == b"\xef\xbb\xbf":
        row["date"] = row["date"][3:]

    # Check the date format!
    # If it doesn't pass, then this isn't a McAfee AV Access Protection Log
    timestamp = self._GetTimestamp(parser_mediator, row["date"], row["time"])
    if timestamp is None:
        return False

    # Use the presence of these strings as a backup or in case of partial file.
    if (
        not "Access Protection" in row["status"]
        and not "Would be blocked" in row["status"]
    ):
        return False

    return True


# Traceback (AttributeError)
Processing started.
Traceback (most recent call last):
File "./tools/log2timeline.py", line 696, in <module>
if not Main():
File "./tools/log2timeline.py", line 682, in Main
tool.ProcessSources()
File "./tools/log2timeline.py", line 624, in ProcessSources
timezone=self._timezone)
File "/home/onager/code/plaso/frontend/extraction_frontend.py", line 456, in ProcessSources
self._PreprocessSetTimezone(pre_obj, timezone=timezone)
File "/home/onager/code/plaso/frontend/extraction_frontend.py", line 322, in _PreprocessSetTimezone
pre_obj.zone = timezone
AttributeError: 'NoneType' object has no attribute 'zone'

# Fixed code
def VerifyRow(self, parser_mediator, row):
    """Verify that this is a McAfee AV Access Protection Log file.

    Args:
      parser_mediator: A parser mediator object (instance of ParserMediator).
      row: A single row from the CSV file.

    Returns:
      True if this is the correct parser, False otherwise.
    """
    if len(row) != 8:
        return False

    # This file can have a UTF-8 byte-order-marker at the beginning of
    # the first row.
    # TODO: Find out all the code pages this can have.  Asked McAfee 10/31.
    if row["date"][0:3] == b"\xef\xbb\xbf":
        row["date"] = row["date"][3:]
        self.encoding = "utf-8"

    # Check the date format!
    # If it doesn't pass, then this isn't a McAfee AV Access Protection Log
    timestamp = self._GetTimestamp(parser_mediator, row["date"], row["time"])
    if timestamp is None:
        return False

    # Use the presence of these strings as a backup or in case of partial file.
    if (
        not "Access Protection" in row["status"]
        and not "Would be blocked" in row["status"]
    ):
        return False

    return True
# Buggy code
def VerifyRow(self, unused_parser_mediator, unused_row):
    """Return a bool indicating whether or not this is the correct parser.

    Args:
      parser_mediator: a parser mediator object (instance of ParserMediator).
      row: a single row from the CSV file.

    Returns:
      True if this is the correct parser, False otherwise.
    """
    pass


# Traceback (AttributeError)
Processing started.
Traceback (most recent call last):
File "./tools/log2timeline.py", line 696, in <module>
if not Main():
File "./tools/log2timeline.py", line 682, in Main
tool.ProcessSources()
File "./tools/log2timeline.py", line 624, in ProcessSources
timezone=self._timezone)
File "/home/onager/code/plaso/frontend/extraction_frontend.py", line 456, in ProcessSources
self._PreprocessSetTimezone(pre_obj, timezone=timezone)
File "/home/onager/code/plaso/frontend/extraction_frontend.py", line 322, in _PreprocessSetTimezone
pre_obj.zone = timezone
AttributeError: 'NoneType' object has no attribute 'zone'

# Fixed code
def VerifyRow(self, unused_parser_mediator, unused_row):
    """Return a bool indicating whether or not this is the correct parser.

    Args:
      parser_mediator: a parser mediator object (instance of ParserMediator).
      row: a single row from the CSV file. Strings in this dict are binary
           strings, to aid in file verification.

    Returns:
      True if this is the correct parser, False otherwise.
    """
    pass
# Buggy code
def ParseRow(self, parser_mediator, row_offset, row):
    """Parse a line of the log file and extract event objects.

    Args:
      parser_mediator: a parser mediator object (instance of ParserMediator).
      row_offset: the offset of the row.
      row: a dictionary containing all the fields as denoted in the
           COLUMNS class list.
    """
    event_object = event.EventObject()
    if row_offset is not None:
        event_object.offset = row_offset
    event_object.row_dict = row
    parser_mediator.ProduceEvent(event_object)


# Traceback (AttributeError)
Processing started.
Traceback (most recent call last):
File "./tools/log2timeline.py", line 696, in <module>
if not Main():
File "./tools/log2timeline.py", line 682, in Main
tool.ProcessSources()
File "./tools/log2timeline.py", line 624, in ProcessSources
timezone=self._timezone)
File "/home/onager/code/plaso/frontend/extraction_frontend.py", line 456, in ProcessSources
self._PreprocessSetTimezone(pre_obj, timezone=timezone)
File "/home/onager/code/plaso/frontend/extraction_frontend.py", line 322, in _PreprocessSetTimezone
pre_obj.zone = timezone
AttributeError: 'NoneType' object has no attribute 'zone'

# Fixed code
def ParseRow(self, parser_mediator, row_offset, row):
    """Parse a line of the log file and extract event objects.

    Args:
      parser_mediator: a parser mediator object (instance of ParserMediator).
      row_offset: the offset of the row.
      row: a dictionary containing all the fields as denoted in the
           COLUMNS class list. Strings in this dict are unicode strings.
    """
    event_object = event.EventObject()
    if row_offset is not None:
        event_object.offset = row_offset
    event_object.row_dict = row
    parser_mediator.ProduceEvent(event_object)
# Buggy code
def ReportingComplete(self):
    """Called by an analysis plugin to signal that it has generated its report.

    This method signals to report consumers that no further reports will be
    produced by the analysis plugin.
    """
    self._analysis_report_queue_producer.Close()
    if self._completion_event:
        self._completion_event.set()


# Traceback (AttributeError)
PYTHONPATH=. ./tools/psort.py --analysis list

******************************* Analysis Plugins *******************************
Traceback (most recent call last):
File "./tools/psort.py", line 604, in <module>
if not Main():
File "./tools/psort.py", line 581, in Main
tool.ListAnalysisPlugins()
File "./tools/psort.py", line 297, in ListAnalysisPlugins
analysis_plugins = self._front_end.GetAnalysisPlugins()
File "/home/onager/code/plaso/plaso/frontend/psort.py", line 96, in GetAnalysisPlugins
return analysis_manager.AnalysisPluginManager.ListAllPluginNames()
File "/home/onager/code/plaso/plaso/analysis/manager.py", line 55, in ListAllPluginNames
for cls_obj in interface.AnalysisPlugin.classes.itervalues():
AttributeError: type object 'AnalysisPlugin' has no attribute 'classes'

# Fixed code
def ReportingComplete(self):
    """Called by an analysis plugin to signal that it has generated its report.

    This method signals to report consumers that no further reports will be
    produced by the analysis plugin.
    """
    if self._completion_event:
        self._completion_event.set()
    self._analysis_report_queue_producer.Close()
# Buggy code
def _AttemptAutoDetectTagFile(self, analysis_mediator):
    """Detect which tag file is most appropriate.

    Args:
      analysis_mediator: The analysis mediator (Instance of
                         AnalysisMediator).

    Returns:
      True if a tag file is autodetected, False otherwise.
    """
    self._autodetect_tag_file_attempt = True
    platform = analysis_mediator.GetPlatform()
    filename = self._OS_TAG_FILES.get(platform.lower(), None)
    if not filename:
        return False
    tag_file_path = os.path.join(analysis_mediator.GetDataLocation(), filename)
    self.SetAndLoadTagFile(tag_file_path)
    return True


# Traceback (AttributeError)
PYTHONPATH=. ./tools/psort.py --analysis list

******************************* Analysis Plugins *******************************
Traceback (most recent call last):
File "./tools/psort.py", line 604, in <module>
if not Main():
File "./tools/psort.py", line 581, in Main
tool.ListAnalysisPlugins()
File "./tools/psort.py", line 297, in ListAnalysisPlugins
analysis_plugins = self._front_end.GetAnalysisPlugins()
File "/home/onager/code/plaso/plaso/frontend/psort.py", line 96, in GetAnalysisPlugins
return analysis_manager.AnalysisPluginManager.ListAllPluginNames()
File "/home/onager/code/plaso/plaso/analysis/manager.py", line 55, in ListAllPluginNames
for cls_obj in interface.AnalysisPlugin.classes.itervalues():
AttributeError: type object 'AnalysisPlugin' has no attribute 'classes'

# Fixed code
def _AttemptAutoDetectTagFile(self, analysis_mediator):
    """Detect which tag file is most appropriate.

    Args:
      analysis_mediator: The analysis mediator (Instance of
                         AnalysisMediator).

    Returns:
      True if a tag file is autodetected, False otherwise.
    """
    self._autodetect_tag_file_attempt = True
    if not analysis_mediator.data_location:
        return False
    platform = analysis_mediator.platform
    filename = self._OS_TAG_FILES.get(platform.lower(), None)
    if not filename:
        return False
    logging.info("Using auto detected tag file: {0:s}".format(filename))
    tag_file_path = os.path.join(analysis_mediator.data_location, filename)
    self.SetAndLoadTagFile(tag_file_path)
    return True
# Buggy code
def _GetVirusTotalJSONResponse(self, hashes):
    """Makes a request to VirusTotal for information about hashes.

    Args:
      A list of file hashes (strings).

    Returns:
      The decoded JSON response from the VirusTotal API for the hashes.

    Raises:
      requests.ConnectionError: If it was not possible to connect to
                                VirusTotal.
      requests.exceptions.HTTPError: If the VirusTotal server returned an
                                     error code.
    """
    resource_string = ", ".join(hashes)
    params = {"apikey": self._api_key, "resource": resource_string}
    try:
        response = requests.get(self.VIRUSTOTAL_API_REPORT_URL, params=params)
        response.raise_for_status()
    except requests.ConnectionError as exception:
        error_string = "Unable to connect to VirusTotal: {0:s}".format(exception)
        raise errors.ConnectionError(error_string)
    except requests.HTTPError as exception:
        error_string = "VirusTotal returned a HTTP error: {0:s}".format(exception)
        raise errors.ConnectionError(error_string)
    json_response = response.json()
    return json_response


# Traceback (AttributeError)
PYTHONPATH=. ./tools/psort.py --analysis list

******************************* Analysis Plugins *******************************
Traceback (most recent call last):
File "./tools/psort.py", line 604, in <module>
if not Main():
File "./tools/psort.py", line 581, in Main
tool.ListAnalysisPlugins()
File "./tools/psort.py", line 297, in ListAnalysisPlugins
analysis_plugins = self._front_end.GetAnalysisPlugins()
File "/home/onager/code/plaso/plaso/frontend/psort.py", line 96, in GetAnalysisPlugins
return analysis_manager.AnalysisPluginManager.ListAllPluginNames()
File "/home/onager/code/plaso/plaso/analysis/manager.py", line 55, in ListAllPluginNames
for cls_obj in interface.AnalysisPlugin.classes.itervalues():
AttributeError: type object 'AnalysisPlugin' has no attribute 'classes'

# Fixed code
def _GetVirusTotalJSONResponse(self, hashes):
    """Makes a request to VirusTotal for information about hashes.

    Args:
      A list of file hashes (strings).

    Returns:
      The decoded JSON response from the VirusTotal API for the hashes.

    Raises:
      requests.ConnectionError: If it was not possible to connect to
                                VirusTotal.
      requests.exceptions.HTTPError: If the VirusTotal server returned an
                                     error code.
    """
    resource_string = ", ".join(hashes)
    params = {"apikey": self._api_key, "resource": resource_string}
    try:
        response = requests.get(self._VIRUSTOTAL_API_REPORT_URL, params=params)
        response.raise_for_status()
    except requests.ConnectionError as exception:
        error_string = "Unable to connect to VirusTotal: {0:s}".format(exception)
        raise errors.ConnectionError(error_string)
    except requests.HTTPError as exception:
        error_string = "VirusTotal returned a HTTP error: {0:s}".format(exception)
        raise errors.ConnectionError(error_string)
    json_response = response.json()
    return json_response
# Buggy code
def ParseOptions(cls, options, analysis_plugin):
    """Parses and validates options.

    Args:
      options: the parser option object (instance of argparse.Namespace).
      analysis_plugin: an analysis plugin (instance of OutputModule).

    Raises:
      BadConfigObject: when the output module object is of the wrong type.
      BadConfigOption: when a configuration parameter fails validation.
    """
    if not isinstance(analysis_plugin, tagging.TaggingPlugin):
        raise errors.BadConfigObject(
            "Analysis plugin is not an instance of TaggingPlugin"
        )

    tagging_file = getattr(options, "tagging_file", None)
    if tagging_file is None:
        raise errors.BadConfigOption("Tagging file path not set.")

    analysis_plugin.SetAndLoadTagFile(tagging_file)


# Traceback (AttributeError)
PYTHONPATH=. ./tools/psort.py --analysis list

******************************* Analysis Plugins *******************************
Traceback (most recent call last):
File "./tools/psort.py", line 604, in <module>
if not Main():
File "./tools/psort.py", line 581, in Main
tool.ListAnalysisPlugins()
File "./tools/psort.py", line 297, in ListAnalysisPlugins
analysis_plugins = self._front_end.GetAnalysisPlugins()
File "/home/onager/code/plaso/plaso/frontend/psort.py", line 96, in GetAnalysisPlugins
return analysis_manager.AnalysisPluginManager.ListAllPluginNames()
File "/home/onager/code/plaso/plaso/analysis/manager.py", line 55, in ListAllPluginNames
for cls_obj in interface.AnalysisPlugin.classes.itervalues():
AttributeError: type object 'AnalysisPlugin' has no attribute 'classes'

# Fixed code
def ParseOptions(cls, options, analysis_plugin):
    """Parses and validates options.

    Args:
      options: the parser option object (instance of argparse.Namespace).
      analysis_plugin: an analysis plugin (instance of OutputModule).

    Raises:
      BadConfigObject: when the output module object is of the wrong type.
      BadConfigOption: when a configuration parameter fails validation.
    """
    if not isinstance(analysis_plugin, tagging.TaggingPlugin):
        raise errors.BadConfigObject(
            "Analysis plugin is not an instance of TaggingPlugin"
        )

    tagging_file = getattr(options, "tagging_file", None)
    if tagging_file:
        if not os.path.exists(tagging_file) or not os.path.isfile(tagging_file):
            raise errors.BadConfigOption(
                "Tagging file {0:s} does not exist.".format(tagging_file)
            )
        analysis_plugin.SetAndLoadTagFile(tagging_file)
# Buggy code
def __init__(self):
    """Initialize the knowledge base object."""
    super(KnowledgeBase, self).__init__()

    # TODO: the first versions of the knowledge base will wrap the pre-process
    # object, but this should be replaced by an artifact style knowledge base
    # or artifact cache.
    self._pre_obj = event.PreprocessObject()

    self._default_codepage = "cp1252"
    self._default_timezone = pytz.timezone("UTC")


# Traceback (AttributeError)
PYTHONPATH=. ./tools/psort.py --analysis list

******************************* Analysis Plugins *******************************
Traceback (most recent call last):
File "./tools/psort.py", line 604, in <module>
if not Main():
File "./tools/psort.py", line 581, in Main
tool.ListAnalysisPlugins()
File "./tools/psort.py", line 297, in ListAnalysisPlugins
analysis_plugins = self._front_end.GetAnalysisPlugins()
File "/home/onager/code/plaso/plaso/frontend/psort.py", line 96, in GetAnalysisPlugins
return analysis_manager.AnalysisPluginManager.ListAllPluginNames()
File "/home/onager/code/plaso/plaso/analysis/manager.py", line 55, in ListAllPluginNames
for cls_obj in interface.AnalysisPlugin.classes.itervalues():
AttributeError: type object 'AnalysisPlugin' has no attribute 'classes'

# Fixed code
def __init__(self, pre_obj=None):
    """Initialize the knowledge base object.

    Args:
        pre_obj: Optional preprocess object (instance of PreprocessObject.).
                 The default is None, which indicates the KnowledgeBase should
                 create a new PreprocessObject.
    """
    super(KnowledgeBase, self).__init__()

    # TODO: the first versions of the knowledge base will wrap the pre-process
    # object, but this should be replaced by an artifact style knowledge base
    # or artifact cache.
    if pre_obj:
        self._pre_obj = pre_obj
    else:
        self._pre_obj = event.PreprocessObject()

    self._default_codepage = "cp1252"
    self._default_timezone = pytz.timezone("UTC")
# Buggy code
def __init__(self):
    """Initializes the front-end object."""
    super(AnalysisFrontend, self).__init__()
    self._storage_file_path = None


# Traceback (AttributeError)
PYTHONPATH=. ./tools/psort.py --analysis list

******************************* Analysis Plugins *******************************
Traceback (most recent call last):
File "./tools/psort.py", line 604, in <module>
if not Main():
File "./tools/psort.py", line 581, in Main
tool.ListAnalysisPlugins()
File "./tools/psort.py", line 297, in ListAnalysisPlugins
analysis_plugins = self._front_end.GetAnalysisPlugins()
File "/home/onager/code/plaso/plaso/frontend/psort.py", line 96, in GetAnalysisPlugins
return analysis_manager.AnalysisPluginManager.ListAllPluginNames()
File "/home/onager/code/plaso/plaso/analysis/manager.py", line 55, in ListAllPluginNames
for cls_obj in interface.AnalysisPlugin.classes.itervalues():
AttributeError: type object 'AnalysisPlugin' has no attribute 'classes'

# Fixed code
def __init__(self):
    """Initializes the front-end object."""
    super(AnalysisFrontend, self).__init__()
    self._data_location = None
    self._storage_file_path = None
# Buggy code
def ParseOptions(self, options):
    """Parses the options and initializes the front-end.

    Args:
      options: the command line arguments (instance of argparse.Namespace).

    Raises:
      BadConfigOption: if the options are invalid.
    """
    if not options:
        raise errors.BadConfigOption("Missing options.")

    self._storage_file_path = getattr(options, "storage_file", None)
    if not self._storage_file_path:
        raise errors.BadConfigOption("Missing storage file.")

    if not os.path.isfile(self._storage_file_path):
        raise errors.BadConfigOption(
            "No such storage file {0:s}.".format(self._storage_file_path)
        )

    self._data_location = getattr(options, "data_location", None)


# Traceback (AttributeError)
PYTHONPATH=. ./tools/psort.py --analysis list

******************************* Analysis Plugins *******************************
Traceback (most recent call last):
File "./tools/psort.py", line 604, in <module>
if not Main():
File "./tools/psort.py", line 581, in Main
tool.ListAnalysisPlugins()
File "./tools/psort.py", line 297, in ListAnalysisPlugins
analysis_plugins = self._front_end.GetAnalysisPlugins()
File "/home/onager/code/plaso/plaso/frontend/psort.py", line 96, in GetAnalysisPlugins
return analysis_manager.AnalysisPluginManager.ListAllPluginNames()
File "/home/onager/code/plaso/plaso/analysis/manager.py", line 55, in ListAllPluginNames
for cls_obj in interface.AnalysisPlugin.classes.itervalues():
AttributeError: type object 'AnalysisPlugin' has no attribute 'classes'

# Fixed code
def ParseOptions(self, options):
    """Parses the options and initializes the front-end.

    Args:
      options: the command line arguments (instance of argparse.Namespace).

    Raises:
      BadConfigOption: if the options are invalid.
    """
    if not options:
        raise errors.BadConfigOption("Missing options.")

    self._storage_file_path = getattr(options, "storage_file", None)
    if not self._storage_file_path:
        raise errors.BadConfigOption("Missing storage file.")

    if not os.path.isfile(self._storage_file_path):
        raise errors.BadConfigOption(
            "No such storage file {0:s}.".format(self._storage_file_path)
        )
# Buggy code
def __init__(self):
    """Initializes the front-end object."""
    super(PsortFrontend, self).__init__()

    self._analysis_process_info = []
    self._filter_buffer = None
    self._filter_expression = None
    self._filter_object = None
    self._output_filename = None
    self._output_file_object = None
    self._output_format = None
    self._preferred_language = "en-US"
    self._quiet_mode = False
    self._storage_file = None


# Traceback (AttributeError)
PYTHONPATH=. ./tools/psort.py --analysis list

******************************* Analysis Plugins *******************************
Traceback (most recent call last):
File "./tools/psort.py", line 604, in <module>
if not Main():
File "./tools/psort.py", line 581, in Main
tool.ListAnalysisPlugins()
File "./tools/psort.py", line 297, in ListAnalysisPlugins
analysis_plugins = self._front_end.GetAnalysisPlugins()
File "/home/onager/code/plaso/plaso/frontend/psort.py", line 96, in GetAnalysisPlugins
return analysis_manager.AnalysisPluginManager.ListAllPluginNames()
File "/home/onager/code/plaso/plaso/analysis/manager.py", line 55, in ListAllPluginNames
for cls_obj in interface.AnalysisPlugin.classes.itervalues():
AttributeError: type object 'AnalysisPlugin' has no attribute 'classes'

# Fixed code
def __init__(self):
    """Initializes the front-end object."""
    super(PsortFrontend, self).__init__()

    self._analysis_process_info = []
    self._data_location = None
    self._filter_buffer = None
    self._filter_expression = None
    self._filter_object = None
    self._output_filename = None
    self._output_file_object = None
    self._output_format = None
    self._preferred_language = "en-US"
    self._quiet_mode = False
    self._storage_file = None
# Buggy code
def GetAnalysisPluginsAndEventQueues(self, analysis_plugins):
    """Return a list of analysis plugins and event queues.

    Args:
      analysis_plugins: comma separated string with names of analysis
                        plugins to load.

    Returns:
      A tuple of two lists, one containing list of analysis plugins
      and the other a list of event queues.
    """
    if not analysis_plugins:
        return [], []

    # Start queues and load up plugins.
    event_queue_producers = []
    event_queues = []
    analysis_plugins_list = [name.strip() for name in analysis_plugins.split(",")]

    for _ in range(0, len(analysis_plugins_list)):
        # TODO: add upper queue limit.
        analysis_plugin_queue = multi_process.MultiProcessingQueue(timeout=5)
        event_queues.append(analysis_plugin_queue)
        event_queue_producers.append(queue.ItemQueueProducer(event_queues[-1]))

    analysis_plugins = analysis_manager.AnalysisPluginManager.LoadPlugins(
        analysis_plugins_list, event_queues
    )

    return analysis_plugins, event_queue_producers


# Traceback (AttributeError)
PYTHONPATH=. ./tools/psort.py --analysis list

******************************* Analysis Plugins *******************************
Traceback (most recent call last):
File "./tools/psort.py", line 604, in <module>
if not Main():
File "./tools/psort.py", line 581, in Main
tool.ListAnalysisPlugins()
File "./tools/psort.py", line 297, in ListAnalysisPlugins
analysis_plugins = self._front_end.GetAnalysisPlugins()
File "/home/onager/code/plaso/plaso/frontend/psort.py", line 96, in GetAnalysisPlugins
return analysis_manager.AnalysisPluginManager.ListAllPluginNames()
File "/home/onager/code/plaso/plaso/analysis/manager.py", line 55, in ListAllPluginNames
for cls_obj in interface.AnalysisPlugin.classes.itervalues():
AttributeError: type object 'AnalysisPlugin' has no attribute 'classes'

# Fixed code
def GetAnalysisPluginsAndEventQueues(self, analysis_plugins_string):
    """Return a list of analysis plugins and event queues.

    Args:
      analysis_plugins_string: comma separated string with names of analysis
                               plugins to load.

    Returns:
      A tuple of two lists, one containing list of analysis plugins
      and the other a list of event queues.
    """
    if not analysis_plugins_string:
        return [], []

    # Start queues and load up plugins.
    event_queue_producers = []
    event_queues = []
    analysis_plugins_list = [
        name.strip() for name in analysis_plugins_string.split(",")
    ]

    for _ in range(0, len(analysis_plugins_list)):
        # TODO: add upper queue limit.
        analysis_plugin_queue = multi_process.MultiProcessingQueue(timeout=5)
        event_queues.append(analysis_plugin_queue)
        event_queue_producers.append(queue.ItemQueueProducer(event_queues[-1]))

    analysis_plugins = analysis_manager.AnalysisPluginManager.LoadPlugins(
        analysis_plugins_list, event_queues
    )

    analysis_plugins = list(analysis_plugins)

    return analysis_plugins, event_queue_producers
# Buggy code
def AddEventObjects(self, event_objects):
    """Adds an event objects to the storage.

    Args:
      event_objects: a list or generator of event objects (instances of
                     EventObject).
    """
    for event_object in event_objects:
        self.AddEventObject(event_object)


# Traceback (AttributeError)
PYTHONPATH=. ./tools/psort.py --analysis list

******************************* Analysis Plugins *******************************
Traceback (most recent call last):
File "./tools/psort.py", line 604, in <module>
if not Main():
File "./tools/psort.py", line 581, in Main
tool.ListAnalysisPlugins()
File "./tools/psort.py", line 297, in ListAnalysisPlugins
analysis_plugins = self._front_end.GetAnalysisPlugins()
File "/home/onager/code/plaso/plaso/frontend/psort.py", line 96, in GetAnalysisPlugins
return analysis_manager.AnalysisPluginManager.ListAllPluginNames()
File "/home/onager/code/plaso/plaso/analysis/manager.py", line 55, in ListAllPluginNames
for cls_obj in interface.AnalysisPlugin.classes.itervalues():
AttributeError: type object 'AnalysisPlugin' has no attribute 'classes'

# Fixed code
def AddEventObjects(self, event_objects):
    """Adds event objects to the storage.

    Args:
      event_objects: a list or generator of event objects (instances of
                     EventObject).
    """
    for event_object in event_objects:
        self.AddEventObject(event_object)
# Buggy code
def _GetSectionNames(self, pefile_object):
    """Retrieves all PE section names.

    Args:
      pefile_object: The pefile object to get the names from
        (instance of pefile.PE).

    Returns:
      A list of the names of the sections.
    """
    section_names = []
    for section in pefile_object.sections:
        section_name = getattr(section, "Name", b"")
        # Ensure the name is encoded correctly.
        section_name = "{0:s}".format(section_name.encode("unicode_escape"))
        section_names.append(section_name)

    return section_names


# Traceback (UnicodeDecodeError)
[pe] Unable to process file: type: OS, location:<PATH>/test_images/win7-64-nfury-10.3.58.6/win7-64-nfury-c-drive/win7-64-nfury-c-drive.E01
type: EWF
type: TSK, inode: 75147, location: /Windows/assembly/NativeImages_v2.0.50727_32/UIAutomationClient/d0972fea9e965a565c3cff76982709db/UIAutomationClient.ni.dll
with error: 'ascii' codec can't decode byte 0x90 in position 7: ordinal not in range(128).

2015-06-02 10:40:54,309 [ERROR] (Worker_08 ) PID:16459 <worker> 'ascii' codec can't decode byte 0x90 in position 7: ordinal not in range(128)
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/plaso-1.2.1_20150602-py2.7.egg/plaso/engine/worker.py", line 169, in _ParseFileEntryWithParser
File "/usr/local/lib/python2.7/dist-packages/plaso-1.2.1_20150602-py2.7.egg/plaso/parsers/interface.py", line 72, in UpdateChainAndParse
File "/usr/local/lib/python2.7/dist-packages/plaso-1.2.1_20150602-py2.7.egg/plaso/parsers/interface.py", line 256, in Parse
File "/usr/local/lib/python2.7/dist-packages/plaso-1.2.1_20150602-py2.7.egg/plaso/parsers/pe.py", line 259, in ParseFileObject
File "/usr/local/lib/python2.7/dist-packages/plaso-1.2.1_20150602-py2.7.egg/plaso/parsers/pe.py", line 132, in _GetSectionNames
UnicodeDecodeError: 'ascii' codec can't decode byte 0x90 in position 7: ordinal not in range(128)

# Fixed code
def _GetSectionNames(self, pefile_object):
    """Retrieves all PE section names.

    Args:
      pefile_object: The pefile object to get the names from
        (instance of pefile.PE).

    Returns:
      A list of the names of the sections.
    """
    section_names = []
    for section in pefile_object.sections:
        section_name = getattr(section, "Name", b"")
        # Ensure the name is decoded correctly.
        try:
            section_name = "{0:s}".format(section_name.decode("unicode_escape"))
        except UnicodeDecodeError:
            section_name = "{0:s}".format(repr(section_name))
        section_names.append(section_name)

    return section_names
# Buggy code
def ListSignatureIdentifiers(self):
    """Lists the signature identifier.

    Raises:
      BadConfigOption: if the data location is invalid.
    """
    if not self._data_location:
        raise errors.BadConfigOption("Missing data location.")

    path = os.path.join(self._data_location, "signatures.conf")
    if not os.path.exists(path):
        raise errors.BadConfigOption(
            "No such format specification file: {0:s}".format(path)
        )

    try:
        specification_store = self._ReadSpecificationFile(path)
    except IOError as exception:
        raise errors.BadConfigOption(
            (
                "Unable to read format specification file: {0:s} with error: {1:s}"
            ).format(path, exception)
        )

    identifiers = []
    for format_specification in specification_store.specifications:
        identifiers.append(format_specification.identifier)

    self._output_writer.Write("Available signature identifiers:\n")
    self._output_writer.Write(
        "\n".join(textwrap.wrap(", ".join(sorted(identifiers)), 79))
    )
    self._output_writer.Write("\n\n")


# Traceback (AttributeError)
./tools/image_export.py --help
Traceback (most recent call last):
File "./tools/image_export.py", line 312, in <module>
if not Main():
File "./tools/image_export.py", line 281, in Main
if not tool.ParseArguments():
File "./tools/image_export.py", line 94, in ParseArguments
self.AddDataOptions(argument_parser)
AttributeError: 'ImageExportTool' object has no attribute 'AddDataOptions'

# Fixed code
def ListSignatureIdentifiers(self):
    """Lists the signature identifier.

    Raises:
      BadConfigOption: if the data location is invalid.
    """
    if not self._data_location:
        raise errors.BadConfigOption("Missing data location.")

    path = os.path.join(self._data_location, "signatures.conf")
    if not os.path.exists(path):
        raise errors.BadConfigOption(
            "No such format specification file: {0:s}".format(path)
        )

    try:
        specification_store = self._front_end.ReadSpecificationFile(path)
    except IOError as exception:
        raise errors.BadConfigOption(
            (
                "Unable to read format specification file: {0:s} with error: {1:s}"
            ).format(path, exception)
        )

    identifiers = []
    for format_specification in specification_store.specifications:
        identifiers.append(format_specification.identifier)

    self._output_writer.Write("Available signature identifiers:\n")
    self._output_writer.Write(
        "\n".join(textwrap.wrap(", ".join(sorted(identifiers)), 79))
    )
    self._output_writer.Write("\n\n")
# Buggy code
def ParseOptions(self, options):
    """Parses tool specific options.

    Args:
      options: the command line arguments (instance of argparse.Namespace).
    """
    self._ParseInformationalOptions(options)
    self._ParseDataLocationOption(options)


# Traceback (AttributeError)
./tools/image_export.py --help
Traceback (most recent call last):
File "./tools/image_export.py", line 312, in <module>
if not Main():
File "./tools/image_export.py", line 281, in Main
if not tool.ParseArguments():
File "./tools/image_export.py", line 94, in ParseArguments
self.AddDataOptions(argument_parser)
AttributeError: 'ImageExportTool' object has no attribute 'AddDataOptions'

# Fixed code
def ParseOptions(self, options):
    """Parses tool specific options.

    Args:
      options: the command line arguments (instance of argparse.Namespace).
    """
    self._ParseInformationalOptions(options)
# Buggy code
def GetParsersFromCategory(category):
    """Return a list of parsers from a parser category."""
    return_list = []
    if category not in categories:
        return return_list

    for item in categories.get(category):
        if item in categories:
            return_list.extend(GetParsersFromCategory(item))
        else:
            return_list.append(item)

    return return_list


# Traceback (UnicodeDecodeError)
Process StorageWriter:
Traceback (most recent call last):
File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/home/onager/code/plaso/plaso/multi_processing/multi_process.py", line 517, in run
self._Main()
File "/home/onager/code/plaso/plaso/multi_processing/multi_process.py", line 670, in _Main
self._storage_writer.WriteEventObjects()
File "/home/onager/code/plaso/plaso/lib/storage.py", line 1648, in WriteEventObjects
self.ConsumeItems()
File "/home/onager/code/plaso/plaso/engine/queue.py", line 132, in ConsumeItems
self._ConsumeItem(item, **kwargs)
File "/home/onager/code/plaso/plaso/lib/storage.py", line 1635, in _ConsumeItem
self._storage_file.AddEventObject(event_object)
File "/home/onager/code/plaso/plaso/lib/storage.py", line 1262, in AddEventObject
event_object)
File "/home/onager/code/plaso/plaso/serializer/json_serializer.py", line 688, in WriteSerialized
return json.dumps(event_object, cls=_EventObjectJSONEncoder)
File "/usr/lib/python2.7/json/__init__.py", line 250, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "/usr/lib/python2.7/json/encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode
return _iterencode(o, 0)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x90 in position 7: invalid start byte

# Fixed code
def GetParsersFromCategory(category):
    """Return a list of parsers from a parser category.

    Args:
      category: One of the parser categories.
    """
    return_list = []
    if category not in categories:
        return return_list

    for item in categories.get(category):
        if item in categories:
            return_list.extend(GetParsersFromCategory(item))
        else:
            return_list.append(item)

    return return_list
# Buggy code
def _GetSectionNames(self, pefile_object):
    """Retrieves all PE section names.

    Args:
      pefile_object: The pefile object to get the names from
        (instance of pefile.PE).

    Returns:
      A list of the names of the sections.
    """
    section_names = []
    for section in pefile_object.sections:
        section_names.append(getattr(section, "Name", None))
    return section_names


# Traceback (UnicodeDecodeError)
Process StorageWriter:
Traceback (most recent call last):
File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/home/onager/code/plaso/plaso/multi_processing/multi_process.py", line 517, in run
self._Main()
File "/home/onager/code/plaso/plaso/multi_processing/multi_process.py", line 670, in _Main
self._storage_writer.WriteEventObjects()
File "/home/onager/code/plaso/plaso/lib/storage.py", line 1648, in WriteEventObjects
self.ConsumeItems()
File "/home/onager/code/plaso/plaso/engine/queue.py", line 132, in ConsumeItems
self._ConsumeItem(item, **kwargs)
File "/home/onager/code/plaso/plaso/lib/storage.py", line 1635, in _ConsumeItem
self._storage_file.AddEventObject(event_object)
File "/home/onager/code/plaso/plaso/lib/storage.py", line 1262, in AddEventObject
event_object)
File "/home/onager/code/plaso/plaso/serializer/json_serializer.py", line 688, in WriteSerialized
return json.dumps(event_object, cls=_EventObjectJSONEncoder)
File "/usr/lib/python2.7/json/__init__.py", line 250, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "/usr/lib/python2.7/json/encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode
return _iterencode(o, 0)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x90 in position 7: invalid start byte

# Fixed code
def _GetSectionNames(self, pefile_object):
    """Retrieves all PE section names.

    Args:
      pefile_object: The pefile object to get the names from
        (instance of pefile.PE).

    Returns:
      A list of the names of the sections.
    """
    section_names = []
    for section in pefile_object.sections:
        section_name = getattr(section, "Name", b"")
        # Ensure the name is encoded correctly.
        section_name = "{0:s}".format(section_name.encode("unicode_escape"))
        section_names.append(section_name)

    return section_names
# Buggy code
def __init__(self, local_zone=True):
    """Constructor for the SlowLexicalTextParser.

    Args:
      local_zone: A boolean value that determines if the entries
                  in the log file are stored in the local time
                  zone of the computer that stored it or in a fixed
                  timezone, like UTC.
    """
    # TODO: remove the multiple inheritance.
    lexer.SelfFeederMixIn.__init__(self)
    interface.SingleFileBaseParser.__init__(self)
    self.line_ready = False
    self.attributes = {
        "body": "",
        "iyear": 0,
        "imonth": 0,
        "iday": 0,
        "time": "",
        "hostname": "",
        "username": "",
    }
    self.local_zone = local_zone
    self.file_entry = None


# Traceback (UnicodeDecodeError)
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/plaso/engine/worker.py", line 169, in _ParseFileEntryWithParser
parser_object.UpdateChainAndParse(self._parser_mediator)
File "/usr/lib/python2.7/dist-packages/plaso/parsers/interface.py", line 72, in UpdateChainAndParse
self.Parse(parser_mediator, **kwargs)
File "/usr/lib/python2.7/dist-packages/plaso/parsers/interface.py", line 256, in Parse
self.ParseFileObject(parser_mediator, file_object, **kwargs)
File "/usr/lib/python2.7/dist-packages/plaso/parsers/text_parser.py", line 160, in ParseFileObject
_ = self.NextToken()
File "/usr/lib/python2.7/dist-packages/plaso/lib/lexer.py", line 191, in NextToken
return Lexer.NextToken(self)
File "/usr/lib/python2.7/dist-packages/plaso/lib/lexer.py", line 99, in NextToken
possible_next_state = callback(string=m.group(0), match=m)
File "/usr/lib/python2.7/dist-packages/plaso/parsers/text_parser.py", line 119, in ParseIncomplete
self.attributes['body'] += match.group(0)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)

# Fixed code
def __init__(self, local_zone=True):
    """Constructor for the SlowLexicalTextParser.

    Args:
      local_zone: a boolean value that determines if the entries
                  in the log file are stored in the local time
                  zone of the computer that stored it or in a fixed
                  timezone, like UTC.
    """
    # TODO: remove the multiple inheritance.
    lexer.SelfFeederMixIn.__init__(self)
    interface.SingleFileBaseParser.__init__(self)
    self.line_ready = False
    self.attributes = {
        "body": "",
        "iyear": 0,
        "imonth": 0,
        "iday": 0,
        "time": "",
        "hostname": "",
        "username": "",
    }
    self.local_zone = local_zone
    self.file_entry = None
# Buggy code
def CreateEvent(self, timestamp, offset, attributes):
    """Creates an event.

       This function should be overwritten by text parsers that required
       the generation of specific event object type, the default event
       type is TextEvent.

    Args:
      timestamp: The timestamp time value. The timestamp contains the
                 number of microseconds since Jan 1, 1970 00:00:00 UTC.
      offset: The offset of the event.
      attributes: A dictionary that contains the event's attributes.

    Returns:
      An event object (instance of TextEvent).
    """
    return text_events.TextEvent(timestamp, offset, attributes)


# Traceback (UnicodeDecodeError)
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/plaso/engine/worker.py", line 169, in _ParseFileEntryWithParser
parser_object.UpdateChainAndParse(self._parser_mediator)
File "/usr/lib/python2.7/dist-packages/plaso/parsers/interface.py", line 72, in UpdateChainAndParse
self.Parse(parser_mediator, **kwargs)
File "/usr/lib/python2.7/dist-packages/plaso/parsers/interface.py", line 256, in Parse
self.ParseFileObject(parser_mediator, file_object, **kwargs)
File "/usr/lib/python2.7/dist-packages/plaso/parsers/text_parser.py", line 160, in ParseFileObject
_ = self.NextToken()
File "/usr/lib/python2.7/dist-packages/plaso/lib/lexer.py", line 191, in NextToken
return Lexer.NextToken(self)
File "/usr/lib/python2.7/dist-packages/plaso/lib/lexer.py", line 99, in NextToken
possible_next_state = callback(string=m.group(0), match=m)
File "/usr/lib/python2.7/dist-packages/plaso/parsers/text_parser.py", line 119, in ParseIncomplete
self.attributes['body'] += match.group(0)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)

# Fixed code
def CreateEvent(self, timestamp, offset, attributes):
    """Creates an event.

       This function should be overwritten by text parsers that required
       the generation of specific event object type, the default event
       type is TextEvent.

    Args:
      timestamp: the timestamp time value. The timestamp contains the
                 number of microseconds since Jan 1, 1970 00:00:00 UTC.
      offset: the offset of the event.
      attributes: a dictionary that contains the event's attributes.

    Returns:
      An event object (instance of TextEvent).
    """
    return text_events.TextEvent(timestamp, offset, attributes)
# Buggy code
def ParseIncomplete(self, match=None, **unused_kwargs):
    """Indication that we've got a partial line to match against.

    Args:
      match: The regular expression match object.
    """
    self.attributes["body"] += match.group(0)
    self.line_ready = True


# Traceback (UnicodeDecodeError)
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/plaso/engine/worker.py", line 169, in _ParseFileEntryWithParser
parser_object.UpdateChainAndParse(self._parser_mediator)
File "/usr/lib/python2.7/dist-packages/plaso/parsers/interface.py", line 72, in UpdateChainAndParse
self.Parse(parser_mediator, **kwargs)
File "/usr/lib/python2.7/dist-packages/plaso/parsers/interface.py", line 256, in Parse
self.ParseFileObject(parser_mediator, file_object, **kwargs)
File "/usr/lib/python2.7/dist-packages/plaso/parsers/text_parser.py", line 160, in ParseFileObject
_ = self.NextToken()
File "/usr/lib/python2.7/dist-packages/plaso/lib/lexer.py", line 191, in NextToken
return Lexer.NextToken(self)
File "/usr/lib/python2.7/dist-packages/plaso/lib/lexer.py", line 99, in NextToken
possible_next_state = callback(string=m.group(0), match=m)
File "/usr/lib/python2.7/dist-packages/plaso/parsers/text_parser.py", line 119, in ParseIncomplete
self.attributes['body'] += match.group(0)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)

# Fixed code
def ParseIncomplete(self, match=None, **unused_kwargs):
    """Parse a partial line match and append to the body attribute.

    Args:
      match: optional regular expression match object (instance of SRE_Match).
             The default is None.
    """
    if not match:
        return

    try:
        self.attributes["body"] += match.group(0)
    except UnicodeDecodeError:
        # TODO: Support other encodings than UTF-8 here, read from the
        # knowledge base or parse from the file itself.
        self.attributes["body"] += "{0:s}".format(
            match.group(0).decode("utf-8", errors="ignore")
        )

    self.line_ready = True