gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __init__(self, num_seasons: int) -> None:
    super(SeasonalityISSM, self).__init__()
    self.num_seasons = num_seasons


# Traceback (mxnet.base.MXNetError)
Traceback (most recent call last):
File "D:/python/DeepSSM/deep ISSM.py", line 53, in <module>
predictor = estimator.train(dataset.train)
File "D:\python\DeepSSM\gluonts\model\estimator.py", line 254, in train
training_data, validation_data, num_workers, num_prefetch, **kwargs
File "D:\python\DeepSSM\gluonts\model\estimator.py", line 233, in train_model
validation_iter=validation_data_loader,
File "D:\python\DeepSSM\gluonts\trainer\_base.py", line 308, in __call__
epoch_loss = loop(epoch_no, train_iter)
File "D:\python\DeepSSM\gluonts\trainer\_base.py", line 242, in loop
output = net(*inputs)
File "C:\Anaconda\envs\time_series\lib\site-packages\mxnet\gluon\block.py", line 540, in __call__
out = self.forward(*args)
File "C:\Anaconda\envs\time_series\lib\site-packages\mxnet\gluon\block.py", line 917, in forward
return self.hybrid_forward(ndarray, x, *args, **params)
File "D:\python\DeepSSM\gluonts\model\deepstate\_network.py", line 193, in hybrid_forward
length=self.past_length,
File "D:\python\DeepSSM\gluonts\model\deepstate\_network.py", line 151, in compute_lds
) = self.issm.get_issm_coeff(seasonal_indicators)
File "D:\python\DeepSSM\gluonts\model\deepstate\issm.py", line 132, in get_issm_coeff
self.innovation_coeff(seasonal_indicators),
File "D:\python\DeepSSM\gluonts\model\deepstate\issm.py", line 247, in innovation_coeff
axis=2
File "C:\Anaconda\envs\time_series\lib\site-packages\mxnet\ndarray\ndarray.py", line 1695, in squeeze
return op.squeeze(self, *args, **kwargs)
File "<string>", line 45, in squeeze
File "C:\Anaconda\envs\time_series\lib\site-packages\mxnet\_ctypes\ndarray.py", line 92, in _imperative_invoke
ctypes.byref(out_stypes)))
File "C:\Anaconda\envs\time_series\lib\site-packages\mxnet\base.py", line 252, in check_call
raise MXNetError(py_str(_LIB.MXGetLastError()))
mxnet.base.MXNetError: [13:47:56] c:\jenkins\workspace\mxnet-tag\mxnet\src\operator\tensor\./matrix_op-inl.h:2178: Check failed: dshape[axes[i]] == 1 (2 vs. 1) cannot select an axis to squeeze out which has size=2 not equal to one

# Fixed code
def __init__(self, num_seasons: int, time_feature: TimeFeature) -> None:
    super(SeasonalityISSM, self).__init__()
    self.num_seasons = num_seasons
    self.time_feature = time_feature
# Buggy code
def emission_coeff(self, seasonal_indicators: Tensor) -> Tensor:
    F = getF(seasonal_indicators)
    return F.one_hot(seasonal_indicators, depth=self.latent_dim())


# Traceback (mxnet.base.MXNetError)
Traceback (most recent call last):
File "D:/python/DeepSSM/deep ISSM.py", line 53, in <module>
predictor = estimator.train(dataset.train)
File "D:\python\DeepSSM\gluonts\model\estimator.py", line 254, in train
training_data, validation_data, num_workers, num_prefetch, **kwargs
File "D:\python\DeepSSM\gluonts\model\estimator.py", line 233, in train_model
validation_iter=validation_data_loader,
File "D:\python\DeepSSM\gluonts\trainer\_base.py", line 308, in __call__
epoch_loss = loop(epoch_no, train_iter)
File "D:\python\DeepSSM\gluonts\trainer\_base.py", line 242, in loop
output = net(*inputs)
File "C:\Anaconda\envs\time_series\lib\site-packages\mxnet\gluon\block.py", line 540, in __call__
out = self.forward(*args)
File "C:\Anaconda\envs\time_series\lib\site-packages\mxnet\gluon\block.py", line 917, in forward
return self.hybrid_forward(ndarray, x, *args, **params)
File "D:\python\DeepSSM\gluonts\model\deepstate\_network.py", line 193, in hybrid_forward
length=self.past_length,
File "D:\python\DeepSSM\gluonts\model\deepstate\_network.py", line 151, in compute_lds
) = self.issm.get_issm_coeff(seasonal_indicators)
File "D:\python\DeepSSM\gluonts\model\deepstate\issm.py", line 132, in get_issm_coeff
self.innovation_coeff(seasonal_indicators),
File "D:\python\DeepSSM\gluonts\model\deepstate\issm.py", line 247, in innovation_coeff
axis=2
File "C:\Anaconda\envs\time_series\lib\site-packages\mxnet\ndarray\ndarray.py", line 1695, in squeeze
return op.squeeze(self, *args, **kwargs)
File "<string>", line 45, in squeeze
File "C:\Anaconda\envs\time_series\lib\site-packages\mxnet\_ctypes\ndarray.py", line 92, in _imperative_invoke
ctypes.byref(out_stypes)))
File "C:\Anaconda\envs\time_series\lib\site-packages\mxnet\base.py", line 252, in check_call
raise MXNetError(py_str(_LIB.MXGetLastError()))
mxnet.base.MXNetError: [13:47:56] c:\jenkins\workspace\mxnet-tag\mxnet\src\operator\tensor\./matrix_op-inl.h:2178: Check failed: dshape[axes[i]] == 1 (2 vs. 1) cannot select an axis to squeeze out which has size=2 not equal to one

# Fixed code
def emission_coeff(self, feature: Tensor) -> Tensor:
    F = getF(feature)
    return F.one_hot(feature, depth=self.latent_dim())
# Buggy code
def innovation_coeff(self, seasonal_indicators: Tensor) -> Tensor:
    F = getF(seasonal_indicators)
    # seasonal_indicators = F.modulo(seasonal_indicators - 1, self.latent_dim)
    return F.one_hot(seasonal_indicators, depth=self.latent_dim()).squeeze(axis=2)


# Traceback (mxnet.base.MXNetError)
Traceback (most recent call last):
File "D:/python/DeepSSM/deep ISSM.py", line 53, in <module>
predictor = estimator.train(dataset.train)
File "D:\python\DeepSSM\gluonts\model\estimator.py", line 254, in train
training_data, validation_data, num_workers, num_prefetch, **kwargs
File "D:\python\DeepSSM\gluonts\model\estimator.py", line 233, in train_model
validation_iter=validation_data_loader,
File "D:\python\DeepSSM\gluonts\trainer\_base.py", line 308, in __call__
epoch_loss = loop(epoch_no, train_iter)
File "D:\python\DeepSSM\gluonts\trainer\_base.py", line 242, in loop
output = net(*inputs)
File "C:\Anaconda\envs\time_series\lib\site-packages\mxnet\gluon\block.py", line 540, in __call__
out = self.forward(*args)
File "C:\Anaconda\envs\time_series\lib\site-packages\mxnet\gluon\block.py", line 917, in forward
return self.hybrid_forward(ndarray, x, *args, **params)
File "D:\python\DeepSSM\gluonts\model\deepstate\_network.py", line 193, in hybrid_forward
length=self.past_length,
File "D:\python\DeepSSM\gluonts\model\deepstate\_network.py", line 151, in compute_lds
) = self.issm.get_issm_coeff(seasonal_indicators)
File "D:\python\DeepSSM\gluonts\model\deepstate\issm.py", line 132, in get_issm_coeff
self.innovation_coeff(seasonal_indicators),
File "D:\python\DeepSSM\gluonts\model\deepstate\issm.py", line 247, in innovation_coeff
axis=2
File "C:\Anaconda\envs\time_series\lib\site-packages\mxnet\ndarray\ndarray.py", line 1695, in squeeze
return op.squeeze(self, *args, **kwargs)
File "<string>", line 45, in squeeze
File "C:\Anaconda\envs\time_series\lib\site-packages\mxnet\_ctypes\ndarray.py", line 92, in _imperative_invoke
ctypes.byref(out_stypes)))
File "C:\Anaconda\envs\time_series\lib\site-packages\mxnet\base.py", line 252, in check_call
raise MXNetError(py_str(_LIB.MXGetLastError()))
mxnet.base.MXNetError: [13:47:56] c:\jenkins\workspace\mxnet-tag\mxnet\src\operator\tensor\./matrix_op-inl.h:2178: Check failed: dshape[axes[i]] == 1 (2 vs. 1) cannot select an axis to squeeze out which has size=2 not equal to one

# Fixed code
def innovation_coeff(self, feature: Tensor) -> Tensor:
    F = getF(feature)
    return F.one_hot(feature, depth=self.latent_dim()).squeeze(axis=2)
# Buggy code
def sample(self, num_samples: Optional[int] = None, dtype=np.float32) -> Tensor:
    F = self.F
    samples_list = [c.sample(num_samples, dtype) for c in self.components]
    samples = F.stack(*samples_list, axis=-1)

    mixture_probs = _expand_param(self.mixture_probs, num_samples)

    idx = F.random.multinomial(mixture_probs)

    for _ in range(self.event_dim):
        idx = idx.expand_dims(axis=-1)
    idx = idx.broadcast_like(samples_list[0])

    selected_samples = F.pick(data=samples, index=idx, axis=-1)

    return selected_samples


# Traceback (ValueError)
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3417, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-30-52d279ea9fbf>", line 9, in <module>
mixture.sample(num_samples=10) # DOESN"T WORK
File "/Users/eeehrlic/Documents/projects/capstone/gluon-ts/src/gluonts/mx/distribution/mixture.py", line 155, in sample
# idx = idx.broadcast_like(samples_list[0])
File "/usr/local/lib/python3.8/site-packages/mxnet/ndarray/ndarray.py", line 2333, in broadcast_like
return self.broadcast_to(other.shape)
File "/usr/local/lib/python3.8/site-packages/mxnet/ndarray/ndarray.py", line 2290, in broadcast_to
raise ValueError(err_str)
ValueError: operands could not be broadcast together with remapped shapes[original->remapped]: (10,) and requeste

# Fixed code
def sample(self, num_samples: Optional[int] = None, dtype=np.float32) -> Tensor:
    F = self.F
    samples_list = [c.sample(num_samples, dtype) for c in self.components]
    samples = F.stack(*samples_list, axis=-1)

    mixture_probs = _expand_param(self.mixture_probs, num_samples)

    idx = F.random.multinomial(mixture_probs)

    n_axes = len(samples_list[0].shape)
    for _ in range(n_axes - len(idx.shape)):
        idx = idx.expand_dims(axis=-1)
    idx = idx.broadcast_to(samples_list[0].shape)

    selected_samples = F.pick(data=samples, index=idx, axis=-1)

    return selected_samples
# Buggy code
def __init__(self, fields: List[str], axes: Tuple[int, int]) -> None:
    self.fields = fields
    self.axis1, self.axis2 = axes


# Traceback (AssertionError)
C:\path>python
Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
from gluonts.dataset.artificial._base import ComplexSeasonalTimeSeries
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\users\alex\src\gluon-ts\src\gluonts\dataset\artificial\__init__.py", line 2, in <module>
from ._base import (
File "c:\users\alex\src\gluon-ts\src\gluonts\dataset\artificial\_base.py", line 20, in <module>
from gluonts.dataset.artificial.recipe import (
File "c:\users\alex\src\gluon-ts\src\gluonts\dataset\artificial\recipe.py", line 242, in <module>
class LinearTrend(Lifted):
File "c:\users\alex\src\gluon-ts\src\gluonts\dataset\artificial\recipe.py", line 244, in LinearTrend
def __init__(self, slope_fun: Callable = Constant(1.0)) -> None:
File "c:\users\alex\src\gluon-ts\src\gluonts\core\component.py", line 352, in validator
**init_fields,
File "C:\Users\Alex\.conda\envs\gts\lib\site-packages\pydantic\main.py", line 410, in create_model
config=config,
File "C:\Users\Alex\.conda\envs\gts\lib\site-packages\pydantic\fields.py", line 107, in infer
schema=schema,
File "C:\Users\Alex\.conda\envs\gts\lib\site-packages\pydantic\fields.py", line 87, in __init__
self.prepare()
File "C:\Users\Alex\.conda\envs\gts\lib\site-packages\pydantic\fields.py", line 135, in prepare
self._populate_sub_fields()
File "C:\Users\Alex\.conda\envs\gts\lib\site-packages\pydantic\fields.py", line 240, in _populate_sub_fields
assert issubclass(origin, Mapping)
AssertionError


# Fixed code
def __init__(self, input_fields: List[str], axes: Tuple[int, int]) -> None:
    self.input_fields = input_fields
    self.axis1, self.axis2 = axes
# Buggy code
def transform(self, data: DataEntry) -> DataEntry:
    for field in self.fields:
        data[field] = self.swap(data[field])
    return data


# Traceback (AssertionError)
C:\path>python
Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
from gluonts.dataset.artificial._base import ComplexSeasonalTimeSeries
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\users\alex\src\gluon-ts\src\gluonts\dataset\artificial\__init__.py", line 2, in <module>
from ._base import (
File "c:\users\alex\src\gluon-ts\src\gluonts\dataset\artificial\_base.py", line 20, in <module>
from gluonts.dataset.artificial.recipe import (
File "c:\users\alex\src\gluon-ts\src\gluonts\dataset\artificial\recipe.py", line 242, in <module>
class LinearTrend(Lifted):
File "c:\users\alex\src\gluon-ts\src\gluonts\dataset\artificial\recipe.py", line 244, in LinearTrend
def __init__(self, slope_fun: Callable = Constant(1.0)) -> None:
File "c:\users\alex\src\gluon-ts\src\gluonts\core\component.py", line 352, in validator
**init_fields,
File "C:\Users\Alex\.conda\envs\gts\lib\site-packages\pydantic\main.py", line 410, in create_model
config=config,
File "C:\Users\Alex\.conda\envs\gts\lib\site-packages\pydantic\fields.py", line 107, in infer
schema=schema,
File "C:\Users\Alex\.conda\envs\gts\lib\site-packages\pydantic\fields.py", line 87, in __init__
self.prepare()
File "C:\Users\Alex\.conda\envs\gts\lib\site-packages\pydantic\fields.py", line 135, in prepare
self._populate_sub_fields()
File "C:\Users\Alex\.conda\envs\gts\lib\site-packages\pydantic\fields.py", line 240, in _populate_sub_fields
assert issubclass(origin, Mapping)
AssertionError


# Fixed code
def transform(self, data: DataEntry) -> DataEntry:
    for field in self.input_fields:
        data[field] = self.swap(data[field])
    return data
# Buggy code
def __init__(self, fields: List[str]) -> None:
    self.fields = fields


# Traceback (AssertionError)
C:\path>python
Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
from gluonts.dataset.artificial._base import ComplexSeasonalTimeSeries
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\users\alex\src\gluon-ts\src\gluonts\dataset\artificial\__init__.py", line 2, in <module>
from ._base import (
File "c:\users\alex\src\gluon-ts\src\gluonts\dataset\artificial\_base.py", line 20, in <module>
from gluonts.dataset.artificial.recipe import (
File "c:\users\alex\src\gluon-ts\src\gluonts\dataset\artificial\recipe.py", line 242, in <module>
class LinearTrend(Lifted):
File "c:\users\alex\src\gluon-ts\src\gluonts\dataset\artificial\recipe.py", line 244, in LinearTrend
def __init__(self, slope_fun: Callable = Constant(1.0)) -> None:
File "c:\users\alex\src\gluon-ts\src\gluonts\core\component.py", line 352, in validator
**init_fields,
File "C:\Users\Alex\.conda\envs\gts\lib\site-packages\pydantic\main.py", line 410, in create_model
config=config,
File "C:\Users\Alex\.conda\envs\gts\lib\site-packages\pydantic\fields.py", line 107, in infer
schema=schema,
File "C:\Users\Alex\.conda\envs\gts\lib\site-packages\pydantic\fields.py", line 87, in __init__
self.prepare()
File "C:\Users\Alex\.conda\envs\gts\lib\site-packages\pydantic\fields.py", line 135, in prepare
self._populate_sub_fields()
File "C:\Users\Alex\.conda\envs\gts\lib\site-packages\pydantic\fields.py", line 240, in _populate_sub_fields
assert issubclass(origin, Mapping)
AssertionError


# Fixed code
def __init__(self, input_fields: List[str]) -> None:
    self.input_fields = input_fields
# Buggy code
def map_transform(self, data: DataEntry, is_train: bool) -> DataEntry:
    return {f: data[f] for f in self.fields}


# Traceback (AssertionError)
C:\path>python
Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
from gluonts.dataset.artificial._base import ComplexSeasonalTimeSeries
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\users\alex\src\gluon-ts\src\gluonts\dataset\artificial\__init__.py", line 2, in <module>
from ._base import (
File "c:\users\alex\src\gluon-ts\src\gluonts\dataset\artificial\_base.py", line 20, in <module>
from gluonts.dataset.artificial.recipe import (
File "c:\users\alex\src\gluon-ts\src\gluonts\dataset\artificial\recipe.py", line 242, in <module>
class LinearTrend(Lifted):
File "c:\users\alex\src\gluon-ts\src\gluonts\dataset\artificial\recipe.py", line 244, in LinearTrend
def __init__(self, slope_fun: Callable = Constant(1.0)) -> None:
File "c:\users\alex\src\gluon-ts\src\gluonts\core\component.py", line 352, in validator
**init_fields,
File "C:\Users\Alex\.conda\envs\gts\lib\site-packages\pydantic\main.py", line 410, in create_model
config=config,
File "C:\Users\Alex\.conda\envs\gts\lib\site-packages\pydantic\fields.py", line 107, in infer
schema=schema,
File "C:\Users\Alex\.conda\envs\gts\lib\site-packages\pydantic\fields.py", line 87, in __init__
self.prepare()
File "C:\Users\Alex\.conda\envs\gts\lib\site-packages\pydantic\fields.py", line 135, in prepare
self._populate_sub_fields()
File "C:\Users\Alex\.conda\envs\gts\lib\site-packages\pydantic\fields.py", line 240, in _populate_sub_fields
assert issubclass(origin, Mapping)
AssertionError


# Fixed code
def map_transform(self, data: DataEntry, is_train: bool) -> DataEntry:
    return {f: data[f] for f in self.input_fields}
# Buggy code
def delete_map(self, query=None):
    query_map = self.interpolated_map(query=query)
    for alias, drivers in query_map.copy().items():
        for driver, vms in drivers.copy().items():
            for vm_name, vm_details in vms.copy().items():
                if vm_details == "Absent":
                    query_map[alias][driver].pop(vm_name)
            if not query_map[alias][driver]:
                query_map[alias].pop(driver)
        if not query_map[alias]:
            query_map.pop(alias)
    return query_map


# Traceback (AttributeError)
[ERROR   ] An un-handled exception was caught by salt's global exception handler:
AttributeError: 'str' object has no attribute 'copy'
Traceback (most recent call last):
File "/usr/bin/salt-cloud", line 10, in <module>
salt_cloud()
File "/usr/lib/python2.7/site-packages/salt/scripts.py", line 435, in salt_cloud
client.run()
File "/usr/lib/python2.7/site-packages/salt/cloud/cli.py", line 191, in run
matching = mapper.delete_map(query='list_nodes')
File "/usr/lib/python2.7/site-packages/salt/cloud/__init__.py", line 1713, in delete_map
for vm_name, vm_details in six.iteritems(vms.copy()):
AttributeError: 'str' object has no attribute 'copy'
Traceback (most recent call last):
File "/usr/bin/salt-cloud", line 10, in <module>
salt_cloud()
File "/usr/lib/python2.7/site-packages/salt/scripts.py", line 435, in salt_cloud
client.run()
File "/usr/lib/python2.7/site-packages/salt/cloud/cli.py", line 191, in run
matching = mapper.delete_map(query='list_nodes')
File "/usr/lib/python2.7/site-packages/salt/cloud/__init__.py", line 1713, in delete_map
for vm_name, vm_details in six.iteritems(vms.copy()):
AttributeError: 'str' object has no attribute 'copy'

# Fixed code
def delete_map(self, query=None):
    query_map = self.interpolated_map(query=query)
    for alias, drivers in query_map.copy().items():
        if alias == "Errors":
            continue
        for driver, vms in drivers.copy().items():
            for vm_name, vm_details in vms.copy().items():
                if vm_details == "Absent":
                    query_map[alias][driver].pop(vm_name)
            if not query_map[alias][driver]:
                query_map[alias].pop(driver)
        if not query_map[alias]:
            query_map.pop(alias)
    return query_map
# Buggy code
def check_libcloud_version(reqver=LIBCLOUD_MINIMAL_VERSION, why=None):
    """
    Compare different libcloud versions
    """
    if not HAS_LIBCLOUD:
        return False

    if not isinstance(reqver, (list, tuple)):
        raise RuntimeError(
            "'reqver' needs to passed as a tuple or list, i.e., (0, 14, 0)"
        )
    try:
        import libcloud  # pylint: disable=redefined-outer-name
    except ImportError:
        raise ImportError(
            "salt-cloud requires >= libcloud {} which is not installed".format(
                ".".join([str(num) for num in reqver])
            )
        )

    if LIBCLOUD_VERSION_INFO >= reqver:
        return libcloud.__version__

    errormsg = "Your version of libcloud is {}. ".format(libcloud.__version__)
    errormsg += "salt-cloud requires >= libcloud {}".format(
        ".".join([str(num) for num in reqver])
    )
    if why:
        errormsg += " for {}".format(why)
    errormsg += ". Please upgrade."
    raise ImportError(errormsg)


# Traceback (KeyError)
[DEBUG   ] Failed to execute 'gce.list_nodes()' while querying for running nodes: running
Traceback (most recent call last):
File "/home/br/Dev/f0cal/2020-04/_venv/lib/python3.6/site-packages/salt/cloud/__init__.py", line 2366, in run_parallel_map_providers_query
cloud.clouds[data['fun']]()
File "/home/br/Dev/f0cal/2020-04/_venv/lib/python3.6/site-packages/salt/cloud/libcloudfuncs.py", line 467, in list_nodes
'state': node_state(node.state)
File "/home/br/Dev/f0cal/2020-04/_venv/lib/python3.6/site-packages/salt/cloud/libcloudfuncs.py", line 86, in node_state
return states_str[id_] if isinstance(id_, six.string_types) else states_int[id_]
KeyError: running

# Fixed code
def check_libcloud_version(reqver=LIBCLOUD_MINIMAL_VERSION, why=None):
    """
    Compare different libcloud versions
    """
    if not HAS_LIBCLOUD:
        return False

    if not isinstance(reqver, (list, tuple)):
        raise RuntimeError(
            "'reqver' needs to passed as a tuple or list, i.e., (1, 5, 0)"
        )

    if LIBCLOUD_VERSION_INFO >= reqver:
        return libcloud.__version__

    errormsg = (
        "Your version of libcloud is {}. salt-cloud requires >= libcloud {}".format(
            libcloud.__version__, ".".join([str(num) for num in reqver])
        )
    )
    if why:
        errormsg += " for {}".format(why)
    errormsg += ". Please upgrade."
    raise ImportError(errormsg)
# Buggy code
def get_location(conn, vm_):
    """
    Return the location object to use
    """
    locations = conn.list_locations()
    vm_location = config.get_cloud_config_value("location", vm_, __opts__)
    for img in locations:
        img_id = str(img.id)
        img_name = str(img.name)

        if vm_location and vm_location in (img_id, img_name):
            return img

    raise SaltCloudNotFound(
        "The specified location, '{}', could not be found.".format(vm_location)
    )


# Traceback (KeyError)
[DEBUG   ] Failed to execute 'gce.list_nodes()' while querying for running nodes: running
Traceback (most recent call last):
File "/home/br/Dev/f0cal/2020-04/_venv/lib/python3.6/site-packages/salt/cloud/__init__.py", line 2366, in run_parallel_map_providers_query
cloud.clouds[data['fun']]()
File "/home/br/Dev/f0cal/2020-04/_venv/lib/python3.6/site-packages/salt/cloud/libcloudfuncs.py", line 467, in list_nodes
'state': node_state(node.state)
File "/home/br/Dev/f0cal/2020-04/_venv/lib/python3.6/site-packages/salt/cloud/libcloudfuncs.py", line 86, in node_state
return states_str[id_] if isinstance(id_, six.string_types) else states_int[id_]
KeyError: running

# Fixed code
def get_location(conn, vm_):
    """
    Return the location object to use
    """
    locations = conn.list_locations()
    vm_location = salt.config.get_cloud_config_value("location", vm_, __opts__)
    for img in locations:
        img_id = str(img.id)
        img_name = str(img.name)

        if vm_location and vm_location in (img_id, img_name):
            return img

    raise SaltCloudNotFound(
        "The specified location, '{}', could not be found.".format(vm_location)
    )
# Buggy code
def get_image(conn, vm_):
    """
    Return the image object to use
    """
    images = conn.list_images()
    vm_image = config.get_cloud_config_value("image", vm_, __opts__)

    for img in images:
        img_id = str(img.id)
        img_name = str(img.name)

        if vm_image and vm_image in (img_id, img_name):
            return img

    raise SaltCloudNotFound(
        "The specified image, '{}', could not be found.".format(vm_image)
    )


# Traceback (KeyError)
[DEBUG   ] Failed to execute 'gce.list_nodes()' while querying for running nodes: running
Traceback (most recent call last):
File "/home/br/Dev/f0cal/2020-04/_venv/lib/python3.6/site-packages/salt/cloud/__init__.py", line 2366, in run_parallel_map_providers_query
cloud.clouds[data['fun']]()
File "/home/br/Dev/f0cal/2020-04/_venv/lib/python3.6/site-packages/salt/cloud/libcloudfuncs.py", line 467, in list_nodes
'state': node_state(node.state)
File "/home/br/Dev/f0cal/2020-04/_venv/lib/python3.6/site-packages/salt/cloud/libcloudfuncs.py", line 86, in node_state
return states_str[id_] if isinstance(id_, six.string_types) else states_int[id_]
KeyError: running

# Fixed code
def get_image(conn, vm_):
    """
    Return the image object to use
    """
    images = conn.list_images()
    vm_image = salt.config.get_cloud_config_value("image", vm_, __opts__)

    for img in images:
        img_id = str(img.id)
        img_name = str(img.name)

        if vm_image and vm_image in (img_id, img_name):
            return img

    raise SaltCloudNotFound(
        "The specified image, '{}', could not be found.".format(vm_image)
    )
# Buggy code
def get_size(conn, vm_):
    """
    Return the VM's size object
    """
    sizes = conn.list_sizes()
    vm_size = config.get_cloud_config_value("size", vm_, __opts__)
    if not vm_size:
        return sizes[0]

    for size in sizes:
        if vm_size and str(vm_size) in (
            str(size.id),
            str(size.name),
        ):
            return size
    raise SaltCloudNotFound(
        "The specified size, '{}', could not be found.".format(vm_size)
    )


# Traceback (KeyError)
[DEBUG   ] Failed to execute 'gce.list_nodes()' while querying for running nodes: running
Traceback (most recent call last):
File "/home/br/Dev/f0cal/2020-04/_venv/lib/python3.6/site-packages/salt/cloud/__init__.py", line 2366, in run_parallel_map_providers_query
cloud.clouds[data['fun']]()
File "/home/br/Dev/f0cal/2020-04/_venv/lib/python3.6/site-packages/salt/cloud/libcloudfuncs.py", line 467, in list_nodes
'state': node_state(node.state)
File "/home/br/Dev/f0cal/2020-04/_venv/lib/python3.6/site-packages/salt/cloud/libcloudfuncs.py", line 86, in node_state
return states_str[id_] if isinstance(id_, six.string_types) else states_int[id_]
KeyError: running

# Fixed code
def get_size(conn, vm_):
    """
    Return the VM's size object
    """
    sizes = conn.list_sizes()
    vm_size = salt.config.get_cloud_config_value("size", vm_, __opts__)
    if not vm_size:
        return sizes[0]

    for size in sizes:
        if vm_size and str(vm_size) in (
            str(size.id),
            str(size.name),
        ):
            return size
    raise SaltCloudNotFound(
        "The specified size, '{}', could not be found.".format(vm_size)
    )
# Buggy code
def script(vm_):
    """
    Return the script deployment object
    """
    return ScriptDeployment(
        salt.utils.cloud.os_script(
            config.get_cloud_config_value("os", vm_, __opts__),
            vm_,
            __opts__,
            salt.utils.cloud.salt_config_to_yaml(
                salt.utils.cloud.minion_config(__opts__, vm_)
            ),
        )
    )


# Traceback (KeyError)
[DEBUG   ] Failed to execute 'gce.list_nodes()' while querying for running nodes: running
Traceback (most recent call last):
File "/home/br/Dev/f0cal/2020-04/_venv/lib/python3.6/site-packages/salt/cloud/__init__.py", line 2366, in run_parallel_map_providers_query
cloud.clouds[data['fun']]()
File "/home/br/Dev/f0cal/2020-04/_venv/lib/python3.6/site-packages/salt/cloud/libcloudfuncs.py", line 467, in list_nodes
'state': node_state(node.state)
File "/home/br/Dev/f0cal/2020-04/_venv/lib/python3.6/site-packages/salt/cloud/libcloudfuncs.py", line 86, in node_state
return states_str[id_] if isinstance(id_, six.string_types) else states_int[id_]
KeyError: running

# Fixed code
def script(vm_):
    """
    Return the script deployment object
    """
    return ScriptDeployment(
        salt.utils.cloud.os_script(
            salt.config.get_cloud_config_value("os", vm_, __opts__),
            vm_,
            __opts__,
            salt.utils.cloud.salt_config_to_yaml(
                salt.utils.cloud.minion_config(__opts__, vm_)
            ),
        )
    )
# Buggy code
def list_nodes(conn=None, call=None):
    """
    Return a list of the VMs that are on the provider
    """
    if call == "action":
        raise SaltCloudSystemExit(
            "The list_nodes function must be called with -f or --function."
        )

    if not conn:
        conn = get_conn()  # pylint: disable=E0602

    nodes = conn.list_nodes()
    ret = {}
    for node in nodes:
        ret[node.name] = {
            "id": node.id,
            "image": node.image,
            "name": node.name,
            "private_ips": node.private_ips,
            "public_ips": node.public_ips,
            "size": node.size,
            "state": node_state(node.state),
        }
    return ret


# Traceback (KeyError)
[DEBUG   ] Failed to execute 'gce.list_nodes()' while querying for running nodes: running
Traceback (most recent call last):
File "/home/br/Dev/f0cal/2020-04/_venv/lib/python3.6/site-packages/salt/cloud/__init__.py", line 2366, in run_parallel_map_providers_query
cloud.clouds[data['fun']]()
File "/home/br/Dev/f0cal/2020-04/_venv/lib/python3.6/site-packages/salt/cloud/libcloudfuncs.py", line 467, in list_nodes
'state': node_state(node.state)
File "/home/br/Dev/f0cal/2020-04/_venv/lib/python3.6/site-packages/salt/cloud/libcloudfuncs.py", line 86, in node_state
return states_str[id_] if isinstance(id_, six.string_types) else states_int[id_]
KeyError: running

# Fixed code
def list_nodes(conn=None, call=None):
    """
    Return a list of the VMs that are on the provider
    """
    if call == "action":
        raise SaltCloudSystemExit(
            "The list_nodes function must be called with -f or --function."
        )

    if not conn:
        conn = get_conn()  # pylint: disable=E0602

    nodes = conn.list_nodes()
    ret = {}
    for node in nodes:
        ret[node.name] = {
            "id": node.id,
            "image": node.image,
            "name": node.name,
            "private_ips": node.private_ips,
            "public_ips": node.public_ips,
            "size": node.size,
            "state": str(node.state).upper(),
        }
    return ret
# Buggy code
def __virtual__():
    if "elasticsearch.index_exists" not in __salt__:
        return (
            False,
            "Elasticsearch module not availble.  Check that the elasticsearch library is installed.",
        )
    return __virtualname__


# Traceback (KeyError)
2020-07-23 16:19:52,469 [salt.minion      :2022][ERROR   ][29262] The return failed for job 20200723141934627314: 'elasticsearch.index_exists'
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/salt/minion.py", line 2011, in _thread_return
minion_instance.returners[returner_str](ret)
File "/usr/lib/python3/dist-packages/salt/returners/elasticsearch_return.py", line 301, in returner
_ensure_index(index)
File "/usr/lib/python3/dist-packages/salt/returners/elasticsearch_return.py", line 177, in _ensure_index
index_exists = __salt__["elasticsearch.index_exists"](index)
File "/usr/lib/python3/dist-packages/salt/loader.py", line 1278, in __getitem__
func = super(LazyLoader, self).__getitem__(item)
File "/usr/lib/python3/dist-packages/salt/utils/lazy.py", line 108, in __getitem__
raise KeyError(key)
KeyError: 'elasticsearch.index_exists'

# Fixed code
def __virtual__():
    if "elasticsearch.index_exists" not in __salt__:
        return (
            False,
            "Elasticsearch module not availble.  Check that the elasticsearch library is installed.",
        )
    return __virtualname__
# Buggy code
def _read_buckets_cache_file(cache_file):
    """
    Return the contents of the buckets cache file
    """

    log.debug("Reading buckets cache file")

    with salt.utils.files.fopen(cache_file, "rb") as fp_:
        try:
            data = pickle.load(fp_)
        except (
            pickle.UnpicklingError,
            AttributeError,
            EOFError,
            ImportError,
            IndexError,
            KeyError,
            ValueError,
        ) as exc:
            log.debug("Exception reading buckets cache file: '{0}'".format(exc))
            data = None

    return data


# Traceback (ValueError)
Exception occurred in runner state.orchestrate: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/salt/client/mixins.py", line 382, in _low
data['return'] = self.functions[fun](*args, **kwargs)
File "/usr/lib/python2.7/site-packages/salt/runners/state.py", line 88, in orchestrate
orchestration_jid=orchestration_jid)
File "/usr/lib/python2.7/site-packages/salt/modules/state.py", line 1098, in sls
initial_pillar=_get_initial_pillar(opts))
File "/usr/lib/python2.7/site-packages/salt/state.py", line 3846, in __init__
BaseHighState.__init__(self, opts)
File "/usr/lib/python2.7/site-packages/salt/state.py", line 2721, in __init__
self.avail = self.__gather_avail()
File "/usr/lib/python2.7/site-packages/salt/state.py", line 2730, in __gather_avail
for saltenv in self._get_envs():
File "/usr/lib/python2.7/site-packages/salt/state.py", line 2791, in _get_envs
client_envs = self.client.envs()
File "/usr/lib/python2.7/site-packages/salt/fileclient.py", line 1331, in envs
return self.channel.send(load)
File "/usr/lib/python2.7/site-packages/salt/fileserver/__init__.py", line 892, in send
return self.fs.envs()
File "/usr/lib/python2.7/site-packages/salt/fileserver/__init__.py", line 488, in envs
ret.update(self.servers[fstr](**kwargs))
File "/usr/lib/python2.7/site-packages/salt/fileserver/s3fs.py", line 93, in envs
metadata = _init()
File "/usr/lib/python2.7/site-packages/salt/fileserver/s3fs.py", line 354, in _init
metadata = _read_buckets_cache_file(cache_file)
File "/usr/lib/python2.7/site-packages/salt/fileserver/s3fs.py", line 553, in _read_buckets_cache_file
data = pickle.load(fp_)
File "/usr/lib64/python2.7/pickle.py", line 1378, in load
return Unpickler(file).load()
File "/usr/lib64/python2.7/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/lib64/python2.7/pickle.py", line 966, in load_string
raise ValueError, "insecure string pickle"
ValueError: insecure string pickle

# Fixed code
def _read_buckets_cache_file(cache_file):
    """
    Return the contents of the buckets cache file
    """

    log.debug("Reading buckets cache file")

    with salt.utils.files.fopen(cache_file, "rb") as fp_:
        try:
            data = pickle.load(fp_)
        except (
            pickle.UnpicklingError,
            AttributeError,
            EOFError,
            ImportError,
            IndexError,
            KeyError,
            ValueError,
        ) as exc:
            log.debug("Exception reading buckets cache file: '{}'".format(exc))
            data = None

    return data
# Buggy code
def __init__(self, futures):
    super(Any, self).__init__()
    for future in futures:
        future.add_done_callback(self.done_callback)


# Traceback (TypeError)
2018-09-07 19:06:22,631 [tornado.application:1495][ERROR   ][998] Uncaught exception POST /run (127.0.0.1)
HTTPServerRequest(protocol='http', host='localhost:8000', method='POST', uri='/run', version='HTTP/1.1', remote_ip='127.0.0.1', headers={'Host': 'localhost:8000', 'Content-Type': 'application/json', 'Content-Length': '125', 'Accept': 'application/x-yaml', 'User-Agent': 'curl/7.29.0'})
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/tornado/web.py", line 1368, in _stack_context_handle_exception
raise_exc_info((type, value, traceback))
File "/usr/lib64/python2.7/site-packages/tornado/stack_context.py", line 313, in wrapped
ret = fn(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/tornado/gen.py", line 770, in <lambda>
IOLoop.current().call_later(duration, lambda: f.set_result(None))
File "/usr/lib64/python2.7/site-packages/tornado/concurrent.py", line 253, in set_result
self._set_done()
File "/usr/lib64/python2.7/site-packages/tornado/concurrent.py", line 297, in _set_done
for cb in self._callbacks:
TypeError: 'NoneType' object is not iterable

# Fixed code
def __init__(self, futures):
    super().__init__()
    for future in futures:
        future.add_done_callback(self.done_callback)
# Buggy code
def _handle_event_socket_recv(self, raw):
    """
    Callback for events on the event sub socket
    """
    mtag, data = self.event.unpack(raw, self.event.serial)

    # see if we have any futures that need this info:
    for (tag, matcher), futures in six.iteritems(self.tag_map):
        try:
            is_matched = matcher(mtag, tag)
        except Exception:  # pylint: disable=broad-except
            log.error("Failed to run a matcher.", exc_info=True)
            is_matched = False

        if not is_matched:
            continue

        for future in futures:
            if future.done():
                continue
            future.set_result({"data": data, "tag": mtag})
            self.tag_map[(tag, matcher)].remove(future)
            if future in self.timeout_map:
                salt.ext.tornado.ioloop.IOLoop.current().remove_timeout(
                    self.timeout_map[future]
                )
                del self.timeout_map[future]


# Traceback (TypeError)
2018-09-07 19:06:22,631 [tornado.application:1495][ERROR   ][998] Uncaught exception POST /run (127.0.0.1)
HTTPServerRequest(protocol='http', host='localhost:8000', method='POST', uri='/run', version='HTTP/1.1', remote_ip='127.0.0.1', headers={'Host': 'localhost:8000', 'Content-Type': 'application/json', 'Content-Length': '125', 'Accept': 'application/x-yaml', 'User-Agent': 'curl/7.29.0'})
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/tornado/web.py", line 1368, in _stack_context_handle_exception
raise_exc_info((type, value, traceback))
File "/usr/lib64/python2.7/site-packages/tornado/stack_context.py", line 313, in wrapped
ret = fn(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/tornado/gen.py", line 770, in <lambda>
IOLoop.current().call_later(duration, lambda: f.set_result(None))
File "/usr/lib64/python2.7/site-packages/tornado/concurrent.py", line 253, in set_result
self._set_done()
File "/usr/lib64/python2.7/site-packages/tornado/concurrent.py", line 297, in _set_done
for cb in self._callbacks:
TypeError: 'NoneType' object is not iterable

# Fixed code
def _handle_event_socket_recv(self, raw):
    """
    Callback for events on the event sub socket
    """
    mtag, data = self.event.unpack(raw, self.event.serial)

    # see if we have any futures that need this info:
    for (tag, matcher), futures in self.tag_map.items():
        try:
            is_matched = matcher(mtag, tag)
        except Exception:  # pylint: disable=broad-except
            log.error("Failed to run a matcher.", exc_info=True)
            is_matched = False

        if not is_matched:
            continue

        for future in futures:
            if future.done():
                continue
            future.set_result({"data": data, "tag": mtag})
            self.tag_map[(tag, matcher)].remove(future)
            if future in self.timeout_map:
                salt.ext.tornado.ioloop.IOLoop.current().remove_timeout(
                    self.timeout_map[future]
                )
                del self.timeout_map[future]
# Buggy code
def more_todo():
    """
    Check if there are any more minions we are waiting on returns from
    """
    return any(x is False for x in six.itervalues(minions))


# Traceback (TypeError)
2018-09-07 19:06:22,631 [tornado.application:1495][ERROR   ][998] Uncaught exception POST /run (127.0.0.1)
HTTPServerRequest(protocol='http', host='localhost:8000', method='POST', uri='/run', version='HTTP/1.1', remote_ip='127.0.0.1', headers={'Host': 'localhost:8000', 'Content-Type': 'application/json', 'Content-Length': '125', 'Accept': 'application/x-yaml', 'User-Agent': 'curl/7.29.0'})
Traceback (most recent call last):
File "/usr/lib64/python2.7/site-packages/tornado/web.py", line 1368, in _stack_context_handle_exception
raise_exc_info((type, value, traceback))
File "/usr/lib64/python2.7/site-packages/tornado/stack_context.py", line 313, in wrapped
ret = fn(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/tornado/gen.py", line 770, in <lambda>
IOLoop.current().call_later(duration, lambda: f.set_result(None))
File "/usr/lib64/python2.7/site-packages/tornado/concurrent.py", line 253, in set_result
self._set_done()
File "/usr/lib64/python2.7/site-packages/tornado/concurrent.py", line 297, in _set_done
for cb in self._callbacks:
TypeError: 'NoneType' object is not iterable

# Fixed code
def more_todo():
    """
    Check if there are any more minions we are waiting on returns from
    """
    return any(x is False for x in minions.values())
# Buggy code
def cluster_exists(version, name="main"):
    """
    Checks if a given version and name of a cluster exists.

    CLI Example:

    .. code-block:: bash

        salt '*' postgres.cluster_exists '9.3'

        salt '*' postgres.cluster_exists '9.3' 'main'
    """
    return "{0}/{1}".format(version, name) in cluster_list()


# Traceback (TypeError)
... skip useless debug lines
[DEBUG   ] LazyLoaded postgres.cluster_create
Passed invalid arguments: 'float' object is not iterable.
Usage:
Adds a cluster to the Postgres server.
.. warning:
Only works for debian family distros so far.
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_create '9.3'
salt '*' postgres.cluster_create '9.3' 'main'
salt '*' postgres.cluster_create '9.3' locale='fr_FR'

Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/cli/caller.py", line 212, in call
ret['return'] = func(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/modules/deb_postgres.py", line 66, in cluster_create
cmdstr = ' '.join([pipes.quote(c) for c in cmd])
File "/usr/lib/python2.7/pipes.py", line 269, in quote
for c in file:
TypeError: 'float' object is not iterable

# Fixed code
def cluster_exists(version, name="main"):
    """
    Checks if a given version and name of a cluster exists.

    CLI Example:

    .. code-block:: bash

        salt '*' postgres.cluster_exists '9.3'

        salt '*' postgres.cluster_exists '9.3' 'main'
    """
    return "{}/{}".format(version, name) in cluster_list()
# Buggy code
def cluster_remove(version, name="main", stop=False):
    """
    Remove a cluster on a Postgres server. By default it doesn't try
    to stop the cluster.

    CLI Example:

    .. code-block:: bash

        salt '*' postgres.cluster_remove '9.3'

        salt '*' postgres.cluster_remove '9.3' 'main'

        salt '*' postgres.cluster_remove '9.3' 'main' stop=True

    """
    cmd = [salt.utils.path.which("pg_dropcluster")]
    if stop:
        cmd += ["--stop"]
    cmd += [version, name]
    cmdstr = " ".join([pipes.quote(c) for c in cmd])
    ret = __salt__["cmd.run_all"](cmdstr, python_shell=False)
    # FIXME - return Boolean ?
    if ret.get("retcode", 0) != 0:
        log.error("Error removing a Postgresql cluster %s/%s", version, name)
    else:
        ret["changes"] = ("Successfully removed cluster {0}/{1}").format(version, name)
    return ret


# Traceback (TypeError)
... skip useless debug lines
[DEBUG   ] LazyLoaded postgres.cluster_create
Passed invalid arguments: 'float' object is not iterable.
Usage:
Adds a cluster to the Postgres server.
.. warning:
Only works for debian family distros so far.
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_create '9.3'
salt '*' postgres.cluster_create '9.3' 'main'
salt '*' postgres.cluster_create '9.3' locale='fr_FR'

Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/cli/caller.py", line 212, in call
ret['return'] = func(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/modules/deb_postgres.py", line 66, in cluster_create
cmdstr = ' '.join([pipes.quote(c) for c in cmd])
File "/usr/lib/python2.7/pipes.py", line 269, in quote
for c in file:
TypeError: 'float' object is not iterable

# Fixed code
def cluster_remove(version, name="main", stop=False):
    """
    Remove a cluster on a Postgres server. By default it doesn't try
    to stop the cluster.

    CLI Example:

    .. code-block:: bash

        salt '*' postgres.cluster_remove '9.3'

        salt '*' postgres.cluster_remove '9.3' 'main'

        salt '*' postgres.cluster_remove '9.3' 'main' stop=True

    """
    cmd = [salt.utils.path.which("pg_dropcluster")]
    if stop:
        cmd += ["--stop"]
    cmd += [str(version), name]
    cmdstr = " ".join([pipes.quote(c) for c in cmd])
    ret = __salt__["cmd.run_all"](cmdstr, python_shell=False)
    # FIXME - return Boolean ?
    if ret.get("retcode", 0) != 0:
        log.error("Error removing a Postgresql cluster %s/%s", version, name)
    else:
        ret["changes"] = ("Successfully removed cluster {}/{}").format(version, name)
    return ret
# Buggy code
def _parse_pg_lscluster(output):
    """
    Helper function to parse the output of pg_lscluster
    """
    cluster_dict = {}
    for line in output.splitlines():
        version, name, port, status, user, datadir, log = line.split()
        cluster_dict["{0}/{1}".format(version, name)] = {
            "port": int(port),
            "status": status,
            "user": user,
            "datadir": datadir,
            "log": log,
        }
    return cluster_dict


# Traceback (TypeError)
... skip useless debug lines
[DEBUG   ] LazyLoaded postgres.cluster_create
Passed invalid arguments: 'float' object is not iterable.
Usage:
Adds a cluster to the Postgres server.
.. warning:
Only works for debian family distros so far.
CLI Example:
.. code-block:: bash
salt '*' postgres.cluster_create '9.3'
salt '*' postgres.cluster_create '9.3' 'main'
salt '*' postgres.cluster_create '9.3' locale='fr_FR'

Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/salt/cli/caller.py", line 212, in call
ret['return'] = func(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/salt/modules/deb_postgres.py", line 66, in cluster_create
cmdstr = ' '.join([pipes.quote(c) for c in cmd])
File "/usr/lib/python2.7/pipes.py", line 269, in quote
for c in file:
TypeError: 'float' object is not iterable

# Fixed code
def _parse_pg_lscluster(output):
    """
    Helper function to parse the output of pg_lscluster
    """
    cluster_dict = {}
    for line in output.splitlines():
        version, name, port, status, user, datadir, log = line.split()
        cluster_dict["{}/{}".format(version, name)] = {
            "port": int(port),
            "status": status,
            "user": user,
            "datadir": datadir,
            "log": log,
        }
    return cluster_dict