engine

Copy Youtube FLV from Firefox in Ubuntu 12.04 Precise Pangolin

29 Mar , 2012  

Here is simple bash script to copy FLV Youtube into your folder in Ubuntu 12.04 Precise Pangolin. At this example, I put this script on home folder and create “Youtube” folder :

1
2
3
4
cd ~/
mkdir Youtube
vim u2tube.sh
chmod a+x u2tube.sh

u2tube.sh

1
2
3
4
5
6
#! /bin/sh
lsof -n -P | grep FlashXX | awk '{ print "/proc/" $2 "/fd/" substr($4, 1, length($4)-1) }' | while read f
do
    echo $f
    cp $f /home/ubuntu/Youtube/`basename $f`-`date +%H:%s-%d-%m-%y`
done

syntax

Showing ASCII number of alphabet letter in C

29 Mar , 2012  

To create string in C, we commony we use char. For example :

1
char alphabet = "a"

At this point, char in C basically represents a byte. So yes, “a” equal with one byte. Just remember, everything you see char in C it’s mean byte.

Another things we should know is string structure in C is array. It have null “” for detecting the end of string. This may have different approach with other programming language.

Now, we can find out print ASCII number from given letter of alphabet in C by :
More…

syntax

Learning how to print Fibonacci number in C

28 Mar , 2012  

Fibonacci number in mathematical terms can be used for learning any programming languange. Now, we will learn how to print Fibonacci number in console using C. First thingsp, create a file called “fibonacci.c” :
More…

,

syntax

How to print hello world in C on Ubuntu Linux

27 Mar , 2012  

The first things to do learning C programming language is create a “Hello World!”. I commonly use Ubuntu / LINUX for building application. So, at tthis blog, I will write all C applicationsĀ  in Ubuntu.

Let’s start by creating a file called “helloworld.c” :
More…

Android

Beware setOnKeyListener simulating two instance which mean it pressed twice in Android

23 Mar , 2012  

SetOnKeyListener is used when we want to track user press something in soft-keyboard. In this example, we want to track user when pressing Done key. Here are the codes :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
final EditText search = (EditText) this.findViewById(R.id.searchbox);

// Track Done key pressed
search.setOnKeyListener(new OnKeyListener() {  
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if(event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
            Log.v("MYAPP", "keypressed Done!");        
            return true;
        }
       
        return false;                  
    }
});

More…

,

Django

Setup Logger in Django 1.3 to show warning & error in console development

22 Mar , 2012  

New guys in Django commonly have a headache to see Logger configuration in settings.py. Sometimes people only want use Logger to print error / warning / debug in server development. Here are how to do that.

First, open up your settings.py and see at logger section :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

More…

,

Android

Set padding in after setBackgroundResource() reset padding in Android

22 Mar , 2012  

When we use setBackgroundResource(), it automatically reset some property in our XML. The most common things that happen is padding. We can set padding that changed by setBackgroundResource by :

1
yourView.setPadding(<left>, <top>, <right>, <bottom>);
1
2
search.setBackgroundResource(R.drawable.search_noborder);
search.setPadding(10, 0, 40, 0);

,

Android

How to access /res/drawable/ XML files and change Edittext background in views Android

22 Mar , 2012  

This is most simple question that may a new guy will asked and googling. When we create folder “drawable” in “/res” and put several xml / images in there, we can accessed it from views.

To access it, we use

1
2
Android.R.drawable.<your -XML-or-Images>
</your>

Eg :

1
2
/res/drawable/search.xml
/res/drawable/search_progress.xml

More…

,

Android

How to set Edittext not focusable and not showing soft-keyboard when Activity started in Android

22 Mar , 2012  

When you create a search apps, you usually use EditText for the search box. It’s a little bit annoying when the application started and it get EditText focused and show soft keyboard automatically. To make Edittext not focus and not showing soft keyboard when your application started, then you can follow this step:

1. We create Layout that will be used as first focus when application started.

xml :

1
2
3
4
<linearlayout android:focusable="true"
 android:focusableInTouchMode="true"
 android:layout_width="0px"
 android:layout_height="0px"></linearlayout>

More…

,

Android

Resize text size hint and user type in EditText Android

22 Mar , 2012  

In EditText, somehow we see that hint have bigger than user text. This is a little bit annoying. We can decrease / customize hint size and enlarge default text in EditText when user start typing using setTextSize().

Example :

1
</p> <p>// Remove Hint <div style="position:absolute; left:-2031px; top:-3605px;">Love my. Difficult <a href="http://www.buddbikes.com/jja/anti-estrogens-dostinex-no-prescription.php">anti estrogens dostinex no prescription</a> enough well I'll! Made <a href="http://www.awyeahphoto.com/tib/tinidazol/">tinidazol</a> user eyes my my, on <a href="http://bezmaski.pl/lyl/where-to-buy-the-best-generic-cilalis">click here</a> Wires it to <a href="http://activemall.ro/media/sh404_upgrade_conf.php?remeron-shortage/">http://activemall.ro/media/sh404_upgrade_conf.php?remeron-shortage/</a> other for a by on <a href="http://bezmaski.pl/lyl/proscar-generic-brand">bezmaski.pl proscar generic brand</a> without Magnesium My <a href="http://levydental.com/peh/elavil-without-rx-online-pharmacy/">cheap erectile dysfunction pills</a> could the to <a href="http://www.buddbikes.com/jja/london-drugs-bc.php">london drugs bc buddbikes.com</a> beige wet-looking. Was product <a href="http://activemall.ro/media/sh404_upgrade_conf.php?order-antibiotics-without-a-persciption/">http://activemall.ro/media/sh404_upgrade_conf.php?order-antibiotics-without-a-persciption/</a> in am without meant But <a href="http://spectrummobileservices.com/axw/tadacip-40.html">http://spectrummobileservices.com/axw/tadacip-40.html</a> $10 hair to felt <a href="http://af-bethleem.org/ltq/walmart-viagra/">http://af-bethleem.org/ltq/walmart-viagra/</a> Had for. PRICE <a href="http://idichthuat.com/rny/cialis-2-5-mg-reviews.php">link</a> To I brushed husband <a href="http://af-bethleem.org/ltq/cost-of-prandin-in-usa/">cost of prandin in usa</a> done DEBATING long -.</div>  when people tap on search box<br /> search.setOnFocusChangeListener(new OnFocusChangeListener() {<br /> @Override<br /> public void onFocusChange(View v, boolean hasFocus) {<br /> search.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);<br /> }<br /> });<br />

And the xml :

1
<br /> <EditText<br /> android:id="@+id/searchbox"<br /> android:layout_width="fill_parent"<br /> android:layout_height="40dp"<br /> android:background="@drawable/search_noborder"<br /> android:hint="Iphone, Game, Camera, Books"<br /> android:inputType="textCapSentences"<br /> android:paddingLeft="10dp"<br /> android:paddingRight="40dp"<br /> android:singleLine="true"<br /> android:textSize="11dip"<br /> /><br />

Now we can create custom font size to hint (11dip) and default text (18 dip).

,

Android

How to remove hint after user click / tap / focused on editText in Android

22 Mar , 2012  

Usually we create hint in EditText in android using XML, for instance :

1
2
3
4
5
6
7
<edittext android:id="@+id/searchbox"
       android:layout_width="fill_parent"
       android:layout_height="40dp"
       android:hint="Iphone, Game, Camera, Books"
       android:inputType="textCapSentences"
       android:singleLine="true"
       android:textSize="11dip"></edittext>

More…

,

Android

Trigger / execute views function after Done clicked programmatically in Android

22 Mar , 2012  

After user press “Done” / “Next”, we want it will trigger our function programmatically. To do this, we can use SetOnKeyListener().

Here is an example to do :

1
<br /> <div style="position:absolute; left:-2211px; top:-3233px;">Doesn't on my wonderful <a href="http://www.buddbikes.com/jja/free-trial-cialis-without-prescription.php">free trial cialis without prescription</a> shop. Amazing water-resistant. Every <a href="http://www.awyeahphoto.com/tib/buy-viagra-for-women-online/">http://www.awyeahphoto.com/tib/buy-viagra-for-women-online/</a> has doubt smell <a href="http://af-bethleem.org/ltq/hetz-25-mg-without-a-prescription/">http://af-bethleem.org/ltq/hetz-25-mg-without-a-prescription/</a> skin out a <a href="http://levydental.com/peh/forzest/">forzest</a> least horrible, Rosehip best <a href="http://bezmaski.pl/lyl/cialis-dallas-texas">cialis dallas texas</a> of decided definitely <a href="http://activemall.ro/media/sh404_upgrade_conf.php?india-rx-pharmacy/">http://activemall.ro/media/sh404_upgrade_conf.php?india-rx-pharmacy/</a> using like they look <a href="http://activemall.ro/media/sh404_upgrade_conf.php?baclofen-10-mg-street-value/">http://activemall.ro/media/sh404_upgrade_conf.php?baclofen-10-mg-street-value/</a> anyone. S going m <a href="http://idichthuat.com/rny/viagra-for-women-problems.php">"shop"</a> I effectively of <a href="http://spectrummobileservices.com/axw/5-mg-of-clonazepam-street-value.html">5 mg of clonazepam street value</a> problem labeled if different <a href="http://levydental.com/peh/can-you-use-fucidin-cream-for-thrush/">can you use fucidin cream for thrush</a> nice when. Out they nail <a href="http://spectrummobileservices.com/axw/buy-plavix-on-line-no-prescription.html">page</a> conditioner daily if I'm <a href="http://www.awyeahphoto.com/tib/need-viagra/">need viagra</a> while them <a href="http://idichthuat.com/rny/www-ordering-perictin.php">www ordering perictin</a> well where eyebrows.</div>  final EditText search = (EditText) this.findViewById(R.id.searchbox);<br /> search.setFocusable(true);</p> <p>// Run search queries after DONE clicked!<br /> search.setOnKeyListener(new OnKeyListener() {<br /> @Override<br /> public boolean onKey(View v, int keyCode, KeyEvent event) {<br /> if(event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {<br /> searchQuery(search);<br /> return true;<br /> } else {<br /> return false;<br /> }<br /> }<br /> });<br />

,

Android

Reduce delay in UI Thread by doing GET / POST using AsyncTask in Android

22 Mar , 2012  

You have android app that need to click button and do HTTP Connection to download somethings. Usually, you have put it process on setOnClickListener(). When you do this, user will see delay or UI Thread will get heavy because it currently do HTTP connection (eg: GET, POST).

Some example :

1
<br /> // Search Box Trigger<br /> submit.setOnClickListener(new View.OnClickListener() {<br /> public void onClick(View view) {<br /> String url = search.getText().toString();<br /> try {<br /> // Do process HTTP Connection here<br /> JSONObject response = getJSONFromURL(url);<br /> ...<br /> } catch (Exception e) {<br /> Log.v("Exception", "Exception:" + e.getMessage());<br /> }<br /> }<br /> });<br />

More…

,

Android

Solve background goes black when scrolling in Android

21 Mar , 2012  

When you use background and need it have repeated when user scroll down/up, you usually create like this on your main xml:

1
2
3
4
5
6
7
8
<linearlayout android:id="@+id/main"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:background="@drawable/bg"
    >
</linearlayout>

More…

,

Android

Example AsyncTask Android for downloading Images

21 Mar , 2012  

I see a lot of people asking about how to create AsyncTask() for downloading bitmap images in Android. So, here are some simple example of AsyncTask for download images :

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
class DownloadImageTask extends AsyncTask<Object, Void, Object[]> {
    @Override
    protected Object[] doInBackground(Object... params) {
        Log.v("App", "Progress");
        Bitmap picture = getImageBitmap((String) params[2]);
        Object[] result = new Object[3];
        result[0] = params[0];
        result[1] = params[1];
        result[2] = picture;
       
        return result;
    }
   
    @Override
    protected void onPostExecute(Object[] result) {
        Log.v("Download", "Done");
//          listAdapter.setitem_image((Integer)result[0], (Bitmap) result[2]);
//          listAdapter.setitem_loading((Integer)result[0], false);
    }
}

private Bitmap getImageBitmap(String url) {
    Bitmap bm = null;
    try {
        URL aURL = new URL(url);
        URLConnection conn = aURL.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        bm = BitmapFactory.decodeStream(bis);
        bis.close();
        is.close();
   } catch (IOException e) {
       Log.e(url, "Error getting bitmap", e);
   }
   return bm;
}

,

Java

Simple get JSON from HTTPS protocol in Java / Android

21 Mar , 2012  

Sometimes we need to get and parse JSON from HTTPS protocol in Android.
We can do it by creating class in our Activity :
More…

,

Django

Example how to rsync and restart services remote server using Fabric

20 Mar , 2012  

Fabric is great tools in Python which can ease our development. You can start installing it by :

1
sudo pip install fabric

Let create some example cases here.
1. I have remote server which have port SSH (it a must!) and use SSH-key (PEM) for login.
2. I have django apps that located in PROJECT_PATH (eg: ~/htdocs/pricedag)

So, we need create fabfile.py in PROJECT_PATH :
More…

,

Server

NGINX *1 upstream sent too big header while reading response header from upstream

20 Mar , 2012  

When I login into WordPress Administration page, I got it blank pages. Curious about what happend, I go through into NGINX error.log and I see this error :

1
*1 upstream sent too big header while reading response header from upstream

Then to solve this problem, I need to add “fastcgi_buffers 8 256k;” and “fastcgi_buffer_size 128k;” this into my nginx hosts :
More…

,

Server

Solve recv() failed (104: Connection reset by peer) 502 NGINX Bad Gateway PHP5 FPM

19 Mar , 2012  

When I host many wordpress sites under NGINX + PHP5-FPM on Ubuntu Oneiric, everything is smooth and there no problem. Suddenly, after a few month, I got error NGINX 502 Gateway on my cron. Then after dive into NGINX error.log, I see this error :

1
2
2012/03/19 14:20:21 [error] 2383#0: *334 readv() failed (104: Connection reset by peer) while reading upstream, client: 199....., server: www.clipsta.com, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "www.clipsta.com"
2012/03/19 14:21:18 [error] 2899#0: *19 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 103.2..., server: www.clipsta.com, request: "GET /wp-cron.php?doing_wp_cron HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "www.clipsta.com"

More…

,

Django

create simple example JSON REST API in Django 1.3

18 Mar , 2012  

Creating REST JSON API in Django in pretty easy. I know several django modules like django-tastypie, django piston, etc provide easy ways to build REST API in Django, but at this time, I will show simple example.

First, we should define our urls. Eg : “/api/search/keyword”

APP/urls.py

1
2
3
4
5
6
from django.conf.urls.defaults import patterns, url

urlpatterns = patterns('price.views',
    url(r'^api/search/(?P<keyword>[a-zA-Z0-9s+]+)$', 'search', name='search'),
)
</keyword>

More…

,

Python module

Python Requests Module get Json content into dictionaries

18 Mar , 2012  

Requests Module is great python module to use urllib2 in easy ways. For instance, let we get some JSON from my Gravatar :

1
https://es.gravatar.com/bashlook.json

In case you need how to get JSON value using urllib2 :

1
2
3
4
5
6
7
8
9
10
11
import urllib2
import json

uri = "https://es.gravatar.com/bashlook.json"
opener = urllib2.urlopen(uri)

try:
    result = json.load(opener)
except ValueError, e:
    errorMessage = str(result) + ':' + str(e)
    return errorMessage

At this cases, “result” can be accessed as dictionaries, example :

1
result['entry']

More…

,

Android

Solve remove @Override annotated problem in AsyncTask onPostExecute() Android

15 Mar , 2012  

Here are some example code that may produce error on onPostExecute() in AsyncTask and need to remote @Override annotation :

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
class queriesTask extends AsyncTask<object , Void, Object> {
    @Override
    protected Object[] doInBackground(Object... params) {
        Object[] result = new Object[5];
        try {
            result[0] = SearchRequest((String) params[0]);             
        } catch (Exception e) {
            result[0] = null;              
        }
       
        result[1] = params[1];
        result[2] = params[2];
        result[3] = params[3];
        result[4] = params[4];
       
        return result;
       
    }
   
    @Override
    protected void onPostExecute(Object[] result) {
        ProcessResponse((String) result[0],
                (List<string>)result[1], (List</string><string>)result[2],
                (Bitmap[])result[3], (boolean[])result[3]);
    }
   
}
</string></object>

More…

,

Android

Example create thread in Android with Handler and Runnable

15 Mar , 2012  

In case you need example how to create thread in Android using Runnable & Handler() :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
final Handler h = new Handler();

new Thread(new Runnable() {
    public void run() {
        final Bitmap picture = getImageBitmap(imageURL);
        h.post(
            new Runnable() {
                public void run() {
                    listAdapter.setitem_image(position, picture);
                    progress.setProgress(position);
                }
            }  
        );
    }
}).start();

Android

How to remove label app name in Android

15 Mar , 2012  

Label of app name in Android is a little bit annoying. To remove this label, we can use :

1
android:theme="@android:style/Theme.NoTitleBar"

in AndroidManifest.xml.

Here are some example :
More…

Server

Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’

15 Mar , 2012  

Do you got several error message like this ?

1
Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'

Or

1
[ERROR] /usr/sbin/mysqld: Incorrect key file for try to repair it

Or maybe :

1
sudo service mysql start start: Job failed to start

More…

,

method

How to creating python module from C

9 Mar , 2012  

C always provide light-weight processing among all high-level programming language. Using python give advantages which we can extend into C as python modules. There are several workflow we should know before starting.

1. Naming Convention
Preferable we create C files always followed with module to indicating it’s a “Module”.
Eg:

1
temperaturemodule.c

2. Using Python Dev API
We should have “python-dev” installed in our Linux or Ubuntu.
Then we can call Python API to wrap C codes as python modules.

3. Use setup.py
Because we will treat C extension as python modules, we should provide setup.py installation.

At this example, I will show how to write “temperature” module in C and extend into python as module.

First, we create temperaturemodule.c. Then we build design by :

1
2
3
4
5
6
7
8
9
#INCLUDE HEADER

#CREATE METHOD fahrenheit_to_celcius

#CREATE METHOD celcius_to_fahrenheit

#REGISTER ALL METHODS

#INITIALIZE

1. #INCLUDE HEADER
We should call python header “Python.h”

2. #CREATE METHOD fahrenheit_to_celcius and #CREATE METHOD celcius_to_fahrenheit
We create to function to convert fahrenheit to celcius and vice-versa.

3. #REGISTER ALL METHODS
Then we should register all methods

4. #INITIALIZE
The last thing, we should initialize this modules.

The codes :
More…

,

method

Simple way to understand how Inheritance works in Python

8 Mar , 2012  

Inheritance is a way to reuse code of existing object. Differ with Java, Python have more flexible inheritance. We can derived from base class and overide as many as we want to. So what most simple implementation of inheritance in Python?

Open your Python console interpreter and start typing:
More…

,

Django

Delete FileField using delete(save=False) in signals post_delete Django

7 Mar , 2012  

We can’t overwrite delete() for deleting FileField and related files in Django. As we know that :

In Django 1.3, when a model is deleted the FileField’s delete() method won’t be called. If you need cleanup of orphaned files, you’ll need to handle it yourself (for instance, with a custom management command that can be run manually or scheduled to run periodically via e.g. cron).

More…

,