Latest 10 wiki articles:

Factor programming

Posted on 13.11.2008 at 11hours 58 minutes with the tags : Factor, Editor,

I've just started studying Factor programming language, here are a few of my notes so far.

Table of contents:

Setting-up your editor

I'll be using e-texteditor, because Factor comes with an included TextMate bundle. But be aware that there are unsupported actions under Windows inside the menu.

I've made a special etexteditor.factor file for factor, you'll find it here.

You'll have to create a file ~/.factor-rc. Windows explorer can't create a file that starts with a . , so this little python script will handle the task :

#!/usr/bin/env python
# -*- coding: utf-8 -*-

conf = """USING: namespaces editors.etexteditor ;"""

f = open('.factor-rc','w')
f.write(conf)
f.close()

Put this in your C:\Documents and Settings\user-name directory and run it once, it will then create a .factor-rc.

Now, supposed you have a vocabulary inside work/palindrome and a word palindrome?, just type the following to edit your word definition:

USE: palindrome
\ palindrome? edit

e-texteditor will then be called by Factor, you must see something like this :

etexteditor

Note : I have a problem when editing a word, _e opens the file it is in but also another one called "-n9*" : I really don't know what's that.


Last time modified on 13.11.2008 at 19hours 1 minutes

Comments

Be productive with PyQt4

Posted on 25.9.2008 at 21hours 53 minutes with the tags : Python, Pyqt4,

Some PyQt4 tips

I enjoy working with PyQt. Here are several tips I use often to build applications.

Some of them uses the excellent book from Mark Summerfield :

Rapid GUI Programming with Python and Qt

Transforming the ui file

Suppose you've ui_myfile.ui. You want to build an Python executable with it. Open a command line and type in :

pyuic4 -o ui_myfile.py -x ui_myfile.ui

Ressource files

As Mark Summerfield said

Often your program assumes that the application directory is the directory where it is located. But if your program is executed from a different directory, it won't work as expected.

So how to solve this problem ?

  • trying to solve it with Python's os.getcwd() won't work because this returns the directory where we invoked the application, wich as we have noted, may not be the directory where the application actually resides.
  • Nor does QApplication.applicationDirPath() method help, since this returns the path to the Python executable, not to our application itself.
  • Another solution is to put all our ressources (help files, images, etc.) into a single .py module and access them from here.
    This not only solve the path problem (because Python knows how to look for a module to be imported), but also means that instead of having dozens of icons, help files, and similar, some of wich could easily become lost, we have a single module containing them all.

So, what's your choice here ? :)

To produce a ressource module, we must do two things :

  1. create a .qrc file that contains the details of the ressources we want included. It's a simple XML file.
  2. run the pyrcc4 utility which reads a .qrc file and produces a ressource module.

Suppose you have done a resources.qrc file, you generate a ressources module (here qrc_resources_rc.py ) by :

pyrcc4 -o qrc_resources_rc.py resources.qrc

Make a new custom class to use your generated file

Suppose you've generated a ui_myfile.py file , create a main.py file with the following contents :

import sys
from PyQt4 import QtGui, QtCore
from ui_myfile import Ui_MainWindow

class MyApp(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = MyApp()
    window.show()
    sys.exit(app.exec_())

Changing the Look & Feel :

Inside main.py, and in the if \name\ == "\main\":, put the following lines to ie use the predefined Cleanlooks style.

QtGui.QApplication.setStyle(QtGui.QStyleFactory.create("Cleanlooks"))
QtGui.QApplication.setPalette(QtGui.QApplication.style().standardPalette())

A little utility

Doing all this is painfull. I've made a little script wich generates a .py file from a given .ui one, then it creates a 'main.py' file with all you need.

Beware, I'm using Python 2.6 new feature (the with statement). Here it is : 'make.py'.

Launch it with :

python make.py myfile.ui

But be aware to launch this script only one time, otherwise the 'main.py' script will be overwritten and you'll lost all of your code !


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os

template = """#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from PyQt4 import QtGui, QtCore
from %(name)s import Ui_MainWindow

class MyApp(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)

        # Setup the ui.
        self.setupUi(self)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    
    ## Look and feel changed to CleanLooks
    QtGui.QApplication.setStyle(QtGui.QStyleFactory.create("Cleanlooks"))
    QtGui.QApplication.setPalette(QtGui.QApplication.style().standardPalette())
    
    window = MyApp()
    window.show()
    sys.exit(app.exec_())"""
    

def main(filename):
    os.system('pyuic4 -o %(name)s.py -x %(name)s.ui'%{'name': filename})
    with open('main.py', 'w') as f:
        f.write(template%{'name': filename})
        
if __name__ == "__main__":
    filename = sys.argv[1]
    main(filename)

Translating signals/slot between C++ and Python

If you read Qt4's doc, you may find some signals like this in C++:

void itemDoubleClicked ( QTableWidgetItem * item )

In PyQt4, you'll have to use the following signal (don't forget the star char !) :

QtCore.SIGNAL("itemDoubleClicked (QTableWidgetItem*)")

Another one, a QComboBox signal:

void currentIndexChanged ( const QString & text )

it has to be translated like this (the string is a constant here, so you'll have to tell it to PyQt):

QtCore.SIGNAL("currentIndexChanged(const QString)")

Mouse handling

Wheel events

You can catch any wheel event by defining a wheelEvent method on your widget, ie :

def wheelEvent(self, event):
    if event.delta() > 0 :
        print "delta positive"
    else:
        print "delta negative"

Fullscreen apps

You can show a widget in fullscreen mode by using the showFullScreen () method of the widget. Note that this apply only to windows. If you have a toolbar, it will be invisible in fullscreen mode.

Here's a sample of a method I've used inside a MainWindow (in wich self.fullScreen = False by default):

class MonAppli(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)
        
        self.fullScreen = False
        QtGui.QShortcut(QtGui.QKeySequence("Ctrl+Shift+W"), self, self.toogleFullScreen )
        
    def toogleFullScreen(self):
        if not self.fullScreen :
            self.showFullScreen()
        else:
            self.showNormal()
            
        self.fullScreen = not (self.fullScreen)

Scintilla

This snippet will show you how to handle QScintilla basically (it prints out all the lexers and the editor methods):

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Basic use of the QScintilla2 widget

Note : name this file "qt4_sci_test.py"
"""

import PyQt4.Qsci
langs = [i for i in dir(PyQt4.Qsci) if i.startswith('QsciLexer')]

for i,l in enumerate(langs):
    print i,l[9:] # we don't need to print "QsciLexer" before each name

import sys
from PyQt4.QtGui import QApplication
from PyQt4 import QtCore, QtGui
from PyQt4.Qsci import QsciScintilla, QsciScintillaBase, QsciLexerPython

if __name__ == "__main__":
    app = QApplication(sys.argv)
    editor = QsciScintilla()

    ## define the font to use
    font = QtGui.QFont()
    font.setFamily("Consolas")
    font.setFixedPitch(True)
    font.setPointSize(12)
    # the font metrics here will help
    # building the margin width later
    fm = QtGui.QFontMetrics(font)

    ## set the default font of the editor
    ## and take the same font for line numbers
    editor.setFont(font)
    editor.setMarginsFont(font)

    ## Line numbers
    # conventionnaly, margin 0 is for line numbers
    editor.setMarginWidth(0, fm.width( "00000" ) + 5)
    editor.setMarginLineNumbers(0, True)

    ## Edge Mode shows a red vetical bar at 80 chars
    editor.setEdgeMode(QsciScintilla.EdgeLine)
    editor.setEdgeColumn(80)
    editor.setEdgeColor(QtGui.QColor("#FF0000"))

    ## Folding visual : we will use boxes
    editor.setFolding(QsciScintilla.BoxedTreeFoldStyle)

    ## Braces matching
    editor.setBraceMatching(QsciScintilla.SloppyBraceMatch)

    ## Editing line color
    editor.setCaretLineVisible(True)
    editor.setCaretLineBackgroundColor(QtGui.QColor("#F5F5DC"))

    ## Margins colors
    # line numbers margin
    editor.setMarginsBackgroundColor(QtGui.QColor("#333333"))
    editor.setMarginsForegroundColor(QtGui.QColor("#CCCCCC"))

    # folding margin colors (foreground,background)
    editor.setFoldMarginColors(QtGui.QColor("#99CC66"),QtGui.QColor("#333300"))

    ## Choose a lexer
    lexer = QsciLexerPython()
    lexer.setDefaultFont(font)
    editor.setLexer(lexer)

    ## Render on screen
    editor.show()

    ## Show this file in the editor
    editor.setText(open("test_sci_qt4.py").read())
    
    # Show all the methods of the editor
    methods = sorted(QsciScintilla.__dict__.keys())
    for m in methods :
        print m

    sys.exit(app.exec_())

... to be continued


Last time modified on 3.11.2008 at 21hours 53 minutes

Comments

windows tips

Posted on 2.7.2008 at 12hours 11 minutes with the tags : Windows,

Add a create new filetype on right-click menu

I needed something today : add a shortcut to my right-clic menu for creating a new Python (or whatever) file.

Inside regedit, find the entry HKEY_CLASSES_ROOT/.py .

  • Right-click on it then add a new key and give it the name ShellNew .
  • Now, inside HKEY_CLASSES_ROOT/.py/ShellNew create a new 'chain' variable, name it NullFile and give it the value Python.

Quit regedit, now you've got your new entry inside the right-click menu.

Another solution maybe to use this Python Cookbook recipe to manipulate the registry contents.

The problem is that your new document will be empty. Using the PowerToys Tweak UI is even easier and you can have your own template : see this page for details.


Last time modified on 2.7.2008 at 12hours 37 minutes

Comments

Projects

Posted on 1.7.2008 at 9hours 34 minutes with the tags : Python, Projects,

geopyx
PyK!

Python

  • GeoPyX : a personnal tool for visualising 2d geometry figures using the PyX package.
  • PyK! was my attempt to setup a text editor using the PyQt4 toolkit; it has some great features like snippets, plugins and so on.
  • TeXBases is a tool to manage and view all the exercises in TeX format I give for my students. Only works on Linux because it uses the GTK bindings to the Poppler libs.
  • Written the TextMate-like snippets features in the UliPad editor.

Others


Last time modified on 19.7.2008 at 22hours 22 minutes

Comments

Lisp page

Posted on 24.6.2008 at 11hours 13 minutes with the tags : Lisp, Scheme,

My Lisp page

Lisp book

There are tons of programming languages, and even if I've choosen Python for my everyday work, I hope to switch one day to Common Lisp.

Common Lisp you can choose your programmming style :

  1. functionnal;
  2. imperative;
  3. object-oriented (one of the most elaborated);

I'll try to add here some of my experiments with it on this page.

The only book I have is Peter Seibel's Practical Common Lisp. It's avaible online, but I really suggest you to buy the original from APress, because they've done a beautiful work.

Citations

"Parentheses? What parentheses? I haven't noticed any parentheses since my first month of Lisp programming. I like to ask people who complain about parentheses in Lisp if they are bothered by all the spaces between words in a newspaper" - Ken Tilton

Alternatives

Clojure maybe the Lisp future.

NewLisp is very interesting : a Lisp-like scripting langage like Python, Ruby and Perl but with macros, and nice features. It's well documented (using the excellent ConTeXt) and very fun to play with.


Last time modified on 13.11.2008 at 13hours 0 minutes

Comments

Python links

Posted on 23.6.2008 at 15hours 43 minutes with the tags : Python,

Docs

The new Python docs are here: Python 2.6 docs

Magazines

There's only one for the moment : Python Magazine

Forum

Tutorials

French

  • The very good page of a French professor in Computer Science : Karczma .
  • My little ShadesOfPy .

English

GUI STUFF

Tkinter

PyQt

PyGTK2

Some tools may help you in writting GTK2 apps :

wxPython

uxPython

Others

  • Albow is a GUI lib based on PyGame.

Text manipulation

DSL (Domain Specific Langage)

Parsing techniques

Best practices

Usefull libs

  • PLib : A namespace package for a number of useful sub-packages and modules.


Last time modified on 3.11.2008 at 22hours 54 minutes

Comments

Haskell page

Posted on 23.6.2008 at 12hours 2 minutes with the tags : Haskell,

Haskell Links

Sites

Tutorials

Editors-IDE

  • An EMacs clone in Haskell : Yi


Last time modified on 23.6.2008 at 18hours 31 minutes

Comments

Compiling Vim with python support on Windows

Posted on 20.6.2008 at 15hours 11 minutes with the tags : Vim, Python, Editor,

Building Vim with Python support on Windows

Vim does not have a native Python 2.6 support on Windows, so you'll have to build it yourself.

The site ShowMeDo gives a nice turorial on the subject.

I'm listing here the important steps :

  1. Install MingW, directly or by another programm (I personnaly installed Qt4.4 on Windows with MingW inside it) ;
  2. Download and Install binaries of GVim on the official Vim site;
  3. Download vim72src.zip on the Vim site;
  4. Unzip it and go to the src dir;
  5. Edit the file Make_ming.mak

The Python section starts at line 130, modify it as follows :

# Python support -- works with the ActiveState python 2.0 release (and others
# too, probably)
#
# uncomment 'PYTHON' to make python-enabled version
# Put the path to the python distro here.  If cross compiling from Linux, you
# will also need to convert the header files to unix instead of dos format:
#   for fil in *.h ; do vim -e -c 'set ff=unix|w|q' $fil
# and also, you will need to make a mingw32 'libpython20.a' to link with:
#   cd $PYTHON/libs
#   pexports python20.dll > python20.def
#   dlltool -d python20.def -l libpython20.a
# on my Linux box, I put the Python stuff here:
#PYTHON=/home/ron/ActivePython-2.0.0-202/src/Core
# on my NT box, it's here:
PYTHON=c:/python26

ifdef PYTHON
ifndef DYNAMIC_PYTHON
DYNAMIC_PYTHON=no
endif

ifndef PYTHON_VER
PYTHON_VER=26
endif

Then, compile with :

mingw32-make -f Make_ming.mak gvim.exe

You just have to replace the old gvim.exe by the new one you've just compiled.

Note: Since this article, Vim 7.2 appeared and the given source file does not work as expected. I had to use the source file from SVN directory to get it work correctly.

Note 2: Compiling with Ruby support gave me a lot of errors, I have to find why.

To test if Python is installed, type the following :

:echo has("python")

This should return 1 (for True).

Setting the fonts

To set the default fonts, you have to modify you vim.rc :

Under Linux, you'll have to write this : set guifont=Consolas\ 12 Under a Windows machine, this is done like this : set guifont=consolas:h12


Last time modified on 13.11.2008 at 12hours 23 minutes

Comments

Atom feeds