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

Python

Python remove dictionary key if value is empty

11 Mar , 2015  

Here is a quick snippet if we want to remove dictionary key if value is empty:

1
new_dict = {k: v for k, v in _data.items() if v if v is not ''}

Javascript

Solve issue Fullcalendar count two day as one day

9 Mar , 2015  

This is not bug. When we try to add day in March with start 10-03-2015T10:00:00 and end 11-03-2015T02:00:00, then it will showing one day instead of two day.

To solve this issue, we need to put nextDayThreshold:

1
nextDayThreshold: "00:00"

To make the next day threshold every 00:00

Algorithm

Counting number contain 14 on n-digit number in less than 1 second

8 Mar , 2015  

My fellow Adiyat in our company POLATIC bug me with this question “How to counting number contain 14 in 10 millions numbers less than 1 second?”. Then I thought, it’s easy, let give python a shot!

Famous-characters-Troll-face-Challenge-accepted-140949

1
print len([x for x in range(0, 10000000) if str(x).find('14') > -1])

With result “590040″ it’s takes 9.6s based on SublimeText (yes, i’m kindda hipster guy!). This is not good, no one want to waiting around 10 seconds to get the answer!

Lets break it down by printing sample data for 0-100 and 0-1000

1
2
print [x for x in range(0, 100) if str(x).find('14') > -1]
print [x for x in range(0, 1000) if str(x).find('14') > -1]

And we got :

1
2
3
[14]
[114, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 214, 314, 414, 514, 614, 714, 814, 914]
[Finished in 0.2s]

Wait, i want more, this is not enough to see pattern

1
2
3
4
[14]
[114, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 214, 314, 414, 514, 614, 714, 814, 914]
[1014, 1114, 1140, 1141, 1142, 1143, 1144, 1145, 1146, 1147, 1148, 1149, 1214, 1314, 1400, 1401, 1402, 1403, 1404, 1405, 1406, 1407, 1408, 1409, 1410, 1411, 1412, 1413, 1414, 1415, 1416, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 1434, 1435, 1436, 1437, 1438, 1439, 1440, 1441, 1442, 1443, 1444, 1445, 1446, 1447, 1448, 1449, 1450, 1451, 1452, 1453, 1454, 1455, 1456, 1457, 1458, 1459, 1460, 1461, 1462, 1463, 1464, 1465, 1466, 1467, 1468, 1469, 1470, 1471, 1472, 1473, 1474, 1475, 1476, 1477, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1489, 1490, 1491, 1492, 1493, 1494, 1495, 1496, 1497, 1498, 1499, 1514, 1614, 1714, 1814, 1914, 2014, 2114, 2140, 2141, 2142, 2143, 2144, 2145, 2146, 2147, 2148, 2149, 2214, 2314, 2414, 2514, 2614, 2714, 2814, 2914, 3014, 3114, 3140, 3141, 3142, 3143, 3144, 3145, 3146, 3147, 3148, 3149, 3214, 3314, 3414, 3514, 3614, 3714, 3814, 3914, 4014, 4114, 4140, 4141, 4142, 4143, 4144, 4145, 4146, 4147, 4148, 4149, 4214, 4314, 4414, 4514, 4614, 4714, 4814, 4914, 5014, 5114, 5140, 5141, 5142, 5143, 5144, 5145, 5146, 5147, 5148, 5149, 5214, 5314, 5414, 5514, 5614, 5714, 5814, 5914, 6014, 6114, 6140, 6141, 6142, 6143, 6144, 6145, 6146, 6147, 6148, 6149, 6214, 6314, 6414, 6514, 6614, 6714, 6814, 6914, 7014, 7114, 7140, 7141, 7142, 7143, 7144, 7145, 7146, 7147, 7148, 7149, 7214, 7314, 7414, 7514, 7614, 7714, 7814, 7914, 8014, 8114, 8140, 8141, 8142, 8143, 8144, 8145, 8146, 8147, 8148, 8149, 8214, 8314, 8414, 8514, 8614, 8714, 8814, 8914, 9014, 9114, 9140, 9141, 9142, 9143, 9144, 9145, 9146, 9147, 9148, 9149, 9214, 9314, 9414, 9514, 9614, 9714, 9814, 9914]
[Finished in 0.2s]

Did you see the patterns?

1
2
3
[{1 number}]
[{1 number}, 140..{10 number}, {1 number}, {1 number}, {1 number}, {1 number}, {1 number}, {1 number}, {1 number}, {1 number}]
[{1 number}, {1 number},{10 number}, {3 number} {100 number}, {5 number}, 2014, 2114, {10 number}, 2214, 2314, 2414, 2514, 2614, 2714, 2814, 2914, 3014, 3114, {10 number}, 3214, 3314, 3414, 3514, 3614, 3714, 3814, 3914, 4014, 4114, {10 number},  ...]

Which i can convert into simple list like :

1
2
3
1
9 + 10, ...  => total (19) + 1 = 20
9 + 10, 100, 10 + 10,  10 + 10,  10 + 10,  10 + 10 ... => total (279) + 20 = 299

My assumption, we need (10^n-2) here to capture total number in combination 14, 14x, 14xx, 14xxx … so on.

Second, we see need for recursive function to add result from previous base.

1
f(x) = 10 * f(n-1) + 10^n-2

Let do test with base 2, 3 and 4 on paper :

1
2
3
1
10 + 10
100 + 200

Well, it’s failed on base 3. Let’s think that this formula 10 * f(n-1) missing reduce duplicate number. Let’s reduce it with f(n-2) and recalculate again :

1
2
3
1
10 + 10
100 + 199

Yeay! Let’s write into code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"""
Calculate contain number of whatever base 2 number
in given base number
"""
def counting(n):
    if n == 2:
        return 1
    elif n < 2:
        return 0

    return 10 * counting(n-1) - counting(n-2) + 10**(n-2)

if __name__ == "__main__":
    n = 7
    print "The results counting {} base is {}".format(n, counting(n))

And the results is :

1
2
The results counting 7 base is 590040
[Finished in 0.2s]

In Polatic, we always learn and solve enterprise problems with best approach. See pattern and use algorithm to provide quick solution is one of our daily challenge.

Btw, you can check my github in http://github.com/yodiaditya or our company github http://github.com/polatic

Follow this discussion in HackerNews:
https://news.ycombinator.com/item?id=9165357

Django

Django unit test formset

1 Mar , 2015  

When testing page that contains formset in Django using unit test, we may encounter :

1
ValidationError: [u'ManagementForm data is missing or has been tampered with']

This is happend because we POST data without required FORMSET hidden value in form. To solve this issue, inspect element on your formset and insert hidden value in payload data.

Example :

1
2
<input id="id_firstformaset-MIN_NUM_FORMS" name="firstformaset-MIN_NUM_FORMS" type="hidden" value="0">
...

And put this in our payload:

1
2
3
4
5
6
7
8
        self.correct = {
            'name': 'TESTDATA',
            'gender': self.model.FEMALE_STATUS,
            'firstformaset-TOTAL_FORMS': 1,
            'firstformaset-INITIAL_FORMS': 0,
            'firstformaset-MIN_NUM_FORMS': 0,
            'firstformaset-MAX_NUM_FORMS': 1,
        }

implementation

Things to consider when choosing new technology or software in enterprise

27 Feb , 2015  

There are few things that we can use as standar for choosing or adopting new technology in our company.

The List

We gave each team a list of features to look for in their assigned templating solution. The idea was to fill out a score, from one (poor) to five (excellent), for each item:

  1. DRY: how DRY is the the technology? is there support for code-reuse and partials?
  2. i18n: is there support for translations and multiple languages?
  3. Hot reload: are changes visible immediately or is there a compile/deploy cycle?
  4. Performance: how long does it take to render in the browser and server?
  5. Ramp-up time: how is the learning curve?
  6. Ramped-up productivity: once you’ve ramped-up, how fast can you build things?
  7. Server/client support: can support both client-side and server-side?
  8. Community: is there an active community using this project? Can you google issues?
  9. Library agnostic: are there dependencies on other libraries?
  10. Testable: how hard is it to write unit and integration tests?
  11. Debuggable: is it possible to step through the code while it’s running to track down errors?
  12. Editor support: is there an editor with auto-complete, syntax highlighting, error checking, etc?
  13. Maturity: is this a relatively stable project or still experimenting and churning?
  14. Documentation: how is the documentation?
  15. Code documentation: do the software encourage/require documentation/comments?

#inspired by https://engineering.linkedin.com/frontend/client-side-templating-throwdown-mustache-handlebars-dustjs-and-more