Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Thursday, November 8, 2012

Nose – Fix nosetests finding 0 tests

 nosetests
Ran 0 tests in 0.000s

Just recheck, your test file  must have "test" in filename

Sunday, October 14, 2012

Language, language, language... I want to be a polyglot

I've tried many time to get Function Programming but I can't. Just learn some syntax then forgot all because it's very hard to get them if you don't really use them.

Of cause, everyone will argue, Haskell or a dialect of LISP?
Some answer can be found here: http://programmers.stackexchange.com/questions/18838/haskell-and-lisp-vs-haskell-or-lisp

Haskell like, Smalltalk. They are so pure, and you should learn them for learning many thing.

"Haskell and Lisp are two totally different beasts.
Haskell is kindof "pure functional programming in an ivory tower"
Lisp is kindof "code-is-data / data-is-code / make your own language constructs". You can manipulate your code in whatever way you can imagine.
They are very different. Both share the "functional programming" aspect, but that's really a tiny little common point compared to their differences. Just try them out and you will see how different they are!"

so go for haskell first, then lisp.
Happy coding!

One thing I hate about Haskell is its compile (ghc) is too heavy weight!

Wednesday, July 25, 2012

Code then fail...

Lesson for to day: (some best practice i've leart from my experiences)

  1. Every Python function should return a value if it supposed to return a value. You should explicit return None. (Explicit is better than implicit - PEP 20)
    "So if a function is supposed to return a value, then I make sure all code paths have a return, and that the return has a value, even if it is None.
    If a function "doesn't" return a value, that is, if it is never called by someone using its return value, then it's ok to end without a return, and if I need to return early, I use the bare form, return."
    http://stackoverflow.com/questions/4027586/is-it-ok-to-skip-return-none?answertab=votes#tab-top
  2.  pdb not work on multithreading
  3. careful with copy. Understand when you need deepcopy
  4. You should know how to use debuger, it will save your life one day.
  5. Debugger and unittest will show it value when you found your bug. When you fail!

Sunday, April 29, 2012

PHP experiences

PHP:

- khi viết câu select từ DB, nên dùng tablename.field thay vì `fieldname`
TODO: check xem khác nhau những gì?

- Datepicker nên dùng cái này cho nhanh:
http://www.triconsole.com/php/calendar_datepicker.php
sau khi lấy giá trị từ $_POST thì dùng strtotime($val)  để chuyển từ YYYY-MM-DD sang timestamp


Thursday, March 15, 2012

Automate Android Dev


Vài tip nhỏ

Auto1: adb connect siêu tốc (on Linux)
Một lệnh bạn thường xuyên phải sử dụng khi test trên máy thật qua AdbWireless

adb connect 192.168.1.x

dùng để adb vào 1 máy trong mạng.

C1: thêm vào ~/.bashrc dòng
alias 'adbc=adb connect'

C2: (tớ đang dùng :D ): viết 1 cái script nhỏ nội dung như sau:

#!/bin/sh

IP=192.168.1.

adb connect $IP$1

đặt tên là adbc, chmod a+x adbc để nó chạy được. Copy file vào 1 thư mục nào đó (vd /usr/bin/) hoặc thêm thư mục hiện thời của bạn vào biến PATH (export $PATH=$PATH:dia_chi_hien_thoi)

giờ thì chỉ cần gõ adbc 7, bạn sẽ gửi lệnh adb connect 192.168.1.7 :D

Auto2:
Vì bạn thường xuyên sử dụng log để test nên hãy thêm dòng này vào template của Eclipse:

Windows > Preferences > Java > Editor > Templates

tạo 1 template mới:
log
Log.d(TAG, "${enclosing_method}");

dòng này sẽ tự tạo 1 dòng log với tên của method mà bạn ghi nó. TAG là 1 constant nên được đặt trước, thường là tên package của chương trình.

Friday, March 2, 2012

[Android] Preferences

Preferences là 1 cách để lưu trữ các tùy chọn của người dùng trong chương trình, quyết định trạng thái của chươgn trình. Nó được chứa trong 1 file xml , mỗi chương trình đều có 1 file preferences mặc định với tên : tên_của_package_preferences


public static SharedPreferences getDefaultSharedPreferences(Context context) {
    return context.getSharedPreferences(getDefaultSharedPreferencesName(context),
        getDefaultSharedPreferencesMode());
}
private static String getDefaultSharedPreferencesName(Context context) {
    return context.getPackageName() + "_preferences";
}
private static int getDefaultSharedPreferencesMode() {
    return Context.MODE_PRIVATE;
}


Thay vì phải truyền các extra qua intent để gửi các thông tin sang activity khác, bạn có thể lưu vào preferences rồi lấy ra lúc cần thiết, việc lưu vào preferences được thực hiện 1 cách "tức thì" nên bạn sẽ không bao giờ phải lo rằng lúc gọi để lấy thông tin từ preference ra thì nó chưa kịp lưu giá trị được gửi vào trước đó :D

Tốt nhất là nên dùng preferences mặc định (tránh những lỗi có thể xảy - gõ sai tên file chẳng hạn ) và tạo 1 class theo singleton pattern với các method set - get các giá trị cần lưu trữ để dễ dàng truy cập lúc cần.

...

Saturday, February 25, 2012

[Java] Access modifier

Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

[Java] Assert and Exception

How to use?
Use assert /ə'sə:t/ as a comment, to TEST a comment
You should now use an assertion whenever you would have written a comment that asserts an invariant.
   if (i % 3 == 0) {
        ...
    } else if (i % 3 == 1) {
        ...
    } else {
        assert i % 3 == 2 : i;
        ...
    }
assert for test/debugging, not error-checking
  • use exceptions when checking parameters passed to public or protected methods and constructors
  • use exceptions when interacting with the user or when you expect the client code to recover from an exceptional situation
  • use exceptions to address problems that might occur
  • use assertions when checking pre-conditions, post-conditions and invariants of private/internal code
  • use assertions to provide feedback to yourself or your developer team
  • use assertions when checking for things that are very unlikely to happen otherwise it means that there is a serious flaw in your application
  • use assertions to state things that you (supposedly) know to be true
In other words, exceptions address the robustness of your application while assertions address its correctness.
Assertions are designed to be cheap to write, you can use them almost everywhere and I'm using this rule of thumb: the more an assertion statement looks stupid, the more valuable it is and the more information it embeds. When debugging a program that does not behave the right way, you will surely check the more obvious failure possibilities based on your experience. Then you will check for problems that just cannot happen: this is exactly when assertions help a lot and save time.

http://docs.oracle.com/javase/1.4.2/docs/guide/lang/assert.html
http://stackoverflow.com/questions/1957645/when-to-use-assertion-vs-exception

Friday, February 24, 2012

[Java] Static method

As defined, power is stateless and has no side effects on any enclosing class so it should be declared static.

Friday, February 10, 2012

[Android] Tổng kết kinh nghiệm làm việc với các loại View

1. Bạn muốn tạo OptionsMenu có khả năng thay đổi?
SOLUTION: sử dụng onPrepareOptionsMenu(Menu menu) thay vì onCreateOptionsMenu


2. Khi nào thì cần extend một View?
SOLUTION: có lẽ bạn chỉ cần 1 loại View mới khi hình ảnh của bạn thường xuyên thay đổi hoặc thật là quái dị :)) khác biệt với các View mà android đã cung cấp. Với những thao tác với 1 View bạn muốn làm như: di chuyển, thay đổi kích cỡ, độ trong suốt thì bạn vẫn chưa cần phải extend 1 View. 

Friday, February 3, 2012

onStart, onCreate.... trình tự chạy của các lệnh

Biết mỗi activity đều implement các method như onCreate, onStart... nhưng có chắc bạn nắm chính xác trình tự chạy của chúng. Hãy làm 1 bài test nhỏ như sau để kiểm nghiệm:

Tạo 1 activity chính, 1 activity 2. Ta implement các method
onCreate
onStart
onResume
onPause
onStop
onDestroy

và đặt log ở tất cả các method này trong cả 2 activity.

Chạy chương trình , bấm nút chuyển từ Activity chính sang Activity 2. Kết quả thu được như sau:

D/AndroidRuntime(  468): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
D/AndroidRuntime(  468): CheckJNI is ON
D/AndroidRuntime(  468): --- registering native functions ---
I/ActivityManager(   59): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.aps.test/.OrderTestActivity }
D/AndroidRuntime(  468): Shutting down VM
D/dalvikvm(  468): Debugger has detached; object registry had 1 entries
I/AndroidRuntime(  468): NOTE: attach of thread 'Binder Thread #3' failed
D/dalvikvm(  436): GC_EXPLICIT freed 1421 objects / 94480 bytes in 1668ms
CHẠY CHƯƠNG TRÌNH
D/ACT1    (  436): onCreate
D/ACT1    (  436): onStart
D/ACT1    (  436): onResume

I/ActivityManager(   59): Displayed activity com.aps.test/.OrderTestActivity: 523 ms (total 523 ms)
I/ActivityManager(   59): Starting activity: Intent { cmp=com.aps.test/.Act2 }
BẤM NÚT CHUYỂN SANG ACTIVITY 2
D/ACT1    (  436): onPause
D/ACT2    (  436): onStart
D/ACT2    (  436): onResume

I/ActivityManager(   59): Displayed activity com.aps.test/.Act2: 391 ms (total 391 ms)
D/ACT1    (  436): onStop
W/KeyCharacterMap(  436): No keyboard for id 0
W/KeyCharacterMap(  436): Using default keymap: /system/usr/keychars/qwerty.kcm.bin

THOÁT KHỎI ACTIVITY 2
D/ACT2    (  436): onPause
D/ACT1    (  436): onRestart
D/ACT1    (  436): onStart
D/ACT1    (  436): onResume
D/ACT2    (  436): onStop
D/ACT2    (  436): onDestroy 




THOÁT KHỎI CHƯƠNG TRÌNH (ACTIVITY 1)
D/ACT1    (  436): onPause
D/ACT1    (  436): onStop
D/ACT1    (  436): onDestroy


Thật quá rõ ràng ^^
PS: để lấy log ra file text trên linux: adb logcat -d > log

Code:
https://github.com/famihug/OrderCallWhenChangeActivity

Android SharedPreferences


Q: mỗi package có 1 defaultSharedPreferences?

A: Sai!
Cả 1 App chỉ có 1 defaultSharedPreferences.

Theo bài này:
http://stackoverflow.com/questions/5946135/difference-between-getdefaultsharedpreferences-and-getsharedpreferences

Thì mỗi ứng dụng có 1 defaultSharedPreferences với tên là tên của package ứng dụng + _preferences
(Chú ý: getPackageName() trả về tên của package của App - là package được khai báo trong file Manifest chứ không phải các package con)

public static SharedPreferences getDefaultSharedPreferences(Context context) {
    return context.getSharedPreferences( 
         getDefaultSharedPreferencesName(context),
        getDefaultSharedPreferencesMode());
}
private static String getDefaultSharedPreferencesName(Context context) {
    return context.getPackageName() + "_preferences";
}
private static int getDefaultSharedPreferencesMode() {
    return Context.MODE_PRIVATE;
}

Tuesday, January 31, 2012

Eclipse tips

1. Switch between "tabs"
Want to change to next tab?
Using Ctrl E or Ctrl Shift E is so ugly.
Use Ctrl Shift Tab, then use navigator left or right. When done, press Tab.

2. Switch Perspective
Ctrl F7

Wednesday, January 11, 2012

[Android] Tổng kết kinh nghiệm làm việc với service và activity

1. Một service có thể vẽ hình, đặt nó trên tất cả các View khác  và nhận event khi user touch vào màn hình nhờ thiết lập qua WindowManager.LayoutParams. Event service nhận được duy nhất là MotionEvent.ACTION_OUTSIDE.

2. Tọa độ khi bắt event bằng service bắt đầu từ (0,0) tại vị trí góc trên trái, dưới StatusBar. Trong StatusBar thì tọa độ y của nó là âm (từ -25 đến 0). Tọa độ bắt bằng View trong Activity bắt đầu từ (0,25) cũng tại điểm góc trên trái dưới StatusBar vừa nói. Bởi thế phải cộng thêm 25 vào tọa độ lấy được từ service nếu muốn sử dụng nó cho Activity.

3. Khi 1 activity không được active nữa (mở 1 activity khác từ nó), hệ thống gọi method onStop() trên nó. Hàm này khác với onDestroy (thoát bằng back...)

4. Nếu service của bạn có "nguy cơ" sẽ tương tác với Activity, tốt nhất là nên implement các method onBind, onUnbind. Chú ý nếu implement onBind mà ko implement onUnbind có thể dẫn đến lỗi "leaks service hay binder j đó"

5. Nếu cần update UI, nhớ dùng view.invalidate()

6. method bindService()  không phải là hàm cho kết quả "ngay lập tức" nên nếu dùng instance của service trả về qua binder để gọi method của service sẽ bị lỗi service đó là null.
Khắc phục: không gọi API của service ngay lập tức (vd 2 dòng này cùng nằm trong onCreate() chẳng hạn). Có thể gọi API trong onConnected, hay bindService trong onCreate()/onStart() và gọi API trong 1 listener nào đó.

Tuesday, January 10, 2012

Android: avoiding memory leaks

In summary, to avoid context-related memory leaks, remember the following:
  • Do not keep long-lived references to a context-activity (a reference to an activity should have the same life cycle as the activity itself)
  • Try using the context-application instead of a context-activity
  • Avoid non-static inner classes in an activity if you don't control their life cycle, use a static inner class and make a weak reference to the activity inside. The solution to this issue is to use a static inner class with a WeakReference to the outer class, as done in ViewRoot and its W inner class for instance
  • A garbage collector is not an insurance against memory leaks
http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html

Friday, January 6, 2012

Android: Frequent mistakes/bugs

(Use Eclipse)
1. When you setOnClickListener on a button, Eclipse requests you change it to other method...
SOLUTION: import android.view.View.OnClickListener;

2. When you write only a service. Installed it into VD and you don't see its start icon. Although you can see that service in "Setting> App Manager> Running Service"
SOLUTION: Create an activity.

3. You edited some file but Eclipse keeps warning you have errors.  
SOLUTION: clean you project : Menu >Project >Clean

4. Some activities or services not run?
SOLUTION: Add them to AndroidManifest

5. You logged something but don't see them?
SOLUTION: Choose device which using by logcat.
Menu>Window>ShowView>Devices

6.You use Toast  but it not show on your screen
SOLUTION: did you forget .show() method?


7. Eclipse: Can't bind to local 8600 for debugger.
SOLUTION: In addition to adding "127.0.0.1 localhost" to your hosts file, make the following changes in Eclipse.
Under Window -> Preferences -> Android -> DDMS:
  • Set Base local debugger port to "8601"
  • Check the box that says "Use ADBHOST" and the value should be "127.0.0.1"
Then, call adb kill-server followed by adb start-server  
After done, if it still not work. Restart your computer

8. Bug when you want to change your UI
SOLUTION: Use  View.invalidate();

9.Error : NoSuchFieldError R$id...
SOLUTION: change that xml layout


10. Connect adb with you device  on Linux. Enter adb devices and get "Unknow device"
SOLUTION: sudo adb kill-server, sudo adb start-server, sudo adb service

11. Eclipse stops responding when changing to DDMS perspective

SOLUTION: The problem was that AVD hanged somewhere at 27% and then I couldn't do really anything with Eclipse. The problem is somewhere in the AVD and re-installing the AVD didn't help me.
Instead this seems to work every time:
  • Start virtual device from Eclipse's Window -> AVD menu
  • Then right click the project and "Debug as -> Android Application"
Here you never need to close the virtual device and it's also a lot faster to use it this way.

12. You are working with dialog and some view inside it not work

SOLUTION: make sure that you are work with approriate views. Maybe some findViewById() should be yourDialog.findViewById();

13. JUnit test
Logcat: Test run failed: Test run incomplete. Expected 1 tests, received 0

SOLUTION: you were using the wrong constructor. Eclipse auto generate the code and it created this:

public LoginTest(String pkg, Class<Login> activityClass) {
    super(pkg, Login.class);
}

change it to this:

public LoginTest() {
    super("pkg_name", Login.class);
}

note that all your test function must be start with test and its modifier is public
Ex:
public void testPreconditions() {
        assertNotNull(mView);
    }

14. Eclipse hangs on loading workbench (after .adt...)
SOLUTION:
remove .snap file from <<workspace_dir>>/.metadata/.plugins/org.eclipse.core.resources/ 
then run eclipse -clean

15. Create hotkey for commit current file with Subclipse
SOLUTION:
In order to get the shortcuts to work, you must go to Window > Customize Perspective, then under the Command Groups Availability tab, check the SVN option. It may require a restart of Eclipse, but the Subclipse keyboard shortcuts will now work.

Then create a key binding for 'Commit'
(under Preferences... General->Keys, search for Commit). Then you just need to click on the row SVN  and hit a key combination => Ok

16. Error on gen folder
SOLUTION:
check your res files, all filename must start with alphabet, not number.

17. Can't install your app on real device but emulator
SOLUTION:
Check your manifest, is there any duplicate activity?

Thursday, January 5, 2012

Android with Proguard

Proguard shrinks, optimizes, and obfuscates your code by removing unused code and renaming classes, fields, and methods with semantically obscure names.

To use Proguard, you should use SDK 2.3.3 (API 10). If you wrote your project in API < 10, you should upgrade it:
android update project --name MyApp --target 2 --path ./MyAppProject

to get the target,run command:
android list targets
Then config your project to use Proguard:
http://developer.android.com/guide/developing/tools/proguard.html

For more android command:
http://developer.android.com/guide/developing/projects/projects-cmdline.html#UpdatingAProject

If you use Eclipse, choose File>Export to release your project in .apk file.
You should see proguard directory in your project directory after exported.

NOTE: you should keep mapping.txt file each time you release. It helps debug your app later.

Android tips, exp

By me, for me  :))
1. Remove all Log to speed up your App when release.
 Xóa tối đa số Log bạn tạo ra khi viết trước khi release để tăng tốc.
2. Try to use Log instead of print (if you come from C, Java).
Tập sử dụng Log thay vì print ra các kết quả để check xem bạn viết đúng hay không. Log rất tiện lợi.

3. Đọc error log TỪ TRÊN XUỐNG. Sau đó mới xem caused by...

Sunday, November 13, 2011

Vim as hex editor

vim -b datafile
:set binary
:set display=uhex
g CTRL-G
234go
:%!xxd
:%!xxd -r

List of tools for developing on Linux

 General:
make Utility to maintain groups of programs with compiling/linker directives
imake Utility to generate Makefiles from a template.
GNU autoconf Tool used to generate configure script. Requires GNU m4.
gHex Binary Editor and Viewer
beav Binary Editor and Viewer
od dump files in octal and other formats. od -c will try to dump everthing as ascii.
xxd make a hexdump or do the reverse
strings Print the strings of printable characters found in a file.
install copy files and set attributes (ginstall)
m4 Macro language for builing configuration files
objdump display assembler information from object files
nm display symbol table from an object file
readelf Displays information about ELF format object files.
ar Create, modify, and extract from archives
ranlib Generate index to archive
ldconfig determine run-time link bindings
ldd Print shared library dependencies for an executable
(i.e.: ldd `which xpdf`)
GNU libtool Used to generate shared libraries.
ipcs Report interprocess communication facility status for queues, shared memory, semaphores
iprm Remove queues, shared memory, or semaphores

more
http://www.yolinux.com/TUTORIALS/LinuxTutorialSoftwareDevelopment.html