Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Saturday, July 09, 2011

Python/Ruby like generators in Vala

Hello,
the post below is copied straight from here.

Here I'll show a cool snippet code making use Vala async functions and iterators for emulating Python/Ruby generators. Creating a generator is as simple as extending the Generator class and implementing the generate() method.

abstract class Generator {
    private bool consumed;
    private G value;
    private SourceFunc callback;

    public Generator () {
        helper ();
    }

    private async void helper () {
        yield generate ();
        consumed = true;
    }

    protected abstract async void generate ();

    protected async void feed (G value) {
        this.value = value;
        this.callback = feed.callback;
        yield;
    }

    public bool next () {
        return !consumed;
    }

    public G get () {
        var result = value;
        callback ();
        return result;
    }

    public Generator<G> iterator () {
        return this;
    }
}

class IntGenerator : Generator<int> {
    protected override async void generate () {
        for (int i=0; i < 10; i++) {
            yield feed (i);
        }
    }
}

void main () {
    var gen = new IntGenerator ();
    foreach (var i in gen) {
        message ("%d", i);
    }
}

You can find the above code snippet here as well.

Wednesday, February 09, 2011

Bluetooth simple one-line device connection pairing with Bluez

Hello,
I've written a simple Python script using the Bluez (version 4.66) stack (thanks to http://shr-project.org/trac/wiki/Using) with this usage:

python connect.py MACADDRESS PIN MOUNTPOINT

Snippet code for connect.py is here. If the device is paired, it will be removed and unmounted.

Disconnection is as easy with:

python disconnect.py MACADDRESS MOUNTPOINT

Snippet code for disconnect.py is here.

Feel free to use the code also for other services, in this case my primary concern was to mount the file system.

Tuesday, February 16, 2010

Secure and Decentralized Chat

Hello,
I'm writing to let you know of the first release of SDChat.
It is a protocol with libraries and programs to create secure IM networks using GPG and RSA.
All the stack is written in Python but the page says it will be rewritten from scratch to provide a C API.

It features a GTK+ interface with many plugins (unfortunately audio and video are being broken due to gstreamer updates) and a simple server for routing. No installation is required.

Wondering if this can be any useful for Iranians.

Monday, December 14, 2009

Lua for Pythoners - Dictionary

Hello,
as promised this is the second post, this time for dictionaries. The most important thing to notice is that tbl[key]=nil means deleting the entry from the table, while in python dict[key]=None is still a valid entry with None value.

Here's the snippet you can launch in a lua interpreter and this is the catalog of python dictionary examples.

Sunday, December 13, 2009

Lua for Pythoners - Lists

Hello,
lately I'm discovering Lua as general purpose language. Many people don't agree with lua being used as a general purpose language, many others (including a newbie like me) think Lua has such a simple syntax and powerful tables to become a full fledged language.
I use a lot of Python, so I start from here: what Python does that Lua can't do almost in the same way? Read the question as it is, don't read "what Python does that Lua can't do", it's different.

This is the first of several post series I'm writing. I'm trying to "translate" python pills in Lua + Penlight

Please consider that many things can be done really better in Lua. As I said, this is a kind of "translation". You will understand that Lua does better than Python in other things that will not be shown because the examples are made in Python.

Here's the snippet, you can run it with a stand-alone Lua interpreter.

If you know better ways of doing things like in Python please comment. Comments like 'Hey, it's inefficient! This is not the way you do things in Lua' are accepted of course but not related to the post.

Errata:
I've had some important feedback thanks to #lua people in IRC:
- Variables in Lua are globally assigned, so at least in functions you must use local
- Using table.insert in loops is slow, better use tbl[#tbl+1] assignment, and even better remember the next free position tbl[next] = element; next = next + 1

Friday, November 27, 2009

Mimaggia, cairo tester

Hello,
From GNOME

I've created a simple pygtk project for testing cairo statements. It includes a sort of terminal where you write statements in a simple language. It features immediate preview of what you write.

Say it's a new format for images.
If you want to test it and see the code, ask me.

Saturday, November 14, 2009

Python and RSA


There are many Python toolkits for crypto, so I hope I've done the best choice (at least for now). This is a simple utility class for managing RSA keys, a sort of wrappera to the m2crypto class.

import M2Crypto
class RSA (object):
def __init__ (self, bits=1024, padding=M2Crypto.RSA.pkcs1_padding, exp=65537):
self.bits = bits
self.padding = padding
self.exp = exp
self.rsa = None

def generate (self):
self.rsa = M2Crypto.RSA.gen_key(
self.bits, self.exp, lambda x: None)

def encrypt (self, s):
c = ""
bytes = self.bits/8-11
for i in range(0, len(s), bytes):
c += self.rsa.public_encrypt (s[i:i+bytes], self.padding)
return c

def sign (self, s, algo="sha1"):
dgst = M2Crypto.EVP.MessageDigest (algo)
dgst.update (s)
return self.rsa.sign (dgst.digest (), algo)

def verify (self, s, sign, algo="sha1"):
dgst = M2Crypto.EVP.MessageDigest (algo)
dgst.update (s)
try:
self.rsa.verify (dgst.digest (), sign, algo)
except:
return False
return True

def decrypt (self, c):
s = ""
bytes = self.bits/8
for i in range(0, len(c), bytes):
s += self.rsa.private_decrypt (c[i:i+bytes], self.padding)
return s
Example usage:

rsa = RSA ()
rsa.generate () # generate key pair
s = "a"*2000 # test data
edata = rsa.encrypt (s)
sign = rsa.sign (s)

ddata = rsa.decrypt (edata)
assert rsa.verify (ddata, sign) == True

Sunday, August 09, 2009

Spadi source code

Hello,
after I've written really a few docs, and cleaned up some stuff, I've published the code of both Spadi and Corraza on gitorious here. In the while, I've added support for floors and closeable views.
Help... help is needed.

Stay tuned.

Thursday, August 06, 2009

Constructing a free ArchiCAD alternative

Hello,
together a couple of university mates we talked about a possible free (as in freedom) ArchiCAD alternative. There are several free CAD out there but none is free for architects/engineers. The project is too big and ambitious, but I wanted to give OpenGL a shot with this excuse to learn something new.

I've started two projects:
  • Corraza, the OpenGL framework for editing 3d objects and exporting the scene graph to ray tracing software... think about a very very very minimal blender but as library
  • Spadi, the GTK+ application that runs on top of Corraza

You can find a video here to see what it can do now, after a week of development.
There's no code published at the moment, contact me if you would like to join the development.

Stay tuned.

Tuesday, July 21, 2009

Aruanne, pdf reporting framework

Hello,
a while ago I've been talking about pango cairo and how to generate pdf with a couple of tables.
In the meantime I've worked on it, improving and enhancing new kinds of elements. This has lead to the creation of a small project, a library providing a simple framework for generating mostly PDF reports (I haven't tried to generate SVG or something else yet).

After a couple of release requests, I've found finally the time to publish a sort of working code.

Here's the git repository and here you can download the snapshot tarball.

Any patches welcome.

Saturday, January 10, 2009

FreeSpeak 0.3.0 has been released

FreeSpeak is a free (as in freedom, developed and released under the terms of GPL) frontend to online translator engines (such as Google, Yahoo, etc.). It is written in Python, it uses the GTK toolkit and some GNOME infrastructure features.

This is a major enhancemenfts release.



Overview of Changes from FreeSpeak 0.2.0 to FreeSpeak 0.3.0
===========================================================

* Project is now hosted at BerliOS.de: http://freespeak.berlios.de

* Support for cancellating operations has been added

* Translation suggestions (open-tran) have been added

* A menubar has been added and the toolbar has been cleaned up

* The behavior of language/translation selection has been fixed and improved

* GNOME documentation has been added

* Dependencies in the configuration have been cleaned up

* Support for global keybindings has been added through python-xlib

* An introduction widget for the main window has been created

Sunday, December 21, 2008

Global keybinding on X

Hello,
lately I've been looking for a way to create a desktop-wide keybinding for FreeSpeak.
I first looked into Tomboy and Deskbar source codes but the egg was too huge to be adopted, and it would have brought C dependency which isn't always nice for a Python project.
Then fargiolas pointed me to a blog post where I could find about gnome keybindings owned by gnome control center. Well that was only a mirage as it doesn't really grab the key but it's only a visual entry in the keyboard shortcuts preferences.
After a few days I've finally found a not-so-hackish solution in about one hundred lines of Python code.

Here is the snippet (download), only using Xlib and GTK+ Python bindings.

Sample usage:

def callback (keybinding):
print 'Callback!'
gtk.main_quit ()

gtk.gdk.threads_init ()
keybinding = GlobalKeyBinding ("/apps/appdir", "key_binding")
keybinding.connect ('activate', callback)
keybinding.grab ()
keybinding.start ()
gtk.main ()


The only problem is that it doesn't make use of GDK filters because PyGTK doesn't provide such function wrappers and there's no GDK-to-Xlib mapping available.
But yes, it works very good.

Sunday, November 30, 2008

FreeSpeak gains translation suggestions

Hello,
it hasn't been a long time since FreeSpeak 0.2.0 has been released. One of the TODOs for the next release was to support open-tran, and more over translation suggestions for development.
This is a screenshot of what's been included in the repository today:
From GNOME
FreeSpeak is a GNOME frontend to online translator engines.

Friday, November 28, 2008

FreeSpeak 0.2.0 has been released

Hello,
after some work in these weeks now I have released a new version of FreeSpeak.

FreeSpeak is a free (as in freedom, developed and released under the terms of GPL) frontend to online translator engines (such as Google, Yahoo, etc.). It is written in Python, it uses the GTK toolkit and some GNOME infrastructure features



.
It's been rewritten almost from scratch so I think there's no need to post release notes here. Anyway you can always read what changed from the old version released a couple of years ago here.

Notice that the project homepage has been changed. The project has now moved to BerliOS.de.

Sunday, November 23, 2008

Replace GTK+ with Clutter for fun

Hello,
lately I was having fun with Clutter and Python. I've started by creating some Gtk-like widgets (such as GtkWindow, GtkBox, and GtkButton) in Clutter.
Well, this is the result... it's a simple example of a very poor toolkit, but it works:

Try it, it's only one .py file source code

Sunday, November 16, 2008

Single app instances, Python and DBus

Hello,
I'm working on FreeSpeak lately and I needed to run the application once per session, as it's got a trayicon and a notebook (maybe windows with an applet is better?)
I decided to use DBus for making the application run only a single instance; when you try to open it again it won't start another process, instead it will use the already running one.

This is how I would create a generic single app instance with dbus-python:
import dbus
import dbus.bus
import dbus.service
import dbus.mainloop.glib
import gobject

class Application (dbus.service.Object):
def __init__ (self, bus, path, name):
dbus.service.Object.__init__ (self, bus, path, name)
self.loop = gobject.MainLoop ()

@dbus.service.method ("org.domain.YourApplication",
in_signature='a{sv}', out_signature='')
def start (self, options={}):
if self.loop.is_running ():
print 'instance already running'
else:
self.loop.run ()

dbus.mainloop.glib.DBusGMainLoop (set_as_default=True)
bus = dbus.SessionBus ()
request = bus.request_name ("org.domain.YourApplication", dbus.bus.NAME_FLAG_DO_NOT_QUEUE)
if request != dbus.bus.REQUEST_NAME_REPLY_EXISTS:
app = Application (bus, '/', "org.domain.YourApplication")
else:
object = bus.get_object ("org.domain.YourApplication", "/")
app = dbus.Interface (object, "org.domain.YourApplication")

# Get your options from the command line, e.g. with OptionParser
options = {'option1': 'value1'}
app.start (options)
How it works?
  1. Setup the mainloop for dbus
  2. Request a session bus name, so that other applications (in our case another instance of the same application) can connect to it
  3. Create a new instance at path / if the bus name doesn't exist (so we are the primary owner). If it exists, then obtain the object from dbus and call the method on the remote Application object using the known interface.
  4. The Application.start method checks if it's already running then decide what to do in both situations.
Creating a GTK+ application this way is really easy. It only needs to use the GTK+ mainloop.
Let's suppose we want to present() the GtkWindow when the user tries to open another instance of the application:
import dbus
import dbus.bus
import dbus.service
import dbus.mainloop.glib
import gobject
import gtk
import gtk.gdk
import time

class Application (dbus.service.Object):
def __init__ (self, bus, path, name):
dbus.service.Object.__init__ (self, bus, path, name)
self.running = False
self.main_window = gtk.Window ()
self.main_window.show_all ()

@dbus.service.method ("org.domain.YourApplication",
in_signature='', out_signature='b')
def is_running (self):
return self.running

@dbus.service.method ("org.domain.YourApplication",
in_signature='a{sv}i', out_signature='')
def start (self, options, timestamp):
if self.is_running ():
self.main_window.present_with_time (timestamp)
else:
self.running = True
gtk.main ()
self.running = False

dbus.mainloop.glib.DBusGMainLoop (set_as_default=True)
bus = dbus.SessionBus ()
request = bus.request_name ("org.domain.YourApplication", dbus.bus.NAME_FLAG_DO_NOT_QUEUE)
if request != dbus.bus.REQUEST_NAME_REPLY_EXISTS:
app = Application (bus, '/', "org.domain.YourApplication")
else:
object = bus.get_object ("org.domain.YourApplication", "/")
app = dbus.Interface (object, "org.domain.YourApplication")

# Get your options from the command line, e.g. with OptionParser
options = {'option1': 'value1'}
app.start (options, int (time.time ()))
if app.is_running ():
gtk.gdk.notify_startup_complete ()
How it works?

Let's say we're running the Application for the first time, the loop begins and when it ends running is set to False, so gtk.gdk.notify_startup_complete() won't be called. Instead, if the application is already running, start() will be called on the remote object running the loop. The method then returns immediately so gtk.gdk.notify_startup_complete() will be called.
If you don't notify to the launcher that the startup is complete... guess what happens to your mouse and to your taskbar panel...

If the loop is running, the window is presented to the user with a little delay. If you don't use any timestamp, the UI interaction won't let the window have the time to be presented.

Of course, you can use DBus for many more things, like both setting options from the command line, as explained in the above code, and let other applications communicate with yours and viceversa.
Nowadays almost all systems use DBus, so it won't be a pain to add such dependency. In my opinion, it would be much more painful to use lock files, FIFO, unix sockets or whatever. FreeSpeak used such old technologies and it was a very poor emulation of what DBus already offers.