Investing
Thursday, January 28, 2016
Sunday, December 30, 2012
DI idioms
- Interface injection—This involves exposing role interfaces that are effectively setter methods in their own interface. It has the advantage of being explicit just like setters, and it can be given meaningful names. However, interface injection is extremely verbose and requires several single-use interfaces to be created for the sole purpose of wiring. It is also not supported by many DI libraries.
- Method decoration—This involves intercepting a method call and returning an injector-provided value instead. In other words, method decoration turns an ordinary method into a Factory method, but importantly, an injector-backed Factory method. This is useful in some rare cases, but it is difficult to test without an injector and so should be carefully weighed first.
- Other idioms—Field injection is a useful utility, where fields are set directly using reflection. This makes for compact classes and is good in tutorial code where space is at a premium. However, it is nearly impossible to test (or replace with mocks) and so should be avoided in production code. Object enhancement is a neat idea that removes the injector from the picture altogether, instead enhancing objects via source code or otherwise leaving them to inject themselves. This is different from Factories or Service Location because it does not pollute source code at development time. There are very few such solutions in practice.
Few thoughts about DI
Thursday, April 09, 2009
Regular Expressions
[a-z3-7] -> small alpha or a number between 3 and 7
a*b -> b, ab, aab
a?b -> b, ab
a+b -> ab, aab
^a$b -> line starting with letter a and ending with letter b
[^a-f] -> except for a to f
ab. > ab followed by any character except for new line
35\{4\} -> 35555
re(ab)d -> read, rebd
\
a\$ => a$
a$ => line ending with a
[:upper:] [:lower:] [:alpha:] [:print:] [:digit:] [:cntrl:][:blank:][:space:][:xdigit:]
Bash
1. File operations
if [ -e "filename" ]; : -> exists
r -> readable, w -> writable, h -> link, -x executable,
PROGRAM_NAME= $0
basename = `basename $PROGRAM_NAME`
Appending to a file:
cat "At the end" >> $filename
Prepending to a file:
cat "At the beginning" > $tempfile
cat $filename >> $tempfile
cat $tempfile > $filename
for file in `ls $PWD`
do
echo $file
done
if [ ! -f "/var/opt/myfile.txt" ]; then
mkdir -p "/var/opt"
cat $content >> /var/opt/myfile.txt
fi
2. String operations
if [ -n "$var" ]; to check whether var is null
if [ -z "$var" ]; to check whether var is empty
if [ -z "$var" ]; then
:
else
echo ok var is not null
fi
3. Arithmetic expressions
(( a=$a+1 ))
(( ++$a ))
a=`$a + 1`
count=0
while [ $count <>
do
echo "Type your name 10 times"
done
4. Logical operations
if [ ! $a ]
if [ $a -ne 0 ]
if [ $a -gt 20 ]
if [ $a -a $b ]
if [ $a -o $b ]
[ -z "$a" ] && exit 0
4. functions:
exit 0 is success, non-zero exit is failure
status is checked by $?
if [ $? = 0 ] -> success
Call by value mechanism (Use \ for referencing )
arguments count $#
arguments: $@ or $*
shift operator
while
5. Execution modes of shell scripts
set -x ... set +x will enable tracing
sh -x script.sh
set -o errexit
set -e -> Froces shell to quit if a command fails. With out, a program has to be written this way
command
if [ $? <> 0 ]; then
echo blah blah command failed
exit 1
fi
with set -e, the result checking is automatically enforced. The script exits when the command fails
set -e
....
comand
But some commands may be interspersed with important commands, that we really donot care of.
In such cases, automatic exit under set -e can be escaped by using the idiom
dontcarecommand true
dontcarecommand { echo command failed! ; exit 1 }
Or if a block of code node needs to be ignored
set +e
block of code
set -e
Some commands inherently possess this option. When executed under -e mode, the -f option of rm will remian silent if the file does not exist.
set -u :-> enforces the program to exit when an undeclared variable is encountered in the script
set -u; rmdir $TMP/etc/hosts -> Will exit if $TMP is not declared
5. Regular Expressions
6. Some sed commands:
7. Some awk commands
id -nu -> username
[ $UID = 0 ] -> root
$$ -> current process id
tr '[:lower:]' '[:upper:]' -> lowerToUpper
IFS -> Internal Field Separator (defaults to space)
set $IFS=':'
read -t 4 name; SECONDS -> number of seconds passed
$LINENO -> Line number with in the script, usefule for debug statements
echo $FUNCNAME -> current function name
SHLVL->Shell Level
function f()
{
local k
while [ $# -ne 0 ];
do
k=$1$k
shift
done
return $k
}
while read line
do
echo eval f $line
done
Development Tools
Open VPN, Poderosa, password less ssh, ultra vnc, nomachine's nxclient, VSphere, SQLTools, WinSCP, nmap, chatzilla, nav tool
Saturday, February 03, 2007
Through the eyes of an analyst
Behind Organizational Management Efficiency:
Every quarter or year, periodically we see that these amounts keep changing.
1) Assets can increase. This results in expenditure. Assets bought will decrease net profits and assets sold could add to net profits. If there are any captial gains or captial losses on the assets sold they should be filed/claimed in taxes.
2) Debt: A company may borrow money or reduce the debt. This change in amount of outstanding debt results in changes in interest amount paid hence reflecting changes in net income.
3) Equity: A = E + L. Assets by itslef does not reflect the wealth of the company. Equity removes liaility from asset to give the true worth. A company can increase equity by reducing debt or by increasing assets. A company should strive to increase the net equity. A company when goes to raise the additional money via shares, then it is diluting the equity. If the raised money is used to reduce the debt, then the equity is increased. Companies can benefit from this from time to time during high interest periods. They can reduce the interest paid amount.
How depreciation helps for a company:
1) tax incentive
2) Most important: Depreciation reduces equity in the book. And at the same time company can defer tax, and use it for expenses. Now assuming that there is no real depreciation for the asset, a company can give a perception that the return on equity is more even though it is not.
3) Company can show increase in net income through this tax deferral. At first look it might sound correct. But it will catch the analysts eye. They will remove this tax deferral amount, to calculate the net income. If the net income does benefit from tax deferral only, then the stock will be down graded.
Most companies can choose to charge high depreciation in early years and reduce it during subsequent years. They deduct this depreciation amount from earned income, to publish net income. The trick here is that by deducting higher depreciation in the beginning and reducing depreciation amounts later on, the company can show improved net earnings,save tax money. This may skew investors perceptions if he looks only for net earnings. More problems when the depreciation amount deducted reduces significantly, because investors feel happy that there is nothing more depreciating and it may also give a feeling that the returns on equity are more during later years.
What would a company do with the earnings, borrowed money or raised income ?
The efficiency of the management of a company lies with what they do with the profits.
A company can do any of the following things in case it thinks it can expand:
a) Invest in cutting edge technology to remain competetive. This does not necessarily improve margins. Atleast management do not foresee that.
b) Invest in better technologies to increase productivity and improve margins.
c) Become a minority iinterest holder in some other company.
d) Buy a company to diversify the business and hedge against unfavorable economic and tax legislations.
e) Buy a competitor (Merger, consolidation, acquisitions) to improve the market share. HP and Compaq marriage.
f) Buy a complementary product manufacturer to become a turn key solution provider. Eg: Cisco bought Scientific Atlanta to enhance the suite of Triple Play products. Arris Networks bought Tandem TV to compete against Cisco.
g) Increase revenues by advertising.
h) Attract and retain highly talented people.
i) Settle litigations. This will improve the company's focus on current operations than on past litigations.
j) Invest in R&D or buy patents or pay royalties.
k) Clear short term, higher interest debt.
For a growing company, it can invest the profits. If additional money is required then it can raise it by
k) by issuing secondary shares.
l) by issuing bonds.
m) by raising short term debt. The short term debt will be cleared with the subsequent profits.
If a company thinks that it cannot better the share holders value or if it considers that growth is significantly achieved with reducing progress, it can do the following:
a) Reduce the outstanding number of shares floated. This increases the per share equity of a share, and hence per share earnings, finally increasing the share price.
b) Reduce the outstanding debt, in a growing economy to reduce the interest expenses.
c) Giving a dividend.
Understanding Earnings and Interpreting Management efficacy:
Gross Margins: Gross Margins are calculated by removing cost of production from total sales. This cost of production is often skewed because, it only calculates direct costs. It does not account indirect costs, such as operating expenses which include Administration costs required to run the business such as compensation to CEO, President, marketing and advertising expenses. If a company has many cost centers then the administration expenses to organize these cost centers is not accounted in Costs.
Gross margins are nevertheless useful in comparing apples to apples, that is companies with in the same domain. A company with better gross margins generally means that it has an edge over its competitors.
Operating margins: Operating margins include both direct and indirect costs. This reflect the true value of a business for an investor. It shows how much an enterprise is able to generate. One quick look at comparing gross to operating margins can show whether the administration is very expensive... If gross margins are high but operating margins are less, it would mean little value for the investor. It could either mean that operating costs are too high or administration at higher levels are excessively paid (CEO compensations).
Gross Margins and Operating margins show the competetiveness of a business. Different industries will have different operating and gross margin ratios. For software companies gross margins will be high (70 %), but operating margins will not be that high (30%). There is significant difference between gross margins and operating margins. This reflects that it costs more to market and sale the product than it costs to manufacture the product. For an airline industry gross margins will be less (5%), because the cost for airlines (renting fleet, crew wages, fuel expenses, ticketing costs), but difference between gross margins and operating margins will be less, unless CEO's are paid hefty pay checks (American Airlines).
A company can improve operating margins by reducing compensations and hence decreasing operational expenses at higher executive positions. A nice example is Cisco during 2001 down turn. The company slashed executive compensations by 10% and company made economy travel as business policy by going frugal. This resulted in better operating margins and also corresponding increase in gross margins. This helped Cisco to remain competitive during the dot com bubble burst.
Gross Margins and Operating margins show the competetiveness of a business. What they do not show is the underlying health of a business by it self. Because they are not accounting: Interest from short term debt and Interest from Long term debt, Taxes, Depreciation. To get a true picture of a business as itself rather than in comparison to its peers, other expenses such as interest expenses, depreciation and taxes need to be looked at.
Companies have to reinvest the earnings to remain competetive. This expenditure could be either in the form of increasing assets or by increased advertising. Advertising may result in increased revenues and could correspondingly increase net income if advertising expenditures are lesser than increased gain in net income. On the other hand if a company tries to increase productivity by investing in cutting edge technology, it may improve on increasing gross margins. This improvement in gross margin can trickle down to operating margins if there is no significant increase in wages/compensation/advertising, Or if the ratio of increase in wages is lesser compared to increase in sales.
When an economy is booming it can result in increased sales. If this increase in gross margins is negated by increase in operating margins, by the way of increased expenditure on wages and compensation then it is not good for the future business. In a downward economy gross margins will come under pressure as more and more consumers will be cutting down on their expenses. But operating margins are not directly dependent on economy, but they are either inherent to the business or show operational inefficiency of the business. So, in a downward economy net margins will suffer.
If taxes are high then it means that a business is operating in a higher taxing areas of the world and business areas. So, when comparing business with in same sector, it is better to look for a business that is having lesser taxes, as in a long run that business can save more... Or if taxes are significant portion of the net income, then it could mean that the health of the business unit is dependent upon the tax rate, which can change... If the current taxing is the highest, then the only direction is for ease of tax rates, which could mean that the business could be more efficient in future. But if current taxing is to encourage businesses, by temporary reduction of taxes. then when the taxes are restored then the business may not sustain these profits...
Taxes should be compared with net profits.. If they are insignificant, then well and good. But if they are significant, then check whether the reported taxes have any temporary tax benefits. If there are, then the business may not sustain the profits when the taxes are restored... If a company is exposed to higher taxing states like CA then their net profits will not be good even though their EBITDA margins, Operating margins and Gross margins are good.
Debt: A company can secure long term debt by issuing senior notes, bonds, by issuing secondary shares etc.. and Short term debt from financial institutions or money lenders. The interest expenses on short term debt are higher, but they can be cleared in a short term from the profits.... if there are any. If the company cannot reduce its short term debt, then it may go for longer term debt. A company may seek long term lending to eliminate short term finances... example: Sun Microsystems recently borrowed money from KPR.. And some companies will issue additional company shares to raise the money for clearing debt both long term and short term. This is not actually reducing the existing share holders equity, as it might look though at the first instance. That debt is already part of the existing share holders equity.
In general, a company which has a significant debt, is not attractive. Unless they earn a lot more money on money borrowed, i.e., if the return on money borrowed is significant to the interest paid. It is important to see how it is using the earnings. Are they investing profits earned to result in increased equity, and further increasing share holders equity. Then if it is so, over a period of time, the companies equity should be more than the debt. If the debt to equity ratio is decreasing at a good rate that means the company is doing good, but if it is increasing, (if it increases or does not improve consistently, then it shows that there are periods where the borrowed money is more expensive than the returns on that money... not good. Because, if it decreases in one quarter, it effectively erases gains from the earlier quarter.)
The more the debt, the more are interest expenses in comparision to gross profits. When the economy is sinking, fed will lower the interest rate to boost the economy and increasing money flow by making money look very attractive to borrow. During these low interest rate periods these companies can do better. But when the economy is good, fed will obviously hike the interest rates to reduce the inflation, Then these companies net profits will suffer. The axiom is that the interest will never remain steady. They need to be tuned to keep economy afloat. For more information on why should fed tinker with interest rate, please google and get a grasp on concepts of increasing inflation, decreasing inflation, deflation, unemployment rate, cpi, cci fed rate cut/hike, manufacturing index, retail sales index etc.
The other two margins of interest are Net Margins and EBITDA margins(Earnings before interest, tax, depreciation and amortization) . Net earnings are also called GAAP (Generally agreed accounting principles) earnings. All analysts will be concerned more about EBITDA margins as they are less skewed and do not benefit from interest rates, tax rates and tax deferrals.
Assessing growth and core competency:
A company can compete in several different areas. But there will be core competency areas that a company is graded against. For example Apple computers, competes in both computers (PC, laptop) and also consumer goods (iPod, iPhone, iTv...). But investor would like Apple to compete in the Computers area more than the consumer goods. Investors are happy that a company is doing well in other areas, but what finally counts is its competency in its core competency. If apple cannot increase its penetration from 1% of the existing computers towards 100%, then its vast revenue potential will be at stake. Because, the amount of revenues that can be earned in computers area are much more multiples than the consumer products. These other non core competency areas have less barrier for existing and new competitors. This is precisely the reason why Apple was downgraded after its blowout revenues in Jan 2007. The strategy for Apple should be to reduce margins on its computers a little or become efficient in reducing manufacturing costs and compete against others such as Microsoft in Personal computers area.
Assessing a fair stock value:
This is where the main problem with a stock. In evaluating a price of a stock, the historical net income growth of a company need to be considered. Unlike a traditional fixed CD, earnings for a company keep growing at a compounded rate. So one dollar in earning now could result in 3 dollar in earnings at the end of 10 years. Or the company could be no longer in existence. If the interest rates are attractive then fixed CD's will be attractive. So, stocks are attractive to enter into when interest rates are higher as more and more money will get into banks. When the interest rates are low, stocks look more attractive and their prices will be high.
The best way to earn money through stocks is to buy low sell high. Every novice investor will do a mistake of being attracted to a blown up stock. The stock looks very attractive as does a blown balloon. It looks irresistable. But the inevitable thing is for a stock price correction. An experienced investor will look for a dip in stock price to get into a company's stock.
To understand what a fair value for a stock, look at Market cap for a company. It is the total of number of shares floating and price of the share. See the net income for the Trailing Tweleve Months (TTM). If you divide the Net Income with Market Cap, we get the amount of earnings per dollar invested. This is not where it ends. We should consider the growth of the company. Let us say for last three years the annual compounded growth rate is 30 %. This could statistically suggest that for next three years this enterprise could sustain that growth rate (when coming to such conclusions we should check gross margins and see whether the enterprise is a monopoly)
Market cap of Apple Inc is 76 B. The net income for the Trailing Tweleve Months (TTM) is 2.2 B. That means that for every 76 dollars of investors amount the return is 2 dollars. It is approximately 2.89 % return. But if the company sustains that growth for next 10 years at a compounded rate of 30% then the returns on 100 $ invested 10 years later would be 2.89 * (1.3 to the power of 10). I guess it must be $24. So $100 invested now would return $24 at the end of 10 years. So thats the reason why stocks trade a higher premium than their current returns, because markets will pay the corresponding premium to enter the stock.
This return of $2.8 per $100 looks attractive when interest rates are low. But in a booming economy this rate would not interest investor as bonds and cd's will be attractive. So, an average joe like you and me should buy stocks when interest rates are high and wait for interest rates to come down significantly. Its just that simple.
We will take a hypothetical examples of growth rates for Apple Inc, and analyze the future possbile price of Apple next.......
Wednesday, April 05, 2006
Thursday, March 10, 2005
Java Security
Disallowing pointer arithmetic
Checking ArrayBounds at runtime
Verifying bytecodes during classloading.
Verifying bytecodes and access during first method call.
Access Control of packages.
Virtual Machine level: The notion is whether or not to allow/grant a code access/execute to JVM.
J2SE uses Java Policy based access control, policy file found in JAVA_HOME/lib/security or $HOME/.java.policy. For default applications there is no policy involved. But policy and the corresponding SecurityManager comes in picture for applets, classes downloaded from URL's. We can specify the policy in the policy file. This is a code based policy, meaning code downloaded from so and so location can execute or not. In summary, it controls 'WHAT' executes on the JVM.
Applets: Applets running in browsers are by default restricted to access only the host from which they are downloaded to avoid malicious applets trying to spy on ports inside a firewall or sending emails etc..
Applets(browsers) cannot access files on the users computer. Applets cannot read any system properties or can they start a new window. The dialogs from applets have a warning message saying that this is an applet, to save users from some spoofing login prompt dialogs
Signed Applets (CABS for IE) provide a way of releasing restrictions to an extent. They usually prompt the user for permission.
Application Level:
JAAS has 2 parts Authentication and authorization.
JAAS
Authentication: A subject can be either a single user or a group of users or a service.Principal is like a name and credential is like a password. Subjects have principals and credentials. Authenication involves autheticating subjects for a service by verifying provided credentials.
JAAS supports PAM (Pluggable Authentication Model). Authenication modules can be plugged transparently.
JAAS uses Java GSS-API for Single-SignOn. Java GSS-API uses Kerberos. Java-GSS uses Credentials as the cache for Kerberos TGT.
Concepts of interest: Principals, Subjects, Credentials, LoginContext, LoginModule.
Authorization: JAAS authorization is analogous to Java policy based access control, and extends the code based access control to include user based access control (controls WHO executes). Authorization is by default not enabled for applications. We can enable it by specifying on the command line during jvm startup to use the securityManager (-D java.security.Manager).Once enabled, the policy file needs to be edited to allow access to code, users for properties, resources (network, files).
Authentication:
LoginContext provides the abstraction from the underlying login modules for the application. LoginContext is the gateway for authentication. Login Modules can be specified in a configuration file and the name of the configuration file needs to be provided during the JVM start up (-Djava.security.auth.login.config==example.conf ).
LoginContext reads the login configuration and uses the specified login modules.
LoginModules are created with a CallBackHandler, that supports different callbacks. The callBack handler has a overloaded execute method that accepts array of different callback types, and we can handle the required callback type.
CallbackHandler fills the principal name, password etc in the correspondig callback object and returns. The login module uses those details to authenticate.
If all LoginModules successfully authenticate the Principal, the principal is added to the subject. and authentication is successful or authentication fails.
If authentication is succesful, then the subject can call the privileged action, an action that implements the privileged interface(basically should have a run() method) using doAs methods of Subject.
Message Digest: It is similar to CRC, a fixed size value computed from the message. This is used to ensure that message is arrived without tampering. But to avoid spoofing the message and message digest both, message digest can be encrypted(using the public key of sender).
Public key of the sender is known to the receiver, hence receiver can compute the message digest and encrypt using public key of sender and compare the encrypted message digests.
If the message needs to be encrypted as well, both message and encrypted message digest are encrypted using receivers public key, which will be decrypted at the receiver using receivers private key.
pk: public key, prk: private key, m:msg, md:message digest, s:sender, r:receiver
At sender:
- md1 = messageDigest(m);// compute Message digest
- e_md1 = pks(md1); // encryption step 1
- M = m+ e_md1; // Full message
- e_M = pkr(M): // encryption step 2
At receiver
- M = m + e_md1 = decrypt_prkr(e_M);
- md2 = messageDigest(m);
- e_md2 = pks(md2);
- e_md2 == e_md1
JSSE provides SSL and certificate store support. Use keytool to generate certificates. Use the same tool to import certificates into $JAVA_HOME/lib/secuirty/jssecerts . Certificate store contains certificates and trust store contains trusted certificates of clients. The name of a certificate can be referenced using an alias.
SSL Handshake involves Hello Protocol comprising of negotiating the cipher suites, and exchanging public keys etc...
A secure webserver request is forwarded to port 443. A resource configured in web.xml as "CONFIDENTIAL" will have to be requested using https. A http request for such a resource will be redirected to https. If the webserver cannot use port 443 and uses some other port then use iptables command on linux server to redirect requests on 443 port to the other actual port.
web server security.
Three web server security mechanisms: Basic, digest and HTTPS client authentication. Basic uses well known base 64 encoding; so no good. Digest is improvement over Base64. But not popular though. In a response to the protected resource request, web server sends, timestamp, url, etc and client uses MD5 to compute message digest. Anyway, in HTTPS client authentication web clients send their certificate when they connect the server, and server maintains client credentials till the connection is closed.
Servlet containers have to support 'Form based' authentication. This is similar to Basic, but allows a custom login page. To enhance security this can be combined with SSL.
J2EE security is based on roles and not users or groups. Users and groups can be configured outside either in database or standard xml file (server specific) and mapped to different roles.
Personalization of web pages can be achieved one possible way by checking roles using isUserInRole() method. Other than that both web server resources and ejb's should better be secured declaratively using web.xml and ejb deployment descriptors.
Wednesday, March 09, 2005
JMS Notes
- Only one receiver. Queues
- Needs acknowledgement. Messages will be persistent till the acknowledgement is received by the sender.
- Receiver can go down and come back up, and the message will still be there.
Publish/Subscriber:
- Can be any number of receivers 0*. Topics
- Needs no acknowledgement. Messages will be persistent till all subscribed 'active' receivers receive message.
- Only 'active' are receivers that are up will receive message. If non active receivers do need the messages too, then they can go for durable subscriptions.
TIPS:
- A non-j2ee jms client application can use transactions for jms messages. These transactions are not meant to be used for request-reply scenario, rather they can be used for a series of send requests or a series of receive requests on a session and for a combination of requests and replies on different sessions.
- A j2ee jms client application can use JTA or container managed transactions. For bean managed transaction, the messages are not redelivered when a transaction rollsback, whereas for container managed transaction messages are redelivered after a transaction rollback.
- Message Driven Bean (MDB), does not have a remote or home interface. It has a setMessage- DrivenContext method. MDB differs from a regular JMS client, in a sense that most of the code required to initiate the message queues/sessions is automated for MDB, via deployment declarations. A MDB has to implement MessageListener and MessageDrivenBean interfaces.
- If a SessionBean or Entity bean wish to be a client for the JMS, they should create the Connection resource in the ejbCreate() and release it in ejbRemove() methods. Create the Session in the business method, then close the resource in finally method. For stateful and entity beans close the sessions in ejbPassivate() and create them again in ejbActivate().
- A session bean or entity bean should not block on a receive call as it will affect the performance of the ejb container.
For performance reasons reliablity need be compromised. For applications where reliability is not a primary concern, and where it is affordable to loose some messages, like in performance data collection or statistics collection, it is advisable to use the following performance improvements:
- Use delivery mode to be NON_PERSISTENT. JMS Provider by default uses persistent mode so that messages will be delivered even in the case of failure of the JMS provider. This is acheived by saving the messages to a log file. By specifying non_persistent mode, this overhead can be eliminated, hence improving performance.
- Use time to live parameter that can specified either in MessageProducer interface or long form of pubish method to expire messages after certain interval. The default value of '0' implies messages will never expire.
- To have variable response times for messages with varying priorities, use priorities for messages.
- Set transaction attribute to "false" for sessions.