Wednesday, August 14, 2019

Show a range of data for the histograms/distributions in TensorBoard

Sometimes we want to look at the detail of histograms/distributions for a particular range of steps. However, TensorBoard does not provide zoom-in function for histograms/distributions. In order to do so, you have to change the TensorBoard code. The relevant python code is PYTHON_DIR/site-packages/tensorboard/plugins/histogram/histograms_plugin.py. In funciton histotrams_impl(), you can filter out the steps constraining e.step you needed before the return. In order to show every steps, you also need to set the flag "--samples_per_plugin hisgograms=0" when starting tensorboard.

Wednesday, January 30, 2019

Incorrect handling of CTRL-C in pdb

I usually start a python program I want to debug by running:
    python3 -m pdb -c continue MY_PROGRAM
I can use CTRL-C to break the program, adding break points, and I can CTRL-C multiple times.
However, recently, for some unknown reason, pdb is no longer able to continue to run the program after the second CTRL-C. Looking into pdb.py, I found the following piece of code for handling CTRL-C.

    def sigint_handler(self, signum, frame):
        if self.allow_kbdint:
            raise KeyboardInterrupt
        self.message("\nProgram interrupted. (Use 'cont' to resume).")
        self.set_step()
        self.set_trace(frame)
        # restore previous signal handler
        signal.signal(signal.SIGINT, self._previous_sigint_handler)

Inspecting the value of self._previous_sigint_handler, it points to the default sigint handler, which will break the program. It turns out that the last two lines were removed in python3.5.3 in this commit.

So you can solve this problem by upgrading to a newer version of python3. Or if it's not easy to upgrade (like me, using Ubuntu 16.04, python 3.6.3 or newer is not available), commenting out the last line seems to work.

Friday, November 30, 2018

Debug into python system libraries in Visual Studio Code

By default, vscode does not let you to debug into python system libraries. If errors or exceptions happen in system libraries, you will only see the errors at the place you call the system library. Even if you set break points in system libraries, when it stops, it will stop at the place you call the system library. And the stack trace only shows the stack up to the call to system library. This can be very inconvenient sometimes. Fortunately, this behavior can be changed by setting "debugStdLib" to true in the launch configuration (can be opened through Menu->Debug->Open Configurations) like the following:

"configurations": [
{
    "name": "Python: Current File (Integrated Terminal)",
    "type": "python",
    "request": "launch",
    "program": "${file}",
    "console": "integratedTerminal",
    "debugStdLib": true,
},

Thursday, November 29, 2018

Fixed randomness for tensorflow.keras for reproducible runs

Just follow the FAQ here
One of the steps is to set environment variable PYTHONHASHSEED=0 before starting python. For Visual Studio Code, you need to add the environment setting like the following in the configuration (can be opened through Menu->Debug->Open Configurations)

"configurations": [
{
    "name": "Python: Current File (Integrated Terminal)",
    "type": "python",
    "request": "launch",
    "program": "${file}",
    "console": "integratedTerminal",
    "debugStdLib": true,
    "env": {"PYTHONHASHSEED": 0}
},

Notes about Keras custum RNN

There are several limitations of keras.layers.RNN

  1. It can have only one input.
  2. It can have only one output.
  3. The input has to be at least 3D (batch * timesteps * extra_dimensions). This is a slight inconvenience because you can use expand_dims to expand 2D tensor to 3D tensor.
  4. The signature of cell.call() is not same as keras.Model.call(), this make it impossible to use Model as the base for cell. Thus it is very cumbersome to write complex custom cell consisting of many Layers.

Wednesday, November 21, 2018

Notes about Eager Execution using Keras

About model inputs
If the model is created using Sequential, the inputs can be numpy ndarray. However, if you compose the model using Keras layers like the MNISTModel in the Guide for Eager Execution, the inputs need to be Tensorflow Tensors. You can use tf.constant() to convert numpy arrays to Tensors. However, some types of numpy array are not accepted by tf.constant(). For example, 'a = np.random.randint(0, 10, (2,3)) % 5' does not work with tf.constant(). You need to do a type conversion a=a.astype(np.int32) before calling tf.constant.




Wednesday, September 13, 2017

Tools for debugging shared library linking issue

1. LD_DEBUG environment variable.
2. LD_PRELOAD environment variable.
3. ltrace utility

See ld.so(8) and ltrace(1) for reference

Friday, October 16, 2015

Signature for C++ lambda function

Lambda function is a class with operator()(...) const. This class does not have default constructor or copy constructor.

Hence the function signature of a lambda function f can be accessed as the following:

 template<typename F> class traits;  
 template<typename C, typename R, typename... Args> struct traits<R (C::*)(Args...) const> {  
   typedef R result_type;  
 };  
 typedef typename traits<decltype(&decltype(lambda)::operator())>::result_type result_type;  



Monday, September 16, 2013

Force Chrome to use socks5 proxy for DNS

Right now, there's no GUI interface for doing this. You need to start Chrome with the following flags:
--proxy-server="socks5://127.0.0.1:1080" --host-resolver-rules="MAP * 127.0.0.1"

Wednesday, December 12, 2012

Compile octave



Latest version of octave needs texinfo and newer version of gcc.

1.  Install gcc 4.7.1. gcc needs additional 3 components which have to be downloaded separatedly:

unzip and copy them to gmp mpfr and mpc or gcc-4.7.1 source dir

mkdir ~/gcc-4.7.1
cd ~/gcc-4.7.1
~/downloads/gcc-4.7.1/configure  --enable-languages=all
make
sudo make install

2. Install texinfo
./configure
make
sudo make install

3. Install blas and lapack. On my environment, this is done by:

yum install blas
yum install lapack

And for me, I have to manually create a sym link libblas.so and liblapack.so as octave configuration cannot find the versioned so.

sudo ln -s libblas.so.3.0.3 /usr/lib64/libblas.so
sudo ln -s liblapack.so.3.0.3 /usr/lib64/liblapack.so

4. Install gnuplot-4.4

5. Install octave
cd octave-3.6.2
LD_RUN_PATH=/usr/local/lib64 LDFLAGS=-L/usr/local/lib64 ./configure --without-curl
LD_RUN_PATH=/usr/local/lib64 make -j 8

You may need to use different directories other than /usr/local/lib64 depending on where your blas/lapack/gfortran  libraries are located. If error happens, look at config.log to get more detail.


Wednesday, October 10, 2012

Creating and inserting into bucketed table

The clause for bucketing is:

[CLUSTERED BY (col_name, col_name, ...) [SORTED BY (col_name [ASC|DESC], ...)] INTO num_buckets BUCKETS]

The CLUSTERED BY and SORTED BY creation commands do not affect how data is inserted into a table – only how it is read. This means that users must be careful to insert data correctly by specifying the number of reducers to be equal to the number of buckets, and using CLUSTER BY and SORT BY commands in their query.

According to https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL+BucketedTables, with hive.enforce.bucketing=true, we don't need CLUSTER BY clause in the insert query. This is NOT correct. We still need CLUSTER BY in insert query.

What hive.enforce.bucketing does is "DISTRIBUTE BY". In order to do sorting automatically, we need "hive.enforce.sorting=true" or have CLUSTER BY in the insert query.

So what "CLUSTERED BY" in the table definition means is "DISTRIBUTE BY" and hive.enforce.bucketing only enforces "DISTRIBUTE BY".

Wednesday, October 03, 2012

Memory units

Different units for size are used in different contexts.

context           unit
ps                1024 bytes
cat /proc/meminfo 1024 bytes
free              1024 bytes
du                1024 bytes
ls -l             1 byte

Wednesday, July 06, 2011

compile mpich2

If you are using gcc version >= 4.3 to compile mpich2-1.3, which can be downloaded from http://www.mcs.anl.gov/research/projects/mpich2, you are likely to get tons of multiple definition errors. It took me quite a while to figure out the reason and the solution. This is caused by the --std=gnu99 used in hwloc. But using gnu99 will change the meaning of "extern inline" used in many c header files as explained in http://gcc.gnu.org/gcc-4.3/porting_to.html. Knowing this, the solution is quite simple: using the following command to configure:

CFLAGS=-fgnu89-inline ./configure

Wednesday, April 13, 2011

Effective alternative minimum tax bracket

2010 AMT bracket for the alternative minimum taxable income (AMT income)
assumming no qualified dividend or long term capital gain.








fromtobracket
072,4500
72,450150,0000.26
150,000227,9600.325
227,960439,8000.35
439,800above0.28


The strange thing is that the tax rate decreases for high AMT income. This is due to the fact that the "Exemption Amount" (Form 6251 line 29) is reduced when the AMT income is between 150,000 and 439,800.

References:

Form 6251

Form 6251 Instruction

Friday, May 28, 2010

rogue virus leading to antispy-guide.net

My wife's computer was infected by a rogue virus. It's constantly asking to buy anti-virus software from antispy-guide.net. And it blocked the execution of other program by saying they are infected.
The only exception is browser. You can still open a browser. Apparently, they don't want to block the way so that the infected user can purchase their software.

Here is how I dealt with it:

In explorer, copy \windows\system32\taskmgr.exe to some other place. Then rename it as firefox.exe and run it. Now the task manager appears. In the task manager find and kill a process with a very strange name which unfortunately I forgot what exactly it is. And I also deleted the corresponding .exe file from the file system.

Now everything is back to normal. I am not sure this is a permanent fix. But so far so good.

Thursday, April 22, 2010

Increase limit on RLIMIT_NOFILE or other resources

Use setrlimit() to change the soft limit. But there is a hard limit which the setrlimit can not increase beyond.

In order to change the hard limit, you need to change the setting in following file
/etc/security/limits.conf

The syntax of the lines is as follows:

[domain] [type] [item] [value]

Use man limits.conf to see detailed explanation.

You can use command 'lsof -p [pid]' to see files opened by process pid.

Install Gnome On centos machine

Citing from

http://wiki.centos.org/FAQ/CentOS5#head-e99a7921ab6ce47e1cbf7d8cc8cadecf92b7ce94


yum --exclude=nautilus-sendto groupinstall "GNOME Desktop Environment"

Friday, February 12, 2010

NX broken session

If the remote server is restarted during an NX session, then you will encounter error when establishing a new session. You need to go to /usr/NX/var/db/running and delete files in the directory.

Friday, January 29, 2010

Passing Special Characters to Commands

Citing from The Linux Cookbook: Tips and Techniques for Everyday Use

Some characters are reserved and have special meaning to the shell on their own. Before you can pass one of these characters to a command, you must quote it by enclosing the entire argument in single quotes (`'').

For example, here's how to pass `Please Stop!' to a command:

'Please Stop!'
When the argument you want to pass has one or more single quote characters in it, enclose it in double quotes, like so:

"Please Don't Stop!"
To pass special characters as a string, give them as:

$'string'
where string is the string of characters to be passed. Special backslash escape sequences for certain characters are commonly included in a string, as listed in the following table.
ESCAPE SEQUENCE DESCRIPTION
\a Alert (rings the system bell).
\b Backspace.
\e Escape.
\f Form feed.
\n Newline.
\r Carriage return.
\t Horizontal tab.
\v Vertical tab.
\\ Backslash.
\NNN Character whose ASCII code is NNN in octal (base 8).
To demonstrate the passing of special character sequences to tool, the following examples will use the figlet tool, which displays the text you give as an argument in a "font" made up of text characters (see Horizontal Text Fonts).

To pass a backslash character as an argument to figlet, type:
$ figlet $'\\' [RET]
To pass a form feed character followed by a pilcrow sign character (octal character code 266) to figlet, type:
$ echo $'\f\266' [RET]

Wednesday, April 08, 2009

Binary numerical file IO in PERL

#following is a simple example
open FP, '>a.bin';
binmode FP; #make it binary file
@values=(3.2,3.3,3.4); #list of floating values
$a=pack 'f3' , @values; #pack as 32bit floating point value
#use 'd' for 64bit floating point
syswrite(FP,$a,12); #save to file
close FP;

Tuesday, August 05, 2008

Styling form file input

Due to certain security considerations, it is very difficult to change the style of file input.
Here is a good post on how to do it.
http://www.quirksmode.org/dom/inputfile.html

Following is quoted from above article:
  1. Take a normal < type="file">
  2. To this same parent element, add a normal <> and an image, which have the correct styles. Position these elements absolutely, so that they occupy the same place as the < type="file">.
  3. Set the z-index of the < type="file"> to 2 so that it lies on top of the styled input/image.
  4. Finally, set the opacity of the < type="file"> to 0. The < type="file"> now becomes effectively invisible, and the styles input/image shines through, but you can still click on the "Browse" button. If the button is positioned on top of the image, the user appears to click on the image and gets the normal file selection window.
    (Note that you can't use visibility: hidden, because a truly invisible element is unclickable, too, and we need the < type="file"> to remain clickable)
  5. When the user has selected a file, the visible, fake input field should show the correct path to this file, as a normal < type="file"> would. It's simply a matter of copying the new value of the < type="file"> to the fake input field, but we need JavaScript to do this.

Linking with static runtime libraries with MFC

In Visual C++, due to some conflicts between libcmt.lib and nafxcw.lib, you need to
make following changes in Linker->Input

Additional Dependencies: nafxcw.lib libcmt.lib
Ignore specific libraries: libcmt.lib nafxcw.lib

Wednesday, May 28, 2008

Using C99 support in Intel Compiler

C99 only works for C. Not C++. So the code must be compiled as C code not C++ code.

Thursday, April 24, 2008

javascript variable scope

The scope of a variable is the current function or, for variables declared outside a function, the current application.
Aassigning a value to an undeclared variable implicitly declares it as a global variable.

Each function is associated with its closure chain
A variable is undefined if cannot be found in the current closure chain,
and the access attemp will generate error.

The global function 'eval' uses current closure chain to evaluate the string.
If a function is still accessible, its function closure chain is still in memory.

Tuesday, April 22, 2008

Image flicker in IE6

This is due to IE 6 keeps check for the background image specified in css property everty time the element is moved over. Note that IE 5 or IE 7 do not have this problem.

A good post about this problem is at http://www.mister-pixel.com/

The solution is to add following javascript code inside the HEAD of the page:
try {
document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}

This fix works only with Internet Explorer 6, Service Pack 1 or newer.
Also, the fix does not apply if you change the background image on :hover. It only prevents the flicker of the same background image, when changing other rules inside the :hover state. But you can still change the background position.

Thursday, September 13, 2007

Save file using different extensions in MS Word

Usually, MS Word will append a fixed extension for a given file type. If you want to use a different extension, you need to enclose the file name in quotes. For example, "textfile.dat" will force MS Word to use dat as extension.

Open a file by drag-and-drop in MS Word

Unlike many other editors, for MSWord, the file should be dropped in the menu area.
It should not be dropped in document area. If it's dropped in document area,
it will become an embedded file.

Friday, August 31, 2007

File Security tab in Windows XP

The security tab for the file property disappears in certain Windows XP installations. Here is how to display the security tab
Citing from
http://www.microsoft.com/windowsxp/using/security/learnmore/accesscontrol.mspx

To display the Security tab

Open Folder Options in Control Panel. (Click Start, click Control Panel, click Appearance and Themes, and then click Folder Options.)

On the View tab, under Advanced settings, clear the Use simple file sharing [Recommended] check box.
By using the access control feature available in Windows XP Professional, you can help ensure that only the people you want to access the files and folders on your network are able to get to them

Monday, January 22, 2007

Misleading median income

Suppose your income is at the top 20% percentile. You think your income are quite good?
Not necessarily.

Consider following senario:

You are in a BIG established company, you have a stable income of, let's say, $100k/year.
However, each of your 9 buddies are in a startup company, each only get a $80k/year salary each year.
Suppose each year one of your buddy's company go IPO, then one of them get $1M from stock options.

Then you are one of the top 20% earners among these 10 persons, because only one get higher income than you because of the stock option.
But wait.
After 9 years, you earned $100k x 9 = $900k
But each of your buddies earned $80k x 9 + $1M = $1720k
Now you are lowest one among these 10 persons.

Tuesday, December 05, 2006

use MPICH on linux

Setup environment (assuming csh or tcsh)
setenv PATH mpi_install_dim/bin:$PATH

Setup ssh:
1. Setup host authentication (by administrator), following two files are relevant. See ssh manual page for detail.
/etc/ssh/ssh_known_hosts
/etc/ssh/ssh_host_rsa_key

2. Setup user authentication (by user)
ssh-keygen -b 1024 -t rsa
cp .ssh/is_rsa.pub .ssh/authorized_keys

If ssh is setup correctly, following command should be able to run without entering password:
ssh remosthostname date

Friday, August 18, 2006

conflict of matlab with Intel IPP

If you use latest version of IPP with matlab 7.1,
then you need make sure your IPP\bin and IPP\bin\win32 is ahead of MATLAB's directory in the PATH environment variable.

linux email forwarding

Create a file named .forward at home directory with the following content:
\username, emailname@abc.com

Of couse, you need to change username, emailname and abc.com to suitable value

Saturday, May 27, 2006

Defragment windows system files

Windows Disk defragmenter does not defragment system files.
A good tool PageDefrag at http://www.sysinternals.com/Utilities/PageDefrag.html can do this.

Optimize the System Cache Size

System Key: [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ Session ManagerMemory Management]
Value Name: LargeSystemCache
Data Type: REG_DWORD (DWORD Value)
Value Data: "0" for Desktops; "1" for Servers

Reference: http://www.winguides.com/registry/display.php/931/

Friday, April 14, 2006

Notes on using GnuPG

1. generate key-pair of yourself using
gpg --gen-key

2. Download desired file and its signature. The signature is supposed from person Joe
The desired file: abc.tar.gz
Its signature: abc.tar.gz.sig

3. Obtain the public key of Joe using
gpg --import KEY-FILE
or
gpg --keyserver pgpkeys.mit.edu --recv-key KEY-ID

Here KEY-FILE is the name of the file for the public key of Joe. This file needs to be obtained from Joe or other trusted source.
KEY-ID is the id of the public key of Joe. It should be obtained from Joe or other trusted source.

4. Verify that the signature using is signed using the public key
gpg --verify abc.tar.gz.sig

5. Make sure the key actually belongs to Joe by confirming the key fingerprint of the public key. The ultimate confirmation is by face to face communication.
gpg --fingerprint KEY-ID

6. If you trust Joe and are sure the public key belongs to Joe, you can sign the public key of Joe using
gpg --sign-key KEY-ID

Thursday, April 13, 2006

point vs. rate for mortgage

n: morgage term in number of years
m: number of years to closing
p: paid point

let t= n *annual_rate
s= m* annual_rate

p is equivalent to an increase of t to d+dt
Assuming no closing cost then

dt ~ c*p
c=t*(exp(t)-1)/(exp(t)-exp(t-s)-s)

So paying point p is equivalent to an increase of annual rate of p*(1/n)*c

example 1:
annual rate = 0.06
term = 30 years
closing until 30 years

t = 0.06*30 = 1.8
s = 0.06*30 = 1.8
c = 1.8 *(exp(1.8)-1)/(exp(1.8)-exp(1.8-1.8)-1.8) = 2.797
suppose paid point is 0.01 (1 point)
then the effective annual rate of this mortgage is
0.06 + 0.01 * (1/30) * 2.797 = 0.06093 = 6.093%

example 2:
Everything same as example 1 except that
closing afte 10 years
s = 0.06*10 = 0.6
c = 1.8 *(exp(1.8)-1)/(exp(1.8)-exp(1.8-0.6)-0.6) = 4.268
then the effective annual rate of this mortgage is
0.06 + 0.01 * (1/30) * 4.268 = 0.06142 = 6.142%

example 3:
Everything same as example 1 except that
closing afte 5 years
s = 0.06*5 = 0.3
c = 1.8 *(exp(1.8)-1)/(exp(1.8)-exp(1.8-0.3)-0.3) = 7.169
then the effective annual rate of this mortgage is
0.06 + 0.01 * (1/30) * 7.169 = 0.06239 = 6.239%

Wednesday, April 12, 2006

Time zone in Java

PST is same as GMT-08:00
PDT is same as GMT-07:00

EST is same as GMT-05:00
EDT is same as GMT-04:00

This mean that for example,
20060412 13:00:00 PST is one hour later than 20060412 13:00:00 PDT


These time zone string can be parsed by java.util.SimpleDataFormat class

Monday, April 10, 2006

Cookie file format of Internet explorer

Cookies are at C:\Documents and Settings\[user name]\Cookies

Cookie name
Cookie value
Host/path for the web server setting the cookie
Flags
Exirpation time (low)
Expiration time (high)
Creation time (low)
Creation time (high)
Record delimiter (*)

Conversion of the time to the number of seconds
elapsed since midnight (00:00:00), January 1, 1970,

t = 1e-7*(high*pow(2,32)+low) - 11644473600



Reference:
Galleta - An Internet Explorer Cookie Analysis Tool

Tuesday, January 24, 2006

Using image in LaTex

Convert the image file to jpeg format.
Use jpeg2ps to convert it to eps file.
Then it can be easily used in LaTex

Thursday, November 17, 2005

Tax for mutual fund

Some special rules:
1. To qualify for the qualified dividend (taxed at same rate as long term captical gain), the fund must be held for at least 61 days.
2. Upon selling of a fund held not more than 6 months, part of short term capital loss (if there's any) must be treated as long term captital loss to the limit of long term captital gain distributions.


A good guide is at
http://fairmark.com/mutual/

At the same site, tax information for other investment can also be found.

Tuesday, November 15, 2005

Notes on Yahoo finance historical prices

The adj close is the actual close multiplied by split multiplier and dividend multiplier
See following page for explanation.
http://help.yahoo.com/help/us/fin/quote/quote-12.html

IMPORTANT NOTE: Historical dividend is also adjusted by split multiplier and dividend multiplier

CSV file for historical price can be retrieved by (SPY as example)
http://ichart.finance.yahoo.com/table.csv?s=SPY

HTML page for historical price
http://finance.yahoo.com/q/hp?s=SPY

Wednesday, November 02, 2005

Can people short in an IRA account?

The answer is NO.
Reason (adapt from http://invest-faq.com/articles/ret-plan-trad-ira.html)
The restriction comes from the combination of the following three facts. First, the law governing IRAs says that if any part of an IRA is used as collateral, the entire IRA is considered distributed and thus subject to income tax and penalties. Second, the rules imposed by the Federal Reserve Board et al. say that short sales have to take place in a margin account. Third and finally, margin accounts require that you pledge the account as collateral. So if you try to turn an IRA into a margin account, you'll void the IRA; but without a margin account, you can't sell short.

Monday, October 31, 2005

How to get information about land

Find the website for county assessor's office. Then look for what you need.
For Santa Clara county, it's at http://www.sccgov.org/ari

How to find information about a person, address, or phone number

The following website is exellent:
http://www.reversephonedirectory.com/

Monday, October 24, 2005

Verizon DSL conflicts with NetBeans javadoc help

Cause : Motive SmartBridge (installed with Verizon support center) take over ALT-F1 globally.
Solution : uninstall Verizon support center.

See following page about Motive SmartBridge
http://www.intelliot.com/blog/archives/2004/06/05/motive-smartbridge/

Thursday, October 06, 2005

FILE privilege for mysql

FILE privilege can only be granted globally (using ON *.* syntax).
Same for the following privileges
PROCESS, RELOAD, REPLICATION CLIENT, REPLICATION SLAVE, SHOW DATABASES, SHUTDOWN, and SUPER privileges

Viewing Javadoc in Eclipse

Eclipse IDE Javadoc Configuration Tutorial

Tuesday, October 04, 2005

Tax for employee stock option

There are several types of stock incentive
1. Incentive stock option
2. Restricted stock
A good article about incentive stock option http://www.fairmark.com/execcomp/iso.htm
For restricted stock, see http://www.rowbotham.com/stock_options/restricted_stock.htm

Key points
For incentive stock option,
1. No tax until exersize. No tax for receiving, vesting ISO.
2. When exercize, no REGULAR tax. There is tax for AMT, difference between market price and exercise price recognized as ordinary income
3. When sell, if qualifying for special holding requirement (>1 years after exercize, >2 years after receiving ISO), For REGULAR tax, taxed as capital gain with exercize price as tax basis. For AMT, taxed as capital gain with market price when exercising as tax basis.
4. When sell, if qualified as Qualified Small Business Stock, half the gain recognized as capital gain for REGULAR tax. 7% of the excluded gain need to be reported for AMT.

---

Instruction for AMT, for 6251

Line 12 - Qualified Small Business Stock
If you claimed the exclusion under section 1202 for gain on qualified small business stock held more than 5 years, multiply the excluded gain (as shown on Schedule D (Form 1040)) by 7% (.07). Enter the result on line 12 as a positive amount.

Line 13 - Exercise of Incentive Stock Options
For the regular tax, no income is recognized when an incentive stock option (ISO), as defined in section 422(b), is exercised. However, this rule does not apply for the AMT. Instead, you generally must include on line 13 the excess, if any, of:
1. The fair market value of the stock acquired through exercise of the option (determined without regard to any lapse restriction) when your rights in the acquired stock first become transferable or when these rights are no longer subject to a substantial risk of forfeiture, over
2. The amount you paid for the stock including any amount you paid for the ISO used to acquire the stock.
Note. Even if your rights in the stock are not transferable and are subject to a substantial risk of forfeiture, you may elect to include in AMT incomethe excess of the stock's fair market value (determineed without regard to any lapse restriction) over the exercise price upon the transfer to you of the stock acquired through exercise of the option. You must make the election by the 30th day after the date of the transfer. See Pub. 525, Taxable and Nontaxable Income, for more details.
If you acquired stock by exercising an ISO and you disposed of that stock in the same year, the tax treatment under the regular tax and the AMT is the same, and no adjustment is required.
Increase your AMT basis in any stock axquired through the exercise of an ISO by the amount of the adjustment. Keep adequate records for both the AMT and regular tax so that you may figure your adjustment. Seethe instructions for 16.


Topic 427 - Stock Options http://www.irs.gov/taxtopics/tc427.html

URL Redirection

Simple way to do page redirection is
<html>
<head>
<meta http-equiv="refresh" content="5; URL=http://my_new_web_address">
</head>
</html>

But user will notice the transition page

For more complicated see a good article about this is at HOWTO: Common URL Redirection Techniques for IIS, Summary

One of ways mention in the article is to use 302 redirect response. See for example:
Working with 301 and 302 Redirects
302 Redirect

Friday, September 30, 2005

Employee Invention

CALIFORNIA LABOR CODE (http://www.leginfo.ca.gov/.html/lab_table_of_contents.html)
DIVISION 3 Article 3.5

2870. (a) Any provision in an employment agreement which provides
that an employee shall assign, or offer to assign, any of his or her
rights in an invention to his or her employer shall not apply to an
invention that the employee developed entirely on his or her own time
without using the employer's equipment, supplies, facilities, or
trade secret information except for those inventions that either:
(1) Relate at the time of conception or reduction to practice of
the invention to the employer's business, or actual or demonstrably
anticipated research or development of the employer; or
(2) Result from any work performed by the employee for the
employer.
(b) To the extent a provision in an employment agreement purports
to require an employee to assign an invention otherwise excluded from
being required to be assigned under subdivision (a), the provision
is against the public policy of this state and is unenforceable.



2871. No employer shall require a provision made void and
unenforceable by Section 2870 as a condition of employment or
continued employment. Nothing in this article shall be construed to
forbid or restrict the right of an employer to provide in contracts
of employment for disclosure, provided that any such disclosures be
received in confidence, of all of the employee's inventions made
solely or jointly with others during the term of his or her
employment, a review process by the employer to determine such issues
as may arise, and for full title to certain patents and inventions
to be in the United States, as required by contracts between the
employer and the United States or any of its agencies.



2872. If an employment agreement entered into after January 1,
1980, contains a provision requiring the employee to assign or offer
to assign any of his or her rights in any invention to his or her
employer, the employer must also, at the time the agreement is made,
provide a written notification to the employee that the agreement
does not apply to an invention which qualifies fully under the
provisions of Section 2870. In any suit or action arising
thereunder, the burden of proof shall be on the employee claiming the
benefits of its provisions.

Avoiding Legal Problems with Employees In California

Monday, September 05, 2005

Configure JDBC datasource for Tomcat 5.5.*

1. Do not modify server.xml.
2. Copy JDBC driver, dbcp and collections jars to common/lib.
3. Add the following to your web.xml in your application:


<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4" xsi="http://www.w3.org/2001/XMLSchema-instance" schemalocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >

<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/dbTest</RES-REF-NAME>
<res-type>javax.sql.DataSource</RES-TYPE>
<res-auth>Container</RES-AUTH>
</RESOURCE-REF>
</WEB-APP>

4. Create new context.xml under META-INF and paste the following:

<context reloadable="true" path="/dbtest" debug="5" crosscontext="true" docbase="dbtest">
<logger timestamp="true" suffix=".txt" prefix="localhost_realtorApp_log." classname="org.apache.catalina.logger.FileLogger">
<resource username="joe" password="XXXX" url="jdbc:mysql://localhost:3306/javatest?autoReconnect=true" type="javax.sql.DataSource" auth="Container" name="jdbc/dbTest" driverclassname="com.mysql.jdbc.Driver" maxwait="5000" maxactive="4" maxidle="2">
</context>

Sunday, August 07, 2005

How to keep the LaTex compilation window open in WinEdt

At Menu -> Options -> Execution Modes, Click 'BATCH' Button

or

Menu -> Options -> Configuration Wizard -> Start -> Tex Configuration Wizard -> 'BATCH Execution Mode'

Thursday, August 04, 2005

Extract wav from wmv using Windows Media Format SDK

Modify the AudioPlayer example in the Media Format SDK 9.
There are several things needed to be done:
1. Call IWMReaderAdvanced::SetUserProvidedClock(TRUE) so that the program can use IWMReaderAdvanced::DeliverTime to request the reader to process the stream as fast as possible (ignore actual time)
2. Call IWMReaderAdvanced::DeliverTime in OnTime call back to request the reader process more data
3. Select the audio stream. Get IWMProfile interface by QueryInterface on IWMReader interface. Get the number of streams by IWMProfile::GetStreamCount. Get config (IWMStreamConfig) of each stream by IWMProfile::GetStream. Get the stream type by IWMStreamConfig::GetStreamType. Look for stream with type WMMEDIATYPE_Audio. Get stream number using IWMStreamConfig::GetStreamNumber. Use IWMReaderAdvanced::SetManualStreamsSelection(TRUE) to enable manual stream selection. Use IWMReaderAdvanced::SetStreamsSelected to select the audio stream.
4. Modify OnSample function to write the wav samples to a file.
5. Remove unnecessary part of the program

Note: AudioPlayer sample use asynchronous reader (IWMReader). It might be easier to use the synchronous reader (IWMSyncReader) obtained by WMCreateSyncReader.

Wednesday, July 20, 2005

Adding JDK Javadoc to NetBeans IDE

Download JDK documentation from http://java.sun.com/j2se/1.5.0/download.jsp
Unzip the zip file to the JDK directory
In NetBeans IDE
1. Choose Tools > Java Platform Manager from the main window.
2. Select the platform to which you want to add Javadoc in the left panel of the dialog box.
3. In the Javadoc tab, click Add ZIP/Folder and specify the location of the Javadoc files.
4. Click Close.

Adding CLASSPATH in NetBeans

In the Projects window, right-click the project node and choose Properties.
Click Libraries in the left panel of the Project Properties dialog box.
Adding library path in the right panel.

Wednesday, July 13, 2005

Setup Tomcat with Apache

Requires following steps
1. install JDK ,
j2se 5.0 http://java.sun.com/j2se/1.5.0/index.jsp

2. install Apache http server
Apache 2.0 http://httpd.apache.org/download.cgi

3. install Tomcat
Tomcat 5.x http://jakarta.apache.org/tomcat/index.html
Be sure to use j2se 5.0 for Tomcat 5. Otherwise a compatibility package needs to be installed.
Without compatibility package, tomcat 5 will not run with earlier version of j2se.

Compatibility package:
http://ftp.wayne.edu/apache/jakarta/tomcat-5/v5.5.9/bin/jakarta-tomcat-5.5.9-compat.zip
unzip it can copy to Tomcat directory

After installation, if everything is right, following pages can be viewed:
http://localhost:8080/
http://localhost:8080/jsp-examples/

4. install a connector, in this case JK
http://jakarta.apache.org/site/downloads/downloads_tomcat-connectors.cgi
copy mod_jk-1.2.14-apache-2.0.54.so to the ${apache_home}/modules, rename it to mod_jk.so.

5. configure and test

Add following line to ${tomcat_home}/conf/server.xml, in the <Engine> section,
<Listener className="org.apache.jk.config.ApacheConfig" modjk="C:/Program Files/Apache Group/Apache2/modules/mod_jk.so" />

Create a file ${tomcat_home}/conf/jk/workers.properties
worker.list=ajp13
worker.ajp13.port=8009
worker.ajp13.host=localhost
worker.ajp13.type=ajp13

Add a line to the end of ${apache_home}/conf/httpd.conf
Include "C:/Program Files/Apache Software Foundation/Tomcat 5.5/conf/auto/mod_jk.conf"

Reference:
Using Apache HTTP with Apache Tomcat(http://johnturner.com/howto/apache-tomcat-howto.html)

Server Configuration Reference
http://jakarta.apache.org/tomcat/tomcat-5.5-doc/config/index.html

For application deployment (Application directory structure setup)
http://jakarta.apache.org/tomcat/tomcat-5.5-doc/config/host.html#Automatic%20Application%20Deployment

Jakarta Tomcat Connector - Apache HowTo
http://jakarta.apache.org/tomcat/connectors-doc/howto/apache.html

Jakarta Tomcat Connector - Workers HowTo
http://jakarta.apache.org/tomcat/connectors-doc/howto/workers.html

Wednesday, May 18, 2005

USB-400 Wireless Adapter

I finally get my USB Wireless Adapter working properly without the original installation disk and documentation.

The adapter has a model name USB-400. There is no manufacturer name.
Finally, I found the manual, driver & utility can be download from
http://www.syntaxgroups.com/support/downloads.php

Wednesday, April 06, 2005

Install TAO

Prerequirement:
PETSC must be installed

edit : include/tao_sys.h
search for the line: extern int PetscLogInfo(void *,const char*,...);
change to: extern int PetscLogInfo(void *,const char[],...);
This is because the prototype in tao_sys.h is different from that in
petsclog.h of PETSC

Run the following commands

export TAO_DIR=`pwd`
export BOPT=O_c++
export PETSC_ARCH=cygwin-intel
make all
make tao_testexamples >& examples.log

check for errors in examples.log

Install PETSC on Intel Microsoft Windows 2000

This note describes how to install PETSC on a machine with following specs:

CPU: Pentium 4
OS: Windows 2000
Compiler : Intel Compiler
Math : Intel MKL
MPI : MPICH
Shell: cygwin

Prerequirement:
install MKL: MKL should be in C:\Program Files\intel, with directory name MKL70, MKL61 or MKL, make sure ia32/mkl_c_dll.lib should be the only one library needed
install MPICH: MPICH should be in C:\Program Files\MPICH

edit :

search in *.py for 'C:\Program' and 'cygdrive', change drive letter for your pre-installed software

edit : ${PETSC_DIR}/makefile
search for the FIRST "MINFO_", change MINFO_ to ${MINFO}
remove the next few lines until line: -@$(RM) MINFO MINFO_
change this line to: -@$(RM) MINFO
This is because unknown problem with sed

environment:
adding the MKL DLL directorty to PATH
before entering cygwin, run vcvars32 first to set the environment

entering cygwin
go to root of PETSC
run following commands:
PETSC_DIR=`pwd`; export PETSC_DIR
config/configure.py --with-fc=0 -with-vendor-compilers=intel
make BOPT=O_c++ all
make BOPT=O_c++ test
NOTE: configure.py will use flag -TP for compiling both .c and .cpp files.

If everything is right, configure.py should automatically locate pre-installed
MKL and MPICH. The end of ${PETSC_DIR}/configure.log should look like
following:


Compilers:
C Compiler: /cygdrive/c/users/xw/work/petsc-2.2.1/bin/win32fe/win32fe icl --nodetect -MT
C++ Compiler: /cygdrive/c/users/xw/work/petsc-2.2.1/bin/win32fe/win32fe icl --nodetect -MT -GX -GR -TP
PETSc:
**
** Configure has determined that your PETSC_ARCH must be specified as:
** ** PETSC_ARCH: cygwin-intel
**
**
** Configure has determined that your PETSC_DIR must be specified as:
** ** PETSC_DIR: /cygdrive/c/users/xw/work/petsc-2.2.1
**
** Please make the above changes to your environment or on the command line for make.
**
BLAS/LAPACK: /cygdrive/c/Program\ Files/Intel/MKL70/ia32/lib/mkl_c_dll.lib
MPI:
Type: Default MPICH install location (C:\Program Files\MPICH with MS compatible SDK
Version: 1.2
Includes: ['/cygdrive/c/Program\\ Files/MPICH/SDK/include']
Library: ['/cygdrive/c/Program\\ Files/MPICH/SDK/lib/mpich.lib', 'ws2_32.lib']
Python Configure Actions
These are the actions performed by configure on the filesystem
-----------------------------------------------------------------
PETSc:
Build : Set default architecture to cygwin-intel in bmake/variables
Build : Set default optimization to g in bmake/common/bopt_
File creation : Generated list of jobs for testing in bmake/cygwin-intel/jobs
File creation : Generated list of jobs for testing in bmake/cygwin-intel/ejobs
File creation : Generated list of jobs for testing in bmake/cygwin-intel/rjobs
File creation : Created bmake/cygwin-intel/configure.py for automatic reconfiguration
Framework:
Substitution : bmake/config/rules.in was substituted to produce bmake/cygwin-intel/rules
Substitution : bmake/config/packages.in was substituted to produce bmake/cygwin-intel/packages
Substitution : bmake/config/variables.in was substituted to produce bmake/cygwin-intel/variables
File creation : Created configure header bmake/cygwin-intel/petscconf.h
File creation : Created C specific configure header bmake/cygwin-intel/petscfix.h

How to show tootips of a toolbar in a dialog window?

It is easy to add a toolbar to a dialog window. However, it takes some effort to make the tooltips of the toolbar to work. Here are the steps needed to be taken.

1. Add the following line to the message map in the header file of the dialog box

afx_msg BOOL OnToolTipText(UINT nID, NMHDR* pNMHDR, LRESULT* pResult);

2. Add the following line to the cpp file of the dialog box

ON_NOTIFY_EX(TTN_NEEDTEXT, 0, OnToolTipText )

3. Add following line to InitDialog()

EnableTooltips();

4. Add the following function


BOOL CConfBrowser_MFCDlg::OnToolTipText(UINT, NMHDR* pNMHDR, LRESULT* pResult)
{
TOOLTIPTEXT *pTTT = (TOOLTIPTEXT *)pNMHDR;
UINT nID =pNMHDR->idFrom;
if (pTTT->uFlags & TTF_IDISHWND)
{
// idFrom is actually the HWND of the tool
nID = ::GetDlgCtrlID((HWND)nID);
}
if (nID)
{
pTTT->lpszText = MAKEINTRESOURCE(nID);
pTTT->hinst = AfxGetResourceHandle();
return(TRUE);
}
return(FALSE);
}