Monday, December 29, 2014

Friday, December 26, 2014

Python Regex

Problem:
    To list all the files in a directory in format with: ama.xxxx or ama.xxxx.gz (x is digital) and print them in the chronological order.

import os
import re

def listdir_fullpath(d):
    return [os.path.join(d, f) for f in os.listdir(d)]

AMA_FILE_NAMING = ".*ama.\d{4}(.gz|)$"
amaFilePattern = dirName + "/" + AMA_FILE_NAMING
amaFiles = sorted( [f for f in listdir_fullpath(dirName) if re.match(AMA_FILE_NAMING, f)], key=os.path.getmtime)

for f in amaFiles:
    print f

@http://hilite.me/


For a simple match, glob can be used.

Wednesday, December 24, 2014

Find the Median - To be continued

The median is the "middle number" in a sorted list of numbers. If it's odd, then it is the middle value. If it's even, it's the average of the two middle values.

/* Problem:
 * How to find the median of a sorted array?
 * How to find the median of an unsorted array?
 * How to find the median of an unsorted array without sorting?
 *
 * How to find the median of two sorted array? - from LeetCode
 * How to find the median of given N sorted arrays?
 */




Reference:
    http://en.wikipedia.org/wiki/Median_of_medians

No Command Line Tools in Xcode 6.2 Beta 3?

I managed to install Xcode 6.2 Beta 3 in my OSX10.10. But I found the UNIX commands like g++/gcc/git/make... are still not available. Note that this is a completely new machine and I did not install any other version of Xcode before.

Usually the Command Line Tools are embedded within the Xcode IDE. There's no reason these commands are still missing since the Xcode has already been installed successfully. Finally I figured it out:

FOSs-MacBook-Pro:Applications fos$ ls -lrt |grep Xcode
drwxr-xr-x   3 fos   admin  102 Dec  5 08:21 Xcode-Beta.app

From the above output you can see that the Xcode 6.2 Beta are installed under /Applicatons/Xcode-Beta.app while the OSX is seeking these UNIX commands in Xcode.app by default. That's why it always prompt a window whenever I'm trying to run g++.

How to work around this? Well, a soft link can fix this problem:
$ ln -s Xcode-Beta.app Xcode.app

lrwxr-xr-x   1 fos   admin   14 Dec 24 23:14 Xcode.app -> Xcode-Beta.app

Note:
    The soft link Xcode.app must be deleted before installing the official release version of Xcode next time.

Sunday, September 14, 2014

Python: return a dictionary from MySQLdb query

By default MySQLdb library in Python only returns an array of values in the order you retrieve them. But you can return an dictionary by changing the cursor type to: MySQLdb.cursors.DictCursor:

cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)

Have a try and have fun.

How to make MyObject serializable

1.  Implement one method to convert your Object to a 'Dict'. e.g.
class MyObject:
    #    ...
    #    MyObject has 3 properties: name (a string), number (an int), and parent (a MyObject)
    @staticmethod
    def serialize(obj):
        return {
            "name":   obj.name,
            "number": obj.number,
            "parent": obj.parent
        }

    #    ...

simplejson.dumps(myObjInstance, default=MyObject.serialize)
The cool thing is that dumps will, like every other JSON-serializable object, call the serialization method recursively. That is, obj.parent will get serialized as well, without any further action from you.

2. If all you want to do is 1-1 map instance variable names to their respective values, you can use some built-in Python magic. Whenever you want to serialize a more complex object (again, only using a 1-1 variable-value map), just call this line:
simplejson.dumps(anyObj, default=lambda obj: obj.__dict__)
For the given instance of MyObject, it will behave identically to the aforementioned serialize method.

Note: The 2nd one works for me, so I don't have to write a serialize method for my class.

Saturday, September 13, 2014

Detect the charset and then decode and encode with UTF-8

        # detect charset of this webpage
        chardit1 = chardet.detect(webPage)
        charset = chardit1['encoding']
        # convert it into UTF-8 if necessary
        if charset.lower() != "utf-8":
            print("charset=", charset, "convert to string in UTF-8")
            webPageInUnicode = webPage.decode(charset, "ignore")
            webPage = webPageInUnicode.encode("UTF-8")


For more information:

https://docs.python.org/2/howto/unicode.html#the-unicode-type

Sunday, August 31, 2014

A scrollable UINavigationBar

After googling, I found these two fantastic implementations in Github for a scrollable UINavigationBar.

  1. https://github.com/andreamazz/AMScrollingNavbar
  2. https://github.com/luugiathuy/GTScrollNavigationBar

Finally, I choose the first one in my application.


Do NOT invent and build a wheel!!!

Tuesday, August 26, 2014

Disable horizontal scrolling in a UIWebview

Firstly I tried

   

but failed.

Then I found the solution that works for me:

  1. set the webV to hide its indicator and set the scroll delegate
        webV.scrollView.delegate = self;    [webV.scrollView setShowsHorizontalScrollIndicator:NO];
  2. add the delegate method:

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.x > 0) {
        scrollView.contentOffset = CGPointMake(0, scrollView.contentOffset.y);
    }
}

Saturday, August 23, 2014

Reuse a UITableViewCell in multiple UITableViewControllers: Xib + Stroyboard

My project has two UITableViewController that will display two kinds of articles. The detailed article content will be displayed in a UIWebView(See the Figure below).
Using prototype cells in a stroyboard would cause a little duplication. You need to duplicate the prototype cells in the two UITableViews. One day in the future, if you need to change the style of the Cell, then you have to that twice(at least you have copy the prototype cell from one UITableViewController to the other). The combination of Xib and Stroyboard can solve this problem elegantly. Here is what I did:

  • Create an empty Xib and add a UITableViewCell into it.
    Design your Cell with whatever format you need in the Xib.
    Set the identifier of this cell as: "RNArticleCellID-1img"
  • Delete the Prototype Cells from The UITableView, set the row height as that defined in Xib
  • Create segue.
    Segue should be linked from the ParentVC to the DestinationVC (NOT from the Prototype Cell)
    Set the identifier of the segue as: "
    ShowArticleDetailFromCoach" and style as: "push"
  • Move to the implementation of the UITablveViewContllers.
    add the following code section to: 
    viewDidLoad
    [self.tableView registerNib:[UINib nibWithNibName:@"RNArticleCell-1img" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"RNArticleCellID-1img"];

get the cell:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    RNArticleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RNArticleCellID-1img" forIndexPath:indexPath];

Note that if you define the segue to go from the TableView instead of the cell, the segue will not be triggered by clicking on a cell. What you can do in this case is to use the didSelectRowAtIndexPath method and trigger the segue manually there. For example, add the following code segment:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self performSegueWithIdentifier:@"ShowArticleDetailFromCoach" sender:self];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([segue.identifier isEqualToString:@"ShowArticleDetailFromCoach"]) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
        RNArticleDetailVC *articleVC = [segue destinationViewController];
        NSIndexPath *path = [self.tableView indexPathForSelectedRow];
        NSInteger row = path.row;
        articleVC.articleDict = [self.articles objectAtIndex:row];
        articleVC.sourceName = @"managershare";
    }
}




Move Existing Xcode project into Bitbucket

I have been using Bitbucket to manage the source code of my personal projects. But I always use the git command in Terminal.

I started working on a new project today and I found it's very easy to move an existing project, which has been managed with the embedded git in Xcode, into Bitbucket. Here are the steps:
  1. Create a new repository for your project in Bitbucket.
  2. Xcode -> Preference, then press the add button("+") to add a repository with the address you created in Bitbucket for your project. e.g.
    https://allesgut@bitbucket.org/allesgut/racenews.git
  3. cd your home directory for your project. e.g.
    cd ~/dev/iOS/RaceNews
  4. set up git on your machine. e.g.
    git remote add origin https://allesgut@bitbucket.org/allesgut/racenews.git
  5. Commit your changes to local server:
    Xcode -> Source Control -> Commit
  6. and push your projects to Bitbucket.
    Xcode -> Source Control -> Push
Now, you can check the source code in Bitbucket to see if the source code of your project has been moved to Bitbucket.

Tuesday, August 19, 2014

Use Bitbucket

First create a new repository in Bitbucket for your new project. Set the "Repository type" as "Git" and select your programming language. It is Python for my new project RaceNews.

Once your new repository is created, you can follow the instructions to set up your git from scratch.


Set up your git:

cd /path/to/your/projectgit initgit remote add origin https://allesgut@bitbucket.org/allesgut/racenews.git

Create your first file, commit, and push:


echo "Alex Xu" >> contributors.txtgit add contributors.txtgit commit -m 'Initial commit with contributors'git push -u origin master

Here is the file list in my project:
FOSs-MacBook:WebSpider fos$ find .
.
./contributors.txt
./output
./src
./src/sources
./src/sources/Chuangxinpai.py
./src/sources/Cnetnews.py
./src/sources/Forbeschina.py
./src/sources/FTchinese.py
./src/sources/Hbrchina.py
./src/sources/Investorchina.py
./src/sources/Reuterscn.py
./src/sources/Wallstreetcn.py
./src/sources/Yicai.py
./src/Spider.py
./src/tst
./src/tst/BS4Demo.py
./src/tst/Test.py
./src/WebUtil.py
Now I need to put the src files into the repository:
git add srcgit add outputgit commit -agit push
When you see the output "b225aae..529962f  master -> master", you can check that all your files should have been put to the repository in Bitbucket.