Adds a state to the state saver.

    Args:
      state_name: The name of this state.
      initial_state: The initial state vector. Only zeros are supported.
      batch_size: The batch_size or None for unknown.
960539
def add_state(self, state_name, initial_state, batch_size=None):
    
    state_shape = initial_state.get_shape().as_list()
    full_shape = [batch_size] + state_shape
    if not batch_size:
      # TODO(): -1 is now reserved for unknown, so this should be
      # updated, but that requires coordination with the binary and is
      # checkpoint incompatible.
      # TODO(eiderman): When we make the above breaking change, we should make
      # the C++ client use the initial state instead of passing in zeros.
      shape_proto = self._as_shape_proto([0] + state_shape)
      batch_size = 1
    else:
      shape_proto = self._as_shape_proto([batch_size] + state_shape)

    # Add a constant tensor of zeros. At training time, this will initialize
    # the state with the initial_state - at inference time,
    # this node is replaced by a feed.
    tiles = [batch_size] + ([1] * len(initial_state.get_shape()))
    feed_op = tf.placeholder_with_default(
        tf.tile(
            tf.expand_dims(initial_state, [0]), tiles),
        shape=full_shape,
        name='%s_feed' % state_name)
    s = {'feed_op': feed_op,
         'feed_type': initial_state.dtype,
         'feed_shape': shape_proto}
    self._states[state_name] = s
1228484
def recursively_register_child_states(self, state):
        
        self.logger.info("Execution status observer add new state {}".format(state))
        if isinstance(state, ContainerState):
            state.add_observer(self, "add_state",
                               notify_after_function=self.on_add_state)
            for state in list(state.states.values()):
                self.recursively_register_child_states(state)
                state.add_observer(self, "state_execution_status",
                                   notify_after_function=self.on_state_execution_status_changed_after)

        if isinstance(state, LibraryState):
            self.recursively_register_child_states(state.state_copy)
            state.add_observer(self, "state_execution_status",
                               notify_after_function=self.on_state_execution_status_changed_after)
1025914
public static void setMetricContextName(State state, String name) {
    state.setProp(Instrumented.METRIC_CONTEXT_NAME_KEY, name);
  }
1100356
def commit_state_create( self, nameop, current_block_number ):
        

        # have to have read-write disposition 
        if self.disposition != DISPOSITION_RW:
            log.error("FATAL: borrowing violation: not a read-write connection")
            traceback.print_stack()
            os.abort()

        cur = self.db.cursor()
        opcode = nameop.get('opcode', None)

        try:
            assert state_create_is_valid( nameop ), "Invalid state-creation"
            assert opcode is not None, "BUG: did not set opcode"
            
            preorder = state_create_get_preorder( nameop )
        except Exception, e:
            log.exception(e)
            log.error("FATAL: missing preorder and/or prior history and/or opcode")
            os.abort()

        initial_state = self.sanitize_op( nameop )
        table = state_create_get_table( nameop )
        history_id_key = state_create_get_history_id_key( nameop )
        history_id = nameop[history_id_key]
        constraints_ignored = state_create_get_always_set( nameop )

        # cannot have collided 
        if BlockstackDB.nameop_is_collided( nameop ):
            # TODO: is this reachable?
            log.debug("Not commiting '%s' since we're collided" % history_id)
            self.log_reject( current_block_number, nameop['vtxindex'], nameop['op'], nameop )
            return {}

        self.log_accept( current_block_number, nameop['vtxindex'], nameop['op'], nameop )
        
        canonical_opdata = None

        if preorder is not None:
            # preordered a name or a namespace, possibly not for the first time even.
            try:
                assert 'preorder_hash' in preorder, 'BUG: missing preorder-hash'
            except Exception as e:
                log.exception(e)
                log.error("FATAL: invalid preorder")
                os.abort()

            canonical_opdata = namedb_state_create(cur, opcode, initial_state, current_block_number,
                                                   initial_state['vtxindex'], initial_state['txid'],
                                                   history_id, preorder, table, constraints_ignored=constraints_ignored)

            if not canonical_opdata:
                log.error("FATAL: failed to create '{}'".format(history_id))
                self.db.rollback()
                os.abort()

            self.db.commit()
        
        else:
            # importing a name
            try:
                assert opcode in OPCODE_NAME_STATE_IMPORTS, "BUG: not an import operation"
            except Exception, e:
                log.exception(e)
                log.error("FATAL: invalid import operation")
                os.abort()

            canonical_opdata = namedb_state_create_as_import(self.db, opcode, initial_state, 
                                                             current_block_number, initial_state['vtxindex'], initial_state['txid'],
                                                             history_id, table, constraints_ignored=constraints_ignored)

            if not canonical_opdata:
                log.error("FATAL: failed to create '{}' as import".format(history_id))
                self.db.rollback()
                os.abort()

            self.db.commit()
        
        return canonical_opdata
1072425
def contribute_to_class(self, cls, name):
        
        super(StateField, self).contribute_to_class(cls, name)

        parent_property = getattr(cls, self.name, None)
        setattr(cls, self.name, StateFieldProperty(self, parent_property))
1162066
def lstm_init_states(batch_size):
    
    hp = Hyperparams()
    init_shapes = lstm.init_states(batch_size=batch_size, num_lstm_layer=hp.num_lstm_layer, num_hidden=hp.num_hidden)
    init_names = [s[0] for s in init_shapes]
    init_arrays = [mx.nd.zeros(x[1]) for x in init_shapes]
    return init_names, init_arrays
365106
public void markInitialState() {

        if (!attachedObjects.isEmpty()) {
            for (T t : attachedObjects) {
                if (t instanceof PartialStateHolder) {
                    ((PartialStateHolder) t).markInitialState();
                }
            }
        }
        initialState = true;

    }
939755
def update_state(self, name, state):
        

        self._loop.run_coroutine(self._client.update_state(name, state))
194945
def set_initial_state(self, initial_state, initial_frames):
    """"""
    self.env.set_initial_state(initial_state, initial_frames)
    self._initial_frames = initial_frames
147213
def _create_initstate_and_embeddings(self):
        """"""
        self._init_state = self.cell.zero_state(self.batch_size, tf.float32)
        embedding = tf.get_variable(
            "embedding", [self.vocab_size, self.num_hidden])
        inputs = tf.nn.embedding_lookup(embedding, self.input_data)
        self.inputs = tf.nn.dropout(inputs, self.dropout)
403298
def set_state(self, new_state):
        
        # Make sure it's a valid state
        if new_state not in self.STATES:
            raise ValueError('Invalid state value: %r' % new_state)

        # Set the state
        LOGGER.debug('State changing from %s to %s', self.STATES[self.state],
                     self.STATES[new_state])
        self.state = new_state
        self.state_start = time.time()
1118711
def initial_state(self, batch_size, dtype=tf.float32, trainable=False,
                    trainable_initializers=None, trainable_regularizers=None,
                    name=None):
    """"""
    core_initial_state = self._core.initial_state(
        batch_size, dtype=dtype, trainable=trainable,
        trainable_initializers=trainable_initializers,
        trainable_regularizers=trainable_regularizers, name=name)

    dropout_masks = [None] * len(self._dropout_state_size)
    def set_dropout_mask(index, state, keep_prob):
      if index is not None:
        ones = tf.ones_like(state, dtype=dtype)
        dropout_masks[index] = tf.nn.dropout(ones, keep_prob=keep_prob)
    tf.contrib.framework.nest.map_structure(
        set_dropout_mask,
        self._dropout_indexes, core_initial_state, self._keep_probs)

    return core_initial_state, dropout_masks
197297
def add_state(self, string):
        """"""
        parsed_string = string.split()
        if len(parsed_string) > 0:
            state, rules = parsed_string[0], parsed_string[1:]

            if len(rules) != len(self.alphabet):
                raise SyntaxError('Wrong count of rules ({cur}/{exp}): {string}'
                                  .format(cur=len(rules), exp=len(self.alphabet),
                                          string=string))

            if state in self.states or state == self.TERM_STATE:
                raise SyntaxError('Double definition of state: ' + state)
            else:
                self.states[state] = []

            for rule in rules:
                try:
                    self._add_rule(state, rule)
                except SyntaxError as err:
                    self.states.pop(state)
                    raise err
1066783
def save_state(self):
        
        if not self.filename:
            self.logger.error('Filename not specified. Could not save state')
            return
        self.logger.debug('Saving system state to %s', self.filename)
        for i in reversed(range(self.num_state_backups)):
            fname = self.filename if i == 0 else '%s.%d' % (self.filename, i)
            new_fname = '%s.%d' % (self.filename, i+1)
            try:
                os.rename(fname, new_fname)
            except FileNotFoundError:
                pass

        with open(self.filename, 'wb') as file, self.worker_thread.queue.mutex:
            obj_list = list(self.objects)
            config = {obj.name: obj.status for obj in obj_list
                      if getattr(obj, 'user_editable', False)}
            data = obj_list, config
            pickle.dump((STATEFILE_VERSION, data), file, pickle.HIGHEST_PROTOCOL)
487653
def initialize_create_state_map(self):
        
        self.fabric_state_map = {
            fw_const.INIT_STATE_STR: fw_const.OS_IN_NETWORK_STATE,
            fw_const.OS_IN_NETWORK_CREATE_FAIL:
                fw_const.OS_IN_NETWORK_STATE,
            fw_const.OS_IN_NETWORK_CREATE_SUCCESS:
                fw_const.OS_OUT_NETWORK_STATE,
            fw_const.OS_OUT_NETWORK_CREATE_FAIL:
                fw_const.OS_OUT_NETWORK_STATE,
            fw_const.OS_OUT_NETWORK_CREATE_SUCCESS:
                fw_const.OS_DUMMY_RTR_STATE,
            fw_const.OS_DUMMY_RTR_CREATE_FAIL:
                fw_const.OS_DUMMY_RTR_STATE,
            fw_const.OS_DUMMY_RTR_CREATE_SUCCESS:
                fw_const.DCNM_IN_NETWORK_STATE,
            fw_const.DCNM_IN_NETWORK_CREATE_FAIL:
                fw_const.DCNM_IN_NETWORK_STATE,
            fw_const.DCNM_IN_NETWORK_CREATE_SUCCESS:
                fw_const.DCNM_IN_PART_UPDATE_STATE,
            fw_const.DCNM_IN_PART_UPDATE_FAIL:
                fw_const.DCNM_IN_PART_UPDATE_STATE,
            fw_const.DCNM_IN_PART_UPDATE_SUCCESS:
                fw_const.DCNM_OUT_PART_STATE,
            fw_const.DCNM_OUT_PART_CREATE_FAIL:
                fw_const.DCNM_OUT_PART_STATE,
            fw_const.DCNM_OUT_PART_CREATE_SUCCESS:
                fw_const.DCNM_OUT_NETWORK_STATE,
            fw_const.DCNM_OUT_NETWORK_CREATE_FAIL:
                fw_const.DCNM_OUT_NETWORK_STATE,
            fw_const.DCNM_OUT_NETWORK_CREATE_SUCCESS:
                fw_const.DCNM_OUT_PART_UPDATE_STATE,
            fw_const.DCNM_OUT_PART_UPDATE_FAIL:
                fw_const.DCNM_OUT_PART_UPDATE_STATE,
            fw_const.DCNM_OUT_PART_UPDATE_SUCCESS:
                fw_const.FABRIC_PREPARE_DONE_STATE}
1186187
def save_state(self, fname):
        
        log.info("Saving state to %s", fname)
        data = {
            'ksize': self.ksize,
            'alpha': self.alpha,
            'id': self.node.id,
            'neighbors': self.bootstrappable_neighbors()
        }
        if not data['neighbors']:
            log.warning("No known neighbors, so not writing to cache.")
            return
        with open(fname, 'wb') as file:
            pickle.dump(data, file)
11257
def _add_new_state(self, *event, **kwargs):
        
        if react_to_event(self.view, self.view['state_machine_tree_view'], event):
            state_type = StateType.EXECUTION if 'state_type' not in kwargs else kwargs['state_type']
            gui_helper_state_machine.add_new_state(self._selected_sm_model, state_type)
            return True