Wednesday, February 25, 2009

jQuery plugin: Add2Cart Example

I want to be free » Blog Archive » jQuery plugin: Add2Cart: "
This plugin implements visual effect of adding something to cart (busket). Visually it’s similar to Microsoft Word post-save visual effect, when a gray rectangular of page moves down to the toolbar.

Example of usage:

<input type='button' value='Add to cart'
onclick='$.add2cart( 'product1_id', 'cart_img_id' )' />

You can try it out at demo page."

32 tips to speed up your queries

32 tips to speed up your queries:
1. Use persistent connections to the database to avoid connection overhead.
2. Check all tables have PRIMARY KEYs on columns with high cardinality (many rows match the key value). Well,`gender` column has low cardinality (selectivity), unique user id column has high one and is a good candidate to become a primary key.
3. All references between different tables should usually be done with indices (which also means they must have identical data types so that joins based on the corresponding columns will be faster). Also check that fields that you often need to search in (appear frequently in WHERE, ORDER BY or GROUP BY clauses) have indices, but don’t add too many: the worst thing you can do is to add an index on every column of a table :) (I haven’t seen a table with more than 5 indices for a table, even 20-30 columns big). If you never refer to a column in comparisons, there’s no need to index it.
4. Using simpler permissions when you issue GRANT statements enables MySQL to reduce permission-checking overhead when clients execute statements.
5. Use less RAM per row by declaring columns only as large as they need to be to hold the values stored in them.
6. Use leftmost index prefix — in MySQL you can define index on several columns so that left part of that index can be used a separate one so that you need less indices.
7. When your index consists of many columns, why not to create a hash column which is short, reasonably unique, and indexed? Then your query will look like:

FROM table
WHERE hash_column = MD5( CONCAT(col1, col2) )
AND col1='aaa' AND col2='bbb';

8. Consider running ANALYZE TABLE (or myisamchk --analyze from command line) on a table after it has been loaded with data to help MySQL better optimize queries.
9. Use CHAR type when possible (instead of VARCHAR, BLOB or TEXT) — when values of a column have constant length: MD5-hash (32 symbols), ICAO or IATA airport code (4 and 3 symbols), BIC bank code (3 symbols), etc. Data in CHAR columns can be found faster rather than in variable length data types columns.
10. Don’t split a table if you just have too many columns. In accessing a row, the biggest performance hit is the disk seek needed to find the first byte of the row.
11. A column must be declared as NOT NULL if it really is — thus you speed up table traversing a bit.
12. If you usually retrieve rows in the same order like expr1, expr2, ..., make ALTER TABLE ... ORDER BY expr1, expr2, ... to optimize the table.
13. Don’t use PHP loop to fetch rows from database one by one just because you can ;) — use IN instead, e.g.

FROM `table`
WHERE `id` IN (1,7,13,42);

14. Use column default value, and insert only those values that differs from the default. This reduces the query parsing time.
15. Use INSERT DELAYED or INSERT LOW_PRIORITY (for MyISAM) to write to your change log table. Also, if it’s MyISAM, you can add DELAY_KEY_WRITE=1 option — this makes index updates faster because they are not flushed to disk until the table is closed
16. Think of storing users sessions data (or any other non-critical data) in MEMORY table — it’s very fast.
17. For your web application, images and other binary assets should normally be stored as files. That is, store only a reference to the file rather than the file itself in the database.
18. If you have to store big amounts of textual data, consider using BLOB column to contain compressed data (MySQL’s COMPRESS() seems to be slow, so gzipping at PHP side may help) and decompressing the contents at application server side. Anyway, it must be benchmarked.
19. If you often need to calculate COUNT or SUM based on information from a lot of rows (articles rating, poll votes, user registrations count, etc.), it makes sense to create a separate table and update the counter in real time, which is much faster. If you need to collect statistics from huge log tables, take advantage of using a summary table instead of scanning the entire log table every time.
20. Don’t use REPLACE (which is DELETE+INSERT and wastes ids): use INSERT … ON DUPLICATE KEY UPDATE instead (i.e. it’s INSERT + UPDATE if conflict takes place). The same technique can be used when you need first make a SELECT to find out if data is already in database, and then run either INSERT or UPDATE. Why to choose yourself — rely on database side.
21. Tune MySQL caching: allocate enough memory for the buffer (e.g. SET GLOBAL query_cache_size = 1000000) and define query_cache_min_res_unit depending on average query resultset size.
22. Divide complex queries into several simpler ones — they have more chances to be cached, so will be quicker.
23. Group several similar INSERTs in one long INSERT with multiple VALUES lists to insert several rows at a time: quiry will be quicker due to fact that connection + sending + parsing a query takes 5-7 times of actual data insertion (depending on row size). If that is not possible, use START TRANSACTION and COMMIT, if your database is InnoDB, otherwise use LOCK TABLES — this benefits performance because the index buffer is flushed to disk only once, after all INSERT statements have completed; in this case unlock your tables each 1000 rows or so to allow other threads access to the table.
24. When loading a table from a text file, use LOAD DATA INFILE (or my tool for that), it’s 20-100 times faster.
25. Log slow queries on your dev/beta environment and investigate them. This way you can catch queries which execution time is high, those that don’t use indexes, and also — slow administrative statements (like OPTIMIZE TABLE and ANALYZE TABLE)
26. Tune your database server parameters: for example, increase buffers size.
27. If you have lots of DELETEs in your application, or updates of dynamic format rows (if you have VARCHAR, BLOB or TEXT column, the row has dynamic format) of your MyISAM table to a longer total length (which may split the row), schedule running OPTIMIZE TABLE query every weekend by crond. Thus you make the defragmentation, which means more speed of queries. If you don’t use replication, add LOCAL keyword to make it faster.
28. Don’t use ORDER BY RAND() to fetch several random rows. Fetch 10-20 entries (last by time added or ID) and make array_random() on PHP side. There are also other solutions.
29. Consider avoiding using of HAVING clause — it’s rather slow.
30. In most cases, a DISTINCT clause can be considered as a special case of GROUP BY; so the optimizations applicable to GROUP BY queries can be also applied to queries with a DISTINCT clause. Also, if you use DISTINCT, try to use LIMIT (MySQL stops as soon as it finds row_count unique rows) and avoid ORDER BY (it requires a temporary table in many cases).
31. When I read “Building scalable web sites”, I found that it worth sometimes to de-normalise some tables (Flickr does this), i.e. duplicate some data in several tables to avoid JOINs which are expensive. You can support data integrity with foreign keys or triggers.
32. If you want to test a specific MySQL function or expression, use BENCHMARK function to do that.

Some of these hints are unapplicable if you use a framework because direct queries are uninvited guests in the case: focus on competent database optimization — tune indexes and server parameters.

More on queries optimization:

* Optimizing SELECT and Other Statements
* Optimizing for Query Speed (more about good index creating practices).

Tuesday, February 17, 2009

Differences Between Parameters and Arguments

Differences Between Parameters and Arguments:

In most cases, a procedure must have some information about the circumstances in which it has been called. A procedure that performs repeated or shared tasks uses different information for each call. This information consists of variables, constants, and expressions that you pass to the procedure when you call it.

To communicate this information to the procedure, the procedure defines a parameter, and the calling code passes an argument to that parameter.
You can think of the parameter as a parking space and the argument as an automobile. Just as different automobiles can park in a parking space at different times, the calling code can pass a different argument to the same parameter every time that it calls the procedure.


A parameter represents a value that the procedure expects you to pass when you call it. The procedure's declaration defines its parameters.

When you define a Function or Sub procedure, you specify a parameter list in parentheses immediately following the procedure name. For each parameter, you specify a name, a data type, and a passing mechanism (ByVal or ByRef). You can also indicate that a parameter is optional. This means that the calling code does not have to pass a value for it.

The name of each parameter serves as a local variable in the procedure. You use the parameter name the same way you use any other variable.


An argument represents the value that you pass to a procedure parameter when you call the procedure. The calling code supplies the arguments when it calls the procedure.

When you call a Function or Sub procedure, you include an argument list in parentheses immediately following the procedure name. Each argument corresponds to the parameter in the same position in the list.

In contrast to parameter definition, arguments do not have names. Each argument is an expression, which can contain zero or more variables, constants, and literals. The data type of the evaluated expression should typically match the data type defined for the corresponding parameter, and in any case it must be convertible to the parameter type."

Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming:
"Java is designed around the principles of object-oriented programming. To truly master Java you must understand the theory behind objects. This article is an introduction to object-oriented programming outlining what objects are, their state and behaviors and how they combine to enforce data encapsulation.

What Is Object-Oriented Programming?

To put it simply, object-oriented programming focuses on data before anything else. How data is modeled and manipulated through the use of objects is fundamental to any object-oriented program.

What Are Objects?

If you look around you, you will see objects everywhere. Perhaps right now you are drinking coffee. The coffee mug is an object, the coffee inside the mug is an object, even the coaster it's sitting on is one too. Object-oriented programming realizes that if we're building an application it's likely that we will be trying to represent the real world. This can be done by using objects.

Let's look at an example. Imagine you want to build a Java application to keep track of all your books. The first thing to consider in object-oriented programming is the data the application will be dealing with. What will the data be about? Books.

We've found our first object type - a book. Our first task is to design an object that will let us store and manipulate data about a book. In Java, the design of an object is done by creating a class. For programmers, a class is what a blueprint of a building is to an architect, it lets us define what data is going to be stored in the object, how it can be accessed and modified, and what actions can be performed on it. And, just like a builder can build more than more building using a blueprint, our programs can create more than one object from a class. In Java, each new object that is created is called an instance of the class.

Let's go back to the example. Imagine you now have a book class in your book tracking application. Bob from next door gives you a new book for your birthday. When you add the book to the tracking application a new instance of the book class is created. It is used to store data about the book. If you then get a book from your father and store it in the application, the same process happens again. Each book object created will contain data about different books.

Maybe you frequently lend your books out to friends. How do we define them in the application? Yes, you guessed it, Bob from next door becomes an object too. Except we wouldn't design a Bob object type, we would want to generalize what Bob represents to make the object as useful as possible. After all there is bound to be more than one person you lend your books to. Therefore we create a person class. The tracking application can then create a new instance of a person class and fill it with data about Bob.
What Is the State of an Object?

Every object has a state. That is, at any point in time it can be described from the data it contains. Let's look at Bob from next door again. Let's say we designed our person class to store the following data about a person: their name, hair color, height, weight, and address. When a new person object is created and stores data about Bob, those properties go together to make Bob's state. For instance today, Bob might have brown hair, be 205 pounds, and live next door. Tomorrow, Bob might have brown hair, be 200 pounds and have moved to a new address across town.

If we update the data in Bob's person object to reflect his new weight and address we have changed the state of the object. In Java, the state of an object is held in fields. In the above example, we would have five fields in the person class; name, hair color, height, weight, and address.
What Is the Behavior of an Object?

Every object has behaviors. That is, an object has a certain set of actions that it can perform. Let's go back to our very first object type – a book. Surely a book doesn't perform any actions? Let's say our book tracking application is being made for a library. There a book has lots of actions, it can be checked out, checked in, reclassified, lost, and so on. In Java, behaviors of an object are written in methods. If a behavior of an object needs to be performed, the corresponding method is called.

Let's go back to the example once more. Our booking tracking application has been adopted by the library and we have defined a check out method in our book class. We have also added a field called borrower to keep track of who has the book. The check out method is written so that it updates the borrower field with the name of the person who has the book. Bob from next door goes to the library and checks out a book. The state of the book object is updated to reflect that Bob now has the book.
What Is Data Encapsulation?

One of the key concepts of object-oriented programming is that to modify an object's state, one of the object's behaviors must be used. Or to put it another way, to modify the data in one of the object's fields, one of its methods must be called. This is called data encapsulation.

By enforcing the idea of data encapsulation on objects we hide the details of how the data is stored. We want objects to be as independent of each other as possible. An object holds data and the ability to manipulate it all in one place. This makes it is easy for us to use that object in more than one Java application. There's no reason why we couldn't take our book class and add it to another application that might also want to hold data about books.

If you want to put some of this theory into practice, you can join me in creating a Book class."

Tuesday, February 3, 2009

How to prevent browser caching : TechPitcher

How to prevent browser caching : TechPitcher: "
How to prevent browser caching

There are many ways you can prevent browser caching.
One of them is to include following meta tags, place these tags in head section of html document.
view plaincopy to clipboardprint?

1. <META HTTP-EQUIV='Pragma' CONTENT='no-cache'>
2. <META HTTP-EQUIV='Expires' CONTENT='-1'>

<META HTTP-EQUIV='Pragma' CONTENT='no-cache'>

For ASP pages use following script at the extreme beginning of the page
view plaincopy to clipboardprint?

1. <% Response.CacheControl = 'no-cache' %>
2. <% Response.AddHeader 'Pragma', 'no-cache' %>
3. <% Response.Expires = -1 %>

<% Response.CacheControl = 'no-cache' %>
<% Response.AddHeader 'Pragma', 'no-cache' %>
<% Response.Expires = -1 %>

In case of JSP pages use following code
view plaincopy to clipboardprint?

1. <%
2. response.setHeader('Cache-Control','no-cache');
3. response.setHeader('Pragma','no-cache');
4. response.setDateHeader ('Expires', -1);
5. %>

response.setDateHeader ('Expires', -1);

If you are generating your response in java or some other languages then you need to set following parameters in response header.
view plaincopy to clipboardprint?

1. response.addHeader('cache-control', 'no-cache');
2. response.addHeader('pragma', 'no-cache');
3. response.addHeader('expires', '-1');

response.addHeader('cache-control', 'no-cache');
response.addHeader('pragma', 'no-cache');
response.addHeader('expires', '-1');

All of the above method works on the response of the particular page and tell browser not the cache the response.

There is another way of telling browser to make a fresh request and don’t use the cached content for the page if any. This is done by appending some random characters to requested url. Below is sample code
view plaincopy to clipboardprint?

1. <script>
2. var url = '';
3. url += '?preventCache='+ Math.floor(Math.random()*100000);
4. </script>

var url = '';
url += '?preventCache='+ Math.floor(Math.random()*100000);

This will create a random url every time and won’t allow browser to use cache content."

C++ : TechPitcher

C++ : TechPitcher: "
Implement strtok() function. (It tokenizes the string )

Implementation of strtok
view plaincopy to clipboardprint?

1. char* strtok(char *s, const char *delim) {
2. static char *old = NULL;
3. char *token;
4. if(! s) {
5. s = old;
6. if(! s) {
7. return NULL;
8. }
9. }
10. if(s) {
11. s += strspn(s, delim);
12. if(*s == 0) {
13. old = NULL;
14. return NULL;
15. }
16. }
18. token = s;
19. s = strpbrk(s, delim);
20. if(s == NULL) {
21. old = NULL;
22. } else {
23. *s = 0;
24. old = s + 1;
25. }
26. return token;
27. }

char* strtok(char *s, const char *delim) {
static char *old = NULL;
char *token;
if(! s) {
s = old;
if(! s) {
return NULL;
if(s) {
s += strspn(s, delim);
if(*s == 0) {
old = NULL;
return NULL;

token = s;
s = strpbrk(s, delim);
if(s == NULL) {
old = NULL;
} else {
*s = 0;
old = s + 1;
return token;

Write implementation of memcpy and memmove functions? What is the difference between the two?
Implementation of memcpy
view plaincopy to clipboardprint?

1. void memcpy(void* dest, void* src, int n_size) {
2. char* d = (char*) dest;
3. char* s = (char*) src;
4. while(n_size-- > 0) {
5. *d++ = *s++;
6. }
7. }

void memcpy(void* dest, void* src, int n_size) {
char* d = (char*) dest;
char* s = (char*) src;
while(n_size-- > 0) {
*d++ = *s++;

Implementation of memmove

1. void memmove(void* dest, void* src, int n_size) {
2. char* d = (char*) dest;
3. char* s = (char*) src;
4. if(d > s) {
5. while(n_size-- > 0) {
6. *d-- = *s--;
7. }
8. } else {
9. while(n_size-- > 0) {
10. *d++ = *s++;
11. }
12. }
13. }

void memmove(void* dest, void* src, int n_size) {
char* d = (char*) dest;
char* s = (char*) src;
if(d > s) {
while(n_size-- > 0) {
*d-- = *s--;
} else {
while(n_size-- > 0) {
*d++ = *s++;

memmove ensure correct copying when the two buffers overlap.

What is a dangling pointer?
A dangling pointer is a pointer to memory that is no longer allocated. The pointer still points to the memory which earlier was allocated for the data. The data is deleted and the memory may now be used with some other purpose.
view plaincopy to clipboardprint?

1. {
2. char *danglingPointer = NULL;
3. /* ... */
4. {
5. char localChar;
6. danglingPointer = &localChar;
7. }
8. /* Memory was allocated to danglingPointer in the block. */
9. /* As soon as program is out of block dandlingPointer points to Memory, */
10. /* which is free for other use.*/
11. }

char *danglingPointer = NULL;
/* ... */
char localChar;
danglingPointer = &localChar;
/* Memory was allocated to danglingPointer in the block. */
/* As soon as program is out of block dandlingPointer points to Memory, */
/* which is free for other use.*/

What is a double pointer? Why is it required? Is it necessary in C++?
Pointer to a pointer is called double pointer. It is needed when one wants to manipulate the pointer itself like in linked list manipulation etc. In C++ same thing can be accomplished using reference which also avoids the overhead of copying."

Embedded : TechPitcher

Embedded : TechPitcher: "
What is watchdog timer?
Watchdog timer is hardware circuitary tightly integrated into embedded systems’ CPU to have a watch on embedded system’s working. It has ability to detect if embedded system is entered into a hanged state. It then resets the embedded system so that it doesn’t remain in hanged state indefinately. Watchdog timer is generally used in embedded systems where their is no human intervention present to reset it when system hangs. As its name suggests watchdog timer is a timer circuitary which keeps on counting and expires until reset. Embedded system software is expected to restart the timer regularly to prevent it from expiring under normal conditions. When systems hangs the timer is not restarted and it expires to give an indication to the system to restart.

How many ways shared data problem can be solved?
1. Disabling interrrupts - to be used when data is shared between ISR and task code. note that scheduler would not be able to switch tasks as interrupts are disabled.
2. Using semaphore - can be used when data is not to be used in ISR as semaphores are not allowed in ISR.
3. Disabling task switches - to be used when data is not shared among ISR and task code.

What is deadly embrace or dead lock?
Dead lock or deadly embrace is another fancy name given to priority inversion.

What is priority inversion?
Priority inversion is a phenomenon which happens when different priority tasks shares common data is a particular fashion. Say task A is higher priority task than task B and they both shares common data say x. Say task B was running and it locks x for its use while task A interrupted and got control now when task A needs to access x it would be able to because control would never be given back to task B to release x. Hence higher priority task is blocked by lower priority task, which is reffered to as priority inversion.

What is mutex?
Mutex is short form of mutual exclusion. It is very much silimar to semaphore and the names are used interchangably in different opperating systems. The semaphore which are task attached i.e. the task which had acquired the sempahore will only be allowed to release it, are generally termed as Mutex.

What is semaphore?
Semaphore is a hardware or software flag. It is facility provided by operating system. In multitasking systems, a semaphore is a variable with a value that indicates the status of a common resource. It’s used to lock the resource that is being used. A process needing the resource checks the semaphore to determine the resource’s status and then decides how to proceed.

What is a critical section in embedded software programs?
Critical Section is a set of instructions that must be atomic for system to work properly. Several techniques are used to ensure that a piece of code is atomic, some of which are semaphore, mutex etc.

What is volatile variable?
volatile is a keyword to indicate compiler that the variable it is used with should not be assumed to be unchanged during the course of execution of the code. Most compilers do optimizations which assumes that variable will not be changed until software is changing it. Refer following piece of code to understand it further:
view plaincopy to clipboardprint?

1. int count = 10;
2. if(count < 20) {
3. //do something
4. }

int count = 10;
if(count < 20) {
//do something

In this code, compiler can not remove if check for optimization. The value of count can be changed between assignment and if check by some other process.

What is UART?
UART is universal asynchronous receiver and transmitter. It is used in many embedded systems for interfacing with other devices. Its purpose is to convert data to and from serial interface. A very popular standard for serial interface is RS-232."

Monday, February 2, 2009

Learn Python in 10 minutes | Poromenos' Stuff

Learn Python in 10 minutes | Poromenos' Stuff [List Comprehensions]: ">>> lst1 = [1, 2, 3]
>>> lst2 = [3, 4, 5]
>>> print [x * y for x in lst1 for y in lst2]
[3, 4, 5, 6, 8, 10, 9, 12, 15]
>>> print [x for x in lst1 if 4 > x > 1]
[2, 3]
# Check if an item has a specific property.
# 'any' returns true if any item in the list is true.
>>> any(i % 3 for i in [3, 3, 4, 4, 3])
# Check how many items have this property.
>>> sum(1 for i in [3, 3, 4, 4, 3] if i == 3)
>>> del lst1[0]
>>> print lst1
[2, 3]
>>> del lst1"