Change to a new state if the transition is allowed

        Args:
            state (str): State to transition to
            message (str): Message if the transition is to a fault state
969265
def transition(self, state, message=""):
        
        with self.changes_squashed:
            initial_state = self.state.value
            if self.state_set.transition_allowed(
                    initial_state=initial_state, target_state=state):
                self.log.debug(
                    "%s: Transitioning from %s to %s",
                    self.mri, initial_state, state)
                if state == ss.DISABLED:
                    alarm = Alarm.invalid("Disabled")
                elif state == ss.FAULT:
                    alarm = Alarm.major(message)
                else:
                    alarm = Alarm()
                self.update_health(self, HealthInfo(alarm))
                self.state.set_value(state)
                self.state.set_alarm(alarm)
                for child, writeable in self._children_writeable[state].items():
                    if isinstance(child, AttributeModel):
                        child.meta.set_writeable(writeable)
                    elif isinstance(child, MethodModel):
                        child.set_writeable(writeable)
            else:
                raise TypeError("Cannot transition from %s to %s" %
                                (initial_state, state))
931859
def __bad_transition(self, state):
        
        statemsg = ""
        oldState = self.stateNames[ self.get_state() ]
        newState = self.stateNames[ state ]
        msg = "Invalid state transition (%s -> %s)" \
              " for breakpoint at address %s"
        msg = msg % (oldState, newState, HexDump.address(self.get_address()))
        raise AssertionError(msg)
392696
private void setState(IState toState)
    {
        // We want to make sure state changes happen purely on the "home" thread,
        // for the sake of sanity and avoiding many obscure race-condition bugs.
        if (Thread.currentThread() == this.homeThread)
        {
            // We are on the home thread, so safe to proceed:
            if (this.state != toState)
            {
                System.out.println(getName() + " enter state: " + toState);
                TCPUtils.Log(Level.INFO, "======== " + getName() + " enter state: " + toState + " ========");
                this.state = toState;
                onPreStateChange(toState);
                onStateChange();
            }
        }
        else
        {
            // We are not on the home thread; queue this state transition
            // so that the home thread can act on it.
            queueStateChange(toState);
        }
    }
1043339
def state(self, state: str) -> None:
        """"""
        self._state = state
        for callback in self._callbacks:
            callback()
865693
def state_transition_run(self, event_to_wait_on):
        
        # with the daemon=Turue setting, this thread should
        # quit 'automatically'
        while event_to_wait_on.wait():
            event_to_wait_on.clear()
            if self.state_transition_callback_kill_event.is_set():
                return
            self.state_transition_func()
505186
def transition_to(state)
      ::Instana.logger.debug("Transitioning to #{state}")
      case state
      when :announced
        # announce successful; set state
        @state = :announced

        # Reset the entity timer
        @entity_last_seen = Time.now

      when :unannounced
        @state = :unannounced
        # Reset our HTTP client
        @httpclient = nil

      else
        ::Instana.logger.debug "Uknown agent state: #{state}"
      end
      ::Instana.collector.reset_timer!
      true
    end
1179276
def _state_invalid(self):
        
        for statemanager, conditions in self.statetransition.transitions.items():
            current_state = getattr(self.obj, statemanager.propname)
            if conditions['from'] is None:
                state_valid = True
            else:
                mstate = conditions['from'].get(current_state)
                state_valid = mstate and mstate(self.obj)
            if state_valid and conditions['if']:
                state_valid = all(v(self.obj) for v in conditions['if'])
            if not state_valid:
                return statemanager, current_state, statemanager.lenum.get(current_state)
51285
def mainswitch_state(frames):
        """"""
        reader = MessageReader(frames)
        res = reader.string("command").bool("state").assert_end().get()
        if res.command != "mainswitch.state":
            raise MessageParserError("Command is not 'mainswitch.state'")
        return (res.state,)
161152
def _oneTransition(self, startState, inputToken, endState, outputTokens,
                       collector):
        
        # FIXME: tests for all of this (some of it is wrong)
        # if not isinstance(startState, MethodicalState):
        #     raise NotImplementedError("start state {} isn't a state"
        #                               .format(startState))
        # if not isinstance(inputToken, MethodicalInput):
        #     raise NotImplementedError("start state {} isn't an input"
        #                               .format(inputToken))
        # if not isinstance(endState, MethodicalState):
        #     raise NotImplementedError("end state {} isn't a state"
        #                               .format(startState))
        # for output in outputTokens:
        #     if not isinstance(endState, MethodicalState):
        #         raise NotImplementedError("output state {} isn't a state"
        #                                   .format(endState))
        self._automaton.addTransition(startState, inputToken, endState,
                                      tuple(outputTokens))
        inputToken.collectors[startState] = collector
717882
def state_transition(
        target_state: Optional[TargetTransferState],
        state_change: StateChange,
        channel_state: NettingChannelState,
        pseudo_random_generator: random.Random,
        block_number: BlockNumber,
) -> TransitionResult[TargetTransferState]:
    
    # pylint: disable=too-many-branches,unidiomatic-typecheck

    iteration = TransitionResult(target_state, list())
    if type(state_change) == ActionInitTarget:
        assert isinstance(state_change, ActionInitTarget), MYPY_ANNOTATION
        if target_state is None:
            iteration = handle_inittarget(
                state_change,
                channel_state,
                pseudo_random_generator,
                block_number,
            )
    elif type(state_change) == Block:
        assert isinstance(state_change, Block), MYPY_ANNOTATION
        assert state_change.block_number == block_number
        assert target_state, 'Block state changes should be accompanied by a valid target state'

        iteration = handle_block(
            target_state=target_state,
            channel_state=channel_state,
            block_number=state_change.block_number,
            block_hash=state_change.block_hash,
        )
    elif type(state_change) == ReceiveSecretReveal:
        assert isinstance(state_change, ReceiveSecretReveal), MYPY_ANNOTATION
        assert target_state, 'ReceiveSecretReveal should be accompanied by a valid target state'
        iteration = handle_offchain_secretreveal(
            target_state=target_state,
            state_change=state_change,
            channel_state=channel_state,
            pseudo_random_generator=pseudo_random_generator,
            block_number=block_number,
        )
    elif type(state_change) == ContractReceiveSecretReveal:
        assert isinstance(state_change, ContractReceiveSecretReveal), MYPY_ANNOTATION
        msg = 'ContractReceiveSecretReveal should be accompanied by a valid target state'
        assert target_state, msg
        iteration = handle_onchain_secretreveal(
            target_state,
            state_change,
            channel_state,
        )
    elif type(state_change) == ReceiveUnlock:
        assert isinstance(state_change, ReceiveUnlock), MYPY_ANNOTATION
        assert target_state, 'ReceiveUnlock should be accompanied by a valid target state'
        iteration = handle_unlock(
            target_state=target_state,
            state_change=state_change,
            channel_state=channel_state,
        )
    elif type(state_change) == ReceiveLockExpired:
        assert isinstance(state_change, ReceiveLockExpired), MYPY_ANNOTATION
        assert target_state, 'ReceiveLockExpired should be accompanied by a valid target state'
        iteration = handle_lock_expired(
            target_state=target_state,
            state_change=state_change,
            channel_state=channel_state,
            block_number=block_number,
        )

    sanity_check(
        old_state=target_state,
        new_state=iteration.new_state,
        channel_state=channel_state,
    )

    return iteration
516574
def _reinterpreted_state(state):
    '''
    
    '''
    ret = state['changes']
    state['changes'] = {}
    state['comment'] = ''

    out = ret.get('stdout')
    if not out:
        if ret.get('stderr'):
            state['comment'] = ret['stderr']
        return state

    is_json = False
    try:
        data = salt.utils.json.loads(out)
        if not isinstance(data, dict):
            return _failout(
                state,
                'script JSON output must be a JSON object (e.g., {})!'
            )
        is_json = True
    except ValueError:
        idx = out.rstrip().rfind('\n')
        if idx != -1:
            out = out[idx + 1:]
        data = {}
        try:
            for item in salt.utils.args.shlex_split(out):
                key, val = item.split('=')
                data[key] = val
        except ValueError:
            state = _failout(
                state,
                'Failed parsing script output! '
                'Stdout must be JSON or a line of name=value pairs.'
            )
            state['changes'].update(ret)
            return state

    changed = _is_true(data.get('changed', 'no'))

    if 'comment' in data:
        state['comment'] = data['comment']
        del data['comment']

    if changed:
        for key in ret:
            data.setdefault(key, ret[key])

        # if stdout is the state output in JSON, don't show it.
        # otherwise it contains the one line name=value pairs, strip it.
        data['stdout'] = '' if is_json else data.get('stdout', '')[:idx]
        state['changes'] = data

    #FIXME: if it's not changed but there's stdout and/or stderr then those
    #       won't be shown as the function output. (though, they will be shown
    #       inside INFO logs).
    return state
1233033
def transition_to(path, current_state=self.current_state)
      path = path.to_s
      state = current_state || self
      exit_states = []

      # Find the nearest parent state on the path of the current state which
      # has a sub-state at the given path
      new_states = state.find_states(path)
      while(!new_states) do
        exit_states << state
        state = state.parent_state
        raise(StateNotFound, transition_error(path)) unless state
        new_states = state.find_states(path)
      end

      # The first time we enter a state, the state_manager gets entered as well
      new_states.unshift(self) unless has_state?

      # Can only transition to leaf states
      # TODO: transition to the initial_state of the state?
      raise(InvalidTransition, transition_error(path)) unless new_states.last.leaf?

      enter_states = new_states - exit_states
      exit_states = exit_states - new_states

      from_state = current_state
      # TODO: does it make more sense to throw an error instead of allowing
      # a transition to the current state?
      to_state = enter_states.last || from_state

      run_before_callbacks(from_state, to_state, current_event, enter_states, exit_states)

      # Set the state on the underlying resource
      self.current_state = to_state

      run_after_callbacks(from_state, to_state, current_event, enter_states, exit_states)
    end
41800
private void transitionTo(State newState, CheckedRunnable listener) {
    boolean transitioned = false;
    synchronized (this) {
      if (!getState().equals(newState)) {
        switch (newState) {
          case CLOSED:
            state.set(new ClosedState(this));
            break;
          case OPEN:
            state.set(new OpenState(this, state.get()));
            break;
          case HALF_OPEN:
            state.set(new HalfOpenState(this));
            break;
        }
        transitioned = true;
      }
    }

    if (transitioned && listener != null) {
      try {
        listener.run();
      } catch (Exception ignore) {
      }
    }
  }
395274
def can_transition(self, status_from: str, status_to: str) -> bool:
        
        if not self.STATUSES.can_transition(status_from=status_from, status_to=status_to):
            _logger.info(
                '`%s` tried to transition from status `%s` to non permitted status `%s`',
                str(self), status_from, status_to)
            return False

        return True
1317801
private synchronized void setState(int state) {
        mState = state;

        // Give the new state to the Handler so the UI Activity can update
        mHandler.obtainMessage(ISOBlueDemo.MESSAGE_STATE_CHANGE, state, -1)
                .sendToTarget();
    }
1298858
protected final synchronized void transitionState(OperationState newState) {
    getLogger().debug("Transitioned state from %s to %s", state, newState);
    state = newState;
    // Discard our buffer when we no longer need it.
    if(state != OperationState.WRITE_QUEUED
        && state != OperationState.WRITING) {
      cmd = null;
    }
    if (state == OperationState.COMPLETE) {
      callback.complete();
    }
  }
1121046
public void createStateDefaultTransition(final TransitionableState state, final String targetState) {
        if (state == null) {
            LOGGER.trace("Cannot add default transition of [{}] to the given state is null and cannot be found in the flow.", targetState);
            return;
        }
        val transition = createTransition(targetState);
        state.getTransitionSet().add(transition);
    }