snippets

Shell : Perfect django .bat dev startup scriptCréez un fichier run.bat qu'il vous suffira de double cliquer pour lancer Django dans une boucle 'infinie'. Faites Ctrl+C pour relancer le serveur si besoin. (uniquement pour le serveur de dev)
@ECHO OFF

SET PORT=9000

:BEGIN
cd %~dp0
c:\python25\python.exe manage.py runserver 192.168.1.31:%PORT%
GOTO BEGIN
 
tags : system, django, bat, windows

Shell : afficher la branche GIT en cours dans votre prompt shell Ceci vous affichera un shell de ce style : ks12344876:~/django/KillerApp(newfeature) $
# a mettre dans  votre .bashrc

parse_git_branch() {
  git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}

export PS1="\h:\w\$(parse_git_branch) $ "
tags : system, bash, git

Python : cross platform library loader helperdrax's answer for loading a named or absolute library on any platform :)
import os, sys, ctypes

# Types reminder:
#!/usr/bin/python
# String  : ctypes.c_char_p
# Integer : ctypes.c_int
# Long    : c_ulonglong

def loadbinlib(libname="", libpath=""):
   if not libpath:
       if sys.platform in ['win32','win64']:
          libpath = '%s.dll' % libname
       elif sys.platform in ['mac']:
          libpath = '%s.dylib' % libname
       elif sys.platform in ['linux', 'linux2']:
          libpath = '%s.so' % libname
   return ctypes.CDLL(libpath)
tags : python, system, linux, windows

Python : dynamic user profile accesUseful to filter profiles dynamically and in a generic way. thanx to mattcc@#django for ideas
from django.db.models import get_model
profile_class = get_model(*settings.AUTH_PROFILE_MODULE.split('.'))
jabber_user = profile_class.objects.filter(jabber !='')
tags : python, django

Python : Hide static files in FiddlerFiddler is very powerful ! Customise the rules to not be spammed with useless requests. see also : http://www.fiddlertool.com/fiddler/dev/scriptsamples.asp
// Click 'Customize rules'

// add in class Handlers

public static RulesOption("Hide Js,Css,jpg,gif,png files [200, 304]")
var m_HideStatics: boolean = false;

// add in OnBeforeResponse
if (m_HideStatics && (oSession.responseCode == 200 || oSession.responseCode == 304) && ( oSession.url.toLowerCase().indexOf(".js")>-1 || oSession.url.toLowerCase().indexOf(".css")>-1 || oSession.url.toLowerCase().indexOf(".jpg")>-1 ||  oSession.url.toLowerCase().indexOf(".gif")>-1 || oSession.url.toLowerCase().indexOf(".png")>-1))
        {
            oSession["ui-hide"]="true"; 
        }
tags : system, proxy, windows

Shell : trouver tous les fichiers qui contiennent un patternAffiche toutes les lignes contenant 'todo' (insensible a la casse avec -i) dans tous les fichiers .py du repertoire en cours et recursivement. Affiche 2 lignes au dessous et en dessous du match, le nom du fichier, et colore les matches dans le term. 'todo' peut etre une expression régulière.
#!/bin/sh

find . -iname '*.py' -exec grep -H -B 2 -A 2 --color -i todo {} \;
tags : system, linux, regexp, bash

Django : automatic and unique slug fieldOverride your model save method to auto create an unique slug id. Useful for SEO. This method ensure the slug is unique using a regexp.
#!/usr/bin/python
 
from django.db import models, IntegrityError
import re
from django.template.defaultfilters import slugify
   
class MyModel(models.Model):

    title= models.CharField(max_length=50)
    slug = models.SlugField(blank = True, unique=True)

    def save(self):
        # auto fill the slug field
        if not self.slug:
            self.slug = slugify(self.title) 
        while True:
            try:
                super(MyModel, self).save()
            except IntegrityError:
                matches = re.match(r'^(.*)-(\d+)$', self.slug)
                if match_obj:
                    current = int(matches .group(2)) + 1
                    self.slug = matches .group(1) + '-' + str(current)
                else:
                    self.slug += '-2'
            else:
                break
tags : python, django, regexp

Django : DictCursor for raw sql using djangothis has been removed from django trunk because of unused, but maybe useful.
# inspired from old django code
# mimics MySQLdb.cursors.DictCursor behaviour

def dictfetchall(cursor): 
    "Returns all rows from a cursor as a dict" 
    desc = cursor.description 
    return [dict(zip([col[0] for col in desc], row))   for row in cursor.fetchall()]
tags : python, django, MySQL

Django : cookieless Django authentificationThis allows you to auth an user without any cookie, using a single POST parameter. this is especially useful for using with swfupload that cannot send cookies. Ideally, use this inside a decorator.
#!/usr/bin/python

def authFromSessionid(request):
    from django.shortcuts import get_object_or_404
    from django.contrib.sessions.models import Session
    session = get_object_or_404(Session, session_key=request.POST.get('sessionid'))
    session_data = session.get_decoded()
    user = get_object_or_404(User, pk = session_data['_auth_user_id'])
    request.user = user
tags : python, django

Django : Use your django project outside djangoThis is how to use your django models and data outside your web project. For example this can be used to create some cron jobs.
#!/usr/bin/python

from django.core.management import setup_environ
import settings
setup_environ(settings)

# do your stuff
tags : python, system, django

Shell : recursive search and replace in linux with find and sedreplace all occurences of oldtext with newtext in any .py file in /home/juju/project directory
#!/bin/sh

find /home/juju/project -iname '*.py' -exec sed -i 's/oldtext/newtext/g' {} \
tags : system, bash

Shell : Change windows default shell (replace explorer)This will change your windows default shell to your custom shell. (Ctrl+Alt+Del still active so you can reactivate explorer.exe if needed)
@echo off
REM create a .bat file with this command inside. execute then reboot.

reg add "HKCU\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /V Shell /t REG_SZ /d  "FullPathToYourApp.exe" /f
tags : system, bat, windows

Python : Email regexp validatorRegexp basique pour la validation d'adresses email simples
#!/usr/bin/python

def valid_email(email):
    import re
    reg = re.compile('([\w\.\-]+@[\w\.\-]+)')
    return reg.match(email)
tags : python, regexp

Python : simple XML/XSL transformationEasyly convert any XML file or string to text, html or anything using an XSLT stylesheet. You can pass a parameters dictionnary to the stylesheet if needed :)
#!/usr/bin/python

def xsl_transormation(xslfile, xmlfile = None, xmlstring = None, params={}):
    from lxml import etree
    import StringIO
    xslt_tree = etree.XML(utils.readfile(xslfile))
    transform = etree.XSLT(xslt_tree)
    xml_contents = xmlstring
    if not xml_contents:
        if xmlfile:
            xml_contents = utils.readfile(xmlfile)
        else:
            xml_contents = '<?xml version="1.0"?>\n<foo>A</foo>\n'
    f = StringIO.StringIO(xml_contents)
 
    doc = etree.parse(f)

    f.close()
    transform = etree.XSLT(xslt_tree)
    result = transform(doc, **params)
   
    return result
tags : python, XML, XSL

Python : Valider un RIB
def validRIB(banque, guichet, compte, cle):
    # http://fr.wikipedia.org/wiki/Clé_RIB#V.C3.A9rifier_un_RIB_avec_une_formule_Excel
    import string
    lettres = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    chiffres = "12345678912345678923456789"
    # subst letters if needed
    for char in compte:
        if char in string.letters:
            achar = char.upper()
            achiffre = chiffres[lettres.find(achar)]
            compte = compte.replace(char, achiffre)
    reste = ( 89*int(banque) + 15*int(guichet) + 3*int(compte) ) % 97
    ccle = 97 - reste
    return (ccle == int(cle))
tags : python

Python : Valider un numéro de sécurité sociale
def validInsee(insee, cle):
    # http://fr.wikipedia.org/wiki/Numero_de_Securite_sociale#Unicit.C3.A9
    # gestion numeros corses
    insee = insee.replace('A', 0)
    insee = insee.replace('B', 0)
    reste = int(insee) % 97
    return ((97 - reste) == int(cle))
 
tags : python

Django : Iterations sur un dictionnaire dans un template djangoSimple mais utile :)
{% for key,value in settings.items %}
        var SESSION_{{ key }} = "{{ value }}";
{% endfor %}
tags : python, django

.NET : Launch Autocad from a .NET applicationThis code in C# .NET launch AutoCAD from an application, and handle the process to interact with it.
public static void Launch_Autocad()
        {
            // "AutoCAD.Application.16.2" uses 2006
            // "AutoCAD.Application.17" uses 2007 or 2008, whichever was most recently run
            // "AutoCAD.Application.17.1" uses 2008, specifically
            // "AutoCAD.Application.18" uses 2010

            const string progID = "AutoCAD.Application.17.1";

            AcadApplication acApp = null;
            try
            {
                acApp = (AcadApplication)Marshal.GetActiveObject(progID);
            }
            catch
            {
                try
                {
                    Type acType = Type.GetTypeFromProgID(progID);
                    acApp = (AcadApplication)Activator.CreateInstance(acType, true);
                }
                catch
                {
                    MessageBox.Show("Cannot create object of type \"" +progID + "\"");
                }
            }
            if (acApp != null)
            {
                try
                {
                    // By the time this is reached AutoCAD is fully
                    // functional and can be interacted with through code
                    acApp.Visible = true;

                   //Here you can call AutoCAD functions or interact with a dll based on OBJECTARX and COM registered

                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Problem executing component: " + ex.Message);
                }
            }
        }
tags : .NET

.NET : Get the intersection point of 2 segments(x1, y1) / (x2, y2) are the 2 points defining the first segment (x3, y3) / (x4, y4) are the 2 points defining the second segment
        private static string Get_Intersect_Point(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4)
        {
            double x;
            double y;
            
            double denominateur = ((y4 - y3)*(x2 - x1)) - ((x4 - x3)*(y2 - y1));
            double nominateur_1 = ((x4 - x3)*(y1 - y3)) - ((y4 - y3)*(x1 - x3));
            double nominateur_2 = ((x2 - x1)*(y1 - y3)) - ((y2 - y1)*(x1 - x3));
   
            //Check if the segments have a unique common point
            if (denominateur == 0 | nominateur_1 == 0 | nominateur_2 == 0)
                return "Colinear or Paralelle";

            //Get the coordonates of the common point
            double ua = nominateur_1 / denominateur;
            double ub = nominateur_2 / denominateur;

            if(ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f)
            {
                // Get the intersection point
                x = x1 + ua*(x2 - x1);
                y = y1 + ua*(y2 - y1);
                return "X = " + x + " and Y = " + y;
            }

            return "No intersection point";
        }
tags : .NET

Apache : ReverseProxy
<VirtualHost *>
        ServerName test.monproxy.com
        ProxyPreserveHost On
        ProxyPass / http://www.google.fr/
        ProxyTimeout 1000
        SetEnv force-proxy-request-1.0 1
        SetEnv proxy-nokeepalive 1
</VirtualHost>
tags : apache, proxy

Python : Détecter la version de l'OS
import sys
print sys.platform
tags : python, system

VLC : Générer des aperçus d'une video
# ceci extraira en jpg la premiere image de la video test.mpg
vlc.exe -V image --start-time 0 --stop-time 1 --image-out-format jpg --image-out-ratio 24 --image-out-prefix snap test.mpg vlc://quit
tags : vlc, video

Shell : Liste fichiers récemment modifiés (récursif)
find . -type f -printf "%TY-%Tm-%Td %TT %p\n" | sort | less
tags : system, linux

Shell : Compter le nombre total de lignes dans un dossier (récursif)
#!/bin/sh
find . -type f -exec wc -l "{}" \; | awk ' { sum += $1 } END {print sum}'
tags : system, linux

SQL : Django+MySQL collation problems
ALTER DATABASE `mydbname` DEFAULT CHARACTER SET utf8 COLLATE 'utf8_unicode_ci';
tags : django, MySQL

Django : Autodetect project pathdont hardcode your paths !
# add this to your settings.py 
# BASE_DIR is your main project path

BASE_DIR = os.path.abspath(os.path.split(__file__)[0])
tags : python, django

all tags : python, system, vlc, video, apache, proxy, linux, django, MySQL, .NET, XML, XSL, regexp, bat, windows, bash, git

site réalisé et hébergé par revolunet © 2009 - informations légales