GUI-server communication — HFT (Piroz)

Mostly based on a veteran’s input…

Most GUI clients I have seen use some sort of messaging and you want that to be as asynchronous as possible.  There is no reason to keep the user waiting.  User clicks on something, the client sends a message to the server and the client is now waiting for a response.  When a response comes in (on a separate thread), the GUI takes it and displays whatever it needs.  Some people stick a unique request id in the message so when the response comes they can figure out to which request it belongs.

You also have subscription cases where you subscribe to prices for a security and the server will tell you listen to this channel for all updates.  That should be encapsulated in some sort of handshake.
RV, 29West and JMS are good choices.

Advertisements

MS iview – DB centric

Q: how do u speed up a stored proc?
%A: join order; index selection; avoid table scan; update stats

Now I think we should first establish performance target, by estimating minimum I/O required. (U can’t make a huge query run faster than a tiny query.) Then measure actual logical i/o. See the gap? Usually u can find clues in the execution plan. Improve the plan.

Q: How could a string object’s content be modified?
A (right): reflection to access the char array.

Q: how does a singleton become a 2-ton?
A: 2 class loaders, but i thought class loaders form a delegating hierarchy so no 2 loaders compete to load a class?
A (from interviewer): you can create a class loader outside the hierarchy. Indeed singletons are per-classloader.

Q:diff between clustered and non-clustered index
The answer I forgot to give: a column with lots of updates is no good as clustered index

Q: Users complain about a delay/slowness. we know it’s due to a Unix process. How do you investigate.
A: top; thrashing.

Q: What’s garbage collection?

Q: I have an object in a cache. it’s not referenced from anywhere outside the cache. After using it once, i don’t need it anymore. How do i get it garbage collected?
A: weakHashMap
A: just delete the entry from the cache

Q: lots of insert/delete/updates to a table. how do u keep track of all changes and by who? How do u ensure changes are always tracked?
A: %_hist table and milestoning

TYPE — different meanings in java vs c++

PRECISE meaning of Type differs between java and C++.

Java :
– any (even marker) interface,
– any class,
– any primitive….
is a type. We say “the declared type of the variable”.

c++ :
* any class, paramtrized or not
* primitive data type … is a type.
* typedef can declare new type names like aliases, but can’t create new types. Consider const_reverse_iterator.

java naming convention — registration

For an architect and a student, it’s good know ..

when a method or field or argument is named like …register…, it often means “add a CALLBACK to an OBSERVABLE”. The observable (subject, dispatcher..) often holds a list of listeners. When some life cycle event occurs, it /notifies/ them. See other posts on callback, listener, async…

Registration is used in DI, Hollywood principal and many “frameworks”

examples:
* registerShutdownHook

FCD vs regular *.h files

A footnote on the post about FCD. Here’s another aha moment — *.h file is #include’d into the the host class (I call it the “umbrella class”).

If the component class changes any part of its field listing including field types, umbrella “detects” it through the #include, tantamount to a text change in the umbrella file. Umbrella is marked dirty and needs a recompile.

Q: If you don’t #include the *.h but use FCD instead, can we avoid the recompile?
A: not sure. How about sizeof(Umbrella)? can compiler calc it if you use FCD? See Item 34 eff c++. I believe the trick borrowed from java is a pointer field, so sizeof(Umbrella) is independent of sizeof(Component)

again, what’s a header file for a c++ class

defining feature: MY Header file is #included by OTHER code, using macro expansion

feature: header file usually contains MY field listing so compiler can do sizeof()

Q: Does the object file include field listing?
A: not important

Q: is header file NOT compiled into the object file? In that case, the field listing is not physically saved in the object file?
A: At runtime, the assembly instructions in the object file has enough details to instantiate objects of my class.

Q: header file creates compile-time dependency, but how about run-time dependency?
http://www.gotw.ca/gotw/007.htm
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml – is a real-world coding standard in a real software company.

2+2 implementations beneath all java collections

1. array — contiguous memory => random access.
2. linked graph
—–which are the basis of ..
3. hash table — uses array and linked list. A LinkedHashTable uses linked list at 2 levels.
4. tree — the dominant sorted structure, an important subtype of linked graph
#) skip list
#) binary heap — priority queues

Everything in STL/collections is based on these 4.

Q: When i declare a “Serializable[22]” array, how does VM decide how many contiguous bytes to reserve for 22 array elements of type Serializable? The actual object can have 900 fields in it, so the object can occupy any amount of memory.
A: 22 pointers, roughly 22*32bits. Thanks to Chad Parry.

make 2 custom exceptions only — one checked, one unchecked

Lots of interviewers asked me about my exception handling strategy. Here’s a tentative exception object design for a small project — Maintain just 2 custom exception classes.

1) MyCheckedEx.java — a big custom checked exception (by extending Exception.java?) containing an enum[2] field. Each value represents a specific error condition[1].

2) MyUncheckedEx — a similar thing but unchecked (extending RuntimeException?).

Now the usage:

1) When you want a given error situation to always be handled in every *context* and never ignored, then register it in MyCheckedEx. Every place it can possibly occur, compiler will be your trusted friend to ensure it’s declared and handled explicitly.

2) things you put into MyUncheckedEx are nicely flexible, less strict. Callers (other developers) can choose to catch them or ignore them, silently escalating them to upstairs.

What about standard JVM exceptions? You can wrap them into your 2 exceptions. In particular, if you don’t like to handle many of the standard checked exceptions, you can wrap them in MyUncheckedEx. I think Spring wraps lots of Checked exceptions into unchecked. Conversely, you can wrap an unchecked exception into MyCheckedEx.

Another requirement — We often need a hierarchy of exceptions. Gmail uses labels instead of folders, so likewise, shall we declare some marker interfaces so an exception can be labeled as both validation and synchronization and billing exceptions? Will this beat a custom inheritance tree?

[1] a priority — i prefer fine-grained types of exception, for better control
[2] or int. You can use these in switch-case. I don’t like String.
non-priority — exception parent-child family. Unnecessary complexity.

base version ^ current version and CAS

http://en.wikipedia.org/wiki/Compare-and-swap#Implementation_in_C describes a compare-And-Swap algo — compare my base version with master’s current version and update master only if matched. If unmatched, then my base version is stale => can’t safely update.

i think iterator uses similar constructs. When an iterator is created from a “master” collection object, it copies master’s current version as its immutable base version. Whenever something changes concurrently in master, current version increments. Next iteration will notice it…. and triggers fail fast??

In other words….I guess a Collection object has an auto-incrementing private counter serving as a version number. Each new iterator gets an immutable snapshot of the version number. At each iteration the iterator checks if the “current version #” has incremented which means a change in the collection??

I guess CVS/SVN use similar constructs?

##[09] productivity skills in some financial firms #Le2xr

XR,

(to be published on blog, no need to reply)

I wrote about the same topic in a 2007 email to you — http://bigblog.tanbin.com/2007/12/interview-topics-are-irrelevant-now_10.html, and you replied — http://bigblog.tanbin.com/2007/12/fwd-interview-topics-are-irrelevant-now.html.

My GS experience shows that I could be somewhat slow initially[1], when getting up to speed on an unfamiliar system. Now i’m feeling a similar “teething pain”.

Now, what technical knowledge do highly *productive* developers tend to have in common?

* IDE — big area i am lacking, though i used IDE’s extensively since 2006.
** ant integration and external build tool
** cvs/svn integration
** content assist
** setting classpath
** using multiple versions of jre system library
** remote debugging? few know it but it’s powerful

* java generics
* junit — how to run, debug, write
* cvs/svn — synchronization, tortoise, branching, tagging
* ant, maven, ivy
* sql
* unix — grep, find, vi …

In GS and my new team here, I have met a few experienced java developers who know Eclipse a lot more than I do, just like I know Perl and Unix more than others. I learned so much Perl by reading and using advanced features — things like the O’Reilly cookbook tricks and tips.

[1] initial 2-4 months

arrays, collection and other initializers

List elements = Arrays.asList(‘a’, ‘b’,’c’, ‘d’);

new HashSet(Arrays.asList(“Fuel”, “Water”));

byte[] smallestObject = new byte[0];

int[] abc = {1,2};

int i = 0, j = 0;

Collection compileNok = new ArrayList();
Collection compileOk = new ArrayList();

new HashMap() {{
                put(“Up”, “Down”);
                put(“Charm”, “Strange”);
                put(“Top”, “Bottom”);
}};

pure VO wrapped in a domain object

why do Viktor and many java data modelers prefer to break a domain object into a pure VO and a wrapper object hosting the behavior or api methods?

Here’s a pratical reason. There’s negligible downside but increasing benefit as the object gets bigger. The one-class design can present hundreds (for a large object) of fields and methods, some belong to the VO, some obviously not. Hard to read. At some point you end up splitting the class anyway, for maintainability and readability. Why not adopt a coding standard?

A purist design is to have the VO as a public inner class of the wrapper. Argument — the VO should never exist outside.

A bad design is to make the wrapper a factory. The wrapper should still be a domain model. One instance represents one real-world instance.

subsumption — mouse with 2 buttons

when you assign an actual Integer to a Number variable named “n1″[1], compiler compares the 2 pointers’ types [2]. Start with the “expected” type. If Expected type has 2 methods, then the actual type “received” must support these methods. So that the Integer received can stand in as a Number.

Conceptually, we can think of the expected type’s class object to expose those 2 methods. The actual object’s class object must expose the same methods.

As an analogy, a customer (compiler) expects a mouse with 2 buttons (ie methods), so any mouse given to the customer must expose these 2 named buttons (ie methods), and can optionally have 8 other buttons(methods).

How, how does this analogy compare to the onion and remote control analogies elsewhere in this blog?


When you assign an array of Integers to a reference declared as Number[], same thing. System knows the expected type and the actual type and is happy. But ArrayList is not array. When you assign an ArrayList of Integers to a reference declared as ArrayList, compiler breaks.

[1] or pass the reference to a method argument
[2] represented by 2 class objects. Even if the 2 types are 2 interface, still there are 2 class objects.

y multicast efficiency imt pub/sub

If a market data update has to reach 100 subscribers, JMS uses tcp/ip to send it 100 times. Each subscriber has a unique IP address and “opens” the 1 “envelope” address to it, and ignores the 99 that it *receives* on the network (typically ethernet). This is unicast not broadcast…

Multicast sends the data once, with UDP/IP. This is significant for exchanges or any live feed provider

Certified delivery in RV stores the undelivered message in some file system, which is less reliable than JMS.

parent dtor always called; field dtor always called@@

When a C object (subclass of B) is destroyed, compiler guarantees to clean up the entire real estate of the C object, which always always includes a B real estate. Therefore the B dtor is never bypassed. (Same deal with B constructor.)

Q: Now what if B has a ptr/ref to a heap object?
A: the heapy thingy is NOT in B real estate
A: Say the ptr field occupies 4 bytes of B real estate. The 4 bytes are reclaimed, but not the heap pointee object. You need to customize dtor to clean up heap.

set-by-index on a list, nCopies and STL vector(int)

javaList.set() means List.updateExisting().

If you construct an ArrayList with capacity of 999, and try to set value to position 888 you will fail.

You need to first populate 999 items into the array like this

new ArrayList(Collections.nCopies(MAX_FIX_TAG, (String)null));

See http://docs.oracle.com/javase/tutorial/collections/implementations/convenience.html

STL vector ctor vector(int) does exactly the same. See http://www.cplusplus.com/reference/stl/vector/vector/

Q: If you construct a vector with a single argument 999, what’s the size of the vector?
A: 0 in java, because 999 is interpreted as capacity, not array size.
A: 999 in STL. 999 default constructed elements inserted.

financial jargon: principal-investing

… something unclear.

There are Public-Principal-Investments and Private-Principal-Investments. If a bank makes a PI into security A, the bank invests its own money into such a position.

make pricipal investments directly” means? with “our own” money instead of other people’s money such as clients’ $?

principal-investing is closely related to co-investing. For a investment bank, clients seek not only advice, but co-investment.

filter(unary)^comparitor(binary): 2 "genders" among STL predicates

Differentiate a “comparitor” vs a “filter”. Both constructs qualify as “predicates”, but if you think in terms of “predicates” you can’t observe the difference between horse and donkey.

Wrong — STL predicates are(?) all binary functions including std::less
Right — STL filters are Unary; STL comparitors are Binary

P41 [[objectSpace]] lists the stl algorithms accepting Unary predicates. EffSTL P168 has example of custom functor class — unary

Canonical example 1 — Most stl algorithms need a …. filter — Unary predicate operating on ONE element at a time.
* You are given a Binary function or functor
** either a std::less
** or a customized function or functor
* so you use bind2nd() to convert binary to unary

Canonical example 2 — your sort() or associative container needs a …. comparitor — binary predicate
* If you stop and think, a comparitor must take 2 inputs, so must be a binary predicate
* a comparitor can be a function or functor
* you don’t need bind2nd()

Std::less or a custom binary functor can be used in filters and comparitors.
$ filter usage needs bind2nd
$ comparitor usage doesn’t

Q: What if a STL algo needs a filter when you only have a binary predicate (including a comparitor)?
A: use bind1st and bind2nd. I guess the binary predicate needs to extend binary_function. See effSTL.

Note filter and comparitor are logical constructs or patterns. Physically they are implemented as function or functor returning bool (therefore known as predicate). Each STL algorithm or container requires either a real filter or a real comparitor, but physical implementation is not focus of this blog.

ref-count` && smart pointers in general

Java GC embraced and surpassed the ref counting capability of smart pointers. I doubt smart pointers handle islands, but do check out boost weak_ptr.

#1 motivation for smart pointers is memory issues like

– double-delete (ok if null)
– dangling pointer access (not “null” nor uninitialized), either read or write
– heap leak [1] — least dramatic but most common

As in any pbref environment, pointers are usually shared among functions, so a standard solution is ownership. Owner of a pointer takes care of deletion, using ref counting.

Another solution to the above memory issues — c++ references.

These memory issues are so common and serious that people come up many variations of these solution…

[1] not stack, so another solution to the list of memory issues — stackVars

convert a java Collection to a generic array T[]

    private T[] convertToArray(final List list) {
        assert list.size() > 0;
        final T[] tmp = createArrayUsing1stElement(list);
        final T[] newData = list.toArray(tmp);
        return newData;
    }
    @SuppressWarnings(“unchecked”)
    private T[] createArrayUsing1stElement(final List list) {
        final T[] ret = (T[]) Array.newInstance(list.get(0).getClass(), list.size());
        return ret;
    }

[09]good life ] U.S.@@

Hi GQ,
(to be published on my blog)

Thanks for sharing so much during my Dec visit. To be fair, many people enjoy US and wouldn’t want to come back to work in S’pore.

* bigger homes — Many live in suburbs and can have homes covering a soccer field.
* lighter workload — compared to S’pore, US workload is often lighter. Exception is (I was told) Wall street and other parts of Manhattan and California. When i was working in Boston, people usually work 9-5.
* high-caliber colleagues and competitors — US remains the global magnet for overseas talents, though many are leaving during the current recession.
* opportunity to work in upstream companies and trend-setters, such as Sillicon Valley and smaller high-tech pockets. S’pore is a little downstream but many parts of South East Asia is further downstream. However, I know there are real innovators in various parts of SEA.

For me,
* US work culture is more relaxed, free flowing individualism, not as conforming (suffocating sometimes) as some S’pore workplaces. Probably your companies are more cosmopolitan.
* higher salary. Comparable to Europe. But you know tax and currency factors.
* branding on the resume due to well-known employers. When jobs become scarce, branding becomes, i venture to say, paramount. Employers trust nothing more than a track record in a well-known company.
* insurance against job market meltdown in S’pore. I witnessed a sharp decline in S’pore salary level after 2002. I feel it may happen again. One day i may have to look at jobs in Hongkong, China, Europe… S’pore Branding is likely a problem as S’pore is not known except SIA.

iterator arg to STL find() can be anything

Suppose I get a vector::iterator from a vector begin().
Suppose I get a list::iterator from a list begin().

Now, these 2 objects don’t have a common super class[1]. But somehow, find() can use either object as its first argument. Find() can even use a qq(int *) object as its first argument. However, find() can’t accept a “float” object as first argument. I guess compiler will not complain, until you deference the iterator. I think find() does that.

Suppose I get a vector::reverse_iterator from a vector rbegin() – call it vec_r_it. Can I pass it to find? I think find() is going to increment it and deference it.

[1] array-based containers’ iterators are pointers, not wrapped into some wrapper object. Linked list, map, set … define real classes for their iterators.

In Java, the param to such a find() would be an interface, or a template param T like . In java, such an “expected-service” is always (“clean” language) expressed using interfaces. C++ is more complicated and flexible.

C# has a bunch of iteration constructs, not as “clean” as java.

STL vector, according to Stanford lecture

In c++, technically vector can (though occasionally not recommended) replace arrays in all cases except…? That’s actually a question (Q1)

* if a func param is an array i.e. a pointer to the element type. [[effective stl]] Item 16 comes to the rescue.
* (not for vector) if you need thread safety but your string implementation uses ref counting

The Stanford lecturer Julie Zelenski suggests the answer to Q1 is “nothing”. She did point out

+ vector offers bound checking.
– Every insert and remove must copy/relocate elements “on the right”, to keep memory contiguous.

[[effective stl]] also covers this topic.

However, we still must master C arrays, as they are widely used in production c++ code, not to mention C.

is actual argument an array or singular pointer@@

Quiz: pretend to be a typical c/c++ function at run time. If one of the arguments to the function is declared an int* pointer, how do you know if real thing is an array or a single pointer?

A: if this is the only argument, then you can’t tell. There has to be another argument like “int size”
A: however, if the argument is char*, then there may not be a size argument. Assume C-string please.

As a function parameter, a simple pointer is indistinguishable from an array.

queue based on Deque

STL queue is an adapter (wrapper) class over other containers, so you can create a queue over a deque. (This is quite common — the only other queue is a queue over a list — Yes only 2 types of queues exist in STL. No q-over-vector[1])

Q: so what’s the difference between a naked deque vs a queue-over-deque? Why use a queue-over-deque
%%A: deque exposes unwanted access — indecent exposure —
* bad programmers can add/remove mid-stream (which is rather slow — linear time).
* bad programmers can add/remove on both ends. A real queue allows insert on the left only, and remove on the right only.

In short, queue hides many unwanted deque operations and offers a cleaner and safer API.

[1] q-over-vector doesn’t exist, due to efficiency — see P178 [[stl tutorial]]

Method Object ^ Param Object

“Essential Java Style” is an excellent text on these 2.

In Both cases, the object is of an inner class. I think the MO need to access the enclosing class’s fields (attributes, properties, inst vars).

Both patterns are safe refactor operations, almost blind, robotic operations. I think a computer scientist can prove they won’t change behaviour/functionality. Therefore, these are more like implementation patterns than design patterns.

If there are x args to the original VLVU method, then the MO constructor gets exactly those x args, no more no less. All the original inst vars are still accessible from the composed methods in the MO (“inner”), and all original local/stack vars become MO attributes.

When to choose MO over PO? See P34. If after applying composed methods the VLVU method splits to 99 methods, then MO serves to group these many methods inside the inner class, whereas PO leaves them all in the enclosing class.

Note we go to such length just to avoid converting local/stack vars into fields. Such conversions contaminates the original class.

Q: how about a method with too many (55) args?
A: i think you can use an inner class or a regular bean to help build the arg list. Converting all args to attributes is the laziest and dirtiest solution.

hash_set insert success/failure: xLang

SGI hash_set (not in STL) insert also returns true/false, as the 2nd field of the returned pair object. http://www.sgi.com/tech/stl/UniqueAssociativeContainer.html

Same for VC++ hash_set. http://msdn.microsoft.com/en-us/library/2t5cf4t8(v=vs.80).aspx

java HashSet add() returns true/false to indicate successful/failed insertion. http://docs.oracle.com/javase/6/docs/api/java/util/HashSet.html#add(E)

Same for c# http://msdn.microsoft.com/en-us/library/bb353005(v=vs.110).aspx#Y0

closure vs lambda – phrase book

Closure and, to a lesser extent, lambda are difficult to describe, but __implementation__ is easy to understand. http://martinfowler.com/bliki/Closure.html and the wikipedia article are good. Here is my own learning notes and phrase book.

anonymous — an lambda expression is an anonymous function. Simple anonymous functions are handy in many contexts — you know it after you learn to use the technique.

* free — a lambda function always has input variables. It’s like a math function. These variables are by-default “free”. See python lambdas.
* bound — a closure is a lambda with its variables bound to something in the lexical environment

C# delegate? The anonymous delegate might be a lambda.

java — anon inner class offers many features of closure. I feel it’s a reasonable (not the standard) illustration of closure. http://martinfowler.com/bliki/Closure.html explains why it’s Unpopular.

C++ functor — Can’t access a variable in the enclosing “lexical-scope”, so not a closure

value — To the end-programmer, a closure (lambda too) appears to be a VALUE you can pass around, and assign to variables. Stateful object.

stateful — I feel closure is usually stateful; lambda is usually stateless

Garbage-collection — a closure holds almost-permanent references to “variables” (not just objects) in the lexical env, so those variables must not be auto/stack variables. You usually need a GC-powered language.

Many languages’ syntax use the keyword “lambda” to cover both lambda and closures. Reason? I feel lambda vs closure syntax (and implementation) is closely related, and end-programmer will welcome a simplified and unified syntax.

Note closure and lambda are not data types. An end-programmer is forgiven to say closure and lambda are simple flow-control constructs just like a for-loop or if-else. You can point to a chunk of source code and say it’s a closure — or you can say it’s an example-of-closure-Pattern. If I must use a single word each, I would say
* a lambda is a kind of …. function
* a closure is a kind of ….. stateful function

—– confusing/non-trivial jargon to avoid if they don’t help your learning — you can safely skip them
lexical
bound variable
“value”
“environment”
“local”

slicing – [[c++ primer]]

Update — c# has no slicing because the only composite type to be passed by cloning is struct but structs is never subclassed. Java is even cleaner. C# class/array/Delegate instances are like java objects — always “pbref” rather than “pbclone” i.e. pass-by-value.

Slicing is the #1 pitfall in c++ inheritance, subsumption, pass-by-value (pbclone — see other posts). It’s common and tricky.

class Base{};
class Derived : public Base {};
Base b;
Derived d;

Q: when do we see slicing of a big object into a small object?
A: assigning qq(b = d). The LHS base object has a smaller real estate than the RHS subclass object
A: copying qq[Base b = d] or qq[Base b(d)]
A: {special case} when pbclone passing a child object into a parent parameter, essentially copying
A: a container with nonref type arg qq[ myMultiset.insert(d) ]
A: in all these cases, the LHS object is a parent object — sufficient memory to contain parent’s fields — no room for child’s toys:).

Q: When can we avoid slicing by sticking to just one object? Note copier/assignment always involve 2 objects — always slicing.
A: pbref using ref or ptr, bypassing field-by-field cloning. However, you can’t avoid slicing completely. If i have an object of type D, to be passed into a field [2] of type B, I get slicing of some sort always, since i can’t access the child portion of the D object, unless i dynamic_cast.

[2] or stackVar incl params

onion — slice off the outer layer.

See [[c++ primer]] P578

callback (listener,functor,event handler,observer)@what thread@@

Whenever I see a callback, listener, observer or event handler [1], i ask
Q1: In which thread does the callback run?
Q2: In which thread does the caller run? Note caller method might spawn a new thread to run the callback.
Q3: In which thread does the event generator/sender run? Usually not the same as the callback method.
Q4: is there a network daemon running a blocking accept()? I feel this is a fundamental question. In Swing and Case 3 below, there’s no network daemon so event generator can invoke the callback in the same thread.

Case 1: swing — experiments show the callback runs in the event-queue thread i.e. EDT. If you suspend the event-queue thread, you see the thread waits in wait()

Case 2: onMessage
Case 3: spring jdbc template
case 4: servlet event listeners
case 5: java.util.Observer. I think the detailed chapter in [[head first design patterns]] is a single-threaded example. The update operation triggers all the callbacks in a single thread.

I guess in both Swing and Rendezvous, listeners are in a static collection. GC can’t reclaim them. Memory leak!

http://www.java-tips.org/java-se-tips/java.util/using-weakhashmap-for-listener-lists.html says listeners are strong references and are not garbage collected, so we must remember to remove the listener. Also see http://www.javalobby.org/java/forums/t19468.html

Doug Lea has a chapter on callbacks in a threaded environment.

A worthwhile distinction — Note a “listener” (and sometimes a callback) is an object; a “callback” is often a dynamic method CALL, or you can think of it as a METHOD in source code, loaded into JVM as part of the class object. Now at registration time, the listener’s object reference (ie memory address) is submitted, photo-copied and stored in the registry.

[1] a method, object, nested class..

how does a mortgage creditor sell off the mortgage@@

Q: If a mortgage is a bad thing to a bank, why would anyone want to buy it from the bank?

Underlying asset is the building. Creditorship of the mortgage is a good thing as it generates an income stream. It’s an interest-bearing instrument.

In the worst case, you still get the house — collatelized.

If a mortage pays $2000/month and the house has a (albeit fallen) value of $300k, someone will be willing to pay $1 to become the creditor.

So there’s a fair value even if the borrower has poor credit.

FX – no clearing house, no comm

http://www.chartfilter.com/Beginners-Guide/how-is-currency-trading-different.html says

Currency trading is not done on a regulated exchange (for example: the NYSE). There is also no central governing body (such as the SEC), there is no clearing house to guarantee the trade. Trading currency is done through credit agreements.

By contrast, In stock, option or futures *traders(like Michael Douglas)* typically use a __broker(Charlie Sheen)__ to execute the transaction as per the trader’s instructions. The broker then gets a commission. No such comm in FX! I guess “never” is too broad — there could be minor exceptions.

http://www.investorguide.com/igu-article-975-dividend-reinvestment-plans.html says

If an investor wanted to purchase stocks, /options/, or futures – they would need to ultimately go through some sort of regulated exchange – such as the NYSE. Currency traders (except CME fx futures) have no such regulated mechanism overseeing transactions. What exactly does this mean for the average investor? – An increased element of risk.

There are no commissions in FX trading! This is possible because there are no brokers – only FX dealers.

iterator inheritance hierarchy (dummy type

Look inside the class definition of template class reverse_iterator : public random_access_iterator

You find a method definition —

RandomAccessIterator base() …

You wonder what’s the random_access_iterator vs the RandomAccessIterator . Here’s what I know.

* RandomAccessIterator is a dummy-type used in templates, just like the customary T in . As a google tech talk speaker puts it, this dummy type means nothing to the compiler. This is what I call a fake-type or dummy-type. A fake-type is a token in a source code presented to the compiler. It can look like a real type but it’s
** not a class or class templatedumm
** not a typedef
** not a ptr
* random_access_iterator is a hand-written template class, and the parent class of reverse_iterator. You can see the source code at http://www.hackchina.com/r/178959/stl_iterator.h__html or http://www.sgi.com/tech/stl/stl_iterator_base.h

Now i know there is a clear inheritance hierarchy among some iterator TYPES. These are not fake types!

input_iterator (and output_iterator) is a class, !! a typedef

SGI says output_iterator is an empty class, presumably a marker-interface

http://www.cppreference.com/wiki/stl/iterators shows….

void advance( input_iterator& pos, Dist n );

Q: so input_iterator is a real type or a typedef or a dummy-type (template)
A: the context around the advance() declaration will tell you.
A: Here’s another context. http://www.hackchina.com/r/178959/stl_iterator.h__html shows it’s a real class or a “class template” to be precise.

Note these things look like fake types but they are real classes, parsed by compiler.

importance of arrays in c++

Q: arrays are fixed blocks of memory (can’t grow beyond their initial allocated “lands” into neighbors). why are they so popular and relevant in c++?
A: The Defensive Coding chapter in Microsoft author’s [[Solid Code]] advocates arrays (over vectors) on the ground of simplicity.

A: a lot of c++ apps are owned by C developer teams. A lot of arrays in use. Consistency is esp. important when you are not in green field.

A: most enterprise C apps, in any language, use lots of strings. The most common string in c/c++ is still a char array.
A: c++ is low level. Arrays are a fundamental low-level structure. For any collection, perhaps the only alternative is linked data structure.

A: as stated in the blog [[4 implementations]], array is the #1 most fundamental implementation of all collections and containers. Salt and vinegar don’t taste good, but you can’t cook without them.

A: pointers are fundamental to and powerful in every language. array is the most natural user of pointers. Much of c++ “most powerful language” reputation rests on pointer/array integration.

A: array is to vector what wait/notify is to jdk5 concurrency constructs

pbref/pbclone — indistinguishable by func call (restriction on overloading

At end of a function, You often see “return someNonRefVar” or “return *ptr”, or “return someRef”. Such a return can either return by ref or return by clone, but which one exactly? Answer is in the func prototype. Return by ref is always indicated there, not in return statements.

Quiz: by looking at the return statement itself, can you tell if it’s return by clone or return by ref?
A: if it returns a non-var like “return amount + 3.22” ==} can’t be pbref.
A: if it returns a local object ==} can’t be pbref as the local object would self-destroy right away. But see post on RVO

It’s instructive to compare with argument passing syntax. Calling code doesn’t need to know to call by clone or call by ref. The func call looks identical [1] — just put vars in the parentheses. To tell a call-by-ref func from a call-by-clone func, Key is the func prototype.

Q: Can 2 otherwise identical functions overload each other simply based on the “&” in a param?
A: no. Compiler can’t “bind” a function call. I tested in gcc. Also covered in IKM test.

[1] except you can’t pass non-vars in pbref.