Android

Create alphabet list in Android using GridView

28 Nov , 2012  

We will build a trivial android app that create alphabet list using GridView. Fyi, Gridview is under ViewGroup that contains several View. I use Android 2.3.3 in this example. So, we can start create a new project called “Demo” and use “MainActivity” as main class.

src/com/yodi/demo/MainActivity.java

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
package com.yodi.demo;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        // Generate alphabet
        String[] numbers = new String[26];
        char letter;
        int i;
       
        for(letter='a', i=0; letter < ='z'; letter++, i++) {
            numbers[i] = String.valueOf(letter);
        }
       
        // Get gridview layout from XML
        GridView gridView = (GridView) findViewById(R.id.gridview);
       
        // Set Adapter to connecting between context data and layout
        ArrayAdapter<String> adapter = new ArrayAdapter<string>(this,
                android.R.layout.simple_list_item_1, numbers);
       
        // Set gridview using array adapter
        gridView.setAdapter(adapter);
       
        // Create handler for clicked item action
        gridView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView< ?> parent, View v, int position, long id) {
                Toast.makeText(MainActivity.this, "" + position, Toast.LENGTH_SHORT).show();
            }
        });
    }

}
</string>

More…

,

Python

Be carefull when creating list in Python using bracket [] or list() method

28 Nov , 2012  

There are big difference between list() and [] in Python. The first one for list() it will seeking iterable objects and make the object into list. The second one will be just wrap the object into list type.

The same object with same result:

1
2
3
4
a = list(1)
b = [1]
print(a)
print(b)

More…

,

Python

Learning how to read pseudo algorithm code and apply into Python code : Insertion Sort

27 Nov , 2012  

Learning and applying algorithm in Python must be fun! In this example, we will try read Algorithm pseudo-code and applied into Python code. We will start with “Insertion Sort”. What is this algorithm? Basically in each repetition, it will remove the element and put it into correct position in “sorted list”.

Here is visual example by Wikipedia:

Now, we get the pseudo-code for this algorithm is :

1
2
3
4
5
6
7
8
Insertion-Sort(A)
for j < - 2 to length[A]
     do key <- A[j]
           i <- j - 1
           while i > 0 and A[i] > key
                  do A[i+1] < - A[i]
                        i <- i - 1
            A[i + 1] <- key

More…

,

Server

Install LXML in Debian

26 Nov , 2012  

To install LXML python module in Debian, you need to install depedency packages :

1
apt-get install python-dev libxml2 libxml2-dev libxslt1-dev libbz2-dev libssl-dev p7zip-full rar lha unrar unzip unace unp bzip2 gzip patch

Then, you can install lxml by :

1
pip install lxml

Basic

How to reverse variable array using pointer to pointer in C++

24 Nov , 2012  

Pointer to pointer is an reference that contain another pointer memory address. Remember, the reason it’s called pointer because it’s just pointing to another place that have “value”. Pointer is different with pointer to pointer. This is the simple explanation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>
#include<str using namespace std;

int main() {
    int customer = 1;
    int *pointerCustomer;
    int *pointerToPointerCustomer;

    pointerCustomer = &customer; // 1
    pointerToPointerCustomer = &pointerCustomer; // 2

    cout << **pointerToPointerCustomer; // 3

    return 0;
}

More…

,

Basic

How to counting array size and total element in C++

24 Nov , 2012  

Array in C++ is just same as variables that organized into one place. Basically, each element in array just stored sequentially in memory. To get the length of array, it just simple by get the size of array and divided it by the data type size. Since the way array stored the value sequentially, then it’s safe to doing this way:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
using namespace std;

int main() {
    int student[] = {1, 2, 3};

    // Showing size of student array
    cout << sizeof(student);
    cout << "n";
    // Showing the element by divided by the data type size
    cout << sizeof student / sizeof(int);
    return 0;
}

Thanks to +Jon Dubovsky that’s give another response that we should carefull of using this kind of approach. We change the “student” int array into int (not array), this code still works but showing wrong results. That’s mean silently fail.

We can passing into as function to make compiler see the declaration of variable. The problem is array is just the way of organizing variables into one reference. You can’t to pass it into method and doing size calculation on it.

In this is example, i use Template :

1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream>
using namespace std;

template<typename T, int size>
int countingArray(T(&)[size]){return size;}

int main() {
  int students[] = {1, 2, 3};
  cout << countingArray(students) << endl;

  return 0;
}

,

Python

Pretty print dictionaries or another data in Python tricks

23 Nov , 2012  

Supposed we have a nested dictionary. We want to print the data inside dictionary in decent format. Example, we have dictionary:

1
a = {1: 'Hello', 2: 'World', 3: {1: "Python", 2: "C++"}}

We usually print this using print() and showing exact format. There is some trick to pretty print this data using JSON.
Wait, JSON? yes, we will convert this data into JSON and print with indentation, like:

1
2
3
4
import json

a = {1: 'Hello', 2: 'World', 3: {1: "Python", 2: "C++"}}
print(json.dumps(a, indent=4))

This will give us results:

1
2
3
4
5
6
7
8
{
    "1": "Hello",
    "2": "World",
    "3": {
        "1": "Python",
        "2": "C++"
    }
}

Nice right? 🙂

,

Python

Static Method / Class Method example in Python

23 Nov , 2012  

Methods is sub-routine that associated with class. Usually, we can using the method inside a class from the instance objects. Static method / Class method is refering to accessing method using Class explicitly. That means to using method inside class, we’re using Class.. Let see the example of Class method in Python:

1
2
3
4
5
6
class Hello:
    def result(self, name):
        print("Hello " + name)

if __name__ == "__main__":
    Hello.result("", "Yodi")

More…

,

Java

Seeing the workflow of Class Inheritance in Java

22 Nov , 2012  

When it comes to Inheritances, that means we try using code reuse. In Java, Python, C++, Inheritance is a common thing since we want to reduce duplicate code and manage them easily. In Java, we can create a subclass by inheriting from parent using “extends”. Here is some trivial example:

InheritanceImplementation.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.lang.String;

class Bank {
    private int id;
    private String type;
   
    public Bank() {
        System.out.println("Creating Bank... ");
    }
}

public class InheritanceImplementation {
    public static void main(String[] args) {
        System.out.println("Execute main programm... ");
        Bank bank = new Bank();
        System.out.println("Bank object created... ");

    }
}

We create a new “parent” class called “Bank” with constructor that showing information when this class instantiated. Then inside the main(), we put information about when this main executed and when the object created. The results as we predicted is :
More…

,

Python

Understanding assigment operator in Python from copying list or dictionary experience

22 Nov , 2012  

When it comes to copy a variable into new variable, a few begginer will found that something weird happen when they modified the new variable.
Yes, the old variables state will get updated as well soon new variable edited. This is some basic example:

1
2
3
4
5
a = {1: "Hello"}
b = a
print(b[1])    # showing Hello
b[1] = "World"
print(a[1])    # showing World

Hey, what is this in Python? Fyi, the way we creating variable in Python is so simple like we create a “label” / “tag” or “pointer” which it’s simple reference to underlying object. So, as you see on example above, “a” and “b” is just simple reference that pointed into same object which have type “dictionary”. All changes that has been made in variable “b” will obviously affecting “a” which they pointed into same resources / object.
More…

, ,

Python

Showing python module help or documentation inside Python Intrepeter in good display / format

21 Nov , 2012  

When we need to import some python modules, sometimes we need to read the documentation inside the python intrepeter.
There are 2 ways to showing help / documentation of the module.

1. __doc__
We can see by print attribute “__doc__” from the module. Example, I use module “copy”:

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
import copy

print(copy.__doc__)
Generic (shallow and deep) copying operations.

Interface summary:

        import copy

        x = copy.copy(y)        # make a shallow copy of y
        x = copy.deepcopy(y)    # make a deep copy of y

For module specific errors, copy.Error is raised.

The difference between shallow and deep copying is only relevant for
compound objects (objects that contain other objects, like lists or
class instances).

- A shallow copy constructs a new compound object and then (to the
  extent possible) inserts *the same objects* into it that the
  original contains.

- A deep copy constructs a new compound object and then, recursively,
  inserts *copies* into it of the objects found in the original.

Two problems often exist with deep copy operations that don't exist
with shallow copy operations:

 a) recursive objects (compound objects that, directly or indirectly,
    contain a reference to themselves) may cause a recursive loop

 b) because deep copy copies *everything* it may copy too much, e.g.
    administrative data structures that should be shared even between
    copies

Python's deep copy operation avoids these problems by:

 a) keeping a table of objects already copied during the current
    copying pass

 b) letting user-defined classes override the copying operation or the
    set of components copied

This version does not copy types like module, class, function, method,
nor stack trace, stack frame, nor file, socket, window, nor array, nor
any similar types.

Classes can use the same interfaces to control copying that they use
to control pickling: they can define methods called __getinitargs__(),
__getstate__() and __setstate__().  See the documentation for module
"pickle" for information on these methods.

More…

,

Java

Example of clone array in Java

20 Nov , 2012  

To making copy of array in Java, we can use method “clone” in the array objects.
First step, we need to create one-dimensional array :

1
2
// Create first array variable
float[] floatArray = {5.0f, 3.0f, 1.5f};

This will create an array objects with 3 elements. We can clone this by:

1
2
// Create clone variable
float[] cloneArray = floatArray.clone();

All modification between two variable will not related each others.
Here is the details:
More…

,

implementation

Implementation of User-Defined data using Struct in C++

20 Nov , 2012  

There are two kind group of data type that needed to reserve amount memory, primitive data and user-defined data. Primitive data just like Int (4 byte), Char (1 byte), Double (8 byte) and so on. But what about we construct our custom data types, like a new data type that contains Int and Char? Then this is called user-defined data.

Basically, we just gathering two or more primitive data into one new data type. For instance, first we have Customer and Grade variable:

1
2
int customer;
string address;

More…

,

Uncategorized

Free Google Apps Mail for Domain

19 Nov , 2012  

Nowadays hard to find Google Free Apps Domain which used to be easy. But don’t worries, because Google still provide Free Version of Google Apps but in hidden menu.

Here is to go Free Google Apps Mail for Domain

,

Java

Grab Twitter Search JSON using simple JAVA bufferStream

18 Nov , 2012  

Open JSON files from twitter search using JAVA is easy. We can use simple buffer stream reader. Here is the example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.io.BufferedReader;  // 1
import java.io.InputStreamReader;
import java.net.URL;

public class OpenWebsite {
    public static void main (String[] args) throws Exception { // 2
    URL twitter = new URL("http://search.twitter.com/search.json?q=" +
                  "blue%20angels&rpp=5&include_entities=true" +
                  "&result_type=mixed"); // 3
    BufferedReader in = new BufferedReader(
        new InputStreamReader(twitter.openStream())); // 4
   
    String output;  // 5
    while((output = in.readLine()) != null) {
        System.out.println(output);  // 6
    }
    }
}

More…

Django

Django queryset filter equal or compared based on another column / fields within same models

15 Nov , 2012  

There will be a case when we want to filtering data that have “equal” between one fields with another fields (column) on same models.
Given example, We have Django built-in user table called “auth_user” and user profile table called “user_profile”. The requirement is we want to get all users that not-logged and have status “GAMER” in their profile.

At this cases, that means we need to compare between “date_joined” and “last_login” column.

Here is the raw mysql:

1
Select COUNT(*) from user_profile AS t1 INNER JOIN auth_user AS t2 ON t1.user_id = t2.id AND t1.status="GAMER" AND t2.last_login = t2.date_joined;

Now, how to make it in Django queryset? Say thanks to “F” objects! Django have a lot of magic gem inside.

How to use it? Here is the example:

1
2
3
4
gamers = User.objects.filter(
             userprofile__status='GAMER',
             date_joined__eq=F("last_login")
         ).order_by('last_login')

Easy! 🙂

,

Java

Example using Map in Java

9 Nov , 2012  

The Map Interface in Java just like dictionaries in Python. It have function to create key – value data structure which each key must be unique. In Java term, this data structure create association between one object to another object.

This is how to use Map() interface in Java:

Filename: MapExample.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// I need to import Map and HashMap interface
import java.util.HashMap;
import java.util.Map;

// I create public class to make class loader find implementation for this files
public class MapExample {
    public static void main(String[] args) {

        // I create new params variable with mapping Integer, String objects associated as key-value
        Map<Integer, String> params = new HashMap<Integer, String>();
     
        // I create a new key-value {1: "Hello World}
        params.put(1, "Hello World");

        // I print params data structure and it's value
        System.out.println(params);
    }  
}

When we execute the code, it will return:

1
{1=Hello World}

We can store objects inside Map() Interface.

OS

Solve Firefox webdriver selenium Failed to dlopen /usr/lib/libX11.so.6 in Fedora

9 Nov , 2012  

I use Selenium for testing, usually I use ChromeDriver which more fast and smoothly than firefox. In case you have failed when using Selenium with Firefox WebDriver and got this issue :

1
WebDriverException: Message: 'The browser appears to have exited before we could connect. The output was: Failed to dlopen /usr/lib/libX11.so.6ndlerror says: /usr/lib/libX11.so.6: wrong ELF class: ELFCLASS32n'

The solution is easy:
More…

,

Python

Private in Python with double underscore instead of one underscore

8 Nov , 2012  

Updated that I was wrong about private variable in Python and get corrected by my friends : http://eugene-yeo.me/

I believe there are a few people thinking single underscore “_” is for create private variable in Python. Well, this is not right anyway. To make it easy for explaining, let see this socket modules in Python
http://svn.python.org/projects/python/trunk/Lib/socket.py at this line:

1
2
3
4
import _socket
from _socket import *
from functools import partial
from types import MethodType

More…

,

Python

Django admin execute action without selecting all objects

7 Nov , 2012  

There will be a task when you need to create a new action like “export to XML / CSV” and execute this action without selecting any objects / records. Technically, that’s mean how we doing response_action inside changelist_view() in Django admin without selecting any partial / all objects. This also will works if you using filter, search, etc.

As you know, if you’re create an “action” in django admin, that action will be executed only if you have selected records / objects. First thing we need to know is why we can’t running action without selected the records in django admin?

What the reason behind this? Here in https://github.com/django/django/blob/master/django/contrib/admin/options.py.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)

# Actions with no confirmation
if (actions and request.method == 'POST' and
        'index' in request.POST and '_save' not in request.POST):
    if selected:
        response = self.response_action(request, queryset=cl.get_query_set(request))
        if response:
            return response
        else:
            action_failed = True
    else:
        msg = _("Items must be selected in order to perform "
                "actions on them. No items have been changed.")
        self.message_user(request, msg)
        action_failed = True

More…

,

Python

Python map with two or more arguments

7 Nov , 2012  

Built-in Python function map() is best way to iterate and generate a new list from given list. Usually we using one arguments when passing objects into function inside map(), eg:

1
map(show_records, list_records)

At this example, x from list_records will passed into show_records(x). But, how to passing multiple arguments into map() ?
Basically, it’s easy with lambda():

1
map(lambda x: show_records(x, some_new_params), list_records)

And you can receive some_new_params in show_records(x, some_new_params) 🙂

,

Django

Django send email on localhost and using Template for content

2 Nov , 2012  

The most common things while developing django application is sending email. Django have built-in function for sending email called “send_email” under django.core.mail. When we using long text of emails content and testing in our local, then we need to set it working on localhost and templating.

1. Set up django send email on local
We can print email on console by edit this settings.py part:
More…

,