Uncategorized

Installing Fatfreecrm in Ubuntu

8 Dec , 2016  

Here are the quick guide:

1
sudo apt-get install ruby-dev libsqlite3-dev ruby libmagick++-dev libxml2 libxml2-dev libxslt1.1 libxslt1-dev libyaml-dev libpq-dev

Then follow this:

http://guides.fatfreecrm.com/Setup-Linux-or-Mac-OS.html

Now for passenger:

1
2
3
4
5
cd fat_free_crm
rvm install ruby-2.3.3
rvm gemset empty
gem install bundler
bundle install

Configure `/etc/passenger/fat_free_crm.yml` and edit NGINX

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
server {
    listen       80;
    server_name  sales.kargo.co.id;
    root         /path/fat_free_crm;

    location / {
            # Tells Nginx to forward all requests for www.foo.com
            # to the Passenger Standalone instance listening on port 4000.
            proxy_pass http://0.0.0.0:8000;
    }

    location /assets  {
         alias /path/fat_free_crm/public/assets/;
    }
}

Dont forget to precompile public and disable static in environments/production.rb

Ubuntu

Fix SSL not working on mobile browser RapidSSL

1 Nov , 2016  

To solve this, we need to make sure our installation of SSL is correct. Please check your current website via https://cryptoreport.rapidssl.com/checker/views/certCheck.jsp.

It will show you the missing SSL Certificate. Please download it into your server. The next step will be:

1. go to /etc/ssl
2. move your current domain.crt into another file
3. then concatenate your existing domain.crt (renamed) with intermediate key into new domain.crt

1
cat existing-domain.crt intermediate.pem > domain.crt

Please double check again with SSL certification checker

Ubuntu

Install Zurmo CRM in Ubuntu 16.04 Xenial Xerus

14 Oct , 2016  

Here are step to install Zurmo CRM into Ubuntu 16.04 Xenial Xerus.
Since Ubuntu 16.04 doesn’t have php5, we would like to install PHP5

1
2
3
4
sudo apt-get install software-properties-common
sudo apt-get purge `dpkg -l | grep php| awk '{print $2}' |tr "\n" " "`
sudo add-apt-repository ppa:ondrej/php
sudo apt-get update

1. Install php5.6

1
sudo apt-get install php5.6-dev php5.6-mysql php5.6-gd php5.6-imap php5.6-mcrypt php5.6-fpm  php5.6-mbstring php5.6-curl php5.6-xml

2. Now we need to switch from php7 to php5.6 by:

1
sudo a2dismod php7.0 ; sudo a2enmod php5.6 ; sudo service apache2 restart ; echo 1 | sudo update-alternatives --config php

3. Change listener in “/etc/php/5.6/fpm/pool.d/www.conf”, take a look on listen and change

1
listen = /var/run/php5-fpm.sock

4. Setup Zurmo NGINX sites-enabled configuration

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
27
28
29
30
31
server {
    listen       80;
    server_name  zurmo.yodiaditya.com;
    root         /var/zurmo;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ ^/(protected|framework|themes/\w+/views) { deny all; }
    location ~ /\. { deny all; access_log off; log_not_found off; }
    location = /favicon.ico { log_not_found off; access_log off; }
    location ~ \.(js|css|png|jpg|gif|ico|pdf|zip|rar)$ {
        try_files $uri =404;
    }

    location ~ \.php {
        fastcgi_split_path_info  ^(.+\.php)(.*)$;

        fastcgi_param  PATH_INFO        $fastcgi_path_info;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        fastcgi_send_timeout 3800;
        fastcgi_read_timeout 3800;
        fastcgi_connect_timeout 2800;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

5. Change Mysql Configuration at “/etc/mysql/mysql.conf.d/mysqld.cnf” :

1
2
3
4
5
6
7
character-set-server=utf8
collation-server=utf8_unicode_ci
default-storage-engine=INNODB
max_sp_recursion_depth=100
max_allowed_packet = 20M
thread_stack = 512K
optimizer-search-depth = 0

6. Now restart the services

1
2
sudo service php5.6-fpm restart
sudo service nginx restart

Ubuntu

Setup Django + WordPress Ubuntu 16.04 Xenial Xerus

14 Oct , 2016  

Here is guide to setup Ubuntu 16.04 Xenial Xerus for Django and WordPress Development. First, we need to install dependencies software.

1. Install dependencies software Python, NGINX, PosgreSQL, MySQL and PHP5

1
sudo apt-get install libpq-dev python-dev python-software-properties postgresql postgresql-contrib nginx git zip unzip build-essential python nmap libxslt1-dev python-pip imagemagick uwsgi uwsgi-plugin-python nmap mysql-server phpmyadmin libffi-dev libmysqlclient-dev libmysqlclient-dev libmysqlclient-dev libjpeg-dev language-pack-id php5-fpm php5-mysql software-properties-common

2. Re-configure locale

1
sudo dpkg-reconfigure locales

3. Create bash_prompt.sh in your home directory

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#!/bin/bash
#
# DESCRIPTION:
#
#   Set the bash prompt according to:
#    * the active virtualenv
#    * the branch/status of the current git repository
#    * the return value of the previous command
#    * the fact you just came from Windows and are used to having newlines in
#      your prompts.
#
# USAGE:
#
#   1. Save this file as ~/.bash_prompt
#   2. Add the following line to the end of your ~/.bashrc or ~/.bash_profile:
#        . ~/.bash_prompt
#
# LINEAGE:
#
#   Based on work by woods
#
#   https://gist.github.com/31967

# The various escape codes that we can use to color our prompt.
        RED="\[\033[0;31m\]"
     YELLOW="\[\033[1;33m\]"
      GREEN="\[\033[0;32m\]"
       BLUE="\[\033[1;34m\]"
  LIGHT_RED="\[\033[1;31m\]"
LIGHT_GREEN="\[\033[1;32m\]"
      WHITE="\[\033[1;37m\]"
 LIGHT_GRAY="\[\033[0;37m\]"
 COLOR_NONE="\[\e[0m\]"

# Detect whether the current directory is a git repository.
function is_git_repository {
  git branch > /dev/null 2>&1
}

# Determine the branch/state information for this git repository.
function set_git_branch {
  # Capture the output of the "git status" command.
  git_status="$(git status 2> /dev/null)"

  # Set color based on clean/staged/dirty.
  if [[ ${git_status} =~ "working directory clean" ]]; then
    state="${GREEN}"
  elif [[ ${git_status} =~ "Changes to be committed" ]]; then
    state="${YELLOW}"
  else
    state="${LIGHT_RED}"
  fi

  # Set arrow icon based on status against remote.
  remote_pattern="# Your branch is (.*) of"
  if [[ ${git_status} =~ ${remote_pattern} ]]; then
    if [[ ${BASH_REMATCH[1]} == "ahead" ]]; then
      remote="↑"
    else
      remote="↓"
    fi
  else
    remote=""
  fi
  diverge_pattern="# Your branch and (.*) have diverged"
  if [[ ${git_status} =~ ${diverge_pattern} ]]; then
    remote="↕"
  fi

  # Get the name of the branch.
  branch_pattern="^# On branch ([^${IFS}]*)"
  if [[ ${git_status} =~ ${branch_pattern} ]]; then
    branch=${BASH_REMATCH[1]}
  fi

  # Set the final branch string.
  BRANCH="${state}(${branch})${remote}${COLOR_NONE} "
}

parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}


# Return the prompt symbol to use, colorized based on the return value of the
# previous command.
function set_prompt_symbol () {
  if test $1 -eq 0 ; then
      PROMPT_SYMBOL="\$"
  else
      PROMPT_SYMBOL="${LIGHT_RED}\$${COLOR_NONE}"
  fi
}

# Determine active Python virtualenv details.
function set_virtualenv () {
  if test -z "$VIRTUAL_ENV" ; then
      PYTHON_VIRTUALENV=""
  else
      PYTHON_VIRTUALENV="${BLUE}[`basename \"$VIRTUAL_ENV\"`]${COLOR_NONE} "
  fi
}

# Set the full bash prompt.
function set_bash_prompt () {
  # Set the PROMPT_SYMBOL variable. We do this first so we don't lose the
  # return value of the last command.
  set_prompt_symbol $?

  # Set the PYTHON_VIRTUALENV variable.
  set_virtualenv

  # Set the BRANCH variable.
  if is_git_repository ; then
    set_git_branch
  else
    BRANCH=''
  fi

  # Set the bash prompt variable.
  PS1="${PYTHON_VIRTUALENV}${GREEN}\u@ ${YELLOW}\w${COLOR_NONE}$(parse_git_branch)${PROMPT_SYMBOL} "
}

export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"

# Tell bash to execute this function just before displaying its prompt.
PROMPT_COMMAND=set_bash_prompt

and edit .bashrc and add this into the last line

1
source ~/bash_prompt.sh

4. Setup your Django

Usually we install requirements for our Django

1
sudo pip install -r requirements.txt

5. Setup your django.ini at “/etc/uwsgi/apps-enabled/”

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
[uwsgi]
# enable master process manager
master = true

# spawn 2 uWSGI worker processes
workers = 2

# bind to UNIX socket at /run/uwsgi/<confnamespace>/<confname>/socket
socket = /tmp/django.sock

# set mode of created UNIX socket
chmod-socket = 666

# place timestamps into log
log-date = true

# user identifier of uWSGI processes
uid = root

# group identifier of uWSGI processes
gid = root

; define variables to use in this script
project = django

; number of worker processes
processes = 8

; plugins=python
; project-level logging to the logs/ folder

; django >= 1.4 project
chdir = /var/django
wsgi-file=/var/django/django/wsgi.py

; run master process as root
enable-threads = true

vacuum = true
env = DJANGO_SETTINGS_MODULE=kargo.settings
pidfile2 = /tmp/django.pid

6. Setup your NGINX at “/etc/nginx/sites-enabled”:

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
server {
        listen   80;
        server_name django.yodiaditya.com;
        root /var/django;

    client_body_timeout 64600000;
    client_header_timeout 64600000;
    send_timeout 6460000;
    client_max_body_size 30m;
    keepalive_timeout 6300000;
    proxy_connect_timeout 6600000;
    proxy_send_timeout 6600000;
    proxy_read_timeout 6600000;

    index  index.php index.html index.htm;

    # Check if a file exists at /var/www/domain/ for the incoming request.
    # If it doesn't proxy to Apache/Django.
    try_files $uri @django;

    location /media  {
         alias /var/django/media;
    }

    location /static {
         alias /var/django/static;
    }

    location / {
        uwsgi_pass unix:/tmp/django.sock;
        uwsgi_read_timeout 600000;
        include uwsgi_params;
    }

    error_page 403 404 500 502 503 504 /custom_50x.html;
    location = /custom_50x.html {
        root /usr/share/nginx/html;
        internal;
    }
}

Mac OS X

Cut and Paste in Mac OS X EL Capitan

1 Sep , 2016  

Here is easy way to cut and paste in Mac OS X EL Capitan:

1. Copy files by “Command + C”
2. Paste with Cut “Command + Option V”

Easy right? :)

Ubuntu

Setup New Server Ubuntu 14.10 with Django, Python and PHP

29 May , 2016  

Here is quickstep to configure a new server in Softlayer for Django and PHP development environtment.

1
2
sudo apt-get update && sudo apt-get upgrade
sudo apt-get install libpq-dev python-dev python-software-properties postgresql postgresql-contrib nginx git zip unzip build-essential python nmap libxslt1-dev python-pip imagemagick uwsgi uwsgi-plugin-python nmap mysql-server phpmyadmin libffi-dev libmysqlclient-dev libmysqlclient-dev libmysqlclient18

For Django sites-enables/ :

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
27
28
29
30
31
32
33
34
35
36
37
server {
    listen 80;
    server_name www.yourdomain.com;
    return 301 $scheme://yourdomain.com$request_uri;
}

server {
    listen 80;

    server_name yourdomain.com;
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;
    root /var/yourdomain;

    client_max_body_size 30m;

    index  index.php index.html index.htm;

    # Check if a file exists at /var/www/domain/ for the incoming request.
    # If it doesn't proxy to Apache/Django.
    try_files $uri @django;

    location /media  {
         alias /var/yourdomain/media;
    }

    location /static {
         alias /var/yourdomain/static;
    }

    location / {
        uwsgi_pass unix:/tmp/yourdomain.sock;
        uwsgi_read_timeout 600000;
        include uwsgi_params;
    }

}

For WordPress configuration:

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
server {
    listen   80;
    server_name www.yourdomain.com;
    root    /var/yourdomain.com;

    client_body_timeout  460;
    client_header_timeout 460;
    send_timeout 460;
    client_max_body_size 10m;
    keepalive_timeout       300 300;

    access_log  /var/log/nginx/access.log;
    index  index.php index.html index.htm;

    location = /favicon.ico {
            log_not_found off;
            access_log off;
    }

    location = /robots.txt {
            allow all;
            log_not_found off;
            access_log off;
    }

    location / {
            # This is cool because no php is touched for static content
            try_files $uri $uri/ /index.php?$args;
    }


    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ .php$ {
            fastcgi_send_timeout 3800;
            fastcgi_read_timeout 3800;
            fastcgi_connect_timeout 2800;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include fastcgi_params;
    }

    location ~* .(js|css|png|jpg|jpeg|gif|ico)$ {
            expires max;
            log_not_found off;
    }

    # deny access to .htaccess files, if Apache document root
    # concurs with nginx one
    #
    location ~ /.ht {
            deny  all;
    }
}

Django

Open Permission access custom for Django Rest Framework

21 Mar , 2016  

When we need to open access for API Django-restframework, we can do it by extending the permission class.
Here is some example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class PublicUserPermissions(permissions.BasePermission):
    """
    Granting public access permissions
    """

    def has_object_permission(self, request, view, obj):

        # Allow get requests for all
        if request.method == 'GET':
            return True
        else:
            return request.user == obj


class SomeViewSet(viewsets.ModelViewSet):
    """
    API to view Some dataset
    """
    model = Some
    queryset = model.objects.all()
    permission_classes = (PublicUserPermissions, )

Web

Kode UBER Gratis Jakarta, Indonesia

30 Nov , 2015  

Berikut kode gratis Uber di Jakarta Indonesia

1
YODIA3UE

,

Ubuntu

Setup SSL Certification RapidSSL on EC2

25 Nov , 2015  

Here are quickstep to generate SSL Certification

1
2
openssl genrsa -out www.domain.com.key 2048
openssl req -new -key www.domain.com.key -out www.domain.com.csr
1
2
3
4
5
6
7
8
9
10
11
12
Country Name (2 letter code) [AU]:ID
State or Province Name (full name) [Some-State]:Jakarta
Locality Name (eg, city) []:Jakarta
Organization Name (eg, company) [Internet Widgits Pty Ltd]:PT POLATIC INFORMATIKA INDONESIA
Organizational Unit Name (eg, section) []:IT
Common Name (e.g. server FQDN or YOUR name) []:www.polatic.com
Email Address []:cs@polatic.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:PT POLATIC INFORMATIKA INDONESIA

Make sure check all value by :

1
openssl req -in www.domain.com.csr -noout -text

Option on “Common Name (e.g. server FQDN or YOUR name)” will used as your domain name certification. Make sure to choose “www” or non-www wisely.

Then we buy the certification.

Next step, we receive the certification from RapidSSL and download the intermediate from their website.
Merge together into :

1
cat www.domain.com.ssl www.domain.com.intermediate > www.domain.com.crt

Then in NGINX

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
server {
    server_name polatic.com;
    return 301 https://www.polatic.com$request_uri;
}

server { #Redirect https, non-www to https, www
    listen 443 ssl;
    server_name polatic.com;

    ssl_certificate      /etc/ssl/polatic.com.crt;
    ssl_certificate_key  /etc/ssl/polatic.com.key;
    return 301 https://www.polatic.com$request_uri;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name www.polatic.com;
    ssl on;
    root    /var/polatic;

    ssl_certificate      /etc/ssl/polatic.com.crt;
    ssl_certificate_key  /etc/ssl/polatic.com.key;

    client_body_timeout  460;
    client_header_timeout 460;
    send_timeout 460;
    client_max_body_size 10m;
    keepalive_timeout       300 300;

    access_log  /var/log/nginx/access.log;
    index  index.php index.html index.htm;

    location = /favicon.ico {
            log_not_found off;
            access_log off;
    }

    location = /robots.txt {
            allow all;
            log_not_found off;
            access_log off;
    }

    location / {
            # This is cool because no php is touched for static content
            try_files $uri $uri/ /index.php?$args;
    }


    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ .php$ {
            fastcgi_send_timeout 3800;
            fastcgi_read_timeout 3800;
            fastcgi_connect_timeout 2800;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include fastcgi_params;
    }

    location ~* .(js|css|png|jpg|jpeg|gif|ico)$ {
            expires max;
            log_not_found off;
    }

    # deny access to .htaccess files, if Apache document root
    # concurs with nginx one
    #
    location ~ /.ht {
            deny  all;
    }

}

Java

Running Play Framework as services in Production Ubuntu

5 Oct , 2015  

Here are steps to deploy Play Framework to Ubuntu as services :

1. Stage

1
activator stage

2. Setup services in /etc/init.d/your-play

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
27
28
29
30
31
32
33
34
#!/bin/sh
### BEGIN INIT INFO
# Provides:          mdm
# Required-Start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start/Stop mdm
### END INIT INFO
#
#source some script files in order to set and export environmental variables
#as well as add the appropriate executables to $PATH

PLAYFRAMEWORK_HOME='PATH-TO-STAGE-FOLDER'
export PIDFILE='PATH-TO-PID'
USER=root
GROUP=nogroup

case "$1" in
    start)
        echo "Starting mdm"
        START_CMD="${PLAYFRAMEWORK_HOME}/bin/playstartapp -Dparam1=value1"
        start-stop-daemon --start -p "${PIDFILE}" --quiet --background --chuid ${USER}:${GROUP} --exec /bin/bash -- ${START_CMD}
        ;;
    stop)
        echo "Stopping mdm"
        start-stop-daemon -K -p "${PIDFILE}" -u "${USER}" -R 30 ;;
      *)
        echo "Usage: /etc/init.d/mdm {start|stop}"
        exit 1
    ;;
esac

exit 0

Just replace PATH-TO-FOLDER and PATH-TO-PID, to your project path

Django

Solve integrity error duplicate key in Django PostgreSQL

25 Sep , 2015  

This error caused by we’re using database from copy / clone database. The sequences will be mixed-up.
To solved this, just follow this way :

1
2
python manage.py sqlsequencereset <app-name> > app.sql
psql -U username -d database -a -f < app.sql

Then your problem shall gone!

Android

Tutorial Implementation Google Cloud Messaging (GCM) with Django

17 Sep , 2015  

Setup GCM for Android Client and Django in Server require efforts to know how it’s works. Here are simple steps to setup the newest GCM (Google Cloud Messaging) in Android.

To understand about GCM, the flow is :

1. Create a Google APIs GCM project, which generates SENDER_ID and API_KEY for server implementation.

2. An Android app registers the device its running on with GCM, using PROJECT_ID, which generates a registration id. The app should send registration ID to the server.

3. The project’s server code can now send a broadcast message to any registered devices by communicating with the GCM service, using the API KEY.

For the implementation:

1. Dependencies
Update your ADT and Google Play Service packages to be able using the latest GCM. Make sure to import google-play-services lib into your project libraries.

2. AndroidManifest

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
    <uses -permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses>
    <uses -permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses>

    <!-- GCM requires a Google account. -->
    <uses -permission android:name="android.permission.GET_ACCOUNTS"></uses>

    <!-- Keeps the processor from sleeping when a message is received. -->
    <uses -permission android:name="android.permission.WAKE_LOCK"></uses>
    <uses -permission android:name="android.permission.INTERNET"></uses>
    <uses -permission android:name="android.permission.GET_ACCOUNTS"></uses>
    <uses -permission android:name="com.google.android.c2dm.permission.RECEIVE"></uses>


    <permission android:name="com.polatic.hospitrack.permission.C2D_MESSAGE"
        android:protectionLevel="signature"></permission>

    <uses -permission android:name="com.polatic.hospitrack.gcm.permission.C2D_MESSAGE"></uses>

    ....



        <service android:name="com.polatic.hospitrack.network.GCMListenerInstanceID"
            android:exported="false" >
            <intent -filter>
                <action android:name="com.google.android.gms.iid.InstanceID"></action>
            </intent>
        </service>

        <service android:name="com.polatic.hospitrack.network.GCMListenerService"
            android:exported="false" >
            <intent -filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE"></action>
            </intent>
        </service>

        <receiver android:name="com.google.android.gms.gcm.GcmReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent -filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE"></action>

                <category android:name="com.polatic.hospitrack"></category>
            </intent>
        </receiver>

        <service android:name="com.polatic.hospitrack.network.GCMRegistrationIntentService"
            android:exported="false" >
        </service>

More…

Uncategorized

LAMPP Ubuntu in Softlayer

22 Aug , 2015  

Quick guide for setup LAMPP server in Ubuntu :

1
2
sudo apt-get update && sudo apt-get upgrade -y
sudo apt-get install nginx php5-fpm php5-mysql mysql-server php5-mysql php5-dev php-pear php5 nmap vim

Server

How to enable WSGIPassAuthorization in NGINX + DJango

12 Aug , 2015  

Just in case we need to enable “WSGIPassAuthorization” in NGINX, we can put this in nginx hosts

1
2
3
4
5
proxy_pass_request_headers on;
proxy_no_cache $cookie_nocache  $arg_nocache$arg_comment;
proxy_no_cache $http_pragma     $http_authorization;
proxy_cache_bypass $cookie_nocache $arg_nocache $arg_comment;
proxy_cache_bypass $http_pragma $http_authorization;

ERP

ERP Development Design

29 Jul , 2015  

Here are the list we need consider when develop ERP. More in technical view.

1. Never trust Front-end validation
We must separate between front-end validation and backend validation.
Always check validation on backend to make sure the data is valid and correct.
To avoid any data updates in the middle of process.

2. Audit-trail
Audit-trail is important, therefore we need to have user session in every inserted data.
More…

postgres

Upload PostgreSQL not working, change the encoding may help

20 Jul , 2015  

When we upload and restore the backup into new postgresql server, sometimes we facing problem because encoding.
To solve this, we can use UTF-8 :

1
update pg_database set encoding = pg_char_to_encoding('UTF8') where datname = 'your-database';

,

Ubuntu

Uwsgi on ubuntu 14.04 not working solution

12 Jul , 2015  

In Ubuntu 14.04, uwsgi that installed via apt-get will not working. To make it working, please use this steps:

1
2
sudo apt-get remove --purge uwsgi uwsgi-plugin-python
sudo apt-get install uwsgi uwsgi-plugin-python

Then follow this steps:

1
2
3
4
sudo pip install uwsgi
cd /usr/bin
sudo mv uwsgi uwsgi-old
sudo ln -s /usr/local/bin/uwsgi uwsgi

If still failed, follow this :

http://yodi.polatic.me/setup-latest-uwsgi-django-in-production-ubuntu-14-04/

Django

Setup Ubuntu Server in Softlayer for Django

10 Jul , 2015  

Here are a quick step to setup Ubuntu server in Softlayer for Django

1. Install depedencies

1
2
3
4
apt-get install python-software-properties software-properties-common
add-apt-repository ppa:webupd8team/java
apt-get update
sudo apt-get install oracle-java7-installer

2. Install UWSGI, Python, PostgreSQL and other modules

1
sudo apt-get install libpq-dev python-dev python-software-properties postgresql postgresql-contrib nginx git zip unzip build-essential python nmap libxslt1-dev python-pip imagemagick uwsgi uwsgi-plugin-python nmap

3. Another modules

1
sudo apt-get install git-core curl openssl libssl-dev pkg-config python-dev libxml2 libxml2-dev libxslt1-dev libbz2-dev libssl-dev p7zip-full unzip unace unp bzip2 gzip patch subversion git libmysqlclient-dev libmysqlclient-dev libmysqlclient18 php5 php5-mysql mysql-server

4. Setup UWSGI and NGINX

Python

Becareful using int() or Decimal() for validation storing in Charfield Django

24 May , 2015  

So, we have CharField() as model field in Django. Then we want to validate input into number only.
Usually, we using obj.is_digit() to validate.

Common mistake happen when we using int() to convert string input.

1
2
value = "0123123123"
int(value)

Will return

1
"123123123"

So becareful when using int() or Decimal() for converting value with leading zero

Javascript

Update parent after children new windows closed

14 Apr , 2015  

Here is a snippet to update parent after new window getting closed :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Start trigger pop-up new window
var createUrl = $(this).data('url') + selectedUUID;
newwindow = window.open(createUrl, 'Some Page, 'scrollbars=yes,resizable=yes,height=600,width='+screen.width/2);

// Set focus on windows
if (window.focus) {
    newwindow.focus();
}

// Update parent once children window already closed
// Reload jqgrid table to get latest data
var monitor = setInterval(function() {
    if (newwindow.closed) {
         // Update children table
         $selectorFarmfield.setGridParam({url: 'someurl' + selectedUUID});
         $selectorFarmfield.trigger("reloadGrid");
         clearInterval(monitor);
    }
}, 1000);

Django

JqGrid inline editing integration with DJango send csrf token

3 Apr , 2015  

Here is a quick snippet to send csrf_token in POST data from inline edit JqGrid to Django:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var tableGrid = $(selector).jqGrid({
   ....
   onSelectRow: function(id){
         if(id && id!==lastSel){
            $(selector).restoreRow(lastSel);
            lastSel=id;
         }

         var editparameters = {
            extraparam: {csrfmiddlewaretoken: $('.token-data').data('token')},
            keys: true,
          };
         $(selector).jqGrid('editRow', id, editparameters);

    }
};

Javascript

Example Jquery Plugin to filtering input value real-time with Regex validation

3 Apr , 2015  

We try to add real-time input validation for dynamic element with some regex. Let say, user allowed only to type “numeric” and disallow any others alphabet and symbols.

Then, we can write a small plugin, at this example, i use https://github.com/akzhan/jquery-keyfilter for Regex validation.

Then, we just need to write this simple and easy plugin :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
(function($) {
    $.fn.validNumber = function(selector) {

        /**
         * Attach key filter with regex int only for dynamic element
         */
        $(document).on('click', selector, function() {
            $(this).keyfilter(/[\dA-F]/);
        });

        /**
         * When input have more than 1 digit but leading with 0
         * Remove the leading zero
         */
        $(document).on('keyup', selector, function() {
            if($(this).val().length > 1 && $(this).val()[0] == "0") {
                 $(this).val($(this).val().substring(1));
            }
        });
    };
})(jQuery);

Then, we just need to use this libraries by :

1
$(document).validNumber('input');

Django

Handle error form.save() with model validation

2 Apr , 2015  

Here is a quick snippet to avoid form.save() error because model validation :

1
2
3
4
5
6
7
8
# handle form save with model validationerror
# http://stackoverflow.com/questions/8771029/django-raise-a-validation-error-in-a-models-save-method
try:
    form.save()
except ValidationError, e:
    form._errors = {}
    for _, v in e.message_dict.items():
        form._errors.setdefault(NON_FIELD_ERRORS, []).extend(v)

Uncategorized

Inline edit jqgrid with select2

2 Apr , 2015  

Here is a quick snippet for inline edit JqGrid with Select2

First, we need to bind colModel with select2 in dataInit :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var colModel = [
     // always put uuid and id
     {name:'id', hidden: true},
     {name:'uuid', hidden: true},
     {name:'youroption', label:'yourlabel',editable: true,
      edittype: "select", editrules: { required: true }, width:450,
      editoptions: {
        value: [[1, ],
        dataInit: function (elem) {
            $(elem).width(450).select2();
            $(elem).addClass("select2box");
        }
      }},
 ...

Second, we need to fix select2 “enter key” to hide search box and execute inline edit save.

1
2
3
4
5
6
7
$(document).on('keyup', '.select2-search > input.select2-input', function (e) {
  // Close select2 if enter key
   if(e.keyCode === 13) {
      $('select.select2box').select2("enable", false);
      $(selector).jqGrid('saveRow', lastSel, false, 'clientArray');
      }
  });

Javascript

Jqgrid for Dummies

1 Apr , 2015  

Here is a quick snippet of how to using JqGrid for dummies, like get data, delete data, access data or data manipulation.

Setup JQGrid:

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
$(document).ready(function() {
    // Enable tooltips
$("body").tooltip({
    selector : '[data-toggle="tooltip"]'
});
$(".chosen").chosen();

var permission = $('.permission');

// Define ID for table
var selector = "#table-index";
var pager = '#table-pager';

// Setup url ajax for loading data in table
var url = $(selector).data('url');

// Define last sel for edit
var lastSel;

var colModel =  [
     {name:'id', hidden: true, key:true, editable:true},
     {name:'uuid', hidden: true},
     {name:'hybrid', label:'Hybrid', editable: true, editrules:{number: true}, classes: 'numberonly'},
     {name:'some_date', label:'Date Selection', editable: true,  editoptions:{size:20,
          dataInit:function(el){
                $(el).datepicker({dateFormat:'dd-mm-yy'});
          },
          defaultValue: function(){
            var currentTime = new Date();
            var month = parseInt(currentTime.getMonth() + 1);
            month = month < = 9 ? "0"+month : month;
            var day = currentTime.getDate();
            day = day <= 9 ? "0"+day : day;
            var year = currentTime.getFullYear();
            return day+"-"+month + "-"+year;
          }
        }
      },
 ];

/**
 * Setup Table GRID
 *
 * We need to define colModel with editable and edittype
 * Check to load pager and bind keys
 */
var tableGrid = $(selector).jqGrid({
    url : url,
    datatype : "json",
    colModel : colModel,
    rowNum : 100,
    rowList : [100, 500, 1000],
    pager : pager,
    sortname : 'id',
    sortorder : "desc",
    height: 300,
    jsonReader : {
        repeatitems: false,
        id: "0"
    },
    editurl: $(selector).data('edit-url'),
    viewrecords: true,
    multiselect: true,
    onSelectRow: function(id){
         if(id && id!==lastSel){
            $(selector).restoreRow(lastSel);
            lastSel=id;
         }
   },
});

More…

Javascript

JqGrid save inline editing callback

1 Apr , 2015  

Here is a quick snippet for callback when saving inline editing in JqGrid:

1
2
3
4
5
6
7
8
9
10
11
12
// http://stackoverflow.com/questions/13303698/total-of-amount-in-jqgrid
ondblClickRow: function (rowid, name, val, iRow, iCol) {
    $(selector).jqGrid("editRow", rowid, {
        keys: true,
        aftersavefunc: function (rowid) {
            var $grid = $(selector);
            var colSum = $grid.jqGrid('getCol', 'debit', false, 'sum');
            $grid.jqGrid('footerData', 'set', { 'debit': colSum });
           
        }
    });
},

In this example, we do calculation after inline edit save.

Django,Javascript

JqGrid delete multiple select rows

1 Apr , 2015  

There is an issue if we delete rows using :

1
2
3
4
5
6
7
8
9
10
// Get all selected row
var rows = $(selector).jqGrid("getGridParam", "selarrrow");
console.log(rows);

// Iterate and delete
for (var i in rows) {
      console.log(i);
      console.log(rows[i]);
      $(selector).jqGrid('delRowData', rows[i]);
}

Only a few records will deleted.

The solution :

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
 * Delete data button handler
 * There is a bug if we delete by forloop, solution
 * http://www.trirand.com/blog/?page_id=393/bugs/delrowdata-bug-on-grid-with-multiselect
 */
$("a.delete-data").click(function(e) {
    e.preventDefault();

    var rowids = $(selector).jqGrid('getGridParam', 'selarrrow');
    for (var i = rowids.length - 1; i >= 0; i--) {
        $(selector).jqGrid('delRowData', rowids[i]);
    }
});

Django

Save django model with dictionaries

29 Mar , 2015  

Beware when queryset filter update() because it will pass model validation. Here is some example save model with dictionaries :

1
2
3
4
5
6
7
8
9
10
for k, v in account.items():
    setattr(instance, k, v)

try:
    instance.save()
except Exception, e:
    raise ValidationError(e)
else:
    updated += 1
    # print account

Django

Convert boolean True and False field value in Django Rest Framework

29 Mar , 2015  

Here is a quick snippet to convert boolean True / False in DRF Serializer:

1
2
3
4
5
6
is_finish = serializers.SerializerMethodField()

def get_is_finish(self, obj):
    if obj.is_finish:
        return "Selesai"
    return "Progress"

Django

Modify object data by write Custom Renderer in Django Rest Framework

29 Mar , 2015  

When we need to modify object or results from DRF / Django Rest Framework, all we need just write a custom JSON Renderer like below :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class JGridJSONRenderer(renderers.JSONRenderer):
    def render(self, data, accepted_media_type=None, renderer_context=None):
        new_rows = []

        # Name the object list
        for obj in data['rows']:
            obj = dict(obj)
            new_rows.append({'id': obj['id'], 'cell': obj})

        data['rows'] = new_rows
        response_data = data
        response = super(JGridJSONRenderer, self).render(response_data, accepted_media_type, renderer_context)

        return response