OS

Solve add partition in etc/fstab in Debian not being mounted

30 Aug , 2012  

I use Hpcloud with Debian Image on Small instance. As usual, I load additional/extra hardisk into another folder in filesytem (/var for instance). But somehow it’s doesn’t works at all. Here are the steps and solutions:

1. Check partition
You can check all partition device by :

1
fdisk -l

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Disk /dev/vda: 10.7 GB, 10737418240 bytes
16 heads, 63 sectors/track, 20805 cylinders
Units = cylinders of 1008 * 512 = 516096 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/vda doesn't contain a valid partition table

Disk /dev/vdb: 21.5 GB, 21474836480 bytes
16 heads, 63 sectors/track, 41610 cylinders
Units = cylinders of 1008 * 512 = 516096 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/vdb doesn't contain a valid partition table

Disk /dev/vdc: 53.7 GB, 53687091200 bytes
16 heads, 63 sectors/track, 104025 cylinders
Units = cylinders of 1008 * 512 = 516096 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

Disk /dev/vdc doesn't contain a valid partition table

More…

Django

How to disable add / view links in Django Admin

30 Aug , 2012  

This is most simple steps that frequently used when we want to showing Log / Histories of Models in Django Admin.
Sometimes we don’t want to give detail/view links for record Models in Django Admin. We can disable them with :

1
2
3
4
5
6
7
8
class InsuranceHistoryAdmin(admin.ModelAdmin):
    """Paypal History Logger"""
    list_display = ('id', 'email', 'activation', 'account',
                    'created', 'modified', 'payment_status')

    def __init__(self, *args, **kwargs):
        super(InsuranceHistoryAdmin, self).__init__(*args, **kwargs)
        self.list_display_links = (None, )

Yes, you see that “self.list_display_links = (None, )” is our saviour.

Then, to disable add permission / delete permission, it simply as :

1
2
3
4
5
def has_add_permission(self, request):
    return False

def has_delete_permission(self, request, obj=None):
    return False

,

Django

Solve Ipython in Django Shell_Plus AttributeError: ‘module’ object has no attribute ‘Shell’

27 Aug , 2012  

Python manage.py shell_plus is a powerfull-tools that we will load all application from settings.py in Django. We no longer need to doing manual import to access some models. Ipython also another grandioso tools that provide best coloring syntax. Combining this both tools will made our day happy. But, sometimes you facing this problem when running django manage.py shell_plus :

1
AttributeError: 'module' object has no attribute 'Shell'

Then solution for this problem is easy:

1
2
sudo pip uninstall ipython
sudo pip install ipython==0.10

Now all your problem shall gone! :D

,

Fedora

Install Fedora 17 in Mac OSX with Macbook Pro

25 Aug , 2012  

1. Setup Wireless Driver Broadcom
By default, Fedora will not detect your Wireless. You need to install broadcom-wl from rpmfusion by :

1
2
3
su -c 'rpm -Uvh http://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-stable.noarch.rpm http://download1.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-stable.noarch.rpm'
sudo yum update
sudo yum install broadcom-wl

For manual download because you don’t have internet access :
http://download1.rpmfusion.org/nonfree/fedora/releases/17/Everything/

2. Install Development Packages

1
2
3
sudo yum install make automake gcc gcc-c++ libxslt libxslt-devel libxml2 libxml2-devel libffi libffi-devel libcurl libcurl-devel openssl-devel sqlite-devel libXv.i686 libXScrnSaver.i686 qt.i686 qt-x11.i686 libxslt-devel
sudo yum install postgresql-server postgresql-develnmap ImageMagick git
sudo yum install yakuake shutter vlc libreoffice

3. Setup LAMPP

1
sudo yum install mysql mysql-server mysql-devel nginx php php-fpm php-common phpmyadmin apache

run “sudo mysql_secure_installation” if you don’t want root with blank password.

1
2
3
4
sudo systemctl start httpd.service
sudo systemctl enable httpd.service
sudo systemctl start mysqld.service
sudo systemctl enable mysqld.service

For PhpMyadmin configuration is located in : “/etc/phpMyAdmin/config.inc.php”.
To make Phpmyadmin work without password, change this line :

1
$cfg['Servers'][$i]['AllowRoot']     = TRUE;        // whether to allow root login

And don’t forget to reload your webserver.

4. Skype 2.2
I love to use old Skype. You can download from http://repo.fedora.md/3rdparty/.

5. NodeJS and Redis
NodeJS and Redis is a must in software development, so we can install this both great software by :

1
2
3
4
5
sudo yum localinstall --nogpgcheck http://nodejs.tchol.org/repocfg/fedora/nodejs-stable-release.noarch.rpm
sudo yum install nodejs-compat-symlinks npm
sudo yum install redis
sudo systemctl start redis.service
sudo systemctl enable redis.service

More…

,

Django

Setup Python and Django Environment in Fedora 17

25 Aug , 2012  

1. Install Dependency Packages

1
2
3
4
sudo yum update
sudo yum install alacarte git wget vim lsb
sudo yum install make automake gcc gcc-c++ kernel-devel
sudo yum install python-devel libevent-devel python-pip bash-completion

2. Setup MySQL

1
sudo yum install mysql mysql-server mysql-devel

Run MySQL at startup :

1
2
sudo systemctl start mysqld.service
sudo systemctl enable mysqld.service

3. Install Virtualenv and Virtualenvwrapper

1
2
sudo pip-python install virtualenv
sudo pip-python install virtualenvwrapper

Load virtualenv into our bash by add this into ~/.bashrc :

1
2
3
4
export WORKON_HOME=$HOME/.virtualenvs
source /usr/bin/virtualenvwrapper.sh
export PIP_VIRTUALENV_BASE=$WORKON_HOME # Tell pip to create its virtualenvs in $WORKON_HOME.
export PIP_RESPECT_VIRTUALENV=true # Tell pip to automatically use the currently active virtualenv

And load this with “source ~/.bashrc”. Then we can start create a new virtualenv called “trip” for example, by :

1
mkvirtualenv --no-site-packages --distribute trip

And it will show you the result :

1
2
3
4
5
6
7
8
9
The --no-site-packages flag is deprecated; it is now the default behavior.
New python executable in trip/bin/python
Installing distribute.................................................................................................................................................................................................done.
Installing pip................done.
virtualenvwrapper.user_scripts creating /home/fedora/.virtualenvs/trip/bin/predeactivate
virtualenvwrapper.user_scripts creating /home/fedora/.virtualenvs/trip/bin/postdeactivate
virtualenvwrapper.user_scripts creating /home/fedora/.virtualenvs/trip/bin/preactivate
virtualenvwrapper.user_scripts creating /home/fedora/.virtualenvs/trip/bin/postactivate
virtualenvwrapper.user_scripts creating /home/fedora/.virtualenvs/trip/bin/get_env_details

4. Install Python Module
Create python-module.txt that contain :

1
2
3
4
5
ipdb
ipython
MySQL-Python
pylint
pep8
1
sudo pip install -r python-module.txt

,

Fedora

Enable / Disable MySQL, Apache, Redis and other services at startup in Fedora 17

23 Aug , 2012  

To enable MySQL, Apache, Redis or other services running at boot startup, you can use this simple command :

1
2
sudo systemctl enable redis.service
sudo systemctl enable httpd.service

To disable :

1
2
sudo systemctl disable redis.service
sudo systemctl disable httpd.service

, ,

Fedora

Setup Synergy Server and Client Multiple Screen in Fedora Core 17

23 Aug , 2012  

Working with 2 laptops and have to connected between each other is important in my daily activities. I have two Fedora laptop here (Macbook Pro + Dell) and get connected seamlessly with synergy. Here are to setup :

1. Install synergy
In both computer, please install synergy by :

1
sudo yum install synergy

2. Hostname
Make sure both computer have difference hostname. To change hostname in Fedora :

1
sudo vim /etc/sysconfig/network

Edit HOSTNAME into different value and don’t forget to restart the network service by:

1
sudo service network restart

3. Setup Server
In server which have hostname “trip” and client hostname “fedora”, I create configuration in “/etc/synergy.conf”:

1
2
3
4
5
6
7
8
9
10
11
section: screens
    trip:
    fedora:
end

section: links
    trip:
       left = fedora  
    fedora:
       right = trip
end

Run this server by :

1
synergys -f --config /etc/synergy.conf

4. Client
We need to add server hostname into our client “/etc/hosts”. For example, server IP is 192.168.1.3 :

1
192.168.1.2 trip

Then we can connect to server by :

1
synergyc -f trip

Now you ready to working with different laptop and different OS if you want :)

,

Fedora

Downgrade from Sun Java 7 into Java 6 in Fedora Core 17

22 Aug , 2012  

Sometimes we have some software that buggy in Sun Java JRE / JDK 7. Then it comes to us to downgrade into 6 Version. Well, isn’t difficult. All you need to do is following this step.

1. Download Oracle Sun Java JRE / JDK 6
Go to http://www.oracle.com/technetwork/java/javase/downloads/index.html and download RPM BIN version.

2. Uninstall existing JDK / JRE 7

1
sudo yum remove jdk jre

3. Install
Execute download files by “./” and you can install extracted RPM by :

1
sudo rpm -Uvh jre-6u34-linux-amd64.rpm

4. Register your Java 6 and set as primary

1
2
3
sudo alternatives --config java
sudo alternatives --install /usr/bin/java java /usr/java/jre1.6.0_34/bin/java 2
sudo alternatives --config java

Now you can use Java 6 for your development in Fedora :)

,

Python

Install and Fix PIL Python Image Library with JPEG support and ZLib in Fedora 17

22 Aug , 2012  

PIL default installation using PIP doesn’t come with JPEG and ZLIB support in Fedora Core 17. So, that why you sometimes facing problem when doing image processing using PIL in Fedora. The solution is easy:

1. Uninstall PIL

1
pip uninstall PIL

2. Install depedency packages

1
sudo yum install libjpeg libjpeg-devel

3. Make Symbolic Link if you are using 64-bit system

1
2
3
sudo ln -s /usr/lib64/libjpeg.so /usr/lib/
sudo ln -s /usr/lib64/libfreetype.so /usr/lib/
sudo ln -s /usr/lib64/libz.so /usr/lib/

4. Install PIL with Zlib and JPEG support

1
pip install -U PIL

And you should see successful results like this :

,

Django

Set initial value in fields Django Admin form

17 Aug , 2012  

Sometimes we need to setup different initial data when user create new records in Django Admin.
Well, when you came at this page, I believe you already search through a lot of web pages and doesn’t see the solution, isn’t ? :D

For instance, I have Order Model like this :

1
2
3
4
5
6
7
8
9
class OrderInfo(CommonInfo):
    """Order to pay subscription"""
    amount = models.DecimalField(max_digits=10,decimal_places=2,
                                 default=SUBSCRIBE_AMOUNT)
    currency = models.ForeignKey(Currency, related_name="%(class)s_currency")
    payment_status = models.ForeignKey(
                         PaymentStatus,
                         related_name="%s(class)s_payment_status"
                     )

And here is admin.py :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class OrderAdmin(admin.ModelAdmin):
    list_display = ['id', 'amount', 'currency', 'payment_status']

    def get_object(self, request, object_id):
        obj = super(OrderAdmin, self).get_object(request, object_id)
        if obj is not None:
            obj.amount = Decimal("0")
        return obj

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == 'currency':
            kwargs["queryset"] = Currency.objects.get(code="USD")
        return super(OrderAdmin, self).formfield_for_foreignkey(db_field,
                                                                request,
                                                                **kwargs)

You will see there are two kinds of function here :
1. get_object(self, request, object_id)
This function used for set initial value for non-foreignKey fields.

2.formfield_for_foreignkey(self, db_field, request, **kwargs)
This function used for set initial value for ForeignKey fields.

Easy right? :D

Django

Cannot import name abbrtask in Django Celery / Celery Python

17 Aug , 2012  

When you facing this error :

1
cannot import name abbrtask

or

1
celery.utils import abbrtask

That’s meaning youre using some python modules that rely on Celery 2.5.5 version.
To solve this issue :

1
2
pip uninstall celery
pip install "celery<3.0"

And your headache shall gone :)

,

implementation

How to doing memory debugging and profiling in C with Valgrind

12 Aug , 2012  

When we playing with C, memory debugging and profiling is a basic need to “break” and doing “analysis” to our C program. Valgrind is a good tools to help us doing memory debugging and profiling. In this case, I use Ubuntu 12.04.

First, we need to install Valgrind by :

1
sudo apt-get install valgrind


Next, let me create some a basic example, format-input.c :

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>

int main(int argc, char *argv[]) {
    int apartment = 3;
    int storey;

    printf("My Apartment number is n");
    printf("My Apartment storey is %dn", storey);
    return 0;
}


In this code, you will see that apartment variable is unused and storey doesn’t have any value. When you doing :

1
2
make format-input
./format-input

You will see result :

1
2
My Apartment number is
My Apartment storey is 0


Definitely we see there two mistaken here but C compiler showing a good result. Well, we can doing deep analysis using Valgrind by :

1
valgrind ./format-input


And you will see the result :

The bottom line here is whatever you’re running your C program, better check with Valgrind to see if everything is goes right :)

Fixing the source :

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>

int main(int argc, char *argv[]) {
    int apartment = 3;
    int storey = 33;

    printf("My Apartment number is %dn", apartment);
    printf("My Apartment storey is %dn", storey);
    return 0;
}

And Valgrind result are :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
==8443== Memcheck, a memory error detector
==8443== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==8443== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==8443== Command: ./formating-input
==8443==
My Apartment number is 3
My Apartment storey is 33
==8443==
==8443== HEAP SUMMARY:
==8443==     in use at exit: 0 bytes in 0 blocks
==8443==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==8443==
==8443== All heap blocks were freed -- no leaks are possible
==8443==
==8443== For counts of detected and suppressed errors, rerun with: -v
==8443== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)

,

Django

Solve ‘Order total is invalid.’ (Error Code: 10401) for Paypal error with Django/Python

8 Aug , 2012  

When I doing Paypal Checkout with multi-currency like Taiwan or Japanese Yen , suddenly I get this error :

1
'Order total is invalid.' (Error Code: 10401)

Wait a seconds, I try with other currencies like USD or GBP, everything is works well!
Then I realize that some currencies in Paypal can’t handle comma in Decimal (cent).
Example:

1
NT 9833.33

So, we should send them round up number to solve this problem, like:

1
NT 9834

If you want to round UP whatever cent behind the amount, then you can use this :

1
2
3
4
from math import ceil
from decimal import Decimal
amount = Decimal('33.144')
round_amount = Decimal(str(ceil(amount))).quantize(Decimal('0'))

When you sending this round amount, you will not see “‘Order total is invalid.’ (Error Code: 10401)” again! :)

Note:
I using https://github.com/duointeractive/paypal-python/ in my Django application.

,

Django

Setup Python and Django working environment in Mac OS X

5 Aug , 2012  

Here is a quick way to setup python and django on the fly in Mac OS X Snow Leopard.

1. Python 2.7
It’s better to use stable / latest Python version for development. At this time, I use Python version 2.7.3 for development. You can grab this at http://www.python.org/download/releases/2.7.3/. Just click on .dmg files and install. Later you should do : “source ~/.bash_profile” to make this Python 2.7 as primary.

2. Install setuptools python 2.7
Download setuptools .egg files in http://pypi.python.org/pypi/setuptools/#credits and install by “sh setuptools-0.6c11-py2.7.egg” :

1
2
3
4
5
6
7
8
Processing setuptools-0.6c11-py2.7.egg
Copying setuptools-0.6c11-py2.7.egg to /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages
Adding setuptools 0.6c11 to easy-install.pth file
Installing easy_install script to /Library/Frameworks/Python.framework/Versions/2.7/bin
Installing easy_install-2.7 script to /Library/Frameworks/Python.framework/Versions/2.7/bin
Installed /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg
Processing dependencies for setuptools==0.6c11
Finished processing dependencies for setuptools==0.6c11

3. Install pip, virtualenv and virtualwrapper
Then we need to install this 3 python modules. Don’t worry, we no need “sudo” here because from now, all of this python modules installed inside “/Library/Frameworks/Python.framework/Versions/2.7/”.

1
2
3
easy_install pip
pip install virtualenv
pip install virtualenvwrapper

Edit your ~/.bash_profile for enabling virtualenvwrapper :

1
2
3
4
export WORKON_HOME=$HOME/.virtualenvs
source /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh
export PIP_VIRTUALENV_BASE=$WORKON_HOME # Tell pip to create its virtualenvs in $WORKON_HOME.
export PIP_RESPECT_VIRTUALENV=true # Tell pip to automatically use the currently active virtualenv.

Then you should load your ~/bash_profile by :

1
source ~/.bash_profile

Let’s play with virtualenv by creating a new one :

1
mkvirtualenv --no-site-packages --distribute trading

For leaving virtualenv environment, you can use “deactivate”. To change or go to virtualenv, use “workon” Or “workon” to see all virtualenv.

Go to Virtualenvwrapper folder by :

1
cd $WORKON_HOME

Let setup your environment default directory by :

1
2
3
cd $WORKON_HOME
cd /bin
vim postactivate

Now you should put your startup-folder, eg:

1
cd ~/htdocs/my-folder-here

We can change Terminal color virtualenvwrapper by edit $WORKON_HOME/postactivate :

1
2
3
#!/bin/bash
# This hook is run after every virtualenv is activated.
PS1="[e[34;1m](`basename "$VIRTUAL_ENV"`)[e[0m] $_OLD_VIRTUAL_PS1"


4. Install MySQL
Download MySQL 64bit for Mac OS X from mysql.com. After installation, you need to do symbolic link libmysqlclient to make it working with MySQL-Python module.

1
sudo ln -s /usr/local/mysql-5.5.23-osx10.6-x86_64/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

It’s depend on your MySQL version.

5. Install homebrew
http://mxcl.github.com/homebrew/. After you install brew, then you can start installing git and other stuff like :

1
brew install git bash-completion wget

Load bash-completion to get ps1 in Terminal by add this into .bash_profile :

1
2
3
if [ -f `brew --prefix`/etc/bash_completion ]; then
. `brew --prefix`/etc/bash_completion
fi

This is my completed .bash_profile :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Setting PATH for Python 2.7
# The orginal version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/2.7/bin:${PATH}"
export PATH

#enables color in the terminal bash shell export
#sets up the color scheme for list export
export CLICOLOR=1
export LSCOLORS=GxFxCxDxBxegedabagaced
alias ls='ls -G'
alias ll='ls -hl'

if [ -f `brew --prefix`/etc/bash_completion ]; then
. `brew --prefix`/etc/bash_completion
fi

export WORKON_HOME=$HOME/.virtualenvs
source /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh
export PIP_VIRTUALENV_BASE=$WORKON_HOME # Tell pip to create its virtualenvs in $WORKON_HOME.
export PIP_RESPECT_VIRTUALENV=true # Tell pip to automatically use the currently active virtualenv.
source /usr/local/etc/bash_completion.d/git-completion.bash
export PS1='[\033[01;32m]u@h[\033[00m]:[\033[01;36m]w[\033[00m] $(__git_ps1 "[[e[34;1m]%s[e[0m]]")$ '
export PATH=/usr/local/mysql-5.5.23-osx10.6-x86_64/bin:$PATH


6. Install django
Simple as “pip install django” :)

,

Blackberry

Setup working environment Blackberry in Mac OS X Snow Leopard

4 Aug , 2012  

Develop Blackberry application under Windows is easy rather with Mac OS X. Again, I only develop application under Linux or Mac OS X. To setup and develop blackberry application in Mac OS X is need a patience. Here are the step to do:

1. Download and Install Latest Xcode
We need Xcode installed eventhough Blackberry may have their own JDE.
Keep with safe belt which it will make us far away from headache.

2. Install Blackberry SDK
Go to https://developer.blackberry.com/java/download/eclipse?os=mac and download that 400MB JDE files. Actually files contain Eclipse and Blackberry plugin for Mac OS X integrated. So, yes, it’s no need to download eclipse. You will need to install Akamai downloader before downloading this.

3. Create a new Project in Blackberry Eclipse SDK
After you open Eclipse-Blackberry SDK, then we can start creating new Project.
Select New Project -> Project -> Blackberry -> Blackberry Project.
You will see two files inside src.


4. Setup blackberry simulator in Mac OS X
I just kidding, you need a real blackberry to running your program because Blackberry doesn’t support simulator for Mac OS X. So, just plug your Blackberry using USB. Make sure Blackberry Desktop Manager not running or you should close this because it will interfere with eclipse debugger.


5. Setup Debugger
There are two way, you can go to Run -> Debug Configuration and select your USB devices. Or just right click into your project folder and set “Debug As” -> Blackberry Device.

6. Running your program.
Moment of truth! Just run debug and you will running your program into your blackberry. If you see “net_rim_bb_qm_peer .debug missing” problem, just click “Don’t ask this again”.

Now you can start to develop a blackberry app :)

,

Mac OS X

Solve sudo chmod / chown not permitted in Mac OS X

4 Aug , 2012  

When you dealing with external files or copy files into your hardrive in Mac OS X, I believe you facing this issue “Unable to change files” or “Operation not permitted”. Even you already use “sudo” but you don’t permission to change permission or owner for this files.

This is happen when we dealing with files with other filesystem. The solution is simple and straightfoward :

1
sudo chflags -R /path/

After you using “chflags”, you can set “chmod” or “chown” without any problem.