Break and Wrap a long word

A situation occurred while doing chat implementation. Someone just typed a long word which was way larger than the div container. The entire page started looking ugly with that single chat message because it extended outside the chat div. I found a solution with the help of Google in css(I feel it’s css3).

word-wrap: break-word;

This one will break the word and wrap it in the defined div. word-wrap has another option, normal, which will keep the word in the same form.

Advertisements

Scroll Button Positioning

If you are using scroll for a div that you created, by default the scroll will be at the top of the div. In some cases you may be required to position it to the bottom of the div. For example(happened in my case, if you are creating a chat app, the scroll button needs to be at the bottom(in most cases). You can do this in using simple JavaScript code.

In simple JavaScript:

    var objDiv = document.getElementById("your_div");
    objDiv.scrollTop = objDiv.scrollHeight;

If you are using jQuery, it becomes more easy:

    $("#mydiv").scrollTop($("#mydiv")[0].scrollHeight);

Python ValueError: bad marshal data

Today I came across a strange error, first time I encountered with such an error.

ValueError: bad marshal data

I couldn’t find the exact reason causing this error. From my view some of the compiled python(.pyc) file got corrupted. So what I did is, removed all the .pyc file from my system, as I don’t know the exact file which caused this bug.

find / -iname \*.pyc -exec rm {} \;

This command will find all the files with .pyc extension(case insensitive) and delete those files without asking for your permission each time.

Adding Contents Dynamically in Jquery Mobile

I’ve started using Jquery Mobile recently for developing a site for mobile platforms. Actually the basic designing is very simple and is described in the official demo/documentation. I met with problems when I dynamically added html content. The two problems I came accross are described below with solution.

Unable to get the default style on dynamically added content

I had to insert an html content, the content comes after an ajax call. I simply did
$('#form-block').append(data)
it shows the content in data, but the styles were missing.

I could figure out that the problem is because the DOM was completely loaded before the data was added. So the styling could not be obtained.

Solution

We can make use of trigger function to get the styling done on the data.
$('#form-block').append(data).trigger('create')

trigger will execute all handlers and behaviors of the matched element for the given event type. In this case create is the event type. It’ll make the data to be created with all style element.

Unable to bind an event on a dynamically added selector(id/class)

I added a new class on the fly(using normal javascript), bind an event with this class on DOM ready. But the event was not getting triggered on calling the event.
$(".slide-in").click(function () {
    $(this).removeClass("slide-up").addClass("slide-up-min");

Solution

The reason for the event not getting triggered is, it is bind to the selector on DOM ready. The selector was absent initially. The above usage is same as using bind, which will only do the bind before DOM is loaded.
$(".slide-in").bind('click', function () {
    $(this).removeClass("slide-up").addClass("slide-up-min");

We have to use a method which will bind the event even after the DOM is loaded completely. live or delegate method can be used in this situation.
$(".slide-in").live('click', function () {
    $(this).removeClass("slide-up").addClass("slide-up-min");

delegate vs live

delegate is similar to live, but in delegate nesting can be done. Difference can be explained using an example, we want to add the click event to all anchors inside the class slide-in. If we are using live we have to use a selector for all the anchors(say, class anchor).
$(".anchor").live('click', function () {
    $(this).removeClass("slide-up").addClass("slide-up-min");

Whereas if we are using delegate there is no need to add a new selector. We can do the same thing as
$(".slide-in").delegate('a', 'click', function () {
    $(this).removeClass("slide-up").addClass("slide-up-min");

Database Migration in Django using South

When I started using Django, if I came across a situation where I’ve to change the max_length of a charfield(for example if I want to change the length from 3 to 4) what I normally did was delete the entire database and start from the beginning using syncdb. At that time I was thinking what will happen if the data in the db are important, I continued to use the same method as I was not handling db populated with client data. But the requirement soon came. I’ve to write sql query inorder to change the field structure. It was a hard process(as I was less familiar with writing sql queries). At that time I came to know about an app built in Python to do the process automatically(basic usage), South.

South brings migrations to our Django applications.

You can install South either by pip or easy_install

  • pip install south

South have two types of migrations:

  • schemamigration(migration for schema change)
  • datamigration(migration for data)

Using South with a New App

Create a new Django project and add a new app(let’s name it web). Add a class to models.py
class Poll(models.Model):
    name = models.CharField(max_length=100)
    published = models.BooleanField()

For automatic migration we have two options initial and auto. auto will look for previous migration and create a new migration which applies the difference. But if we are using South for first time, we don’t have any previous migration. Here comes the role of initial. It’ll create the first migration. It works almost similar to syncdb. Afterwards we use auto.

Instead of running syncdb, execute the following command:
shinu@odol:~/login$ python manage.py schemamigration web --initial
Creating migrations directory at '/home/users/shinu/venvs/login/login/web/migrations'...
Creating __init__.py in '/home/users/shinu/venvs/login/login/web/migrations'...
+ Added model web.Poll
Created 0001_initial.py. You can now apply this migration with: ./manage.py migrate web

On executing the above code, a new folder(migrations) will be created inside your app folder(web). It will contain the migration files.

And inorder to apply the changes to your db you’ve execute:
shinu@odol:~/login$ python manage.py migrate web
Running migrations for web:
 - Migrating forwards to 0001_initial.
 > web:0001_initial
 - Loading initial data for web.
No fixtures found.

What we have done is similar to what syncdb does. Now comes the real play of South. Now if we want to add a new field to the class Poll.
class Poll(models.Model):
    name = models.CharField(max_length=100)
    published = models.BooleanField()
    latest = models.BooleanField()

As we are using South we need only two steps to make db know we’ve added a new field. First create a schemamigration with auto feature(because we’ve already created a migration with initial feature) and then migrate the db using the file created by schemamigration.
shinu@odol:~/login$ python manage.py schemamigration web --auto
 + Added field latest on web.Poll
Created 0002_auto__add_field_poll_latest.py. You can now apply this migration with: ./manage.py migrate web

You can now apply the migration
shinu@odol:~/login$ python manage.py migrate web
Running migrations for web:
 - Migrating forwards to 0002_auto__add_field_poll_latest.
 > web:0002_auto__add_field_poll_latest
 - Loading initial data for web.
No fixtures found.

A new column latest will be added to your table.

Using South in an Existing App

In many case you may need to install South after working on an app a bit. In that case you have to first convert you existing app to a app using South. You have to perform the following steps:

  • Install South and add south to your INSTALLED_APPS in settings.py
  • Run python manage.py syncdb
  • Run ./manage.py convert_to_south web

That’s it.

If you are working in a team and using any version control system, you have to commit this migration. And every other member have to perform a syncdb and then run
./manage.py migrate myapp 0001 --fake
on their machine after pulling code.

But if you are using a fresh installation of the same codebase, you just have to run syncdb and a normal migration.

Advanced Uses

Upto now we just saw the basic usage of South. Let’s find something advance.

Add a column length to the model class Poll:
class Poll(models.Model):
    name = models.CharField(max_length=100)
    published = models.BooleanField()
    latest = models.BooleanField()
    length = models.IntegerField(null=False)

The length field is not nullable and doesn’t have a default given. So the problem here is South doesn’t know whether our database have any value stored or not. It just assumes that the db contains some data. And now we are adding a new column which is not having a default value or can be made nullable. If that field is nullable South will save null to all the existing data. In this case it will prompt for the user to do the needful.

python manage.py schemamigration web --auto
 ? The field 'Poll.length' does not have a default specified, yet is NOT NULL.
 ? Since you are adding this field, you MUST specify a default
 ? value to use for existing rows. Would you like to:
 ? 1. Quit now, and add a default to the field in models.py
 ? 2. Specify a one-off value to use for existing columns now
 ? Please select a choice: 2
 ? Please enter Python code for your one-off default value.
 ? The datetime module is available, so you can do e.g. datetime.date.today()
 >>> 0
 + Added field length on web.Poll
Created 0003_auto__add_field_poll_length.py. You can now apply this migration with: ./manage.py migrate web

In this case what I’ve done is simply given a default value(0) to existing db data. If I have selected option 1, the command will quit automatically. We have to manually goto models.py and add a default value and run the schemamigration again.

Apply the migration normally
./manage.py migrate web
Running migrations for web:
 - Migrating forwards to 0003_auto__add_field_poll_length.
 > web:0003_auto__add_field_poll_length
 - Loading initial data for web.
No fixtures found.

Data Migration

Some case may come in which you want to modify a field(for example from IntegerField to ForeignKey), but you need the values stored in that field to compute the new value as you cannot give a default value or make it null. In that case South comes with data migration. We can view data migration with an example(it’s the best way to explain it).

In the existing Poll class let’s add a new field.
comment_id = models.IntegerField()
Let it store the id of Comment class. Apply the necessary schemamigration and migrate the app.

Now I want to change the comment_id field to a field which is a ForeignKey to the comment. That means I’ve to make use of all comment_id‘s and have to find corresponding comment. This can be done with 3 migrations: first a schemamigration, then a data migration and finally again a achemamigration.

Let me explain it in the following steps:

Step1:

Add the new field with null=True to Poll class:
comment = models.ForeignKey(Comment, null=True)

Do a schemamigration for this change:
python manage.py schemamigration web --auto
If you’ve defined the class Comment after the class Poll you’ll get a name error:
NameError: name 'Comment' is not defined

You can get rid of this error in two ways:

  • move the class Comment before Poll
  • modify the field comment as following
    comment = models.ForeignKey('Comment', null=True)

python manage.py schemamigration web --auto
 + Added field comment on web.Poll
Created 0005_auto__add_field_poll_comment.py. You can now apply this migration with: ./manage.py migrate web

Step2:

Now we’ve to do a datamigration. Use the field comment_id to populate the field comment, which is null now. Usage of datamigration is a little bit different. We have to create a new migration file and manually edit it. After that apply the migration as normal.
python manage.py datamigration web poll_comment_added
Created 0006_poll_comment_added.py.

A new file with name 0006_poll_comment_added.py is created in migration folder. The last parameter is the name of the migration, which you can name at your choice. Now open the file to edit. You will have to edit two methods: forward and backward.

def forwards(self, orm):
    "Write your forwards methods here."
    for poll in orm.Polls.objects.all():
        poll.comment = orm.Comment.objects.get(id=poll.comment_id)
        poll.save()

forwards will populate the comment field using comment_id field.
def backwards(self, orm):
    "Write your backwards methods here."
    raise RuntimeError("Cannot reverse this migration.")

backwards is set to raise an exception as datamigration is an irreversible process.

Step3:

Now do a schemamigration after removing the field comment_id
python manage.py schemamigration web --auto
 ? The field 'Poll.comment_id' does not have a default specified, yet is NOT NULL.
 ? Since you are removing this field, you MUST specify a default
 ? value to use for existing rows. Would you like to:
 ? 1. Quit now, and add a default to the field in models.py
 ? 2. Specify a one-off value to use for existing columns now
 ? 3. Disable the backwards migration by raising an exception.
 ? Please select a choice: 3
 - Deleted field comment_id on web.Poll
Created 0007_auto__del_field_poll_comment_id.py. You can now apply this migration with: ./manage.py migrate web

South is asking for a default value for comment_id because if you have to reverse this migration, South will try to add this default value when reversed. In this case I’ve selected choice 3, and if again we try to reverse this migration South will raise an exception.

Migrate the database:
./manage.py migrate web
Running migrations for web:
 - Migrating forwards to 0007_auto__del_field_poll_comment_id.
 > web:0006_poll_comment_added
 - Loading initial data for web.
No fixtures found.

Common Error

One error I came across while I tried to use datamigration is a KeyError, eg:
KeyError: "The model 'user' from the app 'web' is not available in this migration."
In this case I tried to use User class provided by Django in my forwards method. We have to modify the forwards method in such a way that wherever we are using orm.User change it to orm['auth.User'].

PostgreSQL OperationalError in Django

One of the common exceptions I came across while using PostgreSQL with Django is OperationalError. The error description appears as follow:

  • FATAL: Ident authentication failed for user “username”

The reason for this error according to my findings is you may have given ‘ident’ authentication for all local users. Ident authentication is one of the methods used by PostgreSQL to authenticate the user. The ident authentication method works by obtaining the client’s operating system user name, then determining the allowed database user names using a map file that lists the permitted corresponding pairs of names(courtesy-PostgreSQL). You may have created the user, who can access the database with full power, with a password. And this password is generally hashed by md5.
By default all the local access are set to ident authentication in PostgreSQL. You can find the details in the file ‘pg_hba.conf’.

Solution

First, locate the ‘pg_hba.conf’ file in your linux machine. You can use the command:

  • locate pg_hba.conf

In my system it was located in ‘/etc/postgresql/8.4/main/’ folder. For you it may be different according to the directory in which you installed PostgreSQL.
Now open the file(pg_hba.conf) in edit mode. You will find a line similar to the following:

  • # “local” is for Unix domain socket connections only
  • local all all ident

You have to change the line to:

  • local all all md5

Restart PostgreSQL:

  • /etc/init.d/postgresql restart

Now the exception should vanish.

PostgreSQL Installation in Linux(Python)

PostgreSQL

PostgreSQL is a powerful, open source object-relational database system. It runs on all major operating systems, including Linux, UNIX and Windows. It has native programming interfaces for C/C++, Java, .Net, Perl, Python, Ruby, Tcl, ODBC.

Install PostgreSQL in your Linux Machine

If you are using Ubuntu you can use the apt command

  • apt-get install postgresql

and if you are using Pardus you can use pisi

  • pisi it postgresql

Create a Database and grant permissions to Users

Add a Linux/UNIX user called odol

  • adduser odol
  • passwd odol

This’ll create the user odol. This is not a required step. This is only for testing purpose. You can use any existing user also.

Becoming a superuser and connect to database server

  • su – postgres

This user will get created automatically when we install PostgreSQL.

  • psql template1

If you are not becoming a superuser, you can do the following

  • psql -d template1 -U postgres

Add a user called odol and Create a database called mydb and Grant Permissions

By the execution of last command, you’ll enter the postgres shell. As the db is template1, the prompt will be template=#

  • CREATE USER odol WITH PASSWORD ‘myPassword’;
  • CREATE DATABASE mydb;
  • GRANT ALL PRIVILEGES ON DATABASE mydb to odol;
  • \q

Enter as odol and test

  • su – odol
  • psql -d mydb -U odol

This will let you get into the shell for mydb database. In which you can create table and do other database activities and queries.

Using PostgreSQL with Django

In order to use Python with PostgreSQl we need an adapter. Psycopg is the most popular PostgreSQL adapter for the Python programming language.
Install the following requirements first

  • apt-get install python-dev libpq-dev

We can get pyscopg using pip or easy_install

  • pip install pyscopg2

Common Errors while installing pyscopg2

The most common error(the one I came across) while installing pyscopg2:

  • Error: pg_config executable not found.

Make sure you have installed python-dev and libpq-dev in your system. The step is already mentioned above.

Admin for PostgreSQL(Graphical)

pgAdmin is an Open Source administration and development platform for PostgreSQL. It provide the graphical interface. And also have an editor in which you can create SQL query and execute it.

Installing Drupal

Drupal is a Content Management System. Drupal allows a easy way of development of websites, without coding a single line. Thus it make even the novice user to develop a website. Apart from the core module it contain thousands of add-on module.

Installation of Drupal is a little bit tricky. The detail description of how to install Drupal is given on the site http://drupal.org/. The main problem with the installation is the permission problems. If a new user is trying to use Drupal try to install in a place where permission is not a problem, better try to do it in a folder named ‘drupal’ in the home folder itself. A specialized user can install it in the place mentioned in the installation file.

The first step is to download the latest release of Drupal from the official site. Untar the .tgz file and move it to a folder named html in the drupal folder placed in the home folder. We must also move the ‘.htaccess’ file.

In sites/default contain a file named ‘default.settings.php’. We must make a copy of this file and name it ‘settings.php’. This file is used as the user settings file. The content will be automatically configured during the install process.

To run the file ‘install.php’, in order to install Drupal, our system must be equipped with some softwares. They are as follows:

  1. apache2
  2. php5-mysql
  3. libapache2-mod-php5
  4. mysql-server

As the ‘install.php’ lies inside the home folder, we must change the web servers default page settings. i.e. if we run 127.0.0.1 in our browser a default page will be displayed. We can change it by changing the path in the configuration file of apache2.

The folder contain a file named ‘default’, we have to alter a couple of lines in this file. The first line is

Replace it with

‘/home/odolshinu/’ is my home folder.

The second line and its replacement strings are

After doing this is to create a database for Drupal alone which will store all the content of the site we are going to build. Drupal must have full access to the database, hence grant all the permission for the database.

After completing all these steps, we can simply run a browser and run the install script, i.e. 127.0.0.1/install.php. All further installation is done using a user interface.

A problem which I faced during the installation is that whenever I tried to run a .php file in a browser, the .php file simply gets downloaded. The problem was, the apache web server don’t know what to do with .php file. It only know what to do with .html file. Thus I’ve to properly install ‘libapache2-mod-php5’.

Pygame – Game Module for Python

Python is a language which is easy to study and program. Development of games in Python is a easy job, as it provide a specialized game module named pygame. With usual Python modules we can develop only textual games. For the development of graphical games the pygame module is needed.

Let us see the common usage of this module with the help of some small examples.

There are two things to be imported for the use of pygame in graphical game development.

The first step to do is to set up up pygame.

Next step is to set up the window for the game. An object is created, for further use, deployment of some images to the surface can be made using this object

Color is given as a tuple with three elements. As it is tedious step to type the full tuple every time, we can create a constant which holds this tuple and can be used whenever needed.

If we want to add a text to the window, first we have to select a font style and a font size.

None gives the default font style and 48 gives the size. In-order to set up the text

An object of the text, textRect, is made.

To fill the background with a specific color

Geometrical figures can be drawn easily, a blue filled circle can be drawn as

In-order to print the text we have created to the window we have to use the keyword blit.

Until now nothing will be displayed on the screen. It will take time to draw something to screen. Thus if we try to draw on the surface each time we create a new object it will create a big delay. In-order to avoid this delay all the updates are written to the screen after a update keyword is used.

A game loop runs until the user explicitly tells to terminate. All the events occurred during a single iteration can be obtained using

If an explicit signal to quit occurs the window is shutdown.

Understanding MSP430 Timer_A

Timer_A is a 16-bit timer/counter. We can understand some features of the Timer_A using a simple code. The Timer_A has a register TAR which holds a the current count of the timer. There are 3 different modes of counting in Timer_A. One will count up to ffffh and again start from 0, other one count up to a defined value and again starts from 0 and the last one counts up to a defined value and counts back to 0.

  • Timer Control Register

TSSELx

These are the 8th and 9th bits of the register. These two bits select the source of the clock for the timer. Subsystem master clock(SMCLK) is used in this situation. This is the clock provider for all the peripherals. To select the SMCLK the 9th and 8th bit must be 1 and 0 respectively.

IDx

These are the 6th and 7th bits of the register. These two bits select which clock frequency must be taken, whether to take the same SMCLK or divide it by 2, 4 or 8.

MCx

These are the 4th and 5th bits in the register. The selects the counting nature of the timer. In this case we select a continuous mode i.e. the count will reach up to ffffh and then overflows to 0 and the count restart. To select this mode 4th and 5th bits must be 0 and 1 respectively.

TACLR

This is the second bit. Setting this bit resets the TAR, the clock divider and the count direction.

TAIFG

0th bit of the register. On overflow of the timer this bit is automatically set.

The following code try to blink between red and green led on overflow of the clock. Between two overflow there is a delay and it is used to light a led. Code has two functions init and delay. init initializes all timer and delay causes the delay.

The watchdog timer must be disabled otherwise there may be frequent resetting of the device.

The init function:

This function do all the initializations. The first step will disables the watchdog timer. The second step will make configure the two led’s as output pin. The third step will select the clock source, input divider, mode control and timer clear. All the uppercase words are macros. MC_2 will select the continuous up mode. If the macro was MC_1, the selected mode will be up mode. In this case what the macro do is, it will left shift the digit 2 by 4 position making the 5th and 4th bit 1 and 0 respectively. It’s similar in case of ID_0 and TASSEL_2.

This function produces the delay. It checks when the count overflows i.e. when the 0th bit is set. Until the a busy looping is done. Once the overflow occurs, the control comes out of the loop and manually reset the 0th bit to 0.

This while loop is an infinite loop. First a delay is called and then the red led blinks and again we call a delay. For that delay time the red led remains and after that delay the green led blinks and red sleeps. This process is continued in an infinite loop.