September 24, 2017 Leave a comment
  • # Preparation
    sudo apt-get install python-numpy python-matplotlib ipython
    # Assume that you already have mkvirtualenv wrapper
    mkvirtualenv ml
    workon ml
    pip install pandas
  • # NUMPY
    import numpy as np
    ## Matrix And Vector
    vector = np.array([1,2])
    matrix = np.array([[1,2],[3,4]])
    identity = np.ones((2,2))
    zeros = np.zeros((2,2))
    random = np.random.randn(2,2)
    inverse = np.linalg.inv(matrix)
    determinant = np.linalg.det(matrix)
    transpose = matrix.T
    diagonal = np.diag([1,2,3])
    inner = np.inner(matrix, matrix) or
    outer = np.outer(matrix, matrix)
    ## Find angle of two vectors
    a = np.array([1,2])
    b = np.array([2,1])
    cosAB = / (np.sqrt(sum(a*a)) * (np.sqrt(sum(b*b))) )
    cosAB = / (np.linalg.norm(a) * np.linalg.norm(b) )
    radAngle = np.arccos(cosAB)
    ## Linear Equation
    A = np.array([[1,2],[3,4]])
    b = np.array([1,2])
    solution = np.linalg.inv(A).dot(b)
    solution = np.linalg.solve(A,b)
  • # PANDAS
    import pandas as pd
    ## Load data
    dframe = pd.read_csv("filename", header=None)
    ## Adding column and Fill data based on ref column
    dframe["new_column"] = dframe.apply(lambda row: some_function(dframe["ref_column"]), axis=1)
    ## Merge data frame
    df1 = pd.read_csv("file1")
    df2 = pd.read_csv("file2")
    df = pd.merge(df1, df2, on="selected_column")
  • # MAT PLOT
    import matplotlib.pyplot as plt
    ## Line plot
    x = np.linspace(0, 10, 200)
    y = np.sin(x)
    ## Scatter plot
    M = pd.read_csv("filename", header=None).as_matrix()
    x = M[:,0]
    y = M[:,1]
    ## Histogram
    x = np.random.randn(1000)
    ## Digit reader from mnist
    df = pd.read_csv("train.csv")
    M = df.as_matrix()
    label_1 = M[0,0]
    digit_1 = M[0,1:]
    digit_1 = digit_1.reshape(28,28)
    plt.imshow(digit_1, cmap="gray")


Categories: Python

Create Django App and Data Model

April 23, 2017 1 comment

Creating Django App

To manage a project, django divide the project into several small django apps. Django app is a group of related functionality used to complete or maintain one aspect of a site.

The following command will create django app called myapp

$ python startapp myapp

To make django load the app, we need to add app name in django setting:

$ nano mysite/

    # project app

Creating Data Model

We often need to store our data into database. In django, we need to define our data model first, then make django to propagate data model creation/changes to database schema by using django commands. In this example, we will create data model inside of django app that we created before.

  1. Create data model
    $ nano myapp/
    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    from django.db import models
    class MyModel(models.Model):
        foo = models.IntegerField(default=0)
        bar = models.TextField(blank=True, null=True)
        class Meta:
            db_table = 'my_model_tbl'
  2. Make django migration
    $ python makemigrations myapp
  3. Apply changes to database schema
    $ python migrate myapp


Categories: Django, Framework

Install Django with Postgresql

April 22, 2017 Leave a comment

This post will guide you quickly step-by-step installing django and Postgresql on Linux Mint.

  1. Install Postgresql Server
    $ sudo apt-get install postgresql
  2. Switch account to postgres and create db user for django project (create non superuser that can create db)
    $ sudo -i -u postgres
    $ createuser djangouser -P --interactive
  3. Connect to postgresql server as djangouser and create db for django project
    $ psql -u djangouser -h localhost -d postgres -W
    $ create database django_project_db
  4. Create Django Environment and install postgres db adapter for python
    $ mkvirtualenv django-project
    $ pip install django psycopg2
  5. Create Django Project
    $ django-admin startproject mysite
  6. Change django project db settings
    $ cd mysite
    $ nano mysite/
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': 'django_project_db',
            'USER': 'djangouser',
            'PASSWORD': 'djangouser',
            'HOST': 'localhost',
            'POST': '5432'
  7. Initialize DB data for django project
    $ python migrate
  8. Test by running the server
    $ python runserver


Categories: Django, Linux

Setup Python Virtual Environment

April 17, 2017 Leave a comment

When working on multiple python projects, perhaps we need to isolate package dependencies that needed for each project, so that dependency changes on one project does not make other project stop working.

Here’s example how to setup python virtual environment on linux mint.

$ sudo apt-get install python-pip
$ pip install setuptools virtualenv virtualenvwrapper

Add following code in ~/.profile

export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/

Execute following command

$ source ~/.profile

Done! It’s time to test.

  1. Create Virtual Environment for project 1: eg env1 (skip this if env1 already created)
    $ mkvirtualenv env1
  2. Activate virtual anvironment (eg: env1)
    $ workon env1
  3. Install package dependencies to current environment (eg: django)
    (env1)$ pip install django
  4. To get info about installed package:
    (env1)$ pip freeze
  5. Deactivate to exit from current virtual environment
    (env1)$ deactivate
  6. Get available virtual environments
    $ workon
  7. Remove virtual environment
    $ rmvirtualenv env1


Categories: Linux, Python

Toon Shading

December 6, 2015 1 comment


Toon shading is 3D technique based on a specific shading method, which consist in recreate the look of traditional 2D animation cels with the use of flat colours for shading 3D objects in a unrealistic way.


This shading technique has been used in several games. There are several games that use this tehcnique, such as: Ni No Kuni, Legend of Zelda, Ōkami, Naruto Shippuden, etc.


There are two main topics in Toon shading, First is shading it self and the second one is Outline.


Toon shading used the enhancement of Diffuse/Lambertian Reflection, called Half Lambert.

What is Diffuse reflection?

When incoming light touch the surface it will be reflected off the surface in all direction equally. The light intensity of a point in the surface can be computed using the surface normal vector N and the light vector L



Half Lambert is Technique first developed in the original Half-Life. Way of getting the lighting to show the surface of an object in low-light areas


Example of Half lambert equation in CG Language:



For the outline we can use Silhouette. A silhouette is an edge shared by one front and one back-facing polygon.


To get the outline more appeared we can enlarge back-facing polygon.


If you look into unity toon shading package, you will see following code in ToonBasicOutline shader to produce the outline.


Try out with 3D Model

This is the result when i tried out a 3d model with diffuse shading and toon shading.


Categories: Game and CG, Uncategorized

Nintendo 3DS Region Unlock

November 29, 2015 Leave a comment

I have bought old Nintendo 3DS from Japan, but sadly there’s a region lock that not permit us to play 3ds games that have different region with the console it self.

3DS games Sellers in my country rarely sell japanese regional games. To buy game, i had my friend in japan to buy the game for me. that’s suck. I did once anyway.

So, I google how to ‘jailbreak’ it, and found out that we can use Gateway 3DS to do that.


  1. Gateway 3ds Catridges:
    • Blue Catridge
    • Red Catridge
  2. Micro SD cards:
    • 2 GB or less for Gateway3ds Firmware
    • 8 GB or more to store your 3DS games
  3. SD Card to store saved game data
  4. Latest Gateway 3DS firmware
  5. Nintendo 3DS (firmware up to version 9)
  6. Original Game catridge (optional)

Steps needed:

  1. Format 2 GB micro SD card with Fat partition
  2. Copy all Files inside “Blue Card (R4i)” folder (from downloaded gateway 3ds firmware)  to root directory of 2 GB micro SD card
  3. Copy Launcher.dat to SD card
  4. Insert 2 GB micro SD card to Gateway 3DS Blue catridge.
  5. Insert Blue catridge to Nintendo 3DS catridge slot
  6. Boot into Gateway Menu. If it not working, then try to open nintendo 3ds browser, go to – when the bottom screen changes to white, Press and hold the Left Shoulder button and your 3DS/2DS will boot to the Gateway Menu.

  7. Backup current 3ds firmware to SD card by selecting “Backup System Nand” menu. cut and paste backup file to a folder in your computer
  8. Downgrade 3ds firmware to version 4.4-4.5
  9. Reboot 3DS, check current 3ds firmware version
  10. Boot into Gateway Menu again
  11. Create EmuNand
  12. Insert original game catridge and save the game file into sd card. cut and paste the file (with extension .3DS) to 8GB micro SD card (exFat formatted). Insert it into Gateway Red catridge
  13. Boot into Emunand from Gateway Menu and update to the latest 3ds firmware.
  14. Insert Gateway Red catridge into 3ds catridge slot
  15. Press “select” button and select available game, your saved game in step 12 should appear
  16. Play the game!!


Categories: Game and CG, Nintendo 3DS

Simple Example using Unit Testing in Python

March 13, 2015 1 comment

This is simple example how to use unit testing in python. For example, you want to create module that generate fibonacci numbers and want to test whether the module is working properly or not.

Below is simple script for module to generate fibonacci numbers :

# Fibonacci numbers module
def fib2(n): # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while b < n:
        a, b = b, a+b
    return result

def main():
    print fib2(100)

if __name__ == '__main__' : main()

And here simple script to test that module:

import fibonacci
import unittest

class TestFibonacciFunctions(unittest.TestCase):

    def test_series_100(self):
        print('\nTest Series 100')
        wanted_result = [1,1,2,3,5,8,13,21,34,55,89]
        test_result = fibonacci.fib2(100)

    def test_series_50(self):
        print('\nTest Series 50')
        wanted_result = [1,1,2,3,5,8,13,21,34]
        test_result = fibonacci.fib2(50)

if __name__ == '__main__' : unittest.main()

Run script with command


You will get following output if the wanted_result and test_result are equal

Test Series 100
Test Series 50
Ran 2 tests in 0.000s

Categories: Programming, Python