gurudesh/pytracebugs huggingface dataset:
# Buggy code
def getValues(self, fx, address, count=1):
    """Get `count` values from datastore

    :param fx: The function we are working with
    :param address: The starting address
    :param count: The number of values to retrieve
    :returns: The requested values from a:a+c
    """
    if not self.zero_mode:
        address = address + 1
    _logger.debug("getValues[%d] %d:%d" % (fx, address, count))
    return self.store[self.decode(fx)].getValues(address, count)


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def getValues(self, fx, address, count=1):
    """Get `count` values from datastore

    :param fx: The function we are working with
    :param address: The starting address
    :param count: The number of values to retrieve
    :returns: The requested values from a:a+c
    """
    if not self.zero_mode:
        address = address + 1
    _logger.debug("getValues fc-[%d] address-%d: count-%d" % (fx, address, count))
    return self.store[self.decode(fx)].getValues(address, count)
# Buggy code
def __init__(self, *args, **kwargs):
    """Initializes the datastores

    :param kwargs: Each element is a ModbusDataBlock
    """
    self.table = kwargs.get("table", "pymodbus")
    self.database = kwargs.get("database", "sqlite:///pymodbus.db")
    self._db_create(self.table, self.database)


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def __init__(self, *args, **kwargs):
    """Initializes the datastores

    :param kwargs: Each element is a ModbusDataBlock
    """
    self.table = kwargs.get("table", "pymodbus")
    self.database = kwargs.get("database", "sqlite:///pymodbus.db")
    self._db_create(self.table, self.database)
# Buggy code
def __str__(self):
    """Returns a string representation of the context

    :returns: A string representation of the context
    """
    return "Modbus Slave Context"


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def __str__(self):
    """Returns a string representation of the context

    :returns: A string representation of the context
    """
    return "Modbus Slave Context"
# Buggy code
def reset(self):
    """Resets all the datastores to their default values"""
    self._metadata.drop_all()
    self._db_create(self.table, self.database)


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def reset(self):
    """Resets all the datastores to their default values"""
    self._metadata.drop_all()
    self._db_create(self.table, self.database)
# Buggy code
def validate(self, fx, address, count=1):
    """Validates the request to make sure it is in range

    :param fx: The function we are working with
    :param address: The starting address
    :param count: The number of values to test
    :returns: True if the request in within range, False otherwise
    """
    address = address + 1  # section 4.4 of specification
    _logger.debug("validate[%d] %d:%d" % (fx, address, count))
    return self._validate(self.decode(fx), address, count)


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def validate(self, fx, address, count=1):
    """Validates the request to make sure it is in range

    :param fx: The function we are working with
    :param address: The starting address
    :param count: The number of values to test
    :returns: True if the request in within range, False otherwise
    """
    address = address + 1  # section 4.4 of specification
    _logger.debug("validate[%d] %d:%d" % (fx, address, count))
    return self._validate(self.decode(fx), address, count)
# Buggy code
def getValues(self, fx, address, count=1):
    """Get `count` values from datastore

    :param fx: The function we are working with
    :param address: The starting address
    :param count: The number of values to retrieve
    :returns: The requested values from a:a+c
    """
    address = address + 1  # section 4.4 of specification
    _logger.debug("get-values[%d] %d:%d" % (fx, address, count))
    return self._get(self.decode(fx), address, count)


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def getValues(self, fx, address, count=1):
    """Get `count` values from datastore

    :param fx: The function we are working with
    :param address: The starting address
    :param count: The number of values to retrieve
    :returns: The requested values from a:a+c
    """
    address = address + 1  # section 4.4 of specification
    _logger.debug("get-values[%d] %d:%d" % (fx, address, count))
    return self._get(self.decode(fx), address, count)
# Buggy code
def setValues(self, fx, address, values):
    """Sets the datastore with the supplied values

    :param fx: The function we are working with
    :param address: The starting address
    :param values: The new values to be set
    """
    address = address + 1  # section 4.4 of specification
    _logger.debug("set-values[%d] %d:%d" % (fx, address, len(values)))
    self._set(self.decode(fx), address, values)


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def setValues(self, fx, address, values, update=True):
    """Sets the datastore with the supplied values

    :param fx: The function we are working with
    :param address: The starting address
    :param values: The new values to be set
    :param update: Update existing register in the db
    """
    address = address + 1  # section 4.4 of specification
    _logger.debug("set-values[%d] %d:%d" % (fx, address, len(values)))
    if update:
        self._update(self.decode(fx), address, values)
    else:
        self._set(self.decode(fx), address, values)
# Buggy code
def _db_create(self, table, database):
    """A helper method to initialize the database and handles

    :param table: The table name to create
    :param database: The database uri to use
    """
    self._engine = sqlalchemy.create_engine(database, echo=False)
    self._metadata = sqlalchemy.MetaData(self._engine)
    self._table = sqlalchemy.Table(
        table,
        self._metadata,
        sqlalchemy.Column("type", sqltypes.String(1)),
        sqlalchemy.Column("index", sqltypes.Integer),
        sqlalchemy.Column("value", sqltypes.Integer),
        UniqueConstraint("type", "index", name="key"),
    )
    self._table.create(checkfirst=True)
    self._connection = self._engine.connect()


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def _db_create(self, table, database):
    """A helper method to initialize the database and handles

    :param table: The table name to create
    :param database: The database uri to use
    """
    self._engine = sqlalchemy.create_engine(database, echo=False)
    self._metadata = sqlalchemy.MetaData(self._engine)
    self._table = sqlalchemy.Table(
        table,
        self._metadata,
        sqlalchemy.Column("type", sqltypes.String(1)),
        sqlalchemy.Column("index", sqltypes.Integer),
        sqlalchemy.Column("value", sqltypes.Integer),
        UniqueConstraint("type", "index", name="key"),
    )
    self._table.create(checkfirst=True)
    self._connection = self._engine.connect()
# Buggy code
def _get(self, type, offset, count):
    """
    :param type: The key prefix to use
    :param offset: The address offset to start at
    :param count: The number of bits to read
    :returns: The resulting values
    """
    query = self._table.select(
        and_(
            self._table.c.type == type,
            self._table.c.index >= offset,
            self._table.c.index <= offset + count - 1,
        )
    )
    query = query.order_by(self._table.c.index.asc())
    result = self._connection.execute(query).fetchall()
    return [row.value for row in result]


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def _get(self, type, offset, count):
    """
    :param type: The key prefix to use
    :param offset: The address offset to start at
    :param count: The number of bits to read
    :returns: The resulting values
    """
    query = self._table.select(
        and_(
            self._table.c.type == type,
            self._table.c.index >= offset,
            self._table.c.index <= offset + count - 1,
        )
    )
    query = query.order_by(self._table.c.index.asc())
    result = self._connection.execute(query).fetchall()
    return [row.value for row in result]
# Buggy code
def _build_set(self, type, offset, values, prefix=""):
    """A helper method to generate the sql update context

    :param type: The key prefix to use
    :param offset: The address offset to start at
    :param values: The values to set
    :param prefix: Prefix fields index and type, defaults to empty string
    """
    result = []
    for index, value in enumerate(values):
        result.append(
            {prefix + "type": type, prefix + "index": offset + index, "value": value}
        )
    return result


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def _build_set(self, type, offset, values, prefix=""):
    """A helper method to generate the sql update context

    :param type: The key prefix to use
    :param offset: The address offset to start at
    :param values: The values to set
    :param prefix: Prefix fields index and type, defaults to empty string
    """
    result = []
    for index, value in enumerate(values):
        result.append(
            {prefix + "type": type, prefix + "index": offset + index, "value": value}
        )
    return result
# Buggy code
def _set(self, type, offset, values):
    """

    :param key: The type prefix to use
    :param offset: The address offset to start at
    :param values: The values to set
    """
    if self._check(type, offset, values):
        context = self._build_set(type, offset, values)
        query = self._table.insert()
        result = self._connection.execute(query, context)
        return result.rowcount == len(values)
    else:
        return False


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def _set(self, type, offset, values):
    """

    :param key: The type prefix to use
    :param offset: The address offset to start at
    :param values: The values to set
    """
    if self._check(type, offset, values):
        context = self._build_set(type, offset, values)
        query = self._table.insert()
        result = self._connection.execute(query, context)
        return result.rowcount == len(values)
    else:
        return False
# Buggy code
def _update(self, type, offset, values):
    """

    :param type: The type prefix to use
    :param offset: The address offset to start at
    :param values: The values to set
    """
    context = self._build_set(type, offset, values, prefix="x_")
    query = self._table.update().values(name="value")
    query = query.where(
        and_(
            self._table.c.type == bindparam("x_type"),
            self._table.c.index == bindparam("x_index"),
        )
    )
    result = self._connection.execute(query, context)
    return result.rowcount == len(values)


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def _update(self, type, offset, values):
    """

    :param type: The type prefix to use
    :param offset: The address offset to start at
    :param values: The values to set
    """
    context = self._build_set(type, offset, values, prefix="x_")
    query = self._table.update().values(value="value")
    query = query.where(
        and_(
            self._table.c.type == bindparam("x_type"),
            self._table.c.index == bindparam("x_index"),
        )
    )
    result = self._connection.execute(query, context)
    return result.rowcount == len(values)
# Buggy code
def _validate(self, type, offset, count):
    """
    :param key: The key prefix to use
    :param offset: The address offset to start at
    :param count: The number of bits to read
    :returns: The result of the validation
    """
    query = self._table.select(
        and_(
            self._table.c.type == type,
            self._table.c.index >= offset,
            self._table.c.index <= offset + count - 1,
        )
    )
    result = self._connection.execute(query).fetchall()
    return len(result) == count


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def _validate(self, type, offset, count):
    """
    :param key: The key prefix to use
    :param offset: The address offset to start at
    :param count: The number of bits to read
    :returns: The result of the validation
    """
    query = self._table.select(
        and_(
            self._table.c.type == type,
            self._table.c.index >= offset,
            self._table.c.index <= offset + count - 1,
        )
    )
    result = self._connection.execute(query).fetchall()
    return len(result) == count
# Buggy code
def __init__(self, string):
    """Initialize the exception
    :param string: The message to append to the error
    """
    self.string = string


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def __init__(self, string):
    """Initialize the exception
    :param string: The message to append to the error
    """
    self.string = string
# Buggy code
def __init__(self, string="", function_code=None):
    """Initialize the exception
    :param string: The message to append to the error
    """
    self.fcode = function_code
    self.message = "[Input/Output] %s" % string
    ModbusException.__init__(self, self.message)


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def __init__(self, string="", function_code=None):
    """Initialize the exception
    :param string: The message to append to the error
    """
    self.fcode = function_code
    self.message = "[Input/Output] %s" % string
    ModbusException.__init__(self, self.message)
# Buggy code
def __init__(self, string=""):
    """Initialize the exception

    :param string: The message to append to the error
    """
    message = "[Invalid Parameter] %s" % string
    ModbusException.__init__(self, message)


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def __init__(self, string=""):
    """Initialize the exception

    :param string: The message to append to the error
    """
    message = "[Invalid Parameter] %s" % string
    ModbusException.__init__(self, message)
# Buggy code
def __init__(self, string=""):
    """Initialize the exception

    :param string: The message to append to the error
    """
    message = "[No Such Slave] %s" % string
    ModbusException.__init__(self, message)


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def __init__(self, string=""):
    """Initialize the exception

    :param string: The message to append to the error
    """
    message = "[No Such Slave] %s" % string
    ModbusException.__init__(self, message)
# Buggy code
def __init__(self, string=""):
    """Initialize the exception
    :param string: The message to append to the error
    """
    message = "[Not Implemented] %s" % string
    ModbusException.__init__(self, message)


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def __init__(self, string=""):
    """Initialize the exception
    :param string: The message to append to the error
    """
    message = "[Not Implemented] %s" % string
    ModbusException.__init__(self, message)
# Buggy code
def __init__(self, string=""):
    """Initialize the exception

    :param string: The message to append to the error
    """
    message = "[Connection] %s" % string
    ModbusException.__init__(self, message)


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def __init__(self, string=""):
    """Initialize the exception

    :param string: The message to append to the error
    """
    message = "[Connection] %s" % string
    ModbusException.__init__(self, message)
# Buggy code
def __init__(self, string=""):
    """Initialize the exception

    :param string: The message to append to the error
    """
    message = "[Invalid Message] %s" % string
    ModbusException.__init__(self, message)


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def __init__(self, string=""):
    """Initialize the exception

    :param string: The message to append to the error
    """
    message = "[Invalid Message] %s" % string
    ModbusException.__init__(self, message)
# Buggy code
def __init__(self):
    """Initializes the client lookup tables"""
    functions = set(f.function_code for f in self.__function_table)
    self.__lookup = dict([(f.function_code, f) for f in self.__function_table])
    self.__sub_lookup = dict((f, {}) for f in functions)
    for f in self.__sub_function_table:
        self.__sub_lookup[f.function_code][f.sub_function_code] = f


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def __init__(self):
    """Initializes the client lookup tables"""
    functions = set(f.function_code for f in self.__function_table)
    self.__lookup = dict([(f.function_code, f) for f in self.__function_table])
    self.__sub_lookup = dict((f, {}) for f in functions)
    for f in self.__sub_function_table:
        self.__sub_lookup[f.function_code][f.sub_function_code] = f
# Buggy code
def decode(self, message):
    """Wrapper to decode a request packet

    :param message: The raw modbus request packet
    :return: The decoded modbus message or None if error
    """
    try:
        return self._helper(message)
    except ModbusException as er:
        _logger.warning("Unable to decode request %s" % er)
    return None


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def decode(self, message):
    """Wrapper to decode a request packet

    :param message: The raw modbus request packet
    :return: The decoded modbus message or None if error
    """
    try:
        return self._helper(message)
    except ModbusException as er:
        _logger.warning("Unable to decode request %s" % er)
    return None
# Buggy code
def lookupPduClass(self, function_code):
    """Use `function_code` to determine the class of the PDU.

    :param function_code: The function code specified in a frame.
    :returns: The class of the PDU that has a matching `function_code`.
    """
    return self.__lookup.get(function_code, ExceptionResponse)


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def lookupPduClass(self, function_code):
    """Use `function_code` to determine the class of the PDU.

    :param function_code: The function code specified in a frame.
    :returns: The class of the PDU that has a matching `function_code`.
    """
    return self.__lookup.get(function_code, ExceptionResponse)
# Buggy code
def _helper(self, data):
    """
    This factory is used to generate the correct request object
    from a valid request packet. This decodes from a list of the
    currently implemented request types.

    :param data: The request packet to decode
    :returns: The decoded request or illegal function request object
    """
    function_code = byte2int(data[0])
    _logger.debug("Factory Request[%d]" % function_code)
    request = self.__lookup.get(function_code, lambda: None)()
    if not request:
        request = IllegalFunctionRequest(function_code)
    request.decode(data[1:])

    if hasattr(request, "sub_function_code"):
        lookup = self.__sub_lookup.get(request.function_code, {})
        subtype = lookup.get(request.sub_function_code, None)
        if subtype:
            request.__class__ = subtype

    return request


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def _helper(self, data):
    """
    This factory is used to generate the correct request object
    from a valid request packet. This decodes from a list of the
    currently implemented request types.

    :param data: The request packet to decode
    :returns: The decoded request or illegal function request object
    """
    function_code = byte2int(data[0])
    request = self.__lookup.get(function_code, lambda: None)()
    if not request:
        _logger.debug("Factory Request[%d]" % function_code)
        request = IllegalFunctionRequest(function_code)
    else:
        fc_string = "%s: %s" % (
            str(self.__lookup[function_code]).split(".")[-1].rstrip("'>"),
            function_code,
        )
        _logger.debug("Factory Request[%s]" % fc_string)
    request.decode(data[1:])

    if hasattr(request, "sub_function_code"):
        lookup = self.__sub_lookup.get(request.function_code, {})
        subtype = lookup.get(request.sub_function_code, None)
        if subtype:
            request.__class__ = subtype

    return request
# Buggy code
def decode(self, message):
    """Wrapper to decode a response packet

    :param message: The raw packet to decode
    :return: The decoded modbus message or None if error
    """
    try:
        return self._helper(message)
    except ModbusException as er:
        _logger.error("Unable to decode response %s" % er)

    except Exception as ex:
        _logger.error(ex)
    return None


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def decode(self, message):
    """Wrapper to decode a response packet

    :param message: The raw packet to decode
    :return: The decoded modbus message or None if error
    """
    try:
        return self._helper(message)
    except ModbusException as er:
        _logger.error("Unable to decode response %s" % er)

    except Exception as ex:
        _logger.error(ex)
    return None
# Buggy code
def _helper(self, data):
    """
    This factory is used to generate the correct response object
    from a valid response packet. This decodes from a list of the
    currently implemented request types.

    :param data: The response packet to decode
    :returns: The decoded request or an exception response object
    """
    fc_string = function_code = byte2int(data[0])
    if function_code in self.__lookup:
        fc_string = "%s: %s" % (
            str(self.__lookup[function_code]).split(".")[-1].rstrip("'>"),
            function_code,
        )
    _logger.debug("Factory Response[%s]" % fc_string)
    response = self.__lookup.get(function_code, lambda: None)()
    if function_code > 0x80:
        code = function_code & 0x7F  # strip error portion
        response = ExceptionResponse(code, ecode.IllegalFunction)
    if not response:
        raise ModbusException("Unknown response %d" % function_code)
    response.decode(data[1:])

    if hasattr(response, "sub_function_code"):
        lookup = self.__sub_lookup.get(response.function_code, {})
        subtype = lookup.get(response.sub_function_code, None)
        if subtype:
            response.__class__ = subtype

    return response


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def _helper(self, data):
    """
    This factory is used to generate the correct response object
    from a valid response packet. This decodes from a list of the
    currently implemented request types.

    :param data: The response packet to decode
    :returns: The decoded request or an exception response object
    """
    fc_string = function_code = byte2int(data[0])
    if function_code in self.__lookup:
        fc_string = "%s: %s" % (
            str(self.__lookup[function_code]).split(".")[-1].rstrip("'>"),
            function_code,
        )
    _logger.debug("Factory Response[%s]" % fc_string)
    response = self.__lookup.get(function_code, lambda: None)()
    if function_code > 0x80:
        code = function_code & 0x7F  # strip error portion
        response = ExceptionResponse(code, ecode.IllegalFunction)
    if not response:
        raise ModbusException("Unknown response %d" % function_code)
    response.decode(data[1:])

    if hasattr(response, "sub_function_code"):
        lookup = self.__sub_lookup.get(response.function_code, {})
        subtype = lookup.get(response.sub_function_code, None)
        if subtype:
            response.__class__ = subtype

    return response
# Buggy code
def checkFrame(self):
    """
    Check if the next frame is available.
    Return True if we were successful.

    1. Populate header
    2. Discard frame if UID does not match
    """
    try:
        self.populateHeader()
        frame_size = self._header["len"]
        data = self._buffer[: frame_size - 2]
        crc = self._buffer[frame_size - 2 : frame_size]
        crc_val = (byte2int(crc[0]) << 8) + byte2int(crc[1])
        return checkCRC(data, crc_val)
    except (IndexError, KeyError, struct.error):
        return False


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def checkFrame(self):
    """
    Check if the next frame is available.
    Return True if we were successful.

    1. Populate header
    2. Discard frame if UID does not match
    """
    try:
        self.populateHeader()
        frame_size = self._header["len"]
        data = self._buffer[: frame_size - 2]
        crc = self._buffer[frame_size - 2 : frame_size]
        crc_val = (byte2int(crc[0]) << 8) + byte2int(crc[1])
        if checkCRC(data, crc_val):
            return True
        else:
            _logger.debug("CRC invalid, discarding header!!")
            self.resetFrame()
            return False
    except (IndexError, KeyError, struct.error):
        return False
# Buggy code
def populateResult(self, result):
    """
    Populates the modbus result header

    The serial packets do not have any header information
    that is copied.

    :param result: The response packet
    """
    result.unit_id = self._header["uid"]


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def populateResult(self, result):
    """
    Populates the modbus result header

    The serial packets do not have any header information
    that is copied.

    :param result: The response packet
    """
    result.unit_id = self._header["uid"]
    result.transaction_id = self._header["uid"]
# Buggy code
def buildPacket(self, message):
    """
    Creates a ready to send modbus packet

    :param message: The populated request/response to send
    """
    data = message.encode()
    packet = (
        struct.pack(RTU_FRAME_HEADER, message.unit_id, message.function_code) + data
    )
    packet += struct.pack(">H", computeCRC(packet))
    return packet


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def buildPacket(self, message):
    """
    Creates a ready to send modbus packet

    :param message: The populated request/response to send
    """
    data = message.encode()
    packet = (
        struct.pack(RTU_FRAME_HEADER, message.unit_id, message.function_code) + data
    )
    packet += struct.pack(">H", computeCRC(packet))
    message.transaction_id = (
        message.unit_id
    )  # Ensure that transaction is actually the unit id for serial comms
    return packet
# Buggy code
def __new__(cls, *args, **kwargs):
    """Create a new instance"""
    if "_inst" not in vars(cls):
        cls._inst = object.__new__(cls)
    return cls._inst


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def __new__(cls, *args, **kwargs):
    """Create a new instance"""
    if "_inst" not in vars(cls):
        cls._inst = object.__new__(cls)
    return cls._inst
# Buggy code
def decode(self, message):
    """Wrapper to decode a given packet

    :param message: The raw modbus request packet
    :return: The decoded modbus message or None if error
    """
    raise NotImplementedException("Method not implemented by derived class")


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def decode(self, message):
    """Wrapper to decode a given packet

    :param message: The raw modbus request packet
    :return: The decoded modbus message or None if error
    """
    raise NotImplementedException("Method not implemented by derived class")
# Buggy code
def lookupPduClass(self, function_code):
    """Use `function_code` to determine the class of the PDU.

    :param function_code: The function code specified in a frame.
    :returns: The class of the PDU that has a matching `function_code`.
    """
    raise NotImplementedException("Method not implemented by derived class")


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def lookupPduClass(self, function_code):
    """Use `function_code` to determine the class of the PDU.

    :param function_code: The function code specified in a frame.
    :returns: The class of the PDU that has a matching `function_code`.
    """
    raise NotImplementedException("Method not implemented by derived class")
# Buggy code
def checkFrame(self):
    """Check and decode the next frame

    :returns: True if we successful, False otherwise
    """
    raise NotImplementedException("Method not implemented by derived class")


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def checkFrame(self):
    """Check and decode the next frame

    :returns: True if we successful, False otherwise
    """
    raise NotImplementedException("Method not implemented by derived class")
# Buggy code
def advanceFrame(self):
    """Skip over the current framed message
    This allows us to skip over the current message after we have processed
    it or determined that it contains an error. It also has to reset the
    current frame header handle
    """
    raise NotImplementedException("Method not implemented by derived class")


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def advanceFrame(self):
    """Skip over the current framed message
    This allows us to skip over the current message after we have processed
    it or determined that it contains an error. It also has to reset the
    current frame header handle
    """
    raise NotImplementedException("Method not implemented by derived class")
# Buggy code
def addToFrame(self, message):
    """Add the next message to the frame buffer

    This should be used before the decoding while loop to add the received
    data to the buffer handle.

    :param message: The most recent packet
    """
    raise NotImplementedException("Method not implemented by derived class")


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def addToFrame(self, message):
    """Add the next message to the frame buffer

    This should be used before the decoding while loop to add the received
    data to the buffer handle.

    :param message: The most recent packet
    """
    raise NotImplementedException("Method not implemented by derived class")
# Buggy code
def isFrameReady(self):
    """Check if we should continue decode logic

    This is meant to be used in a while loop in the decoding phase to let
    the decoder know that there is still data in the buffer.

    :returns: True if ready, False otherwise
    """
    raise NotImplementedException("Method not implemented by derived class")


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def isFrameReady(self):
    """Check if we should continue decode logic

    This is meant to be used in a while loop in the decoding phase to let
    the decoder know that there is still data in the buffer.

    :returns: True if ready, False otherwise
    """
    raise NotImplementedException("Method not implemented by derived class")
# Buggy code
def getFrame(self):
    """Get the next frame from the buffer

    :returns: The frame data or ''
    """
    raise NotImplementedException("Method not implemented by derived class")


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def getFrame(self):
    """Get the next frame from the buffer

    :returns: The frame data or ''
    """
    raise NotImplementedException("Method not implemented by derived class")
# Buggy code
def populateResult(self, result):
    """Populates the modbus result with current frame header

    We basically copy the data back over from the current header
    to the result header. This may not be needed for serial messages.

    :param result: The response packet
    """
    raise NotImplementedException("Method not implemented by derived class")


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def populateResult(self, result):
    """Populates the modbus result with current frame header

    We basically copy the data back over from the current header
    to the result header. This may not be needed for serial messages.

    :param result: The response packet
    """
    raise NotImplementedException("Method not implemented by derived class")
# Buggy code
def processIncomingPacket(self, data, callback):
    """The new packet processing pattern

    This takes in a new request packet, adds it to the current
    packet stream, and performs framing on it. That is, checks
    for complete messages, and once found, will process all that
    exist.  This handles the case when we read N + 1 or 1 / N
    messages at a time instead of 1.

    The processed and decoded messages are pushed to the callback
    function to process and send.

    :param data: The new packet data
    :param callback: The function to send results to
    """
    raise NotImplementedException("Method not implemented by derived class")


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def processIncomingPacket(self, data, callback):
    """The new packet processing pattern

    This takes in a new request packet, adds it to the current
    packet stream, and performs framing on it. That is, checks
    for complete messages, and once found, will process all that
    exist.  This handles the case when we read N + 1 or 1 / N
    messages at a time instead of 1.

    The processed and decoded messages are pushed to the callback
    function to process and send.

    :param data: The new packet data
    :param callback: The function to send results to
    """
    raise NotImplementedException("Method not implemented by derived class")
# Buggy code
def buildPacket(self, message):
    """Creates a ready to send modbus packet

    The raw packet is built off of a fully populated modbus
    request / response message.

    :param message: The request/response to send
    :returns: The built packet
    """
    raise NotImplementedException("Method not implemented by derived class")


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def buildPacket(self, message):
    """Creates a ready to send modbus packet

    The raw packet is built off of a fully populated modbus
    request / response message.

    :param message: The request/response to send
    :returns: The built packet
    """
    raise NotImplementedException("Method not implemented by derived class")
# Buggy code
def decode(self, fx):
    """Converts the function code to the datastore to

    :param fx: The function we are working with
    :returns: one of [d(iscretes),i(inputs),h(oliding),c(oils)
    """
    return self.__fx_mapper[fx]


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def decode(self, fx):
    """Converts the function code to the datastore to

    :param fx: The function we are working with
    :returns: one of [d(iscretes),i(inputs),h(oliding),c(oils)
    """
    return self.__fx_mapper[fx]