gurudesh/pytracebugs huggingface dataset:
# Buggy code
def reset(self):
    """Resets all the datastores to their default values"""
    raise NotImplementedException("Context Reset")


# 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"""
    raise NotImplementedException("Context Reset")
# 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
    """
    raise NotImplementedException("validate context 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 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
    """
    raise NotImplementedException("validate context values")
# 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
    """
    raise NotImplementedException("get context 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 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
    """
    raise NotImplementedException("get context values")
# 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
    """
    raise NotImplementedException("set context 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):
    """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
    """
    raise NotImplementedException("set context values")
# Buggy code
def build(self):
    """Return the payload buffer as a list

    This list is two bytes per element and can
    thus be treated as a list of registers.

    :returns: The payload buffer as a list
    """
    raise NotImplementedException("set context 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 build(self):
    """Return the payload buffer as a list

    This list is two bytes per element and can
    thus be treated as a list of registers.

    :returns: The payload buffer as a list
    """
    raise NotImplementedException("set context values")
# Buggy code
def execute(self, context=None):
    """Run a read exeception status request against the store

    :returns: The populated response
    """
    identifier = b"Pymodbus"
    return ReportSlaveIdResponse(identifier)


# 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 execute(self, context=None):
    """Run a read exeception status request against the store

    :returns: The populated response
    """
    information = DeviceInformationFactory.get(_MCB)
    identifier = "-".join(information.values()).encode()
    identifier = identifier or b"Pymodbus"
    return ReportSlaveIdResponse(identifier)
# Buggy code
def to_coils(self):
    """Convert the payload buffer into a coil
    layout that can be used as a context block.

    :returns: The coil layout to use as a block
    """
    payload = self.to_registers()
    coils = [bool(int(bit)) for reg in payload[1:] for bit in format(reg, "016b")]
    return coils


# 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 to_coils(self):
    """Convert the payload buffer into a coil
    layout that can be used as a context block.

    :returns: The coil layout to use as a block
    """
    payload = self.to_registers()
    coils = [bool(int(bit)) for reg in payload for bit in format(reg, "016b")]
    return coils
# Buggy code
def fromCoils(klass, coils, byteorder=Endian.Little):
    """Initialize a payload decoder with the result of
    reading a collection of coils from a modbus device.

    The coils are treated as a list of bit(boolean) values.

    :param coils: The coil results to initialize with
    :param byteorder: The endianess of the payload
    :returns: An initialized PayloadDecoder
    """
    if isinstance(coils, list):
        payload = pack_bitstring(coils)
        return klass(payload, byteorder)
    raise ParameterException("Invalid collection of coils supplied")


# 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 fromCoils(klass, coils, byteorder=Endian.Little, wordorder=Endian.Big):
    """Initialize a payload decoder with the result of
    reading a collection of coils from a modbus device.

    The coils are treated as a list of bit(boolean) values.

    :param coils: The coil results to initialize with
    :param byteorder: The endianess of the payload
    :returns: An initialized PayloadDecoder
    """
    if isinstance(coils, list):
        payload = b""
        padding = len(coils) % 8
        if padding:  # Pad zero's
            extra = [False] * padding
            coils = extra + coils
        chunks = klass.bit_chunks(coils)
        for chunk in chunks:
            payload += pack_bitstring(chunk[::-1])
        return klass(payload, byteorder)
    raise ParameterException("Invalid collection of coils supplied")
# Buggy code
def __init__(self, store, framer=None, identity=None, **kwargs):
    """Overloaded initializer for the modbus factory

    If the identify structure is not passed in, the ModbusControlBlock
    uses its own empty structure.

    :param store: The ModbusServerContext datastore
    :param framer: The framer strategy to use
    :param identity: An optional identify structure
    :param ignore_missing_slaves: True to not send errors on a request to
    a missing slave
    """
    framer = framer or ModbusSocketFramer
    self.framer = framer(decoder=ServerDecoder())
    self.store = store or ModbusServerContext()
    self.control = ModbusControlBlock()
    self.access = ModbusAccessControl()
    self.ignore_missing_slaves = kwargs.get(
        "ignore_missing_slaves", Defaults.IgnoreMissingSlaves
    )

    if isinstance(identity, ModbusDeviceIdentification):
        self.control.Identity.update(identity)


# 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, store, framer=None, identity=None, **kwargs):
    """Overloaded initializer for the modbus factory

    If the identify structure is not passed in, the ModbusControlBlock
    uses its own empty structure.

    :param store: The ModbusServerContext datastore
    :param framer: The framer strategy to use
    :param identity: An optional identify structure
    :param ignore_missing_slaves: True to not send errors on a request to
    a missing slave
    """
    framer = framer or ModbusSocketFramer
    self.decoder = ServerDecoder()
    self.framer = framer(self.decoder)
    self.store = store or ModbusServerContext()
    self.control = ModbusControlBlock()
    self.access = ModbusAccessControl()
    self.ignore_missing_slaves = kwargs.get(
        "ignore_missing_slaves", Defaults.IgnoreMissingSlaves
    )

    if isinstance(identity, ModbusDeviceIdentification):
        self.control.Identity.update(identity)
# Buggy code
def StartTcpServer(
    context,
    identity=None,
    address=None,
    console=False,
    defer_reactor_run=False,
    **kwargs,
):
    """
    Helper method to start the Modbus Async TCP server

    :param context: The server data context
    :param identify: The server identity to use (default empty)
    :param address: An optional (interface, port) to bind to.
    :param console: A flag indicating if you want the debug console
    :param ignore_missing_slaves: True to not send errors on a request
           to a missing slave
    :param defer_reactor_run: True/False defer running reactor.run() as part
           of starting server, to be explictly started by the user

    """
    from twisted.internet import reactor

    address = address or ("", Defaults.Port)
    framer = kwargs.pop("framer", ModbusSocketFramer)
    factory = ModbusServerFactory(context, framer, identity, **kwargs)
    if console:
        InstallManagementConsole({"factory": factory})

    _logger.info("Starting Modbus TCP Server on %s:%s" % address)
    reactor.listenTCP(address[1], factory, interface=address[0])
    if not defer_reactor_run:
        reactor.run(installSignalHandlers=_is_main_thread())


# 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 StartTcpServer(
    context,
    identity=None,
    address=None,
    console=False,
    defer_reactor_run=False,
    custom_functions=[],
    **kwargs,
):
    """
    Helper method to start the Modbus Async TCP server

    :param context: The server data context
    :param identify: The server identity to use (default empty)
    :param address: An optional (interface, port) to bind to.
    :param console: A flag indicating if you want the debug console
    :param ignore_missing_slaves: True to not send errors on a request \
    to a missing slave
    :param defer_reactor_run: True/False defer running reactor.run() as part \
    of starting server, to be explictly started by the user
    :param custom_functions: An optional list of custom function classes
        supported by server instance.
    """
    from twisted.internet import reactor

    address = address or ("", Defaults.Port)
    framer = kwargs.pop("framer", ModbusSocketFramer)
    factory = ModbusServerFactory(context, framer, identity, **kwargs)
    for f in custom_functions:
        factory.decoder.register(f)
    if console:
        InstallManagementConsole({"factory": factory})

    _logger.info("Starting Modbus TCP Server on %s:%s" % address)
    reactor.listenTCP(address[1], factory, interface=address[0])
    if not defer_reactor_run:
        reactor.run(installSignalHandlers=_is_main_thread())
# Buggy code
def StartUdpServer(
    context, identity=None, address=None, defer_reactor_run=False, **kwargs
):
    """
    Helper method to start the Modbus Async Udp server

    :param context: The server data context
    :param identify: The server identity to use (default empty)
    :param address: An optional (interface, port) to bind to.
    :param ignore_missing_slaves: True to not send errors on a request
           to a missing slave
    :param defer_reactor_run: True/False defer running reactor.run() as part
           of starting server, to be explictly started by the user
    """
    from twisted.internet import reactor

    address = address or ("", Defaults.Port)
    framer = kwargs.pop("framer", ModbusSocketFramer)
    server = ModbusUdpProtocol(context, framer, identity, **kwargs)

    _logger.info("Starting Modbus UDP Server on %s:%s" % address)
    reactor.listenUDP(address[1], server, interface=address[0])
    if not defer_reactor_run:
        reactor.run(installSignalHandlers=_is_main_thread())


# 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 StartUdpServer(
    context,
    identity=None,
    address=None,
    defer_reactor_run=False,
    custom_functions=[],
    **kwargs,
):
    """
    Helper method to start the Modbus Async Udp server

    :param context: The server data context
    :param identify: The server identity to use (default empty)
    :param address: An optional (interface, port) to bind to.
    :param ignore_missing_slaves: True to not send errors on a request \
    to a missing slave
    :param defer_reactor_run: True/False defer running reactor.run() as part \
    of starting server, to be explictly started by the user
    :param custom_functions: An optional list of custom function classes
        supported by server instance.
    """
    from twisted.internet import reactor

    address = address or ("", Defaults.Port)
    framer = kwargs.pop("framer", ModbusSocketFramer)
    server = ModbusUdpProtocol(context, framer, identity, **kwargs)
    for f in custom_functions:
        server.decoder.register(f)

    _logger.info("Starting Modbus UDP Server on %s:%s" % address)
    reactor.listenUDP(address[1], server, interface=address[0])
    if not defer_reactor_run:
        reactor.run(installSignalHandlers=_is_main_thread())
# Buggy code
def execute(self, request):
    """The callback to call with the resulting message

    :param request: The decoded request message
    """
    try:
        context = self.server.context[request.unit_id]
        response = request.execute(context)
    except NoSuchSlaveException as ex:
        _logger.debug("requested slave does not exist: %s" % request.unit_id)
        if self.server.ignore_missing_slaves:
            return  # the client will simply timeout waiting for a response
        response = request.doException(merror.GatewayNoResponse)
    except Exception as ex:
        _logger.debug(
            "Datastore unable to fulfill request: %s; %s", ex, traceback.format_exc()
        )
        response = request.doException(merror.SlaveFailure)
    response.transaction_id = request.transaction_id
    response.unit_id = request.unit_id
    self.send(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 execute(self, request):
    """The callback to call with the resulting message

    :param request: The decoded request message
    """
    broadcast = False
    try:
        if self.server.broadcast_enable and request.unit_id == 0:
            broadcast = True
            # if broadcasting then execute on all slave contexts, note response will be ignored
            for unit_id in self.server.context.slaves():
                response = request.execute(self.server.context[unit_id])
        else:
            context = self.server.context[request.unit_id]
            response = request.execute(context)
    except NoSuchSlaveException as ex:
        _logger.debug("requested slave does not exist: %s" % request.unit_id)
        if self.server.ignore_missing_slaves:
            return  # the client will simply timeout waiting for a response
        response = request.doException(merror.GatewayNoResponse)
    except Exception as ex:
        _logger.debug(
            "Datastore unable to fulfill request: %s; %s", ex, traceback.format_exc()
        )
        response = request.doException(merror.SlaveFailure)
    # no response when broadcasting
    if not broadcast:
        response.transaction_id = request.transaction_id
        response.unit_id = request.unit_id
        self.send(response)
# Buggy code
def handle(self):
    """Callback when we receive any data"""
    while self.running:
        try:
            data = self.request.recv(1024)
            if data:
                units = self.server.context.slaves()
                single = self.server.context.single
                self.framer.processIncomingPacket(
                    data, self.execute, units, single=single
                )
        except Exception as msg:
            # Since we only have a single socket, we cannot exit
            # Clear frame buffer
            self.framer.resetFrame()
            _logger.debug("Error: Socket error occurred %s" % msg)


# 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 handle(self):
    """Callback when we receive any data"""
    while self.running:
        try:
            data = self.request.recv(1024)
            if data:
                units = self.server.context.slaves()
                if not isinstance(units, (list, tuple)):
                    units = [units]
                # if broadcast is enabled make sure to process requests to address 0
                if self.server.broadcast_enable:
                    if 0 not in units:
                        units.append(0)
                single = self.server.context.single
                self.framer.processIncomingPacket(
                    data, self.execute, units, single=single
                )
        except Exception as msg:
            # Since we only have a single socket, we cannot exit
            # Clear frame buffer
            self.framer.resetFrame()
            _logger.debug("Error: Socket error occurred %s" % msg)
# Buggy code
def send(self, message):
    """Send a request (string) to the network

    :param message: The unencoded modbus response
    """
    if message.should_respond:
        # self.server.control.Counter.BusMessage += 1
        pdu = self.framer.buildPacket(message)
        if _logger.isEnabledFor(logging.DEBUG):
            _logger.debug("send: %s" % b2a_hex(pdu))
        return self.request.send(pdu)


# 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 send(self, message):
    """Send a request (string) to the network

    :param message: The unencoded modbus response
    """
    if message.should_respond:
        # self.server.control.Counter.BusMessage += 1
        pdu = self.framer.buildPacket(message)
        if _logger.isEnabledFor(logging.DEBUG):
            _logger.debug("send: [%s]- %s" % (message, b2a_hex(pdu)))
        return self.request.send(pdu)
# Buggy code
def handle(self):
    """Callback when we receive any data"""
    reset_frame = False
    while self.running:
        try:
            data, self.socket = self.request
            if not data:
                self.running = False
            if _logger.isEnabledFor(logging.DEBUG):
                _logger.debug("Handling data: " + hexlify_packets(data))
            # if not self.server.control.ListenOnly:
            units = self.server.context.slaves()
            single = self.server.context.single
            self.framer.processIncomingPacket(data, self.execute, units, single=single)
        except socket.timeout:
            pass
        except socket.error as msg:
            _logger.error("Socket error occurred %s" % msg)
            self.running = False
            reset_frame = True
        except Exception as msg:
            _logger.error(msg)
            self.running = False
            reset_frame = True
        finally:
            # Reset data after processing
            self.request = (None, self.socket)
            if reset_frame:
                self.framer.resetFrame()
                reset_frame = 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 handle(self):
    """Callback when we receive any data"""
    reset_frame = False
    while self.running:
        try:
            data, self.socket = self.request
            if not data:
                self.running = False
                data = b""
            if _logger.isEnabledFor(logging.DEBUG):
                _logger.debug("Handling data: " + hexlify_packets(data))
            # if not self.server.control.ListenOnly:
            units = self.server.context.slaves()
            single = self.server.context.single
            self.framer.processIncomingPacket(data, self.execute, units, single=single)
        except socket.timeout:
            pass
        except socket.error as msg:
            _logger.error("Socket error occurred %s" % msg)
            self.running = False
            reset_frame = True
        except Exception as msg:
            _logger.error(msg)
            self.running = False
            reset_frame = True
        finally:
            # Reset data after processing
            self.request = (None, self.socket)
            if reset_frame:
                self.framer.resetFrame()
                reset_frame = False
# Buggy code
def send(self, message):
    """Send a request (string) to the network

    :param message: The unencoded modbus response
    """
    if message.should_respond:
        # self.server.control.Counter.BusMessage += 1
        pdu = self.framer.buildPacket(message)
        if _logger.isEnabledFor(logging.DEBUG):
            _logger.debug("send: %s" % b2a_hex(pdu))
        return self.socket.sendto(pdu, self.client_address)


# 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 send(self, message):
    """Send a request (string) to the network

    :param message: The unencoded modbus response
    """
    if message.should_respond:
        # self.server.control.Counter.BusMessage += 1
        pdu = self.framer.buildPacket(message)
        if _logger.isEnabledFor(logging.DEBUG):
            _logger.debug("send: [%s]- %s" % (message, b2a_hex(pdu)))
        return self.socket.sendto(pdu, self.client_address)
# Buggy code
def StartTcpServer(context=None, identity=None, address=None, **kwargs):
    """A factory to start and run a tcp modbus server

    :param context: The ModbusServerContext datastore
    :param identity: An optional identify structure
    :param address: An optional (interface, port) to bind to.
    :param ignore_missing_slaves: True to not send errors on a request to a
                                  missing slave
    """
    framer = kwargs.pop("framer", ModbusSocketFramer)
    server = ModbusTcpServer(context, framer, identity, address, **kwargs)
    server.serve_forever()


# 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 StartTcpServer(
    context=None, identity=None, address=None, custom_functions=[], **kwargs
):
    """A factory to start and run a tcp modbus server

    :param context: The ModbusServerContext datastore
    :param identity: An optional identify structure
    :param address: An optional (interface, port) to bind to.
    :param custom_functions: An optional list of custom function classes
        supported by server instance.
    :param ignore_missing_slaves: True to not send errors on a request to a
                                      missing slave
    """
    framer = kwargs.pop("framer", ModbusSocketFramer)
    server = ModbusTcpServer(context, framer, identity, address, **kwargs)

    for f in custom_functions:
        server.decoder.register(f)
    server.serve_forever()
# Buggy code
def StartUdpServer(context=None, identity=None, address=None, **kwargs):
    """A factory to start and run a udp modbus server

    :param context: The ModbusServerContext datastore
    :param identity: An optional identify structure
    :param address: An optional (interface, port) to bind to.
    :param framer: The framer to operate with (default ModbusSocketFramer)
    :param ignore_missing_slaves: True to not send errors on a request
                                    to a missing slave
    """
    framer = kwargs.pop("framer", ModbusSocketFramer)
    server = ModbusUdpServer(context, framer, identity, address, **kwargs)
    server.serve_forever()


# 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 StartUdpServer(
    context=None, identity=None, address=None, custom_functions=[], **kwargs
):
    """A factory to start and run a udp modbus server

    :param context: The ModbusServerContext datastore
    :param identity: An optional identify structure
    :param address: An optional (interface, port) to bind to.
    :param custom_functions: An optional list of custom function classes
        supported by server instance.
    :param framer: The framer to operate with (default ModbusSocketFramer)
    :param ignore_missing_slaves: True to not send errors on a request
                                    to a missing slave
    """
    framer = kwargs.pop("framer", ModbusSocketFramer)
    server = ModbusUdpServer(context, framer, identity, address, **kwargs)
    for f in custom_functions:
        server.decoder.register(f)
    server.serve_forever()
# Buggy code
def StartSerialServer(context=None, identity=None, **kwargs):
    """A factory to start and run a serial modbus server

    :param context: The ModbusServerContext datastore
    :param identity: An optional identify structure
    :param framer: The framer to operate with (default ModbusAsciiFramer)
    :param port: The serial port to attach to
    :param stopbits: The number of stop bits to use
    :param bytesize: The bytesize of the serial messages
    :param parity: Which kind of parity to use
    :param baudrate: The baud rate to use for the serial device
    :param timeout: The timeout to use for the serial device
    :param ignore_missing_slaves: True to not send errors on a request to a
                                  missing slave
    """
    framer = kwargs.pop("framer", ModbusAsciiFramer)
    server = ModbusSerialServer(context, framer, identity, **kwargs)
    server.serve_forever()


# 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 StartSerialServer(context=None, identity=None, custom_functions=[], **kwargs):
    """A factory to start and run a serial modbus server

    :param context: The ModbusServerContext datastore
    :param identity: An optional identify structure
    :param custom_functions: An optional list of custom function classes
        supported by server instance.
    :param framer: The framer to operate with (default ModbusAsciiFramer)
    :param port: The serial port to attach to
    :param stopbits: The number of stop bits to use
    :param bytesize: The bytesize of the serial messages
    :param parity: Which kind of parity to use
    :param baudrate: The baud rate to use for the serial device
    :param timeout: The timeout to use for the serial device
    :param ignore_missing_slaves: True to not send errors on a request to a
                                  missing slave
    """
    framer = kwargs.pop("framer", ModbusAsciiFramer)
    server = ModbusSerialServer(context, framer, identity, **kwargs)
    for f in custom_functions:
        server.decoder.register(f)
    server.serve_forever()
# Buggy code
def connect(self):
    """Connect to the modbus serial server

    :returns: True if connection succeeded, False otherwise
    """
    if self.socket:
        return True
    try:
        self.socket = serial.Serial(
            port=self.port,
            timeout=self.timeout,
            bytesize=self.bytesize,
            stopbits=self.stopbits,
            baudrate=self.baudrate,
            parity=self.parity,
        )
    except serial.SerialException as msg:
        _logger.error(msg)
        self.close()
    if self.method == "rtu":
        self.socket.interCharTimeout = self.inter_char_timeout
        self.last_frame_end = None
    return self.socket is not 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 connect(self):
    """Connect to the modbus serial server

    :returns: True if connection succeeded, False otherwise
    """
    if self.socket:
        return True
    try:
        self.socket = serial.Serial(
            port=self.port,
            timeout=self.timeout,
            bytesize=self.bytesize,
            stopbits=self.stopbits,
            baudrate=self.baudrate,
            parity=self.parity,
        )
        if self.method == "rtu":
            if self._strict:
                self.socket.interCharTimeout = self.inter_char_timeout
            self.last_frame_end = None
    except serial.SerialException as msg:
        _logger.error(msg)
        self.close()
    return self.socket is not None
# 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,
        )
    )
    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 _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,
        )
    )
    result = self._connection.execute(query)
    return result.rowcount == 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 _validate_unit_id(self, units, single):
    """
    Validates if the received data is valid for the client
    :param units: list of unit id for which the transaction is valid
    :param single: Set to true to treat this as a single context
    :return:"""

    if single:
        return True
    else:
        if 0 in units or 0xFF in units:
            # Handle Modbus TCP unit identifier (0x00 0r 0xFF)
            # in async requests
            return True
        return self._header["uid"] in units


# 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_unit_id(self, units, single):
    """
    Validates if the received data is valid for the client
    :param units: list of unit id for which the transaction is valid
    :param single: Set to true to treat this as a single context
    :return:"""

    if single:
        return True
    else:
        if 0 in units or 0xFF in units:
            # Handle Modbus TCP unit identifier (0x00 0r 0xFF)
            # in asynchronous requests
            return True
        return self._header["uid"] in units
# Buggy code
def connect(self):
    """Connect to the modbus serial server

    :returns: True if connection succeeded, False otherwise
    """
    if self.socket:
        return True
    try:
        self.socket = serial.Serial(
            port=self.port,
            timeout=self.timeout,
            bytesize=self.bytesize,
            stopbits=self.stopbits,
            baudrate=self.baudrate,
            parity=self.parity,
        )
    except serial.SerialException as msg:
        _logger.error(msg)
        self.close()
    if self.method == "rtu":
        if self._strict:
            self.socket.interCharTimeout = self.inter_char_timeout
        self.last_frame_end = None
    return self.socket is not 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 connect(self):
    """Connect to the modbus serial server

    :returns: True if connection succeeded, False otherwise
    """
    if self.socket:
        return True
    try:
        self.socket = serial.Serial(
            port=self.port,
            timeout=self.timeout,
            bytesize=self.bytesize,
            stopbits=self.stopbits,
            baudrate=self.baudrate,
            parity=self.parity,
        )
        if self.method == "rtu":
            if self._strict:
                self.socket.interCharTimeout = self.inter_char_timeout
            self.last_frame_end = None
    except serial.SerialException as msg:
        _logger.error(msg)
        self.close()
    return self.socket is not None
# Buggy code
def websocket_emit_data(self):
    websocket_data = super(InventoryUpdate, self).websocket_emit_data()
    websocket_data.update(dict(inventory_source_id=self.inventory_source.pk))

    if self.inventory_source.inventory is not None:
        websocket_data.update(dict(inventory_id=self.inventory_source.inventory.pk))

    if self.inventory_source.deprecated_group is not None:  # TODO: remove in 3.3
        websocket_data.update(dict(group_id=self.inventory_source.deprecated_group.id))
    return websocket_data


# Traceback (AttributeError)
Traceback (most recent call last): File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/awx/main/tasks.py", line 1308, in run args = self.build_args(self.instance, private_data_dir, passwords) File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/awx/main/tasks.py", line 2472, in build_args if getattr(settings, '%s_EXCLUDE_EMPTY_GROUPS' % src.upper()): File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/awx/conf/settings.py", line 511, in __getattr_without_cache__ return getattr(self._wrapped, name) File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/awx/conf/settings.py", line 418, in __getattr__ value = self._get_default(name) File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/awx/conf/settings.py", line 405, in _get_default return getattr(self.default_settings, name) AttributeError: 'Settings' object has no attribute '_EXCLUDE_EMPTY_GROUPS'

# Fixed code
def websocket_emit_data(self):
    websocket_data = super(InventoryUpdate, self).websocket_emit_data()
    websocket_data.update(dict(inventory_source_id=self.inventory_source.pk))

    if self.inventory_source.inventory is not None:
        websocket_data.update(dict(inventory_id=self.inventory_source.inventory.pk))

    return websocket_data
# Buggy code
def reap(instance=None, status="failed", excluded_uuids=[]):
    """
    Reap all jobs in waiting|running for this instance.
    """
    me = instance or Instance.objects.me()
    now = tz_now()
    workflow_ctype_id = ContentType.objects.get_for_model(WorkflowJob).id
    jobs = UnifiedJob.objects.filter(
        (
            Q(status="running")
            | Q(status="waiting", modified__lte=now - timedelta(seconds=60))
        )
        & (Q(execution_node=me.hostname) | Q(controller_node=me.hostname))
        & ~Q(polymorphic_ctype_id=workflow_ctype_id)
    ).exclude(celery_task_id__in=excluded_uuids)
    for j in jobs:
        reap_job(j, status)


# Traceback (RuntimeError)
Jul  4 17:20:39 1.awx.node.dc1 dispatcher[505]: 2019-07-04 14:20:39,433 ERROR    awx.main.dispatch failed to write inbound message
Jul  4 17:20:39 1.awx.node.dc1 dispatcher[505]: Traceback (most recent call last):
Jul  4 17:20:39 1.awx.node.dc1 dispatcher[505]: File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/awx/main/dispatch/pool.py", line 388, in write
Jul  4 17:20:39 1.awx.node.dc1 dispatcher[505]: self.cleanup()
Jul  4 17:20:39 1.awx.node.dc1 dispatcher[505]: File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/awx/main/dispatch/pool.py", line 373, in cleanup
Jul  4 17:20:39 1.awx.node.dc1 dispatcher[505]: reaper.reap(excluded_uuids=running_uuids)
Jul  4 17:20:39 1.awx.node.dc1 dispatcher[505]: File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/awx/main/dispatch/reaper.py", line 35, in reap
Jul  4 17:20:39 1.awx.node.dc1 dispatcher[505]: me = instance or Instance.objects.me()
Jul  4 17:20:39 1.awx.node.dc1 dispatcher[505]: File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/awx/main/managers.py", line 88, in me
Jul  4 17:20:39 1.awx.node.dc1 dispatcher[505]: raise RuntimeError("No instance found with the current cluster host id")
Jul  4 17:20:39 1.awx.node.dc1 dispatcher[505]: RuntimeError: No instance found with the current cluster host id

# Fixed code
def reap(instance=None, status="failed", excluded_uuids=[]):
    """
    Reap all jobs in waiting|running for this instance.
    """
    me = instance
    if me is None:
        (changed, me) = Instance.objects.get_or_register()
        if changed:
            logger.info("Registered tower node '{}'".format(me.hostname))
    now = tz_now()
    workflow_ctype_id = ContentType.objects.get_for_model(WorkflowJob).id
    jobs = UnifiedJob.objects.filter(
        (
            Q(status="running")
            | Q(status="waiting", modified__lte=now - timedelta(seconds=60))
        )
        & (Q(execution_node=me.hostname) | Q(controller_node=me.hostname))
        & ~Q(polymorphic_ctype_id=workflow_ctype_id)
    ).exclude(celery_task_id__in=excluded_uuids)
    for j in jobs:
        reap_job(j, status)
# Buggy code
def instance_info(since):
    info = {}
    instances = models.Instance.objects.values_list("hostname").values(
        "uuid",
        "version",
        "capacity",
        "cpu",
        "memory",
        "managed_by_policy",
        "hostname",
        "last_isolated_check",
        "enabled",
    )
    for instance in instances:
        instance_info = {
            "uuid": instance["uuid"],
            "version": instance["version"],
            "capacity": instance["capacity"],
            "cpu": instance["cpu"],
            "memory": instance["memory"],
            "managed_by_policy": instance["managed_by_policy"],
            "last_isolated_check": instance["last_isolated_check"],
            "enabled": instance["enabled"],
        }
        info[instance["uuid"]] = instance_info
    return info


# Traceback (TypeError)
2019-06-25 00:24:00,434 ERROR    awx.main.analytics Could not generate metric instance_info.json
Traceback (most recent call last):
File "/var/lib/awx/venv/awx/lib64/python3.6/site-packages/awx/main/analytics/core.py", line 94, in gather
json.dump(func(last_run), f)
File "/opt/rh/rh-python36/root/usr/lib64/python3.6/json/__init__.py", line 179, in dump
for chunk in iterable:
File "/opt/rh/rh-python36/root/usr/lib64/python3.6/json/encoder.py", line 430, in _iterencode
yield from _iterencode_dict(o, _current_indent_level)
File "/opt/rh/rh-python36/root/usr/lib64/python3.6/json/encoder.py", line 404, in _iterencode_dict
yield from chunks
File "/opt/rh/rh-python36/root/usr/lib64/python3.6/json/encoder.py", line 404, in _iterencode_dict
yield from chunks
File "/opt/rh/rh-python36/root/usr/lib64/python3.6/json/encoder.py", line 437, in _iterencode
o = _default(o)
File "/opt/rh/rh-python36/root/usr/lib64/python3.6/json/encoder.py", line 180, in default
o.__class__.__name__)
TypeError: Object of type 'datetime' is not JSON serializable
2019-06-25 00:24:00,469 ERROR    awx.main.analytics could not find insights-client on PATH

# Fixed code
def instance_info(since):
    info = {}
    instances = models.Instance.objects.values_list("hostname").values(
        "uuid",
        "version",
        "capacity",
        "cpu",
        "memory",
        "managed_by_policy",
        "hostname",
        "last_isolated_check",
        "enabled",
    )
    for instance in instances:
        instance_info = {
            "uuid": instance["uuid"],
            "version": instance["version"],
            "capacity": instance["capacity"],
            "cpu": instance["cpu"],
            "memory": instance["memory"],
            "managed_by_policy": instance["managed_by_policy"],
            "last_isolated_check": _get_isolated_datetime(
                instance["last_isolated_check"]
            ),
            "enabled": instance["enabled"],
        }
        info[instance["uuid"]] = instance_info
    return info