Save history to a text file in user home directory
354425
def save_history(self):
        """"""
        # Don't fail when saving search history to disk
        # See issues 8878 and 6864
        try:
            search_history = [to_text_string(self.combo.itemText(index))
                              for index in range(self.combo.count())]
            search_history = '\n'.join(search_history)
            open(self.LOG_PATH, 'w').write(search_history)
        except (UnicodeEncodeError, UnicodeDecodeError, EnvironmentError):
            pass
318166
def save_file(self, filename, text):
        """"""
        if not filename.endswith('.py'):
            filename += '.py'
        path = os.path.join(self.currentpath, filename)
        with open(path, 'w', encoding="utf-8") as file_:
            file_.write(text)
1011911
def append_to_history(self):
        
        # Validate first. If not valid, set validation exception.
        if not self.validate():
            return

        # Save at the tail of the history. (But don't if the last entry the
        # history is already the same.)
        if self.text and (not len(self.history) or self.history[-1] != self.text):
            self.history.append(self.text)
981441
def save_file(self):
        """"""

        l = []
        walk = self.walker
        for edit in walk.lines:
            # collect the text already stored in edit widgets
            if edit.original_text.expandtabs() == edit.edit_text:
                l.append(edit.original_text)
            else:
                l.append(re_tab(edit.edit_text))

        # then the rest
        while walk.file is not None:
            l.append(walk.read_next_line())

        # write back to disk
        outfile = open(self.save_name, "w")

        l_iter = iter(l)

        line = next(l_iter)
        prefix = ""

        while True:
            try:
                outfile.write(prefix + line)
                prefix = "\n"
                line = next(l_iter)
            except StopIteration:
                if line != "\n":
                    outfile.write("\n")
                break
831095
def _generate_transcript(self, history: List[Union[HistoryItem, str]], transcript_file: str) -> None:
        """"""
        import io
        # Validate the transcript file path to make sure directory exists and write access is available
        transcript_path = os.path.abspath(os.path.expanduser(transcript_file))
        transcript_dir = os.path.dirname(transcript_path)
        if not os.path.isdir(transcript_dir) or not os.access(transcript_dir, os.W_OK):
            self.perror("{!r} is not a directory or you don't have write access".format(transcript_dir),
                        traceback_war=False)
            return

        try:
            with self.sigint_protection:
                # Disable echo while we manually redirect stdout to a StringIO buffer
                saved_echo = self.echo
                saved_stdout = self.stdout
                self.echo = False

            # The problem with supporting regular expressions in transcripts
            # is that they shouldn't be processed in the command, just the output.
            # In addition, when we generate a transcript, any slashes in the output
            # are not really intended to indicate regular expressions, so they should
            # be escaped.
            #
            # We have to jump through some hoops here in order to catch the commands
            # separately from the output and escape the slashes in the output.
            transcript = ''
            for history_item in history:
                # build the command, complete with prompts. When we replay
                # the transcript, we look for the prompts to separate
                # the command from the output
                first = True
                command = ''
                for line in history_item.splitlines():
                    if first:
                        command += '{}{}\n'.format(self.prompt, line)
                        first = False
                    else:
                        command += '{}{}\n'.format(self.continuation_prompt, line)
                transcript += command
                # create a new string buffer and set it to stdout to catch the output
                # of the command
                membuf = io.StringIO()
                self.stdout = membuf
                # then run the command and let the output go into our buffer
                self.onecmd_plus_hooks(history_item)
                # rewind the buffer to the beginning
                membuf.seek(0)
                # get the output out of the buffer
                output = membuf.read()
                # and add the regex-escaped output to the transcript
                transcript += output.replace('/', r'\/')
        finally:
            with self.sigint_protection:
                # Restore altered attributes to their original state
                self.echo = saved_echo
                self.stdout = saved_stdout

        # finally, we can write the transcript out to the file
        try:
            with open(transcript_file, 'w') as fout:
                fout.write(transcript)
        except OSError as ex:
            self.perror('Failed to save transcript: {}'.format(ex), traceback_war=False)
        else:
            # and let the user know what we did
            if len(history) > 1:
                plural = 'commands and their outputs'
            else:
                plural = 'command and its output'
            msg = '{} {} saved to transcript file {!r}'
            self.pfeedback(msg.format(len(history), plural, transcript_file))
1206531
def save_log(self, filename = None):
        
        if filename is None:
            filename = self.filename('-info.txt')
        filename = self.check_filename(filename)
        # filename = self.check_filename(filename)
        # windows can't deal with long filenames so we have to use the prefix '\\\\?\\'
        # if len(filename.split('\\\\?\\')) == 1:
        #     filename = '\\\\?\\' + filename
        with open(filename, 'w') as outfile:
            for item in self.log_data:
                outfile.write("%s\n" % item)
448125
def saveLogs(self, filename) :
		""""""
		f = open(filename, 'wb')
		cPickle.dump(self.logs, f)
		f.close()
134488
def load_history(self) -> List["IterationRecord"]:
        
        if path.isfile(self.history_filename):
            with open(self.history_filename, "r") as f:
                try:
                    dicts = json.load(f)

                except json.decoder.JSONDecodeError as e:
                    self.log.error(f"Got error \n{e}\n decoding JSON history, overwriting it.\n"
                                   f"Former history available in {self.history_filename}.bak")
                    copyfile(self.history_filename, f"{self.history_filename}.bak")
                    return []

                history: List[IterationRecord] = []
                for hdict_pre in dicts:

                    if "_type" in hdict_pre and hdict_pre["_type"] == IterationRecord.__name__:
                        # repair any corrupted entries
                        hdict = _repair(hdict_pre)
                        record = IterationRecord.from_dict(hdict)
                        history.append(record)

                    # Be sure to handle legacy tweetrecord-only histories.
                    # Assume anything without our new _type (which should have been there from the
                    # start, whoops) is a legacy history.
                    else:
                        item = IterationRecord()

                        # Lift extra keys up to upper record (if they exist).
                        extra_keys = hdict_pre.pop("extra_keys", {})
                        item.extra_keys = extra_keys

                        hdict_obj = TweetRecord.from_dict(hdict_pre)

                        # Lift timestamp up to upper record.
                        item.timestamp = hdict_obj.timestamp

                        item.output_records["birdsite"] = hdict_obj

                        history.append(item)

                self.log.debug(f"Loaded history:\n {history}")

                return history

        else:
            return []
508861
def serve_forever(self, banner=None):
        
        if hasattr(readline, "read_history_file"):
            try:
                readline.read_history_file(self.histfile)
            except IOError:
                pass
            atexit.register(self._save_history)
        super(Shell, self).serve_forever(banner)
873082
private static String getHistoryFileUrl(RetireJobInfo info) {
    String historyFile = info.getHistoryFile();
    String historyFileUrl = null;
    if (historyFile != null && !historyFile.equals("")) {
      try {
        historyFileUrl = URLEncoder.encode(info.getHistoryFile(), "UTF-8");
      } catch (UnsupportedEncodingException e) {
        LOG.warn("Can't create history url ", e);
      }
    }
    return historyFileUrl;
  }
1233140
def history_file(self, location=None):
        
        if location:
            # Hardcoded location passed from the config file.
            if os.path.exists(location):
                return location
            else:
                logger.warn("The specified history file %s doesn't exist",
                            location)
        filenames = []
        for base in ['CHANGES', 'HISTORY', 'CHANGELOG']:
            filenames.append(base)
            for extension in ['rst', 'txt', 'markdown']:
                filenames.append('.'.join([base, extension]))
        history = self.filefind(filenames)
        if history:
            return history
1157254
def save_files(self):
        """"""
        while True:
            try:
                os.mkdir(self.output_name)
            except Exception as e:
                self.output_name = raw_input("This directory already exists - please enter a new name:")
            else:
                break
        self.workdir = os.getcwd()
        os.chdir(self.workdir+"/"+self.output_name)
800180
def _put_to_history(self, command_script):
        """"""
        history_file_name = self._get_history_file_name()
        if os.path.isfile(history_file_name):
            with open(history_file_name, 'a') as history:
                entry = self._get_history_line(command_script)
                if six.PY2:
                    history.write(entry.encode('utf-8'))
                else:
                    history.write(entry)
1267684
def write_history_file(self, filename = None): 
        '''
        if filename is None:
            filename = self.history_filename
        fp = open(filename, u'wb')
        for line in self.history[-self.history_length:]:
            fp.write(ensure_str(line.get_line_text()))
            fp.write(u'\n')
        fp.close()
213567
def go_to_history(self, index):
        
        if index < len(self._working_lines):
            self.working_index = index
            self.cursor_position = len(self.text)
798247
def set_history_file(self, path):
        """"""
        if path:
            self.history = prompt_toolkit.history.FileHistory(fixpath(path))
        else:
            self.history = prompt_toolkit.history.InMemoryHistory()
1244400
def namedb_history_save( cur, opcode, history_id, creator_address, value_hash, block_id, vtxindex, txid, accepted_rec, history_snapshot=False ):
    

    assert 'op' in accepted_rec, "Malformed record at ({},{}): missing op".format(block_id, accepted_rec['vtxindex'])
    
    op = accepted_rec['op']
   
    record_data = op_canonicalize(opcode, accepted_rec)
    record_txt = json.dumps(record_data, sort_keys=True)

    history_insert = {
        "txid": txid,
        "history_id": history_id,
        "creator_address": creator_address,
        "block_id": block_id,
        "vtxindex": vtxindex,
        "op": op,
        "opcode": opcode,
        "history_data": record_txt,
        'value_hash': value_hash
    }

    try:
        query, values = namedb_insert_prepare( cur, history_insert, "history" )
    except Exception, e:
        log.exception(e)
        log.error("FATAL: failed to append history record for '%s' at (%s, %s)" % (history_id, block_id, vtxindex))
        os.abort()

    namedb_query_execute( cur, query, values )
    return True