easyMock && mock-object — oo technique

* uses java’s proxy feature
* covers one of junit’s weaknesses
* “recording” required
* useful for jdbc testing

http://en.wikipedia.org/wiki/Mock_Object addresses
* needed in what kind of unit testing scenarios

“mock objects can simulate the behavior of complex, real (non-mock) objects and are therefore useful when a real object is difficult to incorporate into a unit test.”
=> For FTTP testing, it might help when u need a “mock iview object” ie a mock object in place of the real iview


test 2 bugs in 1 method #junit

“multiple assertions” are a common topic among Junit users — “it’s not important to have precisely one assert per test; many experienced testers have multiple assertions in a block at the end of a test method.”

bash search`unix command #precedence

Q: what if you have an alias, a shell func, a shell built-in (like “echo”), a unix executable file, and your own script all sharing the same name?

Focus on 2 simple rules for now:

1) Your own aliases override everything else (such as shell functions)

2) $PATH is the very last (after things like shell built-in commands) place searched by the shell. Executables in $PATH are external to the shell.

I think the same precedence holdes for any shell.

simple(@@) topics ] java

db connection obj
db connection set-up
thread-safe collections
jdbc conn pool

4 scopes


simple? Is shell scripting simple?

These tend to be interview questions, because
* most of us are expected to have used them or know them well
* => yardstick to measure and compare candidates
* familiar to most interviewers

php oo match`java@@

The claim: php is 70% as competent as java, in terms of OO features to model and design a system. I think it’s below 70%.

* polymophism, dynamic bind` @@
* strongly typed — fundamental to OO system design
* A java return type can be declared as an interface/abstract type, so clients can safely use an expected service of the interface
* inner class for OO design
* more access modifiers
* Constructor chain reaction up to Object@@
* overload@@
* custom classloader
* factory, singleton and other patterns
* java proxy to implement AOP
* distributed components — RMI, corba… important for some enterprise systems.

each object’s wait set

— surprises
custom exception@@ yes

DB tables]FX cash trading system(any bank

Q999: database tables that are the biggest or busiest

A: see blog on Currency Tables and SymbolSourceMapping tables to compute safe crosses.
A999 from ZJW and Piroz
– Trade table,
– Order table –limit orders are pending and have a lifetime. Also, London traders often need to hand over overnight orders to NY, either mandatory stop-loss-orders or unfilled customer orders.
– A family of RFQ tables like my bidans/bidstreet/bidreq tables.
– IncomingQuote table is (according to ZJW) the biggest and busiest, but there’s probably a separate table for each quote source.
– OutgoingQuote table ??
– ClientPosition table has a primary key on (ClientAcct, Currency)
– TraderPosition table is the mos interesting. Even though there could be a small number of trader accounts, I was told it’s unlikely that system maintains a separate table for each account. Primary key would be (TraderAcct, Currency). In cash trading, most positions are flat i.e. closed out quickly, so there should be relatively few rows in this table. However, if base currency is USD, then a particular trader’s JPY row would get a lot of concurrent updates. Since this row represents real inventory, all updates must follow strict ACID transaction rule. Possibly a bottleneck just like in bond trading.

Q: Any reference data tables

FeedSource ??

smarty vs View # mvc in j2ee

smarty is an extremely well-defined, simple and above all, concrete, implementation of many abstract concepts. Suprisingly, I used and studied struts many times more than smarty but I understand smarty better.

We can use smarty as a starting point or reference point to understand views in struts MVC.

In fact, jsp Expression Language and JSTL also mirror smarty.

* request object = a huge nested php object passed into smarty template
* afward = a logical name (no such thing in smarty) for a “physical” view
* forward request to a view =
* controller as request router =

cluster admin server

In Weblogic (perhaps similar elsewhere), a cluster needs an admin server that’s not one of the cluster nodes.
j4: single point to deploy application, but without admin server, we can have similar convenience?
j4: watch tower to monitor the nodes, but without it, we can monitor them from another place?
j4: single location to store node-configuration

tiers ] ports^1-jvm

Refer to the overview post on ports^1-jvm.

Suffering from the same abuse-of-terminology as “server”, the word “tier” can now refer to not only separate-jvm but also to 1-jvm AR. Consider

“data tier” —
“dao tier” — basically the same as “dao modules”, as a layer of abstraction
“orm tier”
“object tier”
“presentation tier” — jsp, struts views, usually within 1-jvm

%%javascript/ajax iview q

You did this for years but some nitty-gritty iview questions may make u appear /amateur/ (adjective)
Many answers are in your book.
* how do u access all the

elements in a page@@

* how do u add a

before the 2nd last


* how do u let a user click a button to add a new

in a designated location on the page@@ Use innerHTML

* how do u change the style of an element@@
* why and how do u register multiple functions (event-handlers) for a button’s onClick@@
* how do u unregister an event handler@@

server/client mean — ports^1-jvm

a “server” is traditionally a separate jvm or unix process but nowadays occasionally can refer to a method (or set of methods) your “client objects” can call within a container.

In the same vein, a “client” used to mean a number — a process id (or thread), often on a different host, but now in Java literature it often means a “caller of a method”. A caller of a method may or may not be an object in memory, but always refers to some “calling context” to be altered by the method.

Every OO students would eventually come to realize when to say “client” and what that implies.

The j2ee community seem to pay little attention to the question “same or separate jvm?”

A “service” is often provided by the container.

The “server” usually provides some utility service like water and electricity.


Perhaps not a good example. jndi is obviously a container service. It can be filesystem-based.

BMC patrol, Microsoft MOM

hi, Tan Bin

Varies Knowledge Module comes with Agent, base on the role, other than monitor OS itself, you can purchase and configure Knowledge Module to monitor applications/services running on it.
it is similar to Microsoft MOM. every new application come on, MS will develop Management pack to install and moitor it.

Z Hao

dependency injection: cost^ROI

Ignore J2EE and EJB for now. Just look at an app with lots of HAS-A relationships. Compared to standardard dependency-setting,

#1 return? testability -> quality assurance

#1 cost? unnatural and perhaps more effort? http://jcp.org/en/jsr/proposalDetails?id=330 argues that flexibility is achieved by factory, service locator or DI. All 3 need extra effort compared to the basic inflexible implementation

dependency injection: %%intro

Inspired by James Shore,

Q: What’s a dependency? What are the 2 parties in a dependency? What’s bad?
A: a “dependency” is one of class A’s instance variables b, of type B.

“injecting the dependency into A” = assigning an object to the instance var b with a public setter method. This can be done in a third-party class C, through an interface.
“setting the dependency” = A autonomously assigning object to its own instance var b. Common practice

Q: why do people mention factory pattern, service-locator pattern?
A: http://jcp.org/en/jsr/proposalDetails?id=330
http://jcp.org/en/jsr/proposalDetails?id=330 has a simple example (stop watch) demonstrating constructor injection. also used in dotnet.

http://www.jamesshore.com/Blog/Dependency-Injection-Demystified.html says

Some call those “dependencies.” Most people call them “instance variables.”


Why Do We Do This?
Among other things, it’s handy for isolating classes during testing.

singleton race condition

http://www.javaworld.com/cgi-bin/mailto/x_java.cgi says

// Also an error, synchronization does not prevent
// two calls of constructor.
0) public static MySingleton getInstance() {
1) if (_instance==null) {
2) synchronized (MySingleton.class) {
3) _instance = new MySingleton();
4) }
5) }
6) return _instance;
7) }

Thread A passes Line 1
Thread B passes Line 1
Thread A gets the lock at Line 2 and releases it at Line 4
Thread A passes Line 7, sets _instance to point to a MySingleton object and returns it to caller who creates a reference to the object.
Thread B gets the lock at Line 2 and instantiates a second MySingleton.

Now both instances have reference count > 0

php-servlet, php-JMS

C) There are at least 2 other php/java glues — popular frontier and playground

A) from http://www.php.net/java

      ” There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is the more ***stable*** and efficient solution, or integrate Java support into PHP “,  using the extention on this page.  

Notice that the home page of the 2nd solution says the 1st solution is more stable and efficient.

Proof of this java-extention-in-php? A 2004 Onjava article on *JMS* in PHP http://www.onjava.com/pub/a/onjava/2004/10/27/php-jms.html

      ” The Zend Platform PHP/Java Integration Bridge allows companies who have investments in J2EE application servers to take advantage of PHP. In addition, the Integration Bridge allows companies using PHP to take advantage of J2EE services. “

easiest way to compare 2 files in a windows box

I wanted to compare the old version of myClass.java with a new version but the two files live on 2 drives.

Now I just browse to the first myClass.java, right click to mark it for “compare later”. Then i browse to the 2nd file, and right click to compare them.

Immediately the 2 files are loaded in a GUI side-by-side with differences highlighted in color. You can scroll both panes at the same time.

More visual/convenient than WinDiff or CVS-diff in Netbeans.

* The GUI tool is winMerge (http://prdownloads.sourceforge.net/winmerge/WinMerge-2.6.8-Setup.exe)
* The WinExplorer context-menu plug-in is Diff-ext (http://diff-ext.sourceforge.net/downloads.shtml)

Diff-ext also lets u compare 3 files or directories.

weblogic multipool

useful when you have 2 database instances (perhaps on 2 DB boxes) that are not a DB cluster. What’s their relationship? Perhaps a replica.
If the 2 db instances form a db cluster, then a db client ( your servlet ) gets a single point of contact — no need for fancy multipool. The DB cluster /masquerades/ as a single regular DB instance.

what ajax brings2the pre-ajax web


“background call to server” to retrieve data needed to update a page fragment

pre-ajax: Given a chunk of (xml) data, javascript to use it to modify page fragments
pre-ajax: javascript to access ANY element via the full DOM
pre-ajax: javascript event handlers to send data to server

%%perl iview q

You have done this thing for years, but iview questions may suprise you and make you look like a fake. Even a veteran need to ancipate iview questions.

  1. how many SAX xml parsers?
  2. how many DOM xml parsers?
  3. how many xslt transformers?
  4. describe some perl/xml projects
  5. query cache?
  6. how do u rollback a db tx?
  7. any way to re-use a db connection after end of script? no background process to keep the memory allocation
  8. real xp with xml parsing? zed

update a session obj -> setAttribute() -> replication

(Perhaps the most basic coding technique when migrating a servlet to a cluster.)

1st time u call setAttribute(amt, Amount), the container binds Amount obj to the session scope. Subsequent changes to Amount would
be forever visible to any other servlet accessing the same session.

However, in a cluster,

make changes to Amount
setAttribute() again
make changes to Amount
setAttribute() again

I think each method call triggers a session replication.

beneath ajax paradim — onreadystatechange

ajax paradigm can be very confusing. Don’t ask me exactly why. Let’s really master one piece at a time. Let’s try to memorize a component’s relationship with other components. Memorize and try to develop quick reflex that you had with struts, java, unix, perl,
#1 reflex:
                    “onreadystatechange callback = javascript function triggered by data from GET/POST”
You already know that a GET (ignore POST for now) always has a caller function, in our case a js function. Caller function always receives the Gdata (GET-data), dictated by http. Now sit up — Gdata is passed to a “special-js” function. Avoid cliches like “callback”.
* special-js uses the data returned by GET
* special-js = a JAVASCRIPT function
* => special-js runs in the browser  
* => special-js usually modifies the DOM content in the browser
* special-js checks if (readyState == 4)
special-js function, as a javascript function, is often defined amid the html and has a name. The special-js function name must be set with
        XMLHttpRequest  .  onreadystatechange = your_special_javascript_function_name

beneath ajax paradim — innerHTML is used in javascript

innerHTML is frequently used. Anything in ajax paradigm can be confusing. Let’s really master one piece at a time. Let’s try to memorize a component’s relationship with other components. Memorize and try to develop quick reflex that you had with struts, java, unix, perl,
#1 reflex:
                        “innerHtml is used in javascript only”
* In javascript you use “innerHtml” to read/edit parts of the Document-Object-Model 
* innerHtml refers to browser content ie page fragments in the browser
* innerHtml has meaning after page loading, not during or before, the browser completes loading a page or a fragment from a ajax call.

%%jsp iview q

imprecise? ok
  1. what kind of content/data do u use Expression Language to express?
  2. give 3 common tags as part of the JSTL
  3. where are security roles defined? give a few examples
  4. where are security usernames defined? give a few examples
  5. mapping a username to a role? to 2 roles?
  6. (entities: real visitors, passwords, usernames, roles, url-resources to protect….) how does system authenticate a real visitor to such a username?
  7. How does a servlet or jsp add to the exception (implicit object)? P 299 [[ jsp ]]

pdo == php data obj

similar to DBI/DBD — one vendor-independent component + one vendor-specific component

how PDO compares to other popular abstraction layers out there, for example, PEAR DB or ADODB. pdo is lighter than either of those, both in terms of API and in terms of performance.

mysql stored procedure is ok with pdo but not pear::db


Many folks resort to a data abstraction layer, such as Pear::DB or DBX. Using a data abstraction layer is a good thing, but its main goal is to make the RDBMS transparent, allowing you to change database vendors fairly easily.

junit usage #briefly #too basic

  • Test Suites (advanced) = Groups of test classes clustered to permit testing of an entire application or project. A test suite looks for all class files that contain “Test” at the end of their file name
  • most “test” methods are “void”
  • Most simple examples use assertEquals(), assertTrue()
  • setUp() is called before the evaluation of each test,
  • tearDown() — setUp has a brother called tearDown which is called after the evaluation of each test and can be used to dereference variables or whatever so that each test may be performed without issuing side-effects

Default flow is “isolated-tests flow” ie

setUp -> testMethod1 -> tearDown ->
-> setUp -> testMethod2 -> tearDown ->

Q: How to do it on Command line?
A: java junit.textui.TestRunner FTTPCktLoaderTest

Q: how to specify a sequence/order among tests?
A: probably u need a test suite

Q: If you want to reuse the result of testmethod1?

chmod -x /bin/chmod

Q: How to undo “chmod -x /bin/chmod” @@

A: perl has a “chmod” function. Probably the root user can do a one-liner.
A: php has a “chmod” statement. Root user may need the php command line. php also has chown()
A: python also has a chmod() method in the OS module

A: copy from another host. Check file size first.
A: recover from backup

php iview questions 20 Jul


Thanks. They did ask about xml, object-oriented php …

q: any object-oriented php framework you used, such as zend framework

q: what’s the object-oriented MVC architecture?

q: how object-oriented is the data access layer?

This xml question was tough, because they decided to drill down right to the limits of the interviewee’s understanding of a past project.
q: in your project, how did xml help flash-php integration.

—– Original Message —–

> Hi, how was your php interview? Guess you must have done it well. Did you meet any unexpected tough questions?

weblogic jdbc "query cache"

the first time a query is run, Liquid Data saves its results into a query results cache. The next time the query is run with the same parameters, Liquid Data checks the cache configuration and, if the results have not expired, quickly retrieves the results from the cache.

similar to EHcache read-only mode

callable-Statement to call a stored procedure

%% nlg pearls:
stored procedures can have some IN, OUT or INOUT params
stored procedures can return 1 or more rows

To call stored procedures, you invoke methods in the CallableStatement class. The basic steps are:

      1. Invoke the Connection.prepareCall method to create a CallableStatement object.
      2. Invoke the CallableStatement.setXXX methods to pass values to the input (IN) parameters.
      3. Invoke the CallableStatement.registerOutParameter method to indicate which parameters are output-only (OUT) parameters, or input and output (INOUT) parameters.
      4. Invoke one of the following methods to call the stored procedure:


          Invoke this method if the stored procedure does not return result sets.


          Invoke this method if the stored procedure returns one result set.


          Invoke this method if the stored procedure returns multiple result sets.

      5. If the stored procedure returns result sets, retrieve the result sets. See Retrieve multiple result sets from a stored procedure in a JDBC application.
      6. Invoke the CallableStatement.getXXX methods to retrieve values from the OUT parameters or INOUT parameters.

    The following code illustrates calling a stored procedure that has one input parameter, four output parameters, and no returned ResultSets. The numbers to the right of selected statements correspond to the previously-described steps.

    Figure 33. Using CallableStatement methods for a stored procedure call with parameter markers
    int ifcaret;
    int ifcareas;
    int xsbytes;
    String errbuff;
    Connection con;
    CallableStatement cstmt;
    ResultSet rs;

    cstmt = con.prepareCall(“CALL DSN8.DSN8ED2(?,?,?,?,?)”);
    // Create a CallableStatement object
    cstmt.setString (1, “DISPLAY THREAD(*)”);
    // Set input parameter (DB2 command)
    cstmt.registerOutParameter (2, Types.INTEGER);
    // Register output parameters
    cstmt.registerOutParameter (3, Types.INTEGER);
    cstmt.registerOutParameter (4, Types.INTEGER);
    cstmt.registerOutParameter (5, Types.VARCHAR);
    cstmt.executeUpdate(); // Call the stored procedure
    ifcaret = cstmt.getInt(2); // Get the output parameter values
    ifcareas = cstmt.getInt(3);
    xsbytes = cstmt.getInt(4);
    errbuff = cstmt.getString(5);

sql to list mutual funds

we don’t know when the database may get updated. we only know it’s very rare

Jingsong J. Feng if the change frequency is very low, create a trigger in the database, when data change, trigger a query, and update result

Jingsong J. Feng schedule Thread to run it every miniute or every 5 miniutes
Bin X. Tan/VEN… to update the local cache?
Jingsong J. Feng yes

Jingsong J. Feng oh, set a timeout variable — Hibernate

How about an update/insert/delete trigger to send a GET request to our servlet and expire the cache immediately? The next visitor to the website would see the updated list fresh from the database.

If there’s a jms broker, trigger can send a cache-expiry alert to the queue even when the web system is unavailable. When the web site comes up again, it receives the jms message and expires the cache?

Without a JMS broker, the GET request could update some persistent expiry-flag on the cache server. Even with frequent reboots, the cache server could check the expiry-flag periodically.

Q: Can a trigger send a GET?
A: yes

Q: Can a trigger be a jms client?
A: Not so common. http://www.oracle.com/technology/products/integration/bam/10.1.3/TechNotes/TechNote_BAM_AQ_Configuration.pdf
(AQ = Oracle Advanced Queuing )

clustered index — when (not) to use

Clustered indexes sort and store the data rows in the table based on their key values. There can only be one clustered index per table, because the data rows themselves can only be sorted in one order

the index can comprise multiple columns (a composite clustered index).

— 2 + 1 usages of clustered index
* A clustered index is particularly efficient on columns that are often searched for ranges of values. After the row with the first value is found using the clustered index, rows with subsequent indexed values are guaranteed to be physically adjacent.

* Also, if there is a column(s) that is used frequently to sort the data retrieved from a table, it can be advantageous to cluster (physically sort) the table on that column(s) to save the cost of a sort each time the column(s) is queried.

%% this last usage isn’t compelling %% * Clustered indexes are also efficient for finding a specific row when the indexed value is unique. For example, the fastest way to find a particular employee using the unique employee ID column emp_id is to create a clustered index or PRIMARY KEY constraint on the emp_id column. Note PRIMARY KEY constraints create clustered indexes automatically if no clustered index already exists on the table and a nonclustered index is not specified when you create the PRIMARY KEY constraint. If you can’t create a clustered index on emp_id, a clustered index could be created on lname, fname (last name, first name), because employee records are often grouped and queried in this way rather than by employee ID.

–Clustered indexes are not a good choice for the following attributes:
* Columns that undergo frequent changes
* identity columns
* very few distinct values, such as boolean columns

ports^1-jvm to decouple web tier

2 common architectures to decouple any object-oriented web (or non-web) system. Master them. Don’t try to add a 3rd architecture to overload your memory.

— A) ports ie tcp ports. You Separate a chunk of java code into another unix-process with a port. You end up with a “tier” in a multi-tier AR. Beware “tier” can now refer to single-jvm modules too, in an abuse of terminology.

connection pools @@

Examples: EJB, ActiveMQ, CPF Single-sign-on-server, crystal-report-server, web services

— B) single-jvm solution. Instantiate intelligent components from an off-the-shelf or /3rd-party/ (3p) jar
thread issues
In a web tier, the 3p objects could be too big to re-create ==> put in session

Examples: struts, spring, hibernate, nanoXML, log4j, shopping cart

Example: the M in MVC could be a 3rd-party module (shopp`cart) or even a legacy ERP, but almost always there are some M-classes within the MVC jvm.

recursion – whiteboard cod`IV tips

  • spend some time writing down the external interface of the recursive func — exactly what to print/return, and what global variables to update.
  • define end-of-recursion condition explicitly. Interviewers want to see that.
  • list all important local variables vs global variables on the side.
  • Some variables must be local — on the stack. All other variables had better be global variables.
    • sometimes local variables are simpler — throw-away temp
    • sometimes global variables are simpler — fewer stateful objects.
    • Simplifies the visualization. Any variable passed into a recursive call is additional state on every stack frame and makes the logic harder to reason about. This is more serious when there are many such local states to keep in mind

synchronized — main-effect^side-effect

Main effect? serialized (not concurrent) access of a block of code

Side effect? trigger a flush from register to main mem, achieving volatile's functionality. See


Why the side effect? not important at this moment. Good to know.

There could be other side effects. No need to research.

jms AR notes, starring IBM-MQ

jdbc is a gateway to databases; jms is a gateway to MOM servers such as IBM MQSeries server, SunONE MQ server.

Q: is session needed for transaction or something else?
A: i think there’s a conversation state with the broker/server, just like DB connection session.

Confused about the jargons — jms-broker, jms-server, MOM-server, exactly what’s on the opposite end to a jms sender/receiver?

Point #1: A JMS connection sometimes requires 2 jvm’s — the client jvm and the broker/server jvm. Consider pushmail (ActiveMQ as a separate jvm). As a source of confusion, the jboss workbook and the Medrec tutorials probably use a single jvm for client and the broker.

Point#0: IBM MQ Series is definitely a separate unix process. See http://www.ibm.com/developerworks/websphere/library/techtip/pwd/wsmq_integration.html, servlet->MQSeries code sample

StringBuffer / StringBuilder offers no prepend()

Use insert(). Example —

   myStringBuffer.insert (0, “prefix string”); // C# and java are similar. See API links below

This technique is rather important to job interview coding tests. (I encountered this in the ITA 50 billion quiz)

Warning — http://stackoverflow.com/questions/738950/c-sharp-or-java-prepend-strings-with-stringbuilder points out that prepend is often less efficient as append

myBuf.insert(5, …) means “insert after 5“, that is, insert after first 5 characters of myBuf.
myBuf.insert(0, …) means insert after 0 character, which is the geeky way of saying prepend

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuilder.html — faster but thread unsafe


java transaction — brief AR notes

a tx is often “managed” on the server. There’s one session per tx in server memory. But how is a XA tx managed??

a tx and a session always involve a private mem, often on server and client

a tx usually (always?) involves a SESSION. perhaps a session with the DB or MOM
a tx usually (always?) involves a java THREAD.
a tx always involves a private mem

“XA-enabled jdbc driver”?? I guess such a driver understands and responds to the commands of global tx mgr.

A Weblogic expert told me that the first phase can be lengthy as all parties fully prepare their commit and rollback infrastructure. It can fail. 2nd phase is extremely quick as the global tx mgr somehow triggers all parties (geographically distant) to perform the final step. Because this last step is extremely _simple_, it’s virtually impossible to fail.

Q: what if one of the parties fails during 2nd phase, while other parties commit.
A: looks like it is a technical possibility but known to be extremely unlikely.

MQ servers made by Tibco and IBM

Hi LS,
A technical question for your consideration when you have time. I just don't have a lot of time for such topics of curiosity.
I learnt that a typical message-driven-bean container can only support a JMS broker made by the same vendor. For example, someone suggested perhaps weblogic MDB only works with weblogic-mq.
However, I guess ibm mq is a popular MOM infrastructure used in non-websphere environments. Similarly, Tibco's MQ broker is probably used in ejb containers made by other software makers such as BEA, Sun, Oracle.
How could (or couldn't?) a SunONE ejb container work with a JMS broker from Tibco?
Is it because Tibco MQ isn't a JMS broker but a more general purpose MOM server?
Thanks and have a lot of exercise!
tan bin

for loop dos^shell

–dos: FOR %A IN (1 2 3 4 5 6 7 8 9 10) DO echo …

i=4; while [ $i != 0 ]; do
i=`expr $i – 1`

The let command is a replacement for the old method of performing shell arithmetic using the expr command.

# Note: != syntax is easier to remember and less error-prone than -le. Now, If you must count from 1 upward,

i=1; while [ $i -le 4 ]; do
i=`expr $i + 1`

ArrayList basic how-to

q: make a copy of an ArrayList? clone() dones’t copy the content
A: new ArrayList(oldAL)

q: pop() and push(an object)
A: add(), and al.remove(al.size()-1)

q: insert before 7th element?
a: add(index…)

q: search and remove a given object
a: remove(index)

q: remove 9th element
a: remove(index)

q: convert a string to an arrayList of single-char-strings?
A: convert to an array then feed to Arrays.asList() then feed to new ArrayList()

q: list all elements matching a condition?

q: replace all elements….

q: remove all elements …

q: convert from a set

q: convert from an array of objects

q: convert from an array of /primitives/

q: split into 2
a: removeRange()

HashMap — entrySet, keySet

If you look into the entrySet of a Map object, u may fail to find a list of fields. Looks like the only field is “this$0”, a ref to the enclosing Map object.

If you look into “keySet” and “values”, you may find them null even though the hashmap is not empty !

capacity management, a Unix /perspective/

aim for simultaneous saturation and eliminate bottleneck? More for perf tuning than cap management

“Capacity” is largely (don’t /sweat/ it) about “resources”.

— can’t add resource?
identify critical resources (bandwidth, simultaneous oracle conn, disk throuput..)
collect usage pattern esp. peak usage for each resource
increase effi 4 each resource ie reduce wastage
Identify — most of the time, perf is cpu-bound, mem-bound, disk io-bound, network io-bound … Same for a Weblogic server

— can add resources?
follow the same suggestions above
do cap plann`
do load forecast


Evolution-wise, I think the closest thing before ror is “object-oriented MVC with smarty and PEAR::DB”, just like bracketology, which offers a unique entry point to the confusing world of ror.


In Rails, if you have, for example, a BlogController and it has a method called list, Rails will automatically use the list.rhtml file inside of a folder called blog in your views folder. Not only that, but Rails will automatically pass on any instance variables you were using in the controller so that the view has access to them.

Now, when I am doing something similar in my own PHP apps, I have to manually instantiate the template object, manually pass references to any variables I know the view will be interested in and then manually tell it what template file to use. While all that manual code is pretty simple and easy to write, on even medium-sized apps it starts to take a toll on the leaness of the codebase.

I think he’s referring to something similar to smarty. Looks like this “convention over config” slogan is one aspect of the evolution from smarty -> ruby-on-rails

Other ror innovations over php?

We both love Singapore


I know you love Singapore’s clean environment, warm weather, efficient government, comfortable jobs for you (not for me). S’pore is also closer to home — You can bring Mom and Dad and relatives over to enjoy this little paradise.

Singaporeans are comfortable, in fact too comfortable. Singapore government knows many Singaporeans are too comfortable and lack the first generations’ toughness to go out of their comfortable home and embrace the world outside.

Like it or not, the ground is shifting right beneath our feet. If Singaporeans (including you and me) stand still, if Singaporeans stay in their comfortable home for too long, we will be left behind (or worse still, swept aside) by the wave of change.

God is kind of fair to Singapore’s competitors — it won’t reserve for Singapore a special place high up on top of most countries, and declare “Don’t rock the little boat of Singapore. Leave Singapore in peace and comfort for 50 years.”

Many believe God is unfair — English is still the preferred language among the rich. Big and rich countries like US, Canada, Australia and European powers (Japan is resource-poor) still capture more resources, attract more talents, create ever more sophisticated technologies which are largely beyond the reach of poor countries.

Over the past 40 years, Singapore upgraded itself by adapting to world economy, by reaching out to the neighbours in South-East Asia and to rich countries. To keep its place on the world’s 20 richest nations, Singaporeans have no choice but continue to reach out from their homebase and explore, adapt, take risks, endure , seek opportunities, learn from mistakes and compete with the best of the world.

Where are the best brains of the world? In London, Shanghai, New York, California, perhaps Tokyo. They continue to flock to Google, to Microsoft, Silicon Valley…

sub-query as column expression (sybase

— sybase
my $subselect=qq[ select min(ApprovalDate) from MtgAccts where …];
my $sql = “select *, convert(varchar, Day1ofMonth, 112) as ‘numeric_month’, ($subselect) as ‘approval_asof’…

http://sqlzoo.net/1.htm (tested on Oracle, MSSQL, Mysql)

* To list number of population “superpowers” by region

SELECT region, count(*),
(select count(*) from bbc a where population > 100123000 and a.region=b.region) as superpowers
FROM bbc b group by region

common 1-table sql:increments between adjacent rows

eg: savings (datetime, balance)

For a live example, let’s use 
http://sqlzoo.net/1.htm table countries (population, area…)

To simplify display, we will limit ourselves to the top 5 populations. 
* rank populations and list the pop decrement
select a.name,a.population, min(a.population-b.population) as decr from bbc a, bbc b where
a.population > b.population and b.population > 150000000
group by a.name, a.population
order by a.population desc

* Rank populations and list the pop decrement along with the 2 countries compared:

SELECT a.name, a.population, a.population-b.population as decr, b.name FROM bbc a, bbc b where b.population > 160000000 and
a.population-b.population = ( select min(a.population-c.population) from bbc c where a.population>c.population)
order by a.population desc