Welcome~~~


Another blog:
http://fun-st.blogspot.com/

It is easier to write an incorrect program than understand a correct one.

Tuesday, July 26, 2011

How to: Use Python and Social Network Analysis to Find New Twitter Friends « Zero Intelligence Agents

How to: Use Python and Social Network Analysis to Find New Twitter Friends « Zero Intelligence Agents

Thursday, June 9, 2011

Advanced WxPython Nuts and Bolts Presentation

Advanced WxPython Nuts and Bolts Presentation

wxPython-users - PyNoAppError: The wx.App object must be created first!

wxPython-users - PyNoAppError: The wx.App object must be created first!

PyNoAppError when coding wxpython in IDEL (ubuntu)

When Using the wxpython, Ubuntu, and IDEL, sometimes, I have the following problem:

PyNoAppError: The wx.App object must be created first!

Check about this, and it seems that IDEL (since it's build on wx...) has some conflict when using wxpython. I tried Drpython, which seems good for now. 


--

♥ ¸¸.•*¨*•♫♪♪♫•*¨*•.¸¸♥
"Stay hungry, stay foolish" -  Steve Jobs

Wednesday, June 8, 2011

About the wxPython: Exit, Destroy, Close


Robin Dunn wrote:

I assume that by "Exit" here you are still talking about the menu item above.

No, I was referring to wx.Exit, which I think is a global call.

It is a way to forcibly kill the app, without any opportunity for the application objects to clean up after themselves. Most of the time you wouldn't want to use it.

You use Close() when you want to programatically tell the frame to go close itself, and is functionally the same as the user telling it to close itself with the "X" button.

Destroy() tells wx to delete the C++ object instance that corresponds to the frame. Normally it will destroy itself when it closes in the default EVT_CLOSE event handler, but if you catch the EVT_CLOSE yourself you either need to call Destroy in your handler, or call event.Skip so the default handler will still run. The EVT_CLOSE handler is where you would normally put the code that checks for open files, asks the user if she wants to save them or cancel, etc. Based on the user's response you can veto the close if you want.

I don't understand. So Close() does nothing more than make the window disappear?

No, it tells the window to close itself. That is a lot different than just hiding it.

Does Close() then automatically call Destroy()?

No, Close causes a EVT_CLOSE event to be sent. The default handler for that event calls Destroy().

What happens if I catch the wx.EVT_CLOSE event and make it call self.frame.Close()?

Then you'll get an endless loop.

Does it get destroyed also, or is the application still running somehow?

According to you and Andrea, I think this is what I need:

self.frame.Bind(wx.EVT_CLOSE, self.OnExitApp)

def OnExitApp(self, event): self.frame.Destroy()

Right? Or do I just use Close() still?

You use Close() from your menu event handler, or wherever you want to programatically cause the frame to be closed. You only need to provide a handler for EVT_CLOSE if you want to have more control over the closing of the frame than the default automatic destroy.

Thursday, June 2, 2011

Limit the border size on a matplotlib graph

fig = pylab.figure()
ax_size = [0,0,1,1]
ax = fig.add_axes(ax_size)
ax.scatter(x[showd[0],:]-min(x[showd[0],:]),x[showd[1],:]-min(x[showd[1],:]),s=50,c=tc,cmap=pylab.cm.jet)

Thursday, April 28, 2011

Factory methods - JavaWorld

Factory methods - JavaWorld

Java sorting - comparable v comparator


java.lang.Comparable
java.util.Comparator
int objOne.compareTO(objTwo) – A Comparable interfaced class must contain a method called compareTo to compare two objects (one being the object on which it is called and the other being passed as a paramater)int compare(objOne, objTwo) – A Comparator is a class in its own right, which implements the Comparator interface; that means it must contain a method called compare (two objects as parameters)
Return Values -
negative – if objOne < objTwo
zero – if objOne = objTwo
positive – if objOne > objTwo
Return Value -
same as Comparable
Only one sort sequence can be createdMany sort sequences can be created
You must modify the class whose instances you want to sortYou build a separate class from the class whose instances you want to sort
Implemented frequently in the API by : String, Wrapper Classes, Date, CalendarMeant to be implemented to sort instances of third-party classes
If you want to sort a collection using its comparable interface, you simply call the static Collections.sort method on it … so if we had an ArrayList called Animal which implemented Comparable, we could write:
Collections.sort(Animal);
To sort a collection using a Comparator class, you need to pass an extra parameter into the Collections.sortmethod – that parameter being an instance of a Comparator object. Thus:
Collections.sort(Animal, new ByBreed());

Saturday, April 23, 2011

Java Tutorial

Java Tutorial

Python Tutorial

Python Tutorial

Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI

Matrix-package-for-Python


http://sourceforge.net/projects/matpy/


Description:
MatPy is a Python package for numerical linear algebra and plotting with a MatLab-like interface. It currently consists of wrappers around Numeric and Gnuplot packages, but eventually may be implemented directly in C/C++, or as interface to Octave.

 PyGoogle

URL:http://sourceforge.net/projects/pygoogle/
Description:A Python wrapper for the Google web API. Allows you to do Google searches, retrieve pages from the Google cache, and ask Google for spelling suggestions

Python Open Source

Python Open Source

Monday, April 18, 2011

Pastie

Printing expressions from Tree

http://www.daniweb.com/forums/thread323976.html

http://www.careercup.com/question?id=7473670

http://wordaligned.org/articles/python-surprise-me
http://openbookproject.net/thinkcs/python/english2e/ch21.html
http://stackoverflow.com/questions/1894846/printing-bfs-binary-tree-in-level-order-with-specific-formatting
http://codinggeeks.blogspot.com/2010/04/serializing-and-de-serializing-binary.html
http://ponywma.spaces.live.com/blog/cns!3757DF93DF1F3015!334.entry
 def printexp(tree):
    sVal=""
    if tree:
        sVal='( ' + printexp(tree.getLeft())
        sVal=sVal+str(tree.getRootValue())
        sVal= sVal+printexp(tree.getRight()) +' )'
    return sVal



Here is the source code and the text file format:
Note that the text file is created "by hand" and only read function is implemented in the code. Implementing write function should be straight forward.
==============================================
#include <stdio.h>

typedef struct tree_struct
{
int data;
int nchildren;
struct tree_struct *children;
}tree_t;

tree_t * create_new()
{
return ((tree_t *) malloc(sizeof(tree_t)));
}

int populate_tree(tree_t *root, FILE *fp)
{
fscanf(fp,"%d",&(root->nchildren));
root->children = NULL;

if(root->nchildren)
{
root->children = (tree_t *) malloc(root->nchildren * sizeof(tree_t));
for(int i=0; i<root->nchildren; i++)
fscanf(fp,"%d",&(root->children[i].data));
for(int i=0; i<root->nchildren; i++)
populate_tree(&root->children[i],fp);
}
else
return 0;
}

int print_tree(tree_t *root)
{
static int count = 0;
if(root)
{
if(!count++)
printf("%d\n",root->data);
if(root->nchildren)
{
for(int i=0; i<root->nchildren; i++)
printf("%d ",root->children[i].data);
printf("\n");
for(int i=0; i<root->nchildren; i++)
print_tree(&(root->children[i]));
}
return 0;
}
else
return -1;
}

int main(int argc, char *argv[])
{
char *filename = argv[1];
FILE *fp = fopen(filename,"r");
tree_t *root = create_new();

fscanf(fp, "%d", &(root->data));
populate_tree(root,fp);
print_tree(root);
}
==============================================
The tree taken for illustration purpose is:

5 ->3(1(4,19),7(20),2(25)), 10(11,17), 2(99,8)

The file format used is as follows:

<example.tree>
5
3 3 10 2
3 1 7 2
2 4 19
0
0
1 20
0
1 25
0
2 11 17
0
0
2 99 8
0
0
==============================================
To compile (on linux):
gcc -std=c99 -g main.c -o treeio
==============================================
Usage:
./treeio example.tree
Output:
5
3 10 2
1 7 2
4 19
20
25
11 17
99 8
==============================================

-- http://www.python-forum.org/pythonforum/viewtopic.php?f=14&t=5842

♥ ¸¸.•*¨*•♫♪♪♫•*¨*•.¸¸♥

Some OOP websites

Some good sources for Objective Oriented Programming



It also has a sub-web site for the algorithms: 
http://www.oopweb.com/Algorithms/Files/Algorithms.html

[Nice One]     http://www.desy.de/gna/html/cc/Tutorial/tutorial.html
--

♥ ¸¸.•*¨*•♫♪♪♫•*¨*•.¸¸♥

Find the longest palindromes

A clear explanation and solution in (Python, Java, C++):

the most naive solution would be to exhaustively examine all n (n + 1) / 2 substrings of the givenn-length string, test each one if it's a palindrome, and keep track of the longest one seen so far. This has worst-case complexity O(n3), but we can easily do better by realizing that a palindrome is centered on either a letter (for odd-length palindromes) or a space between letters (for even-length palindromes). Therefore we can examine all 2n + 1 possible centers and find the longest palindrome for that center, keeping track of the overall longest palindrome. This has worst-case complexity O(n2).

But this can be done in O(N)






SomeLinks:


A Java Code:

est data used is HYTBCABADEFGHABCDEDCBAGHTFYW12345678987654321ZWETYGDE

  public static string GetPalindromeString(string theInputString) 

{ int j = 0;

          int k = 0;         string aPalindrome = string.Empty;         string aLongestPalindrome = string.Empty ;                   for (int i = 1; i < theInputString.Length; i++)         {             k = i + 1;             j = i - 1;             while (j >= 0 && k < theInputString.Length)             {                 if (theInputString[j] != theInputString[k])                 {                     break;                 }                 else                 {                     j--;                     k++;                 }                 aPalindrome = theInputString.Substring(j + 1, k - j - 1);                 if (aPalindrome.Length > aLongestPalindrome.Length)                 {                     aLongestPalindrome = aPalindrome;                 }             }         }         return aLongestPalindrome;        }


This one is related -- to use the regular expression to detect the palindrome:

--

♥ ¸¸.•*¨*•♫♪♪♫•*¨*•.¸¸♥

Notes on Path Finding problem

Some good sources on Path-finding:


# A* path finding: ( googling for astar c.)
By Patrick Lester (Updated July 18, 2005)  

# Path matrix for required length
Create the adjacency matrix where matrix[u][v] = 1 denotes an edge between u and v, and matrix[u][v] = 0 denotes no edge between u and v. Then (matrix)^3 (just simple matrix exponentiation) is 'magically' the path matrix of exactly length 3.
The theorem that addresses the random walk problem is this:
Let A = [aij] be the adjacency matrix of a graph G having points n1, …, nn.  Let k be any positive integer.  Then the number of distinct n1-nj walks of length k in G is equal to the i, j element of A^k. 
Check 
A) book: Classic Data Structures, by D. Samanta at page 367


# Some other related topics:

# Find the longest path:
From the record:
  • An efficient implementation of Dijkstra's algorithm takes O(Elog V) time for a graph with E edges and V vertices.
  • Hosam Aly's "flood fill" is a breadth first search, which is O(V). This can be thought of as a special case of Dijkstra's algorithm in which no vertex can have its distance estimate revised.
  • The Floyd-Warshall algorithm takes O(V^3) time, is very easy to code, and is still the fastest for dense graphs (those graphs where vertices are typically connected to many other vertices). But it'snot the right choice for the OP's task, which involves very sparse graphs.
Raimund Seidel gives a simple method using matrix multiplication to compute the all-pairs distance matrix on an unweighted, undirected graph (which is exactly what you want) in the first section of his paper On the All-Pairs-Shortest-Path Problem in Unweighted Undirected Graphs [pdf].

# This one is not exactly the path finding problem, but also very interesting-- like generating the possible move

(This is not exactly the problem that I have, but it's isomorphic, and I think that this explanation will be easiest for others to understand.)

Suppose that I have a set of points in an n-dimensional space. Using 3 dimensions for example:

  A : [1,2,3] B : [4,5,6] C : [7,8,9] 

I also have a set of vectors that describe possible movements in this space:

  V1 : [+1,0,-1] V2 : [+2,0,0] 

Now, given a point dest, I need to find a starting point p and a set of vectors moves that will bring me todest in the most efficient manner. Efficiency is defined as "fewest number of moves", not necessarily "least linear distance": it's permissible to select a p that's further from dest than other candidates if the move set is such that you can get there in fewer moves. The vectors in moves must be a strict subset of the available vectors; you can't use the same vector more than once unless it appears more than once in the input set.

My input contains ~100 starting points and maybe ~10 vectors, and my number of dimensions is ~20. The starting points and available vectors will be fixed for the lifetime of the app, but I'll be finding paths for many, many different dest points. I want to optimize for speed, not memory. It's acceptable for the algorithm to fail (to find no possible paths to dest).

Update w/ Accepted Solution

I adopted a solution very similar to the one marked below as "accepted". I iterate over all points and vectors and build a list of all reachable points with the routes to reach them. I convert this list into a hash of <destp+vectors>, selecting the shortest set of vectors for each destination point. (There is also a little bit of optimization for hash size, which isn't relevant here.) Subsequent dest lookups happen in constant time.


Other links from arizona cs445:

--

♥ ¸¸.•*¨*•♫♪♪♫•*¨*•.¸¸♥

Minimum Spaning Tree

Minimum Spaning Tree:

Brief Def: spanning tree of minimum total weight

+  Prim-Jarnik algorithm
+  Kruskal algorithm

--

♥ ¸¸.•*¨*•♫♪♪♫•*¨*•.¸¸♥

Some Notes

# Find duplicates in a array of elements
==> we can assign -1 to each number in the array
use it's value as index, so the position it pointed to be assigned as positive, if we found one that pointing to the positive value, we have already found the duplication element. 

# Find if a tree is a mirror of itself
==>Use a variant of recursive function for checking sameTree() instead of checking left and left, right and right. Check left with right and right with left.

# An array contain +ve and -ve element, find subarray whose sum =0;
==> Traverse the array, 

at position i, recored the up-to-now sum --> put this into  a hash table (key = the up-to now sum), value = current position
keep on travers, if to some posiiton j, we found the same value in the hash table, then the 
subarray from i to j is the subarray we are looking for
e.g. we have the array 
-3, -1, 3, -3, -11, -1, 10

we could generate the hash table by the up-to-now sum:
-3, -4, -1, -4
when face another -4, it mens that during the element -1, to the 4th element -3, there is no increasing, so the sum of this sub-array is ZERO


--

♥ ¸¸.•*¨*•♫♪♪♫•*¨*•.¸¸♥

Counting sort

# To fast sort millions integers with known range:

counting sort.

Counting sort (sometimes referred to as ultra sort or math sort) is a sorting algorithm which (like bucket sort) takes advantage of knowing the range of the numbers in the array to be sorted (array A).

Counting sort is a stable sort and has a running time of Θ(n+k), where n and k are the lengths of the arrays A (the input array) and C (the counting array), respectively. In order for this algorithm to be efficient, k must not be much larger than n.

--

♥ ¸¸.•*¨*•♫♪♪♫•*¨*•.¸¸♥