gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _get_loadings(self, loadings):
    from hyperspy.api import signals

    data = loadings.T.reshape((-1,) + self.axes_manager.navigation_shape[::-1])
    signal = signals.BaseSignal(
        data,
        axes=(
            [{"size": data.shape[0], "navigate": True}]
            + self.axes_manager._get_navigation_axes_dicts()
        ),
    )
    for axis in signal.axes_manager._axes[1:]:
        axis.navigate = False
    return signal


# Traceback (AttributeError)
s = hs.load(signal)
s.plot_decomposition_results()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-19-7c3b0ba4e00e> in <module>()
----> 1 s.plot_decomposition_results()

c:\users\thomasaar\hyperspy\hyperspy\signal.py in plot_decomposition_results(self, factors_navigator, loadings_navigator, factors_dim, loadings_dim)
1472
1473         """
-> 1474         factors = self.get_decomposition_factors()
1475         loadings = self.get_decomposition_loadings()
1476         _plot_x_results(factors=factors, loadings=loadings,

c:\users\thomasaar\hyperspy\hyperspy\signal.py in get_decomposition_factors(self)
1363
1364         """
-> 1365         signal = self._get_factors(self.learning_results.factors)
1366         signal.axes_manager._axes[0].name = "Decomposition component index"
1367         signal.metadata.General.title = ("Decomposition factors of " +

c:\users\thomasaar\hyperspy\hyperspy\signal.py in _get_factors(self, factors)
1333     def _get_factors(self, factors):
1334         signal = self.__class__(
-> 1335             factors.T.reshape((-1,) + self.axes_manager.signal_shape[::-1]),
1336             axes=[{"size": factors.shape[-1], "navigate": True}] +
1337             self.axes_manager._get_signal_axes_dicts())

AttributeError: 'NoneType' object has no attribute 'T'

# Fixed code
def _get_loadings(self, loadings):
    if loadings is None:
        raise RuntimeError("No learning results found.")
    from hyperspy.api import signals

    data = loadings.T.reshape((-1,) + self.axes_manager.navigation_shape[::-1])
    signal = signals.BaseSignal(
        data,
        axes=(
            [{"size": data.shape[0], "navigate": True}]
            + self.axes_manager._get_navigation_axes_dicts()
        ),
    )
    for axis in signal.axes_manager._axes[1:]:
        axis.navigate = False
    return signal
# Buggy code
def _get_factors(self, factors):
    signal = self.__class__(
        factors.T.reshape((-1,) + self.axes_manager.signal_shape[::-1]),
        axes=[{"size": factors.shape[-1], "navigate": True}]
        + self.axes_manager._get_signal_axes_dicts(),
    )
    signal.set_signal_type(self.metadata.Signal.signal_type)
    for axis in signal.axes_manager._axes[1:]:
        axis.navigate = False
    return signal


# Traceback (AttributeError)
s = hs.load(signal)
s.plot_decomposition_results()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-19-7c3b0ba4e00e> in <module>()
----> 1 s.plot_decomposition_results()

c:\users\thomasaar\hyperspy\hyperspy\signal.py in plot_decomposition_results(self, factors_navigator, loadings_navigator, factors_dim, loadings_dim)
1472
1473         """
-> 1474         factors = self.get_decomposition_factors()
1475         loadings = self.get_decomposition_loadings()
1476         _plot_x_results(factors=factors, loadings=loadings,

c:\users\thomasaar\hyperspy\hyperspy\signal.py in get_decomposition_factors(self)
1363
1364         """
-> 1365         signal = self._get_factors(self.learning_results.factors)
1366         signal.axes_manager._axes[0].name = "Decomposition component index"
1367         signal.metadata.General.title = ("Decomposition factors of " +

c:\users\thomasaar\hyperspy\hyperspy\signal.py in _get_factors(self, factors)
1333     def _get_factors(self, factors):
1334         signal = self.__class__(
-> 1335             factors.T.reshape((-1,) + self.axes_manager.signal_shape[::-1]),
1336             axes=[{"size": factors.shape[-1], "navigate": True}] +
1337             self.axes_manager._get_signal_axes_dicts())

AttributeError: 'NoneType' object has no attribute 'T'

# Fixed code
def _get_factors(self, factors):
    if factors is None:
        raise RuntimeError("No learning results found.")
    signal = self.__class__(
        factors.T.reshape((-1,) + self.axes_manager.signal_shape[::-1]),
        axes=[{"size": factors.shape[-1], "navigate": True}]
        + self.axes_manager._get_signal_axes_dicts(),
    )
    signal.set_signal_type(self.metadata.Signal.signal_type)
    for axis in signal.axes_manager._axes[1:]:
        axis.navigate = False
    return signal
# Buggy code
def __init__(self, A=1e-5, r=3.0, origin=0.0, shift=20.0, ratio=1.0, **kwargs):
    super(DoublePowerLaw, self).__init__(
        expression="A * (ratio * (x - origin - shift) ** -r + (x - origin) ** -r)",
        name="DoublePowerLaw",
        A=A,
        r=r,
        origin=origin,
        shift=shift,
        ratio=ratio,
        position="origin",
        autodoc=True,
        **kwargs,
    )

    self.origin.free = False
    self.shift.value = 20.0
    self.shift.free = False
    self.left_cutoff = 0.0  # in x-units

    # Boundaries
    self.A.bmin = 0.0
    self.A.bmax = None
    self.r.bmin = 1.0
    self.r.bmax = 5.0

    self.isbackground = True
    self.convolved = False


# Traceback (ValueError)
Traceback (most recent call last):
File "ReproduceBug.py", line 17, in <module>
FeSub = FeL.remove_background(signal_range=(670., 695.), background_type='Polynomial', polynomial_order=1)
File "/Users/Zack/anaconda3/envs/conda37/lib/python3.7/site-packages/hyperspy/_signals/signal1d.py", line 1099, in remove_background
show_progressbar=show_progressbar)
File "/Users/Zack/anaconda3/envs/conda37/lib/python3.7/site-packages/hyperspy/_signals/signal1d.py", line 1040, in _remove_background_cli
background_estimator.function_nd(axis))
ValueError: operands could not be broadcast together with shapes (35,35,2048) (35,2,2048)

# Fixed code
def __init__(
    self, A=1e-5, r=3.0, origin=0.0, shift=20.0, ratio=1.0, module="numexpr", **kwargs
):
    super(DoublePowerLaw, self).__init__(
        expression="A * (ratio * (x - origin - shift) ** -r + (x - origin) ** -r)",
        name="DoublePowerLaw",
        A=A,
        r=r,
        origin=origin,
        shift=shift,
        ratio=ratio,
        position="origin",
        autodoc=True,
        module=module,
        **kwargs,
    )

    self.origin.free = False
    self.shift.value = 20.0
    self.shift.free = False
    self.left_cutoff = 0.0  # in x-units

    # Boundaries
    self.A.bmin = 0.0
    self.A.bmax = None
    self.r.bmin = 1.0
    self.r.bmax = 5.0

    self.isbackground = True
    self.convolved = False
# Buggy code
def function_nd(self, *args):
    """%s"""
    if self._is2D:
        x, y = args[0], args[1]
        # navigation dimension is 0, f_nd same as f
        if not self._is_navigation_multidimensional():
            return self.function(x, y)
        else:
            return self._f(
                x[np.newaxis, ...],
                y[np.newaxis, ...],
                *[
                    p.map["values"][..., np.newaxis, np.newaxis]
                    for p in self.parameters
                ],
            )
    else:
        x = args[0]
        if not self._is_navigation_multidimensional():
            return self.function(x)
        else:
            return self._f(
                x[np.newaxis, ...],
                *[p.map["values"][..., np.newaxis] for p in self.parameters],
            )


# Traceback (ValueError)
Traceback (most recent call last):
File "ReproduceBug.py", line 17, in <module>
FeSub = FeL.remove_background(signal_range=(670., 695.), background_type='Polynomial', polynomial_order=1)
File "/Users/Zack/anaconda3/envs/conda37/lib/python3.7/site-packages/hyperspy/_signals/signal1d.py", line 1099, in remove_background
show_progressbar=show_progressbar)
File "/Users/Zack/anaconda3/envs/conda37/lib/python3.7/site-packages/hyperspy/_signals/signal1d.py", line 1040, in _remove_background_cli
background_estimator.function_nd(axis))
ValueError: operands could not be broadcast together with shapes (35,35,2048) (35,2,2048)

# Fixed code
def function_nd(self, *args):
    """%s"""
    if self._is2D:
        x, y = args[0], args[1]
        # navigation dimension is 0, f_nd same as f
        if not self._is_navigation_multidimensional:
            return self.function(x, y)
        else:
            return self._f(
                x[np.newaxis, ...],
                y[np.newaxis, ...],
                *[
                    p.map["values"][..., np.newaxis, np.newaxis]
                    for p in self.parameters
                ],
            )
    else:
        x = args[0]
        if not self._is_navigation_multidimensional:
            return self.function(x)
        else:
            return self._f(
                x[np.newaxis, ...],
                *[p.map["values"][..., np.newaxis] for p in self.parameters],
            )
# Buggy code
def function_nd(self, axis):
    """%s"""
    x = axis[np.newaxis, :]
    o = self.offset.map["values"][..., np.newaxis]
    return self._function(x, o)


# Traceback (ValueError)
Traceback (most recent call last):
File "ReproduceBug.py", line 17, in <module>
FeSub = FeL.remove_background(signal_range=(670., 695.), background_type='Polynomial', polynomial_order=1)
File "/Users/Zack/anaconda3/envs/conda37/lib/python3.7/site-packages/hyperspy/_signals/signal1d.py", line 1099, in remove_background
show_progressbar=show_progressbar)
File "/Users/Zack/anaconda3/envs/conda37/lib/python3.7/site-packages/hyperspy/_signals/signal1d.py", line 1040, in _remove_background_cli
background_estimator.function_nd(axis))
ValueError: operands could not be broadcast together with shapes (35,35,2048) (35,2,2048)

# Fixed code
def function_nd(self, axis):
    """%s"""
    if self._is_navigation_multidimensional:
        x = axis[np.newaxis, :]
        o = self.offset.map["values"][..., np.newaxis]
    else:
        x = axis
        o = self.offset.value
    return self._function(x, o)
# Buggy code
def select(self):
    """
    Cause this widget to be the selected widget in its MPL axes. This
    assumes that the widget has its patch added to the MPL axes.
    """
    if not self.patch or not self.is_on() or not self.ax:
        return

    canvas = self.ax.figure.canvas
    # Simulate a pick event
    x, y = self.patch[0].get_transform().transform_point((0, 0))
    mouseevent = MouseEvent("pick_event", canvas, x, y)
    canvas.pick_event(mouseevent, self.patch[0])
    self.picked = False


# Traceback (TypeError)
Traceback (most recent call last):

File "<ipython-input-1-83892adf2fe2>", line 12, in <module>
w = roi_nav.add_widget(s)

File "/home/eric/Python_dev/hyperspy/hyperspy/roi.py", line 447, in add_widget
widget.set_mpl_ax(ax)

File "/home/eric/Python_dev/hyperspy/hyperspy/drawing/widget.py", line 168, in set_mpl_ax
self.select()

File "/home/eric/Python_dev/hyperspy/hyperspy/drawing/widget.py", line 182, in select
canvas.pick_event(mouseevent, self.patch[0])

File "/opt/anaconda3/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 1883, in pick_event
self.callbacks.process(s, event)

File "/opt/anaconda3/lib/python3.6/site-packages/matplotlib/cbook.py", line 554, in process
proxy(*args, **kwargs)

File "/opt/anaconda3/lib/python3.6/site-packages/matplotlib/cbook.py", line 416, in __call__
return mtd(*args, **kwargs)

File "/home/eric/Python_dev/hyperspy/hyperspy/drawing/widget.py", line 671, in onpick
super(ResizableDraggableWidgetBase, self).onpick(event)

File "/home/eric/Python_dev/hyperspy/hyperspy/drawing/widget.py", line 438, in onpick
super(DraggableWidgetBase, self).onpick(event)

File "/home/eric/Python_dev/hyperspy/hyperspy/drawing/widget.py", line 958, in onpick
self.pick_offset = (x - self._pos[0], y - self._pos[1])

TypeError: unsupported operand type(s) for -: 'NoneType' and 'float'

# Fixed code
def select(self):
    """
    Cause this widget to be the selected widget in its MPL axes. This
    assumes that the widget has its patch added to the MPL axes.
    """
    if not self.patch or not self.is_on() or not self.ax:
        return

    canvas = self.ax.figure.canvas
    # Simulate a pick event
    x, y = self.patch[0].get_transform().transform_point((0, 0))
    mouseevent = MouseEvent("pick_event", canvas, x, y)
    # when the widget is added programatically, mouseevent can be "empty"
    if mouseevent.button:
        canvas.pick_event(mouseevent, self.patch[0])
    self.picked = False
# Buggy code
def __init__(self, signal1D):
    Component.__init__(self, ["yscale", "xscale", "shift"])

    self._position = self.shift
    self._whitelist["signal1D"] = ("init,sig", signal1D)
    self.signal = signal1D
    self.yscale.free = True
    self.yscale.value = 1.0
    self.xscale.value = 1.0
    self.shift.value = 0.0

    self.prepare_interpolator()
    # Options
    self.isbackground = True
    self.convolved = False
    self.interpolate = True


# Traceback (TypeError)
s = hs.datasets.example_signals.EDS_SEM_Spectrum()
hs.model.components1D.ScalableFixedPattern(s,xscale=2)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-97-f7d2822487b5> in <module>()
----> 1 c = hs.model.components1D.ScalableFixedPattern(s,xscale=2)

TypeError: __init__() got an unexpected keyword argument 'xscale'

# Fixed code
def __init__(self, signal1D, yscale=1.0, xscale=1.0, shift=0.0, interpolate=True):
    Component.__init__(self, ["yscale", "xscale", "shift"])

    self._position = self.shift
    self._whitelist["signal1D"] = ("init,sig", signal1D)
    self.signal = signal1D
    self.yscale.free = True
    self.yscale.value = yscale
    self.xscale.value = xscale
    self.shift.value = shift

    self.prepare_interpolator()
    # Options
    self.isbackground = True
    self.convolved = False
    self.interpolate = interpolate
# Buggy code
def _set_sum_edx(self, root):
    for i in range(self.mapping_count):
        spec_node = root.find("./SpectrumData{0}/ClassInstance".format(str(i)))
        self.spectra_data[i] = EDXSpectrum(spec_node)


# Traceback (IndexError)
hs.load(filename)
Traceback (most recent call last):

File "<ipython-input-3-ada763a7934e>", line 1, in <module>
hs.load(filename)

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io.py", line 243, in load
for filename in filenames]

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io.py", line 243, in <listcomp>
for filename in filenames]

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io.py", line 286, in load_single_file
**kwds)

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io.py", line 295, in load_with_reader
**kwds)

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io_plugins\bcf.py", line 1189, in file_reader
obj_bcf = BCF_reader(filename, instrument=instrument)

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io_plugins\bcf.py", line 876, in __init__
self.header = HyperHeader(header_byte_str, instrument=instrument)

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io_plugins\bcf.py", line 585, in __init__
self._set_sum_edx(root)

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io_plugins\bcf.py", line 735, in _set_sum_edx
str(i))[0].ClassInstance)

IndexError: list index out of range

# Fixed code
def _set_sum_edx(self, root, indexes):
    for i in indexes:
        spec_node = root.find("./SpectrumData{0}/ClassInstance".format(str(i)))
        self.spectra_data[i] = EDXSpectrum(spec_node)
# Buggy code
def __init__(self, filename, instrument=None):
    SFS_reader.__init__(self, filename)
    header_file = self.get_file("EDSDatabase/HeaderData")
    header_byte_str = header_file.get_as_BytesIO_string().getvalue()
    self.header = HyperHeader(header_byte_str, instrument=instrument)
    self.hypermap = {}


# Traceback (IndexError)
hs.load(filename)
Traceback (most recent call last):

File "<ipython-input-3-ada763a7934e>", line 1, in <module>
hs.load(filename)

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io.py", line 243, in load
for filename in filenames]

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io.py", line 243, in <listcomp>
for filename in filenames]

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io.py", line 286, in load_single_file
**kwds)

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io.py", line 295, in load_with_reader
**kwds)

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io_plugins\bcf.py", line 1189, in file_reader
obj_bcf = BCF_reader(filename, instrument=instrument)

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io_plugins\bcf.py", line 876, in __init__
self.header = HyperHeader(header_byte_str, instrument=instrument)

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io_plugins\bcf.py", line 585, in __init__
self._set_sum_edx(root)

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io_plugins\bcf.py", line 735, in _set_sum_edx
str(i))[0].ClassInstance)

IndexError: list index out of range

# Fixed code
def __init__(self, filename, instrument=None):
    SFS_reader.__init__(self, filename)
    header_file = self.get_file("EDSDatabase/HeaderData")
    self.available_indexes = []
    for i in self.vfs["EDSDatabase"].keys():
        if "SpectrumData" in i:
            self.available_indexes.append(int(i[-1]))
    self.def_index = min(self.available_indexes)
    header_byte_str = header_file.get_as_BytesIO_string().getvalue()
    self.header = HyperHeader(
        header_byte_str, self.available_indexes, instrument=instrument
    )
    self.hypermap = {}
# Buggy code
def persistent_parse_hypermap(
    self, index=0, downsample=None, cutoff_at_kV=None, lazy=False
):
    """Parse and assign the hypermap to the HyperMap instance.

    Arguments:
    index -- index of hypermap in bcf if v2 (default 0)
    downsample -- downsampling factor of hypermap (default None)
    cutoff_at_kV -- low pass cutoff value at keV (default None)

    Method does not return anything, it adds the HyperMap instance to
    self.hypermap dictionary.

    See also:
    HyperMap, parse_hypermap
    """
    dwn = downsample
    hypermap = self.parse_hypermap(
        index=index, downsample=dwn, cutoff_at_kV=cutoff_at_kV, lazy=lazy
    )
    self.hypermap[index] = HyperMap(hypermap, self, index=index, downsample=dwn)


# Traceback (IndexError)
hs.load(filename)
Traceback (most recent call last):

File "<ipython-input-3-ada763a7934e>", line 1, in <module>
hs.load(filename)

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io.py", line 243, in load
for filename in filenames]

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io.py", line 243, in <listcomp>
for filename in filenames]

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io.py", line 286, in load_single_file
**kwds)

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io.py", line 295, in load_with_reader
**kwds)

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io_plugins\bcf.py", line 1189, in file_reader
obj_bcf = BCF_reader(filename, instrument=instrument)

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io_plugins\bcf.py", line 876, in __init__
self.header = HyperHeader(header_byte_str, instrument=instrument)

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io_plugins\bcf.py", line 585, in __init__
self._set_sum_edx(root)

File "C:\ProgramData\Anaconda3\lib\site-packages\hyperspy\io_plugins\bcf.py", line 735, in _set_sum_edx
str(i))[0].ClassInstance)

IndexError: list index out of range

# Fixed code
def persistent_parse_hypermap(
    self, index=None, downsample=None, cutoff_at_kV=None, lazy=False
):
    """Parse and assign the hypermap to the HyperMap instance.

    Arguments:
    index -- index of hypermap in bcf if v2 (default 0)
    downsample -- downsampling factor of hypermap (default None)
    cutoff_at_kV -- low pass cutoff value at keV (default None)

    Method does not return anything, it adds the HyperMap instance to
    self.hypermap dictionary.

    See also:
    HyperMap, parse_hypermap
    """
    if index is None:
        index = self.def_index
    dwn = downsample
    hypermap = self.parse_hypermap(
        index=index, downsample=dwn, cutoff_at_kV=cutoff_at_kV, lazy=lazy
    )
    self.hypermap[index] = HyperMap(hypermap, self, index=index, downsample=dwn)
# Buggy code
def fft_correlation(in1, in2, normalize=False):
    """Correlation of two N-dimensional arrays using FFT.

    Adapted from scipy's fftconvolve.

    Parameters
    ----------
    in1, in2 : array
    normalize: bool
        If True performs phase correlation

    """
    s1 = np.array(in1.shape)
    s2 = np.array(in2.shape)
    size = s1 + s2 - 1
    # Use 2**n-sized FFT
    fsize = 2 ** np.ceil(np.log2(size))
    IN1 = fftn(in1, fsize)
    IN1 *= fftn(in2, fsize).conjugate()
    if normalize is True:
        ret = ifftn(np.nan_to_num(IN1 / np.absolute(IN1))).real.copy()
    else:
        ret = ifftn(IN1).real.copy()
    del IN1
    return ret


# Traceback (TypeError)
Traceback (most recent call last):
File "/home/bm424/Documents/phd/dev/test/venv/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-14-1876e2251fb7>", line 1, in <module>
roi(dat)
File "/home/bm424/Documents/phd/dev/test/venv/lib/python3.5/site-packages/hyperspy/roi.py", line 1138, in __call__
order=order)
File "/home/bm424/Documents/phd/dev/test/venv/lib/python3.5/site-packages/hyperspy/roi.py", line 1074, in profile_line
linewidth=linewidth)
File "/home/bm424/Documents/phd/dev/test/venv/lib/python3.5/site-packages/hyperspy/roi.py", line 998, in _line_profile_coordinates
data[0, :, :] = np.tile(line_col, [linewidth, 1]).T
File "/home/bm424/Documents/phd/dev/test/venv/lib/python3.5/site-packages/numpy/lib/shape_base.py", line 881, in tile
return c.reshape(shape_out)
TypeError: 'numpy.float64' object cannot be interpreted as an integer

# Fixed code
def fft_correlation(in1, in2, normalize=False):
    """Correlation of two N-dimensional arrays using FFT.

    Adapted from scipy's fftconvolve.

    Parameters
    ----------
    in1, in2 : array
    normalize: bool
        If True performs phase correlation

    """
    s1 = np.array(in1.shape)
    s2 = np.array(in2.shape)
    size = s1 + s2 - 1
    # Use 2**n-sized FFT
    fsize = (2 ** np.ceil(np.log2(size))).astype("int")
    IN1 = fftn(in1, fsize)
    IN1 *= fftn(in2, fsize).conjugate()
    if normalize is True:
        ret = ifftn(np.nan_to_num(IN1 / np.absolute(IN1))).real.copy()
    else:
        ret = ifftn(IN1).real.copy()
    del IN1
    return ret
# Buggy code
def signal1D(self, value):
    if isinstance(value, EELSSpectrum):
        self._signal = value
        self.signal._are_microscope_parameters_missing()
    else:
        raise ValueError(
            "This attribute can only contain an EELSSpectrum "
            "but an object of type %s was provided" % str(type(value))
        )


# Traceback (AttributeError)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-21-23a6348573b8> in <module>()
----> 1 m = s.create_model()

/home/magnunor/Documents/HyperSpy/hyperspy/hyperspy/_signals/eels.py in create_model(self, ll, auto_background, auto_add_edges, GOS, dictionary)
   1252                           auto_background=auto_background,
   1253                           auto_add_edges=auto_add_edges,
-> 1254                           GOS=GOS,
   1255                           dictionary=dictionary)
   1256         return model

/home/magnunor/Documents/HyperSpy/hyperspy/hyperspy/models/eelsmodel.py in __init__(self, signal1D, auto_background, auto_add_edges, ll, GOS, dictionary)
     91 
     92         if self.signal.subshells and auto_add_edges is True:
---> 93             self._add_edges_from_subshells_names()
     94 
     95     @property

/home/magnunor/Documents/HyperSpy/hyperspy/hyperspy/models/eelsmodel.py in _add_edges_from_subshells_names(self, e_shells)
    190         # we reassing the value of self.GOS
    191         self.GOS = master_edge.GOS._name
--> 192         self.append(master_edge)
    193         element = master_edge.element
    194         while len(e_shells) > 0:

/home/magnunor/Documents/HyperSpy/hyperspy/hyperspy/models/eelsmodel.py in append(self, component)
    111         super(EELSModel, self).append(component)
    112         if isinstance(component, EELSCLEdge):
--> 113             tem = self.signal.metadata.Acquisition_instrument.TEM
    114             component.set_microscope_parameters(
    115                 E0=tem.beam_energy,

/home/magnunor/Documents/HyperSpy/hyperspy/hyperspy/misc/utils.py in __getattribute__(self, name)
    333             name = name.decode()
    334         name = slugify(name, valid_variable_name=True)
--> 335         item = super(DictionaryTreeBrowser, self).__getattribute__(name)
    336         if isinstance(item, dict) and '_dtb_value_' in item and "key" in item:
    337             return item['_dtb_value_']

AttributeError: 'DictionaryTreeBrowser' object has no attribute 'Acquisition_instrument'

# Fixed code
def signal1D(self, value):
    if isinstance(value, EELSSpectrum):
        self._signal = value
        if self.signal._are_microscope_parameters_missing():
            raise ValueError(
                "The required microscope parameters are not defined in "
                "the EELS spectrum signal metadata. Use "
                "``set_microscope_parameters`` to set them."
            )
    else:
        raise ValueError(
            "This attribute can only contain an EELSSpectrum "
            "but an object of type %s was provided" % str(type(value))
        )
# Buggy code
def summary(self):
    """Prints a summary of the decomposition and demixing parameters
    to the stdout
    """
    summary_str = (
        "Decomposition parameters:\n"
        "-------------------------\n\n"
        + ("Decomposition algorithm : \t%s\n" % self.decomposition_algorithm)
        + ("Poissonian noise normalization : %s\n" % self.poissonian_noise_normalized)
        + ("Output dimension : %s\n" % self.output_dimension)
        + ("Centre : %s" % self.centre)
    )
    if self.bss_algorithm is not None:
        summary_str += (
            "\n\nDemixing parameters:\n"
            "------------------------\n"
            + ("BSS algorithm : %s" % self.bss_algorithm)
            + ("Number of components : %i" % len(self.unmixing_matrix))
        )
    _logger.info(summary_str)


# Traceback (AttributeError)
s = hs.signals.Signal1D(np.random.rand(10,15, 1024))
s.decomposition(True)
s2 = s.get_decomposition_model(9)
s.blind_source_separation(9)

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-34-ef9c7adc7bb5> in <module>()
----> 1 s.blind_source_separation(9)

/home/eric/Python_prog/hyperspy/hyperspy/learn/mva.py in blind_source_separation(self, number_of_components, algorithm, diff_order, diff_axes, factors, comp_list, mask, on_loadings, pretreatment, **kwargs)
528             if not hasattr(lr, 'factors') or lr.factors is None:
529                 raise AttributeError(
--> 530                     'A decomposition must be performed before blind '
531                     'source seperation or factors must be provided.')
532

AttributeError: A decomposition must be performed before blind source seperation or factors must be provided.

# Fixed code
def summary(self):
    """Prints a summary of the decomposition and demixing parameters
    to the stdout
    """
    print(self._summary())
# Buggy code
def _print_summary(self):
    string = "\n\tTitle: "
    string += self.metadata.General.title.decode("utf8")
    if self.metadata.has_item("Signal.signal_type"):
        string += "\n\tSignal type: "
        string += self.metadata.Signal.signal_type
    string += "\n\tData dimensions: "
    string += str(self.axes_manager.shape)
    if self.metadata.has_item("Signal.record_by"):
        string += "\n\tData representation: "
        string += self.metadata.Signal.record_by
        string += "\n\tData type: "
        string += str(self.data.dtype)
    print(string)


# Traceback (AttributeError)
s = hs.load("*.msa", stack=True)

Loading individual files

Individual files loaded correctly
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-23a60eda1ce6> in <module>()
----> 1 s = hs.load("*.msa", stack=True)

/home/fjd29/git/hyperspy/hyperspy/io.py in load(filenames, record_by, signal_type, signal_origin, stack, stack_axis, new_axis_name, mmap, mmap_dir, **kwds)
194                 )[1]
195             messages.information('Individual files loaded correctly')
--> 196             signal._print_summary()
197             objects = [signal, ]
198         else:

/home/fjd29/git/hyperspy/hyperspy/signal.py in _print_summary(self)
2808     def _print_summary(self):
2809         string = "\n\tTitle: "
-> 2810         string += self.metadata.General.title.decode('utf8')
2811         if self.metadata.has_item("Signal.signal_type"):
2812             string += "\n\tSignal type: "

AttributeError: 'str' object has no attribute 'decode'

# Fixed code
def _print_summary(self):
    string = "\n\tTitle: "
    string += self.metadata.General.title
    if self.metadata.has_item("Signal.signal_type"):
        string += "\n\tSignal type: "
        string += self.metadata.Signal.signal_type
    string += "\n\tData dimensions: "
    string += str(self.axes_manager.shape)
    if self.metadata.has_item("Signal.record_by"):
        string += "\n\tData representation: "
        string += self.metadata.Signal.record_by
        string += "\n\tData type: "
        string += str(self.data.dtype)
    print(string)
# Buggy code
def found_wake_word(self, frame_data):
    if self.has_found:
        self.has_found = False
        return True
    return False


# Traceback (TypeError)
2020-10-13 18:03:22.296 | INFO     |  6577 | mycroft.client.speech.listener:create_wake_word_recognizer:328 | Creating wake word engine
2020-10-13 18:03:22.299 | INFO     |  6577 | mycroft.client.speech.listener:create_wake_word_recognizer:351 | Using hotword entry for blueberry
2020-10-13 18:03:22.302 | WARNING  |  6577 | mycroft.client.speech.listener:create_wake_word_recognizer:353 | Phonemes are missing falling back to listeners configuration
2020-10-13 18:03:22.305 | WARNING  |  6577 | mycroft.client.speech.listener:create_wake_word_recognizer:357 | Threshold is missing falling back to listeners configuration
2020-10-13 18:03:22.310 | INFO     |  6577 | mycroft.client.speech.hotword_factory:load_module:403 | Loading "blueberry" wake word via porcupine
2020-10-13 18:03:22.315 | INFO     |  6577 | mycroft.client.speech.hotword_factory:__init__:331 | Adding /home/pi/.mycroft/Porcupine/binding/python to Python path
2020-10-13 18:03:22.338 | INFO     |  6577 | mycroft.client.speech.hotword_factory:__init__:356 | Loading Porcupine using library path /home/pi/.mycroft/Porcupine/lib/linux/armv7l/libpv_porcupine.so and keyword paths ['/home/pi/.mycroft/Porcupine/resources/keyword_files/raspberry-pi/blueberry_raspberry-pi.ppn']
2020-10-13 18:03:22.341 | ERROR    |  6577 | mycroft.client.speech.hotword_factory:initialize:423 | Could not create hotword. Falling back to default.
Traceback (most recent call last):
File "/home/pi/mycroft-core/mycroft/client/speech/hotword_factory.py", line 411, in initialize
instance = clazz(hotword, config, lang=lang)
File "/home/pi/mycroft-core/mycroft/client/speech/hotword_factory.py", line 361, in __init__
sensitivities=sensitivities)
TypeError: __init__() got an unexpected keyword argument 'model_file_path'
2020-10-13 18:03:22.345 | INFO     |  6577 | mycroft.client.speech.hotword_factory:load_module:403 | Loading "blueberry" wake word via pocketsphinx
2020-10-13 18:03:22.475 | INFO     |  6577 | mycroft.client.speech.listener:create_wakeup_recognizer:365 | creating stand up word engine
2020-10-13 18:03:22.478 | INFO     |  6577 | mycroft.client.speech.hotword_factory:load_module:403 | Loading "wake up" wake word via pocketsphinx
2020-10-13 18:03:22.602 | INFO     |  6577 | __main__:on_ready:175 | Speech client is ready.

# Fixed code
def found_wake_word(self, frame_data):
    """Check if wakeword has been found.

    Returns:
        (bool) True if wakeword was found otherwise False.
    """
    if self.has_found:
        self.has_found = False
        return True
    return False
# Buggy code
def stop(self):
    if self.porcupine is not None:
        self.porcupine.delete()


# Traceback (TypeError)
2020-10-13 18:03:22.296 | INFO     |  6577 | mycroft.client.speech.listener:create_wake_word_recognizer:328 | Creating wake word engine
2020-10-13 18:03:22.299 | INFO     |  6577 | mycroft.client.speech.listener:create_wake_word_recognizer:351 | Using hotword entry for blueberry
2020-10-13 18:03:22.302 | WARNING  |  6577 | mycroft.client.speech.listener:create_wake_word_recognizer:353 | Phonemes are missing falling back to listeners configuration
2020-10-13 18:03:22.305 | WARNING  |  6577 | mycroft.client.speech.listener:create_wake_word_recognizer:357 | Threshold is missing falling back to listeners configuration
2020-10-13 18:03:22.310 | INFO     |  6577 | mycroft.client.speech.hotword_factory:load_module:403 | Loading "blueberry" wake word via porcupine
2020-10-13 18:03:22.315 | INFO     |  6577 | mycroft.client.speech.hotword_factory:__init__:331 | Adding /home/pi/.mycroft/Porcupine/binding/python to Python path
2020-10-13 18:03:22.338 | INFO     |  6577 | mycroft.client.speech.hotword_factory:__init__:356 | Loading Porcupine using library path /home/pi/.mycroft/Porcupine/lib/linux/armv7l/libpv_porcupine.so and keyword paths ['/home/pi/.mycroft/Porcupine/resources/keyword_files/raspberry-pi/blueberry_raspberry-pi.ppn']
2020-10-13 18:03:22.341 | ERROR    |  6577 | mycroft.client.speech.hotword_factory:initialize:423 | Could not create hotword. Falling back to default.
Traceback (most recent call last):
File "/home/pi/mycroft-core/mycroft/client/speech/hotword_factory.py", line 411, in initialize
instance = clazz(hotword, config, lang=lang)
File "/home/pi/mycroft-core/mycroft/client/speech/hotword_factory.py", line 361, in __init__
sensitivities=sensitivities)
TypeError: __init__() got an unexpected keyword argument 'model_file_path'
2020-10-13 18:03:22.345 | INFO     |  6577 | mycroft.client.speech.hotword_factory:load_module:403 | Loading "blueberry" wake word via pocketsphinx
2020-10-13 18:03:22.475 | INFO     |  6577 | mycroft.client.speech.listener:create_wakeup_recognizer:365 | creating stand up word engine
2020-10-13 18:03:22.478 | INFO     |  6577 | mycroft.client.speech.hotword_factory:load_module:403 | Loading "wake up" wake word via pocketsphinx
2020-10-13 18:03:22.602 | INFO     |  6577 | __main__:on_ready:175 | Speech client is ready.

# Fixed code
def stop(self):
    """Stop the hotword engine.

    Clean up Porcupine library.
    """
    if self.porcupine is not None:
        self.porcupine.delete()
# Buggy code
def add(self, name, handler, once=False):
    """Create event handler for executing intent or other event.

    Arguments:
        name (string): IntentParser name
        handler (func): Method to call
        once (bool, optional): Event handler will be removed after it has
                               been run once.
    """

    def once_wrapper(message):
        # Remove registered one-time handler before invoking,
        # allowing them to re-schedule themselves.
        handler(message)
        self.remove(name)

    if handler:
        if once:
            self.bus.once(name, once_wrapper)
        else:
            self.bus.on(name, handler)
        self.events.append((name, handler))


# Traceback (KeyError)
12:04:25.758 | INFO     | 22386 | mycroft.skills.skill_loader:reload:109 | ATTEMPTING TO RELOAD SKILL: mycroft-alarm.mycroftai
12:04:25.760 | ERROR    | 22386 | mycroft.skills.skill_loader:_execute_instance_shutdown:145 | An error occurred while shutting down AlarmSkill
Traceback (most recent call last):
File "/home/fs-neriahbjato/Documents/Full_Scale/Mycroft/mycroft-core/mycroft/skills/skill_loader.py", line 142, in _execute_instance_shutdown
self.instance.default_shutdown()
File "/home/fs-neriahbjato/Documents/Full_Scale/Mycroft/mycroft-core/mycroft/skills/mycroft_skill/mycroft_skill.py", line 1162, in default_shutdown
self.event_scheduler.shutdown()
File "/home/fs-neriahbjato/Documents/Full_Scale/Mycroft/mycroft-core/mycroft/skills/event_scheduler.py", line 433, in shutdown
self.events.clear()
File "/home/fs-neriahbjato/Documents/Full_Scale/Mycroft/mycroft-core/mycroft/skills/mycroft_skill/event_container.py", line 183, in clear
self.bus.remove(e, f)
File "/home/fs-neriahbjato/Documents/Full_Scale/Mycroft/mycroft-core/mycroft/messagebus/client/client.py", line 172, in remove
self.emitter.remove_listener(event_name, func)
File "/home/fs-neriahbjato/Documents/Full_Scale/Mycroft/mycroft-core/mycroft/messagebus/client/threaded_event_emitter.py", line 57, in remove_listener
return super().remove_listener(event_name, func)
File "/home/fs-neriahbjato/Documents/Full_Scale/Mycroft/mycroft-core/.venv/lib/python3.6/site-packages/pyee/__init__.py", line 205, in remove_listener
self._events[event].pop(f)
KeyError: <function create_basic_wrapper.<locals>.wrapper at 0x7f2a504781e0>

# Fixed code
def add(self, name, handler, once=False):
    """Create event handler for executing intent or other event.

    Arguments:
        name (string): IntentParser name
        handler (func): Method to call
        once (bool, optional): Event handler will be removed after it has
                               been run once.
    """

    def once_wrapper(message):
        # Remove registered one-time handler before invoking,
        # allowing them to re-schedule themselves.
        handler(message)
        self.remove(name)

    if handler:
        if once:
            self.bus.once(name, once_wrapper)
            self.events.append((name, once_wrapper))
        else:
            self.bus.on(name, handler)
            self.events.append((name, handler))

        LOG.debug("Added event: {}".format(name))
# Buggy code
def _get_full_key(self, key: Union[str, Enum, int, None]) -> str: ...


# Traceback (KeyError)
del cfg["FOO"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/jasha10/omegaconf/omegaconf/dictconfig.py", line 405, in __delitem__
del self.__dict__["_content"][key]
KeyError: 'FOO'

# Fixed code
def _get_full_key(self, key: Optional[Union[DictKeyType, int]]) -> str: ...
# Buggy code
def _resolve_with_default(
    self,
    key: Union[str, int, Enum],
    value: Any,
    default_value: Any = DEFAULT_VALUE_MARKER,
) -> Any:
    """returns the value with the specified key, like obj.key and obj['key']"""

    def is_mandatory_missing(val: Any) -> bool:
        return bool(get_value_kind(val) == ValueKind.MANDATORY_MISSING)

    val = _get_value(value)
    has_default = default_value is not DEFAULT_VALUE_MARKER
    if has_default and (val is None or is_mandatory_missing(val)):
        return default_value

    resolved = self._maybe_resolve_interpolation(
        parent=self,
        key=key,
        value=value,
        throw_on_missing=not has_default,
        throw_on_resolution_failure=not has_default,
    )
    if resolved is None and has_default:
        return default_value

    if is_mandatory_missing(resolved):
        if has_default:
            return default_value
        else:
            raise MissingMandatoryValue("Missing mandatory value: $FULL_KEY")

    return _get_value(resolved)


# Traceback (KeyError)
del cfg["FOO"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/jasha10/omegaconf/omegaconf/dictconfig.py", line 405, in __delitem__
del self.__dict__["_content"][key]
KeyError: 'FOO'

# Fixed code
def _resolve_with_default(
    self,
    key: Union[DictKeyType, int],
    value: Any,
    default_value: Any = DEFAULT_VALUE_MARKER,
) -> Any:
    """returns the value with the specified key, like obj.key and obj['key']"""

    def is_mandatory_missing(val: Any) -> bool:
        return bool(get_value_kind(val) == ValueKind.MANDATORY_MISSING)

    val = _get_value(value)
    has_default = default_value is not DEFAULT_VALUE_MARKER
    if has_default and (val is None or is_mandatory_missing(val)):
        return default_value

    resolved = self._maybe_resolve_interpolation(
        parent=self,
        key=key,
        value=value,
        throw_on_missing=not has_default,
        throw_on_resolution_failure=not has_default,
    )
    if resolved is None and has_default:
        return default_value

    if is_mandatory_missing(resolved):
        if has_default:
            return default_value
        else:
            raise MissingMandatoryValue("Missing mandatory value: $FULL_KEY")

    return _get_value(resolved)
# Buggy code
def prepand(full_key: str, parent_type: Any, cur_type: Any, key: Any) -> str:
    if isinstance(key, slice):
        key = _slice_to_str(key)
    elif isinstance(key, Enum):
        key = key.name

    if issubclass(parent_type, ListConfig):
        if full_key != "":
            if issubclass(cur_type, ListConfig):
                full_key = f"[{key}]{full_key}"
            else:
                full_key = f"[{key}].{full_key}"
        else:
            full_key = f"[{key}]"
    else:
        if full_key == "":
            full_key = key
        else:
            if issubclass(cur_type, ListConfig):
                full_key = f"{key}{full_key}"
            else:
                full_key = f"{key}.{full_key}"
    return full_key


# Traceback (KeyError)
del cfg["FOO"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/jasha10/omegaconf/omegaconf/dictconfig.py", line 405, in __delitem__
del self.__dict__["_content"][key]
KeyError: 'FOO'

# Fixed code
def prepand(full_key: str, parent_type: Any, cur_type: Any, key: Any) -> str:
    if isinstance(key, slice):
        key = _slice_to_str(key)
    elif isinstance(key, Enum):
        key = key.name
    elif isinstance(key, (int, float, bool)):
        key = str(key)

    if issubclass(parent_type, ListConfig):
        if full_key != "":
            if issubclass(cur_type, ListConfig):
                full_key = f"[{key}]{full_key}"
            else:
                full_key = f"[{key}].{full_key}"
        else:
            full_key = f"[{key}]"
    else:
        if full_key == "":
            full_key = key
        else:
            if issubclass(cur_type, ListConfig):
                full_key = f"{key}{full_key}"
            else:
                full_key = f"{key}.{full_key}"
    return full_key
# Buggy code
def _s_validate_and_normalize_key(self, key_type: Any, key: Any) -> DictKeyType:
    if key_type is Any:
        for t in DictKeyType.__args__:  # type: ignore
            try:
                return self._s_validate_and_normalize_key(key_type=t, key=key)
            except KeyValidationError:
                pass
        raise KeyValidationError("Incompatible key type '$KEY_TYPE'")
    elif key_type == str:
        if not isinstance(key, str):
            raise KeyValidationError(
                f"Key $KEY ($KEY_TYPE) is incompatible with ({key_type.__name__})"
            )

        return key
    elif key_type == int:
        if not isinstance(key, int):
            raise KeyValidationError(
                f"Key $KEY ($KEY_TYPE) is incompatible with ({key_type.__name__})"
            )

        return key
    elif issubclass(key_type, Enum):
        try:
            ret = EnumNode.validate_and_convert_to_enum(key_type, key)
            assert ret is not None
            return ret
        except ValidationError:
            valid = ", ".join([x for x in key_type.__members__.keys()])
            raise KeyValidationError(
                f"Key '$KEY' is incompatible with the enum type '{key_type.__name__}', valid: [{valid}]"
            )
    else:
        assert False, f"Unsupported key type {key_type}"


# Traceback (KeyError)
del cfg["FOO"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/jasha10/omegaconf/omegaconf/dictconfig.py", line 405, in __delitem__
del self.__dict__["_content"][key]
KeyError: 'FOO'

# Fixed code
def _s_validate_and_normalize_key(self, key_type: Any, key: Any) -> DictKeyType:
    if key_type is Any:
        for t in DictKeyType.__args__:  # type: ignore
            if isinstance(key, t):
                return key  # type: ignore
        raise KeyValidationError("Incompatible key type '$KEY_TYPE'")
    elif key_type is bool and key in [0, 1]:
        # Python treats True as 1 and False as 0 when used as dict keys
        #   assert hash(0) == hash(False)
        #   assert hash(1) == hash(True)
        return bool(key)
    elif key_type in (str, int, float, bool):  # primitive type
        if not isinstance(key, key_type):
            raise KeyValidationError(
                f"Key $KEY ($KEY_TYPE) is incompatible with ({key_type.__name__})"
            )

        return key  # type: ignore
    elif issubclass(key_type, Enum):
        try:
            ret = EnumNode.validate_and_convert_to_enum(key_type, key, allow_none=False)
            assert ret is not None
            return ret
        except ValidationError:
            valid = ", ".join([x for x in key_type.__members__.keys()])
            raise KeyValidationError(
                f"Key '$KEY' is incompatible with the enum type '{key_type.__name__}', valid: [{valid}]"
            )
    else:
        assert False, f"Unsupported key type {key_type}"
# Buggy code
def __delitem__(self, key: DictKeyType) -> None:
    if self._get_flag("readonly"):
        self._format_and_raise(
            key=key,
            value=None,
            cause=ReadonlyConfigError(
                "DictConfig in read-only mode does not support deletion"
            ),
        )
    if self._get_flag("struct"):
        self._format_and_raise(
            key=key,
            value=None,
            cause=ConfigTypeError(
                "DictConfig in struct mode does not support deletion"
            ),
        )
    if self._is_typed() and self._get_node_flag("struct") is not False:
        self._format_and_raise(
            key=key,
            value=None,
            cause=ConfigTypeError(
                f"{type_str(self._metadata.object_type)} (DictConfig) does not support deletion"
            ),
        )

    del self.__dict__["_content"][key]


# Traceback (KeyError)
del cfg["FOO"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/jasha10/omegaconf/omegaconf/dictconfig.py", line 405, in __delitem__
del self.__dict__["_content"][key]
KeyError: 'FOO'

# Fixed code
def __delitem__(self, key: DictKeyType) -> None:
    key = self._validate_and_normalize_key(key)
    if self._get_flag("readonly"):
        self._format_and_raise(
            key=key,
            value=None,
            cause=ReadonlyConfigError(
                "DictConfig in read-only mode does not support deletion"
            ),
        )
    if self._get_flag("struct"):
        self._format_and_raise(
            key=key,
            value=None,
            cause=ConfigTypeError(
                "DictConfig in struct mode does not support deletion"
            ),
        )
    if self._is_typed() and self._get_node_flag("struct") is not False:
        self._format_and_raise(
            key=key,
            value=None,
            cause=ConfigTypeError(
                f"{type_str(self._metadata.object_type)} (DictConfig) does not support deletion"
            ),
        )

    try:
        del self.__dict__["_content"][key]
    except KeyError:
        msg = "Key not found: '$KEY'"
        self._format_and_raise(key=key, value=None, cause=ConfigKeyError(msg))