<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def count_cores_in_state(self, state, app_id):
 """Count the number of cores in a given state. .. warning:: In current implementations of SARK, signals (which are used to determine the state of cores) are highly likely to arrive but this is not guaranteed (especially when the system's network is heavily utilised). Users should treat this mechanism with caution. Future versions of SARK may resolve this issue. Parameters state : string or :py:class:`~rig.machine_control.consts.AppState` or iterable Count the number of cores currently in this state. This may be either an entry of the :py:class:`~rig.machine_control.consts.AppState` enum or, for convenience, the name of a state (defined in :py:class:`~rig.machine_control.consts.AppState`) as a string or an iterable of these, in which case the total count will be returned. """

        if (isinstance(state, collections.Iterable) and
                not isinstance(state, str)):
            # If the state is iterable then call for each state and return the
            # sum.
            return sum(self.count_cores_in_state(s, app_id) for s in state)

        if isinstance(state, str):
            try:
                state = getattr(consts.AppState, state)
            except AttributeError:
                # The state name is not present in consts.AppSignal! The next
                # test will throw an appropriate exception since no string can
                # be "in" an IntEnum.
                pass
        if state not in consts.AppState:
            raise ValueError(
                "count_cores_in_state: Unknown state {}".format(
                    repr(state)))

        # TODO Determine a way to nicely express a way to use the region data
        # stored in arg3.
        region = 0x0000ffff  # Largest possible machine, level 0
        level = (region >> 16) & 0x3
        mask = region & 0x0000ffff

        # Construct the packet
        arg1 = consts.diagnostic_signal_types[consts.AppDiagnosticSignal.count]
        arg2 = ((level << 26) | (1 << 22) |
                (consts.AppDiagnosticSignal.count << 20) | (state << 16) |
                (0xff << 8) | app_id)  # App mask for 1 app_id = 0xff
        arg3 = mask

        # Transmit and return the count
        return self._send_scp(
            255, 255, 0, SCPCommands.signal, arg1, arg2, arg3).arg1