gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __init__(self, filename, filename_info, filetype_info):
    super(NCOLCI1B, self).__init__(filename, filename_info, filetype_info)
    self.nc = h5netcdf.File(filename, "r")
    self.channel = filename_info["dataset_name"]
    cal_file = os.path.join(os.path.dirname(filename), "instrument_data.nc")
    self.cal = h5netcdf.File(cal_file, "r")
    # TODO: get metadata from the manifest file (xfdumanifest.xml)
    self.platform_name = PLATFORM_NAMES[filename_info["mission_id"]]
    self.sensor = "olci"


# Traceback (AttributeError)
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')

/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632             datasets = self.datasets.values()
633         writer = self.get_writer(writer, **kwargs)
--> 634         writer.save_datasets(datasets, **kwargs)
635
636     def get_writer(self, writer="geotiff", **kwargs):

/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176                     coords = [line_coord, pixel_coord]
177
--> 178                 domain = cf.Domain(dim=coords,
179                                    aux=aux,
180                                    ref=grid_mapping)

AttributeError: 'module' object has no attribute 'Domain'

# Fixed code
def __init__(self, filename, filename_info, filetype_info, cal):
    super(NCOLCI1B, self).__init__(filename, filename_info, filetype_info)
    self.cal = cal.nc
# Buggy code
def get_dataset(self, key, info):
    """Load a dataset"""
    if self.channel != key.name:
        return
    logger.debug("Reading %s.", key.name)
    variable = self.nc[self.channel + "_radiance"]

    radiances = (
        np.ma.masked_equal(variable[:], variable.attrs["_FillValue"], copy=False)
        * variable.attrs["scale_factor"]
        + variable.attrs["add_offset"]
    )
    units = variable.attrs["units"]
    if key.calibration == "reflectance":
        solar_flux = self.cal["solar_flux"][:]
        d_index = np.ma.masked_equal(
            self.cal["detector_index"][:],
            self.cal["detector_index"].attrs["_FillValue"],
            copy=False,
        )
        idx = int(key.name[2:]) - 1
        radiances /= solar_flux[idx, d_index]
        radiances *= np.pi * 100
        units = "%"

    proj = Dataset(
        radiances,
        copy=False,
        units=units,
        platform_name=self.platform_name,
        sensor=self.sensor,
    )
    proj.info.update(key.to_dict())
    return proj


# Traceback (AttributeError)
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')

/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632             datasets = self.datasets.values()
633         writer = self.get_writer(writer, **kwargs)
--> 634         writer.save_datasets(datasets, **kwargs)
635
636     def get_writer(self, writer="geotiff", **kwargs):

/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176                     coords = [line_coord, pixel_coord]
177
--> 178                 domain = cf.Domain(dim=coords,
179                                    aux=aux,
180                                    ref=grid_mapping)

AttributeError: 'module' object has no attribute 'Domain'

# Fixed code
def get_dataset(self, key, info):
    """Load a dataset."""
    if self.channel != key.name:
        return
    logger.debug("Reading %s.", key.name)

    radiances = self.nc[self.channel + "_radiance"]

    if key.calibration == "reflectance":
        idx = int(key.name[2:]) - 1
        sflux = self._get_solar_flux(idx)
        radiances = radiances / sflux * np.pi * 100
        radiances.attrs["units"] = "%"

    radiances.attrs["platform_name"] = self.platform_name
    radiances.attrs["sensor"] = self.sensor
    radiances.attrs.update(key.to_dict())
    return radiances
# Buggy code
def _collect_attrs(self, name, obj):
    """Collect all the attributes for the provided file object."""
    for key in obj.ncattrs():
        value = getattr(obj, key)
        value = np.squeeze(value)
        if issubclass(value.dtype.type, str) or np.issubdtype(
            value.dtype, np.character
        ):
            self.file_content["{}/attr/{}".format(name, key)] = str(value)
        else:
            self.file_content["{}/attr/{}".format(name, key)] = value


# Traceback (AttributeError)
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')

/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632             datasets = self.datasets.values()
633         writer = self.get_writer(writer, **kwargs)
--> 634         writer.save_datasets(datasets, **kwargs)
635
636     def get_writer(self, writer="geotiff", **kwargs):

/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176                     coords = [line_coord, pixel_coord]
177
--> 178                 domain = cf.Domain(dim=coords,
179                                    aux=aux,
180                                    ref=grid_mapping)

AttributeError: 'module' object has no attribute 'Domain'

# Fixed code
def _collect_attrs(self, name, obj):
    """Collect all the attributes for the provided file object."""
    for key in obj.ncattrs():
        value = getattr(obj, key)
        fc_key = "{}/attr/{}".format(name, key)
        try:
            self.file_content[fc_key] = np2str(value)
        except ValueError:
            self.file_content[fc_key] = value
# Buggy code
def __getitem__(self, key):
    val = self.file_content[key]
    if isinstance(val, netCDF4.Variable):
        # these datasets are closed and inaccessible when the file is
        # closed, need to reopen
        v = netCDF4.Dataset(self.filename, "r")
        val = v[key]
        val.set_auto_maskandscale(self.auto_maskandscale)
    return val


# Traceback (AttributeError)
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')

/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632             datasets = self.datasets.values()
633         writer = self.get_writer(writer, **kwargs)
--> 634         writer.save_datasets(datasets, **kwargs)
635
636     def get_writer(self, writer="geotiff", **kwargs):

/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176                     coords = [line_coord, pixel_coord]
177
--> 178                 domain = cf.Domain(dim=coords,
179                                    aux=aux,
180                                    ref=grid_mapping)

AttributeError: 'module' object has no attribute 'Domain'

# Fixed code
def __getitem__(self, key):
    val = self.file_content[key]
    if isinstance(val, netCDF4.Variable):
        # these datasets are closed and inaccessible when the file is
        # closed, need to reopen
        # TODO: Handle HDF4 versus NetCDF3 versus NetCDF4
        parts = key.rsplit("/", 1)
        if len(parts) == 2:
            group, key = parts
        else:
            group = None
        val = xr.open_dataset(
            self.filename,
            group=group,
            chunks=CHUNK_SIZE,
            mask_and_scale=self.auto_maskandscale,
        )[key]
    return val
# Buggy code
def get_shape(self, ds_id, ds_info):
    """Return data array shape for item specified."""
    var_path = ds_info.get("file_key", "{}".format(ds_id.name))
    shape = self[var_path + "/shape"]
    if "index" in ds_info:
        shape = shape[1:]
    if "pressure_index" in ds_info:
        shape = shape[:-1]
    return shape


# Traceback (AttributeError)
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')

/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632             datasets = self.datasets.values()
633         writer = self.get_writer(writer, **kwargs)
--> 634         writer.save_datasets(datasets, **kwargs)
635
636     def get_writer(self, writer="geotiff", **kwargs):

/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176                     coords = [line_coord, pixel_coord]
177
--> 178                 domain = cf.Domain(dim=coords,
179                                    aux=aux,
180                                    ref=grid_mapping)

AttributeError: 'module' object has no attribute 'Domain'

# Fixed code
def get_shape(self, ds_id, ds_info):
    """Return data array shape for item specified."""
    var_path = ds_info.get("file_key", "{}".format(ds_id.name))
    if var_path + "/shape" not in self:
        # loading a scalar value
        shape = 1
    else:
        shape = self[var_path + "/shape"]
        if "index" in ds_info:
            shape = shape[1:]
        if "pressure_index" in ds_info:
            shape = shape[:-1]
    return shape
# Buggy code
def __init__(self, config_files, mask_surface=True, mask_quality=True, **kwargs):
    """Configure reader behavior.

    Args:
        mask_surface (boolean): mask anything below the surface pressure
        mask_quality (boolean): mask anything where the `quality_flag` metadata is ``!= 1``.

    """
    self.pressure_dataset_names = defaultdict(list)
    super(NUCAPSReader, self).__init__(config_files, **kwargs)
    self.mask_surface = self.info.get("mask_surface", mask_surface)
    self.mask_quality = self.info.get("mask_quality", mask_quality)


# Traceback (AttributeError)
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')

/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632             datasets = self.datasets.values()
633         writer = self.get_writer(writer, **kwargs)
--> 634         writer.save_datasets(datasets, **kwargs)
635
636     def get_writer(self, writer="geotiff", **kwargs):

/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176                     coords = [line_coord, pixel_coord]
177
--> 178                 domain = cf.Domain(dim=coords,
179                                    aux=aux,
180                                    ref=grid_mapping)

AttributeError: 'module' object has no attribute 'Domain'

# Fixed code
def __init__(self, config_files, mask_surface=True, mask_quality=True, **kwargs):
    """Configure reader behavior.

    Args:
        mask_surface (boolean): mask anything below the surface pressure
        mask_quality (boolean): mask anything where the `Quality_Flag` metadata is ``!= 1``.

    """
    self.pressure_dataset_names = defaultdict(list)
    super(NUCAPSReader, self).__init__(config_files, **kwargs)
    self.mask_surface = self.info.get("mask_surface", mask_surface)
    self.mask_quality = self.info.get("mask_quality", mask_quality)
# Buggy code
def get_shape(self, ds_id, ds_info):
    var_path = ds_info.get("file_key", "observation_data/{}".format(ds_id.name))
    return self[var_path + "/shape"]


# Traceback (AttributeError)
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')

/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632             datasets = self.datasets.values()
633         writer = self.get_writer(writer, **kwargs)
--> 634         writer.save_datasets(datasets, **kwargs)
635
636     def get_writer(self, writer="geotiff", **kwargs):

/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176                     coords = [line_coord, pixel_coord]
177
--> 178                 domain = cf.Domain(dim=coords,
179                                    aux=aux,
180                                    ref=grid_mapping)

AttributeError: 'module' object has no attribute 'Domain'

# Fixed code
def get_shape(self, ds_id, ds_info):
    var_path = ds_info.get("file_key", "observation_data/{}".format(ds_id.name))
    return self.get(var_path + "/shape", 1)
# Buggy code
def _load_and_slice(self, dtype, var_path, shape, xslice, yslice):
    if isinstance(shape, tuple) and len(shape) == 2:
        return np.require(self[var_path][yslice, xslice], dtype=dtype)
    elif isinstance(shape, tuple) and len(shape) == 1:
        return np.require(self[var_path][yslice], dtype=dtype)
    else:
        return np.require(self[var_path][:], dtype=dtype)


# Traceback (AttributeError)
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')

/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632             datasets = self.datasets.values()
633         writer = self.get_writer(writer, **kwargs)
--> 634         writer.save_datasets(datasets, **kwargs)
635
636     def get_writer(self, writer="geotiff", **kwargs):

/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176                     coords = [line_coord, pixel_coord]
177
--> 178                 domain = cf.Domain(dim=coords,
179                                    aux=aux,
180                                    ref=grid_mapping)

AttributeError: 'module' object has no attribute 'Domain'

# Fixed code
def _load_and_slice(self, var_path, shape, xslice, yslice):
    if isinstance(shape, tuple) and len(shape) == 2:
        return self[var_path][yslice, xslice]
    elif isinstance(shape, tuple) and len(shape) == 1:
        return self[var_path][yslice]
    else:
        return self[var_path]
# Buggy code
def scale_swath_data(self, data, mask, scaling_factors):
    """Scale swath data using scaling factors and offsets.

    Multi-granule (a.k.a. aggregated) files will have more than the usual two values.
    """
    num_grans = len(scaling_factors) // 2
    gran_size = data.shape[0] // num_grans
    for i in range(num_grans):
        start_idx = i * gran_size
        end_idx = start_idx + gran_size
        m = scaling_factors[i * 2]
        b = scaling_factors[i * 2 + 1]
        # in rare cases the scaling factors are actually fill values
        if m <= -999 or b <= -999:
            mask[start_idx:end_idx] = 1
        else:
            data[start_idx:end_idx] *= m
            data[start_idx:end_idx] += b


# Traceback (AttributeError)
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')

/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632             datasets = self.datasets.values()
633         writer = self.get_writer(writer, **kwargs)
--> 634         writer.save_datasets(datasets, **kwargs)
635
636     def get_writer(self, writer="geotiff", **kwargs):

/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176                     coords = [line_coord, pixel_coord]
177
--> 178                 domain = cf.Domain(dim=coords,
179                                    aux=aux,
180                                    ref=grid_mapping)

AttributeError: 'module' object has no attribute 'Domain'

# Fixed code
def scale_swath_data(self, data, scaling_factors):
    """Scale swath data using scaling factors and offsets.

    Multi-granule (a.k.a. aggregated) files will have more than the usual two values.
    """
    num_grans = len(scaling_factors) // 2
    gran_size = data.shape[0] // num_grans
    factors = scaling_factors.where(scaling_factors > -999)
    factors = xr.DataArray(
        np.repeat(factors.values[None, :], gran_size, axis=0),
        dims=(data.dims[0], "factors"),
    )
    data = data * factors[:, 0] + factors[:, 1]
    return data
# Buggy code
def __init__(
    self, config_files, filter_parameters=None, filter_filenames=True, **kwargs
):
    super(FileYAMLReader, self).__init__(config_files)

    self.file_handlers = {}
    self.filter_filenames = self.info.get("filter_filenames", filter_filenames)
    self.filter_parameters = filter_parameters or {}
    if kwargs:
        logger.warning(
            "Unrecognized/unused reader keyword argument(s) '{}'".format(kwargs)
        )


# Traceback (AttributeError)
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')

/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632             datasets = self.datasets.values()
633         writer = self.get_writer(writer, **kwargs)
--> 634         writer.save_datasets(datasets, **kwargs)
635
636     def get_writer(self, writer="geotiff", **kwargs):

/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176                     coords = [line_coord, pixel_coord]
177
--> 178                 domain = cf.Domain(dim=coords,
179                                    aux=aux,
180                                    ref=grid_mapping)

AttributeError: 'module' object has no attribute 'Domain'

# Fixed code
def __init__(
    self, config_files, filter_parameters=None, filter_filenames=True, **kwargs
):
    super(FileYAMLReader, self).__init__(config_files)

    self.file_handlers = {}
    self.filter_filenames = self.info.get("filter_filenames", filter_filenames)
    self.filter_parameters = filter_parameters or {}
    if kwargs:
        logger.warning(
            "Unrecognized/unused reader keyword argument(s) '{}'".format(kwargs)
        )
    self.coords_cache = WeakValueDictionary()
# Buggy code
def _load_dataset_data(
    self, file_handlers, dsid, xslice=slice(None), yslice=slice(None)
):
    ds_info = self.ids[dsid]
    try:
        # Can we allow the file handlers to do inplace data writes?
        [list(fhd.get_shape(dsid, ds_info)) for fhd in file_handlers]
    except NotImplementedError:
        # FIXME: Is NotImplementedError included in Exception for all
        # versions of Python?
        proj = self._load_entire_dataset(dsid, ds_info, file_handlers)
    else:
        proj = self._load_sliced_dataset(dsid, ds_info, file_handlers, xslice, yslice)
    # FIXME: areas could be concatenated here
    # Update the metadata
    proj.info["start_time"] = file_handlers[0].start_time
    proj.info["end_time"] = file_handlers[-1].end_time

    return proj


# Traceback (AttributeError)
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')

/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632             datasets = self.datasets.values()
633         writer = self.get_writer(writer, **kwargs)
--> 634         writer.save_datasets(datasets, **kwargs)
635
636     def get_writer(self, writer="geotiff", **kwargs):

/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176                     coords = [line_coord, pixel_coord]
177
--> 178                 domain = cf.Domain(dim=coords,
179                                    aux=aux,
180                                    ref=grid_mapping)

AttributeError: 'module' object has no attribute 'Domain'

# Fixed code
def _load_dataset_data(
    self, file_handlers, dsid, xslice=slice(None), yslice=slice(None)
):
    ds_info = self.ids[dsid]
    proj = self._load_dataset(dsid, ds_info, file_handlers)
    # FIXME: areas could be concatenated here
    # Update the metadata
    proj.attrs["start_time"] = file_handlers[0].start_time
    proj.attrs["end_time"] = file_handlers[-1].end_time

    return proj
# Buggy code
def _load_dataset_with_area(self, dsid, coords):
    """Loads *dsid* and it's area if available."""
    file_handlers = self._get_file_handlers(dsid)
    if not file_handlers:
        return

    area = self._load_dataset_area(dsid, file_handlers, coords)
    slice_kwargs, area = self._get_slices(area)

    try:
        ds = self._load_dataset_data(file_handlers, dsid, **slice_kwargs)
    except (KeyError, ValueError) as err:
        logger.exception("Could not load dataset '%s': %s", dsid, str(err))
        return None

    if area is not None:
        ds.info["area"] = area
    return ds


# Traceback (AttributeError)
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')

/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632             datasets = self.datasets.values()
633         writer = self.get_writer(writer, **kwargs)
--> 634         writer.save_datasets(datasets, **kwargs)
635
636     def get_writer(self, writer="geotiff", **kwargs):

/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176                     coords = [line_coord, pixel_coord]
177
--> 178                 domain = cf.Domain(dim=coords,
179                                    aux=aux,
180                                    ref=grid_mapping)

AttributeError: 'module' object has no attribute 'Domain'

# Fixed code
def _load_dataset_with_area(self, dsid, coords):
    """Loads *dsid* and it's area if available."""
    file_handlers = self._get_file_handlers(dsid)
    if not file_handlers:
        return

    area = self._load_dataset_area(dsid, file_handlers, coords)
    slice_kwargs, area = self._get_slices(area)

    try:
        ds = self._load_dataset_data(file_handlers, dsid, **slice_kwargs)
    except (KeyError, ValueError) as err:
        logger.exception("Could not load dataset '%s': %s", dsid, str(err))
        return None

    if area is not None:
        ds.attrs["area"] = area
        if (("x" not in ds.coords) or ("y" not in ds.coords)) and hasattr(
            area, "get_proj_vectors_dask"
        ):
            ds["x"], ds["y"] = area.get_proj_vectors_dask(CHUNK_SIZE)
    return ds
# Buggy code
def load(self, dataset_keys):
    """Load *dataset_keys*."""
    all_datasets = DatasetDict()
    datasets = DatasetDict()

    # Include coordinates in the list of datasets to load
    dsids = [self.get_dataset_key(ds_key) for ds_key in dataset_keys]
    coordinates = self._get_coordinates_for_dataset_keys(dsids)
    all_dsids = list(set().union(*coordinates.values())) + dsids

    for dsid in all_dsids:
        coords = [all_datasets.get(cid, None) for cid in coordinates.get(dsid, [])]
        ds = self._load_dataset_with_area(dsid, coords)
        if ds is not None:
            all_datasets[dsid] = ds
            if dsid in dsids:
                datasets[dsid] = ds

    return datasets


# Traceback (AttributeError)
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')

/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632             datasets = self.datasets.values()
633         writer = self.get_writer(writer, **kwargs)
--> 634         writer.save_datasets(datasets, **kwargs)
635
636     def get_writer(self, writer="geotiff", **kwargs):

/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176                     coords = [line_coord, pixel_coord]
177
--> 178                 domain = cf.Domain(dim=coords,
179                                    aux=aux,
180                                    ref=grid_mapping)

AttributeError: 'module' object has no attribute 'Domain'

# Fixed code
def load(self, dataset_keys, previous_datasets=None):
    """Load `dataset_keys`.

    If `previous_datasets` is provided, do not reload those."""
    all_datasets = previous_datasets or DatasetDict()
    datasets = DatasetDict()

    # Include coordinates in the list of datasets to load
    dsids = [self.get_dataset_key(ds_key) for ds_key in dataset_keys]
    coordinates = self._get_coordinates_for_dataset_keys(dsids)
    all_dsids = list(set().union(*coordinates.values())) + dsids

    for dsid in all_dsids:
        if dsid in all_datasets:
            continue
        coords = [all_datasets.get(cid, None) for cid in coordinates.get(dsid, [])]
        ds = self._load_dataset_with_area(dsid, coords)
        if ds is not None:
            all_datasets[dsid] = ds
            if dsid in dsids:
                datasets[dsid] = ds
    self._load_ancillary_variables(all_datasets)

    return datasets
# Buggy code
def get_area_file():
    conf, successes = get_config("satpy.cfg")
    if conf is None or not successes:
        LOG.warning(
            "Couldn't find the satpy.cfg file. Do you have one ? is it in $PPP_CONFIG_DIR ?"
        )
        return None

    try:
        fn = os.path.join(
            conf.get("projector", "area_directory") or "",
            conf.get("projector", "area_file"),
        )
        return get_config_path(fn)
    except configparser.NoSectionError:
        LOG.warning("Couldn't find 'projector' section of 'satpy.cfg'")


# Traceback (AttributeError)
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')

/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632             datasets = self.datasets.values()
633         writer = self.get_writer(writer, **kwargs)
--> 634         writer.save_datasets(datasets, **kwargs)
635
636     def get_writer(self, writer="geotiff", **kwargs):

/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176                     coords = [line_coord, pixel_coord]
177
--> 178                 domain = cf.Domain(dim=coords,
179                                    aux=aux,
180                                    ref=grid_mapping)

AttributeError: 'module' object has no attribute 'Domain'

# Fixed code
def get_area_file():
    """Find area file(s) to use.

    The files are to be named `areas.yaml` or `areas.def`.
    """
    paths = config_search_paths("areas.yaml")
    if paths:
        return paths
    else:
        return get_config_path("areas.def")
# Buggy code
def hash_area(area):
    """Get (and set) the hash for the *area*."""
    try:
        return area.kdtree_hash
    except AttributeError:
        LOG.debug("Computing kd-tree hash for area %s", getattr(area, "name", "swath"))
    try:
        area_hash = "".join(
            (
                hashlib.sha1(
                    json.dumps(area.proj_dict, sort_keys=True).encode("utf-8")
                ).hexdigest(),
                hashlib.sha1(json.dumps(area.area_extent).encode("utf-8")).hexdigest(),
                hashlib.sha1(
                    json.dumps((int(area.shape[0]), int(area.shape[1]))).encode("utf-8")
                ).hexdigest(),
            )
        )
    except AttributeError:
        if not hasattr(area, "lons") or area.lons is None:
            lons, lats = area.get_lonlats()
        else:
            lons, lats = area.lons, area.lats

        try:
            mask_hash = hashlib.sha1(lons.mask | lats.mask).hexdigest()
        except AttributeError:
            mask_hash = "False"
        area_hash = "".join(
            (mask_hash, hashlib.sha1(lons).hexdigest(), hashlib.sha1(lats).hexdigest())
        )
    area.kdtree_hash = area_hash
    return area_hash


# Traceback (AttributeError)
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')

/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632             datasets = self.datasets.values()
633         writer = self.get_writer(writer, **kwargs)
--> 634         writer.save_datasets(datasets, **kwargs)
635
636     def get_writer(self, writer="geotiff", **kwargs):

/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176                     coords = [line_coord, pixel_coord]
177
--> 178                 domain = cf.Domain(dim=coords,
179                                    aux=aux,
180                                    ref=grid_mapping)

AttributeError: 'module' object has no attribute 'Domain'

# Fixed code
def hash_area(area):
    """Get (and set) the hash for the *area*."""
    return str(area.__hash__())
# Buggy code
def resample(self, data, cache_dir=False, mask_area=True, **kwargs):
    """Resample the *data*, saving the projection info on disk if *precompute* evaluates to True.

    :param mask_area: Provide data mask to `precompute` method to mask invalid data values in geolocation.
    """
    if mask_area and hasattr(data, "mask"):
        kwargs.setdefault("mask", data.mask)
    cache_id = self.precompute(cache_dir=cache_dir, **kwargs)
    return self.compute(data, cache_id=cache_id, **kwargs)


# Traceback (AttributeError)
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')

/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632             datasets = self.datasets.values()
633         writer = self.get_writer(writer, **kwargs)
--> 634         writer.save_datasets(datasets, **kwargs)
635
636     def get_writer(self, writer="geotiff", **kwargs):

/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176                     coords = [line_coord, pixel_coord]
177
--> 178                 domain = cf.Domain(dim=coords,
179                                    aux=aux,
180                                    ref=grid_mapping)

AttributeError: 'module' object has no attribute 'Domain'

# Fixed code
def resample(self, data, cache_dir=False, mask_area=True, **kwargs):
    """Resample the *data*, saving the projection info on disk if *precompute* evaluates to True.

    :param mask_area: Provide data mask to `precompute` method to mask invalid data values in geolocation.
    """
    if mask_area:
        mask = kwargs.get("mask", np.zeros_like(data, dtype=np.bool))
        if data.attrs.get("_FillValue"):
            mask = xu.logical_and(data, data == data.attrs["_FillValue"])
        if hasattr(data, "mask"):
            mask = xu.logical_and(data, data.mask)
        elif hasattr(data, "isnull"):
            mask = xu.logical_and(data, data.isnull())
        summing_dims = [dim for dim in data.dims if dim not in ["x", "y"]]
        mask = mask.sum(dim=summing_dims).astype(bool)
        kwargs["mask"] = mask
    cache_id = self.precompute(cache_dir=cache_dir, **kwargs)
    data.attrs["_last_resampler"] = self
    return self.compute(data, cache_id=cache_id, **kwargs)
# Buggy code
def _read_params_from_cache(self, cache_dir, hash_str, filename):
    """Read resampling parameters from cache"""
    try:
        self.cache = self.caches[hash_str]
        # trick to keep most used caches away from deletion
        del self.caches[hash_str]
        self.caches[hash_str] = self.cache

        if cache_dir:
            self.dump(filename)
        return
    except KeyError:
        if os.path.exists(filename):
            self.cache = dict(np.load(filename))
            self.caches[hash_str] = self.cache
            while len(self.caches) > CACHE_SIZE:
                self.caches.popitem(False)
            if cache_dir:
                self.dump(filename)
        else:
            self.cache = None


# Traceback (AttributeError)
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')

/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632             datasets = self.datasets.values()
633         writer = self.get_writer(writer, **kwargs)
--> 634         writer.save_datasets(datasets, **kwargs)
635
636     def get_writer(self, writer="geotiff", **kwargs):

/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176                     coords = [line_coord, pixel_coord]
177
--> 178                 domain = cf.Domain(dim=coords,
179                                    aux=aux,
180                                    ref=grid_mapping)

AttributeError: 'module' object has no attribute 'Domain'

# Fixed code
def _read_params_from_cache(self, cache_dir, hash_str, filename):
    """Read resampling parameters from cache"""
    self.cache = self.caches.pop(hash_str, None)
    if self.cache is not None and cache_dir:
        self.dump(filename)
    elif os.path.exists(filename):
        self.cache = dict(np.load(filename))
        self.caches[hash_str] = self.cache
# Buggy code
def _update_caches(self, hash_str, cache_dir, filename):
    """Update caches and dump new resampling parameters to disk"""
    self.caches[hash_str] = self.cache
    while len(self.caches) > CACHE_SIZE:
        self.caches.popitem(False)

    if cache_dir:
        # XXX: Look in to doing memmap-able files instead
        # `arr.tofile(filename)`
        self.dump(filename)


# Traceback (AttributeError)
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')

/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632             datasets = self.datasets.values()
633         writer = self.get_writer(writer, **kwargs)
--> 634         writer.save_datasets(datasets, **kwargs)
635
636     def get_writer(self, writer="geotiff", **kwargs):

/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176                     coords = [line_coord, pixel_coord]
177
--> 178                 domain = cf.Domain(dim=coords,
179                                    aux=aux,
180                                    ref=grid_mapping)

AttributeError: 'module' object has no attribute 'Domain'

# Fixed code
def _update_caches(self, hash_str, cache_dir, filename):
    """Update caches and dump new resampling parameters to disk"""
    self.caches[hash_str] = self.cache
    if cache_dir:
        # XXX: Look in to doing memmap-able files instead
        # `arr.tofile(filename)`
        self.dump(filename)
# Buggy code
def compute(
    self, data, weight_funcs=None, fill_value=None, with_uncert=False, **kwargs
):
    del kwargs

    return get_sample_from_neighbour_info(
        "nn",
        self.target_geo_def.shape,
        data,
        self.cache["valid_input_index"],
        self.cache["valid_output_index"],
        self.cache["index_array"],
        distance_array=self.cache["distance_array"],
        weight_funcs=weight_funcs,
        fill_value=fill_value,
        with_uncert=with_uncert,
    )


# Traceback (AttributeError)
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')

/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632             datasets = self.datasets.values()
633         writer = self.get_writer(writer, **kwargs)
--> 634         writer.save_datasets(datasets, **kwargs)
635
636     def get_writer(self, writer="geotiff", **kwargs):

/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176                     coords = [line_coord, pixel_coord]
177
--> 178                 domain = cf.Domain(dim=coords,
179                                    aux=aux,
180                                    ref=grid_mapping)

AttributeError: 'module' object has no attribute 'Domain'

# Fixed code
def compute(
    self, data, weight_funcs=None, fill_value=None, with_uncert=False, **kwargs
):
    del kwargs
    LOG.debug("Resampling " + str(data.name))
    if fill_value is None:
        fill_value = data.attrs.get("_FillValue")
    res = self.resampler.get_sample_from_neighbour_info(data, fill_value)
    return res
# Buggy code
def _get_sensor_names(self):
    """Join the sensors from all loaded readers."""
    # if the user didn't tell us what sensors to work with, let's figure it
    # out
    if not self.info.get("sensor"):
        # reader finder could return multiple readers
        return set(
            [
                sensor
                for reader_instance in self.readers.values()
                for sensor in reader_instance.sensor_names
            ]
        )
    elif not isinstance(self.info["sensor"], (set, tuple, list)):
        return set([self.info["sensor"]])
    else:
        return set(self.info["sensor"])


# Traceback (AttributeError)
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')

/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632             datasets = self.datasets.values()
633         writer = self.get_writer(writer, **kwargs)
--> 634         writer.save_datasets(datasets, **kwargs)
635
636     def get_writer(self, writer="geotiff", **kwargs):

/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176                     coords = [line_coord, pixel_coord]
177
--> 178                 domain = cf.Domain(dim=coords,
179                                    aux=aux,
180                                    ref=grid_mapping)

AttributeError: 'module' object has no attribute 'Domain'

# Fixed code
def _get_sensor_names(self):
    """Join the sensors from all loaded readers."""
    # if the user didn't tell us what sensors to work with, let's figure it
    # out
    if not self.attrs.get("sensor"):
        # reader finder could return multiple readers
        return set(
            [
                sensor
                for reader_instance in self.readers.values()
                for sensor in reader_instance.sensor_names
            ]
        )
    elif not isinstance(self.attrs["sensor"], (set, tuple, list)):
        return set([self.attrs["sensor"]])
    else:
        return set(self.attrs["sensor"])
# Buggy code
def start_time(self):
    """Return the start time of the file."""
    return self.info["start_time"]


# Traceback (AttributeError)
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] Saving datasets to NetCDF4/CF.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No longitude and latitude data to save.
[INFO: 2017-12-12 08:14:04 : satpy.writers.cf_writer] No grid mapping to save.
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-24-58ece08c15f3> in <module>()
----> 1 lcl.save_datasets(writer='cf', filename='/tmp/foo.nc')

/home/lahtinep/Software/pytroll/packages/satpy/satpy/scene.pyc in save_datasets(self, writer, datasets, **kwargs)
632             datasets = self.datasets.values()
633         writer = self.get_writer(writer, **kwargs)
--> 634         writer.save_datasets(datasets, **kwargs)
635
636     def get_writer(self, writer="geotiff", **kwargs):

/home/lahtinep/Software/pytroll/packages/satpy/satpy/writers/cf_writer.pyc in save_datasets(self, datasets, filename, **kwargs)
176                     coords = [line_coord, pixel_coord]
177
--> 178                 domain = cf.Domain(dim=coords,
179                                    aux=aux,
180                                    ref=grid_mapping)

AttributeError: 'module' object has no attribute 'Domain'

# Fixed code
def start_time(self):
    """Return the start time of the file."""
    return self.attrs["start_time"]