Thursday, October 17, 2013

Partial function call

This post is part of the pyfun series, I will try to *log* some of the features that I think they make Python funny :)

Again, I was reading the Scala tutorial and find that she has built-in support of partial function call (see http://twitter.github.io/scala_school/basics.html#functions). This reminded me that Python does also has functools.partial(), which can be used as function shortcuts.

Let's see this example of Django.

# Let's have a Coupon that can either be fixed amount discount or percentage off
# But, we don't want to have model inheritance and table join to get the data
class Coupon(models.Model):
    code = models.CharField(max_length=8)
    type = models.CharField(max_length=11, choices=['fixedamount', 'percentage'])
    amount = models.DecimalField(max_digits=8, decimal_places=2)
    currency = models.CharField(max_length=3, choices=['USD', 'CAD'], default='')


# To create a Coupon based on certain conditions, you can have this
kwargs = {'code': code}

if condition_a:
    kwargs.update({'type': 'fixedamount', 'currency': 'USD'})
elif condition_b:
    kwargs.update({'type': 'percentage'})

kwargs.update({'amount': x if condition_c else y})
coupon = Coupon.objects.create(**kwargs)


# Or with functools.partial()
FixedamountCoupon = functools.partial(Coupon.objects.create, type='fixedamount')
PercentageCoupon = functools.partial(Coupon.objects.create, type='percentage')

if condition_a:
    coupon = functools.partial(FixedamountCoupon, code=code, currency='USD')
elif condition_b:
    coupon = functools.partial(PercentageCoupon, code=code)

coupon = functools.partial(coupon, amount=x if condition_c else y)
coupon = coupon()

Yes, we just shortcuted two types of Coupon using functools.partial(), created "sub-class" of Coupon. Furthermore, if the underlying function accepts positional arguments, we can also shortcut those arguments.

Clean code FTW.

Friday, October 11, 2013

Scala Traits in Python?

Sometimes, I would question myself, am I qualify as a seasoned Python engineer? The answer is I'm still a junior. The next question is, how to qualify as a seasoned one?

I have two things in mind that may be part of the answer to the second question:

1. Know when to use certain Python features.
2. Know what kind of library or framework is suitable for particular task.

In this pyfun series, I will try to *log* some of the features that I think they make Python funny :)

Let's get back to the primary subject of this post. Scala, which compiles to JAVA bytecode and runs on JVM, is one of the latest big hit. So, I'm going through some tutorials of it to check out her magics. One of the topic is Traits.

Traits, is similar to Java interface. When I read some samples about it, I wonder how can it be done in Python. From stackoverflow, http://stackoverflow.com/q/6240118, there is a suggestion that to use Python class to simulate the thing. And, starting from that idea, I wonder can we do that in runtime instead of just static definition. Here, we come to Python type().

Most of the time, type() can be used as Enum in C (see http://stackoverflow.com/a/1695250), or dynamic objects like those in Javascript (https://gist.github.com/mrkschan/6936112). It is because type() is essentially a dynamic form of the class statement (http://docs.python.org/2/library/functions.html#type). In other words, we can use type() to create Python class that simulates Traits (JAVA interface) at runtime.

Here is an example.

# See original Scala version at http://twitter.github.io/scala_school/basics.html#trait
Car = type('Car', (object,), {'brand': ''})
Shiny = type('Shiny', (object,), {'refraction': 0})

BMW = type('BMW', (Car, Shiny,), {'brand': 'BMW', 'refraction': 100})
my_bmw = BMW()

print my_bmw.brand, my_bmw.refraction

# We can have constructor as well
def bmw_init(self, refraction):
    self.refraction = refraction

BMW = type('BMW', (Car, Shiny,), {'brand': 'BMW', '__init__': bmw_init})
c1, c2 = BMW(10), BMW(100)
print c1.refraction, c2.refraction

As we can see, we can use type() to create a set of "interfaces". And, use type() to create class that implement the "interface". These "interfaces" can have its name changed according to runtime conditions. type() is Python magic and it's fun :)

However, I did not come up with a use case for runtime defined Traits yet :P

Saturday, September 28, 2013

Bypassing (Great) firewall to access GitHub / BitBucket via SSH Tunnel

Sometimes, you may be blocked by a firewall and cannot access GitHub / BitBucket. In this post, the steps to bypass the firewall using SSH tunnel is documented.


Step 1 - Setup the tunnel
----------------------------------------

Assuming you use SSH to perform git operations (git clone, fetch, pull, merge, etc.), you should find a SSH URL like: git@github.com:example/example.git or git@bitbucket.org:example/example.git. In order to access the blocked SSH hosts, we have to SSH tunnel to forward the requests. To do so, use the following commands to create a tunnel (assume you have a SSH host that can be accessed).

ssh -C -L 8022:github.com:22 example@example.com  # Establish a tunnel to github.com, SSH requests to local port 8022 are forwarded to github.com:22.

ssh -C -L 8122:bitbucket.org:22 example@example.com  # Establish a tunnel to bitbucket.org, SSH requests to local port 8122 are forwarded to bitbucket.org:22.

Of course, you can combine the two to have one SSH session only.

ssh -C -L 8022:github.com:22 -L 8122:bitbucket.org:22 example@example.com


Step 2 - Config SSH client
------------------------------------------

After you have your tunnels, you can then configure your SSH client to redirect SSH requests to your tunnels. Put the following lines in your ~/.ssh/config file.

Host github.com
HostName 127.0.0.1
Port 8022

Host bitbucket.org
HostName 127.0.0.1
Port 8122



Afterwards, feel free to use git clone git@github.com:example/example.git or git clone git@bitbucket.org:example/example.git (you can also use git fetch, pull, merge, etc.). All requests will be passing through your SSH tunnel.

Tuesday, April 16, 2013

中產工種被誰取代

昨天在看一篇評論,說美國總統做什麼都改變不了大部分中產階層的命運。理據如下:

1. 大學生普及化,一般水平的人力資源充足,而需求卻沒有相對增加,使一般中產階級工種薪酬下降,而且惡性循環不斷。

2. 軟件業發達,企業軟件取蒂中產階級工種人手(如中級管理人員),高層工作效率因軟件發達而不斷上升,促使人手需求不斷下降。

那麼,要擺脫那惡性循環,除了是優秀人才,或是專業工作從業者,或是成功startup的核心團員。還有什麼正常途徑?扎鐵吧!

作為軟件行業從業員, 又如何擺脫厄運?

Monday, March 25, 2013

Laptop火牛點解咁大隻

Laptop本來的設計精要在於移動性,
但係好多laptop的火牛,都差不多是一罐可樂咁重(最近習慣了用可樂做單位)。帶laptop出街 ,本來是1.5kg卻變了2kg,實在無耐。

點解火牛要咁大隻,唔可以好似Apple果D維他奶size?

我有谂過買多一隻牛,公司一隻屋企一隻,咁就少左個藉口唔帶Laptop,但又不想為一部舊laptop投入過多金錢… 你話人係不係總要犯賤?又要解決問題又不肯付出:P 還是多花一兩舊水,把懶惰的藉口抹去吧啦

Friday, March 08, 2013

SEO Tips: Abuse Github

NOTE: I'm not a SEO guy. If this post used wrong wordings, sorry for that.  And, I'm not a native English speaker, don't blame my English writing :P And, I don't know whether someone has shared something similar :)

I have several pet projects hosted on github. And, I observed that Google give pretty high ranking to github repository. If a github repository has a homepage, that homepage will get benefits as well.

Thus, I carried out an experiment at https://github.com/mrkschan/github-seo-effect. I used the search terms "Github SEO effect" as the repository name and set the homepage that links to my blog post at http://mrkschan.blogspot.hk/2013/03/github-seo-effect.html

The result is pretty amazing. Here is a Google search result before I carried out the experiment (I was using Chromium private browsing, with links set to use "gl=us").

My blog post gets nowhere on the search result.

After a few days that I set the homepage to the blog post, the result becomes the following screencap.
My repository goes to the top of the search result. And, the blog post is on the first page of the Google Search :)

BTW, shall we abuse Github for SEO purpose? Try your search here: http://www.google.com/search?gl=us&q=github+seo+effect

Friday, March 01, 2013

Github SEO effect

This is a blog post to experiment the hypothesis:

Google would give github repo pretty high ranking.
If a repo's README has a link to a page outside github, that page gets SEO bonus.edit: 20130308 If a repo's homepage has set to a web page, that page would get SEO bonus from Google (I didn't carry out experiment on the effect of the README yet). And, if the page links back to the github repo, that's a plus.

Search google with the query "Github SEO effect" :)

Link: https://github.com/mrkschan/github-seo-effect

Result: http://www.google.com/search?gl=us&q=github+seo+effect

Thursday, February 28, 2013

信念, Faith

男人問女人: "你有什麼信念嗎?"

女人問: "為什麼問這個問題?"

男人說: "別人說人不能沒有信念."

女人答: "我相信會找到一個愛我的人."

女人問: "那你呢?"

男人說: "我不知道."

朋友們, 你的信念是什麼?


Faith - (from thefreedictionary.com)
1. Confident belief in the truth, value, or trustworthiness of a person, idea, or thing.
2. Belief that does not rest on logical proof or material evidence.

信念 - (from 中華民國教育部 - 重編國語辭典修訂本)
信仰不疑的意念.


我的信念? 可能是建立一個舒適的家 :)

Thursday, January 31, 2013

很久沒寫

最近寫的, 不是生活相關的, 就是技術相關的, 缺少了思考的東西. 人像懶了, 笨了.

原因? 曾經想過會不會是生活太匆忙而給自己藉口不去思考東西/反思. 又會不會是習慣了 twitter 文化, 一切從簡? 那今天又為什麼在寫這篇廢話呢? 不是在 twitter 上寫句: o, i'm so lazy. 就行了嗎?

事原: 有位家人最近離開了這個世界, 我因而接觸到佛學的地藏王菩薩經. 裡面, 提到了無間地獄. 無間地獄在電影無間道被提及過: "明明我已晝夜無間踏盡面前路, 夢想中的彼岸為何還未到". 再加上最近有點迷失(even after i read the book "Life is what you make it" twice), 對無間地獄提起了點興趣. 剛坐車回家的時候, 在想如何去認識無間地獄. 忽然, 想起了在大學的時候, 學習道家文化時在這個 blog 寫了點東西. 到家了, 便走上這裡, 找找以前寫的東西. 期間, 我在看自己以前寫的東西. 整個過程很有趣. 因為我在嘗試認識從前的我. 看了, 發覺對從前的我很陌生, 而且這個過程很有趣 :)

為此有感而發, 在twitter文化驅使下寫了句 "regrets should be prevented, but reviewed is encouraged. mrkschan.blogspot.hk/2006/09/blog-p my 1st blog :)". review的就是要多認識自己, regret的就是我的靈魂好像有一年時間消失了一樣.

想了一會, 我不想以後再後悔. 花少少時間, 寫一寫, 裝個讀書人.


 
© 2009 Emptiness Blogging. All Rights Reserved | Powered by Blogger
Design by psdvibe | Bloggerized By LawnyDesignz