Django: How to find the url/path you’re into, in a template loaded by a generic view

0

In a Django project, I have a template that is used by two urls, which is quite common (generic views, using ‘create_object’ and ‘update_object’). The problem is that I had to add a supplementary menu just when the template is loaded from the ‘update’ generic view, and not from the ‘create’ generic view.

Making the difference between the two urls calls at the template level is a problem because it’s managed by generic views, so the same template is used.

Anyways, there are several possibilities:

In urls.py, use the ‘template_name’ variable, where you can speficy a specific template for this url(). That is instead of using the default <model>_form.html.
What I don’t like in this situation, is that I will have two nearly similar templates, just for an added menu. Not cool. Another problem is that I use a loop to create all my urls. So if I add a special template, I’ll add it to ALL my models :-(.

Another solution, is to find a way to use a variable in the template that would be different wether the template has been loaded by update_object or create_object.

In our urlpatterns in urls.py, we can use the ‘extra_context‘ variable (takes a dictionnary as parameter). It is correctly managed, even when using generic views. So, you’ll have :

url(r'foo/ajouter/$', 'django.views.generic.create_update.create_object',  
		dict(form_class=modelForm,
                extra_context={'usage':'create'},
                name='foo_create',))
 
url(r'foo/%s/(?P<object_id>\d+)/modifier/$',
                'django.views.generic.create_update.update_object',
		dict(form_class=modelForm,
                extra_context={'usage':'modify'},
                name='foo_update'))

We can also use, in urls.py, the ‘context_processors’ variable. For more information about the context processors, have a look at this tutorial. The goal is to add ‘django.core.context_processors.request’, like this:

from django.core.context_processors import request

and in the url(), add context_processors:

url(r'foo/ajouter/$', 'django.views.generic.create_update.create_object',  
		dict(form_class=modelForm,
		context_processors=[request,]),
                name='foo_create',))

The last possiblity is a more global solution. It’s like the context_processors usage above, but added into every templates automatically.
To do this, you’ll have to edit the list of Template Processors in your settings.py file. That list is run each time a template is loaded, and allows one to add any variable to the template automatically. By default (on Django 1.0.x) this list is commented out, so it has by default the list:

("django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media")

You’ll have to uncomment it, and add ‘django.core.context_processors.request’. By doing this, you get the variable ‘request.path’ available in your template.

Finally, you’ll be able to test your variable with {% ifequal %} and display your conditional elements.

calcubetimer moved to Google Code

2

Calcubetimer’s website doesn’t seem to work anymore :-( Fortunately, gnehzr has moved the code to Google Code.

Asterisk cirpack problem with Free and freephonie.net

0

If you configured your Asterisk/FreeSWITCH server to talk to your freephonie.net (french Free ISP provider), you’ll see in the logs the following warning message:
[Feb 12 09:29:06] WARNING[9228]: chan_sip.c:6624 determine_firstline_parts: Bad request protocol Packet

This is not really a problem, but an annoyance, as it fills up your logs. This is a known problem for more than years, but has never been corrected (neither by Asterisk nor by Cirpack devs). The usual correction was to add the following line to your startup scripts (/etc/rc.local on Debian for example):
iptables -A INPUT -p udp -m udp --dport 5060 -m string --string "Cirpack KeepAlive Packet" -j DROP

But the syntax has changed in iptables, and you’ll get the error:
iptables v1.3.6: STRING match: You must specify `--algo'

so, just add one of the 2 available algorithms (bm and kmp):
iptables -A INPUT -p udp -m udp --dport 5060 -m string --string "Cirpack KeepAlive Packet" --algo bm -j DROP

Easy chess games for kids (mate in one)

11

UPDATE: You can get a much better revised version of the PDF now, with coordinates, in this newer post.

In my journey to teach chess to Ido, an easy (I thought) job was to generate diagrams where he has to find mate in a fixed number of turns. Starting with mate in one.
It appeared that making diagrams is an easy task, as there are many programs (Linux and Windows) that permit this.
On Linux, the best I could find is scid. That’s cool as I use it to maintain my databases of games. Even cooler, is that scid development has just restarted (stopped around 2004!), with the help of Pascal Georges. Using scid (I’m using the 3.7devel2009 version) I can export games to HTML or even to LaTeX files.

At first I thought I’d create the endings myself, for example, using online diagrams generators or using Wikipedia/MediaWiki’s templates, but it was not so easy, so I thought about making a program to generate them.
Generating one from scratch would take me time I really don’t have, and there are just two python modules that give high-level functions to chess.
So I started looking for projects similar to mine, that include games with mate in one. I found a small database of mate in one on my favorite chess website, in the download section: a Chessbase datafile with 1171 mate in one studies! So cool.

Well, It was really a pain to convert that Chessbase (.cbv) file, as the only program able to convert to PGN is running on Windows (at least it’s free). You just have to follow the instructions from this thread.
After getting a nice PGN file, just open it with scid, go to “Tools”, then select “Write the filter”, and choose LaTeX. You’ll get a TeX file. Use you favorite TeX generator (Live TeX seems to be the one today), like this for example, to generate directly a PDF file:

1
2
cat mat_temp.tex |grep -v "\\\\$" &gt; mate_in_one.tex
latex --output-format=pdf mate_in_one.tex

(Yes I had to cleanup a bit the file before generating the .pdf)

The result is here, 196 pages of tests (6 one each page) if you don’t want to fight with the missing TeX modules (you’ll need chess12.sty) and get a nice result.

I’m sure many people search for this kind of file, so I’m pretty happy to help other parents/coaches.

White mate in one

White mate in one

Edit: I added a PDF version without the solution included.

Ido’s chess Journey: How to teach chess to a 3 year old kid

1

How to teach chess to a 3 year old kid? That’s a good question. I wanted to teach Ido chess for a long time, but each time I tried, he lost focus after 2 minutes, even just for teaching him just rook movements.
I decided I needed to plan it a little more, make it much more fun, and “embed” it in mini-games. It seems to work much better now, but that’s maybe because he matured a lot.

Here are some ideas (some not yet implemented):

  • Using a DIY plastified chess board, allows me to show/play different positions really fast, anywhere.
  • Colorize squares where a piece is allowed to go :

    Ido colored in the squares where the bishop is allowed to go

  • Pawn race games (no en-passant rule yet).
  • Really small games (must not go over 5 minutes) with reduced chess set (for example Queen and 3 pawns vs Knight, bishop and 3 pawns).
  • Checkmate in one, using DiagTransfer program to draw series of chess diagrams. This program works only on Windows, but it works fine with Wine.

    Ido found the mate in 1, for white

    For quick single diagrams, I found wbeditor, an online javascript diagram generator.

There’s a thread (french) about experience from different teachers, giving really good advices.
Most notably, Véronique Houck who has 15 years of experience of teaching chess to kindergarten/maternelle children. She wrote two books (in french). One is named Bibou & le monde des échecs, and the other one Le jeu d’échecs au cycle2. It’s not so easy to find, but using Google, you can find shows many links.

I’ve not yet read them. I’ll make a review when I get them.

Python snippet to get Mediawiki/Wikipedia Recent Changes externally

0

Mediawiki allows one to send Recent Changes (RC) to a UDP port.
The ip address is defined by the variable wgRC2UDPAddress, and the port by the variable wgRC2UDPPort. It’s a really good idea that it’s a UDP transfer, since there is no need for any ACK, so Mediawiki doesn’t block if there is nothing listening on that port.

These parameters must be set in the LocalSettings.php file, like this, for example.

$wgRC2UDPAddress = '127.0.0.1';
$wgRC2UDPPort = 9390;

I wrote a really simple python program (more a proof of concept) that receives the data, cleans it, and then prints it to stdout :

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# vim:syntax=python:sw=4:ts=4:expandtab
import SocketServer
import re

HOST,PORT = '', 9390

class MyUDPHandler(SocketServer.BaseRequestHandler):
def handle(self):
print re.sub(r'\x03\d{0,2}', '', self.request[0])

if __name__ == '__main__':
server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
server.serve_forever()

I plan to make it into a complete project that will send the data/notifications using Jabber(XMPP).

How to dial a number using Asterisk and Python

2

I didn’t find any example in Python on how to Dial a number from an Asterisk server and link it to another channel. So here’s a quick code to do it. You just need to have a manager defined in your /etc/asterisk/manager.conf defined.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import socket
 
HOST="192.168.1.116"
PORT=5038
 
p = """Action: login
Events: off
Username: %(username)s
Secret: %(password)s
 
Action: originate
Channel: SIP/%(local_user)s
WaitTime: 60
CallerId: 600
Exten: %(phone_to_dial)s
Context: default
Priority: 1
 
Action: Logoff
"""
def click_to_call(phone_to_dial, username, password, local_user):
    pattern = p % {
            'phone_to_dial': phone_to_dial,
            'username': username,
            'password': password,
            'local_user': local_user}
 
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))
 
    data = s.recv(1024)
    for l in pattern.split('\n'):
        print "Sending>", l
        s.send(l+'\r\n')
        if l == "":
            data = s.recv(1024)
            print data
    data = s.recv(1024)
    s.close()
 
if __name__ == '__main__':
    click_to_call(phone_to_dial='123456789',
                  username='manager_login', password='yourpass',
                  local_user='600')

Synchronization methods of a file with Puppet

0

Usually, to synchronize a file with remote hosts, using puppet, one would use the following pattern:

file { "/etc/init.d/pvfs2-server":
owner => root, group => root,
mode => 755,
source => "puppet:///files/pvfs2-server"
}

(using “source” to copy data as-is, and using “template(“filename”) to use a template structure as data).

Or, if one wishes to directly set the content of the target file:

file { "/etc/init.d/pvfs2-server":
owner => root, group => root,
mode => 755,
source => "puppet:///files/pvfs2-server"
}

Please note that on the first line, for example ‘file { “/etc/mpd.conf”:’), the “/etc/mpd.conf” is a merge of two functionalities/concepts: Usually, the syntax is clear and simple:

file { mon_fichier_mpd_conf:
path => "/etc/mpd.conf",
[...]
}

The first line is about the resource description. Its goal is to be able to reference to it a little later from another resources (Notify[], etc.). By putting directly the file path and name (I think it’s identified as a filename and not as a description because there are quotes, or maybe it’s because it begins with a slash?) you mege the “path” attribute with its description.
On the other end, we’ll not be able to reference to it later, if you need to.

You may also need to synchronize a file that is not present in the repository (puppet:///files/*). That usually happens, for example, when that file is regenerated by an external program or an external action (like /etc/passwd).

file {"/etc/passwd":
owner => root, group => root, mode => 644,
content => file("/etc/passwd")
}

How to automatically run a script after inserting a USB device on Ubuntu?

3

Here’s the setup: you have a computer which has a SD port (small memory cards, mostly used in cameras, phones, etc.). You want to get all of your photos from that card automatically as soon as you insert your card (may be a USB key as well), that is, run a script which will search for all of your photos, and copy them to a local directory.

(more…)

Go to Top