Announcement

Wednesday, August 08, 2012

Useful code snippets for knockoutjs - Part 1

1. Function 'deferComputed' to create a computed observable with deferred evaluation.

Many times we want to create  'computed' observable with deferred evaluation. The syntax to create it is somewhat complex. So this is just a convenience function.

 deferedComputed = function(readfunc){  
   return ko.computed({read:readfunc, deferEvaluation:true});  
 };  

Now to create deferred computed observable, you can use var
 deferedObs = deferedComputed(function() { /* code to compute the observables value */ });  

2. yes/no binding:

Suppose you have observable that contains a Boolean value (true/false), many times it is not appropriate to display this value as 'true/false'. It is better to display this value as 'yes or no'.  'YesNo' binding converts a boolean variable into 'yes' or 'no' text.

 ko.bindingHandlers.yesno = {  
   update: function(element,valueAccessor){  
     var text = 'no';  
     var value = ko.utils.unwrapObservable(valueAccessor());  
     if(value) { text = 'yes'; }  
     $(element).text(text);  
   }  
 };  

Wednesday, July 11, 2012

Django connection pooling using sqlalchemy connection pool

As you know, Django uses new database connection for each request. This works well initially. However as the load on the server increases, creating/destroying connections to database starts taking significant amount of time.  You will find many questions about using some kind of connection pooling for Django on sites like StackOverflow . For example, Django persistent database connection. 

At BootStrapToday we use sqlalchemy's connection pooling mechanism with Django for pooling the database connections. We use variation of approach by Igor Katson described in http://dumpz.org/67550/.  Igor's approach requires patching Django which we wanted to avoid. Hence we created a small function that we import in one of __init__.py (or models.py) (i.e. some file which gets imported early in the application startup).


import sqlalchemy.pool as pool
pool_initialized=False

def init_pool():
     if not globals().get('pool_initialized', False):
         global pool_initialized
         pool_initialized = True
         try:
             backendname = settings.DATABASES['default']['ENGINE']
             backend = load_backend(backendname)

             #replace the database object with a proxy.
             backend.Database = pool.manage(backend.Database)

             backend.DatabaseError = backend.Database.DatabaseError
             backend.IntegrityError = backend.Database.IntegrityError
             logging.info("Connection Pool initialized")
         except:
             logging.exception("Connection Pool initialization error")

#Now call init_pool function to initialize the connection pool. No change required in the
# Django code.
init_pool()

So far this seems to be working quite well.

Tuesday, June 19, 2012

CSS and Icon sprites - tips and tricks

[NOTE : This post was originally published on  BootStrapToday blog as "CSS and Icon sprites – tips and tricks"]

We used image sprites for icons on bootstraptoday.com for version 2.0 and also in the latest version that we are working on (version 3). Quickly I realized that making sure that the icons looks same on major browsers is a task in itself.  For example, when you have an empty 'span' element which is supposed to display the icons, different browser will treat it slightly differently. Some browsers will give it a height/width of 1 character, some browsers height same as line height but width will be 0. If your icons are not arranged properly then putting those icons on buttons with consistent look & feel is a nightmare.  So here are few tips to define the icon image sprites and to use them effectively.

  1. First and most important tip is to have single sized icons in one sprite and arrange them in a grid. So if you have two icon sizes (e.g. 16px and 24px), make two sprites. One for 16px icons arranged on 16px X 16px grid. Another for 24px icons arranged on 24px X 24px grid.  Check the twitter-bootstrap icons.

  2. Use LessCSS or (some other equivalent) to define the icons css.

  3. Use span as 'display:inline-block'.  Typically span elements are inline elements. And you cannot define width/height of an inline element. Since we need to place the icons inline but need the flexibility of defining width/height, use 'display:inline-block'.

  4. Usually set the 'vertical-align:text-top'. This will align the icons to text.

  5. Use content:"". It will satisfy browsers which need to see text inside the span.
Here is a sample .less css fragment to be used with an icon sprite and
@icon-sprite-path:url(../images/icongrid.png);     /* url of the image path */
@icon-grid-size:16px;

.icongrid {
background-image:@icon-sprite-path:
background-repeat:no-repeat;

/* the element should be placed as 'inline' but we need flexibility to define width/height, padding etc*/
display:inline-block;

/* to ensure that each span is 'icon-grid-size' by 'icon-grid-size' square */
padding:@icon-grid-size/2;

/* to satisfy browsers which don't like empty elements */
content:"";

/* align the icons with text */
vertical-align:text-top;

}

/* define individual icon positions in sprite */
.testicon { background-position:0 -16px; }

Now you can use the icons with spans. For example to append the 'test icon' to some text, use
<div> ... your text here
<span class='icongrid testicon"></span>
</div>

Acknowledgement : I picked up some of these ideas by going over the twitter-bootstrap css and icon sprites.