Hummingbird Instant Messenger using mqtt

Inspired by a tech talk given by the Facebook messenger developer team, I am developing my own instant messenger app on Android, named hummingbird, it’s going to be a light weight messenger app that uses mqtt protocol.

Still at early stage of setting up the UI, working with the famous open source slidingmenu library by Mr Jeremy Feistein. suggestions are welcome!

repo

Cheers!

May 20, 2014 | View Comments

Bitstamp API Monitor on Android with Websocket

Hello there!

Things are getting more interesting! I am trying Bitstamp’s websocket api now. Basicly, it uses a third-party tool called Pusher to open a websocket to stream all transactions in real time to your device.

Here are some specs of this version of my app: DrawerLayout Fragments: 3, for each of transaction, orderbook, and ticker Service: 1, in it: AsyncTask fired to pull data from Bitstamp API and store to database if first time use; after that, use pusher to open socket to listen for the streaming data, and store new data to database. This technique used both for transaction and orderbook. another handler for repeatly updating ticker info Sqlite: 3, for each of the transaction, orderbook, and ticker ContentProvider: 3, for each of transaction, orderbook and ticker, monitoring the change in database, and presenting the new data to fragments sharedPreference TODO: internet connection check on start, and resume pusher after internet reconnected, check user setting, with connectivityManager.getActiveNetworkInfo(), isConnected(), public static final String CONNECTIVITY_ACTION. first time open without internet, would cause transaction db to be empty afterwards (bulkinsert never called)

repo here

the app is in Google Play Store now

I will try to add more functionality in project in the following days :)

Cheers

May 08, 2014 | View Comments

Bitstamp API Client on Android

I am making a simple Android app to graphically display Bitstamp’s trading data through their API

The app utilizes an open source Android charting library called Androidplot, and a slide menu from here. The app features AlarmManager to repeatly firing IntentService, the later’s working thread would be pulling data from Bitstamp API (making http calls), and if there are new data, update database (sqlite) accordingly, once database is updated, a Broadcast is sent to the main UI thread and updates the chart.

[Check it out](https://github.com/ericcj24/simple-bitstamp-api-androidclient) new repo [here](https://github.com/ericcj24/bitstamp-api-android2)

I have been exploiting with different designs to approach this problem, here is the newest version, check it out :)

I will try to add more functionality in project in the following days :)

Cheers

April 11, 2014 | View Comments

Bitstamp API

I am making a simple GUI java app to graphically display Bitstamp’s trading data through their API.

The java app utilizes apache’s httpclient library to make http connection, uses Jackson to bind JSON data to Java class and/or generic containers.

The app also uses jmathplot libary to help plot the data.
After some considration, I switched my ploting tool to JFreeChart for its detailed documentation.

Find it at my project repo. I have also changed the new project to a newer repo

I will try to add more functionality in project in the following days :)

Cheers

March 25, 2014 | View Comments

Twitter API

Twitter is a little vague in terms of how you could make your first ‘hello world’ post, that’s why I am writing this post for your convenient.

If you, like me, always like to write a python script with Requests library on the spot just to quick-test some new APIs you encountered, you could be, just like me, puzzled by Twitter API’s authentication. Thanks to this dude ’s hint, I finally made a successful Twitter post (a tweet) through my what was supposed to be simple python script.

import requests
from requests_oauthlib import OAuth1
url='https://api.twitter.com/1.1/statuses/update.json'
#i am making a tweet http post call
auth=OAuth1('CONSUMER_KEY',client_secret='CONSUMER SECRET',resource_owner_key='OAUTH TOKEN',resource_owner_secret='OAUTH TOKEN SECRET')
r=requests.post(u,data={'status':'hello'},auth=auth)

So you should realize that there is OAuth1 function in Requests that helps you encode all the authorization parameters. And it seems like Twitter only takes that for a successful authorization. otherwise you get a 400 error saying not valid authorization :(
Of course, prior to make this call, you need to create/register your Twitter app at their developer page, and set app’s authorization to both read AND write. then, you could generate your token and secret. Be sure to generate token AFTER you set app’s authorization :D Once you have all consumer_secret, consumer_key, oauth_token, and oauth_token_secret, you are set to go! Cheers!!!

October 28, 2013 | View Comments

A Brief Reflection on my Interviews

I have been doing interviews for a while now, companies I interviewed with range from big names to small inspiring start-ups. Here is a little murmuring of my reflections on it.

In the data structure class, we know we could traverse a tree in two basic fashion, depth-first and breadth-first, each of the traversing methods has recursive and iterative two ways to implement(well I think every recursive implementation has its iterative way to implement), in the iterative way depth-first traverse we usually use a stack as a helping data structure to traverse through the tree, while in breadth-first, we use a queue (a FIFO first in first out structure).

#include <iostream>
using std::cout;

breadth_first_traversal(Node* croot){
    queue<Node*> q;
    Node* level;
    int height;
    if (!croot){
        q.enqueue(croot);
        q.enqueue(level);
        while (!q.empty()){
            Node* temp = q.dequeue();
            if (temp==level){
                height++;
		q.enqueue(level);	
                temp = q.dequeue();
            }
            cout<<temp->value<<' ';
            if(!temp->left) q.enqueue(temp->left);
            if(!temp->right) q.enqueue(temp->right);
        }
     }
}

The brief code showed how powerful breadth-first search could be, it could help you traverse through each node of a tree, while help you keep track of the height of the tree. In my recent interview questions, I also encountered a question that ask me to implement an iterator for a general tree class, given by the short timing, I also found that the same breadth-first traverse philosophy could apply to the problem, using a queue structure as iterator, checking if the queue is empty to see if this iterator ‘hasNext’. And in another question, where a brief Facebook Member class is defined, which includes a name and a email address of the user, and a list of his friends (List), the question was to ask you to write a function that print out user’s friends first (level 1), then user’s friends’ friends (level 2), and etc etc. You could still use the queue to help you do a breadth-first search to solve the similar problem. Happy Halloween :D Cheers !

October 13, 2013 | View Comments

Binary Search in Sorted Array

Overview

This is the code that do a binary search for a value in a sorted array.

C code

#include <iostream>
using std::cout;

int Find(int a[], int v, int size){
//sizeof(a)/sizeof(a[0]) would not give the correct size of array, as sizeof(a) here gives the size of pointer, not the entire array!!!
// that is why you need to pass size info of the array to save the trouble
    if (a==NULL) {
	return -1;	
    }
    int p=0;
    while(size>0 && p>=0) {
	size=size/2;
	if (a[p] >v) {
            p=p-size;
	}
	else if (a[p] <v){	
	    if (a[p+1] == v) {
		return p+1;
	    }
	    p=p+size;
	}
	else if (a[p] == v){
	    return p;
	}
    }	
    return -1;
}

int main(){
    int a[4] = {1,2,3,4};
    int sa = sizeof(a)/sizeof(a[0]);
    cout<<"size of array a"<<sa<<'\n';
    int a1 = Find( a, 1, sa);
    int a2 = Find( a, 2, sa);
    int a3 = Find( a, 3, sa);
    int a4 = Find( a, 4, sa);
    int a5 = Find( a, 0, sa);
    int a6 = Find( a, 5, sa);

    int b[5] = {1,2,3,4,5};
    int sb = sizeof(b)/sizeof(b[0]);
    cout<<"size of array b"<<sb<<'\n';
    int b1 = Find( b, 1, sb);
    int b2 = Find( b, 2, sb );
    int b3 = Find( b, 3, sb );
    int b4 = Find( b, 4, sb );
    int b5 = Find( b, 5, sb );
    int b6 = Find( b, 0, sb );
    int b7 = Find( b, 6, sb );
	
    cout<<a1<<' '<<a2<<' '<<a3<<' '<<a4<<' '<<a5<<' '<<a6<<'\n';
    cout<<b1<<' '<<b2<<' '<<b3<<' '<<b4<<' '<<b5<<' '<<b6<<' '<<b7<<'\n';
    return 0;
}

Interesting Notes

  • sizeof(array), if array was the integer array passed as a parameter, the sizeof(array) would give the actual size of the pointer, not the actual size of the array, as it interprets array as pointer. (C pass integer arrays as pointers). so it will be helpful to pass an integer array’s size info together with the array for child-function’s convenience.
  • In the binary search phase, while you are jumping around using array’s index, watch out for the boundary, make sure to cover every corner.
  • Binary Search is O (logn) efficient, as half of the search space is eliminated in each iteration.
September 15, 2013 | View Comments

A Little Study on Requests

Overview

Requests is a great python lib to handle http calls, it is simple and intuitive to use. But when actually implement your class, to handle exceptions raised by Requests, the official document seems to be a little slim on it. First, unlike urllib2, Requests does not treat http errors as exceptions (it has a status_code to reflect the error, but won’t actually raise the exception flag). So I implement a customized error class, combined with a if condition statement, I manage to catch the http error as an exception.

Python code

import requests
class APIError(StandardError):
    def __init__(self, error_code, error, request):
        self.error_code = error_code #code
        self.error = error #msg
        self.request = request
        StandardError.__init__(self, error)

    def __unicode__(self):
        return u'APIError: %s: %s, request: %s' % (self.error_code, self.error, self.request)

def c():
    access_token = YOUR_TOKEN
    url = 'https://api.douban.com/shuo/v2/statuses/'
    v = {'text':'hello'}
    h = {'Authorization':'Bearer %s' % access_token}
    try:
        r = requests.post(url, data=v, headers = h)
	rr = r.json()
	# example error response
	#{"msg":"\u9700\u8981\u767b\u5f55","code":1000}
	#{'msg': invalid_access_token: YOUR_TOKEN', 'code': 103, 'request': 'POST /shuo/v2/statuses/'}
	if rr.__contains__('code'):
	    raise APIError(rr['code'], rr.get('msg', ''), rr.get('request', ''))
	return rr
    except requests.exceptions.ConnectionError, e:
	print '%s' %e # for debuggin
	raise APIError(u'requests.exceptions.ConnectionError', e, 'request: %s'%url)
    except requests.exceptions.RequestException, e:
	print '!%s' %e # for debuggin
	raise APIError(u'requests.exceptions.RequestException', e, 'request: %s'%url)
    except requests.exceptions.TooManyRedirects, e:
	print '!!%s' %e # for debuggin
	raise APIError(u'requests.exceptions.TooManyRedirects', e, 'request: %s'%url)
    except requests.exceptions.URLRequired, e:
	print '!!!url missing %s' % e # for debuggin
	raise APIError(u'requests.exceptions.URLRequired', e, 'request: %s'%url)
    except APIError, e:
        print 'customized error'
	raise APIError(e.error_code, e.error, e.request)
    except Exception, err:
	print "renren_http_call: unexpected error %s" %err
	raise APIError(u'unkown code', str(err), type(err))

def d():
    try:
	r = c()
	return r
    except APIError, e:
	print type(e)
	print e.error_code
	print e.error
	print e.request

c() is the child function that actually takes care of the requests calling. If in the response dictionary, there is a ‘code’ key, (or you could use r.status_code != 200), that means there is a http error, and we could raise our customized error class to pass alone the error information to the mother function (or class), in our case, the function d().
and in d()’s exception handling, you could deal with different situations by implement if condition statement, in the example code, I just print out the message for demo purpose.
Hope this helps, enjoy :)

August 14, 2013 | View Comments

A Little Note on Renren API

Overview

Renren is popular Chinese social website. This post introduces an easy way, and yet different from Douban’s photo uploading previews introduced, to upload photo to your Renren albums with Python requests.

Python code

import requests
access_token = YOUR_ACCESS_TOKEN
fh = open('YOUR_IMAGE_FILE_PATH','rb')
files = {'file':fh}
url = 'https://api.renren.com/v2/photo/upload'
text = 'WORDS_TO_DESCRIBE_YOUR_PHOTO' 
v = {'description':text, 'albumId':YOUR_ALBUMID, 'access_token':access_token}
r = requests.post(url, data=v, files=files)
r.status_code # would give you the http call result
r_json = r.json() # would give the result in json format

Things to take extra care are: use ‘data’ to pass your dictionary when make a POST call with requests, Multipart-Encoded File should be put in a dictionary and pass to ‘files’.
cheers!

August 11, 2013 | View Comments

Thoughts on Pushing Wind Power

photo courtesy of [Vattenfall](http://www.flickr.com/photos/vattenfall/3581236645/

)

The process of pushing green energy is slow. Solar power, wind power, bio energy development are slow, and there are even some pushing-back on the implementation of wind farms. Some local residents fought against the implementation of wind farm off their coast because they worry about that they may lose their scenery to the ocean. I am a frequent commuter between Chicago and Champaign by train, and I find it anecdote to see those lovely white wind turbines standings on the horizon of the green farm ground.
This brought me to think about how to push public’s acceptance to wind farm. People are slow to accept changes, and new technologies. I think about using popular culture as a break through point to re-introduce wind farm to people.
Associations like a cruise trip to Titanic, empire state building to An affair to Remember and Sleepless Seattle, and Casablanca to, well, the movie Casablanca, the unforgettable movies were so successful that it creates a iconic association between the location where the movie was filmed and the story of the movie. Without personally experiencing it, people gradually accept the idea of a new life style, a new product, and eventually, a new technology. I propose that investment should be put together to write, and shot a good movie that associates wind farm with, maybe, say, a everlasting love story. Maybe there could even be a scene taken right in fhe vast farm ground, the green farm ground filled the picture, our beautiful heroin stands right in front the white blades of wind turbine, and re-united her destined mate who just came back from a serious war fair. The background music is tear-drawing, and in the background of the picture, the entire wind farm is standing there. The moving story and beautiful scene would take influence in popular culture, with wind turbine in it, people would start to accept wind farm as a friendly, and even welcoming image.
With this publicity, the next step is to raise more money from the public, with the money, there comes a chance to influence the D.C.. With persuasive lobbyists in D.C. influence Washington’s law-making in Gay-rights, Affirmative action, Petroleum and Environment fight, the green energy, especially the wind farm technology should equip themselves with a stronger and more influential lobby group. The later could put more persuasion on congressional decision. And by that time, we shall see a Renaissance of the green energy.

August 08, 2013 | View Comments