2013年5月8日星期三

copy from Blog of Bruce Eckel

Computing Thoughts
Decorators I: Introduction to Python Decorators
by Bruce Eckel
October 18, 2008
Summary
This amazing feature appeared in the language almost apologetically and with concern that it might not be that useful.

ADVERTISEMENT
I predict that in time it will be seen as one of the more powerful features in the language. The problem is that all the introductions to decorators that I have seen have been rather confusing, so I will try to rectify that here.
(This series of articles will be incorporated into the open-source book Python 3 Patterns & Idioms).

Decorators vs. the Decorator Pattern

First, you need to understand that the word "decorator" was used with some trepidation, because there was concern that it would be completely confused with the Decorator pattern from theDesign Patterns book. At one point other terms were considered for the feature, but "decorator" seems to be the one that sticks.
Indeed, you can use Python decorators to implement the Decorator pattern, but that's an extremely limited use of it. Python decorators, I think, are best equated to macros.

History of Macros

The macro has a long history, but most people will probably have had experience with C preprocessor macros. The problems with C macros were (1) they were in a different language (not C) and (2) the behavior was sometimes bizarre, and often inconsistent with the behavior of the rest of C.
Both Java and C# have added annotations, which allow you to do some things to elements of the language. Both of these have the problems that (1) to do what you want, you sometimes have to jump through some enormous and untenable hoops, which follows from (2) these annotation features have their hands tied by the bondage-and-discipline (or as Martin Fowler gently puts it: "Directing") nature of those languages.
In a slightly different vein, many C++ programmers (myself included) have noted the generative abilities of C++ templates and have used that feature in a macro-like fashion.
Many other languages have incorporated macros, but without knowing much about it I will go out on a limb and say that Python decorators are similar to Lisp macros in power and possibility.

The Goal of Macros

I think it's safe to say that the goal of macros in a language is to provide a way to modify elements of the language. That's what decorators do in Python -- they modify functions, and in the case of class decorators, entire classes. This is why they usually provide a simpler alternative to metaclasses.
The major failings of most language's self-modification approaches are that they are too restrictive and that they require a different language (I'm going to say that Java annotations with all the hoops you must jump through to produce an interesting annotation comprises a "different language").
Python falls into Fowler's category of "enabling" languages, so if you want to do modifications, why create a different or restricted language? Why not just use Python itself? And that's what Python decorators do.

What Can You Do With Decorators?

Decorators allow you to inject or modify code in functions or classes. Sounds a bit like Aspect-Oriented Programming (AOP) in Java, doesn't it? Except that it's both much simpler and (as a result) much more powerful. For example, suppose you'd like to do something at the entry and exit points of a function (such as perform some kind of security, tracing, locking, etc. -- all the standard arguments for AOP). With decorators, it looks like this:
@entryExit
def func1():
    print "inside func1()"

@entryExit
def func2():
    print "inside func2()"
The @ indicates the application of the decorator.

Function Decorators

A function decorator is applied to a function definition by placing it on the line before that function definition begins. For example:
@myDecorator
def aFunction():
    print "inside aFunction"
When the compiler passes over this code, aFunction() is compiled and the resulting function object is passed to the myDecorator code, which does something to produce a function-like object that is then substituted for the original aFunction().
What does the myDecorator code look like? Well, most introductory examples show this as a function, but I've found that it's easier to start understanding decorators by using classes as decoration mechanisms instead of functions. In addition, it's more powerful.
The only constraint upon the object returned by the decorator is that it can be used as a function -- which basically means it must be callable. Thus, any classes we use as decorators must implement __call__.
What should the decorator do? Well, it can do anything but usually you expect the original function code to be used at some point. This is not required, however:
class myDecorator(object):

    def __init__(self, f):
        print "inside myDecorator.__init__()"
        f() # Prove that function definition has completed

    def __call__(self):
        print "inside myDecorator.__call__()"

@myDecorator
def aFunction():
    print "inside aFunction()"

print "Finished decorating aFunction()"

aFunction()
When you run this code, you see:
inside myDecorator.__init__()
inside aFunction()
Finished decorating aFunction()
inside myDecorator.__call__()
Notice that the constructor for myDecorator is executed at the point of decoration of the function. Since we can call f() inside __init__(), it shows that the creation of f() is complete before the decorator is called. Note also that the decorator constructor receives the function object being decorated. Typically, you'll capture the function object in the constructor and later use it in the __call__() method (the fact that decoration and calling are two clear phases when using classes is why I argue that it's easier and more powerful this way).
When aFunction() is called after it has been decorated, we get completely different behavior; the myDecorator.__call__() method is called instead of the original code. That's because the act of decoration replaces the original function object with the result of the decoration -- in our case, the myDecorator object replaces aFunction. Indeed, before decorators were added you had to do something much less elegant to achieve the same thing:
def foo(): pass
foo = staticmethod(foo)
With the addition of the @ decoration operator, you now get the same result by saying:
@staticmethod
def foo(): pass
This is the reason why people argued against decorators, because the @ is just a little syntax sugar meaning "pass a function object through another function and assign the result to the original function."
The reason I think decorators will have such a big impact is because this little bit of syntax sugar changes the way you think about programming. Indeed, it brings the idea of "applying code to other code" (i.e.: macros) into mainstream thinking by formalizing it as a language construct.

Slightly More Useful

Now let's go back and implement the first example. Here, we'll do the more typical thing and actually use the code in the decorated functions:
class entryExit(object):

    def __init__(self, f):
        self.f = f

    def __call__(self):
        print "Entering", self.f.__name__
        self.f()
        print "Exited", self.f.__name__

@entryExit
def func1():
    print "inside func1()"

@entryExit
def func2():
    print "inside func2()"

func1()
func2()
The output is:
Entering func1
inside func1()
Exited func1
Entering func2
inside func2()
Exited func2
You can see that the decorated functions now have the "Entering" and "Exited" trace statements around the call.
The constructor stores the argument, which is the function object. In the call, we use the __name__ attribute of the function to display that function's name, then call the function itself.

Using Functions as Decorators

The only constraint on the result of a decorator is that it be callable, so it can properly replace the decorated function. In the above examples, I've replaced the original function with an object of a class that has a __call__() method. But a function object is also callable, so we can rewrite the previous example using a function instead of a class, like this:
def entryExit(f):
    def new_f():
        print "Entering", f.__name__
        f()
        print "Exited", f.__name__
    return new_f

@entryExit
def func1():
    print "inside func1()"

@entryExit
def func2():
    print "inside func2()"

func1()
func2()
print func1.__name__
new_f() is defined within the body of entryExit(), so it is created and returned when entryExit() is called. Note that new_f() is aclosure, because it captures the actual value of f.
Once new_f() has been defined, it is returned from entryExit() so that the decorator mechanism can assign the result as the decorated function.
The output of the line print func1.__name__ is new_f, because the new_f function has been substituted for the original function during decoration. If this is a problem you can change the name of the decorator function before you return it:
def entryExit(f):
    def new_f():
        print "Entering", f.__name__
        f()
        print "Exited", f.__name__
    new_f.__name__ = f.__name__
    return new_f
The information you can dynamically get about functions, and the modifications you can make to those functions, are quite powerful in Python.

More Examples

Now that you have the basics, you can look at some more examples of decorators here. Note the number of these examples that use classes rather than functions as decorators.
In this article I have intentionally avoided dealing with the arguments of the decorated function, which I will look at in the next article.

2013年5月3日星期五

knowledge for installing speakers on nissan 2012

DIY Altima dash removal / radio replacement


Ok time to takle the altima dash.

1. Remove all cd's out of stock head unit

2. Disconnect the negative battery terminal under the hood

3. Using a pry tool work the air vents loose and remove them. Disconnect both the hazard harness and the air bag light. NOTE Remember to have you negative battery terminal off.

Click the image to open in full size.

Click the image to open in full size.

Click the image to open in full size.

4. After removing the vents this will expose 2 Philips screws silver in color remove them.

Click the image to open in full size.

5. Next reach under the center and pull a small cover off exposing 2 silver screws remove these as well.

Click the image to open in full size.

Click the image to open in full size.

6. You are now ready to remove the radio. Using both hands one at the top and one at the bottom. Start pulling towards you working back and fourth as well. There will be a few wiring harnesses you will have to disconnect after you get the radio out.

Click the image to open in full size.

7. Radio removed
Click the image to open in full size.

8. Fallow your instructions of your new dash kit.

9. Install in reverse order

Click the image to open in full size.

2011年8月7日星期日


1938年9月,中共中央政治局会议与会者合影。前排左起:康生、毛泽东、王稼祥、朱德、项英、王明;后排左起:陈云、博古、彭德怀、刘少奇、周恩来、张闻天。

2011年7月6日星期三

interactive learning

machine learning deals with the task of learning a function from observations of examples which have been labeled or unlabeled. This recovered function can be used to make predictions on the future new coming data.

However, most of previous ML algorithms do not interact with the environment, or other helpful resources that may improve the learning ability. A new topic appears recently, which is called interactive learning. Its idea has close connection with active learning and self-taught learning. The computer agent not only analyzes the data by utilizing its powerful computation ability, but also develops a kind of intelligent ability to actively seek new resources and interact with other objects in the world to improve learning ability. Human has this ability. When a baby is learning to speak, the first step he/she is trying to mimic the sound from his/her parents. At the same time, he/she can feel the feedback from the parents, such as appraise or disappointment. Based on such feedback, a baby will adjust his/her speaking. After the baby grows more mature, he/she is able to infer the intent of parents and proactively takes some action to attract parents or probe the feedback of parents.

Computer of course has larger advantage in computation capacity than human being, while it needs more advanced algorithms to become as intelligent as human being. That is an important purpose of artificial intelligence. The new research on interactive learning topic is challenging, while it is also very promising if we can develop some practical algorithms in this area.

2011年5月24日星期二

implicit problems using matlab on clusters

CPU resource limits will now be enforced on Tensor. CPU usage will be monitored during the lifetime of each job and if the average CPU load exceeds the requested value of ncpus by 50% then the job will be automatically killed.

For example, if a job requests ncpus=1 but it actually uses eight cores then the job will end prematurely with a warning similar to the following:

PBS: job killed: ncpus 7.37 exceeded limit 1 (sum)

It is particularly easy to consume too many CPUs when using MATLAB because all versions of MATLAB since 2008a have multithreading enabled by default. Consequently, you may not be aware that your MATLAB job is using more than one CPU. Please consult the MATLAB documentation for further information on implicit multithreading.

2011年5月18日星期三

how to compile matlab codes to standalone applciations

Sometimes, our matlab simulation may require a large amount of computation resources, which even causes hundreds of days for us to wait for the results. It seems unendurable and what we can do is just to give up the experiments. Is it true? No, we can find some solution to overcome this difficulty. Cluster! the same idea of Mapreduce. First, we dicompose the problem into subproblems, then we solve these subproblems using different processors in a cluster of computers. Finally, we combine the results of subproblems into one final solution to the original large-scale problem.

To use matlab on the cluster, the first problem we have to solve is to compile the matlab code into a standalone application. Because it not only speeds up the computation time but also is not limited by the restriction of maximum licenses for the matlab software we can use at the same time.

To compile the matlab, we have to configure the environment at the beginning. The command is
module add mcc
This command sets the lib path for matlab standalone executable. Without this setting, you may get the error saying that some shared library is missing. Next, we call

mcc -m -v main.m -a \sourcecode\

which not only compiles your main matlab codes but also the codes in the folder and subfolder of sourcecode.

Now we can talk about how to submit the executable file to clusters.

2011年5月14日星期六

a project summary transfered from nyu Glimcher lab's website

Dopamine and Reinforcement Learning



Psychological and microeconomic theories of choice suggest that humans and animals must assign values to actions and objects in the world. These values can then be used to select the appropriate action or goal for a particular circumstance. Two major strands of research suggest that reinforcement learning is a mechanism that humans and animals use to learn these values. Classic behavioral studies of reinforcement learning in free choice environments have used the concurrent variable interval schedule introduced by Herrnstein in the late 1960's. In our lab we have extended this behavioral work and are now developing a replacement behavioral task better suited for neuroeconomic research.

Recent evidence has linked computational models of reinforcement learning (e.g. Sutton & Barto, 1998) originally derived from the psychological models of Bush & Mosteller and Rescorla & Wagner to the midbrain dopamine system. In particular, electrophysiological studies, suggest that dopamine neurons in the substantia nigra pars compacta (SNc) and ventral tegmental area (VTA) encode a reward prediction error (RPE) signal, the difference between experienced and anticipated reward.

Work done by Hannah Bayer in her thesis work in the Glimcher lab extended this research to show that dopamine neuron activity quantitatively encodes the predicted RPE signal (Bayer & Glimcher, 2004). Other labs have extended this research to show that the BOLD response in the Striatum (a dopamine target area) reflects a RPE signal as measured by fMRI in humans.

Further evidence for the encoding of values in the Striatum through reinforcement learning comes from electrophysiological recordings including the thesis work of Brian Lau in the Glimcher Lab. Brian demonstrated that both 'offer values' and 'chosen values' are represented in the Striatum. The time course of this neural encoding is compatible with possible roles in choice selection and the generation of RPE signals.

Reinforcement learning in monkeys with stimulation (Schafer).
Previous work (Schultz) indicates that SNc dopamine neurons encode a RPE when animals receive (or miss) a reward. We are extending this to actual decision tasks modeled after Hernnstein’s matching law (Herrnstein, 1961), where the animal chooses between two targets with different reward contingencies. We find that under choice conditions, dopamine firing rates are well predicted by the reinforcement learning models. Our current project causally tests the hypothesis that dopamine neurons are, in fact, encoding a RPE signal used in reinforcement learning. By actively stimulating dopamine neurons with pulses of current at the appropriate time during our choice task, we should cause the animal's predicted value of an option to increase and the animal’s behavior should change to reflect this.

Bandit task in humans (DeWitt, Dean).
The classic choice task developed by Herrnstein to study the 'Matching Law' has critical flaws when extended to the dynamic environments faced by humans and animals. We have developed a novel dynamic choice task based on the n-armed bandit problem widely studied in economics and computer science that overcomes these flaws. Importantly, we know the optimal strategy for our task on a choice-by-choice basis and this strategy is classic reinforcement learning! Our new task allows the measurement of the efficiency of reinforcement learning and to determine if humans and animals correctly trade-off the effect of noise against underlying changes in the environment as predicted by Bayesian theory.

Reinforcement learning in Parkinson's disease (Rutledge).
Parkinson's disease is characterized by a loss of dopamine neurons in the SNc and is associated with tremor, rigidity, and akinesia. The effect of this degeneration on reinforcement learning is unclear. To characterize human reinforcement learning we developed a task, adapted from our monkey choice task, in which subjects fish for crabs to earn money. By testing patients with Parkinson's disease both on and off dopaminergic medication, we find that reinforcement learning is modulated as predicted by theory. This project is a collaboration with Mark Gluck (Rutgers-Newark).

Methods for imaging dopamine areas in humans (DeWitt, Rutledge).
We are developing novel techniques to measure BOLD signals in dopamine projection and target areas in humans using Functional Magnetic Resonance Imaging (fMRI). We use the BOLD signal to provide an indirect measure of dopamine neural activity in humans. Unfortunately, current fMRI techniques make it difficult to accurately measure the midbrain dopamine areas and the orbito-frontal cortex (a major dopamine target area implicated in reinforcement learning). To better describe dopamine activity in choice tasks, we are developing imaging protocols to overcome measurement problems and functional and anatomical localizers to accurately and reliably find the dopamine areas. Our anatomical localizer uses an appropriate pulse sequence to image iron that accumulates in the dopamine areas as a byproduct of dopamine synthesis. Our functional localizer uses a classical conditioning task with primary rewards (juice) to identify dopamine areas. We have also developed a new method of image reconstruction using field map estimates to correct for signal dropout in the orbito-frontal cortex caused by magnetic field inhomogeneities near the air-filled sinuses.This project is a collaboration with Souheil Inati (Center for Brain Imaging, NYU).

An axiomatic model of dopamine function (Dean, Rutledge).
Although widely accepted, the dopamine RPE model has never been properly tested. We have developed a formal economic model which provides us with a number of testable axioms. We are collecting fMRI data using a task in which subjects choose between lotteries and observe the outcomes to win and lose real money. As expected, dopamine area activity is correlated with the predicted RPE signal. We are now testing whether dopamine area activity satisfies our economic axioms. This project is a collaboration with Mark Dean and Andrew Caplin (Economics, NYU).