Here you can get state - used by tools as well as modules That save state persistently
180130
function getImageIdSpecificToolState(element, toolType) {
    const enabledElement = external.cornerstone.getEnabledElement(element);
    // If we don't have any tool state for this imageId, return undefined

    if (
      !enabledElement.image ||
      toolState.hasOwnProperty(enabledElement.image.imageId) === false
    ) {
      return;
    }

    const imageIdToolState = toolState[enabledElement.image.imageId];

    // If we don't have tool state for this type of tool, return undefined
    if (imageIdToolState.hasOwnProperty(toolType) === false) {
      return;
    }

    const toolData = imageIdToolState[toolType];

    return toolData;
  }
704021
def _set_persistent_module(mod):
    '''
    
    '''
    if not mod or mod in mod_list(True) or mod not in \
            available():
        return set()
    __salt__['file.append'](_LOADER_CONF, _LOAD_MODULE.format(mod))
    return set([mod])
472968
def PushState(self, **_):
    """"""
    if self.verbose:
      logging.debug("Storing state %r", self.state)
    self.state_stack.append(self.state)
379237
def collect_internal_data(self):
        '''
        
        '''
        section = 'configuration'
        self.out.put(section)
        self.collector.add(section)
        self.out.put('Saving config', indent=2)
        self.collector.write('General Configuration', self.config)
        self.out.put('Saving pillars', indent=2)
        self.collector.write('Active Pillars', self._local_call({'fun': 'pillar.items'}))

        section = 'highstate'
        self.out.put(section)
        self.collector.add(section)
        self.out.put('Saving highstate', indent=2)
        self.collector.write('Rendered highstate', self._local_call({'fun': 'state.show_highstate'}))
356747
def get_state(self):
        """"""
        return {"started": (True if self.background_process and
                            self.background_process.is_alive() else False),
                "paused": self._pause.value,
                "stopped": self._end.value,
                "tasks": len(self.current_tasks),
                "busy_tasks": len(self.busy_tasks),
                "free_tasks": len(self.free_tasks)}
844063
def get_app_state():
    
    if not hasattr(g, 'app_state'):
        model = get_model()
        g.app_state = {
            'app_title': APP_TITLE,
            'model_name': type(model).__name__,
            'latest_ckpt_name': model.latest_ckpt_name,
            'latest_ckpt_time': model.latest_ckpt_time
        }
    return g.app_state
397496
function save_allstate() {
    var res = {};

    if (gli_rootwin)
        res.rootwin = gli_rootwin.disprock;

    if (gli_currentstr)
        res.currentstr = gli_currentstr.disprock;

    if (gli_timer_interval)
        res.timer_interval = gli_timer_interval;

    res.windows = [];
    for (var win = gli_windowlist; win; win = win.next) {
        var obj = {
            type: win.type, rock: win.rock, disprock: win.disprock,
            style: win.style, hyperlink: win.hyperlink
        };
        if (win.parent)
            obj.parent = win.parent.disprock;
        obj.str = win.str.disprock;
        if (win.echostr)
            obj.echostr = win.echostr.disprock;

        obj.bbox = { 
            left: win.bbox.left, right: win.bbox.right,
            top: win.bbox.top, bottom: win.bbox.bottom 
        };

        if (win.linebuf !== null) {
            var info = GiDispa.get_retained_array(win.linebuf);
            obj.linebuf = {
                addr: info.addr,
                len: info.len,
                arr: info.arr.slice(0),
                arg: info.arg.serialize()
            };
        }
        obj.char_request = win.char_request;
        obj.line_request = win.line_request;
        obj.char_request_uni = win.char_request_uni;
        obj.line_request_uni = win.line_request_uni;
        obj.hyperlink_request = win.hyperlink_request;
        obj.mouse_request = win.mouse_request;
        obj.echo_line_input = win.echo_line_input;
        obj.request_echo_line_input = win.request_echo_line_input;
        obj.line_input_terminators = win.line_input_terminators.slice(0);
        //### should have a request_line_input_terminators as well

        switch (win.type) {
        case Const.wintype_TextBuffer:
            obj.reserve = win.reserve.slice(0);
            break;
        case Const.wintype_TextGrid:
            obj.gridwidth = win.gridwidth;
            obj.gridheight = win.gridheight;
            obj.lines = [];
            for (var ix=0; ix<win.lines.length; ix++) {
                var ln = win.lines[ix];
                obj.lines.push({
                        chars: ln.chars.slice(0),
                        styles: ln.styles.slice(0),
                        hyperlinks: ln.hyperlinks.slice(0)
                    });
            }
            obj.cursorx = win.cursorx;
            obj.cursory = win.cursory;
            break;
        case Const.wintype_Graphics:
            obj.graphwidth = win.graphwidth;
            obj.graphheight = win.graphheight;
            obj.reserve = win.reserve.slice(0);
            break;
        case Const.wintype_Pair:
            obj.pair_dir = win.pair_dir;
            obj.pair_division = win.pair_division;
            obj.pair_key = win.pair_key.disprock;
            obj.pair_keydamage = false;
            obj.pair_size = win.pair_size;
            obj.pair_hasborder = win.pair_hasborder;
            obj.pair_vertical = win.pair_vertical;
            obj.pair_backward = win.pair_backward;
            obj.child1 = win.child1.disprock;
            obj.child2 = win.child2.disprock;
            break;
        }

        res.windows.push(obj);
    }

    res.streams = [];
    for (var str = gli_streamlist; str; str = str.next) {
        var obj = {
            type: str.type, rock: str.rock, disprock: str.disprock,
            unicode: str.unicode, isbinary: str.isbinary,
            readcount: str.readcount, writecount: str.writecount,
            readable: str.readable, writable: str.writable,
            streaming: str.streaming
        };

        switch (str.type) {

        case strtype_Window:
            if (str.win)
                obj.win = str.win.disprock;
            break;

        case strtype_Memory:
            if (str.buf !== null) {
                var info = GiDispa.get_retained_array(str.buf);
                obj.buf = {
                    addr: info.addr,
                    len: info.len,
                    arr: info.arr.slice(0),
                    arg: info.arg.serialize()
                };
            }
            obj.buflen = str.buflen;
            obj.bufpos = str.bufpos;
            obj.bufeof = str.bufeof;
            break;

        case strtype_Resource:
            obj.resfilenum = str.resfilenum;
            // Don't need str.buf
            obj.buflen = str.buflen;
            obj.bufpos = str.bufpos;
            obj.bufeof = str.bufeof;
            break;

        case strtype_File:
            obj.origfmode = str.origfmode;
            if (!Dialog.streaming) {
                obj.ref = str.ref;
                gli_stream_flush_file(str);
                // Don't need str.buf
                obj.buflen = str.buflen;
                obj.bufpos = str.bufpos;
                obj.bufeof = str.bufeof;
            }
            else {
                str.fstream.fflush();
                obj.ref = str.ref;
                obj.filepos = str.fstream.ftell();
            }
            break;

        }

        res.streams.push(obj);
    }

    res.filerefs = [];
    for (var fref = gli_filereflist; fref; fref = fref.next) {
        var obj = {
            type: fref.type, rock: fref.rock, disprock: fref.disprock,
            filename: fref.filename, textmode: fref.textmode,
            filetype: fref.filetype, filetypename: fref.filetypename
        };

        obj.ref = fref.ref;

        res.filerefs.push(obj);
    }

    // Ignore gli_schannellist, as it's currently always empty.

    /* Save GlkOte-level information. This includes the overall metrics. */
    res.glkote = GlkOte.save_allstate();

    return res;
}
747660
def state(cls, obj, state=None):
        
        if state is None:
            ids = cls.capture_ids(obj)
            original_custom_keys = set(Store.custom_options().keys())
            return (ids, original_custom_keys)
        else:
            (ids, original_custom_keys) = state
            current_custom_keys = set(Store.custom_options().keys())
            for key in current_custom_keys.difference(original_custom_keys):
                del Store.custom_options()[key]
                cls.restore_ids(obj, ids)
976132
def get_state():
    
    sdp_state = SDPState()
    errval, errdict = _check_status(sdp_state)
    if errval == "error":
        LOG.debug(errdict['reason'])
        return dict(
            current_state="unknown",
            target_state="unknown",
            last_updated="unknown",
            reason=errdict['reason']
        )
    _last_updated = sdp_state.current_timestamp
    if sdp_state.target_timestamp > _last_updated:
        _last_updated = sdp_state.target_timestamp

    return dict(
        current_state=sdp_state.current_state,
        target_state=sdp_state.target_state,
        allowed_target_states=sdp_state.allowed_target_states[
            sdp_state.current_state],
        last_updated=_last_updated.isoformat()
    ), HTTPStatus.OK
87619
def save():
    
    from .models import ModuleInfo

    logger = logging.getLogger(__name__)
    logger.info("Saving changes")

    # Save + restart
    for module in modules():
        if module.enabled:
            if module.changed:
                module.save()
                module.restart()
                module.commit()
            else:
                logger.debug('Not saving unchanged module: %s' %
                             module.verbose_name)
        else:
            logger.debug('Not saving disabled module: %s' %
                         module.verbose_name)

    # Commit
    ModuleInfo.commit()

    logger.info("Changes saved")
142408
def snapshot(self):
        
        with self._lock:
            current_state = self.state_manager.current_state
            state_change_id = self.state_change_id

            # otherwise no state change was dispatched
            if state_change_id:
                self.storage.write_state_snapshot(state_change_id, current_state)
1050605
def savestate(self, state, chain=-1):
        """"""
        cur_chain = self._chains[chain]
        if hasattr(cur_chain, '_state_'):
            cur_chain._state_[0] = state
        else:
            s = self._h5file.create_vlarray(
                cur_chain,
                '_state_',
                tables.ObjectAtom(),
                title='The saved state of the sampler',
                filters=self.filter)
            s.append(state)
        self._h5file.flush()
783068
def get_state(self, site):
        """"""
        parser = ConfigParser()
        status_section = 'incremental'
        parser.read(self.status_file)
        timestamp = None
        try:
            timestamp = float(
                parser.get(
                    status_section,
                    self.config_site_to_name(site)))
        except NoSectionError as e:
            pass
        except NoOptionError as e:
            pass
        return(timestamp)
1129658
def restore_state(self):
        """"""
        last_path = setting('directory', '', expected_type=str)
        self.output_directory.setText(last_path)
865020
def persistent_modprobe(module):
    """"""
    if not os.path.exists('/etc/rc.modules'):
        open('/etc/rc.modules', 'a')
        os.chmod('/etc/rc.modules', 111)
    with open('/etc/rc.modules', 'r+') as modules:
        if module not in modules.read():
            modules.write('modprobe %s\n' % module)
1173139
def compute_state(self):
        
        data = {}
        data['directory'] = self._dir.path
        data['files'] = list(self._dir.files())
        data['subdirs'] = list(self._dir.subdirs())
        data['index'] = self.index()
        return data
843222
def get_current_state():
    """"""
    sdp_state = SDPState()
    errval, errdict = _check_status(sdp_state)
    if errval == "error":
        LOG.debug(errdict['reason'])
        return dict(
            current_state="unknown",
            last_updated="unknown",
            reason=errdict['reason']
        )
    LOG.debug('Current State: %s', sdp_state.current_state)
    LOG.debug('Current State last updated: %s',
              sdp_state.current_timestamp.isoformat())
    return dict(
        current_state=sdp_state.current_state,
        last_updated=sdp_state.current_timestamp.isoformat()
    ), HTTPStatus.OK