Feeds:
Posts
Comments

Archive for the ‘Python’ Category

Hi there everyone.
Sorry for the long delay on posts and updates, lots of stuff happening.

So, CairoPlot now has a Mailing List as suggested by Yang. It’s actually a GoogleGroup named CairoPlot. Subscription is now open for anyone who’d like to discuss, question or suggest new features.

So… Join now!

Read Full Post »

CairoPlot 1.1

CairoPlot is on GitHub!

CairoPlot now has a Mailing List! For more information, refer to: this post.

v1.1 is out!!

CairoPlot is an API written in Python and uses PyCairo to plot 6 kinds of graphics.
Lots of changes happened since last post, CairoPlot now has a Logo, it’s not just me anymore, we have an all new repository and lots of new functions and options. Read the rest of the post to see all the changes.

LOGO

As you all must’ve seen on the beginning of this text, CairoPlot now has a logo! Actually I did two but I ended up choosing this one. What do you guys think?

CONTRIBUTOR

It’s not just me anymore! I’m happy to say that this release had GREAT help from João S. O. Bueno. It was his idea to change the code into object oriented style which turned out to be a great option for the project.

NEW REPOSITORY

I’d like to apologize to everyone who’s been using v1.0 since June. Many changes happened and no one even knew they were there. By the time the repositories where changed, João had just started helping the project and lots of things were incomplete. After that, one change lead to the other and the only stable release came out now. Again, I’m sorry but I believe you all will be pleased by the changes.
To visit the new repository, just hit CairoPlot Launchpad.

HOW TO DOWNLOAD

CairoPlot is on GitHub!

HOW TO HELP

I believe CairoPlot can grow a lot more, so if you think you can help, please contact me at alf.rodrigo@gmail.com.

NEWS

Now for the exciting ChangeLog.
All the old functions are still supported with some little but important changes.

overall changes

Every chart now has an associated class and a function.
The functions where kept to maintain backward compatibility and allow for easy use of the api.
The classes, however, provide much more customization as access to the cairo context or its surface.
All functions still have the background parameter, but now it supports colors (in tuple form, red = (255, 0, 0)) and Cairo Linear Gradients. The None option is still present and will generate the gray to white gradient of the previous version.

more output options

CairoPlot now outputs images on the following formats: pdf, ps, png and svg thanks to João.

dot_line_plot

Dot Line Plot kept most of its functions but got a little more customizable.

dot_line_plot (name,
               data,
               width,
               height,
               background = None,
               border = 0,
               axis = False,
               grid = False,
               dots = False,
               h_labels = None,
               v_labels = None,
               h_bounds = None,
               v_bounds = None)

dots – new parameter added to determine whether or not the dots are needed;
h_legend and v_legend – got renamed to h_labels and v_labels;
Note: As this function’s been present since the last version, please refer to the latest post for more detailed information.

pie_plot

The old Pizza Plot got renamed and revamped into the all new Pie Plot

pie_plot(name,
           data,
           width,
           height,
           background = None,
           gradient = False,
           shadows = False,
           colors = None)

gradient – Whether or not the slices are painted with gradient colors;
shadows – Now, it’s possible to draw a shadow behind the pie;
colors – And the user can pass a pre-selected list of colors for the slices;
Note: As this function’s been present since the last version, please refer to the latest post for more detailed information.

gantt_chart

No cosmetic changes on this one, but as the rest of the api, it got refactored on OO and the overall changes also apply.

gantt_chart(name,
            pieces,
            width,
            height,
            h_labels,
            v_labels,
            colors)

h_legend and v_legend – got renamed to h_labels and v_labels;
Note: As this function’s been present since the last version, please refer to the latest post for more detailed information.

donut_plot

Used to plot donut graphics.

donu_plot(name,
                data,
                width,
                height,
                background = None,
                gradient = False,
                shadows = False,
                colors = None,
                inner_radius = -1)

name – Name of the desired output file;
data – The list, list of lists or dictionary holding the data to be plotted;
width, height – Dimensions of the output image;
background – A 3 element tuple representing the rgb color expected for the background or a new cairo linear gradient. If left None, a gray to white gradient will be generated;
gradient – Whether or not the slices are painted with gradient colors;
shadows – It’s possible to draw a shadow behind the donut;
colors – Pre-selected list of colors for the slices;
inner_radius – The radius of the donut’s inner circle;

Example of use:

teste_data = {"carl" : 123, "fawn" : 489, "susan" : 890 , "lavon" : 235}
CairoPlot.donut_plot("donut_teste.png", teste_data, 500, 500)

Result:

function_plot

Used to plot function graphics.

function_plot (name,
                    data,
                    width,
                    height,
                    background = None,
                    border = 0,
                    axis = False,
                    grid = False,
                    dots = False,
                    h_labels = None,
                    v_labels = None,
                    h_bounds = None,
                    v_bounds = None,
                    step = 1,
                    discrete = False)

name – Name of the desired output file.;
data – The function to be plotted;
width, height – Dimensions of the output image;
background – A 3 element tuple representing the rgb color expected for the background or a new cairo linear gradient. If left None, a gray to white gradient will be generated;
border – Distance in pixels of a square border into which the graphics will be drawn;
axis – Whether or not the axis are to be drawn;
grid – Whether or not the grids is to be drawn;
dots – new parameter added to determine whether or not the dots are needed;
h_labels, v_labels – lists of strings containing the horizontal and vertical labels for the axis;
h_bounds, v_bounds – tuples containing the lower and upper value bounds for the data to be plotted;
step – the horizontal distance from one point to the other. The smaller, the smoother the curve will be;
discrete – whether or not the function should be plotted in discrete format.

Example of use:

data = lambda x : x**2
CairoPlot.function_plot('function_teste.png', data, 400, 300, grid = True, h_bounds=(-10,10), step = 0.1)

Result:

bar_plot

Used to plot bar graphics.

bar_plot (name,
              data,
              width,
              height,
              background = None,
              border = 0,
              axis = False,
              grid = False,
              dots = False,
              h_labels = None,
              v_labels = None,
              h_bounds = None,
              v_bounds = None,
              step = 1,
              discrete = False)

name – Name of the desired output file.;
data – The function to be plotted;
width, height – Dimensions of the output image;
background – A 3 element tuple representing the rgb color expected for the background or a new cairo linear gradient. If left None, a gray to white gradient will be generated;
border – Distance in pixels of a square border into which the graphics will be drawn;
grid – Whether or not the grids is to be drawn;
rounded_corners – Whether or not the bars should have rounded corners;
three_dimension – Whether or not the bars should be drawn in pseudo 3D;
h_labels, v_labels – lists of strings containing the horizontal and vertical labels for the axis;
h_bounds, v_bounds – tuples containing the lower and upper value bounds for the data to be plotted;
colors – List containing the colors expected for each of the bars.

Examples of use:

data = [3,1,10,2]
CairoPlot.bar_plot ('bar_teste.png', data, 400, 300, border = 20, grid = True, rounded_corners = True)

Result:

REMEMBER!

CairoPlot is on GitHub!

So, I hope you liked it. It’s been a while I’ve been trying to finish this release and I’m very proud of what it has become. Don’t forget to download and test it. In case any bugs surface or if you have any questions or suggestion, don’t be afraid to use the bug tracker or the answers options on the site CairoPlot Launchpad.

Thanks for the interest.

Read Full Post »

A brincadeira toda começou depois que me perguntaram como manipular o mouse no Xorg. Uma rápida pesquisada na documentação do python-xlib e encontrei coisas interessantes. Por exemplo, como mover o mouse no X?


from Xlib import X, XK, display
import Xlib.ext.xtest

display = display.Display()
Xlib.ext.xtest.fake_input(display, X.MotionNotify, x, y)
display.sync()

E simular um click ?


from Xlib import X, XK, display
import Xlib.ext.xtest

display = display.Display()
Xlib.ext.xtest.fake_input(display, X.ButtonPress, 1) #1 left, 2 middle, 3 right
Xlib.ext.xtest.fake_input(display, X.ButtonRelease, 1)
display.sync()

Ok, já sabemos como manipular o mouse, e com o teclado, como seria?


from Xlib import X, XK, display
import Xlib.ext.xtest

display = display.Display()
Xlib.ext.xtest.fake_input(display, X.KeyPress, key)
Xlib.ext.xtest.fake_input(display, X.KeyRelease, key)
display.sync()

Diante dessa facilidade surgiu uma idéia, eu poderia fazer um software que monitarasse todos os eventos de mouse e teclado, armazenasse isso e reproduzisse posteriormente.

Esse software poderia ser usado para automatizar testes em interfaces gráficas, assim como páginas Web. O XorgRecord poderia ser usado também para ensinar uma pessoa em outro computador como realizar determinada tarefa. No lugar de assistir um screencast, o usuário baixaria um simples arquivo txt que faria com que seu computador reproduzisse a aula, sem consumir tanta banda ou demorar quanto baixar um vídeo e com o benefício de todas as atividades da aula ficarem gravadas em seu computador. Evidentemente aqui tem uma falha incrível de segurança se mal utilizado.

Outro exemplo seria ensinar alguém a configurar uma impressora apenas enviando um arquivo de reprodução. Além de observar toda a operação necessária, o usuário já teria sua impressora configurada ao fim da aula.

O projeto esta muito simples, os dados são salvos em formato txt limpo, de forma clara e legível, podendo ser reproduzido manualmente caso desejado. Para trafegar na rede uma simples compactação dos arquivos gerados já diminui bastante o seu tamanho.

xorgrecord

O software se integra ao systray do gnome e tem as opções de gravar e reproduzir eventos, assim como salvar e abrir um arquivo de eventos. Ele esta disponível no seguinte link e já pode ser usado pelos interessados. Quem quiser colaborar, comentar ou solicitar algum novo recurso pode entrar em contato.

Read Full Post »

This is not anymore the most recent version of the API. Please refer to the newest post.
CairoPlot now has a Mailing List! For more information, refer to: this post.

So, a while ago, I’ve decided to code a library to plot some information I had.

The idea was to create simple graphics in a way they would be easy to create, beautiful and good to present to people with no or few backgrounds on math and computers.

For the ease one creation I, obviously, used Python :D

And, as I was already a PyCairo enthusiast (that began by the time I read Aventuras no cairo by Marcelo Lira and, as pointed out by him, this other one), I decide to use it to draw my graphics.

On this first version, the CairoPlot library provides 3 functions:

dot_line_plot()

Function to plot graphics using dots and lines as seen below.

dot_line_plot (name,
               data,
               width,
               height,
               background = None,
               border = 0,
               axis = False,
               grid = False,
               h_legend = None,
               v_legend = None,
               h_bounds = None,
               v_bounds = None)

name – Name of the desired output file, no need to input the .svg as it will be added at runtim;
data – The list, list of lists or dictionary holding the data to be plotted;
width, height – Dimensions of the output image;
background – A 3 element tuple representing the rgb color expected for the background. If left None, a gray to white gradient will be generated;
border – Distance in pixels of a square border into which the graphics will be drawn;
axis – Whether or not the axis are to be drawn;
grid – Whether or not the gris is to be drawn;
h_legend, v_legend – lists of strings containing the horizontal and vertical legends for the axis;
h_bounds, v_bounds – tuples containing the lower and upper value bounds for the data to be plotted.

Example of Use

teste_data = [0, 1, 3, 8, 9, 0, 10, 10, 2, 1]
CairoPlot.dot_line_plot('teste', teste_data, 400, 300, axis=True)

Result:

dot_line_plot - Example 01

teste_data_2 = {"john" : [10, 10, 10, 10, 30], "mary" : [0, 0, 3, 5, 15], "philip" : [13, 33, 11, 25, 2]}
teste_h_legend = ["jan/2008", "feb/2008", "mar/2008", "apr/2008", "may/2008"]
CairoPlot.dot_line_plot('teste2', teste_data_2, 400, 300, h_legend = teste_h_legend, axis = True, grid = True)

Result:

dot_line_plot - Example 02

pizza_plot()

Function to plot pizza graphics.

pizza_plot(name,
           data,
           width,
           height,
           background = None)

name – Name of the desired output file, no need to input the .svg as it will be added at runtim;
data – The list, list of lists or dictionary holding the data to be plotted;
width, height – Dimensions of the output image;
background – A 3 element tuple representing the rgb color expected for the background. If left None, a gray to white gradient will be generated;

Example of Use

teste_data = {"john" : 123, "mary" : 489, "philip" : 600 , "suzy" : 235}
CairoPlot.pizza_plot("pizza_teste", teste_data, 500, 500)

Result:

gantt_chart()

Function to create Gantt Charts.

Note: the output for this function was based on the graphic seen on this post from wired.

gantt_chart(name,
            pieces,
            width,
            height,
            h_legend,
            v_legend,
            colors)

name – Name of the desired output file, no need to input the .svg as it will be added at runtim;
pieces – A list defining the spaces to be drawn. The user must pass, for each line, the index of its start and the index of its end. If a line must have two or more spaces, they must be passed inside a list;
width, height – Dimensions of the output image;
h_legend – A list of names for each of the vertical lines;
v_legend – A list of names for each of the horizontal spaces;
colors – List containing the colors expected for each of the horizontal spaces.

Example of Use

pieces = [ (0.5,5.5) , [(0,4),(6,8)] , (5.5,7) , (7,8)]
h_legend = [ 'teste01', 'teste02', 'teste03', 'teste04']
v_legend = [ '0001', '0002', '0003', '0004', '0005', '0006', '0007', '0008', '0009', '0010' ]
colors = [ (1.0, 0.0, 0.0), (1.0, 0.7, 0.0), (1.0, 1.0, 0.0), (0.0, 1.0, 0.0) ]
CairoPlot.gantt_chart('gantt_teste', pieces, 600, 300, h_legend, v_legend, colors)

Result:

So, I think it’s ready for you guys to use. CairoPlot Google Code Project
The support is also open :D, whenever you need, feel free to contact at alf.rodrigo@gmail.com or leave a comment.

Read Full Post »

Frequentemente encontramos na lista do python-brasil novatos perguntando qual a melhor IDE para se programar em Python. São tantas as vezes que isso ocorre que o python-brasil conta, na sua wiki, com uma página para responder somente a essa pergunta. A página esta acessível aqui.

Uma IDE que deve ser em breve adicionada a lista é o Editra. Demos uma breve olhada nessa IDE e gostamos. Ficamos devendo uma análise da mesma. No entanto, o que assusta muitos iniciantes é o fato dos veteranos recomendarem o uso do Vim. Ele realmente assusta as pessoas e, por isso, em cursos de computação é comum que os alunos comecem a programar com o Gedit ou o Kate. Ao longo do curso o panorama vai mudando e são muitos os que se tornam mais habilidosos com o uso do Vim e permanecem nele.

O Vim já conta com várias funcionalidades de interesse dos programadores mas acredito que uma das melhores seja a possibilidade de extendê-lo via plugins. Além de todo o conjunto de recursos já fornecidos pelo Vim, muitos das quais passamos anos e anos sem nem sequer conhecer, muitos plugins de terceiros são realmente úteis.

Uso Vim para programar em Python há algum tempo e hoje encontrei um post que contém tudo que é necessário para a pessoa começar a usar o Vim de forma confortável, contendo todas as funcionalidades encontradas nas grandes IDEs. O post é esse aqui. Um excelente post, dispensa qualquer adição da minha parte.

O único plugin que não foi mencionado pelo autor mas não passou desapercebido pelo leitores é o NERDTree. Seguindo todos os passos e instalando também o NERDTree você terá em mãos uma IDE muito próxima das gráficas, com a vantagem de ser leve :D

Read Full Post »

Note for brazilian readers: this text was already posted as “GEdit completando código Python automaticamente” and we are making it available in English now.

It’s been a while since I’ve started to develop a plugin to make Gedit able of completing python code. After a while, it became clearer that this was a functionality desired by many users and it is also of interest for the group that keeps the project. Actually, I will be posting this to the wiki of plugins of the GEdit.

So, for this to happen, I decided to take a look at the code used on Vim to complete python codes. For my surprise, that code was also written in python and after some reading, I realized that it could be ported to other text editors. One of the reasons I chose GEdit is that it makes the plugin creation process very easy and understandable by new developers (I recommend the article the Python Plugin How, which explains how to develop plugins for this editor). Using Osmo Salomaa Autocomplete words plugin, made this process even easier.

Long story short, what I did was to connect the two parts: the code for Vim auto-complete (authored by Aaron Griffin) and the code for Autocomplete words (authored by Osmo Salomaa). This is, indeed, a good example of the benefits of free software: providing easy ways for me not having to repeat the work of both authors and rendering me able to use both codes to provide a new for another text editor.

During the trip, which came up being more complicated than expected, I lost many files at my old computer, so the work was stopped until I had the guts to start again. The restart was even better: development was faster and the old errors were quickly solved.

The plugin works on Gedit through the shortcut Ctrl+Alt+Space and allows fast code completing for python scripts and python modules are also supported. Basically, it works the same way it did on Vim, apart from some small adjustments I made in the code. Aaron Griffin alerted me that the code contained some small known problems and that would be corrected soon. I will keep myself up to date with Aaron for the plugin not to become outdated.

This is an alpha version which wasn’t by any means put through rough tests yet. That said, I believe it can already be used but, surely, bugs will come up. I am available to assist whoever is interested on the plugin. On the sequence, there are some screenshots demonstrating the use of the plugin. Today, Gedit has a lot of plugins for Python development, which is taking it nearer to becoming Python development environment. But I still use Vim.

The installation of plugin is relatively easy: the user must unpack the archive into the directory gnome2/gedit/plugins of its home, restart gedit and activate plugin in edit – > preferences – > plugins. This plugin will only work with python code. I hope the community can help on the development and that it makes it more and more usable over time.

Auto in completes code real teams.Show doc strings

The plugin of auto complete Python code is avaliable here.

Read Full Post »

Back Again and PyS60

we are sorry

We, the Linil Team, would like to present our humble apologies for this enormous gap on our blog. Work, College and a lot of other aspects intended to get on the way.

That said, we would also like to let you all know: we are back

So getting back to business, let’s talk about PyS60.

As the idea of this post is not to present a full introduction, it would be good if you all got familiarized with the idea by reading this great article the guys at AllAboutSymbian wrote about it.

So, I bought my N73 on june, 2007. My cellphone plan only covers 50 text messages per month, and I usually pass that limit. One of many reasons this happened on the begining was because S60 platform won’t allow you to separate your messages by month. To keep track of that 50 messages, I needed to erase all my sent messages every first day of each month but I kept forgetting about it what made me pay a lot of extra message taxes.

I installed PyS60 on my phone somewhere between September and October last year, but until last week I still haven’t thought about using it to help solve that problem. So a solution came and it was simple (as Alan Kay says: “Simple things should be simple, complex things should be possible”).

The idea is to look through all the sent messages box and put them into a dictionary, using the months as keys and the number of messages sent on it as values as seen below on part 0 of the code.

#part 0
import inbox
from e32db import format_time
i = inbox.Inbox( inbox.ESent )
m = i.sms_messages()
message_by_time = {}
for message in m:
    time_date = format_time(message_time).split(' ')[0]
    month = time_date.split('/')[0]
    message_time = i.time(message)
    year = time_date.split('/')[2]
    if not message_by_time.has_key( (year,month) ):
        message_by_time[(year,month)] = 0
        message_by_time[(year,month)] += 1

The first lines get a list of sent messages (m) and initialize the dictionary I will use. Through the for, all the messages are analyzed and their times are taken and formatted. After that, their years and months are used to create a tuple to index the dictionary and the element associated is incremented. The if test is used to avoid KeyError exceptions and will assign a number to the key if the dictionary doesn’t already has it.

After that, it was all about creating the interface to allow for better user experience. The idea was to provide a menu where the user could see how many messages he sent on the current month and an option to access a list and show how many messages he has sent on all months.

#part 1
k = message_by_time.keys()
k.sort()

#part 2
time_picker_list = []
for x in k:
    a = u"%s/%s" % (x[1],x[0])
    b = u"%s messages sent" % (message_by_time[x])
    time_picker_list.append((a,b))</div>

Part 1 gets the keys of the dictionary (years and months of messages) and sorts them. After that, on part 2, a new list is created to contain pairs of strings (a,b), where ‘a’ stands for strings formatted as yyyy,mm and ‘b’ stands for another string containing the number of messages sent.

#part 3
time_picker = None
def list_handler():
    month_year = k[time_picker.current()]
    appuifw.note(u"You have sent %d messages on %s/%s" % (message_by_time[month_year], month_year[1], month_year[0]), "info")

#part 4
options = [u"This Month", u"Messages by time"]
options_menu = None

#part 5
def handler_options():
    if options_menu.current() == 0 :
        appuifw.note(u"You have sent %d messages this month" % (message_by_time[k[-1]]), "info")</div>
    else:
        global time_picker
        time_picker = appuifw.Listbox(time_picker_list, list_handler)
        appuifw.app.body = time_picker
        appuifw.app.exit_key_handler = exit_picker

#part 6
options_menu = appuifw.Listbox(options, handler_options)

#part 7
def exit_key_handler():
app_lock.signal()
def exit_picker():
    appuifw.app.body = options_menu
    appuifw.app.exit_key_handler = exit_key_handler</div>

#part 8
app_lock = e32.Ao_lock()
appuifw.app.title = u'SentCounter'
appuifw.app.body = options_menu
appuifw.app.exit_key_handler = exit_key_handler
app_lock.wait()

From part 3, the interface begins to be described. This part defines the function that will be called every time the user selects a month on the list of messages sent through all months. On part 4, the initial menu is defined as a list of two options. Part 5 describes the function that will be called whenever the user select one of the initial menu options. Part 6 creates the menu and part 7 defines the exiting functions, first for when the exit key is pressed on the initial screen and then for when the user presses it on the list of messages by month.
Part 8, at last, creates the application, sets its name and exit functions, and displays it on the screen.

Please be aware that this explanation of PyS60 interface is superficial. For a real better understanding of it, you should take a look at the more than helpful. tutorials.

So the code will be posted in a while (as soon as I get home).
Hope you enjoyed :D

Read Full Post »

Older Posts »

Follow

Get every new post delivered to your Inbox.