Friday, September 17, 2010

Display resolution of LCD monitors.

An interesting fact: LCD monitors are designed with a single resolution only. This resolution is known as the native resolution of the monitor. To get the best display, its always best to use the native resolution. If one lower's the display resolution, the monitor must use interpolation to fill in the extra pixels. This leads to blurriness in LCD displays.

In trade shows I usually had to connect my laptop to an external LCD monitor. In cloned display mode, both my laptop's built-in monitor and the external LCD monitor would use the same display resolution, which would typically be much lower than the full resolution of the external monitor. I always used to wonder at this and fixed the problem by going for the external monitor only display option and then setting the resolution to the highest possible resolution of the LCD monitor. Now I understand the logic behind this.

Monday, June 14, 2010

The origin of the term Endianness

So most of us programming people know about Endianness. We know that Intel microprocessors are little-endian while Motorola microprocessors are big-endian. Most of the Internet protocols as well as most of audio/video binary formats also follow big-endian style. Yet I wonder if many of us do know about the origin (etymology) of the these terms. I for myself didn't know about this before today. And I found it to be quite funny.

According to Wikipedia The term big-endian originally comes from Jonathan Swift's satirical novel Gulliver’s Travels by way of Danny Cohen in 1980[2]. In 1726, Swift described tensions in Lilliput and Blefuscu: whereas royal edict in Lilliput requires cracking open one's soft-boiled egg at the small end, inhabitants of the rival kingdom of Blefuscu crack theirs at the big end (giving them the moniker Big-endians).[6] The terms little-endian and endianness have a similar intent.[7]

"On Holy Wars and a Plea for Peace"[2] by Danny Cohen ends with: "Swift's point is that the difference between breaking the egg at the little-end and breaking it at the big-end is trivial. Therefore, he suggests, that everyone does it in his own preferred way. We agree that the difference between sending eggs with the little- or the big-end first is trivial, but we insist that everyone must do it in the same way, to avoid anarchy. Since the difference is trivial we may choose either way, but a decision must be made."



I first read about this story in Memory Management Programming Guide for Core Foundation. Hope you find this story interesting.


Saturday, June 12, 2010

A simple program for FTP directory listing using pycurl

  1. #import pycurl
  2. import pycurl
  3. import StringIO
  4. # lets create a pycurl object
  5. c = pycurl.Curl()
  6. # lets specify the details of FTP server
  7. c.setopt(pycurl.URL, r'ftp://ftp.ncbi.nih.gov/refseq/release/')
  8. # lets create a buffer in which we will write the output
  9. output = StringIO.StringIO()
  10. # lets assign this buffer to pycurl object
  11. c.setopt(pycurl.WRITEFUNCTION, output.write)
  12. # lets perform the LIST operation
  13. c.perform()
  14. # lets get the output in a string
  15. result = output.getvalue()
  16. # lets print the string on screen
  17. print result
  18. # FTP LIST output is separated by \r\n
  19. # lets split the output in lines
  20. lines = result.split('\r\n')
  21. # lets print the number of lines
  22. print len(lines)
  23. # lets walk through each line
  24. for line in lines:
  25.     # lets print each part separately
  26.     parts = line.split()
  27.     # we can print the parts now
  28.     print parts
  29.     # the individual fields in this list of parts
  30.     if not parts: continue
  31.     permissions = parts[0]
  32.     group = parts[2]
  33.     user = parts[3]
  34.     size = parts[4]
  35.     month = parts[5]
  36.     day = parts[6]
  37.     yearortime = parts[7]
  38.     name = parts[8]

The above program

  • Creates a pycurl object
  • Specifies the URL of an FTP server (anonymous account)
  • Creates a StringIO buffer to store the results of FTP LIST command
  • Associates the pycurl object with the StringIO buffer for writing output received from FTP server
  • Performs the curl operation
  • Extracts the output
  • Breaks the output in lines (considering \r\n as separator)
  • Walks through the lines one by one
  • Splits the line based on whitespace into different parts
  • Extracts different fields from the directory listing (permissions, group, user, size, filename etc.)

Notes about processing the output of FTP LIST command

The response of FTP LIST command is very much non-standard. Different flavors of FTP servers simply display the directory listing differently. So the parsing of this output may be easy for one FTP server but a code for parsing directory listings which works across all kinds of FTP servers is difficult to write. This is probably the reason why this functionality is not provided in ftplib (Python Standard Library). In
the FTP standard, the output of FTP LIST command was intended for human consumption rather than computer interpretation which led to all the variations over the years.

FTPPARSE http://cr.yp.to/ftpparse.html is a library for parsing FTP LIST command responses for a variety of FTP servers. ftpparse currently understands the LIST output from any UNIX server, Microsoft FTP Service, Windows NT FTP Server, VMS, WFTPD, NetPresenz, NetWare, and MSDOS. Its easy to write a Python wrapper for this library using ctypes.

Even this library doesn't work for a number of situations:
- When the size of a file is bigger than 2 GB.
- FTP servers of various video servers (I have seen GUI FTP clients like FileZilla or Windows explorer suck on some of them)

Thursday, May 27, 2010

Visual Studio (VS) 2005 IDE for IronPython (Python) - Yang Li's blog - Site Home - MSDN Blogs

Visual Studio (VS) 2005 IDE for IronPython (Python) - Yang Li's blog - Site Home - MSDN Blogs

Provides the steps for integrating IronPython into Visual Studio 2005.

Sandcastle (software) - Wikipedia, the free encyclopedia

Sandcastle (software) - Wikipedia, the free encyclopedia

Sandcastle is a documentation generator from Microsoft that automatically produces MSDN style reference documentation out of reflection information of .NET assemblies and XML documentation comments found in the source code of these assemblies. It can also be used to produce compiled user documentation from Microsoft Assistance Markup Language with the same look and feel as reference documentation.

Thursday, May 20, 2010

Pretty printing boolean values in C++

By default boolean values (type bool, values true and false) are printed as 1 and 0 in C++ iostreams. There is a simple way to print them as their names (true/false). The following code-example demonstrates how to do that using boolalpha manipulator.

  1: #include <iostream>
  2: using namespace std;
  3: 
  4: int main()
  5: {
  6:     // By default true prints as 1 and false prints as 0
  7:     cout << true << " " <<  false << endl;
  8:     // We can enable boolalpha formatting flag 
  9:     cout << boolalpha;
 10:     // Now true and false will be inserted as their names instead
 11:     // of integral values
 12:     cout << true << " " <<  false << endl;
 13:     // We can later on unset boolalpha with noboolalpha format manipulator
 14:     cout << noboolalpha << endl;
 15:     cout << true << " " <<  false << endl;
 16:     // The boolalpha flag is not set in standard streams on initialization
 17:     return 0;
 18: }
 19: 
 20: 


The output of the program looks as follows:



  1: 1 0
  2: true false
  3: 1 0


We can notice that on the first line the output is integral. After setting boolalpha, the output becomes textual. Later on the output becomes integral again after setting noboolalpha.



Input streams



The manipulator can similarly be used on input streams for reading boolean values as true/false or 1/0.

Wednesday, May 19, 2010

Adding custom draw functionality to an MFC CButton

We will start by defining a subclass CBDButton to the MFC class CButton.


  1: class CBDButton : public CButton
  2: {
  3: public:
  4:     // overwrite void DrawItem function and draw your button
  5:     void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
  6: };
  7: 


As you can notice above, we have overridden one function DrawItem in this class. Lets now look at its implementation.



 



  1: void CBDButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
  2: {
  3:     // TODO: Add your code to draw the specified item
  4:     UINT uStyle = DFCS_BUTTONPUSH;
  5: 
  6:     // This code only works with buttons.
  7:     ASSERT(lpDrawItemStruct->CtlType == ODT_BUTTON);
  8: 
  9:     // If drawing selected, add the pushed style to DrawFrameControl.
 10:     if (lpDrawItemStruct->itemState & ODS_SELECTED)
 11:     {
 12:         uStyle |= DFCS_PUSHED;
 13:     }
 14: 
 15:     CDC dc;
 16:     dc.Attach(lpDrawItemStruct->hDC);
 17: 
 18:     // Draw the button frame.
 19:     dc.DrawFrameControl(&lpDrawItemStruct->rcItem, DFC_BUTTON, uStyle);
 20: 
 21:     CRect rect = lpDrawItemStruct->rcItem;
 22:     rect.left = rect.left + 1;
 23:     rect.right = rect.right - 2;
 24:     rect.top = rect.left + 1;
 25:     rect.bottom = rect.bottom - 2;
 26:     dc.FillSolidRect(rect, m_clrBk);
 27: 
 28:     // Get the button's text.
 29:     CString strText;
 30:     GetWindowText(strText);
 31:     // Draw the button text using the text color.
 32:     COLORREF crOldColor = dc.SetTextColor(m_crText);
 33:     dc.DrawText(strText, strText.GetLength(), &lpDrawItemStruct->rcItem, DT_SINGLELINE|DT_VCENTER|DT_CENTER);
 34:     dc.SetTextColor(crOldColor);
 35: 
 36:     dc.Detach();
 37: }

Wednesday, May 5, 2010

Testing windows live writer

Windows Live Writer is expected to help me write source code examples easily and post them to my blog seamlessly. In this post I am trying to test its functions.

Here is some C++ code:

  1: class A
  2: {
  3: public:
  4:     A();
  5:     ~A();
  6:     void f();
  7: };
  8: 
  9: // an example of implementation inheritance
 10: class B : private A
 11: {
 12: public:
 13:     B();
 14:     ~B();
 15:    void g();
 16: };
 17: 
 18: 


Following is some Python code:



  1: import os
  2: import sys
  3: 
  4: def main():
  5:     filepath = sys.argv[1]
  6:     contents = open(filepath).readlines()
  7:     print 'Number of lines: ' , len(contents)
  8: 
  9: if __name__ == '__main__':
 10:     main()


A Haskell code example:



  1: double:: Integer -> Integer
  2: double x = x + x
  3: 
  4: square :: Integer -> Integer
  5: square x = x * x
  6: 
  7: main = do
  8:          print $ square 10
  9:          print $ double 20
 10: 
 11: 


Some JavaScript:



  1: fucntion f()
  2: {
  3:      alert('Hello World');
  4: }
  5: 


 



Some HTML:



  1: <html>
  2:   <head>
  3:     <title>Hello World </title>
  4:   </head>
  5:   <body>
  6:     <p> Don't Panic </p>
  7:   </body>
  8: </html>
  9: 


Some CSS:



  1: .header
  2: {
  3:   forground-color: black;
  4:   background-color: red;
  5:   text-size: 20;
  6: }
  7: 

I guess this is more than enough for me. I am happy it works nicely.

Tuesday, May 4, 2010

Side effects and functional programming

What are side effects in programming?

When we call a function in a typical programming language (C, C++, Java, Python, etc.), the function gets some input arguments and returns an output value.

  • The function has some local variables which are lost after the function execution completes (no side effect)
  • The function may compute a value which it returns (no side effect)
  • If the arguments are references/pointers to some objects, the function may modify them (a side effect to the input arguments)
  • The function may modify some global variable (a side effect)
  • The function may output something on output or to a file or a socket (a side effect to the outside world with which the program is associated)
  • The function may read something from input or from a file or a socket (a side effect to the outside world with which the program is associated)
  • A member function may alter the state of the object with which it is associated (a side effect)

Essentially if the function is touching anything apart from computing a simple result and returning it, then the function is causing some form of side effect.

What is functional programming?

Functional programming is a programming paradigm where functions are free from side effects. i.e. they take some input values as arguments and generate an output value as result and do nothing else. They don't touch anything in the outside world.

This approach is useful since this allows for easy composition of functions to create more powerful functionality without worrying about any side effects. Since the functions don't have any side effects, hence their behavior are well understood and combining them becomes straight-forward. If you think about it, side-effect free functions are very close to mathematical functions (a mapping from a domain to a range thats all).

Can we live without side effects?

No. All kinds of IO is side effects. Most useful software requires some form of IO (files, networks, databases, GUIs, you name it). Hence a programming paradigm which doesn't support side-effects, is pretty much useless.

How functional programming works then?

So here is the trick. A well designed functional programming language has two parts. One part focuses on side effects (its a small part), while the rest of the language provides extensive support for pure functional programming (side-effect free). The program design focuses on clear separation between side-effect free computations and side-effect full user/system interfaces. The full power of techniques like currying, higher order functions, lazy evaluation, etc. is utilized in the functional part.

An example?

Here is a simple example which shows how to compute the square of a given number (in Haskell).

square x = x * x

main = print $ square 4

square is a function which computes the square of a given number. This is a side-effect free function. main uses this function to compute the square of four and print on standard output. main is side-effect full.

The language requires that effect free functions cannot call effect full functions while effect full functions can call other effect full functions as well as effect free functions. Thus the effect free part of the program is completely segregated.




Are C++ Raw Pointers First Class Objects?

I had this doubt nagging me for a long time whether C++ raw pointers are first class objects or not. Wikipedia had a certain definition about it and C++ raw pointers seemed to satisfy all the requirements. PPD (our Head of Engineering) had taken a lecture on RAII (Resource Acquisition Is Initialization) principle some time back and in that context he had suggested that C++ raw pointers are not first class objects. I wasn't fully sure whether I understood this well or not. So I raised this question on Stack Overflow (http://stackoverflow.com/questions/2695169/are-raw-c-pointers-first-class-objects).

It turned out that different people had different opinions about it. Some even trashed the Wikipedia definition. Finally I got PPD also on this discussion to provide a clear perspective on this. His answer can be seen from the above post in detail.

In short both "Pointers are first class objects" and "Pointers are not first class objects" statements are true. It depends purely on the context in which we are discussing about them.
If we are using the pointers merely to point to some data (some object) then they are first class object. If we are using the pointers to hold the data (hence have an ownership semantics attached to them) then they are not first class objects.

For more in depth explanation, read on the stack overflow link above.

Monday, January 11, 2010

Unloading DLLs in Python through CTYPES

How can I unload a DLL using ctypes in Python? - Stack Overflow discusses the issues related to unloading a DLL which has been loaded using ctypes in Python


Sunday, January 10, 2010

SCC - Trac

Streaming component combinators framework (a Haskell library) is a collection of streaming components and component combinators. As described on the website "The components operate on data streams, usually producing output before all input is known. "

This looks like an interesting library to explore in future.

Certified Programming with Dependent Types

Certified Programming with Dependent Types

This is the web site for an in-progress textbook about practical engineering with the Coq proof assistant. The focus is on building programs with proofs of correctness, using dependent types and scripted proof automation.

Saturday, January 9, 2010

Writer - Windows Live

Writer - Windows Live

Writer makes it easy to share your photos and videos on almost any blog service—Windows Live, Wordpress, Blogger, LiveJournal, TypePad, and many more.

It also has an Insert code plugin which helps you quickly format source code examples in your blog posts.

GLFW - An OpenGL library

GLFW - An OpenGL library: "GLFW is a free, Open Source, multi-platform library for creating OpenGL contexts and managing input, including keyboard, mouse, joystick and time. It is intended to be simple to integrate into existing applications and does not lay claim to the main loop."

A Techie Tech Writer Blog � Single-sourcing Training Exercises with Sphinx

A Techie Tech Writer Blog � Single-sourcing Training Exercises with Sphinx shows a nice example of how to use Sphinx to generate training exercises from Python source files.

Thursday, January 7, 2010

Tooltips in dijit.layout.TabContainer

Some time back I started using dijit.layout.TabContainer from DOJO Toolkit in my user interface. Soon a particular requirement came where I needed to attach tooltips to the tab headings in the tab container. In the following I outline the issues I faced and solutions I figured out for the same.

DOJO toolkit comes with a widget dijit.Tooltip which can be used to easily associate rich tooltips with any element in the page. It requires the "id" of the element with which the tooltip will be associated. After some experiments with Firebug, I figured out that when a dijit.layout.TabContainer is parsed, specific ids are assigned for the titles of content panes inside it. These ids look like:
  • dijit_layout__TabButton_0
  • dijit_layout__TabButton_1
  • dijit_layout__TabButton_2
  • and so on...
Depending upon your page structure and number of tab containers in the page, these ids would vary.

I first tried to add a declarative tooltip like as follows.


But as luck would have it, it didn't work. I guess the reason is the fact that the ids are assigned at runtime during parsing and probably when the tooltip was processed, the corresponding connect ids were not yet assigned. So I had to figure out an alternative solution.

dojo.addOnLoad(function(){setTimeout(function(){addTooltips();}, 1000);});

function addTooltips()
{
var tooltip = new dijit.Tooltip({
connectId: ["dijit_layout__TabButton_0"],
label : 'Hello World'
});
}

What this achieved was following:
  • Call a function 1 second after the page has been loaded. By this time, the ids for different titles for tabs inside the tab container are expected to be associated.
  • Create the tooltips at run time based on the generated ids.

This approach worked. May be there is a better way of doing this, but this works for me now :)