Archive

Archive for the ‘Programming’ Category

Numpy+Pandas+Matplot

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 matrix.dot(matrix)
    outer = np.outer(matrix, matrix)
    ## Find angle of two vectors
    a = np.array([1,2])
    b = np.array([2,1])
    cosAB = a.dot(b) / (np.sqrt(sum(a*a)) * (np.sqrt(sum(b*b))) )
    cosAB = a.dot(b) / (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)
    dframe.info()
    dframe.head()
    ## 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)
    plt.plot(y)
    plt.show()
    ## Scatter plot
    M = pd.read_csv("filename", header=None).as_matrix()
    x = M[:,0]
    y = M[:,1]
    plt.scatter(x,y)
    ## Histogram
    x = np.random.randn(1000)
    plt.hist(x)
    plt.show()
    ## 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")
    plt.show()

     

Advertisements
Categories: Python

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
export PROJECT_HOME=$HOME/Devel
source /usr/local/bin/virtualenvwrapper.sh

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

Simple Example using Unit Testing in Python

March 13, 2015 Leave a 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 fibonacci.py 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:
        result.append(b)
        a, b = b, a+b
    return result

def main():
    print fib2(100)

if __name__ == '__main__' : main()

And here simple testfibo.py 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)
        self.assertEqual(wanted_result,test_result)

    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)
        self.assertEqual(wanted_result,test_result)

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

Run testfibo.py script with command

python testfibo.py

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

OK
Categories: Programming, Python

CodeIgniter & TokuMX

February 4, 2015 Leave a comment

CodeIgniter is a lightweight PHP framework that can help you to develop Web Application. TokuMX is a drop-in replacement for MongoDB, that support transaction.

You can download codeigniter from here, and TokuMX from here . For more information about how to install TokuMX, you can read TokuMX documentation from GitHub here.

To Make Web Application can connect to Mongo Instance, you need to install PHP extension for mongo. To Install in Centos or Redhat environment, run command :

pecl install mongo

and add to /etc/php.ini

extension=mongo.so

Restart Web Service

service httpd restart

Download codeigniter-mongo-library from here .

Here’s simple code example how to use codeigniter-mongo-library to perform CRUD operation.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller
{
  // Insert Operation
  public function mongo_insert_test()      
  {
     $this->load->library("cimongo/cimongo");
     for($i=0;$i<25;$i++) {
        $this->cimongo
            ->insert("testData", array("x" => $i, "y" => 25-$i ));
     }
  }

  // Select Operation 
  public function mongo_select_test()
  {
     $this->load->library("cimongo/cimongo");
     $mongo_data = $this->cimongo->get("testData");
     foreach($mongo_data->result_array() as $row) {
        echo sprintf('x:%d,y:%d <br>',$row['x'],$row['y']);
     }
  }
  
  // Update Operation
  public function mongo_update_test()
  {
     $this->load->library("cimongo/cimongo");
     $result = $this->cimongo->where(array("x" => 24 ))
                    ->set(array("x" => 25 ))->update("testData");
     echo $result
  }

  // Delete Operation
  public function mongo_delete_test()
  {
     $this->load->library("cimongo/cimongo");
     $result = $this->cimongo->where(array("x" => 25 ))
                    ->delete("testData");
     echo $result;
  } 

}

?>

 

Categories: Database, Mongo, PHP, Programming

Facebook Login with Code Igniter

January 7, 2015 1 comment

Requirement:

  • Code Igniter 2
  • Facebook SDK 3.2.3 (consist of facebook.php & base_facebook.php, put them in libraries folder)

Controllers Code

  • application/controllers/user_auth.php (Handle login process)
    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    class User_auth extends MY_Controller
    {
        public function __construct()
        {
            parent::__construct();
        }
        
        private function load_fb()
        {
            $fb_config = array(
                'appId'  => $this->config->item('apps_facebook_id'),
                'secret' => $this->config->item('apps_facebook_secret'),
            );
            
            $this->load->library('facebook',$fb_config);
        }
        
        public function login()
        {
            $this->load->helper('url');
            $this->load_fb();
            $user = $this->facebook->getUser();
    
            if($user)
            {
                try 
                {
                    $profile_data = $this->facebook->api('/v2.1/me?fields=id');
                    $this->session->set_userdata(
                      'blablabla',intval($profile_data['id'],10)
                    );
                } 
                catch (FacebookApiException $e) 
                {
                    $user = null;
                }            
            }
            else
            {
                $this->facebook->destroySession();
            }   
            redirect(site_url('welcome/index'));
        }
        
        public function logout()
        {
            
            $this->session->unset_userdata('blablabla');
            redirect(site_url('welcome/index'));    
        }
    }
    
    ?>
  • application/controllers/welcome.php (User access /welcome/index page)
    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    class Welcome extends MY_Controller
    {    
        public function __construct()
        {
            parent::__construct();
        }
        private function load_fb()
        {
            $fb_config = array(
                'appId'  => $this->config->item('apps_facebook_id'),
                'secret' => $this->config->item('apps_facebook_secret'),
            );
            
            $this->load->library('facebook',$fb_config);        
        }
        
        public function index()
        {   
            $this->load->helper('url');
            $fb_id = intval($this->session->userdata('blablabla'),10);
            $page_data = array();
            if(!empty($fb_id) && ($fb_id>0) )
            {
                $page_data['facebook_data']['logged_in'] = true;
                $page_data['facebook_data']['logout_url'] = 
                               site_url('user_auth/logout.php');
            }
            else
            {
                $page_data['facebook_data']['logged_in'] = false;
                $this->load_fb();
                $page_data['facebook_data']['login_url'] = 
                  $this->facebook->getLoginUrl(array(
                    'display' => 'popup',
                    'redirect_uri' => site_url('user_auth/login.php'), 
                    'scope' => array("email,public_profile,user_friends")
                ));
                
            }
            
            $this->load->view('welcome_view', $page_data);
        }
        
    }
    
    ?>

View Code

  • application/views/welcome_view.php (Put login/logout button  here)
    <html>
    <head>
      <title>Hello</title>
    </head>
    <body>
    <div id="fb-root"></div>
    <script>
        window.fbAsyncInit = function () {
          FB.init({
            appId: '<?php echo $facebook_data['apps_id'] ?>',
            version : 'v2.1',
            status: true,
            cookie: true,
            xfbml: true
          });          
        };
    
        (function (doc) {
          var js;
          var id = 'facebook-jssdk';
          var ref = doc.getElementsByTagName('script')[0];
          if (doc.getElementById(id)) {
            return;
          }
          js = doc.createElement('script');
          js.id = id;
          js.async = true;
          js.src = "//connect.facebook.com/en_US/sdk.js";
          ref.parentNode.insertBefore(js, ref);
        }(document));
        
        function Login() {
          FB.login(function (response) {
            if (response.authResponse) {
              location.replace(<?php echo site_url("user_auth/login.php");?>);
            } else {
              alert("Login attempt failed!");
            }
          }, { scope: 'email,public_profile,user_friends' });
        }
    </script>
    <div id="top_menu">
        <?php if(isset($facebook_data['logged_in']) && 
                 ($facebook_data['logged_in'] != false)  ) : ?>
            <div id="logout">
              <a href="<?php echo $facebook_data['logout_url'];?>" >Logout</a>
            </div>
        <?php else : ?>
            <div id="login">
              <a onclick="Login();" href="javascript:void(0);" >Login</a>
            </div>
        <?php endif; ?>
    </div>
    </body>
    </html>

Simple Callback

January 7, 2015 Leave a comment

Callback is a function that is executed when some other function is done with its work.

Example Code:

using UnityEngine;
using System.Collections;

public class SimpleCallback : MonoBehaviour 
{
    delegate void delegateCaller();

    void DoACall()
    {
        Debug.Log("Do A Call");
    }

    void DoAnotherCall()
    {
        Debug.Log("Do Another Call");
    }

    IEnumerator StartATask(delegateCaller callThis)
    {
        Debug.Log("Starting...");
        yield return new WaitForSeconds(1);
        Debug.Log("Done.");
        callThis();
    }

    // Use this for initialization
    void Start () 
    {
        StartCoroutine(StartATask(DoACall));
        StartCoroutine(StartATask(DoAnotherCall));
    }
    

}

Output

Starting...
Starting...
Done.
Do A Call
Done.
Do Another Call
Categories: C#, Programming, Unity

Create Simple Loading Screen

December 16, 2014 Leave a comment

Just try to create simple Loading screen during the idle time …

  1. Create Folders Scripts, Scenes, and Textures in Assets Folder
    • Scenes
      • Loading.unity (Set Background in Main Camera to Black)
      • Scene01.unity
      • Scene02.unity
    • Scripts
      • Base
        • PersistentObject.cs
      • Game
        • Scene01Controller.cs
        • Scene02Controller.cs
      • Loading
        • LoadingManager.cs
        • LoadingScript.cs
        • Fading.cs
    • Textures
      • fadeout_texture.png (black image 2×2 pixels) imported as texture
  2. Write Script
    • PersistentObject.cs
      using UnityEngine;
      using System.Collections;
      
      public abstract class PersistentObject<T> : 
      MonoBehaviour where T : Component {
          private static T instance;
          
          void Awake() {
              if (instance == null) {
                  instance = GetComponent<T>();
                  DontDestroyOnLoad(gameObject);
                  OnAwake();
              } else {
                  Destroy(gameObject);
              }
          }
          
          protected virtual void OnAwake() {
              
          }
      }
    • Fading.cs
      using UnityEngine;
      using System.Collections;
      
      public class Fading : MonoBehaviour 
      {
          public Texture2D fadeOutTexture;
          public float fadeSpeed = 0.8f;
      
          private int drawDepth = -1000;
          private float alpha = 1.0f;
          private int fadeDir = -1;
      
          void OnGUI()
          {
            alpha += fadeDir * fadeSpeed * Time.deltaTime;
            alpha = Mathf.Clamp01(alpha);
      
            GUI.color = new Color(GUI.color.r,GUI.color.g,GUI.color.b,alpha);
            GUI.depth = drawDepth;
            GUI.DrawTexture(new Rect(0,0, Screen.width, Screen.height), 
                            fadeOutTexture);
      
          }
      
          public float BeginFade(int direction)
          {
              fadeDir = direction;
              return fadeSpeed;
          }
      
          void OnLevelWasLoaded()
          {
              BeginFade(-1);
          }
      }
    • LoadingManager.cs
      using UnityEngine;
      using System.Collections;
      
      public class LoadingManager : PersistentObject<LoadingManager
      {
          private string _nextScene = "Scene01";
          public string NextScene { get { return _nextScene;} }
          public void Load (string name) {
              _nextScene = name;
              Application.LoadLevel("Loading");
          }
          IEnumerator WaitAndLoad() { 
              float fadeTime = Component.FindObjectOfType<Fading>().BeginFade(1);
              yield return new WaitForSeconds(fadeTime);
              Application.LoadLevel("Loading");
          }
       }
    • LoadingScript.cs
      using UnityEngine;
      using System.Collections;
      
      public class LoadingScript : MonoBehaviour 
      {
          [SerializeFieldprivate GUIText textLbl;
          private float progress;
          AsyncOperation op;
          
          IEnumerator Start() {
              yield return new WaitForSeconds(0.2f);
              LoadingManager loadingManager = 
              Component.FindObjectOfType<LoadingManager>();
              op = Application.LoadLevelAsync(loadingManager.NextScene);
              yield return op;
          }
          
         void Update() {
              if( (op!=null) && (!op.isDone) ) {
                  progress = op.progress * 100f;
                  textLbl.text = "Loading.. " + progress" %";
              }
          }
      }
      
    • Scene01Controller.cs
      using UnityEngine;
      using System.Collections;
      
      public class Scene01Controller : MonoBehaviour 
      {
          void OnGUI() {
              GUILayout.BeginArea (new Rect (10,10,100,100));
              if(GUILayout.Button("Scene02")) {
                  var loadingManager = 
                  Component.FindObjectOfType<LoadingManager>();
                  loadingManager.Load("Scene02");
              }
              GUILayout.EndArea ();
          }
      }
    • Scene02Controller.cs
      using UnityEngine;
      using System.Collections;
      
      public class Scene02Controller : MonoBehaviour 
      {
          void OnGUI() {
              GUILayout.BeginArea (new Rect (10,10,100,100));
              if(GUILayout.Button("Scene01")) {
                  var loadingManager = 
                  Component.FindObjectOfType<LoadingManager>();
                  loadingManager.Load("Scene01");
              }
              GUILayout.EndArea ();
          }
      }
  3. Attach Script
    • LoadingScript.cs & LoadingManager.cs
      Create 2 empty game objects (LoadingScript and LoadingManager) in Loading.unity and attach these script
    • Fading.cs
      Attach this script to LoadingManager game object in scene Loading.unity and assign fadeout_texture texture
    • Scene01Controller.cs
      Create 1  empty game object in Scene01.unity and attach this script
    • Scene02Controller.cs
      Create 1 empty game object in Scene02.unity and attach this script
  4. Attach GUIText Component
    • Attach GUIText Component to LoadingScript.cs empty game object (step3)
    • Set text to “Loading ..”
    • Set position to (0.5,0.5,0.0)
    • Set Anchor value to “middle center” and Alignment to “center”
    • Drag this GUIText Component to variable textLbl in LoadingScript.cs inspector
  5. Include Scenes in Build Settings
    • Loading.unity
    • Scene01.unity
    • Scene02.unity
  6. Test
Categories: Game and CG, Programming, Unity