Update to the python packaging guide.

May 19th, 2012 by exhuma.twn

Following some of the comments, the previous article about python packaging has been updated.

  • Added a note about pip install -e as an alternative to python setup.py develop
  • Added a note about testpypi.python.org
  • Fixed the section about the manifest (I forgot to add include_package_data to the setup script)

Posted in Uncategorized | No Comments »

A comprehensive guide through Python packaging (a.k.a. setup scripts)

May 13th, 2012 by exhuma.twn

One of the really useful things in python are the setup scripts. When doing “serious” business, you really should look into them. Setup scripts are amazingly powerful. But they don’t necessarily need to be complex. But because of this flexibility, the documentation around them seems like a lot to read. Additionally, the state of packaging has changed quite a bit over the years. So you now have a couple of packages (distutils, setuptools, distribute) which all seem to try to solve the same problem. SeeĀ the current state of packaging for more details on this.

This post attempts to summarize the important bits using a “Hello World” project and steeping through the process of creating the setup.py file:

  • Creating a package distribution
  • Automatic generation of executables
  • Version numbers
  • Dependency management
  • Publishing your package (thus also making it available for automatic dependency resolution)
  • Some more food for thought.
NOTE: The setup.py script we will construct in this post, will use two bits of code which may not work in all cases:

  • importing the package itself (to centralize the version number)
  • Reading the long_description content from a text-file

Both methodologies have their issues. Importing the package only works if you can import it cleanly (i.e. without dependencies) from standard python. Reading the text file only works if the setup.py is called from the proper location.

This is mostly true. There are corner-cases however where this is not possible. If that is the case, you will need to live without these helpful shortcuts. See the comments on this article for more on this.

Read the rest of this entry »

Posted in Python | 18 Comments »

Git visualization with gource

May 7th, 2012 by latz.twn

Are you using git/svn/mercurial/bazaar as version control system and you ever wanted to visualize your work, how the project developed over time well Gource is there to visualize all this in a beautiful way. It takes the history of your svn/git/mercurial/bazaar repository and visualizes the changes over time, by whom they were done and so forth.

sudo apt-get install gource

Now run the following with path/to/project being your projects root directory, and give gource the .git subfolder. Run it and you should see the animation being presented.

gource /path/to/project/.git/

Now to export this to an mpeg4 video do the following.

gource /path/to/project/.git/ --stop-at-end --output-ppm-stream - | ffmpeg -y -b 6000k -r 60 -f image2pipe -vcodec ppm -i - -vcodec mpeg4 /tmp/gource.mp4

Here an example I created from one of my projects.

Posted in Linux | No Comments »

Monitoring memory on Solaris

April 24th, 2012 by exhuma.twn

I am currently writing a new munin plugin to monitor memory usage on Solaris machines. Strangely the existing plugins are fairly useless. Currently the script is running on a test-machine. If the results are satisfactory, I’ll post them here. Stay tuned.

Posted in Linux | No Comments »

disqus

April 20th, 2012 by exhuma.twn

Yesterday evening I enabled disqus.com comments on foobar.lu. This should make commenting easier and more accessible in the future.

Existing comments have been put into the the disqus importer queue, and according to them, they should appear after 24 hours. So nothing is lost!

Posted in Uncategorized | 1 Comment »

Custom bash completion for fabric tasks

March 20th, 2012 by exhuma.twn

Here’s a small bash function to provide TAB-completion for fabric tasks.

Simply add the following to your ~/.bashrc

You may already have a block like if [ -f /etc/bash_completion ]... in that case, simply add the extra line into that block.

#
# Bash completion for fabric
#
function _fab_complete() {
    local cur
    if [ -f "fabfile.py" ]; then
cur="${COMP_WORDS[COMP_CWORD]}"
        COMPREPLY=( $(compgen -W "$(fab -F short -l)" -- ${cur}) )
        return 0
    else
        # no fabfile.py found. Don't do anything.
        return 1
    fi
}
                                                                                                                                                                                                     
# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
    . /etc/bash_completion
    complete -o nospace -F _fab_complete fab
fi
view raw gistfile1.sh This Gist brought to you by GitHub.

Have fun

Posted in Coding Voodoo, Linux | 1 Comment »

First steps with the closure library

March 1st, 2012 by exhuma.twn

I recently switched work, and now after a lot of JavaEE development for the past 5 years, I am finally back home: Web-development. During my Java time, I did some small web bits here and there. Mainly to keep up with evolution, and followed the massive move towards more JavaScript heavy development. During my free time I took baby steps with a couple of JavaScript libraries, starting with Prototype, then script.aculo.us, MochiKit and MooTools to get some visual effects done. Without doubt, I preferred MochiKit because of it’s similarity to Python. I also dipped into Dojo because of it’s nice HTML Form widgets, fooled around with backbone.js. But eventually I ended up with jQuery, simply because it currently has the backing of The Community. All I’ve done in all of these libraries can only be summarized as “wetting my feet”. At some point I consumed all the Crockford material I could find, and boy was that eye-opening. I realized I was not aware of the most important aspects of JavaScript (especially: “Everything is global! Use Namespaces!”)!

The next thing that caught my eye, was CoffeeScript. It allowed me to write pythonesque code, and compile right down to proper JavaScript.

So what has this to do with the closure library? Well, recently (as stated above) I started web-development again. And some parts of the project made it obvious, that a good dash of JavaScript would help the project a lot. So I needed to take a decision on what library I would base my work on. My first reflex was jQuery. But out of sheer coincidence I stumbled across a blog post from someone discussing jQuery and closure. Unfortunately, I don’t have the link anymore :( The TL;DR of that blog post was however (paraphrasing):

If I had known about closure before, I would have used it instead of jQuery, because it makes it easier to structure the source code.

This made me more that curious. So the next thing I did, was read the closure tutorials, and also read the API top to bottom. I wanted to know what was in there before deeming it useful. And boy did it look interesting! The most interesting feature, as the author of said blog post pointed out, it the ability to easily structure your code. Using goog.provides and goog.require you can very easily split your JS files into multiple, well structured files, and the closure compiler will then re-combine them into one file, all properly ordered. To me, this feels a lot like writing Java or Python, which both allow you to structure your code very well. This also allows you to easily write modules which can in turn be re-used with ease in other projects (or, you could publish them).

For now, I am not missing anything from jQuery except the easy DOM querying from it. But I can happily live without it.

With my current experience, I can see the following benefits:

  • Makes it easy to structure code
  • The optional linter forces you to write proper/clean code. Especially with the --strict flag. Using it right from the start forces you to write in a uniform coding style, which makes code more readable!
  • The compiler solves dependency chains with the help of goog.provide and goog.require, and can optionally minify your code.
  • The library feels very professional. It’s even got a Logger loosely inspired by java.util.logger, and let’s you do exactly what you expect it to! This is awesome for debugging!
  • The library source code is very readable

And some disadvantages:

  • The community is much smaller than the one around jQuery. But so far I could figure out all I needed by reading the code.
  • It does not seem to have versioned downloads. You have to checkout from SVN trunk. I would prefer to be able to say: “I am basing my work on version 1.0″ instead of “trunk”
  • Instead of linking one CSS file (as in jQuery), you have to link multiple styles and figure out which ones by yourself. But given the filenames are self-explanatory, that’s not too difficult.
  • There are no predefined CSS themes. Something jQuery’s theme builder would be nice. But, I assume that the closure-style-sheet project should help writing CSS files easily. I did not yet look into that one!

As I progress with the library I’ll post my findings…

Here are two related links I found while looking for the mentioned blog post:

Posted in JavaScript | No Comments »

JScript to query scheduled tasks

June 9th, 2011 by exhuma.twn

Soon, we will need to send out notifications as soon something bad happens with a scheduled task on Windows. The following JScript file runs natively on Windows and is capable of just that. It uses the command line tool “schtasks” to query the information and wraps the result into a list of usable object instances.

It’s possible to use this list to react to important events in the job executions. For example, you could loop through the list and send emails to the appropriate people if the variable “lastResult” is non-zero.

/**
* Naive CSV splitter
*
* This splitter is *very* simplistic and may result in errors when parsing
* unknown CSV sources. This works well in the current problem domain.
*
* As we have well defined data, with no escaped quotes inside the fields, we
* can sefaly assume that this will work.
*/
function simpleCsvSplit(lineText){
var columns = [];
var inside_quote = false;
var current_data = "";
var i=0;
for(i=0; i<lineText.length; i++){
var chr = lineText.substring(i, i+1);
if (chr === "\""){
inside_quote = !inside_quote;
continue;
} else if (chr === "," && !inside_quote){
columns[columns.length] = current_data;
current_data = "";
}
if (inside_quote){
current_data += chr;
}
}
columns[columns.length] = current_data;
return columns;
}

/**
* A container object for the task metadata
* This makes further processing with the data a lot more expressive.
*
* @param lineText A string taken from the CSV output representing one line
*/
var Task = function(lineText){
// parse the CSV data
columns = simpleCsvSplit(lineText);

// put everything into explicitly named variables
this.hostName = columns[0];
this.name = columns[1];
this.nextRun = columns[2];
this.status = columns[3];
this.lastRun = columns[4];
this.lastResult = columns[5];
this.creator = columns[6];
this.schedule = columns[7];
this.command = columns[8];
this.startIn = columns[9];
this.comment = columns[10];
this.scheduledState = columns[11];
this.scheduledType = columns[12];
this.startTime = columns[13];
this.startDate = columns[14];
this.endDate = columns[15];
this.days = columns[16];
this.months = columns[17];
this.runAs = columns[18];
this.deleteIfNotRescheduled = columns[19];
this.stopIf = columns[20];
this.repeatEvery = columns[21];
this.repeatUntilTime = columns[22];
this.repeatUntilDuration = columns[23];
this.repeatStopIfRunning =columns[24];
this.idleTime = columns[25];
this.powerManagement = columns[26];
};

// execute the shell command to retrieve the scheduled tasks
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("schtasks /Query /FO CSV /V");

// retrieve the lines from stdout and save them as tasks
var tasks = [];
while( !oExec.StdOut.AtEndOfStream){
   tasks[tasks.length] = oExec.StdOut.ReadLine();
}

// now do something with the tasks
for(var i=2; i<tasks.length; i++){
var tmp = new Task(tasks[i]);
WScript.Echo(tmp.lastResult + " - " + tmp.status);
}

Posted in Coding Voodoo | No Comments »

Windows script to remove old files

June 8th, 2011 by exhuma.twn

Simple script… still, I thought I’d share…

/**
* Remove all files and folders that are older than a set number of days.
*
* @param rootURI The URI of the root folder. All old files and folders in this
* folder are removed.
* @param days Files older than this number of days are deleted
*/
function purgeFiles(rootURI, days) {

  var fso = new ActiveXObject("Scripting.FileSystemObject");
  var rootFolder = fso.GetFolder(rootURI);
  var subFolders = new Enumerator(rootFolder.SubFolders);

  // create a date before which files are considered "old"
  var threshold_date = new Date();
  threshold_date.setDate(threshold_date.getDate()-days);

  // loop over each file
  subFolders.moveFirst();
  for(;!subFolders.atEnd(); subFolders.moveNext()){
     var f = subFolders.item();
     if(f.DateCreated < threshold_date ){
        //WScript.Echo("Deleting "+f.Name+" last accessed on: "+f.DateCreated);
        f.Delete(true);
     }
  }

}

purgeFiles("C:/path/to/folder", 300);

view raw purgeFiles.js This Gist brought to you by GitHub.

Posted in Coding Voodoo | No Comments »

Change JPA EntityManager connection properties at Runtime

December 30th, 2010 by exhuma.twn

There are many times you want to be able to use different connection options for a JPA EntityManager. The most obvious is different user-credentials (think of a user login-screen and re-using these credentials to connect to the DB), or to make the distinction between development/testing/production environment.

However, if you let Netbeans create the persistence configuration, it will hardcode all connection parameters into the persistence.xml file. When retrieving an EntityManager instance, it will use this information to connect.

If, instead you would like to do this at runtime, you can do the following:

  1. Remove the “properties” tag from the persistence.xml. This may not be necessary, but this will make it clear, that the properties are set inside the code.
  2. Create a “Map<String, String>” which will contain the properties. A list of standard properties can be found in the specs in section 8.2.1.9.
  3. Use this map to create an EntityManagerFactory and use this to create your EntityManager

An example persistence.xml without properties

<?xml version="1.0" encoding="UTF-8"?>                                          
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLo
 <persistence-unit name="myTestPU" transaction-type="RESOURCE_LOCAL">    
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>            
    <class>my.package.Entity1</class>                    
    <class>my.package.Entity2</class>                    
  </persistence-unit>                                                              
</persistence>

In case Netbeans created a method “getEntityManager”, you can safely replace this. Here is an example I currently have in use. The “appConf” instance is a singleton I use to store configuration data in the user’s home folder, and yes, the password is stored in plain-text, but for this test-case I did not need to go any further:

    private EntityManager getEntityManager() {                                  
                                                                               
        Map<String, String> dbProps = new HashMap<String, String>();            
                                                                               
        dbProps.put("eclipselink.logging.level",                                
                appConf.get("eclipselink.logging.level", "INFO").toString());  
                                                                               
        // On linux, the GSSAPI is not available. Use a default user/password  
        // pair to connect                                                      
        if ("Linux".equals(System.getProperty("os.name"))) {                    
            dbProps.put("javax.persistence.jdbc.url",                          
                    String.format("jdbc:jtds:sqlserver://%s/%s",                
                    appConf.get("db.host", "my-default-host"),                          
                    appConf.get("db.database", "my-default-db")));                
            dbProps.put("javax.persistence.jdbc.driver",                        
                    "net.sourceforge.jtds.jdbc.Driver");                        
            dbProps.put("javax.persistence.jdbc.password",                      
                    appConf.get("db.password").toString());                    
            dbProps.put("javax.persistence.jdbc.user",                          
                    appConf.get("db.user", "my-default-username").toString());          
        } else {                                                                
            dbProps.put("javax.persistence.jdbc.url",                          
                    String.format("jdbc:sqlserver://%s;databaseName=%s;integratedSecurity=true",
                    appConf.get("db.host", "my-default-host"),                          
                    appConf.get("db.database", "my-default-db")));                
            dbProps.put("javax.persistence.jdbc.driver",                        
                    "com.microsoft.sqlserver.jdbc.SQLServerDriver");            
        }                                                                      
        appConf.flush();                                                        
                                                                               
        EntityManagerFactory fact = Persistence.createEntityManagerFactory("myTestPU", dbProps);
        return fact.createEntityManager();                                      
   }

This example uses eclipselink. All available properties can be found it the EclipseLink Wiki

Posted in Coding Voodoo | 5 Comments »

« Previous Entries

Pages

Recent Posts

Categories

Links


Archives

Meta