Codelog

foreach(Snippet aSnippet in CodeLog){ aSnippet.GetSolution(); }

Review of Stack Overflow beta

without comments

I have been talking about Stack Overflow and it’s beta. So, what is this Stack Overflow. It is a site for programmers to come by and discuss about their problems, post questions, answer other’s questions and solve problems together. It was started by Jeff Atwood and Joel Spolsky who were doing the Stack Overflow podcast for over 4 months. It was launched into a private beta late July.

The interface is really simple - nice big fonts, lot of numbers displaying information about the post like votes, views, answers, etc., a list of tags, everything you would find in a normal Web 2.0ish site.

But what is important is that there is a really good community around it and the number questions are mostly answered within an hour.

Stack Overflow screenshot

Stack Overflow screenshot

Once a user goes to the site, he can do one of the following things:

  • Read other’s questions
  • Provide answers to the questions
  • Ask your own questions
  • And as you keep participating in the site, upmod/downmod questions/answers, edit other’s questions/answers, etc.

All these can be done without even logging in. The inertia to begin using and participating in the site is almost zero. All your user details are tracked with a cookie on your browser. So you can always claim your account by logging in (using openid) anytime later.

One incentive for the users to keep coming back to the site is the reputation system. For every action of the user which is of some value to the community, he is rewarded with reputation points. For eg: if your answer is upvoted/downvoted, selected as the best answer, etc., all will earn and make you lose points. It really works and I am addicted to it and find it hard to find questions which I can answer before others.

Along with this, there is also the badges system. If your answer gets one upvote, if you answer someone’s question, if you edit someone’s answer/question, etc. Yeah, you did read that right. You can edit someone’s questions and answers provided you have the right reputation points. So as Jeff said, “the system automatically learns to trust you as you keep participating“. It is a mix of a wiki, forum and reddit like site.

The site almost has more than a thousand users and has pretty good volume of questions and answers and it would soon grow to be a huge repository of programming knowledge. Right now the questions and the user base is skewed to C#, .NET and Microsoft technologies, but other open source languages too are answered and I guess once it becomes public the entire crowd from proggit will come over here.

There are still some features which I miss like, but the dev team is working on

  • RSS Feeds
  • Subscribe to interesting questions
  • Links to voted questions

There are however a huge list of suggestions/bugs/features that others want which can be reached over at the Uservoice site. If you have a beta pass to the site, how do find the site? What are the things you think that could go wrong? How do you think the SOFlow team should proceed?

Written by cnu

August 18th, 2008 at 12:07 am

Posted in Sites

Tagged with ,

Pretty print XML files in Emacs

without comments

I have been using Emacs for most of my editing chores and recently I had to edit lot of XML files - most of which were machine generated without any space or indentation. I wanted someway to pretty print the XML file. Maybe I didn’t search very well, but today after getting my StackOverflow beta invite, I decided to post it there. I did get a good answer through it, but found another solution from Google.

It is an elisp function which you have to just copy-paste onto your .emacs file and reload emacs. After that, you can pretty print your XML files by marking the region and typing M-x bf-pretty-print-xml-region

Here is the function

(defun bf-pretty-print-xml-region (begin end)
  "Pretty format XML markup in region. You need to have nxml-mode
http://www.emacswiki.org/cgi-bin/wiki/NxmlMode installed to do
this.  The function inserts linebreaks to separate tags that have
nothing but whitespace between them.  It then indents the markup
by using nxml's indentation rules."
  (interactive "r")
  (save-excursion
      (nxml-mode)
      (goto-char begin)
      (while (search-forward-regexp "\>[ \\t]*\<" nil t)
        (backward-char) (insert "\n"))
      (indent-region begin end))
    (message "Ah, much better!"))

By the way thanks to Marcel Levy for answering my first SO question. Now I really have to post a review about the beta.

Written by cnu

August 15th, 2008 at 11:47 pm

Posted in Editors, XML

Tagged with , ,

Transparent images over controls

with one comment

Before me starting off with the article, sorry for not posting anything last week. I was kinna busy with the office works :P Hmm. Lets begin.

Have you ever tried to put a transparent image over a button or some other control ?? I meant transparent. If not, lets try it.

Way that may not give you the solution you need

not_so_transparent

Way that you may be interested to know about

  • Add a button to your applicationReally transparent image


System.Windows.Forms.Button myTransparentImageButton = new System.Windows.Forms.Button();

this.Controls.Add(myTransparentImageButton);

  • For the picture … do we need a picturebox to put the image ?? No. Lets try to draw the image over the button.
  • Import an image to the resource file and add the following snippet to the paint event of the button
private void myTransparentImageButton_Paint(object sender, PaintEventArgs e)  //Handling the
paintevent as the image should be painted over the button when the button is painted
{
     Graphics aGraphics = e.Graphics;  //To draw the image, we use the abstract class -- Graphics
     Image aImage = (Image)<your_name_space>.<resource_file_class_name>.<image>;  //Creating an
image object using the bitmap from the resource file
     aGraphics.DrawImage(aImage, new Point(e.ClipRectangle.Width - aImage.Width, 0)); //Drawing the
image in the required position
}

Written by sudarsanyes

August 14th, 2008 at 10:43 am

Posted in C#, Controls, UI

Tagged with , ,

Doctests in Python

without comments

This post is due for a long time since my post on Singular form of a word program and here it is - Doctests in Python. From the python library reference,

The doctest module searches for pieces of text that look like interactive Python sessions, and then executes those sessions to verify that they work exactly as shown.

Doctests are an easy way to test small functions by specifying the output of the function in docstrings. In python you can (should) write docstrings for classes and methods which can be used to generate the documentation for the module. In those docstrings, you just specify calls to the function with the return string specified. The doctest module automatically asserts the output and verifies whether the test passes or fails.

Lets see an example of doctest and how to run them. Lets create a function which adds two numbers.

def add(x, y):
    """Adds two numbers/strings together

    >>> add(1,2)
    3
    >>> add('foo','bar')
    'foobar'
    """
    return x+y

Here we have written the docstrings and have four lines which look like the python shell. There we call the function with various arguments and also specify how the function will return.

So, how do we run the test? Just include these lines in the module and run the file directly. This is the usual way we run doctest (in the __main__ part of the file).

def _test():
    import doctest
    doctest.testmod()

if __name__ == "__main__":
    _test()

You just have to call the doctest.testmod() function and it will search for all such tests in the docstrings and outputs nothing if the tests pass. If you want to get more verbose output, run the file as python filename.py -v

There are many advantages of doctests (wikipedia has a lot more):

  • Easy to understand what a function is going to do if called
  • Tests and code together - easy to update the test if code changes
  • Most of the times I execute my functions on the shell - so I just have to copy-paste the output from the shell to the code

Once you start using doctests, you would find yourself trying to use it in all possible places. For more elaborate testing, you should probably use pyunit.

Is there any other programming language which has tests written directly in the documentations? If you were to design such a testing module for you favourite language, how would you do it (especially if it doesn’t have a interactive shell)? Do explain your views on it below.

Written by cnu

August 9th, 2008 at 8:08 am

Posted in Documentation, Python, Testing

Tagged with , ,

Stack Overflow beta now open

without comments

Stack Overflow is a new website that Jeff Atwood (of CodingHorror) and Joel Spolsky (JoelOnSoftware) have started together. It is a wiki + forum kind of a site where anyone (no signup required) can ask any question in programming and the community around the site will answer it. The owner of the question has the power to choose one or more right answers and others can vote up/down the questions and answers. 

A pretty simple site and I have been listening to the podcast right from the beginning and I wanted to be on the beta. Last week Jeff opened up a private list of beta testers and the dev team has been listening to all bugs and feedback using the uservoice service (which we also use here at blogial). 

I am happy to note that the site is now up for public beta and getting onto the beta list is simple. Just fill in your name and email address at a Google Spreadsheet form and you are done. 

Reading this review of the private beta, I think the dev team has done a great job. Waiting for the beta link and will try to post a review as soon as I get my hands dirty.

Written by cnu

August 6th, 2008 at 11:21 pm

Posted in Sites

Tagged with ,

Sections in Turbogears Config file

without comments

In turbogears you have three important config files. One is the dev.cfg file used during development, another is prod.cfg used during deploying your code. The last one is app.cfg file which has parameters which are common to both dev and prod.

When you store the parameters in the app.cfg file, it is good to group related parameters together under a section. A new section can be created by enclosing a word with [ and ], eg: [API]

All this is fine till we come to the point of reading back the values from the config file. We faced this same problem and whenever we tried to read it back, it used to give some error about no such variable present.

After looking through the code of the configparser.py for cherrypy, we saw that there was one more additional parameter called path. The path parameter takes in the section name and the variable inside the section is taken in by the parameter key.

So instead of doing a tg.config.get('url'), you would need to do a tg.config.get('url', path='API').

Though this was slightly different than the usual config parser module, it solved the problem of properly categorizing the config file.

Written by cnu

August 1st, 2008 at 12:37 pm

Posted in Python

Tagged with , ,

Git hosting for code snippets

without comments

Gist LogoGithub - hosting provider for the open source version control system Git, has launched a version control system for small code snippets called Gist. Now you can use pastebins without having to delete the entire snippet and recreating it again.

Git LogoIt even automatically detects the code highlighting based on the file extension you create. And if you want to protect your code, you can make them private. I do wish that they have a facility to upload the source code instead of me having to manually copy-paste it. Best of all, you have got yourself a entire git branch - which you can clone it from any machine if you just know the number.

You will see me using more of Gist for all my code snippets.

Written by cnu

July 29th, 2008 at 11:34 am

Posted in source control

Tagged with ,

Using ContextMenus in C#

without comments

In my last post I was talking about ContextMenus and ContextMenuStrips. In this one, I will try to explain some of the ways you can make use of that control. Before that a quick recap. ContextMenus are obsolete. Now a days we use ContextMenuStrip. It has many cool facilities that makes your application more eye cathy (can’t beat mac though). Lets begin with

Remember: ContextMenu, menu, ContextMenuStrip means ContextMenuStrip in the following explanations

Adding a ContextMenuStrip
ContextMenuStrip can be found under System.Windows.Forms.ContextMenuStrip. So to have a menu control, just create an object of the above

System.Windows.Forms.ContextMenuStrip myContextMenuStrip = new System.Windows.Forms.ContextMenuStrip(); //Just creates a usable object. Nothing else

Adding items to the ContextMenuStrip
Adding items to the menu is easy (as usual). Use the Items.Add() method to do so.

myContextMenu.Items.Add("foo"); //Now you can see and click foo from the contextmenu

Read the rest of this entry »

Written by sudarsanyes

July 28th, 2008 at 7:27 pm

Posted in C#, Controls, UI

Tagged with , ,

if-else conditions in lambda functions

with 2 comments

On reading my last post singular form of a word, a friend of mine (Sathya) didn’t understand what I had done in the lambda functions. It was of the form lambda w: w[-3:] == ‘ies’ and w[:-3] + ‘y’. I had forgotten to explain about that in that post.

There is one small restriction in lambdas - you can’t use if-else constructs in them. If you want to use a condition check in your lambda, then it has to be of this form

lambda : <condition> and <if block> or <else block>

This is easy to understand when you compare it with conditional or ternary operators in C (?:) - condition?if block:else block.

Written by cnu

July 28th, 2008 at 3:53 pm

Posted in Python

Tagged with ,

Singular form of a word in python

with 4 comments

Last post I talked about using list comprehensions and promised to post a simple method to find the singular form of a word. When I wanted to write such a function, I initially thought of using a chain of if-elif-else constructs. But I didn’t like it that way. So I used lambda functions and list comprehensions to do the same job.

def singularize(word):
    """Return the singular form of a word

    >>> singularize('rabbits')
    'rabbit'
    >>> singularize('potatoes')
    'potato'
    >>> singularize('leaves')
    'leaf'
    >>> singularize('knives')
    'knife'
    >>> singularize('spies')
    'spy'
    """
    sing_rules = [lambda w: w[-3:] == 'ies' and w[:-3] + 'y',
                  lambda w: w[-4:] == 'ives' and w[:-4] + 'ife',
                  lambda w: w[-3:] == 'ves' and w[:-3] + 'f',
                  lambda w: w[-2:] == 'es' and w[:-2],
                  lambda w: w[-1:] == 's' and w[:-1],
                  lambda w: w,
                  ]
    word = word.strip()
    singleword = [f(word) for f in sing_rules if f(word) is not False][0]
    return singleword

def _test():
    import doctest
    doctest.testmod()

if __name__ == '__main__':
    _test()

This method is simple if you know the rules of plurals in the english language. I have converted each rule into a lambda function which returns the corresponding singular word depending on the word ending. The order of the rules are important, for eg., i should first check for -es before checking for -s. I haven’t taken care of the special plurals like men-man, people-person, children-child.

I then use list comprehensions to apply each function on the input word and pick the 0th element. Now you get the singular for of the word.

If you notice in the function, I have used something called doctests which is a very easy way to test your functions. You can download the source code and run it to run the doctest. Wow, now I got another topic to write about in the next post - doctests in python.

Written by cnu

July 27th, 2008 at 1:48 pm

Posted in Python

Tagged with ,