Clean up CVS and SVN directories

A quick python script to clean up a “used to be” cvs or svn working directory – I know that TortoiseSVN has an export feature but TortoiseCVS does not.
[code lang=”python”]
“””
Removes all cvs and svn directories
usage: “CVSSVNCleanup.py true” to delete all cvs and svn directories
“CVSSVNCleanup.py” to view all cvs and svn directories
“””

import os
import shutil
import sys

#get a list of all the root level directories
lDirs=os.listdir(os.curdir)

if len(sys.argv) > 1 and sys.argv[1].lower()==”true”:
delete = True
else:
delete = False

for d in lDirs:
for root,dirs,files in os.walk(d):

for dirName in dirs:
if dirName.lower() == “.svn” or dirName.lower() == “cvs”:
curDir = os.getcwd()+”\\”+root+”\\”+dirName
if delete == True:
shutil.rmtree(curDir)
curDir = curDir + ” – Deleted”
print curDir
continue
print “Finished”
[/code]

Python Publisher Posted Vars

I was trying to get all of the variables posted to a python script added to a dictionary and was trying
[code lang=”python”]
form = cgi.FieldStorage()
[/code]
but it seems that you cannot use FieldStorage when using the publisher handler in mod_python. As the request variable req is always available, use the following.
[code lang=”python”]
styleArgs = {}
for k in req.form.keys():
styleArgs[k] = “‘”+req.form[k]+”‘”
[/code]

I couldn’t find any docs on this so I thought I’d post it.

What’s my bloody session ID

While having a wander over at xulplanet.com I stumbled across the Cookie Manager Interface (Interface to the Gecko engine that is).

We have a simple HTML page in work that we use to emulate Payment Service Providers[PSP] (like Paypal or SecureTrading). It’s a right pain to test as we have to edit the page each time we test a different site. We also have to find our session ID from that sites cookie if we want to test it.

I wrote a few functions to allow me to populate a select drop down with the cookie domains (and session IDs) for a filtered list of all my cookies. On Page load the drop down is genereated and onChange of that dropdown the forms are updated with the chosen sites SessionID and the forms actions is also changed. Pretty neat and saves me about 10 clicks everytime I need to test my payment emails or that the PSP integration is working.

[code lang=”javascript”]
function _loadCookies()
{

//need to ask for permission to look at the users cookies
try {
netscape.security.PrivilegeManager.enablePrivilege(“UniversalXPConnect”);
} catch (e) {
alert(“Permission to save file was denied.”);
}
var nsICookie = Components.interfaces.nsICookie;
var _cm = Components.classes[“@mozilla.org/cookiemanager;1”]
.getService(Components.interfaces.nsICookieManager);

var _ds = Components.classes[“@mozilla.org/intl/scriptabledateformat;1″]
.getService(Components.interfaces.nsIScriptableDateFormat);
var _hosts = {};
var e = _cm.enumerator;
var hostCount = { value: 0 };

while (e.hasMoreElements()) {
var cookie = e.getNext();
if (cookie && cookie instanceof Components.interfaces.nsICookie)
{

var strippedHost = _makeStrippedHost(cookie.host);
if (!(strippedHost in _hosts) || !_hosts[strippedHost])
{
_hosts[strippedHost] = { cookies : [],
rawHost : strippedHost,
level : 0,
open : false,
container : true };

++hostCount.value;
var c = _makeCookieObject(strippedHost, cookie);
_hosts[strippedHost].cookies.push(c);
}
}
else
break;
}

var _select = document.createElement(‘SELECT’)
for (var host in _hosts) {
var cookies = _hosts[host].cookies;
var hostName =_hosts[host].rawHost;
var rExp = /kf/gi;
var rExpResults = hostName.match(rExp);
if(rExpResults && rExpResults.length > 0)
{
for (var _cookie in cookies)
{
var _option = document.createElement(‘OPTION’)
_option.innerHTML = _hosts[host].rawHost;
_option.value = cookies[_cookie].value;
_select.appendChild(_option);
}

}
}
_select.id=”siteURLChange”;
_select.onchange = changeActionAndSessID;

var URLForm = document.getElementById(‘siteurl’);
var URLInput = document.getElementById(‘url_site’);
URLInput.style.display = “none”;
insertAfter(URLForm, _select, URLInput);
changeActionAndSessID();
}

function _makeStrippedHost(aHost)
{
var formattedHost = aHost.charAt(0) == “.” ? aHost.substring(1, aHost.length) : aHost;
return formattedHost.substring(0, 4) == “www.” ? formattedHost
.substring(4, formattedHost.length) : formattedHost;
}

function _makeCookieObject(aStrippedHost, aCookie)
{
var host = aCookie.host;
var formattedHost = host.charAt(0) == “.” ? host.substring(1, host.length) : host;
var c = { name : aCookie.name,
value : aCookie.value,
isDomain : aCookie.isDomain,
host : aCookie.host,
rawHost : aStrippedHost,
path : aCookie.path,
isSecure : aCookie.isSecure,
expires : aCookie.expires,
level : 1,
container : false };
return c;
}
[/code]

I hope this code helps someone wanting to view cookies from a certain domain or from a filtered list.

MySQLdb 1.2.0 with Mysql 5.0.18 and Python 2.4

I was trying to get Python 2.4 working with MySQL 5.0 and thought it would be pretty simple….Oh No. I thought I’d run a quick test last night while I checked my mail before bed….2 1/2 hours later still no joy. I downloaded the MySQLdb win32 exe from MySQLdb’s SourceForge page and ran it. I then tried to import MySQLdb which resulted in an import error stating that _mysql and MySQLdb were different versions. The funny thing was that when I imported _mysql which is also in the package it worked fine

[code lang=”python”]
import _mysql
db=_mysql.connect(host=”localhost”,user=”root”,passwd=”****”,db=”test”)
db.query(“””SELECT VERSION()”””)
r=db.store_result()
r.fetch_row()
[/code]

I then downloaded the most recent source release and tried to build it (with some help) but to no avail… I kept getting link errors. I then had a look at the MySQLdb __init__.py file whilch gets called on all MySQLdb imports. I commented out the following
[code lang=”python”]
v = getattr(_mysql, ‘version_info’, None)
if version_info != v:
raise ImportError, “this is MySQLdb version %s, but _mysql is version %s” %\
(version_info, v)
del v
[/code]

to read

[code lang=”python”]
#v = getattr(_mysql, ‘version_info’, None)
#if version_info != v:
# raise ImportError, “this is MySQLdb version %s, but _mysql is version %s” %\
# (version_info, v)
#del v
[/code]

This stops the version check and importing MySQLdb works fine. I’m sure it’s not the right thing to do but it works and I haven’t had any problems yet.. Hope it helps somebody out there 🙂

[code lang=”python”]
import MySQLdb
conn = MySQLdb.connect (host=”localhost”,user=”root”,passwd=”****”,db=”test”)
cursor = conn.cursor ()
cursor.execute (“SELECT VERSION()”)
row = cursor.fetchone ()
print “server version:”, row[0]
cursor.close ()
conn.close ()
[/code]

Multiline you regex bastard

“I said multiline you F*^k” I shouted repeatedly as my c# kept failing to match my regex. I did have
[code lang=”cpp”]
(<span>)(.*?)(</span>)
[/code]

in multiline mode but I also needed ^$

[code lang=”cpp”]
(<span>)([^$.]*?)(</span>)
[/code]

At last

Update… no it wasnt.

What I needed was singleLine option instead of multiline. Where is the logic???

[code lang=”cpp”]
(<span>)(.*?)(</span>)
[/code]

with the /s or System.Text.RegularExpressions.RegexOptions.Singleline incase you have the same problem as me 🙂