gurudesh/pytracebugs huggingface dataset:
# Buggy code
def create_from_config(config, prefix=""):
    """Create a PostgreSQLClient client using settings in the provided config."""
    if sqlalchemy is None:
        message = (
            "PostgreSQL dependencies missing. "
            "Refer to installation section in documentation."
        )
        raise ImportWarning(message)

    settings = config.get_settings()
    url = settings[prefix + "url"]

    if url in _ENGINES:
        msg = (
            "Reuse existing PostgreSQL connection. "
            "Parameters %s* will be ignored." % prefix
        )
        warnings.warn(msg)
        return PostgreSQLClient(_ENGINES[url])

    # Initialize SQLAlchemy engine.
    poolclass_key = prefix + "poolclass"
    settings.setdefault(poolclass_key, "sqlalchemy.pool.QueuePool")
    settings[poolclass_key] = config.maybe_dotted(settings[poolclass_key])
    settings.pop(prefix + "max_fetch_size", None)
    settings.pop(prefix + "backend", None)

    # XXX: Disable pooling at least during tests to avoid stalled tests.
    if os.getenv("TRAVIS", False):  # pragma: no cover
        warnings.warn("Disable pooling on TravisCI")
        settings = dict([(poolclass_key, sqlalchemy.pool.StaticPool)])

    engine = sqlalchemy.engine_from_config(settings, prefix=prefix, url=url)

    # Store one engine per URI.
    _ENGINES[url] = engine

    return PostgreSQLClient(engine)


# Traceback (AttributeError)
web_1   | Traceback (most recent call last):
web_1   |   File "/usr/local/lib/python3.5/dist-packages/cliquet/initialization.py", line 399, in setup_listeners
web_1   |     listener = listener_mod.load_from_config(config, prefix)
web_1   | AttributeError: module 'redis' has no attribute 'load_from_config'

# Fixed code
def create_from_config(config, prefix=""):
    """Create a PostgreSQLClient client using settings in the provided config."""
    if sqlalchemy is None:
        message = (
            "PostgreSQL dependencies missing. "
            "Refer to installation section in documentation."
        )
        raise ImportWarning(message)

    settings = config.get_settings()
    url = settings[prefix + "url"]

    if url in _ENGINES:
        msg = (
            "Reuse existing PostgreSQL connection. "
            "Parameters %s* will be ignored." % prefix
        )
        warnings.warn(msg)
        return PostgreSQLClient(_ENGINES[url])

    # Initialize SQLAlchemy engine.
    poolclass_key = prefix + "poolclass"
    settings.setdefault(poolclass_key, "sqlalchemy.pool.QueuePool")
    settings[poolclass_key] = config.maybe_dotted(settings[poolclass_key])
    settings.pop(prefix + "max_fetch_size", None)
    settings.pop(prefix + "backend", None)

    engine = sqlalchemy.engine_from_config(settings, prefix=prefix, url=url)

    # Store one engine per URI.
    _ENGINES[url] = engine

    return PostgreSQLClient(engine)
# Buggy code
def render_template(template, destination, **kwargs):
    template = os.path.join(HERE, template)

    with codecs.open(template, "r", encoding="utf-8") as f:
        raw_template = f.read()
        rendered = raw_template.format(**kwargs)
        with codecs.open(destination, "w+", encoding="utf-8") as output:
            output.write(rendered)


# Traceback (IOError)
kinto init
Which backend to use? (1 - postgresql, 2 - redis, default - memory)
Traceback (most recent call last):
File "/var/www/kinto.leplat.re/venv/bin/kinto", line 9, in <module>
load_entry_point('kinto==1.9.0', 'console_scripts', 'kinto')()
File "/var/www/kinto.leplat.re/venv/local/lib/python2.7/site-packages/kinto/__main__.py", line 44, in main
init(config_file)
File "/var/www/kinto.leplat.re/venv/local/lib/python2.7/site-packages/kinto/config/__init__.py", line 61, in init
permission_url=values['permission_url'])
File "/var/www/kinto.leplat.re/venv/local/lib/python2.7/site-packages/kinto/config/__init__.py", line 15, in render_template
with codecs.open(destination, 'w+', encoding='utf-8') as output:
File "/var/www/kinto.leplat.re/venv/lib/python2.7/codecs.py", line 881, in open
file = __builtin__.open(filename, mode, buffering)
IOError: [Errno 2] No such file or directory: 'config/kinto.ini'

# Fixed code
def render_template(template, destination, **kwargs):
    template = os.path.join(HERE, template)

    folder = os.path.dirname(destination)
    os.makedirs(folder)

    with codecs.open(template, "r", encoding="utf-8") as f:
        raw_template = f.read()
        rendered = raw_template.format(**kwargs)
        with codecs.open(destination, "w+", encoding="utf-8") as output:
            output.write(rendered)
# Buggy code
def __init__(self, file, fs=None):
    """Initialise the FSFile instance.

    *file* can be string or an fsspec.OpenFile instance. In the latter case, the follow argument *fs* has no effect.
    *fs* can be None or a fsspec filesystem instance.
    """
    try:
        self._file = file.path
        self._fs = file.fs
    except AttributeError:
        self._file = file
        self._fs = fs


# Traceback (TypeError)
Traceback (most recent call last):
File "mwe/mwe002.py", line 5, in <module>
print(str(fsf))
TypeError: __str__ returned non-string (type PosixPath)

# Fixed code
def __init__(self, file, fs=None):
    """Initialise the FSFile instance.

    Args:
        file (str, Pathlike, or OpenFile):
            String, object implementing the `os.PathLike` protocol, or
            an `fsspec.OpenFile` instance.  If passed an instance of
            `fsspec.OpenFile`, the following argument ``fs`` has no
            effect.
        fs (fsspec filesystem, optional)
            Object implementing the fsspec filesystem protocol.
    """
    try:
        self._file = file.path
        self._fs = file.fs
    except AttributeError:
        self._file = file
        self._fs = fs
# Buggy code
def __str__(self):
    """Return the string version of the filename."""
    return self._file


# Traceback (TypeError)
Traceback (most recent call last):
File "mwe/mwe002.py", line 5, in <module>
print(str(fsf))
TypeError: __str__ returned non-string (type PosixPath)

# Fixed code
def __str__(self):
    """Return the string version of the filename."""
    return os.fspath(self._file)
# Buggy code
def __fspath__(self):
    """Comply with PathLike."""
    return self._file


# Traceback (TypeError)
Traceback (most recent call last):
File "mwe/mwe002.py", line 5, in <module>
print(str(fsf))
TypeError: __str__ returned non-string (type PosixPath)

# Fixed code
def __fspath__(self):
    """Comply with PathLike."""
    return os.fspath(self._file)
# Buggy code
def __init__(self, filename, filename_info, filetype_info):
    """Initialize object information by reading the input file."""
    super(AVHRRAAPPL1BFile, self).__init__(filename, filename_info, filetype_info)
    self.channels = {i: None for i in AVHRR_CHANNEL_NAMES}
    self.units = {i: "counts" for i in AVHRR_CHANNEL_NAMES}

    self._data = None
    self._header = None
    self._is3b = None
    self._is3a = None
    self._shape = None
    self.lons = None
    self.lats = None
    self.area = None
    self.sensor = "avhrr-3"
    self.read()

    self.platform_name = PLATFORM_NAMES.get(self._header["satid"][0], None)

    if self.platform_name is None:
        raise ValueError("Unsupported platform ID: %d" % self.header["satid"])

    self.sunz, self.satz, self.azidiff = None, None, None


# Traceback (ValueError)
Traceback (most recent call last):
File "/home/a001673/usr/src/satpy/satpy/readers/yaml_reader.py", line 785, in _load_dataset_with_area
ds = self._load_dataset_data(file_handlers, dsid, **kwargs)
File "/home/a001673/usr/src/satpy/satpy/readers/yaml_reader.py", line 668, in _load_dataset_data
proj = self._load_dataset(dsid, ds_info, file_handlers, **kwargs)
File "/home/a001673/usr/src/satpy/satpy/readers/yaml_reader.py", line 644, in _load_dataset
projectable = fh.get_dataset(dsid, ds_info)
File "/home/a001673/usr/src/satpy/satpy/readers/aapp_l1b.py", line 112, in get_dataset
dataset = self.calibrate(key)
File "/home/a001673/usr/src/satpy/satpy/readers/aapp_l1b.py", line 234, in calibrate
raise ValueError("Empty dataset for channel 3A")
ValueError: Empty dataset for channel 3A

# Fixed code
def __init__(self, filename, filename_info, filetype_info):
    """Initialize object information by reading the input file."""
    super(AVHRRAAPPL1BFile, self).__init__(filename, filename_info, filetype_info)
    self.channels = {i: None for i in AVHRR_CHANNEL_NAMES}
    self.units = {i: "counts" for i in AVHRR_CHANNEL_NAMES}

    self._data = None
    self._header = None
    self._is3b = None
    self._is3a = None
    self._shape = None
    self.area = None
    self.sensor = "avhrr-3"
    self.read()

    self.active_channels = self._get_active_channels()

    self.platform_name = PLATFORM_NAMES.get(self._header["satid"][0], None)

    if self.platform_name is None:
        raise ValueError("Unsupported platform ID: %d" % self.header["satid"])
# Buggy code
def get_dataset(self, key, info):
    """Get a dataset from the file."""
    if key["name"] in CHANNEL_NAMES:
        dataset = self.calibrate(key)
    elif key["name"] in ["longitude", "latitude"]:
        if self.lons is None or self.lats is None:
            self.navigate()
        if key["name"] == "longitude":
            dataset = create_xarray(self.lons)
        else:
            dataset = create_xarray(self.lats)
        dataset.attrs = info
    else:  # Get sun-sat angles
        if key["name"] in ANGLES:
            if isinstance(getattr(self, ANGLES[key["name"]]), np.ndarray):
                dataset = create_xarray(getattr(self, ANGLES[key["name"]]))
            else:
                dataset = self.get_angles(key["name"])
        else:
            raise ValueError(
                "Not a supported sun-sensor viewing angle: %s", key["name"]
            )

    dataset.attrs.update({"platform_name": self.platform_name, "sensor": self.sensor})
    dataset.attrs.update(key.to_dict())
    for meta_key in ("standard_name", "units"):
        if meta_key in info:
            dataset.attrs.setdefault(meta_key, info[meta_key])

    if not self._shape:
        self._shape = dataset.shape

    return dataset


# Traceback (ValueError)
Traceback (most recent call last):
File "/home/a001673/usr/src/satpy/satpy/readers/yaml_reader.py", line 785, in _load_dataset_with_area
ds = self._load_dataset_data(file_handlers, dsid, **kwargs)
File "/home/a001673/usr/src/satpy/satpy/readers/yaml_reader.py", line 668, in _load_dataset_data
proj = self._load_dataset(dsid, ds_info, file_handlers, **kwargs)
File "/home/a001673/usr/src/satpy/satpy/readers/yaml_reader.py", line 644, in _load_dataset
projectable = fh.get_dataset(dsid, ds_info)
File "/home/a001673/usr/src/satpy/satpy/readers/aapp_l1b.py", line 112, in get_dataset
dataset = self.calibrate(key)
File "/home/a001673/usr/src/satpy/satpy/readers/aapp_l1b.py", line 234, in calibrate
raise ValueError("Empty dataset for channel 3A")
ValueError: Empty dataset for channel 3A

# Fixed code
def get_dataset(self, key, info):
    """Get a dataset from the file."""
    if key["name"] in CHANNEL_NAMES:
        if self.active_channels[key["name"]]:
            dataset = self.calibrate(key)
        else:
            return None
    elif key["name"] in ["longitude", "latitude"]:
        dataset = self.navigate(key["name"])
        dataset.attrs = info
    elif key["name"] in ANGLES:
        dataset = self.get_angles(key["name"])
    else:
        raise ValueError("Not a supported dataset: %s", key["name"])

    self._update_dataset_attributes(dataset, key, info)

    if not self._shape:
        self._shape = dataset.shape

    return dataset
# Buggy code
def get_angles(self, angle_id):
    """Get sun-satellite viewing angles."""
    sunz40km = self._data["ang"][:, :, 0] * 1e-2
    satz40km = self._data["ang"][:, :, 1] * 1e-2
    azidiff40km = self._data["ang"][:, :, 2] * 1e-2

    try:
        from geotiepoints.interpolator import Interpolator
    except ImportError:
        logger.warning(
            "Could not interpolate sun-sat angles, python-geotiepoints missing."
        )
        self.sunz, self.satz, self.azidiff = sunz40km, satz40km, azidiff40km
    else:
        cols40km = np.arange(24, 2048, 40)
        cols1km = np.arange(2048)
        lines = sunz40km.shape[0]
        rows40km = np.arange(lines)
        rows1km = np.arange(lines)

        along_track_order = 1
        cross_track_order = 3

        satint = Interpolator(
            [sunz40km, satz40km, azidiff40km],
            (rows40km, cols40km),
            (rows1km, cols1km),
            along_track_order,
            cross_track_order,
        )
        self.sunz, self.satz, self.azidiff = delayed(satint.interpolate, nout=3)()
        self.sunz = da.from_delayed(self.sunz, (lines, 2048), sunz40km.dtype)
        self.satz = da.from_delayed(self.satz, (lines, 2048), satz40km.dtype)
        self.azidiff = da.from_delayed(self.azidiff, (lines, 2048), azidiff40km.dtype)

    return create_xarray(getattr(self, ANGLES[angle_id]))


# Traceback (ValueError)
Traceback (most recent call last):
File "/home/a001673/usr/src/satpy/satpy/readers/yaml_reader.py", line 785, in _load_dataset_with_area
ds = self._load_dataset_data(file_handlers, dsid, **kwargs)
File "/home/a001673/usr/src/satpy/satpy/readers/yaml_reader.py", line 668, in _load_dataset_data
proj = self._load_dataset(dsid, ds_info, file_handlers, **kwargs)
File "/home/a001673/usr/src/satpy/satpy/readers/yaml_reader.py", line 644, in _load_dataset
projectable = fh.get_dataset(dsid, ds_info)
File "/home/a001673/usr/src/satpy/satpy/readers/aapp_l1b.py", line 112, in get_dataset
dataset = self.calibrate(key)
File "/home/a001673/usr/src/satpy/satpy/readers/aapp_l1b.py", line 234, in calibrate
raise ValueError("Empty dataset for channel 3A")
ValueError: Empty dataset for channel 3A

# Fixed code
def get_angles(self, angle_id):
    """Get sun-satellite viewing angles."""
    sunz, satz, azidiff = self._get_all_interpolated_angles()

    name_to_variable = dict(zip(ANGLES, (satz, sunz, azidiff)))
    return create_xarray(name_to_variable[angle_id])
# Buggy code
def navigate(self):
    """Get the longitudes and latitudes of the scene."""
    lons40km = self._data["pos"][:, :, 1] * 1e-4
    lats40km = self._data["pos"][:, :, 0] * 1e-4

    try:
        from geotiepoints import SatelliteInterpolator
    except ImportError:
        logger.warning("Could not interpolate lon/lats, python-geotiepoints missing.")
        self.lons, self.lats = lons40km, lats40km
    else:
        cols40km = np.arange(24, 2048, 40)
        cols1km = np.arange(2048)
        lines = lons40km.shape[0]
        rows40km = np.arange(lines)
        rows1km = np.arange(lines)

        along_track_order = 1
        cross_track_order = 3

        satint = SatelliteInterpolator(
            (lons40km, lats40km),
            (rows40km, cols40km),
            (rows1km, cols1km),
            along_track_order,
            cross_track_order,
        )
        self.lons, self.lats = delayed(satint.interpolate, nout=2)()
        self.lons = da.from_delayed(self.lons, (lines, 2048), lons40km.dtype)
        self.lats = da.from_delayed(self.lats, (lines, 2048), lats40km.dtype)


# Traceback (ValueError)
Traceback (most recent call last):
File "/home/a001673/usr/src/satpy/satpy/readers/yaml_reader.py", line 785, in _load_dataset_with_area
ds = self._load_dataset_data(file_handlers, dsid, **kwargs)
File "/home/a001673/usr/src/satpy/satpy/readers/yaml_reader.py", line 668, in _load_dataset_data
proj = self._load_dataset(dsid, ds_info, file_handlers, **kwargs)
File "/home/a001673/usr/src/satpy/satpy/readers/yaml_reader.py", line 644, in _load_dataset
projectable = fh.get_dataset(dsid, ds_info)
File "/home/a001673/usr/src/satpy/satpy/readers/aapp_l1b.py", line 112, in get_dataset
dataset = self.calibrate(key)
File "/home/a001673/usr/src/satpy/satpy/readers/aapp_l1b.py", line 234, in calibrate
raise ValueError("Empty dataset for channel 3A")
ValueError: Empty dataset for channel 3A

# Fixed code
def navigate(self, coordinate_id):
    """Get the longitudes and latitudes of the scene."""
    lons, lats = self._get_all_interpolated_coordinates()
    if coordinate_id == "longitude":
        return create_xarray(lons)
    elif coordinate_id == "latitude":
        return create_xarray(lats)
    else:
        raise KeyError("Coordinate {} unknown.".format(coordinate_id))
# Buggy code
def __init__(self, filename, filename_info, filetype_info):
    """Init the olci reader base."""
    super(NCOLCIBase, self).__init__(filename, filename_info, filetype_info)
    self.nc = xr.open_dataset(
        self.filename,
        decode_cf=True,
        mask_and_scale=True,
        engine="h5netcdf",
        chunks={"columns": CHUNK_SIZE, "rows": CHUNK_SIZE},
    )

    self.nc = self.nc.rename({"columns": "x", "rows": "y"})

    # TODO: get metadata from the manifest file (xfdumanifest.xml)
    self.platform_name = PLATFORM_NAMES[filename_info["mission_id"]]
    self.sensor = "olci"


# Traceback (ImportError)
Traceback (most recent call last):
File "/network/aopp/apres/users/proud/satpyconda/lib/python3.7/site-packages/xarray/backends/file_manager.py", line 243, in __del__
File "/network/aopp/apres/users/proud/satpyconda/lib/python3.7/site-packages/xarray/backends/file_manager.py", line 221, in close
File "/network/aopp/apres/users/proud/satpyconda/lib/python3.7/site-packages/h5netcdf/core.py", line 701, in close
File "/network/aopp/apres/users/proud/satpyconda/lib/python3.7/site-packages/h5py/_hl/files.py", line 431, in close
File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
File "h5py/h5f.pyx", line 267, in h5py.h5f.get_obj_ids
File "h5py/h5i.pyx", line 43, in h5py.h5i.wrap_identifier
ImportError: sys.meta_path is None, Python is likely shutting down

# Fixed code
def __init__(self, filename, filename_info, filetype_info, engine=None):
    """Init the olci reader base."""
    super(NCOLCIBase, self).__init__(filename, filename_info, filetype_info)
    self.nc = xr.open_dataset(
        self.filename,
        decode_cf=True,
        mask_and_scale=True,
        engine=engine,
        chunks={"columns": CHUNK_SIZE, "rows": CHUNK_SIZE},
    )

    self.nc = self.nc.rename({"columns": "x", "rows": "y"})

    # TODO: get metadata from the manifest file (xfdumanifest.xml)
    self.platform_name = PLATFORM_NAMES[filename_info["mission_id"]]
    self.sensor = "olci"
# Buggy code
def __init__(self, filename, filename_info, filetype_info):
    """Init the file handler."""
    super(NCOLCIChannelBase, self).__init__(filename, filename_info, filetype_info)

    self.channel = filename_info.get("dataset_name")


# Traceback (ImportError)
Traceback (most recent call last):
File "/network/aopp/apres/users/proud/satpyconda/lib/python3.7/site-packages/xarray/backends/file_manager.py", line 243, in __del__
File "/network/aopp/apres/users/proud/satpyconda/lib/python3.7/site-packages/xarray/backends/file_manager.py", line 221, in close
File "/network/aopp/apres/users/proud/satpyconda/lib/python3.7/site-packages/h5netcdf/core.py", line 701, in close
File "/network/aopp/apres/users/proud/satpyconda/lib/python3.7/site-packages/h5py/_hl/files.py", line 431, in close
File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
File "h5py/h5f.pyx", line 267, in h5py.h5f.get_obj_ids
File "h5py/h5i.pyx", line 43, in h5py.h5i.wrap_identifier
ImportError: sys.meta_path is None, Python is likely shutting down

# Fixed code
def __init__(self, filename, filename_info, filetype_info, engine=None):
    """Init the file handler."""
    super(NCOLCIChannelBase, self).__init__(filename, filename_info, filetype_info)

    self.channel = filename_info.get("dataset_name")
# Buggy code
def __init__(self, filename, filename_info, filetype_info, cal):
    """Init the file handler."""
    super(NCOLCI1B, self).__init__(filename, filename_info, filetype_info)
    self.cal = cal.nc


# Traceback (ImportError)
Traceback (most recent call last):
File "/network/aopp/apres/users/proud/satpyconda/lib/python3.7/site-packages/xarray/backends/file_manager.py", line 243, in __del__
File "/network/aopp/apres/users/proud/satpyconda/lib/python3.7/site-packages/xarray/backends/file_manager.py", line 221, in close
File "/network/aopp/apres/users/proud/satpyconda/lib/python3.7/site-packages/h5netcdf/core.py", line 701, in close
File "/network/aopp/apres/users/proud/satpyconda/lib/python3.7/site-packages/h5py/_hl/files.py", line 431, in close
File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
File "h5py/h5f.pyx", line 267, in h5py.h5f.get_obj_ids
File "h5py/h5i.pyx", line 43, in h5py.h5i.wrap_identifier
ImportError: sys.meta_path is None, Python is likely shutting down

# Fixed code
def __init__(self, filename, filename_info, filetype_info, cal, engine=None):
    """Init the file handler."""
    super(NCOLCI1B, self).__init__(filename, filename_info, filetype_info)
    self.cal = cal.nc
# Buggy code
def __init__(self, filename, filename_info, filetype_info):
    """Init the file handler."""
    super(NCOLCIAngles, self).__init__(filename, filename_info, filetype_info)
    self.nc = None
    # TODO: get metadata from the manifest file (xfdumanifest.xml)
    self.platform_name = PLATFORM_NAMES[filename_info["mission_id"]]
    self.sensor = "olci"
    self.cache = {}
    self._start_time = filename_info["start_time"]
    self._end_time = filename_info["end_time"]


# Traceback (ImportError)
Traceback (most recent call last):
File "/network/aopp/apres/users/proud/satpyconda/lib/python3.7/site-packages/xarray/backends/file_manager.py", line 243, in __del__
File "/network/aopp/apres/users/proud/satpyconda/lib/python3.7/site-packages/xarray/backends/file_manager.py", line 221, in close
File "/network/aopp/apres/users/proud/satpyconda/lib/python3.7/site-packages/h5netcdf/core.py", line 701, in close
File "/network/aopp/apres/users/proud/satpyconda/lib/python3.7/site-packages/h5py/_hl/files.py", line 431, in close
File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
File "h5py/h5f.pyx", line 267, in h5py.h5f.get_obj_ids
File "h5py/h5i.pyx", line 43, in h5py.h5i.wrap_identifier
ImportError: sys.meta_path is None, Python is likely shutting down

# Fixed code
def __init__(self, filename, filename_info, filetype_info, engine=None):
    """Init the file handler."""
    super(NCOLCIAngles, self).__init__(filename, filename_info, filetype_info)
    self.nc = None
    # TODO: get metadata from the manifest file (xfdumanifest.xml)
    self.platform_name = PLATFORM_NAMES[filename_info["mission_id"]]
    self.sensor = "olci"
    self.cache = {}
    self._start_time = filename_info["start_time"]
    self._end_time = filename_info["end_time"]
    self.engine = engine
# Buggy code
def precompute(
    self,
    mask=None,
    radius_of_influence=50000,
    epsilon=0,
    reduce_data=True,
    cache_dir=False,
    **kwargs,
):
    """Create bilinear coefficients and store them for later use."""
    del kwargs
    del mask

    if self.resampler is None:
        kwargs = dict(
            source_geo_def=self.source_geo_def,
            target_geo_def=self.target_geo_def,
            radius_of_influence=radius_of_influence,
            neighbours=32,
            epsilon=epsilon,
            reduce_data=reduce_data,
        )

        self.resampler = XArrayResamplerBilinear(**kwargs)
        try:
            self.load_bil_info(cache_dir, **kwargs)
            LOG.debug("Loaded bilinear parameters")
        except IOError:
            LOG.debug("Computing bilinear parameters")
            self.resampler.get_bil_info()
            LOG.debug("Saving bilinear parameters.")
            self.save_bil_info(cache_dir, **kwargs)


# Traceback (ImportError)
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/media/nas/x21324/miniconda3/envs/py37_sandbox/lib/python3.7/site-packages/satpy/__init__.py", line 53, in <module>
from satpy.writers import available_writers  # noqa
File "/media/nas/x21324/miniconda3/envs/py37_sandbox/lib/python3.7/site-packages/satpy/writers/__init__.py", line 41, in <module>
from satpy.resample import get_area_def
File "/media/nas/x21324/miniconda3/envs/py37_sandbox/lib/python3.7/site-packages/satpy/resample.py", line 148, in <module>
from pyresample import bucket
ImportError: cannot import name 'bucket' from 'pyresample' (/media/nas/x21324/miniconda3/envs/py37_sandbox/lib/python3.7/site-packages/pyresample/__init__.py)

# Fixed code
def precompute(
    self,
    mask=None,
    radius_of_influence=50000,
    epsilon=0,
    reduce_data=True,
    cache_dir=False,
    **kwargs,
):
    """Create bilinear coefficients and store them for later use."""
    from pyresample.bilinear.xarr import XArrayResamplerBilinear

    del kwargs
    del mask

    if self.resampler is None:
        kwargs = dict(
            source_geo_def=self.source_geo_def,
            target_geo_def=self.target_geo_def,
            radius_of_influence=radius_of_influence,
            neighbours=32,
            epsilon=epsilon,
            reduce_data=reduce_data,
        )

        self.resampler = XArrayResamplerBilinear(**kwargs)
        try:
            self.load_bil_info(cache_dir, **kwargs)
            LOG.debug("Loaded bilinear parameters")
        except IOError:
            LOG.debug("Computing bilinear parameters")
            self.resampler.get_bil_info()
            LOG.debug("Saving bilinear parameters.")
            self.save_bil_info(cache_dir, **kwargs)
# Buggy code
def __init__(self, source_geo_def, target_geo_def):
    super(BucketResamplerBase, self).__init__(source_geo_def, target_geo_def)
    self.resampler = None


# Traceback (ImportError)
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/media/nas/x21324/miniconda3/envs/py37_sandbox/lib/python3.7/site-packages/satpy/__init__.py", line 53, in <module>
from satpy.writers import available_writers  # noqa
File "/media/nas/x21324/miniconda3/envs/py37_sandbox/lib/python3.7/site-packages/satpy/writers/__init__.py", line 41, in <module>
from satpy.resample import get_area_def
File "/media/nas/x21324/miniconda3/envs/py37_sandbox/lib/python3.7/site-packages/satpy/resample.py", line 148, in <module>
from pyresample import bucket
ImportError: cannot import name 'bucket' from 'pyresample' (/media/nas/x21324/miniconda3/envs/py37_sandbox/lib/python3.7/site-packages/pyresample/__init__.py)

# Fixed code
def __init__(self, source_geo_def, target_geo_def):
    """Initialize bucket resampler."""
    super(BucketResamplerBase, self).__init__(source_geo_def, target_geo_def)
    self.resampler = None
# Buggy code
def precompute(self, **kwargs):
    """Create X and Y indices and store them for later use."""
    LOG.debug("Initializing bucket resampler.")
    source_lons, source_lats = self.source_geo_def.get_lonlats(chunks=CHUNK_SIZE)
    self.resampler = bucket.BucketResampler(
        self.target_geo_def, source_lons, source_lats
    )


# Traceback (ImportError)
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/media/nas/x21324/miniconda3/envs/py37_sandbox/lib/python3.7/site-packages/satpy/__init__.py", line 53, in <module>
from satpy.writers import available_writers  # noqa
File "/media/nas/x21324/miniconda3/envs/py37_sandbox/lib/python3.7/site-packages/satpy/writers/__init__.py", line 41, in <module>
from satpy.resample import get_area_def
File "/media/nas/x21324/miniconda3/envs/py37_sandbox/lib/python3.7/site-packages/satpy/resample.py", line 148, in <module>
from pyresample import bucket
ImportError: cannot import name 'bucket' from 'pyresample' (/media/nas/x21324/miniconda3/envs/py37_sandbox/lib/python3.7/site-packages/pyresample/__init__.py)

# Fixed code
def precompute(self, **kwargs):
    """Create X and Y indices and store them for later use."""
    from pyresample import bucket

    LOG.debug("Initializing bucket resampler.")
    source_lons, source_lats = self.source_geo_def.get_lonlats(chunks=CHUNK_SIZE)
    self.resampler = bucket.BucketResampler(
        self.target_geo_def, source_lons, source_lats
    )
# Buggy code
def compute(self, data, **kwargs):
    """Call the resampling."""
    LOG.debug("Resampling %s", str(data.name))
    results = []
    if data.ndim == 3:
        for i in range(data.shape[0]):
            res = self.resampler.get_count()
            results.append(res)
    else:
        res = self.resampler.get_count()
        results.append(res)

    return da.stack(results)


# Traceback (ImportError)
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/media/nas/x21324/miniconda3/envs/py37_sandbox/lib/python3.7/site-packages/satpy/__init__.py", line 53, in <module>
from satpy.writers import available_writers  # noqa
File "/media/nas/x21324/miniconda3/envs/py37_sandbox/lib/python3.7/site-packages/satpy/writers/__init__.py", line 41, in <module>
from satpy.resample import get_area_def
File "/media/nas/x21324/miniconda3/envs/py37_sandbox/lib/python3.7/site-packages/satpy/resample.py", line 148, in <module>
from pyresample import bucket
ImportError: cannot import name 'bucket' from 'pyresample' (/media/nas/x21324/miniconda3/envs/py37_sandbox/lib/python3.7/site-packages/pyresample/__init__.py)

# Fixed code
def compute(self, data, **kwargs):
    """Call the resampling."""
    LOG.debug("Resampling %s", str(data.name))
    results = []
    if data.ndim == 3:
        for _i in range(data.shape[0]):
            res = self.resampler.get_count()
            results.append(res)
    else:
        res = self.resampler.get_count()
        results.append(res)

    return da.stack(results)
# Buggy code
def omerc2cf(proj_dict):
    """Return the cf grid mapping for the omerc projection."""
    if "no_rot" in proj_dict:
        no_rotation = " "
    else:
        no_rotation = None

    args = dict(
        azimuth_of_central_line=proj_dict.get("alpha"),
        latitude_of_projection_origin=proj_dict.get("lat_0"),
        longitude_of_projection_origin=proj_dict.get("lonc"),
        grid_mapping_name="oblique_mercator",
        # longitude_of_projection_origin=0.,
        no_rotation=no_rotation,
        # reference_ellipsoid_name=proj_dict.get('ellps'),
        semi_major_axis=6378137.0,
        semi_minor_axis=6356752.3142,
        false_easting=0.0,
        false_northing=0.0,
    )
    return args


# 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 omerc2cf(area):
    """Return the cf grid mapping for the omerc projection."""
    proj_dict = area.proj_dict

    args = dict(
        azimuth_of_central_line=proj_dict.get("alpha"),
        latitude_of_projection_origin=proj_dict.get("lat_0"),
        longitude_of_projection_origin=proj_dict.get("lonc"),
        grid_mapping_name="oblique_mercator",
        reference_ellipsoid_name=proj_dict.get("ellps", "WGS84"),
        false_easting=0.0,
        false_northing=0.0,
    )
    if "no_rot" in proj_dict:
        args["no_rotation"] = 1
    if "gamma" in proj_dict:
        args["gamma"] = proj_dict["gamma"]
    return args
# Buggy code
def geos2cf(proj_dict):
    """Return the cf grid mapping for the geos projection."""
    args = dict(
        perspective_point_height=proj_dict.get("h"),
        latitude_of_projection_origin=proj_dict.get("lat_0"),
        longitude_of_projection_origin=proj_dict.get("lon_0"),
        grid_mapping_name="geostationary",
        semi_major_axis=proj_dict.get("a"),
        semi_minor_axis=proj_dict.get("b"),
        sweep_axis=proj_dict.get("sweep"),
    )
    return args


# 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 geos2cf(area):
    """Return the cf grid mapping for the geos projection."""
    proj_dict = area.proj_dict
    args = dict(
        perspective_point_height=proj_dict.get("h"),
        latitude_of_projection_origin=proj_dict.get("lat_0"),
        longitude_of_projection_origin=proj_dict.get("lon_0"),
        grid_mapping_name="geostationary",
        semi_major_axis=proj_dict.get("a"),
        semi_minor_axis=proj_dict.get("b"),
        sweep_axis=proj_dict.get("sweep"),
    )
    return args
# Buggy code
def laea2cf(proj_dict):
    """Return the cf grid mapping for the laea projection."""
    args = dict(
        latitude_of_projection_origin=proj_dict.get("lat_0"),
        longitude_of_projection_origin=proj_dict.get("lon_0"),
        grid_mapping_name="lambert_azimuthal_equal_area",
    )
    return args


# 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 laea2cf(area):
    """Return the cf grid mapping for the laea projection."""
    proj_dict = area.proj_dict
    args = dict(
        latitude_of_projection_origin=proj_dict.get("lat_0"),
        longitude_of_projection_origin=proj_dict.get("lon_0"),
        grid_mapping_name="lambert_azimuthal_equal_area",
    )
    return args
# Buggy code
def create_grid_mapping(area):
    """Create the grid mapping instance for `area`."""
    try:
        grid_mapping = mappings[area.proj_dict["proj"]](area.proj_dict)
        grid_mapping["name"] = area.proj_dict["proj"]
    except KeyError:
        raise NotImplementedError

    return grid_mapping


# 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 create_grid_mapping(area):
    """Create the grid mapping instance for `area`."""
    try:
        grid_mapping = mappings[area.proj_dict["proj"]](area)
        grid_mapping["name"] = area.proj_dict["proj"]
    except KeyError:
        raise NotImplementedError

    return grid_mapping
# Buggy code
def save_datasets(self, datasets, filename, **kwargs):
    """Save all datasets to one or more files."""
    LOG.info("Saving datasets to NetCDF4/CF.")

    ds_collection = {}
    for ds in datasets:
        ds_collection.update(get_extra_ds(ds))

    datas = {}
    for ds in ds_collection.values():
        try:
            new_datasets = area2cf(ds)
        except KeyError:
            new_datasets = [ds]
        for new_ds in new_datasets:
            datas[new_ds.attrs["name"]] = self.da2cf(new_ds, kwargs.get("epoch", EPOCH))

    dataset = xr.Dataset(datas)
    dataset.attrs["history"] = "Created by pytroll/satpy on " + str(datetime.utcnow())
    dataset.attrs["conventions"] = "CF-1.7"
    dataset.to_netcdf(filename, engine="h5netcdf")


# 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 save_datasets(self, datasets, filename, **kwargs):
    """Save all datasets to one or more files."""
    logger.info("Saving datasets to NetCDF4/CF.")

    datas, start_times, end_times = self._collect_datasets(datasets, kwargs)

    dataset = xr.Dataset(datas)
    try:
        dataset["time_bnds"] = make_time_bounds(dataset, start_times, end_times)
        dataset["time"].attrs["bounds"] = "time_bnds"
    except KeyError:
        logger.warning("No time dimension in datasets, skipping time bounds creation.")

    header_attrs = kwargs.pop("header_attrs", None)

    if header_attrs is not None:
        dataset.attrs.update({k: v for k, v in header_attrs.items() if v})

    dataset.attrs["history"] = "Created by pytroll/satpy on " + str(datetime.utcnow())
    dataset.attrs["conventions"] = "CF-1.7"
    engine = kwargs.pop("engine", "h5netcdf")
    kwargs.pop("config_files")
    kwargs.pop("compute")
    kwargs.pop("overlay", None)
    dataset.to_netcdf(filename, engine=engine, **kwargs)
# Buggy code
def __str__(self):
    from pprint import pformat

    return pformat(self.info)


# 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 __str__(self):
    from pprint import pformat

    return pformat(self.attrs)
# Buggy code
def __repr__(self):
    from pprint import pformat

    return pformat(self.info)


# 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 __repr__(self):
    from pprint import pformat

    return pformat(self.attrs)
# Buggy code
def apply_modifier_info(self, origin, destination):
    o = getattr(origin, "info", origin)
    d = getattr(destination, "info", destination)
    for k in DATASET_KEYS:
        if k == "modifiers":
            d[k] = self.info[k]
        elif d.get(k) is None:
            if self.info.get(k) is not None:
                d[k] = self.info[k]
            elif o.get(k) is not None:
                d[k] = o[k]


# 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 apply_modifier_info(self, origin, destination):
    o = getattr(origin, "attrs", origin)
    d = getattr(destination, "attrs", destination)
    for k in DATASET_KEYS:
        if k == "modifiers":
            d[k] = self.attrs[k]
        elif d.get(k) is None:
            if self.attrs.get(k) is not None:
                d[k] = self.attrs[k]
            elif o.get(k) is not None:
                d[k] = o[k]