Thursday, 9 October 2014

Stopping a run-time plot via key-press using threads in pylab

You can use threads to tell a python script to end a plotting loop:
#!/usr/bin/env python
from pylab import *
import threading
import time

# Replot some data each time is called
def replot(datafile, title) :

    # Control errors (mainly "file not found")
    try :

        # read the data file 
        data=loadtxt(datafile)

        # open figure (in case create it)
        fig = figure(title)

        # clear canvas    
        fig.clear()
        # plot data
        plot(data.T)
        # redraw
        fig.canvas.draw()

    except :
        pass


# A thread dedicated to read the keyboard
class KeyPressThread(threading.Thread):
    def run(self):
        global end_thread;

        # wait for keypress
        raw_input()

        lock = threading.Lock()
        lock.acquire()

        # if a key is pressed switch 
        # the end flag to true
        end_thread = True;

        lock.release()


if __name == "__main__" :

    ion()
    close('all')

    # init the end flag
    end_thread = False

    # Start the dedicated thread
    k = KeyPressThread()
    k.start()

    # start the replot loop
    while(not end_thread) :
        replot("my_data","my_plot")

    # link the thread to main thread
    k.join()

Thursday, 2 October 2014

Reformatting latex code with Vim

Vim can be used as a very  nice latex IDE with the help of the vim-latex plugin. Unfortunatelly format indenting the selected code (SHIFT+=) does not include latex comments (using the '%' delimiter).
This issue can be solved by manually replacing the delimiter with a neutral string before formatting and then restoring the original delimiter.

The code shown below does the job. Any delimiter can be given as the argument of the IndentComments function so that  it can be used with any type of code. The last  line creates a map for calling the function set on latex by pressing '§'.

Just add it to your  ~/.vimrc configuration file.



" Solve the issue of formatting comments 
" @param delimiter  the comment delimiter for the chosen filetype"
function! IndentComments(delimiter) range

    " set a temporary substitute for the delimiter 
    let s:tmp_delimiter = 'delimiter>>>>'

    " replace the delimiter with the substitute
    exec a:firstline.','.a:lastline.' '.'s/'.a:delimiter.'/'.s:tmp_delimiter.'/'

    " reformat all lines in the range
    exec a:firstline.','.a:lastline.' '.'normal! =='

    " put back the original delimiter
    exec a:firstline.','.a:lastline.' '.'s/'.s:tmp_delimiter.'/'.a:delimiter.'/'

endfunction

" mapping '§' to reformat selected code in latex
:map <silent> § :call IndentComments("%") <CR>